/*! For license information please see outboundCallComposite.js.LICENSE.txt */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.outboundCallComposite=t():e.outboundCallComposite=t()}(self,(()=>(()=>{var e,t,i={4473:(e,t,i)=>{"use strict";i.d(t,{_:()=>n});class n extends Error{constructor(e){super(e),this.name="AbortError"}}},6251:function(e,t,i){!function(e,t,n){"use strict";var r,a="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==i.g?i.g:"undefined"!=typeof self?self:{};function s(e,t,i){return e(i={path:t,exports:{},require:function(e,t){return function(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}(null==t&&i.path)}},i.exports),i.exports}!function(e){!function(t){var i="object"==typeof a?a:"object"==typeof self?self:"object"==typeof this?this:Function("return this;")(),n=r(e);function r(e,t){return function(i,n){"function"!=typeof e[i]&&Object.defineProperty(e,i,{configurable:!0,writable:!0,value:n}),t&&t(i,n)}}void 0===i.Reflect?i.Reflect=e:n=r(i.Reflect,n),function(e){var t=Object.prototype.hasOwnProperty,i="function"==typeof Symbol,n=i&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",r=i&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",a="function"==typeof Object.create,s={__proto__:[]}instanceof Array,o=!a&&!s,l={create:a?function(){return ne(Object.create(null))}:s?function(){return ne({__proto__:null})}:function(){return ne({})},has:o?function(e,i){return t.call(e,i)}:function(e,t){return t in e},get:o?function(e,i){return t.call(e,i)?e[i]:void 0}:function(e,t){return e[t]}},c=Object.getPrototypeOf(Function),d="object"==typeof process&&process.env&&"true"===process.env.REFLECT_METADATA_USE_MAP_POLYFILL,u=d||"function"!=typeof Map||"function"!=typeof Map.prototype.entries?ee():Map,h=d||"function"!=typeof Set||"function"!=typeof Set.prototype.entries?te():Set,p=new(d||"function"!=typeof WeakMap?ie():WeakMap);function g(e,t,i,n){if(L(i)){if(!j(e))throw new TypeError;if(!W(t))throw new TypeError;return b(e,t)}if(!j(e))throw new TypeError;if(!U(t))throw new TypeError;if(!U(n)&&!L(n)&&!x(n))throw new TypeError;return x(n)&&(n=void 0),I(e,t,i=G(i),n)}function m(e,t){function i(i,n){if(!U(i))throw new TypeError;if(!L(n)&&!q(n))throw new TypeError;k(e,t,i,n)}return i}function f(e,t,i,n){if(!U(i))throw new TypeError;return L(n)||(n=G(n)),k(e,t,i,n)}function v(e,t,i){if(!U(t))throw new TypeError;return L(i)||(i=G(i)),R(e,t,i)}function S(e,t,i){if(!U(t))throw new TypeError;return L(i)||(i=G(i)),A(e,t,i)}function y(e,t,i){if(!U(t))throw new TypeError;return L(i)||(i=G(i)),P(e,t,i)}function C(e,t,i){if(!U(t))throw new TypeError;return L(i)||(i=G(i)),M(e,t,i)}function _(e,t){if(!U(e))throw new TypeError;return L(t)||(t=G(t)),D(e,t)}function E(e,t){if(!U(e))throw new TypeError;return L(t)||(t=G(t)),O(e,t)}function T(e,t,i){if(!U(t))throw new TypeError;L(i)||(i=G(i));var n=w(t,i,!1);if(L(n))return!1;if(!n.delete(e))return!1;if(n.size>0)return!0;var r=p.get(t);return r.delete(i),r.size>0||p.delete(t),!0}function b(e,t){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(t);if(!L(n)&&!x(n)){if(!W(n))throw new TypeError;t=n}}return t}function I(e,t,i,n){for(var r=e.length-1;r>=0;--r){var a=(0,e[r])(t,i,n);if(!L(a)&&!x(a)){if(!U(a))throw new TypeError;n=a}}return n}function w(e,t,i){var n=p.get(e);if(L(n)){if(!i)return;n=new u,p.set(e,n)}var r=n.get(t);if(L(r)){if(!i)return;r=new u,n.set(t,r)}return r}function R(e,t,i){if(A(e,t,i))return!0;var n=X(t);return!x(n)&&R(e,n,i)}function A(e,t,i){var n=w(t,i,!1);return!L(n)&&H(n.has(e))}function P(e,t,i){if(A(e,t,i))return M(e,t,i);var n=X(t);return x(n)?void 0:P(e,n,i)}function M(e,t,i){var n=w(t,i,!1);if(!L(n))return n.get(e)}function k(e,t,i,n){w(i,n,!0).set(e,t)}function D(e,t){var i=O(e,t),n=X(e);if(null===n)return i;var r=D(n,t);if(r.length<=0)return i;if(i.length<=0)return r;for(var a=new h,s=[],o=0,l=i;o<l.length;o++){var c=l[o];a.has(c)||(a.add(c),s.push(c))}for(var d=0,u=r;d<u.length;d++)c=u[d],a.has(c)||(a.add(c),s.push(c));return s}function O(e,t){var i=[],n=w(e,t,!1);if(L(n))return i;for(var r=J(n.keys()),a=0;;){var s=Q(r);if(!s)return i.length=a,i;var o=Y(s);try{i[a]=o}catch(e){try{Z(r)}finally{throw e}}a++}}function N(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function L(e){return void 0===e}function x(e){return null===e}function F(e){return"symbol"==typeof e}function U(e){return"object"==typeof e?null!==e:"function"==typeof e}function B(e,t){switch(N(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var i=3===t?"string":5===t?"number":"default",r=K(e,n);if(void 0!==r){var a=r.call(e,i);if(U(a))throw new TypeError;return a}return V(e,"default"===i?"number":i)}function V(e,t){if("string"===t){var i=e.toString;if(z(i)&&!U(r=i.call(e)))return r;if(z(n=e.valueOf)&&!U(r=n.call(e)))return r}else{var n;if(z(n=e.valueOf)&&!U(r=n.call(e)))return r;var r,a=e.toString;if(z(a)&&!U(r=a.call(e)))return r}throw new TypeError}function H(e){return!!e}function $(e){return""+e}function G(e){var t=B(e,3);return F(t)?t:$(t)}function j(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function z(e){return"function"==typeof e}function W(e){return"function"==typeof e}function q(e){switch(N(e)){case 3:case 4:return!0;default:return!1}}function K(e,t){var i=e[t];if(null!=i){if(!z(i))throw new TypeError;return i}}function J(e){var t=K(e,r);if(!z(t))throw new TypeError;var i=t.call(e);if(!U(i))throw new TypeError;return i}function Y(e){return e.value}function Q(e){var t=e.next();return!t.done&&t}function Z(e){var t=e.return;t&&t.call(e)}function X(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===c)return t;if(t!==c)return t;var i=e.prototype,n=i&&Object.getPrototypeOf(i);if(null==n||n===Object.prototype)return t;var r=n.constructor;return"function"!=typeof r||r===e?t:r}function ee(){var e={},t=[],i=function(){function e(e,t,i){this._index=0,this._keys=e,this._values=t,this._selector=i}return e.prototype["@@iterator"]=function(){return this},e.prototype[r]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var i=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:i,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var i=this._find(e,!0);return this._values[i]=t,this},t.prototype.delete=function(t){var i=this._find(t,!1);if(i>=0){for(var n=this._keys.length,r=i+1;r<n;r++)this._keys[r-1]=this._keys[r],this._values[r-1]=this._values[r];return this._keys.length--,this._values.length--,t===this._cacheKey&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new i(this._keys,this._values,n)},t.prototype.values=function(){return new i(this._keys,this._values,a)},t.prototype.entries=function(){return new i(this._keys,this._values,s)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[r]=function(){return this.entries()},t.prototype._find=function(e,t){return this._cacheKey!==e&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=e)),this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function n(e,t){return e}function a(e,t){return t}function s(e,t){return[e,t]}}function te(){return function(){function e(){this._map=new u}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.values()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[r]=function(){return this.keys()},e}()}function ie(){var e=16,i=l.create(),n=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=a(e,!1);return void 0!==t&&l.has(t,this._key)},e.prototype.get=function(e){var t=a(e,!1);return void 0!==t?l.get(t,this._key):void 0},e.prototype.set=function(e,t){return a(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=a(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var e;do{e="@@WeakMap@@"+c()}while(l.has(i,e));return i[e]=!0,e}function a(e,i){if(!t.call(e,n)){if(!i)return;Object.defineProperty(e,n,{value:l.create()})}return e[n]}function s(e,t){for(var i=0;i<t;++i)e[i]=255*Math.random()|0;return e}function o(e){return"function"==typeof Uint8Array?"undefined"!=typeof crypto?crypto.getRandomValues(new Uint8Array(e)):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(new Uint8Array(e)):s(new Uint8Array(e),e):s(new Array(e),e)}function c(){var t=o(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var i="",n=0;n<e;++n){var r=t[n];4!==n&&6!==n&&8!==n||(i+="-"),r<16&&(i+="0"),i+=r.toString(16).toLowerCase()}return i}}function ne(e){return e.__=void 0,delete e.__,e}e("decorate",g),e("metadata",m),e("defineMetadata",f),e("hasMetadata",v),e("hasOwnMetadata",S),e("getMetadata",y),e("getOwnMetadata",C),e("getMetadataKeys",_),e("getOwnMetadataKeys",E),e("deleteMetadata",T)}(n)}()}(r||(r={}));var o=s((function(e,t){function i(e,t){var i=0;return e.replace(/%[dixs%]/g,(function(e){var n=0;if("%"!==e[n++])return"";var r=e[n++];return"%"===r?"%":"s"===r||"d"===r||"i"===r?t[i++]:"x"===r?t[i++].toString(16):e}))}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Trace=10]="Trace",e[e.Debug6=16]="Debug6",e[e.Debug5=18]="Debug5",e[e.Debug4=20]="Debug4",e[e.Debug3=30]="Debug3",e[e.Debug2=40]="Debug2",e[e.Debug1=50]="Debug1",e[e.Warning=60]="Warning",e[e.Error=70]="Error",e[e.Fatal=80]="Fatal",e[e.MetaData=90]="MetaData"}(t.LogLevel||(t.LogLevel={})),function(e){e[e.UseDefault=0]="UseDefault",e[e.Compress=1]="Compress",e[e.Disabled=2]="Disabled"}(t.LogFileCompression||(t.LogFileCompression={})),function(e){e[e.Raw=0]="Raw",e[e.Base64=1]="Base64"}(t.LogFileEncoding||(t.LogFileEncoding={})),function(e){e[e.Unencrypted=0]="Unencrypted",e[e.Encrypted=1]="Encrypted"}(t.LogFileEncryption||(t.LogFileEncryption={})),function(e){e[e.PEM=0]="PEM",e[e.DER=1]="DER",e[e.BER=2]="BER"}(t.CertStoreFormat||(t.CertStoreFormat={})),function(e){e[e.InsertFront=8]="InsertFront"}(t.AppenderFlags||(t.AppenderFlags={})),t.vsprintf=i,t.sprintf=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return i(e,t)}})),l=s((function(e,t){var i,n,r=a&&a.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});function s(e){if(null===e)return-1;for(var t=0,i=e.length-1;i>=0;i--)t=37*t+e.charCodeAt(i)|0;var n="__auf_literal:";for(i=13;i>=0;i--)t=37*t+n.charCodeAt(i)|0;return t}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Unsafe=0]="Unsafe",e[e.Safe=1]="Safe",e[e.Inherited_Unsafe=2]="Inherited_Unsafe",e[e.Inherited_Safe=3]="Inherited_Safe",e[e.Blacklisted_Unsafe=4]="Blacklisted_Unsafe"}(n||(n={}));var l,c=function(){function e(e,t){this._level=o.LogLevel.Debug4,this._threshold=255,this._safe=n.Inherited_Unsafe,this._name=e,t&&(this._level=t.level(),this._safe=t.safe()?n.Inherited_Safe:n.Inherited_Unsafe,this._extendedInfo=t.extendedInfo())}return e.prototype.name=function(){return this._name},e.prototype.safe=function(){return this._safe===n.Safe||this._safe===n.Inherited_Safe},e.prototype.safety=function(){return this._safe},e.prototype.setSafety=function(e){this._safe=e},e.prototype.description=function(){return this._desc},e.prototype.setDescription=function(e){this._desc=e},e.prototype.level=function(){return this._level},e.prototype.setLevel=function(e){l.setLevel(this,e)},e.prototype._setLevel=function(e){this._level=e},e.prototype._setThreshold=function(e){this._threshold=e},e.prototype.isEnabled=function(e){return this._threshold<=e},e.prototype.setExtendedInfo=function(e){this._extendedInfo=e},e.prototype.extendedInfo=function(){return this._extendedInfo},e.prototype.trace=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Trace,s(e),e].concat(t))},e.prototype.debug6=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug6,s(e),e].concat(t))},e.prototype.debug5=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug5,s(e),e].concat(t))},e.prototype.debug4=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug4,s(e),e].concat(t))},e.prototype.debug3=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug3,s(e),e].concat(t))},e.prototype.debug2=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug2,s(e),e].concat(t))},e.prototype.debug1=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Debug1,s(e),e].concat(t))},e.prototype.warn=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Warning,s(e),e].concat(t))},e.prototype.error=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Error,s(e),e].concat(t))},e.prototype.fatal=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.Fatal,s(e),e].concat(t))},e.prototype.meta=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];l.log.apply(l,[this,o.LogLevel.MetaData,s(e),e].concat(t))},e}(),d=function(){function e(){}return e.instance=function(){return l},e.levelToString=function(e){return e<=o.LogLevel.Trace?"TRACE":e<=o.LogLevel.Debug6?"DEBUG6":e<=o.LogLevel.Debug5?"DEBUG5":e<=o.LogLevel.Debug4?"DEBUG4":e<=o.LogLevel.Debug3?"DEBUG3":e<=o.LogLevel.Debug2?"DEBUG2":e<=o.LogLevel.Debug1?"DEBUG1":e<=o.LogLevel.Warning?"WARN":e<=o.LogLevel.Error?"ERROR":e<=o.LogLevel.Fatal?"FATAL":(o.LogLevel.MetaData,"META")},e.levelFromString=function(e){return this._levelFromString[e]||parseInt(e,10)},e}();function u(e,t){for(var i=t.name();i.length>0;){if(e[i])return e[i];var n=i.lastIndexOf(".");i=n<0?"":i.substr(0,n)}return e[""]?e[""]:o.LogLevel.Debug4}function h(e,t){var i=255;return t.forEach((function(t){var n=255;t.appender.levels()?n=Math.min(n,u(t.appender.levels(),e)):t.appender.receiveAll()||(n=Math.min(n,e.level())),i=Math.min(i,n)})),i}d._levelFromString={TRACE:o.LogLevel.Trace,DEBUG6:o.LogLevel.Debug6,DEBUG5:o.LogLevel.Debug5,DEBUG4:o.LogLevel.Debug4,DEBUG3:o.LogLevel.Debug3,DEBUG2:o.LogLevel.Debug2,DEBUG1:o.LogLevel.Debug1,WARN:o.LogLevel.Warning,ERROR:o.LogLevel.Error,FATAL:o.LogLevel.Fatal,META:o.LogLevel.MetaData},t.LogFactory=d;var p=function(e){function t(){var t=e.call(this)||this;return t._nextId=0,t._appenders=[],t._components={},t._componentBlacklist=[],t._components[""]=new c("",null),t}return r(t,e),t.prototype.toHex=function(e){return(4294967296+e).toString(16).substr(-8)},t.prototype.addAppender=function(e,t){void 0===t&&(t=0);var i=this._nextId++;return t&o.AppenderFlags.InsertFront?this._appenders.unshift({appender:e,handle:i}):this._appenders.push({appender:e,handle:i}),this.recalcComponentThresholds(),i},t.prototype.removeAppender=function(e){for(var t=0;t<this._appenders.length;t++)if(this._appenders[t].handle===e){this._appenders.splice(t,1);break}this.recalcComponentThresholds()},t.prototype.log=function(e,t,i,n){for(var r=[],a=4;a<arguments.length;a++)r[a-4]=arguments[a];try{if(e.isEnabled(t)){var s={timestamp:(new Date).getTime(),component:e,level:t};this._appenders.forEach((function(a){(function(e,t,i){return!!e.appender.receiveAll()||(e.appender.levels()?i>=u(e.appender.levels(),t):i>=t.level())})(a,e,t)&&a.appender.log(s,i,n,r)}))}}catch(e){}},t.prototype.parent=function(e){for(;;){var t=e.lastIndexOf(".");if(e=t>=0?e.substr(0,t):"",this._components[e])return this._components[e]}},t.prototype.children=function(e){var t=[];for(var i in this._components)this.parent(i).name()===e&&t.push(this._components[i]);return t},t.prototype.component=function(e){if(this._components[e])return this._components[e];var t=new c(e,this.parent(e));this._components[e]=t;var i=h(t,this._appenders);return t._setThreshold(i),t},t.prototype.rootComponent=function(){return this.component("")},t.prototype.setSafetyRecursive=function(e,t){var i=this;this.children(e).forEach((function(e){e.safety()!==n.Inherited_Safe&&e.safety()!==n.Inherited_Unsafe||(e.setSafety(t),i.setSafetyRecursive(e.name(),t))}))},t.prototype.declareComponentSafe=function(e,t){var i=this.component(e);-1!==this._componentBlacklist.indexOf(i.name())?i.setSafety(n.Blacklisted_Unsafe):i.setSafety(t?n.Safe:n.Unsafe),this.setSafetyRecursive(e,t?n.Inherited_Safe:n.Inherited_Unsafe)},t.prototype.declareComponentDescription=function(e,t){this.component(e).setDescription(t)},t.prototype.setExtendedInfoRecursive=function(e,t){var i=this;this.children(e).forEach((function(e){void 0===e.extendedInfo()&&(e.setExtendedInfo(t),i.setExtendedInfoRecursive(e.name(),t))}))},t.prototype.declareComponentExtendedInfo=function(e,t){var i=this.component(e);i.setExtendedInfo(t),this.setExtendedInfoRecursive(i.name(),t)},t.prototype.recalcComponentThresholds=function(){for(var e in this._components){var t=this._components[e],i=h(t,this._appenders);t._setThreshold(i)}},t.prototype.setLevel=function(e,t){if(""===e.name())for(var i in this._components){(a=this._components[i])._setLevel(t);var n=h(a,this._appenders);a._setThreshold(n)}else{var r=e.name()+".";for(var i in e._setLevel(t),n=h(e,this._appenders),e._setThreshold(n),this._components){var a;if((a=this._components[i]).name().substr(0,r.length)===r){a._setLevel(t);var s=h(a,this._appenders);a._setThreshold(s)}}}},t.prototype.setComponentBlacklist=function(e){for(var t in this._componentBlacklist=e,this._components){var i=this._components[t];-1!==this._componentBlacklist.indexOf(i.name())&&i.setSafety(n.Blacklisted_Unsafe)}},t}(d);l=new p})),c=s((function(e,t){function i(e){return null!=e&&"function"==typeof e.then}function n(e){return null!=e&&"function"==typeof e.cancel}function r(e,i){if(!t.config.catchExceptions)return e();try{return e()}catch(e){return i(e)}}Object.defineProperty(t,"__esModule",{value:!0}),t.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(e){throw e}},t.fromThenable=function(e){var t=d();return e.then((function(e){t.resolve(e)}),(function(e){t.reject(e)})),t.promise().thenAsync((function(e){return e}))};var a,s=[],o="undefined"!=typeof setImmediate;function l(e){s.push(e),1===s.length&&(o?setImmediate(c):setTimeout(c,0))}function c(){var e=s;s=[];for(var t=0;t<e.length;t++)e[t]()}function d(){return new a.SyncTask}function u(e){return(new a.SyncTask).resolve(e).promise()}function h(e){var t=d(),r=!1;return t.onCancel((function(t){e.forEach((function(e){n(e)&&a.SyncTask.cancelOtherInternal(e,t)}))})),e.forEach((function(e){i(e)?e.then((function(e){r||(r=!0,t.resolve(e))}),(function(e){r||(r=!0,t.reject(e))})):r||(r=!0,t.resolve(e))})),t.promise()}t.asyncCallback=l,function(e){var a=function(){function e(){this._completedSuccess=!1,this._completedFail=!1,this._traceEnabled=!1,this._cancelCallbacks=[],this._wasCanceled=!1,this._wasExplicitlyCanceled=!1,this._resolving=!1,this._storedCallbackSets=[],this._mustHandleError=!0}return e.prototype._addCallbackSet=function(t,i){var n=this,r=new e;return r.onCancel((function(e){t.wasCanceled=!0,t.cancelContext=e,n._cancelInternal(e)})),t.task=r,this._storedCallbackSets.push(t),i?this._mustHandleError=!1:r._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),r.promise()},e.prototype.onCancel=function(e){return this._completedSuccess||this._completedFail||(this._wasCanceled?e(this._cancelContext):this._cancelCallbacks.push(e)),this},e.prototype.then=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t},!0)},e.prototype.thenAsync=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t,asyncCallback:!0},!0)},e.prototype.catch=function(e){return this._addCallbackSet({failFunc:e},!0)},e.prototype.always=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!0)},e.prototype.setTracingEnabled=function(e){return this._traceEnabled=e,this},e.prototype.finally=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!1),this},e.prototype.done=function(e){return this._addCallbackSet({successFunc:e},!1),this},e.prototype.fail=function(e){return this._addCallbackSet({failFunc:e},!1),this},e.prototype.resolve=function(e){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=e,this._cancelCallbacks=[],this._resolveSuccesses(),this},e.prototype.reject=function(t){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=t,this._cancelCallbacks=[],this._resolveFailures(),e._enforceErrorHandled(this),this},e.prototype._checkState=function(e){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var i="Failed to "+(e?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(i)}(t.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},e._enforceErrorHandled=function(i){i._mustHandleError&&(e._rejectedTasks.push(i),e._enforceErrorHandledTimer||(e._enforceErrorHandledTimer=setTimeout((function(){e._enforceErrorHandledTimer=void 0;var i=e._rejectedTasks;e._rejectedTasks=[],i.forEach((function(e,i){e._mustHandleError&&t.config.unhandledErrorHandler(e._storedErrResolution)}))}),0)))},e.prototype.cancel=function(e){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(e)},e.prototype._cancelInternal=function(e){var t=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=e;var i=this._cancelCallbacks;this._cancelCallbacks=[],i.length>0&&i.forEach((function(e){t._completedSuccess||t._completedFail||e(t._cancelContext)}))}},e.cancelOtherInternal=function(e,t){var i=e;i._storedCallbackSets&&i._cancelInternal?i._cancelInternal(t):e.cancel(t)},e.prototype.promise=function(){return this},e.prototype._resolveSuccesses=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?l((function(){return e._resolveSuccessCallback(t)})):e._resolveSuccessCallback(t)}))}this._resolving=!1},e.prototype._resolveSuccessCallback=function(t){var a=this;t.successFunc?r((function(){var r=t.successFunc(a._storedResolution);n(r)&&(t.wasCanceled?e.cancelOtherInternal(r,t.cancelContext):t.task.onCancel((function(t){return e.cancelOtherInternal(r,t)}))),i(r)?r.then((function(e){t.task.resolve(e)}),(function(e){t.task.reject(e)})):t.task.resolve(r)}),(function(e){a._handleException(e,"SyncTask caught exception in success block: "+e.toString()),t.task.reject(e)})):t.task.resolve(this._storedResolution)},e.prototype._resolveFailures=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?l((function(){return e._resolveFailureCallback(t)})):e._resolveFailureCallback(t)}))}this._resolving=!1},e.prototype._resolveFailureCallback=function(t){var a=this;t.failFunc?r((function(){var r=t.failFunc(a._storedErrResolution);n(r)&&(t.wasCanceled?e.cancelOtherInternal(r,t.cancelContext):t.task.onCancel((function(t){return e.cancelOtherInternal(r,t)}))),i(r)?r.then((function(e){t.task.resolve(e)}),(function(e){t.task.reject(e)})):t.task.resolve(r)}),(function(e){a._handleException(e,"SyncTask caught exception in failure block: "+e.toString()),t.task.reject(e)})):t.task.reject(this._storedErrResolution)},e.prototype._handleException=function(e,i){t.config.exceptionsToConsole&&console.error(i),t.config.exceptionHandler&&t.config.exceptionHandler(e)},e.prototype.toEs6Promise=function(){var e=this;return new Promise((function(t,i){return e.then(t,i)}))},e._rejectedTasks=[],e}();e.SyncTask=a}(a||(a={})),t.all=function(e){if(0===e.length)return u([]);var t,r=d(),s=e.length,o=Array(e.length);r.onCancel((function(t){e.forEach((function(e){n(e)&&a.SyncTask.cancelOtherInternal(e,t)}))}));var l=function(){0==--s&&(void 0!==t?r.reject(t):r.resolve(o))};return e.forEach((function(e,n){i(e)?e.then((function(e){o[n]=e,l()}),(function(e){void 0===t&&(t=void 0===e||e),l()})):(o[n]=e,l())})),r.promise()},t.Defer=d,t.Resolved=u,t.Rejected=function(e){return(new a.SyncTask).reject(e).promise()},t.race=h,t.raceTimer=function(e,t){var i=d(),n=setTimeout((function(){i.resolve({timedOut:!0})}),t);return h([e.then((function(e){return clearTimeout(n),{timedOut:!1,result:e}})),i.promise()])}})),d=s((function(e,t){var i,n=a&&a.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r,s=function(){function e(e){this._formatter=e||new u}return e.prototype.formatter=function(){return this._formatter},e.prototype.receiveAll=function(){return!1},e.prototype.levels=function(){return null},e}();function c(e){return(4294967296+e).toString(16).substr(-8)}function d(e,t){return(1e12+e).toString(10).substr(-t)}t.AbstractLogAppender=s,function(e){e[e.Timestamp=1]="Timestamp",e[e.Component=4]="Component",e[e.Level=8]="Level",e[e.FullDate=32]="FullDate",e[e.LogId=64]="LogId"}(r=t.SLF_Flags||(t.SLF_Flags={}));var u=function(){function e(e){void 0===e&&(e=4294967295),this._flags=e}return e.prototype.format=function(e,t,i,n){var a="";if(this._flags&r.FullDate)a+=new Date(e.timestamp).toISOString()+" ";else if(this._flags&r.Timestamp){var s=new Date(e.timestamp);a+=d(s.getHours(),2)+":"+d(s.getMinutes(),2)+":"+d(s.getSeconds(),2)+"."+d(s.getMilliseconds(),2)+" "}return this._flags&r.LogId&&(a+="[#"+c(t)+"-"+(e.component.safe()?"S":"u")+"] "),this._flags&r.Level&&(a+="["+l.LogFactory.levelToString(e.level)+"] "),this._flags&r.Component&&(a+="["+e.component.name()+"] "),i||""===i?a+o.vsprintf(i,n):a+c(t)+": "+n.join(" ")},e}();t.StandardLogFormatter=u;var h=console,p=console.log||function(){},g=console.info||p,m=console.warn||g,f=console.error||m,v=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return n(t,e),t.prototype.log=function(e,t,i,n){n=n.slice(0);var r=e.level<=o.LogLevel.Debug3?p:e.level<=o.LogLevel.Debug1?g:e.level<=o.LogLevel.Warning?m:f;if(-1===t){var a=this.formatter().format(e,t,"",[]);"string"==typeof n[0]&&(a+=n.shift()),r.apply(h,[a].concat(n))}else{for(var s=void 0,l=[];s=i.match(/\s*%@\s*$/);)i=i.substr(0,i.length-s[0].length),l.unshift(n.pop());a=this.formatter().format(e,t,i,n),r.apply(h,[a].concat(l))}},t}(s);t.ConsoleAppender=v;var S=function(){function e(e){this._chained=e}return e.prototype.log=function(e,t,i,n){this._chained.log(e,t,i,n)},e.prototype.receiveAll=function(){return this._chained.receiveAll()},e.prototype.levels=function(){return this._chained.levels()},e}();t.ChainedLogAppender=S;var y=function(e){function t(t,i){var n=e.call(this,t)||this;return n._levels=i,n}return n(t,e),t.prototype.levels=function(){return this._levels},t}(S);t.wrapAppenderWithLogLevels=function(e,t){return new y(e,t)}})),u=s((function(e,t){var i,n=a&&a.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r=l.LogFactory.instance().component("RootToolsManager");l.LogFactory.instance().declareComponentSafe("RootToolsManager",!0);var s;!function(e){e[e.InternalBuild=0]="InternalBuild",e[e.PublicBuild=1]="PublicBuild"}(s=t.BuildType||(t.BuildType={}));var u=s.InternalBuild;function h(e){return(4294967296+e).toString(16).substr(-8)}function p(e,t){var i=[];for(var n in e)i.push(t(n,e[n]));return i}function g(e,t,i){if(null==e)return null==t||0===t.length;if(null==t)return null==e||0===e.length;if(e.length===t.length){for(var n=0;n<e.length;n++)if(!i(e[n],t[n]))return!1;return!0}return!1}function m(e,t){return null==e?null==t:null==t?null==e:e.arg===t.arg&&e.op===t.op&&e.value===t.value}function f(e,t){return null==e?null==t||0===t.logId:null==t?null==e||0===e.logId:e.logId===t.logId&&e.name===t.name&&g(e.matchers,t.matchers,m)}function v(e,t){return null==e?null==t:null==t?null==e:e.component===t.component&&e.parsedLevel===t.level}function S(e,t){return null==e?null==t:null==t?null==e:e.component===t.component&&e.level===t.level}function y(e){for(var t=[],i=0;i<e.length;i++)"string"==typeof e[i]||"number"==typeof e[i]?t.push(e[i]):t.push(JSON.stringify(e[i]));return t}t.setBuildType=function(e){var t=u;return u=e,t};var C=function(e){function t(t,i,n){var r=e.call(this)||this;return r._unmetConditions=[],r._rtMan=t,r._triggerCallback=i,r._ecsConfig=n,r.resetConditions(),r}return n(t,e),t.prototype.config=function(){return this._ecsConfig},t.prototype.configEquals=function(e){return this._ecsConfig.includeUnsafe===e.includeUnsafe&&this._ecsConfig.mutualSubmissionType===e.mutualSubmissionType&&this._ecsConfig.name===e.name&&this._ecsConfig.reenableAfterTriggering===e.reenableAfterTriggering&&this._ecsConfig.experimentTarget===e.experimentTarget&&f(this._ecsConfig.resetCondition,e.resetCondition)&&g(this._ecsConfig.conditions,e.conditions,f)&&g(this._ecsConfig.filters,e.filters,S)},t.prototype.nativeConfigEquals=function(e){return this._ecsConfig.includeUnsafe===e.includeUnsafe&&this._ecsConfig.name===e.name&&this._ecsConfig.reenableAfterTriggering===e.reenableAfterTriggering&&f(this._ecsConfig.resetCondition,e.resetCondition)&&g(this._ecsConfig.conditions,e.conditions,f)&&g(this._ecsConfig.filters,e.filters,v)},t.prototype.needReset=function(e){return!this.configEquals(e)},t.prototype.resetConditions=function(){this._unmetConditions=[];for(var e=0;e<this._ecsConfig.conditions.length;e++)this._unmetConditions.push(e)},t.prototype.matcherMatches=function(e,t){if(e.arg>=t.length)return!1;var i=t[e.arg],n="string"==typeof i?e.value:parseInt(e.value,10);return"="===e.op||"=="===e.op?i===n:"!="===e.op?i!==n:"<"===e.op?i<n:"<="===e.op?i<=n:">"===e.op?i>n:">="===e.op?i>=n:"CONTAINS"===e.op.toUpperCase()&&(""+i).indexOf(e.value)>=0},t.prototype.conditionMatches=function(e,t,i){if(t!==e.logId)return!1;if(e.matchers)for(var n=0;n<e.matchers.length;n++)if(!this.matcherMatches(e.matchers[n],i))return!1;return!0},t.prototype.log=function(e,t,i,n){if(0!==this._unmetConditions.length&&e.component!==r){var a=this._ecsConfig;a.resetCondition&&this.conditionMatches(a.resetCondition,t,n)&&(r.debug4("LogTrigger %s: resetCondition met",a.name),this.resetConditions());for(var s=0;s<this._unmetConditions.length;s++){var o=this._unmetConditions[s];if(this.conditionMatches(a.conditions[o],t,n)){r.debug4("LogTrigger %s: condition %s met",a.name,a.conditions[o].name),this._unmetConditions.splice(s,1);break}}0===this._unmetConditions.length&&(r.debug1("LogTrigger %s has triggered, trying to send the log",a.name),this._triggerCallback.call(this._rtMan,a),a.reenableAfterTriggering&&this.resetConditions())}},t.prototype.receiveAll=function(){return!0},t}(d.AbstractLogAppender),_=function(e){function t(t,i,n){var r=e.call(this)||this;return r._circularBuffer=[],r._circularBufferMaxSize=0,r._onBufferOverflow=null,r._circularBuffer=[],r._circularBufferMaxSize=i,r._includeUnsafe=t,r._onBufferOverflow=n||function(){return r._circularBuffer.shift()},r}return n(t,e),t.prototype.log=function(e,t,i,n){if((this._includeUnsafe||e.component.safe())&&!(this._circularBuffer.length>this._circularBufferMaxSize)){var r={md:e,logId:t,messages:y(n)};this._circularBuffer.push(r),this._circularBuffer.length>this._circularBufferMaxSize&&this._onBufferOverflow()}},t.prototype.visitReverseOrder=function(e){for(var t=this._circularBuffer.length-1;t>=0;t--){var i=this._circularBuffer[t];if(!e(i.md,i.logId,i.messages))return}},t.prototype.visitForwardOrder=function(e){for(var t=0;t<this._circularBuffer.length;t++){var i=this._circularBuffer[t];if(!e(i.md,i.logId,i.messages))return}},t.prototype.needReset=function(e,t){return e!==this._includeUnsafe||t!==this._circularBufferMaxSize},t.prototype.dumpLogBuffer=function(e,t,i){var n=this,r=new E(e.reverse),a=e.filter.map((function(e){return{component:"root"===e.component?"":e.component,parsedLevel:e.level}})),s=i||{matchedLines:0,totalLines:0};return(e.reverse?this.visitReverseOrder:this.visitForwardOrder).apply(this,[function(e,i,o){return s.totalLines++,n.filterMatches(e,i,o,a)&&(s.matchedLines++,r.log(e.component,e.timestamp,e.level,i,o)),!t||r._data.length<t}]),r.close(),r.data()},t.prototype.filterMatches=function(e,t,i,n){for(var r=0;r<n.length;r++)if((""===n[r].component||e.component.name()===n[r].component||e.component.name().substr(0,n[r].component.length)===n[r].component&&"."===e.component.name().charAt(n[r].component.length))&&e.level>=n[r].parsedLevel)return!0;return!1},t.prototype.clear=function(){this._circularBuffer=[]},t.prototype.size=function(){return this._circularBuffer.length},t.prototype.empty=function(){return 0===this.size()},t.prototype.capacity=function(){return this._circularBufferMaxSize},t}(d.AbstractLogAppender);t.CircularBuffer=_;var E=function(){function e(e){this._reverse=e,this._first=!0,this._pending=[],this._components={},this._componentCount=0,this._lastts=0,this._base64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",this._data="ULOG2"+String.fromCharCode(33)+String.fromCharCode(32),this._data+=e?String.fromCharCode(34):String.fromCharCode(32),this._data+=String.fromCharCode(32)}return e.prototype._add8=function(e){if(this._pending.push(255&e),3===this._pending.length){var t=(this._pending[0]<<16)+(this._pending[1]<<8)+(0|this._pending[2]),i=this._base64chars[t>>18&63]+this._base64chars[t>>12&63]+this._base64chars[t>>6&63]+this._base64chars[63&t];this._data+=i,this._pending=[]}},e.prototype._add16=function(e){this._add8(e>>8&255),this._add8(255&e)},e.prototype._add32=function(e){this._add8(e>>24&255),this._add8(e>>16&255),this._add8(e>>8&255),this._add8(255&e)},e.prototype._add64=function(e){this._add32(e/4294967296|0),this._add32(0|e)},e.prototype._addS=function(e){for(var t=0;t<e.length;t++)this._add8(e.charCodeAt(t));this._add8(0)},e.prototype._close=function(){for(;this._pending.length;)this._add8(0)},e.prototype.log=function(e,t,i,n,r){var a=this._components[e.name()];a||(a=++this._componentCount,this._components[e.name()]=a,this._add8(2),this._add16(a),this._addS(e.name()),this._addS(""),this._addS(""),this._add8(e.safe()?1:0));var s=128;this._first&&(s|=2);var o=t-this._lastts;this._lastts=t,o>-128&&o<128&&(s|=1),this._add8(s),1&s?this._add8(o):this._add64(1e3*t),this._first&&(this._add32(1),this._add8(0),this._add16(0)),this._add16(a),this._add8(i),this._add32(n),this._add8(r.length);for(var l=0;l<r.length;l++)this._add8(8),this._addS(""+r[l]);this._first=!1},e.prototype.close=function(){this._add8(7),this._close()},e.prototype.data=function(){return this._data},e.prototype.empty=function(){return this._first},e}(),T=function(e){function t(t,i,n,r){var a=e.call(this)||this;return a._capacity=t,a._onBufferOverflow=i,a._enableThrottling=n,a._maxVerbosityLevel=r,a._outputFormatter=new E(!1),a._linesStored=0,a._throttling=!1,a._linesThrottled=0,a}return n(t,e),t.prototype.log=function(e,t,i,n){this._maxVerbosityLevel&&e.level<this._maxVerbosityLevel||(this._throttling?this._linesThrottled++:(this._linesStored++,this._outputFormatter.log(e.component,e.timestamp,e.level,t,y(n))),this._linesStored>this._capacity&&(this._enableThrottling?this._throttling||(this._throttling=!0):this._onBufferOverflow()))},t.prototype.dumpAndReset=function(){if(this._outputFormatter.empty())return"";this._linesThrottled>0&&this._outputFormatter.log(r,(new Date).getTime(),o.LogLevel.Fatal,-1,["RooToolsManager: Log buffer overflow! "+this._linesThrottled+" lines thrown away"]),this._outputFormatter.close();var e=this._outputFormatter.data();return this.clearBuffer(),e},t.prototype.empty=function(){return this._outputFormatter.empty()},t.prototype.clearBuffer=function(){this._outputFormatter=new E(!1),this._linesStored=0,this._linesThrottled=0,this._throttling=!1},t.prototype.capacity=function(){return this._capacity},t.prototype.throttlingEnabled=function(){return this._enableThrottling},t.prototype.size=function(){return this._linesStored},t.prototype.maxVerbosityLevel=function(){return this._maxVerbosityLevel},t}(d.AbstractLogAppender);function b(e){return"Native"===e||"JavaScript"===e||"Mixed"===e}t.DumperBuffer=T;var I=function(){function e(){this._maxUploadSize=0,this._jsToNativeBuffer=null,this._jsToNativeBufferHandle=null,this._jsToNativeFlushTimer=null,this._jsToNativeFlushInterval=0,this._triggers={},this._defaultBuffers=[{size:2097152,level:o.LogLevel.Debug4}],this._defaultKillswitch={blacklist:[],whitelist:[]},this._defaultBlacklists={component:[],logline:[]},this._localLogLevels={},this._defaultExperimentTarget="Mixed",this._BRBCallback=null}return e.prototype.setDelegate=function(e){this._glue=e,this.registerListeners()},e.prototype.isDelegateSet=function(){return null!=this._glue},e.prototype.setNativeFunctions=function(e){this._native&&this._native.log_config.removeLogTriggerListener(this),this._native=e,this._native&&this._native.log_config.addLogTriggerListener(this)},e.prototype.applyLogLevels=function(){var e={};for(var t in this._localLogLevels)e[t]=this._localLogLevels[t];e[""]=e.root||o.LogLevel.Debug4,delete e.root;var i=p(e,(function(e,t){return{component:e,level:t}}));i.sort((function(e,t){return e.component.length-t.component.length})),i.forEach((function(e){return l.LogFactory.instance().component(e.component).setLevel(e.level)})),this._native&&this._native.log_config.setLogLevelConfig(i)},e.prototype.setLocalLogLevelConfig=function(e){this._localLogLevels=e,this.applyLogLevels()},e.prototype.parseMatcher=function(e){return null==e||null==e.arg||null==e.op||null==e.value?null:{arg:e.arg,op:e.op,value:e.value}},e.prototype.parseCondition=function(e){if(null==e||null==e.logId)return null;if(e.matchers&&!(e.matchers instanceof Array))return null;var t={name:e.name||h(e.logId),logId:e.logId,matchers:[]};if(e.matchers&&e.matchers.length)for(var i=0,n=e.matchers;i<n.length;i++){var r=n[i],a=this.parseMatcher(r);a&&t.matchers.push(a)}return t},e.prototype.parseFilter=function(e){return null==e||null==e.component||0===e.component.length?null:{component:e.component,level:e.level,parsedLevel:l.LogFactory.levelFromString(e.level)}},e.prototype.parseConfig=function(e,t,i){if(null==e)return null;if(!(e.conditions instanceof Array)||0==e.conditions.length)return null;if(!(e.filters instanceof Array)||0==e.filters.length)return null;if(e.resetCondition&&!this.parseCondition(e.resetCondition))return null;for(var n={name:e.name||t+"->"+i,ecsNs:t,reenableAfterTriggering:e.reenableAfterTriggering||!1,mutualSubmissionType:e.mutualSubmissionType||"",includeUnsafe:u!==s.PublicBuild&&(e.includeUnsafe||!1),experimentTarget:b(e.experimentTarget)&&e.experimentTarget||this._defaultExperimentTarget,conditions:[],resetCondition:null==e.resetCondition?e.resetCondition:this.parseCondition(e.resetCondition),filters:[]},r=0,a=e.conditions;r<a.length;r++){var o=a[r],l=this.parseCondition(o);l&&n.conditions.push(l)}for(var c=0,d=e.filters;c<d.length;c++){var h=d[c],p=this.parseFilter(h);p&&n.filters.push(p)}return 0===n.conditions.length?null:n},e.prototype.isExperimentListed=function(e,t,i,n){return!!e&&(!(!n||!e.some((function(e){return"*"===e.namespace})))||e.some((function(e){return e.namespace===t&&(e.experiment===i||"*"==e.experiment)})))},e.prototype.isExperimentAllowed=function(e,t,i){return!this.isExperimentListed(e.blacklist,t,i,!0)||this.isExperimentListed(e.whitelist,t,i,!1)},e.prototype.findTrigger=function(e,t){for(var i in e)if(e[i].configEquals(t))return i;return null},e.prototype.findTriggerByNativeConfig=function(e,t){for(var i in e)if(e[i].nativeConfigEquals(t))return i;return null},e.prototype.OnEcsChange=function(){var e=this;function t(e,i,n){return i<e.length?n(e[i]).then((function(){return t(e,i+1,n)})):c.Resolved()}return null==this._glue?c.Resolved():this._glue.fetchEcsConfig("SkypeRootTools","ULBaseline").then((function(i){r.debug4("Reloading ULBaseline config - new config: %@",i),i||(r.warn("No ULBaseline config"),i={}),e._maxUploadSize=i.logUpload&&i.logUpload.maxSize||1024;var n=[],a=e._triggers;e._triggers={};var s=(i.logUpload&&i.logUpload.maxSize||1024)/100,c=i.circularBuffer&&i.circularBuffer.enabled,u=i.circularBuffer&&i.circularBuffer.buffers||e._defaultBuffers,h=i.circularBuffer&&i.circularBuffer.storeUnsafe;e._defaultExperimentTarget=b(i.defaultExperimentTarget)&&i.defaultExperimentTarget||"Mixed";var g=i.killswitch||e._defaultKillswitch,m=i.blacklists||e._defaultBlacklists;m.component.length>0&&l.LogFactory.instance().setComponentBlacklist(m.component);var f={};(i.componentLevels||[]).forEach((function(e){return f[e.component]=e.level})),t(i.configPaths||[],0,(function(t){return e._glue.fetchEcsConfig(t.ns,t.key).then((function(i){var s=i instanceof Array?i:[i];r.debug4("Reloading ECS config for %s->%s - new config: %@",t.ns,t.key,s);for(var o=0,l=s;o<l.length;o++){var d=l[o];if(null!=d){var u=e.parseConfig(d,t.ns,t.key);if(null!=u)if("JavaScript"===u.experimentTarget||"Mixed"===u.experimentTarget)if(r.debug2("Parsed ECS config for %s->%s - %@",t.ns,t.key,u),e.isExperimentAllowed(g,t.ns,u.name)){r.debug2("Allowing %s->%s:%s according to killswitch",t.ns,t.key,u.name),c=!0;var p=e.findTrigger(a,u);null!=p?(r.debug2("Triggers updated, keeping trigger %s",u.name),e._triggers[p]=a[p],delete a[p]):n.push(u),u.filters&&u.filters.forEach((function(e){return f[e.component]=Math.min(f[e.component]||255,e.parsedLevel)})),u.includeUnsafe&&(h=!0)}else r.debug2("Disallowing %s->%s according to killswitch",t.ns,t.key);else r.debug4("Skipping %s->%s, targeted for %s",t.ns,t.key,u);else r.error("Failed to parse ECS config for %s->%s",t.ns,t.key)}}}))})).always((function(){for(var t in e.applyLogLevels(),a)r.debug2("Triggers updated, removing trigger %s",a[t].config().name),l.LogFactory.instance().removeAppender(+t);if(n.forEach((function(t){r.debug2("Triggers updated, adding trigger %s",t.name);var i=new C(e,e._triggered,t),n=l.LogFactory.instance().addAppender(i);e._triggers[String(n)]=i})),f[""]=f.root||o.LogLevel.Debug4,delete f.root,!e._circularBuffer||c&&!e._circularBuffer.needReset(h,s)?e._circularBuffer&&(Object.keys(a).length>0||n.length>0?(r.debug2("Buffer updated, reapplying log levels, removing log levels wrapper"),l.LogFactory.instance().removeAppender(e._circularBufferHandle),e._circularBufferHandle=null):r.debug2("Buffer updated, no change")):(r.debug2("Buffer updated, removing existing buffer"),l.LogFactory.instance().removeAppender(e._circularBufferHandle),e._circularBuffer=null,e._circularBufferHandle=null),c&&(e._circularBuffer||(r.debug2("Buffer updated, adding new buffer (storeUnsafe=%d,maxSize=%s)",h,s),e._circularBuffer=new _(h,s)),null==e._circularBufferHandle&&(r.debug2("Creating log level wrapper"),e._circularBufferHandle=l.LogFactory.instance().addAppender(d.wrapAppenderWithLogLevels(e._circularBuffer,f),o.AppenderFlags.InsertFront))),e._native){var i=p(f,(function(e,t){return{component:e,level:t}}));i.sort((function(e,t){return e.component.length-t.component.length})),e._native.log_config.setLogBufferConfig(c,{storeUnsafe:h,buffers:u},i);var g=[];for(var m in e._triggers){var v=e._triggers[m].config();g.push({name:v.name,ecsNs:v.ecsNs,conditions:v.conditions,resetCondition:v.resetCondition,includeUnsafe:v.includeUnsafe,reenableAfterTriggering:v.reenableAfterTriggering,filters:v.filters.map((function(e){return{component:e.component,level:e.parsedLevel}})),dumpFile:!1,metadata:{}})}e._native.log_config.setLogTriggerConfig(g,{})}}))}))},e.prototype._send=function(e,t){null!=this._glue&&(this._glue.sendTelemetry("638b8ba2bae14e07aa5d73ddb5d5e5c5-297b8412-5df3-4a83-83c4-7b76c6c5d3f0-7104",{logTriggerName:e.name,logEcsNs:e.ecsNs,logdata:t}),r.debug4("LogSender::send, sent %d bytes",t.length))},e.prototype.triggered=function(e,t){},e.prototype.triggeredPartially=function(e,t,i,n,r){var a=this.findTriggerByNativeConfig(this._triggers,e);if(a){var s={level:t.level,component:l.LogFactory.instance().component(t.component),timestamp:t.timestamp};this._triggers[a].log(s,i,n,r)}},e.prototype.reset=function(e){var t=this.findTriggerByNativeConfig(this._triggers,e);t&&this._triggers[t].resetConditions()},e.prototype.dumpLogBuffer=function(e,t){if(this._circularBuffer){var i={matchedLines:0,totalLines:0},n=this._circularBuffer.dumpLogBuffer(e,this._maxUploadSize,i);if(r.debug4("dumpLogBuffer: dumped %d of %d lines, size of payload: %d",i.matchedLines,i.totalLines,null!=n?n.length:0),this._native){var a=c.Defer();return this._native.log_config.mergeAndDumpLogBuffer(n,e,t,(function(e){return a.resolve(e)})),a.promise()}return c.Resolved(n)}return r.warn("dumpLogBuffer: no log buffer enabled"),c.Rejected()},e.prototype._triggered=function(e){var t=this,i={compression:o.LogFileCompression.Compress,encoding:o.LogFileEncoding.Base64,encryption:o.LogFileEncryption.Encrypted,maxRotations:0,maxSize:this._maxUploadSize,reverse:!0},n={includeUnsafe:e.includeUnsafe,filter:e.filters.map((function(e){return{component:e.component,level:e.parsedLevel}})),reverse:!0};this.dumpLogBuffer(n,i).then((function(i){return t._send(e,i)}))},e.prototype.sendBRBEvent=function(e,t){try{if(r.debug2("sendBRBEvent %s",JSON.stringify(e)),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var i={eventType:"uploadBRB",mutualSubmissionType:"call",payload:e},n=void 0!==t?JSON.stringify({userIds:t}):"";this._glue.sendLoggingEventToNative(JSON.stringify(i),n)}}catch(e){r.error("sendBRBEvent %s: %s",e.name,e.message)}},e.prototype.setBRBCallback=function(e){r.debug2("setBRBCallback"),null!=this._glue?"function"==typeof this._glue.setNativeLoggingEventCallback?this._BRBCallback=e:r.warn("setBRBCallback: RootToolsManagerDelegate missing setNativeLoggingEventCallback method"):r.warn("setBRBCallback: RootToolsManagerDelegate is not set")},e.prototype.registerListeners=function(){var e=this;null!=this._glue&&"function"==typeof this._glue.setNativeLoggingEventCallback?this._glue.setNativeLoggingEventCallback((function(t,i){return e.handleNativeLoggingEvent(t,i)})):r.warn("registerListeners: RootToolsManagerDelegate missing setNativeLoggingEventCallback method")},e.prototype.handleNativeLoggingEvent=function(e,t){try{r.debug2("Native Log event message: %s aux: %s",e,t);var i=JSON.parse(e);if(i.eventType&&"uploadBRB"===i.eventType){if("function"!=typeof this._BRBCallback)return void r.warn("BRBCallback not set, ignoring native event");r.debug4("Sending BRB callback: %@",i.payload),this._BRBCallback(i.payload)}else i.eventType&&"jsLogFileConfiguration"===i.eventType&&this.handleLogFileConfigEvent(i)}catch(e){r.error("handleNativeLoggingEvent %s: %s",e.name,e.message)}},e.prototype.handleLogFileConfigEvent=function(e){if(e.payload){var t=e.payload;if(t.enabled){if(t.chunkSize&&t.flushInterval){var i={chunkSize:t.chunkSize,flushInterval:t.flushInterval,enableThrottling:t.enableThrottling,maxVerbosityLevel:t.maxVerbosityLevel};this.startJsToNativeLogging(i)}}else this.flushDisableJsToNativeLogging()}},e.prototype.logExternalForDDL=function(e,t){try{if(r.debug2("logExternalForDDL %s %s",e,t),null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative){var i={eventType:"logInSClog",payload:{message:e,parameters:t}};this._glue.sendLoggingEventToNative(JSON.stringify(i),"")}else r.warn("ignoring logExternalForDDL, delegate misconfigured")}catch(e){r.error("logExternalForDDL %s: %s",e.name,e.message)}},e.prototype.startJsToNativeLogging=function(e){var t=this,i=e.chunkSize,n=e.flushInterval,a=e.enableThrottling,s=this._getVerbosityLevelFromConfig(e.maxVerbosityLevel);if(this._jsToNativeBuffer){if(this._jsToNativeBuffer.capacity()===i&&this._jsToNativeFlushInterval===n&&this._jsToNativeBuffer.throttlingEnabled()===a&&this._jsToNativeBuffer.maxVerbosityLevel()===s)return void r.debug1("Same JS2Native settings received - doing nothing");r.debug1("Reapplying js to native settings"),this.flushDisableJsToNativeLogging()}this._jsToNativeBuffer=new T(i,(function(){t.onJsToNativeBufferReady(t._jsToNativeBuffer)}),a,s),this.setJsToNativeFlushTimeout(n),this._jsToNativeFlushInterval=n,this._jsToNativeBufferHandle=l.LogFactory.instance().addAppender(this._jsToNativeBuffer)},e.prototype._getVerbosityLevelFromConfig=function(e){return e?l.LogFactory.levelFromString(e):null},e.prototype.flushDisableJsToNativeLogging=function(){this._jsToNativeBuffer&&this.onJsToNativeBufferReady(this._jsToNativeBuffer),this.plainDisableJsToNativeLogging()},e.prototype.plainDisableJsToNativeLogging=function(){this.clearJsToNativeFlushTimeout(),this._jsToNativeBufferHandle&&(l.LogFactory.instance().removeAppender(this._jsToNativeBufferHandle),this._jsToNativeBufferHandle=0,this._jsToNativeBuffer=null,r.debug1("Disabling forwarding JS logs to native"))},e.prototype.onJsToNativeBufferReady=function(e){null!=this._glue&&"function"==typeof this._glue.sendLoggingEventToNative?(this.clearJsToNativeFlushTimeout(),this.dumpJsToNativeBuffer(e),this.setJsToNativeFlushTimeout(this._jsToNativeFlushInterval)):this.plainDisableJsToNativeLogging()},e.prototype.dumpJsToNativeBuffer=function(e){if(!e.empty()){var t=e.dumpAndReset();this._glue.sendLoggingEventToNative(JSON.stringify({eventType:"writeLogData"}),t)}},e.prototype.clearJsToNativeFlushTimeout=function(){this._jsToNativeFlushTimer&&(clearTimeout(this._jsToNativeFlushTimer),this._jsToNativeFlushTimer=null)},e.prototype.setJsToNativeFlushTimeout=function(e){var t=this;!this._jsToNativeFlushTimer&&e&&(this._jsToNativeFlushTimer=setTimeout((function(){t._jsToNativeFlushTimer=null,t.onJsToNativeBufferReady(t._jsToNativeBuffer)}),e))},e.prototype.stopAsyncOperations=function(){this.flushDisableJsToNativeLogging()},e}();t.RootToolsManager=new I})),h=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e},n=!0,r=i,a={},s=0;var o,l=/^([0-9][0-9]?):([^<>\*\{\}&'\"\/\\?^`|~\s]+)$/;!function(e){e[e.MSA=1]="MSA",e[e.S4B_Bridge=2]="S4B_Bridge",e[e.PSTN=4]="PSTN",e[e.SkypeId=8]="SkypeId",e[e.Thread=19]="Thread",e[e.LegacyShortCircuit=20]="LegacyShortCircuit",e[e.OneToOneTextMessage=21]="OneToOneTextMessage",e[e.GroupTextMessage=22]="GroupTextMessage",e[e.Bot=28]="Bot",e[e.InternalSkype=48]="InternalSkype"}(o||(o={}));var c=[o.Thread,o.InternalSkype,o.Bot];t.enableAnonymization=function(e){n=e},t.useTagger=function(e){r=e||i},function(e){function t(e){return n?e?a[e]||function(e){return a[e]="u"+ ++s}(e):null:e}e.UserName=function(e){var i=t(e);return r(i)},e.Mri=function(e){var i,n=e.match(l);if(n){var a=Number(n[1]),s=n[2];i=-1!=c.indexOf(a)?e:a+":"+t(s)}else i=t(e);return r(i)},e.Omit=function(e){var t;return t=n?"number"==typeof e?19229:"string"==typeof e?e.charAt(0)+"...":null:e,r(t)}}(t.pii||(t.pii={}))})),p=s((function(e,t){function i(e){for(var i in e)t.hasOwnProperty(i)||(t[i]=e[i])}Object.defineProperty(t,"__esModule",{value:!0}),i(o),i(l),i(u),i(d),i(h)})),g=s((function(e,t){(function(){var i,n="Expected a function",r="__lodash_hash_undefined__",s="__lodash_placeholder__",o=16,l=32,c=64,d=128,u=256,h=1/0,p=9007199254740991,g=NaN,m=4294967295,f=[["ary",d],["bind",1],["bindKey",2],["curry",8],["curryRight",o],["flip",512],["partial",l],["partialRight",c],["rearg",u]],v="[object Arguments]",S="[object Array]",y="[object Boolean]",C="[object Date]",_="[object Error]",E="[object Function]",T="[object GeneratorFunction]",b="[object Map]",I="[object Number]",w="[object Object]",R="[object Promise]",A="[object RegExp]",P="[object Set]",M="[object String]",k="[object Symbol]",D="[object WeakMap]",O="[object ArrayBuffer]",N="[object DataView]",L="[object Float32Array]",x="[object Float64Array]",F="[object Int8Array]",U="[object Int16Array]",B="[object Int32Array]",V="[object Uint8Array]",H="[object Uint8ClampedArray]",$="[object Uint16Array]",G="[object Uint32Array]",j=/\b__p \+= '';/g,z=/\b(__p \+=) '' \+/g,W=/(__e\(.*?\)|\b__t\)) \+\n'';/g,q=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,J=RegExp(q.source),Y=RegExp(K.source),Q=/<%-([\s\S]+?)%>/g,Z=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,ee=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,te=/^\w*$/,ie=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ne=/[\\^$.*+?()[\]{}|]/g,re=RegExp(ne.source),ae=/^\s+/,se=/\s/,oe=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,le=/\{\n\/\* \[wrapped with (.+)\] \*/,ce=/,? & /,de=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ue=/[()=,{}\[\]\/\s]/,he=/\\(\\)?/g,pe=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,ge=/\w*$/,me=/^[-+]0x[0-9a-f]+$/i,fe=/^0b[01]+$/i,ve=/^\[object .+?Constructor\]$/,Se=/^0o[0-7]+$/i,ye=/^(?:0|[1-9]\d*)$/,Ce=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,_e=/($^)/,Ee=/['\n\r\u2028\u2029\\]/g,Te="\\ud800-\\udfff",be="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Ie="\\u2700-\\u27bf",we="a-z\\xdf-\\xf6\\xf8-\\xff",Re="A-Z\\xc0-\\xd6\\xd8-\\xde",Ae="\\ufe0e\\ufe0f",Pe="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Me="['’]",ke="["+Te+"]",De="["+Pe+"]",Oe="["+be+"]",Ne="\\d+",Le="["+Ie+"]",xe="["+we+"]",Fe="[^"+Te+Pe+Ne+Ie+we+Re+"]",Ue="\\ud83c[\\udffb-\\udfff]",Be="[^"+Te+"]",Ve="(?:\\ud83c[\\udde6-\\uddff]){2}",He="[\\ud800-\\udbff][\\udc00-\\udfff]",$e="["+Re+"]",Ge="\\u200d",je="(?:"+xe+"|"+Fe+")",ze="(?:"+$e+"|"+Fe+")",We="(?:['’](?:d|ll|m|re|s|t|ve))?",qe="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ke="(?:"+Oe+"|"+Ue+")?",Je="["+Ae+"]?",Ye=Je+Ke+"(?:"+Ge+"(?:"+[Be,Ve,He].join("|")+")"+Je+Ke+")*",Qe="(?:"+[Le,Ve,He].join("|")+")"+Ye,Ze="(?:"+[Be+Oe+"?",Oe,Ve,He,ke].join("|")+")",Xe=RegExp(Me,"g"),et=RegExp(Oe,"g"),tt=RegExp(Ue+"(?="+Ue+")|"+Ze+Ye,"g"),it=RegExp([$e+"?"+xe+"+"+We+"(?="+[De,$e,"$"].join("|")+")",ze+"+"+qe+"(?="+[De,$e+je,"$"].join("|")+")",$e+"?"+je+"+"+We,$e+"+"+qe,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Ne,Qe].join("|"),"g"),nt=RegExp("["+Ge+Te+be+Ae+"]"),rt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,at=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],st=-1,ot={};ot[L]=ot[x]=ot[F]=ot[U]=ot[B]=ot[V]=ot[H]=ot[$]=ot[G]=!0,ot[v]=ot[S]=ot[O]=ot[y]=ot[N]=ot[C]=ot[_]=ot[E]=ot[b]=ot[I]=ot[w]=ot[A]=ot[P]=ot[M]=ot[D]=!1;var lt={};lt[v]=lt[S]=lt[O]=lt[N]=lt[y]=lt[C]=lt[L]=lt[x]=lt[F]=lt[U]=lt[B]=lt[b]=lt[I]=lt[w]=lt[A]=lt[P]=lt[M]=lt[k]=lt[V]=lt[H]=lt[$]=lt[G]=!0,lt[_]=lt[E]=lt[D]=!1;var ct={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},dt=parseFloat,ut=parseInt,ht="object"==typeof a&&a&&a.Object===Object&&a,pt="object"==typeof self&&self&&self.Object===Object&&self,gt=ht||pt||Function("return this")(),mt=t&&!t.nodeType&&t,ft=mt&&e&&!e.nodeType&&e,vt=ft&&ft.exports===mt,St=vt&&ht.process,yt=function(){try{return ft&&ft.require&&ft.require("util").types||St&&St.binding&&St.binding("util")}catch(e){}}(),Ct=yt&&yt.isArrayBuffer,_t=yt&&yt.isDate,Et=yt&&yt.isMap,Tt=yt&&yt.isRegExp,bt=yt&&yt.isSet,It=yt&&yt.isTypedArray;function wt(e,t,i){switch(i.length){case 0:return e.call(t);case 1:return e.call(t,i[0]);case 2:return e.call(t,i[0],i[1]);case 3:return e.call(t,i[0],i[1],i[2])}return e.apply(t,i)}function Rt(e,t,i,n){for(var r=-1,a=null==e?0:e.length;++r<a;){var s=e[r];t(n,s,i(s),e)}return n}function At(e,t){for(var i=-1,n=null==e?0:e.length;++i<n&&!1!==t(e[i],i,e););return e}function Pt(e,t){for(var i=null==e?0:e.length;i--&&!1!==t(e[i],i,e););return e}function Mt(e,t){for(var i=-1,n=null==e?0:e.length;++i<n;)if(!t(e[i],i,e))return!1;return!0}function kt(e,t){for(var i=-1,n=null==e?0:e.length,r=0,a=[];++i<n;){var s=e[i];t(s,i,e)&&(a[r++]=s)}return a}function Dt(e,t){return!(null==e||!e.length)&&Gt(e,t,0)>-1}function Ot(e,t,i){for(var n=-1,r=null==e?0:e.length;++n<r;)if(i(t,e[n]))return!0;return!1}function Nt(e,t){for(var i=-1,n=null==e?0:e.length,r=Array(n);++i<n;)r[i]=t(e[i],i,e);return r}function Lt(e,t){for(var i=-1,n=t.length,r=e.length;++i<n;)e[r+i]=t[i];return e}function xt(e,t,i,n){var r=-1,a=null==e?0:e.length;for(n&&a&&(i=e[++r]);++r<a;)i=t(i,e[r],r,e);return i}function Ft(e,t,i,n){var r=null==e?0:e.length;for(n&&r&&(i=e[--r]);r--;)i=t(i,e[r],r,e);return i}function Ut(e,t){for(var i=-1,n=null==e?0:e.length;++i<n;)if(t(e[i],i,e))return!0;return!1}var Bt=qt("length");function Vt(e){return e.match(de)||[]}function Ht(e,t,i){var n;return i(e,(function(e,i,r){if(t(e,i,r))return n=i,!1})),n}function $t(e,t,i,n){for(var r=e.length,a=i+(n?1:-1);n?a--:++a<r;)if(t(e[a],a,e))return a;return-1}function Gt(e,t,i){return t==t?function(e,t,i){for(var n=i-1,r=e.length;++n<r;)if(e[n]===t)return n;return-1}(e,t,i):$t(e,zt,i)}function jt(e,t,i,n){for(var r=i-1,a=e.length;++r<a;)if(n(e[r],t))return r;return-1}function zt(e){return e!=e}function Wt(e,t){var i=null==e?0:e.length;return i?Yt(e,t)/i:g}function qt(e){return function(t){return null==t?i:t[e]}}function Kt(e){return function(t){return null==e?i:e[t]}}function Jt(e,t,i,n,r){return r(e,(function(e,r,a){i=n?(n=!1,e):t(i,e,r,a)})),i}function Yt(e,t){for(var n,r=-1,a=e.length;++r<a;){var s=t(e[r]);s!==i&&(n=n===i?s:n+s)}return n}function Qt(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n}function Zt(e){return e?e.slice(0,mi(e)+1).replace(ae,""):e}function Xt(e){return function(t){return e(t)}}function ei(e,t){return Nt(t,(function(t){return e[t]}))}function ti(e,t){return e.has(t)}function ii(e,t){for(var i=-1,n=e.length;++i<n&&Gt(t,e[i],0)>-1;);return i}function ni(e,t){for(var i=e.length;i--&&Gt(t,e[i],0)>-1;);return i}var ri=Kt({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",Ĳ:"IJ",ĳ:"ij",Œ:"Oe",œ:"oe",ŉ:"'n",ſ:"s"}),ai=Kt({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function si(e){return"\\"+ct[e]}function oi(e){return nt.test(e)}function li(e){return rt.test(e)}function ci(e){var t=-1,i=Array(e.size);return e.forEach((function(e,n){i[++t]=[n,e]})),i}function di(e,t){return function(i){return e(t(i))}}function ui(e,t){for(var i=-1,n=e.length,r=0,a=[];++i<n;){var o=e[i];o!==t&&o!==s||(e[i]=s,a[r++]=i)}return a}function hi(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=e})),i}function pi(e){return oi(e)?function(e){for(var t=tt.lastIndex=0;tt.test(e);)++t;return t}(e):Bt(e)}function gi(e){return oi(e)?function(e){return e.match(tt)||[]}(e):function(e){return e.split("")}(e)}function mi(e){for(var t=e.length;t--&&se.test(e.charAt(t)););return t}var fi=Kt({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});function vi(e){return e.match(it)||[]}var Si=function e(t){var a,se=(t=null==t?gt:Si.defaults(gt.Object(),t,Si.pick(gt,at))).Array,de=t.Date,Te=t.Error,be=t.Function,Ie=t.Math,we=t.Object,Re=t.RegExp,Ae=t.String,Pe=t.TypeError,Me=se.prototype,ke=be.prototype,De=we.prototype,Oe=t["__core-js_shared__"],Ne=ke.toString,Le=De.hasOwnProperty,xe=0,Fe=(a=/[^.]+$/.exec(Oe&&Oe.keys&&Oe.keys.IE_PROTO||""))?"Symbol(src)_1."+a:"",Ue=De.toString,Be=Ne.call(we),Ve=gt._,He=Re("^"+Ne.call(Le).replace(ne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),$e=vt?t.Buffer:i,Ge=t.Symbol,je=t.Uint8Array,ze=$e?$e.allocUnsafe:i,We=di(we.getPrototypeOf,we),qe=we.create,Ke=De.propertyIsEnumerable,Je=Me.splice,Ye=Ge?Ge.isConcatSpreadable:i,Qe=Ge?Ge.iterator:i,Ze=Ge?Ge.toStringTag:i,tt=function(){try{var e=va(we,"defineProperty");return e({},"",{}),e}catch(e){}}(),it=t.clearTimeout!==gt.clearTimeout&&t.clearTimeout,nt=de&&de.now!==gt.Date.now&&de.now,rt=t.setTimeout!==gt.setTimeout&&t.setTimeout,ct=Ie.ceil,ht=Ie.floor,pt=we.getOwnPropertySymbols,mt=$e?$e.isBuffer:i,ft=t.isFinite,St=Me.join,yt=di(we.keys,we),Bt=Ie.max,Kt=Ie.min,yi=de.now,Ci=t.parseInt,_i=Ie.random,Ei=Me.reverse,Ti=va(t,"DataView"),bi=va(t,"Map"),Ii=va(t,"Promise"),wi=va(t,"Set"),Ri=va(t,"WeakMap"),Ai=va(we,"create"),Pi=Ri&&new Ri,Mi={},ki=za(Ti),Di=za(bi),Oi=za(Ii),Ni=za(wi),Li=za(Ri),xi=Ge?Ge.prototype:i,Fi=xi?xi.valueOf:i,Ui=xi?xi.toString:i;function Bi(e){if(lo(e)&&!Qs(e)&&!(e instanceof Gi)){if(e instanceof $i)return e;if(Le.call(e,"__wrapped__"))return Wa(e)}return new $i(e)}var Vi=function(){function e(){}return function(t){if(!oo(t))return{};if(qe)return qe(t);e.prototype=t;var n=new e;return e.prototype=i,n}}();function Hi(){}function $i(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=i}function Gi(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=m,this.__views__=[]}function ji(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function zi(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function Wi(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}function qi(e){var t=-1,i=null==e?0:e.length;for(this.__data__=new Wi;++t<i;)this.add(e[t])}function Ki(e){var t=this.__data__=new zi(e);this.size=t.size}function Ji(e,t){var i=Qs(e),n=!i&&Ys(e),r=!i&&!n&&to(e),a=!i&&!n&&!r&&vo(e),s=i||n||r||a,o=s?Qt(e.length,Ae):[],l=o.length;for(var c in e)!t&&!Le.call(e,c)||s&&("length"==c||r&&("offset"==c||"parent"==c)||a&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||ba(c,l))||o.push(c);return o}function Yi(e){var t=e.length;return t?e[Jn(0,t-1)]:i}function Qi(e,t){return $a(kr(e),on(t,0,e.length))}function Zi(e){return $a(kr(e))}function Xi(e,t,n){(n!==i&&!qs(e[t],n)||n===i&&!(t in e))&&an(e,t,n)}function en(e,t,n){var r=e[t];Le.call(e,t)&&qs(r,n)&&(n!==i||t in e)||an(e,t,n)}function tn(e,t){for(var i=e.length;i--;)if(qs(e[i][0],t))return i;return-1}function nn(e,t,i,n){return hn(e,(function(e,r,a){t(n,e,i(e),a)})),n}function rn(e,t){return e&&Dr(t,Bo(t),e)}function an(e,t,i){"__proto__"==t&&tt?tt(e,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):e[t]=i}function sn(e,t){for(var n=-1,r=t.length,a=se(r),s=null==e;++n<r;)a[n]=s?i:No(e,t[n]);return a}function on(e,t,n){return e==e&&(n!==i&&(e=e<=n?e:n),t!==i&&(e=e>=t?e:t)),e}function ln(e,t,n,r,a,s){var o,l=1&t,c=2&t,d=4&t;if(n&&(o=a?n(e,r,a,s):n(e)),o!==i)return o;if(!oo(e))return e;var u=Qs(e);if(u){if(o=function(e){var t=e.length,i=new e.constructor(t);return t&&"string"==typeof e[0]&&Le.call(e,"index")&&(i.index=e.index,i.input=e.input),i}(e),!l)return kr(e,o)}else{var h=Ca(e),p=h==E||h==T;if(to(e))return Ir(e,l);if(h==w||h==v||p&&!a){if(o=c||p?{}:Ea(e),!l)return c?function(e,t){return Dr(e,ya(e),t)}(e,function(e,t){return e&&Dr(t,Vo(t),e)}(o,e)):function(e,t){return Dr(e,Sa(e),t)}(e,rn(o,e))}else{if(!lt[h])return a?e:{};o=function(e,t,i){var n=e.constructor;switch(t){case O:return wr(e);case y:case C:return new n(+e);case N:return function(e,t){var i=t?wr(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.byteLength)}(e,i);case L:case x:case F:case U:case B:case V:case H:case $:case G:return Rr(e,i);case b:return new n;case I:case M:return new n(e);case A:return function(e){var t=new e.constructor(e.source,ge.exec(e));return t.lastIndex=e.lastIndex,t}(e);case P:return new n;case k:return function(e){return Fi?we(Fi.call(e)):{}}(e)}}(e,h,l)}}s||(s=new Ki);var g=s.get(e);if(g)return g;s.set(e,o),go(e)?e.forEach((function(i){o.add(ln(i,t,n,i,e,s))})):co(e)&&e.forEach((function(i,r){o.set(r,ln(i,t,n,r,e,s))}));var m=u?i:(d?c?da:ca:c?Vo:Bo)(e);return At(m||e,(function(i,r){m&&(i=e[r=i]),en(o,r,ln(i,t,n,r,e,s))})),o}function cn(e,t,n){var r=n.length;if(null==e)return!r;for(e=we(e);r--;){var a=n[r],s=t[a],o=e[a];if(o===i&&!(a in e)||!s(o))return!1}return!0}function dn(e,t,r){if("function"!=typeof e)throw new Pe(n);return Ua((function(){e.apply(i,r)}),t)}function un(e,t,i,n){var r=-1,a=Dt,s=!0,o=e.length,l=[],c=t.length;if(!o)return l;i&&(t=Nt(t,Xt(i))),n?(a=Ot,s=!1):t.length>=200&&(a=ti,s=!1,t=new qi(t));e:for(;++r<o;){var d=e[r],u=null==i?d:i(d);if(d=n||0!==d?d:0,s&&u==u){for(var h=c;h--;)if(t[h]===u)continue e;l.push(d)}else a(t,u,n)||l.push(d)}return l}Bi.templateSettings={escape:Q,evaluate:Z,interpolate:X,variable:"",imports:{_:Bi}},Bi.prototype=Hi.prototype,Bi.prototype.constructor=Bi,$i.prototype=Vi(Hi.prototype),$i.prototype.constructor=$i,Gi.prototype=Vi(Hi.prototype),Gi.prototype.constructor=Gi,ji.prototype.clear=function(){this.__data__=Ai?Ai(null):{},this.size=0},ji.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},ji.prototype.get=function(e){var t=this.__data__;if(Ai){var n=t[e];return n===r?i:n}return Le.call(t,e)?t[e]:i},ji.prototype.has=function(e){var t=this.__data__;return Ai?t[e]!==i:Le.call(t,e)},ji.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=Ai&&t===i?r:t,this},zi.prototype.clear=function(){this.__data__=[],this.size=0},zi.prototype.delete=function(e){var t=this.__data__,i=tn(t,e);return!(i<0||(i==t.length-1?t.pop():Je.call(t,i,1),--this.size,0))},zi.prototype.get=function(e){var t=this.__data__,n=tn(t,e);return n<0?i:t[n][1]},zi.prototype.has=function(e){return tn(this.__data__,e)>-1},zi.prototype.set=function(e,t){var i=this.__data__,n=tn(i,e);return n<0?(++this.size,i.push([e,t])):i[n][1]=t,this},Wi.prototype.clear=function(){this.size=0,this.__data__={hash:new ji,map:new(bi||zi),string:new ji}},Wi.prototype.delete=function(e){var t=ma(this,e).delete(e);return this.size-=t?1:0,t},Wi.prototype.get=function(e){return ma(this,e).get(e)},Wi.prototype.has=function(e){return ma(this,e).has(e)},Wi.prototype.set=function(e,t){var i=ma(this,e),n=i.size;return i.set(e,t),this.size+=i.size==n?0:1,this},qi.prototype.add=qi.prototype.push=function(e){return this.__data__.set(e,r),this},qi.prototype.has=function(e){return this.__data__.has(e)},Ki.prototype.clear=function(){this.__data__=new zi,this.size=0},Ki.prototype.delete=function(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i},Ki.prototype.get=function(e){return this.__data__.get(e)},Ki.prototype.has=function(e){return this.__data__.has(e)},Ki.prototype.set=function(e,t){var i=this.__data__;if(i instanceof zi){var n=i.__data__;if(!bi||n.length<199)return n.push([e,t]),this.size=++i.size,this;i=this.__data__=new Wi(n)}return i.set(e,t),this.size=i.size,this};var hn=Lr(_n),pn=Lr(En,!0);function gn(e,t){var i=!0;return hn(e,(function(e,n,r){return i=!!t(e,n,r)})),i}function mn(e,t,n){for(var r=-1,a=e.length;++r<a;){var s=e[r],o=t(s);if(null!=o&&(l===i?o==o&&!fo(o):n(o,l)))var l=o,c=s}return c}function fn(e,t,n,r){var a=e.length;for((n=Eo(n))<0&&(n=-n>a?0:a+n),(r=r===i||r>a?a:Eo(r))<0&&(r+=a),r=n>r?0:To(r);n<r;)e[n++]=t;return e}function vn(e,t){var i=[];return hn(e,(function(e,n,r){t(e,n,r)&&i.push(e)})),i}function Sn(e,t,i,n,r){var a=-1,s=e.length;for(i||(i=Ta),r||(r=[]);++a<s;){var o=e[a];t>0&&i(o)?t>1?Sn(o,t-1,i,n,r):Lt(r,o):n||(r[r.length]=o)}return r}var yn=xr(),Cn=xr(!0);function _n(e,t){return e&&yn(e,t,Bo)}function En(e,t){return e&&Cn(e,t,Bo)}function Tn(e,t){return kt(t,(function(t){return ro(e[t])}))}function bn(e,t){for(var n=0,r=(t=_r(t,e)).length;null!=e&&n<r;)e=e[ja(t[n++])];return n&&n==r?e:i}function In(e,t,i){var n=t(e);return Qs(e)?n:Lt(n,i(e))}function wn(e){return null==e?e===i?"[object Undefined]":"[object Null]":Ze&&Ze in we(e)?function(e){var t=Le.call(e,Ze),n=e[Ze];try{e[Ze]=i;var r=!0}catch(e){}var a=Ue.call(e);return r&&(t?e[Ze]=n:delete e[Ze]),a}(e):function(e){return Ue.call(e)}(e)}function Rn(e,t){return e>t}function An(e,t){return null!=e&&Le.call(e,t)}function Pn(e,t){return null!=e&&t in we(e)}function Mn(e,t,n){for(var r=n?Ot:Dt,a=e[0].length,s=e.length,o=s,l=se(s),c=1/0,d=[];o--;){var u=e[o];o&&t&&(u=Nt(u,Xt(t))),c=Kt(u.length,c),l[o]=!n&&(t||a>=120&&u.length>=120)?new qi(o&&u):i}u=e[0];var h=-1,p=l[0];e:for(;++h<a&&d.length<c;){var g=u[h],m=t?t(g):g;if(g=n||0!==g?g:0,!(p?ti(p,m):r(d,m,n))){for(o=s;--o;){var f=l[o];if(!(f?ti(f,m):r(e[o],m,n)))continue e}p&&p.push(m),d.push(g)}}return d}function kn(e,t,n){var r=null==(e=Na(e,t=_r(t,e)))?e:e[ja(ns(t))];return null==r?i:wt(r,e,n)}function Dn(e){return lo(e)&&wn(e)==v}function On(e,t,i,n,r){return e===t||(null==e||null==t||!lo(e)&&!lo(t)?e!=e&&t!=t:function(e,t,i,n,r,a){var s=Qs(e),o=Qs(t),l=s?S:Ca(e),c=o?S:Ca(t),d=(l=l==v?w:l)==w,u=(c=c==v?w:c)==w,h=l==c;if(h&&to(e)){if(!to(t))return!1;s=!0,d=!1}if(h&&!d)return a||(a=new Ki),s||vo(e)?aa(e,t,i,n,r,a):sa(e,t,l,i,n,r,a);if(!(1&i)){var p=d&&Le.call(e,"__wrapped__"),g=u&&Le.call(t,"__wrapped__");if(p||g){var m=p?e.value():e,f=g?t.value():t;return a||(a=new Ki),r(m,f,i,n,a)}}return!!h&&(a||(a=new Ki),oa(e,t,i,n,r,a))}(e,t,i,n,On,r))}function Nn(e,t,n,r){var a=n.length,s=a,o=!r;if(null==e)return!s;for(e=we(e);a--;){var l=n[a];if(o&&l[2]?l[1]!==e[l[0]]:!(l[0]in e))return!1}for(;++a<s;){var c=(l=n[a])[0],d=e[c],u=l[1];if(o&&l[2]){if(d===i&&!(c in e))return!1}else{var h=new Ki;if(r)var p=r(d,u,c,e,t,h);if(!(p===i?On(u,d,3,r,h):p))return!1}}return!0}function Ln(e){return!(!oo(e)||function(e){return!!Fe&&Fe in e}(e))&&(ro(e)?He:ve).test(za(e))}function xn(e){return"function"==typeof e?e:null==e?ul:"object"==typeof e?Qs(e)?$n(e[0],e[1]):Hn(e):Cl(e)}function Fn(e){if(!Pa(e))return yt(e);var t=[];for(var i in we(e))Le.call(e,i)&&"constructor"!=i&&t.push(i);return t}function Un(e){if(!oo(e))return function(e){var t=[];if(null!=e)for(var i in we(e))t.push(i);return t}(e);var t=Pa(e),i=[];for(var n in e)("constructor"!=n||!t&&Le.call(e,n))&&i.push(n);return i}function Bn(e,t){return e<t}function Vn(e,t){var i=-1,n=Xs(e)?se(e.length):[];return hn(e,(function(e,r,a){n[++i]=t(e,r,a)})),n}function Hn(e){var t=fa(e);return 1==t.length&&t[0][2]?ka(t[0][0],t[0][1]):function(i){return i===e||Nn(i,e,t)}}function $n(e,t){return wa(e)&&Ma(t)?ka(ja(e),t):function(n){var r=No(n,e);return r===i&&r===t?Lo(n,e):On(t,r,3)}}function Gn(e,t,n,r,a){e!==t&&yn(t,(function(s,o){if(a||(a=new Ki),oo(s))!function(e,t,n,r,a,s,o){var l=xa(e,n),c=xa(t,n),d=o.get(c);if(d)Xi(e,n,d);else{var u=s?s(l,c,n+"",e,t,o):i,h=u===i;if(h){var p=Qs(c),g=!p&&to(c),m=!p&&!g&&vo(c);u=c,p||g||m?Qs(l)?u=l:eo(l)?u=kr(l):g?(h=!1,u=Ir(c,!0)):m?(h=!1,u=Rr(c,!0)):u=[]:ho(c)||Ys(c)?(u=l,Ys(l)?u=Io(l):oo(l)&&!ro(l)||(u=Ea(c))):h=!1}h&&(o.set(c,u),a(u,c,r,s,o),o.delete(c)),Xi(e,n,u)}}(e,t,o,n,Gn,r,a);else{var l=r?r(xa(e,o),s,o+"",e,t,a):i;l===i&&(l=s),Xi(e,o,l)}}),Vo)}function jn(e,t){var n=e.length;if(n)return ba(t+=t<0?n:0,n)?e[t]:i}function zn(e,t,i){t=t.length?Nt(t,(function(e){return Qs(e)?function(t){return bn(t,1===e.length?e[0]:e)}:e})):[ul];var n=-1;t=Nt(t,Xt(ga()));var r=Vn(e,(function(e,i,r){var a=Nt(t,(function(t){return t(e)}));return{criteria:a,index:++n,value:e}}));return function(e,t){var i=e.length;for(e.sort(t);i--;)e[i]=e[i].value;return e}(r,(function(e,t){return function(e,t,i){for(var n=-1,r=e.criteria,a=t.criteria,s=r.length,o=i.length;++n<s;){var l=Ar(r[n],a[n]);if(l)return n>=o?l:l*("desc"==i[n]?-1:1)}return e.index-t.index}(e,t,i)}))}function Wn(e,t,i){for(var n=-1,r=t.length,a={};++n<r;){var s=t[n],o=bn(e,s);i(o,s)&&tr(a,_r(s,e),o)}return a}function qn(e,t,i,n){var r=n?jt:Gt,a=-1,s=t.length,o=e;for(e===t&&(t=kr(t)),i&&(o=Nt(e,Xt(i)));++a<s;)for(var l=0,c=t[a],d=i?i(c):c;(l=r(o,d,l,n))>-1;)o!==e&&Je.call(o,l,1),Je.call(e,l,1);return e}function Kn(e,t){for(var i=e?t.length:0,n=i-1;i--;){var r=t[i];if(i==n||r!==a){var a=r;ba(r)?Je.call(e,r,1):pr(e,r)}}return e}function Jn(e,t){return e+ht(_i()*(t-e+1))}function Yn(e,t,i,n){for(var r=-1,a=Bt(ct((t-e)/(i||1)),0),s=se(a);a--;)s[n?a:++r]=e,e+=i;return s}function Qn(e,t){var i="";if(!e||t<1||t>p)return i;do{t%2&&(i+=e),(t=ht(t/2))&&(e+=e)}while(t);return i}function Zn(e,t){return Ba(Oa(e,t,ul),e+"")}function Xn(e){return Yi(Ko(e))}function er(e,t){var i=Ko(e);return $a(i,on(t,0,i.length))}function tr(e,t,n,r){if(!oo(e))return e;for(var a=-1,s=(t=_r(t,e)).length,o=s-1,l=e;null!=l&&++a<s;){var c=ja(t[a]),d=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return e;if(a!=o){var u=l[c];(d=r?r(u,c,l):i)===i&&(d=oo(u)?u:ba(t[a+1])?[]:{})}en(l,c,d),l=l[c]}return e}var ir=Pi?function(e,t){return Pi.set(e,t),e}:ul,nr=tt?function(e,t){return tt(e,"toString",{configurable:!0,enumerable:!1,value:ll(t),writable:!0})}:ul;function rr(e){return $a(Ko(e))}function ar(e,t,i){var n=-1,r=e.length;t<0&&(t=-t>r?0:r+t),(i=i>r?r:i)<0&&(i+=r),r=t>i?0:i-t>>>0,t>>>=0;for(var a=se(r);++n<r;)a[n]=e[n+t];return a}function sr(e,t){var i;return hn(e,(function(e,n,r){return!(i=t(e,n,r))})),!!i}function or(e,t,i){var n=0,r=null==e?n:e.length;if("number"==typeof t&&t==t&&r<=2147483647){for(;n<r;){var a=n+r>>>1,s=e[a];null!==s&&!fo(s)&&(i?s<=t:s<t)?n=a+1:r=a}return r}return lr(e,t,ul,i)}function lr(e,t,n,r){var a=0,s=null==e?0:e.length;if(0===s)return 0;for(var o=(t=n(t))!=t,l=null===t,c=fo(t),d=t===i;a<s;){var u=ht((a+s)/2),h=n(e[u]),p=h!==i,g=null===h,m=h==h,f=fo(h);if(o)var v=r||m;else v=d?m&&(r||p):l?m&&p&&(r||!g):c?m&&p&&!g&&(r||!f):!g&&!f&&(r?h<=t:h<t);v?a=u+1:s=u}return Kt(s,4294967294)}function cr(e,t){for(var i=-1,n=e.length,r=0,a=[];++i<n;){var s=e[i],o=t?t(s):s;if(!i||!qs(o,l)){var l=o;a[r++]=0===s?0:s}}return a}function dr(e){return"number"==typeof e?e:fo(e)?g:+e}function ur(e){if("string"==typeof e)return e;if(Qs(e))return Nt(e,ur)+"";if(fo(e))return Ui?Ui.call(e):"";var t=e+"";return"0"==t&&1/e==-h?"-0":t}function hr(e,t,i){var n=-1,r=Dt,a=e.length,s=!0,o=[],l=o;if(i)s=!1,r=Ot;else if(a>=200){var c=t?null:Xr(e);if(c)return hi(c);s=!1,r=ti,l=new qi}else l=t?[]:o;e:for(;++n<a;){var d=e[n],u=t?t(d):d;if(d=i||0!==d?d:0,s&&u==u){for(var h=l.length;h--;)if(l[h]===u)continue e;t&&l.push(u),o.push(d)}else r(l,u,i)||(l!==o&&l.push(u),o.push(d))}return o}function pr(e,t){return null==(e=Na(e,t=_r(t,e)))||delete e[ja(ns(t))]}function gr(e,t,i,n){return tr(e,t,i(bn(e,t)),n)}function mr(e,t,i,n){for(var r=e.length,a=n?r:-1;(n?a--:++a<r)&&t(e[a],a,e););return i?ar(e,n?0:a,n?a+1:r):ar(e,n?a+1:0,n?r:a)}function fr(e,t){var i=e;return i instanceof Gi&&(i=i.value()),xt(t,(function(e,t){return t.func.apply(t.thisArg,Lt([e],t.args))}),i)}function vr(e,t,i){var n=e.length;if(n<2)return n?hr(e[0]):[];for(var r=-1,a=se(n);++r<n;)for(var s=e[r],o=-1;++o<n;)o!=r&&(a[r]=un(a[r]||s,e[o],t,i));return hr(Sn(a,1),t,i)}function Sr(e,t,n){for(var r=-1,a=e.length,s=t.length,o={};++r<a;){var l=r<s?t[r]:i;n(o,e[r],l)}return o}function yr(e){return eo(e)?e:[]}function Cr(e){return"function"==typeof e?e:ul}function _r(e,t){return Qs(e)?e:wa(e,t)?[e]:Ga(wo(e))}var Er=Zn;function Tr(e,t,n){var r=e.length;return n=n===i?r:n,!t&&n>=r?e:ar(e,t,n)}var br=it||function(e){return gt.clearTimeout(e)};function Ir(e,t){if(t)return e.slice();var i=e.length,n=ze?ze(i):new e.constructor(i);return e.copy(n),n}function wr(e){var t=new e.constructor(e.byteLength);return new je(t).set(new je(e)),t}function Rr(e,t){var i=t?wr(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)}function Ar(e,t){if(e!==t){var n=e!==i,r=null===e,a=e==e,s=fo(e),o=t!==i,l=null===t,c=t==t,d=fo(t);if(!l&&!d&&!s&&e>t||s&&o&&c&&!l&&!d||r&&o&&c||!n&&c||!a)return 1;if(!r&&!s&&!d&&e<t||d&&n&&a&&!r&&!s||l&&n&&a||!o&&a||!c)return-1}return 0}function Pr(e,t,i,n){for(var r=-1,a=e.length,s=i.length,o=-1,l=t.length,c=Bt(a-s,0),d=se(l+c),u=!n;++o<l;)d[o]=t[o];for(;++r<s;)(u||r<a)&&(d[i[r]]=e[r]);for(;c--;)d[o++]=e[r++];return d}function Mr(e,t,i,n){for(var r=-1,a=e.length,s=-1,o=i.length,l=-1,c=t.length,d=Bt(a-o,0),u=se(d+c),h=!n;++r<d;)u[r]=e[r];for(var p=r;++l<c;)u[p+l]=t[l];for(;++s<o;)(h||r<a)&&(u[p+i[s]]=e[r++]);return u}function kr(e,t){var i=-1,n=e.length;for(t||(t=se(n));++i<n;)t[i]=e[i];return t}function Dr(e,t,n,r){var a=!n;n||(n={});for(var s=-1,o=t.length;++s<o;){var l=t[s],c=r?r(n[l],e[l],l,n,e):i;c===i&&(c=e[l]),a?an(n,l,c):en(n,l,c)}return n}function Or(e,t){return function(i,n){var r=Qs(i)?Rt:nn,a=t?t():{};return r(i,e,ga(n,2),a)}}function Nr(e){return Zn((function(t,n){var r=-1,a=n.length,s=a>1?n[a-1]:i,o=a>2?n[2]:i;for(s=e.length>3&&"function"==typeof s?(a--,s):i,o&&Ia(n[0],n[1],o)&&(s=a<3?i:s,a=1),t=we(t);++r<a;){var l=n[r];l&&e(t,l,r,s)}return t}))}function Lr(e,t){return function(i,n){if(null==i)return i;if(!Xs(i))return e(i,n);for(var r=i.length,a=t?r:-1,s=we(i);(t?a--:++a<r)&&!1!==n(s[a],a,s););return i}}function xr(e){return function(t,i,n){for(var r=-1,a=we(t),s=n(t),o=s.length;o--;){var l=s[e?o:++r];if(!1===i(a[l],l,a))break}return t}}function Fr(e){return function(t){var n=oi(t=wo(t))?gi(t):i,r=n?n[0]:t.charAt(0),a=n?Tr(n,1).join(""):t.slice(1);return r[e]()+a}}function Ur(e){return function(t){return xt(al(Qo(t).replace(Xe,"")),e,"")}}function Br(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var i=Vi(e.prototype),n=e.apply(i,t);return oo(n)?n:i}}function Vr(e,t,n){var r=Br(e);return function a(){for(var s=arguments.length,o=se(s),l=s,c=pa(a);l--;)o[l]=arguments[l];var d=s<3&&o[0]!==c&&o[s-1]!==c?[]:ui(o,c);return(s-=d.length)<n?Qr(e,t,Gr,a.placeholder,i,o,d,i,i,n-s):wt(this&&this!==gt&&this instanceof a?r:e,this,o)}}function Hr(e){return function(t,n,r){var a=we(t);if(!Xs(t)){var s=ga(n,3);t=Bo(t),n=function(e){return s(a[e],e,a)}}var o=e(t,n,r);return o>-1?a[s?t[o]:o]:i}}function $r(e){return la((function(t){var r=t.length,a=r,s=$i.prototype.thru;for(e&&t.reverse();a--;){var o=t[a];if("function"!=typeof o)throw new Pe(n);if(s&&!l&&"wrapper"==ha(o))var l=new $i([],!0)}for(a=l?a:r;++a<r;){var c=ha(o=t[a]),d="wrapper"==c?ua(o):i;l=d&&Ra(d[0])&&424==d[1]&&!d[4].length&&1==d[9]?l[ha(d[0])].apply(l,d[3]):1==o.length&&Ra(o)?l[c]():l.thru(o)}return function(){var e=arguments,i=e[0];if(l&&1==e.length&&Qs(i))return l.plant(i).value();for(var n=0,a=r?t[n].apply(this,e):i;++n<r;)a=t[n].call(this,a);return a}}))}function Gr(e,t,n,r,a,s,o,l,c,u){var h=t&d,p=1&t,g=2&t,m=24&t,f=512&t,v=g?i:Br(e);return function i(){for(var d=arguments.length,S=se(d),y=d;y--;)S[y]=arguments[y];if(m)var C=pa(i),_=function(e,t){for(var i=e.length,n=0;i--;)e[i]===t&&++n;return n}(S,C);if(r&&(S=Pr(S,r,a,m)),s&&(S=Mr(S,s,o,m)),d-=_,m&&d<u){var E=ui(S,C);return Qr(e,t,Gr,i.placeholder,n,S,E,l,c,u-d)}var T=p?n:this,b=g?T[e]:e;return d=S.length,l?S=La(S,l):f&&d>1&&S.reverse(),h&&c<d&&(S.length=c),this&&this!==gt&&this instanceof i&&(b=v||Br(b)),b.apply(T,S)}}function jr(e,t){return function(i,n){return function(e,t,i,n){return _n(e,(function(e,r,a){t(n,i(e),r,a)})),n}(i,e,t(n),{})}}function zr(e,t){return function(n,r){var a;if(n===i&&r===i)return t;if(n!==i&&(a=n),r!==i){if(a===i)return r;"string"==typeof n||"string"==typeof r?(n=ur(n),r=ur(r)):(n=dr(n),r=dr(r)),a=e(n,r)}return a}}function Wr(e){return la((function(t){return t=Nt(t,Xt(ga())),Zn((function(i){var n=this;return e(t,(function(e){return wt(e,n,i)}))}))}))}function qr(e,t){var n=(t=t===i?" ":ur(t)).length;if(n<2)return n?Qn(t,e):t;var r=Qn(t,ct(e/pi(t)));return oi(t)?Tr(gi(r),0,e).join(""):r.slice(0,e)}function Kr(e,t,i,n){var r=1&t,a=Br(e);return function t(){for(var s=-1,o=arguments.length,l=-1,c=n.length,d=se(c+o),u=this&&this!==gt&&this instanceof t?a:e;++l<c;)d[l]=n[l];for(;o--;)d[l++]=arguments[++s];return wt(u,r?i:this,d)}}function Jr(e){return function(t,n,r){return r&&"number"!=typeof r&&Ia(t,n,r)&&(n=r=i),t=_o(t),n===i?(n=t,t=0):n=_o(n),Yn(t,n,r=r===i?t<n?1:-1:_o(r),e)}}function Yr(e){return function(t,i){return"string"==typeof t&&"string"==typeof i||(t=bo(t),i=bo(i)),e(t,i)}}function Qr(e,t,n,r,a,s,o,d,u,h){var p=8&t;t|=p?l:c,4&(t&=~(p?c:l))||(t&=-4);var g=[e,t,a,p?s:i,p?o:i,p?i:s,p?i:o,d,u,h],m=n.apply(i,g);return Ra(e)&&Fa(m,g),m.placeholder=r,Va(m,e,t)}function Zr(e){var t=Ie[e];return function(e,i){if(e=bo(e),(i=null==i?0:Kt(Eo(i),292))&&ft(e)){var n=(wo(e)+"e").split("e");return+((n=(wo(t(n[0]+"e"+(+n[1]+i)))+"e").split("e"))[0]+"e"+(+n[1]-i))}return t(e)}}var Xr=wi&&1/hi(new wi([,-0]))[1]==h?function(e){return new wi(e)}:fl;function ea(e){return function(t){var i=Ca(t);return i==b?ci(t):i==P?function(e){var t=-1,i=Array(e.size);return e.forEach((function(e){i[++t]=[e,e]})),i}(t):function(e,t){return Nt(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function ta(e,t,r,a,s,d,u,h){var p=2&t;if(!p&&"function"!=typeof e)throw new Pe(n);var g=a?a.length:0;if(g||(t&=-97,a=s=i),u=u===i?u:Bt(Eo(u),0),h=h===i?h:Eo(h),g-=s?s.length:0,t&c){var m=a,f=s;a=s=i}var v=p?i:ua(e),S=[e,t,r,a,s,m,f,d,u,h];if(v&&Da(S,v),e=S[0],t=S[1],r=S[2],a=S[3],s=S[4],!(h=S[9]=S[9]===i?p?0:e.length:Bt(S[9]-g,0))&&24&t&&(t&=-25),t&&1!=t)y=8==t||t==o?Vr(e,t,h):t!=l&&33!=t||s.length?Gr.apply(i,S):Kr(e,t,r,a);else var y=function(e,t,i){var n=1&t,r=Br(e);return function t(){return(this&&this!==gt&&this instanceof t?r:e).apply(n?i:this,arguments)}}(e,t,r);return Va((v?ir:Fa)(y,S),e,t)}function ia(e,t,n,r){return e===i||qs(e,De[n])&&!Le.call(r,n)?t:e}function na(e,t,n,r,a,s){return oo(e)&&oo(t)&&(s.set(t,e),Gn(e,t,i,na,s),s.delete(t)),e}function ra(e){return ho(e)?i:e}function aa(e,t,n,r,a,s){var o=1&n,l=e.length,c=t.length;if(l!=c&&!(o&&c>l))return!1;var d=s.get(e),u=s.get(t);if(d&&u)return d==t&&u==e;var h=-1,p=!0,g=2&n?new qi:i;for(s.set(e,t),s.set(t,e);++h<l;){var m=e[h],f=t[h];if(r)var v=o?r(f,m,h,t,e,s):r(m,f,h,e,t,s);if(v!==i){if(v)continue;p=!1;break}if(g){if(!Ut(t,(function(e,t){if(!ti(g,t)&&(m===e||a(m,e,n,r,s)))return g.push(t)}))){p=!1;break}}else if(m!==f&&!a(m,f,n,r,s)){p=!1;break}}return s.delete(e),s.delete(t),p}function sa(e,t,i,n,r,a,s){switch(i){case N:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case O:return!(e.byteLength!=t.byteLength||!a(new je(e),new je(t)));case y:case C:case I:return qs(+e,+t);case _:return e.name==t.name&&e.message==t.message;case A:case M:return e==t+"";case b:var o=ci;case P:var l=1&n;if(o||(o=hi),e.size!=t.size&&!l)return!1;var c=s.get(e);if(c)return c==t;n|=2,s.set(e,t);var d=aa(o(e),o(t),n,r,a,s);return s.delete(e),d;case k:if(Fi)return Fi.call(e)==Fi.call(t)}return!1}function oa(e,t,n,r,a,s){var o=1&n,l=ca(e),c=l.length;if(c!=ca(t).length&&!o)return!1;for(var d=c;d--;){var u=l[d];if(!(o?u in t:Le.call(t,u)))return!1}var h=s.get(e),p=s.get(t);if(h&&p)return h==t&&p==e;var g=!0;s.set(e,t),s.set(t,e);for(var m=o;++d<c;){var f=e[u=l[d]],v=t[u];if(r)var S=o?r(v,f,u,t,e,s):r(f,v,u,e,t,s);if(!(S===i?f===v||a(f,v,n,r,s):S)){g=!1;break}m||(m="constructor"==u)}if(g&&!m){var y=e.constructor,C=t.constructor;y==C||!("constructor"in e)||!("constructor"in t)||"function"==typeof y&&y instanceof y&&"function"==typeof C&&C instanceof C||(g=!1)}return s.delete(e),s.delete(t),g}function la(e){return Ba(Oa(e,i,Za),e+"")}function ca(e){return In(e,Bo,Sa)}function da(e){return In(e,Vo,ya)}var ua=Pi?function(e){return Pi.get(e)}:fl;function ha(e){for(var t=e.name+"",i=Mi[t],n=Le.call(Mi,t)?i.length:0;n--;){var r=i[n],a=r.func;if(null==a||a==e)return r.name}return t}function pa(e){return(Le.call(Bi,"placeholder")?Bi:e).placeholder}function ga(){var e=Bi.iteratee||hl;return e=e===hl?xn:e,arguments.length?e(arguments[0],arguments[1]):e}function ma(e,t){var i=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?i["string"==typeof t?"string":"hash"]:i.map}function fa(e){for(var t=Bo(e),i=t.length;i--;){var n=t[i],r=e[n];t[i]=[n,r,Ma(r)]}return t}function va(e,t){var n=function(e,t){return null==e?i:e[t]}(e,t);return Ln(n)?n:i}var Sa=pt?function(e){return null==e?[]:(e=we(e),kt(pt(e),(function(t){return Ke.call(e,t)})))}:Tl,ya=pt?function(e){for(var t=[];e;)Lt(t,Sa(e)),e=We(e);return t}:Tl,Ca=wn;function _a(e,t,i){for(var n=-1,r=(t=_r(t,e)).length,a=!1;++n<r;){var s=ja(t[n]);if(!(a=null!=e&&i(e,s)))break;e=e[s]}return a||++n!=r?a:!!(r=null==e?0:e.length)&&so(r)&&ba(s,r)&&(Qs(e)||Ys(e))}function Ea(e){return"function"!=typeof e.constructor||Pa(e)?{}:Vi(We(e))}function Ta(e){return Qs(e)||Ys(e)||!!(Ye&&e&&e[Ye])}function ba(e,t){var i=typeof e;return!!(t=null==t?p:t)&&("number"==i||"symbol"!=i&&ye.test(e))&&e>-1&&e%1==0&&e<t}function Ia(e,t,i){if(!oo(i))return!1;var n=typeof t;return!!("number"==n?Xs(i)&&ba(t,i.length):"string"==n&&t in i)&&qs(i[t],e)}function wa(e,t){if(Qs(e))return!1;var i=typeof e;return!("number"!=i&&"symbol"!=i&&"boolean"!=i&&null!=e&&!fo(e))||te.test(e)||!ee.test(e)||null!=t&&e in we(t)}function Ra(e){var t=ha(e),i=Bi[t];if("function"!=typeof i||!(t in Gi.prototype))return!1;if(e===i)return!0;var n=ua(i);return!!n&&e===n[0]}(Ti&&Ca(new Ti(new ArrayBuffer(1)))!=N||bi&&Ca(new bi)!=b||Ii&&Ca(Ii.resolve())!=R||wi&&Ca(new wi)!=P||Ri&&Ca(new Ri)!=D)&&(Ca=function(e){var t=wn(e),n=t==w?e.constructor:i,r=n?za(n):"";if(r)switch(r){case ki:return N;case Di:return b;case Oi:return R;case Ni:return P;case Li:return D}return t});var Aa=Oe?ro:bl;function Pa(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||De)}function Ma(e){return e==e&&!oo(e)}function ka(e,t){return function(n){return null!=n&&n[e]===t&&(t!==i||e in we(n))}}function Da(e,t){var i=e[1],n=t[1],r=i|n,a=r<131,o=n==d&&8==i||n==d&&i==u&&e[7].length<=t[8]||384==n&&t[7].length<=t[8]&&8==i;if(!a&&!o)return e;1&n&&(e[2]=t[2],r|=1&i?0:4);var l=t[3];if(l){var c=e[3];e[3]=c?Pr(c,l,t[4]):l,e[4]=c?ui(e[3],s):t[4]}return(l=t[5])&&(c=e[5],e[5]=c?Mr(c,l,t[6]):l,e[6]=c?ui(e[5],s):t[6]),(l=t[7])&&(e[7]=l),n&d&&(e[8]=null==e[8]?t[8]:Kt(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=r,e}function Oa(e,t,n){return t=Bt(t===i?e.length-1:t,0),function(){for(var i=arguments,r=-1,a=Bt(i.length-t,0),s=se(a);++r<a;)s[r]=i[t+r];r=-1;for(var o=se(t+1);++r<t;)o[r]=i[r];return o[t]=n(s),wt(e,this,o)}}function Na(e,t){return t.length<2?e:bn(e,ar(t,0,-1))}function La(e,t){for(var n=e.length,r=Kt(t.length,n),a=kr(e);r--;){var s=t[r];e[r]=ba(s,n)?a[s]:i}return e}function xa(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Fa=Ha(ir),Ua=rt||function(e,t){return gt.setTimeout(e,t)},Ba=Ha(nr);function Va(e,t,i){var n=t+"";return Ba(e,function(e,t){var i=t.length;if(!i)return e;var n=i-1;return t[n]=(i>1?"& ":"")+t[n],t=t.join(i>2?", ":" "),e.replace(oe,"{\n/* [wrapped with "+t+"] */\n")}(n,function(e,t){return At(f,(function(i){var n="_."+i[0];t&i[1]&&!Dt(e,n)&&e.push(n)})),e.sort()}(function(e){var t=e.match(le);return t?t[1].split(ce):[]}(n),i)))}function Ha(e){var t=0,n=0;return function(){var r=yi(),a=16-(r-n);if(n=r,a>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(i,arguments)}}function $a(e,t){var n=-1,r=e.length,a=r-1;for(t=t===i?r:t;++n<t;){var s=Jn(n,a),o=e[s];e[s]=e[n],e[n]=o}return e.length=t,e}var Ga=function(e){var t=Hs(e,(function(e){return 500===i.size&&i.clear(),e})),i=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(ie,(function(e,i,n,r){t.push(n?r.replace(he,"$1"):i||e)})),t}));function ja(e){if("string"==typeof e||fo(e))return e;var t=e+"";return"0"==t&&1/e==-h?"-0":t}function za(e){if(null!=e){try{return Ne.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Wa(e){if(e instanceof Gi)return e.clone();var t=new $i(e.__wrapped__,e.__chain__);return t.__actions__=kr(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var qa=Zn((function(e,t){return eo(e)?un(e,Sn(t,1,eo,!0)):[]})),Ka=Zn((function(e,t){var n=ns(t);return eo(n)&&(n=i),eo(e)?un(e,Sn(t,1,eo,!0),ga(n,2)):[]})),Ja=Zn((function(e,t){var n=ns(t);return eo(n)&&(n=i),eo(e)?un(e,Sn(t,1,eo,!0),i,n):[]}));function Ya(e,t,i){var n=null==e?0:e.length;if(!n)return-1;var r=null==i?0:Eo(i);return r<0&&(r=Bt(n+r,0)),$t(e,ga(t,3),r)}function Qa(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var a=r-1;return n!==i&&(a=Eo(n),a=n<0?Bt(r+a,0):Kt(a,r-1)),$t(e,ga(t,3),a,!0)}function Za(e){return null!=e&&e.length?Sn(e,1):[]}function Xa(e){return e&&e.length?e[0]:i}var es=Zn((function(e){var t=Nt(e,yr);return t.length&&t[0]===e[0]?Mn(t):[]})),ts=Zn((function(e){var t=ns(e),n=Nt(e,yr);return t===ns(n)?t=i:n.pop(),n.length&&n[0]===e[0]?Mn(n,ga(t,2)):[]})),is=Zn((function(e){var t=ns(e),n=Nt(e,yr);return(t="function"==typeof t?t:i)&&n.pop(),n.length&&n[0]===e[0]?Mn(n,i,t):[]}));function ns(e){var t=null==e?0:e.length;return t?e[t-1]:i}var rs=Zn(as);function as(e,t){return e&&e.length&&t&&t.length?qn(e,t):e}var ss=la((function(e,t){var i=null==e?0:e.length,n=sn(e,t);return Kn(e,Nt(t,(function(e){return ba(e,i)?+e:e})).sort(Ar)),n}));function os(e){return null==e?e:Ei.call(e)}var ls=Zn((function(e){return hr(Sn(e,1,eo,!0))})),cs=Zn((function(e){var t=ns(e);return eo(t)&&(t=i),hr(Sn(e,1,eo,!0),ga(t,2))})),ds=Zn((function(e){var t=ns(e);return t="function"==typeof t?t:i,hr(Sn(e,1,eo,!0),i,t)}));function us(e){if(!e||!e.length)return[];var t=0;return e=kt(e,(function(e){if(eo(e))return t=Bt(e.length,t),!0})),Qt(t,(function(t){return Nt(e,qt(t))}))}function hs(e,t){if(!e||!e.length)return[];var n=us(e);return null==t?n:Nt(n,(function(e){return wt(t,i,e)}))}var ps=Zn((function(e,t){return eo(e)?un(e,t):[]})),gs=Zn((function(e){return vr(kt(e,eo))})),ms=Zn((function(e){var t=ns(e);return eo(t)&&(t=i),vr(kt(e,eo),ga(t,2))})),fs=Zn((function(e){var t=ns(e);return t="function"==typeof t?t:i,vr(kt(e,eo),i,t)})),vs=Zn(us);var Ss=Zn((function(e){var t=e.length,n=t>1?e[t-1]:i;return n="function"==typeof n?(e.pop(),n):i,hs(e,n)}));function ys(e){var t=Bi(e);return t.__chain__=!0,t}function Cs(e,t){return t(e)}var _s=la((function(e){var t=e.length,n=t?e[0]:0,r=this.__wrapped__,a=function(t){return sn(t,e)};return!(t>1||this.__actions__.length)&&r instanceof Gi&&ba(n)?((r=r.slice(n,+n+(t?1:0))).__actions__.push({func:Cs,args:[a],thisArg:i}),new $i(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(i),e}))):this.thru(a)}));var Es=Or((function(e,t,i){Le.call(e,i)?++e[i]:an(e,i,1)}));var Ts=Hr(Ya),bs=Hr(Qa);function Is(e,t){return(Qs(e)?At:hn)(e,ga(t,3))}function ws(e,t){return(Qs(e)?Pt:pn)(e,ga(t,3))}var Rs=Or((function(e,t,i){Le.call(e,i)?e[i].push(t):an(e,i,[t])}));var As=Zn((function(e,t,i){var n=-1,r="function"==typeof t,a=Xs(e)?se(e.length):[];return hn(e,(function(e){a[++n]=r?wt(t,e,i):kn(e,t,i)})),a})),Ps=Or((function(e,t,i){an(e,i,t)}));function Ms(e,t){return(Qs(e)?Nt:Vn)(e,ga(t,3))}var ks=Or((function(e,t,i){e[i?0:1].push(t)}),(function(){return[[],[]]}));var Ds=Zn((function(e,t){if(null==e)return[];var i=t.length;return i>1&&Ia(e,t[0],t[1])?t=[]:i>2&&Ia(t[0],t[1],t[2])&&(t=[t[0]]),zn(e,Sn(t,1),[])})),Os=nt||function(){return gt.Date.now()};function Ns(e,t,n){return t=n?i:t,t=e&&null==t?e.length:t,ta(e,d,i,i,i,i,t)}function Ls(e,t){var r;if("function"!=typeof t)throw new Pe(n);return e=Eo(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=i),r}}var xs=Zn((function(e,t,i){var n=1;if(i.length){var r=ui(i,pa(xs));n|=l}return ta(e,n,t,i,r)})),Fs=Zn((function(e,t,i){var n=3;if(i.length){var r=ui(i,pa(Fs));n|=l}return ta(t,n,e,i,r)}));function Us(e,t,r){var a,s,o,l,c,d,u=0,h=!1,p=!1,g=!0;if("function"!=typeof e)throw new Pe(n);function m(t){var n=a,r=s;return a=s=i,u=t,l=e.apply(r,n)}function f(e){var n=e-d;return d===i||n>=t||n<0||p&&e-u>=o}function v(){var e=Os();if(f(e))return S(e);c=Ua(v,function(e){var i=t-(e-d);return p?Kt(i,o-(e-u)):i}(e))}function S(e){return c=i,g&&a?m(e):(a=s=i,l)}function y(){var e=Os(),n=f(e);if(a=arguments,s=this,d=e,n){if(c===i)return function(e){return u=e,c=Ua(v,t),h?m(e):l}(d);if(p)return br(c),c=Ua(v,t),m(d)}return c===i&&(c=Ua(v,t)),l}return t=bo(t)||0,oo(r)&&(h=!!r.leading,o=(p="maxWait"in r)?Bt(bo(r.maxWait)||0,t):o,g="trailing"in r?!!r.trailing:g),y.cancel=function(){c!==i&&br(c),u=0,a=d=s=c=i},y.flush=function(){return c===i?l:S(Os())},y}var Bs=Zn((function(e,t){return dn(e,1,t)})),Vs=Zn((function(e,t,i){return dn(e,bo(t)||0,i)}));function Hs(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Pe(n);var i=function(){var n=arguments,r=t?t.apply(this,n):n[0],a=i.cache;if(a.has(r))return a.get(r);var s=e.apply(this,n);return i.cache=a.set(r,s)||a,s};return i.cache=new(Hs.Cache||Wi),i}function $s(e){if("function"!=typeof e)throw new Pe(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}Hs.Cache=Wi;var Gs=Er((function(e,t){var i=(t=1==t.length&&Qs(t[0])?Nt(t[0],Xt(ga())):Nt(Sn(t,1),Xt(ga()))).length;return Zn((function(n){for(var r=-1,a=Kt(n.length,i);++r<a;)n[r]=t[r].call(this,n[r]);return wt(e,this,n)}))})),js=Zn((function(e,t){var n=ui(t,pa(js));return ta(e,l,i,t,n)})),zs=Zn((function(e,t){var n=ui(t,pa(zs));return ta(e,c,i,t,n)})),Ws=la((function(e,t){return ta(e,u,i,i,i,t)}));function qs(e,t){return e===t||e!=e&&t!=t}var Ks=Yr(Rn),Js=Yr((function(e,t){return e>=t})),Ys=Dn(function(){return arguments}())?Dn:function(e){return lo(e)&&Le.call(e,"callee")&&!Ke.call(e,"callee")},Qs=se.isArray,Zs=Ct?Xt(Ct):function(e){return lo(e)&&wn(e)==O};function Xs(e){return null!=e&&so(e.length)&&!ro(e)}function eo(e){return lo(e)&&Xs(e)}var to=mt||bl,io=_t?Xt(_t):function(e){return lo(e)&&wn(e)==C};function no(e){if(!lo(e))return!1;var t=wn(e);return t==_||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ho(e)}function ro(e){if(!oo(e))return!1;var t=wn(e);return t==E||t==T||"[object AsyncFunction]"==t||"[object Proxy]"==t}function ao(e){return"number"==typeof e&&e==Eo(e)}function so(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=p}function oo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function lo(e){return null!=e&&"object"==typeof e}var co=Et?Xt(Et):function(e){return lo(e)&&Ca(e)==b};function uo(e){return"number"==typeof e||lo(e)&&wn(e)==I}function ho(e){if(!lo(e)||wn(e)!=w)return!1;var t=We(e);if(null===t)return!0;var i=Le.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Ne.call(i)==Be}var po=Tt?Xt(Tt):function(e){return lo(e)&&wn(e)==A};var go=bt?Xt(bt):function(e){return lo(e)&&Ca(e)==P};function mo(e){return"string"==typeof e||!Qs(e)&&lo(e)&&wn(e)==M}function fo(e){return"symbol"==typeof e||lo(e)&&wn(e)==k}var vo=It?Xt(It):function(e){return lo(e)&&so(e.length)&&!!ot[wn(e)]};var So=Yr(Bn),yo=Yr((function(e,t){return e<=t}));function Co(e){if(!e)return[];if(Xs(e))return mo(e)?gi(e):kr(e);if(Qe&&e[Qe])return function(e){for(var t,i=[];!(t=e.next()).done;)i.push(t.value);return i}(e[Qe]());var t=Ca(e);return(t==b?ci:t==P?hi:Ko)(e)}function _o(e){return e?(e=bo(e))===h||e===-h?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function Eo(e){var t=_o(e),i=t%1;return t==t?i?t-i:t:0}function To(e){return e?on(Eo(e),0,m):0}function bo(e){if("number"==typeof e)return e;if(fo(e))return g;if(oo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=oo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Zt(e);var i=fe.test(e);return i||Se.test(e)?ut(e.slice(2),i?2:8):me.test(e)?g:+e}function Io(e){return Dr(e,Vo(e))}function wo(e){return null==e?"":ur(e)}var Ro=Nr((function(e,t){if(Pa(t)||Xs(t))Dr(t,Bo(t),e);else for(var i in t)Le.call(t,i)&&en(e,i,t[i])})),Ao=Nr((function(e,t){Dr(t,Vo(t),e)})),Po=Nr((function(e,t,i,n){Dr(t,Vo(t),e,n)})),Mo=Nr((function(e,t,i,n){Dr(t,Bo(t),e,n)})),ko=la(sn);var Do=Zn((function(e,t){e=we(e);var n=-1,r=t.length,a=r>2?t[2]:i;for(a&&Ia(t[0],t[1],a)&&(r=1);++n<r;)for(var s=t[n],o=Vo(s),l=-1,c=o.length;++l<c;){var d=o[l],u=e[d];(u===i||qs(u,De[d])&&!Le.call(e,d))&&(e[d]=s[d])}return e})),Oo=Zn((function(e){return e.push(i,na),wt($o,i,e)}));function No(e,t,n){var r=null==e?i:bn(e,t);return r===i?n:r}function Lo(e,t){return null!=e&&_a(e,t,Pn)}var xo=jr((function(e,t,i){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),e[t]=i}),ll(ul)),Fo=jr((function(e,t,i){null!=t&&"function"!=typeof t.toString&&(t=Ue.call(t)),Le.call(e,t)?e[t].push(i):e[t]=[i]}),ga),Uo=Zn(kn);function Bo(e){return Xs(e)?Ji(e):Fn(e)}function Vo(e){return Xs(e)?Ji(e,!0):Un(e)}var Ho=Nr((function(e,t,i){Gn(e,t,i)})),$o=Nr((function(e,t,i,n){Gn(e,t,i,n)})),Go=la((function(e,t){var i={};if(null==e)return i;var n=!1;t=Nt(t,(function(t){return t=_r(t,e),n||(n=t.length>1),t})),Dr(e,da(e),i),n&&(i=ln(i,7,ra));for(var r=t.length;r--;)pr(i,t[r]);return i}));var jo=la((function(e,t){return null==e?{}:function(e,t){return Wn(e,t,(function(t,i){return Lo(e,i)}))}(e,t)}));function zo(e,t){if(null==e)return{};var i=Nt(da(e),(function(e){return[e]}));return t=ga(t),Wn(e,i,(function(e,i){return t(e,i[0])}))}var Wo=ea(Bo),qo=ea(Vo);function Ko(e){return null==e?[]:ei(e,Bo(e))}var Jo=Ur((function(e,t,i){return t=t.toLowerCase(),e+(i?Yo(t):t)}));function Yo(e){return rl(wo(e).toLowerCase())}function Qo(e){return(e=wo(e))&&e.replace(Ce,ri).replace(et,"")}var Zo=Ur((function(e,t,i){return e+(i?"-":"")+t.toLowerCase()})),Xo=Ur((function(e,t,i){return e+(i?" ":"")+t.toLowerCase()})),el=Fr("toLowerCase");var tl=Ur((function(e,t,i){return e+(i?"_":"")+t.toLowerCase()}));var il=Ur((function(e,t,i){return e+(i?" ":"")+rl(t)}));var nl=Ur((function(e,t,i){return e+(i?" ":"")+t.toUpperCase()})),rl=Fr("toUpperCase");function al(e,t,n){return e=wo(e),(t=n?i:t)===i?li(e)?vi(e):Vt(e):e.match(t)||[]}var sl=Zn((function(e,t){try{return wt(e,i,t)}catch(e){return no(e)?e:new Te(e)}})),ol=la((function(e,t){return At(t,(function(t){t=ja(t),an(e,t,xs(e[t],e))})),e}));function ll(e){return function(){return e}}var cl=$r(),dl=$r(!0);function ul(e){return e}function hl(e){return xn("function"==typeof e?e:ln(e,1))}var pl=Zn((function(e,t){return function(i){return kn(i,e,t)}})),gl=Zn((function(e,t){return function(i){return kn(e,i,t)}}));function ml(e,t,i){var n=Bo(t),r=Tn(t,n);null!=i||oo(t)&&(r.length||!n.length)||(i=t,t=e,e=this,r=Tn(t,Bo(t)));var a=!(oo(i)&&"chain"in i&&!i.chain),s=ro(e);return At(r,(function(i){var n=t[i];e[i]=n,s&&(e.prototype[i]=function(){var t=this.__chain__;if(a||t){var i=e(this.__wrapped__);return(i.__actions__=kr(this.__actions__)).push({func:n,args:arguments,thisArg:e}),i.__chain__=t,i}return n.apply(e,Lt([this.value()],arguments))})})),e}function fl(){}var vl=Wr(Nt),Sl=Wr(Mt),yl=Wr(Ut);function Cl(e){return wa(e)?qt(ja(e)):function(e){return function(t){return bn(t,e)}}(e)}var _l=Jr(),El=Jr(!0);function Tl(){return[]}function bl(){return!1}var Il=zr((function(e,t){return e+t}),0),wl=Zr("ceil"),Rl=zr((function(e,t){return e/t}),1),Al=Zr("floor");var Pl,Ml=zr((function(e,t){return e*t}),1),kl=Zr("round"),Dl=zr((function(e,t){return e-t}),0);return Bi.after=function(e,t){if("function"!=typeof t)throw new Pe(n);return e=Eo(e),function(){if(--e<1)return t.apply(this,arguments)}},Bi.ary=Ns,Bi.assign=Ro,Bi.assignIn=Ao,Bi.assignInWith=Po,Bi.assignWith=Mo,Bi.at=ko,Bi.before=Ls,Bi.bind=xs,Bi.bindAll=ol,Bi.bindKey=Fs,Bi.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Qs(e)?e:[e]},Bi.chain=ys,Bi.chunk=function(e,t,n){t=(n?Ia(e,t,n):t===i)?1:Bt(Eo(t),0);var r=null==e?0:e.length;if(!r||t<1)return[];for(var a=0,s=0,o=se(ct(r/t));a<r;)o[s++]=ar(e,a,a+=t);return o},Bi.compact=function(e){for(var t=-1,i=null==e?0:e.length,n=0,r=[];++t<i;){var a=e[t];a&&(r[n++]=a)}return r},Bi.concat=function(){var e=arguments.length;if(!e)return[];for(var t=se(e-1),i=arguments[0],n=e;n--;)t[n-1]=arguments[n];return Lt(Qs(i)?kr(i):[i],Sn(t,1))},Bi.cond=function(e){var t=null==e?0:e.length,i=ga();return e=t?Nt(e,(function(e){if("function"!=typeof e[1])throw new Pe(n);return[i(e[0]),e[1]]})):[],Zn((function(i){for(var n=-1;++n<t;){var r=e[n];if(wt(r[0],this,i))return wt(r[1],this,i)}}))},Bi.conforms=function(e){return function(e){var t=Bo(e);return function(i){return cn(i,e,t)}}(ln(e,1))},Bi.constant=ll,Bi.countBy=Es,Bi.create=function(e,t){var i=Vi(e);return null==t?i:rn(i,t)},Bi.curry=function e(t,n,r){var a=ta(t,8,i,i,i,i,i,n=r?i:n);return a.placeholder=e.placeholder,a},Bi.curryRight=function e(t,n,r){var a=ta(t,o,i,i,i,i,i,n=r?i:n);return a.placeholder=e.placeholder,a},Bi.debounce=Us,Bi.defaults=Do,Bi.defaultsDeep=Oo,Bi.defer=Bs,Bi.delay=Vs,Bi.difference=qa,Bi.differenceBy=Ka,Bi.differenceWith=Ja,Bi.drop=function(e,t,n){var r=null==e?0:e.length;return r?ar(e,(t=n||t===i?1:Eo(t))<0?0:t,r):[]},Bi.dropRight=function(e,t,n){var r=null==e?0:e.length;return r?ar(e,0,(t=r-(t=n||t===i?1:Eo(t)))<0?0:t):[]},Bi.dropRightWhile=function(e,t){return e&&e.length?mr(e,ga(t,3),!0,!0):[]},Bi.dropWhile=function(e,t){return e&&e.length?mr(e,ga(t,3),!0):[]},Bi.fill=function(e,t,i,n){var r=null==e?0:e.length;return r?(i&&"number"!=typeof i&&Ia(e,t,i)&&(i=0,n=r),fn(e,t,i,n)):[]},Bi.filter=function(e,t){return(Qs(e)?kt:vn)(e,ga(t,3))},Bi.flatMap=function(e,t){return Sn(Ms(e,t),1)},Bi.flatMapDeep=function(e,t){return Sn(Ms(e,t),h)},Bi.flatMapDepth=function(e,t,n){return n=n===i?1:Eo(n),Sn(Ms(e,t),n)},Bi.flatten=Za,Bi.flattenDeep=function(e){return null!=e&&e.length?Sn(e,h):[]},Bi.flattenDepth=function(e,t){return null!=e&&e.length?Sn(e,t=t===i?1:Eo(t)):[]},Bi.flip=function(e){return ta(e,512)},Bi.flow=cl,Bi.flowRight=dl,Bi.fromPairs=function(e){for(var t=-1,i=null==e?0:e.length,n={};++t<i;){var r=e[t];n[r[0]]=r[1]}return n},Bi.functions=function(e){return null==e?[]:Tn(e,Bo(e))},Bi.functionsIn=function(e){return null==e?[]:Tn(e,Vo(e))},Bi.groupBy=Rs,Bi.initial=function(e){return null!=e&&e.length?ar(e,0,-1):[]},Bi.intersection=es,Bi.intersectionBy=ts,Bi.intersectionWith=is,Bi.invert=xo,Bi.invertBy=Fo,Bi.invokeMap=As,Bi.iteratee=hl,Bi.keyBy=Ps,Bi.keys=Bo,Bi.keysIn=Vo,Bi.map=Ms,Bi.mapKeys=function(e,t){var i={};return t=ga(t,3),_n(e,(function(e,n,r){an(i,t(e,n,r),e)})),i},Bi.mapValues=function(e,t){var i={};return t=ga(t,3),_n(e,(function(e,n,r){an(i,n,t(e,n,r))})),i},Bi.matches=function(e){return Hn(ln(e,1))},Bi.matchesProperty=function(e,t){return $n(e,ln(t,1))},Bi.memoize=Hs,Bi.merge=Ho,Bi.mergeWith=$o,Bi.method=pl,Bi.methodOf=gl,Bi.mixin=ml,Bi.negate=$s,Bi.nthArg=function(e){return e=Eo(e),Zn((function(t){return jn(t,e)}))},Bi.omit=Go,Bi.omitBy=function(e,t){return zo(e,$s(ga(t)))},Bi.once=function(e){return Ls(2,e)},Bi.orderBy=function(e,t,n,r){return null==e?[]:(Qs(t)||(t=null==t?[]:[t]),Qs(n=r?i:n)||(n=null==n?[]:[n]),zn(e,t,n))},Bi.over=vl,Bi.overArgs=Gs,Bi.overEvery=Sl,Bi.overSome=yl,Bi.partial=js,Bi.partialRight=zs,Bi.partition=ks,Bi.pick=jo,Bi.pickBy=zo,Bi.property=Cl,Bi.propertyOf=function(e){return function(t){return null==e?i:bn(e,t)}},Bi.pull=rs,Bi.pullAll=as,Bi.pullAllBy=function(e,t,i){return e&&e.length&&t&&t.length?qn(e,t,ga(i,2)):e},Bi.pullAllWith=function(e,t,n){return e&&e.length&&t&&t.length?qn(e,t,i,n):e},Bi.pullAt=ss,Bi.range=_l,Bi.rangeRight=El,Bi.rearg=Ws,Bi.reject=function(e,t){return(Qs(e)?kt:vn)(e,$s(ga(t,3)))},Bi.remove=function(e,t){var i=[];if(!e||!e.length)return i;var n=-1,r=[],a=e.length;for(t=ga(t,3);++n<a;){var s=e[n];t(s,n,e)&&(i.push(s),r.push(n))}return Kn(e,r),i},Bi.rest=function(e,t){if("function"!=typeof e)throw new Pe(n);return Zn(e,t=t===i?t:Eo(t))},Bi.reverse=os,Bi.sampleSize=function(e,t,n){return t=(n?Ia(e,t,n):t===i)?1:Eo(t),(Qs(e)?Qi:er)(e,t)},Bi.set=function(e,t,i){return null==e?e:tr(e,t,i)},Bi.setWith=function(e,t,n,r){return r="function"==typeof r?r:i,null==e?e:tr(e,t,n,r)},Bi.shuffle=function(e){return(Qs(e)?Zi:rr)(e)},Bi.slice=function(e,t,n){var r=null==e?0:e.length;return r?(n&&"number"!=typeof n&&Ia(e,t,n)?(t=0,n=r):(t=null==t?0:Eo(t),n=n===i?r:Eo(n)),ar(e,t,n)):[]},Bi.sortBy=Ds,Bi.sortedUniq=function(e){return e&&e.length?cr(e):[]},Bi.sortedUniqBy=function(e,t){return e&&e.length?cr(e,ga(t,2)):[]},Bi.split=function(e,t,n){return n&&"number"!=typeof n&&Ia(e,t,n)&&(t=n=i),(n=n===i?m:n>>>0)?(e=wo(e))&&("string"==typeof t||null!=t&&!po(t))&&!(t=ur(t))&&oi(e)?Tr(gi(e),0,n):e.split(t,n):[]},Bi.spread=function(e,t){if("function"!=typeof e)throw new Pe(n);return t=null==t?0:Bt(Eo(t),0),Zn((function(i){var n=i[t],r=Tr(i,0,t);return n&&Lt(r,n),wt(e,this,r)}))},Bi.tail=function(e){var t=null==e?0:e.length;return t?ar(e,1,t):[]},Bi.take=function(e,t,n){return e&&e.length?ar(e,0,(t=n||t===i?1:Eo(t))<0?0:t):[]},Bi.takeRight=function(e,t,n){var r=null==e?0:e.length;return r?ar(e,(t=r-(t=n||t===i?1:Eo(t)))<0?0:t,r):[]},Bi.takeRightWhile=function(e,t){return e&&e.length?mr(e,ga(t,3),!1,!0):[]},Bi.takeWhile=function(e,t){return e&&e.length?mr(e,ga(t,3)):[]},Bi.tap=function(e,t){return t(e),e},Bi.throttle=function(e,t,i){var r=!0,a=!0;if("function"!=typeof e)throw new Pe(n);return oo(i)&&(r="leading"in i?!!i.leading:r,a="trailing"in i?!!i.trailing:a),Us(e,t,{leading:r,maxWait:t,trailing:a})},Bi.thru=Cs,Bi.toArray=Co,Bi.toPairs=Wo,Bi.toPairsIn=qo,Bi.toPath=function(e){return Qs(e)?Nt(e,ja):fo(e)?[e]:kr(Ga(wo(e)))},Bi.toPlainObject=Io,Bi.transform=function(e,t,i){var n=Qs(e),r=n||to(e)||vo(e);if(t=ga(t,4),null==i){var a=e&&e.constructor;i=r?n?new a:[]:oo(e)&&ro(a)?Vi(We(e)):{}}return(r?At:_n)(e,(function(e,n,r){return t(i,e,n,r)})),i},Bi.unary=function(e){return Ns(e,1)},Bi.union=ls,Bi.unionBy=cs,Bi.unionWith=ds,Bi.uniq=function(e){return e&&e.length?hr(e):[]},Bi.uniqBy=function(e,t){return e&&e.length?hr(e,ga(t,2)):[]},Bi.uniqWith=function(e,t){return t="function"==typeof t?t:i,e&&e.length?hr(e,i,t):[]},Bi.unset=function(e,t){return null==e||pr(e,t)},Bi.unzip=us,Bi.unzipWith=hs,Bi.update=function(e,t,i){return null==e?e:gr(e,t,Cr(i))},Bi.updateWith=function(e,t,n,r){return r="function"==typeof r?r:i,null==e?e:gr(e,t,Cr(n),r)},Bi.values=Ko,Bi.valuesIn=function(e){return null==e?[]:ei(e,Vo(e))},Bi.without=ps,Bi.words=al,Bi.wrap=function(e,t){return js(Cr(t),e)},Bi.xor=gs,Bi.xorBy=ms,Bi.xorWith=fs,Bi.zip=vs,Bi.zipObject=function(e,t){return Sr(e||[],t||[],en)},Bi.zipObjectDeep=function(e,t){return Sr(e||[],t||[],tr)},Bi.zipWith=Ss,Bi.entries=Wo,Bi.entriesIn=qo,Bi.extend=Ao,Bi.extendWith=Po,ml(Bi,Bi),Bi.add=Il,Bi.attempt=sl,Bi.camelCase=Jo,Bi.capitalize=Yo,Bi.ceil=wl,Bi.clamp=function(e,t,n){return n===i&&(n=t,t=i),n!==i&&(n=(n=bo(n))==n?n:0),t!==i&&(t=(t=bo(t))==t?t:0),on(bo(e),t,n)},Bi.clone=function(e){return ln(e,4)},Bi.cloneDeep=function(e){return ln(e,5)},Bi.cloneDeepWith=function(e,t){return ln(e,5,t="function"==typeof t?t:i)},Bi.cloneWith=function(e,t){return ln(e,4,t="function"==typeof t?t:i)},Bi.conformsTo=function(e,t){return null==t||cn(e,t,Bo(t))},Bi.deburr=Qo,Bi.defaultTo=function(e,t){return null==e||e!=e?t:e},Bi.divide=Rl,Bi.endsWith=function(e,t,n){e=wo(e),t=ur(t);var r=e.length,a=n=n===i?r:on(Eo(n),0,r);return(n-=t.length)>=0&&e.slice(n,a)==t},Bi.eq=qs,Bi.escape=function(e){return(e=wo(e))&&Y.test(e)?e.replace(K,ai):e},Bi.escapeRegExp=function(e){return(e=wo(e))&&re.test(e)?e.replace(ne,"\\$&"):e},Bi.every=function(e,t,n){var r=Qs(e)?Mt:gn;return n&&Ia(e,t,n)&&(t=i),r(e,ga(t,3))},Bi.find=Ts,Bi.findIndex=Ya,Bi.findKey=function(e,t){return Ht(e,ga(t,3),_n)},Bi.findLast=bs,Bi.findLastIndex=Qa,Bi.findLastKey=function(e,t){return Ht(e,ga(t,3),En)},Bi.floor=Al,Bi.forEach=Is,Bi.forEachRight=ws,Bi.forIn=function(e,t){return null==e?e:yn(e,ga(t,3),Vo)},Bi.forInRight=function(e,t){return null==e?e:Cn(e,ga(t,3),Vo)},Bi.forOwn=function(e,t){return e&&_n(e,ga(t,3))},Bi.forOwnRight=function(e,t){return e&&En(e,ga(t,3))},Bi.get=No,Bi.gt=Ks,Bi.gte=Js,Bi.has=function(e,t){return null!=e&&_a(e,t,An)},Bi.hasIn=Lo,Bi.head=Xa,Bi.identity=ul,Bi.includes=function(e,t,i,n){e=Xs(e)?e:Ko(e),i=i&&!n?Eo(i):0;var r=e.length;return i<0&&(i=Bt(r+i,0)),mo(e)?i<=r&&e.indexOf(t,i)>-1:!!r&&Gt(e,t,i)>-1},Bi.indexOf=function(e,t,i){var n=null==e?0:e.length;if(!n)return-1;var r=null==i?0:Eo(i);return r<0&&(r=Bt(n+r,0)),Gt(e,t,r)},Bi.inRange=function(e,t,n){return t=_o(t),n===i?(n=t,t=0):n=_o(n),function(e,t,i){return e>=Kt(t,i)&&e<Bt(t,i)}(e=bo(e),t,n)},Bi.invoke=Uo,Bi.isArguments=Ys,Bi.isArray=Qs,Bi.isArrayBuffer=Zs,Bi.isArrayLike=Xs,Bi.isArrayLikeObject=eo,Bi.isBoolean=function(e){return!0===e||!1===e||lo(e)&&wn(e)==y},Bi.isBuffer=to,Bi.isDate=io,Bi.isElement=function(e){return lo(e)&&1===e.nodeType&&!ho(e)},Bi.isEmpty=function(e){if(null==e)return!0;if(Xs(e)&&(Qs(e)||"string"==typeof e||"function"==typeof e.splice||to(e)||vo(e)||Ys(e)))return!e.length;var t=Ca(e);if(t==b||t==P)return!e.size;if(Pa(e))return!Fn(e).length;for(var i in e)if(Le.call(e,i))return!1;return!0},Bi.isEqual=function(e,t){return On(e,t)},Bi.isEqualWith=function(e,t,n){var r=(n="function"==typeof n?n:i)?n(e,t):i;return r===i?On(e,t,i,n):!!r},Bi.isError=no,Bi.isFinite=function(e){return"number"==typeof e&&ft(e)},Bi.isFunction=ro,Bi.isInteger=ao,Bi.isLength=so,Bi.isMap=co,Bi.isMatch=function(e,t){return e===t||Nn(e,t,fa(t))},Bi.isMatchWith=function(e,t,n){return n="function"==typeof n?n:i,Nn(e,t,fa(t),n)},Bi.isNaN=function(e){return uo(e)&&e!=+e},Bi.isNative=function(e){if(Aa(e))throw new Te("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Ln(e)},Bi.isNil=function(e){return null==e},Bi.isNull=function(e){return null===e},Bi.isNumber=uo,Bi.isObject=oo,Bi.isObjectLike=lo,Bi.isPlainObject=ho,Bi.isRegExp=po,Bi.isSafeInteger=function(e){return ao(e)&&e>=-p&&e<=p},Bi.isSet=go,Bi.isString=mo,Bi.isSymbol=fo,Bi.isTypedArray=vo,Bi.isUndefined=function(e){return e===i},Bi.isWeakMap=function(e){return lo(e)&&Ca(e)==D},Bi.isWeakSet=function(e){return lo(e)&&"[object WeakSet]"==wn(e)},Bi.join=function(e,t){return null==e?"":St.call(e,t)},Bi.kebabCase=Zo,Bi.last=ns,Bi.lastIndexOf=function(e,t,n){var r=null==e?0:e.length;if(!r)return-1;var a=r;return n!==i&&(a=(a=Eo(n))<0?Bt(r+a,0):Kt(a,r-1)),t==t?function(e,t,i){for(var n=i+1;n--;)if(e[n]===t)return n;return n}(e,t,a):$t(e,zt,a,!0)},Bi.lowerCase=Xo,Bi.lowerFirst=el,Bi.lt=So,Bi.lte=yo,Bi.max=function(e){return e&&e.length?mn(e,ul,Rn):i},Bi.maxBy=function(e,t){return e&&e.length?mn(e,ga(t,2),Rn):i},Bi.mean=function(e){return Wt(e,ul)},Bi.meanBy=function(e,t){return Wt(e,ga(t,2))},Bi.min=function(e){return e&&e.length?mn(e,ul,Bn):i},Bi.minBy=function(e,t){return e&&e.length?mn(e,ga(t,2),Bn):i},Bi.stubArray=Tl,Bi.stubFalse=bl,Bi.stubObject=function(){return{}},Bi.stubString=function(){return""},Bi.stubTrue=function(){return!0},Bi.multiply=Ml,Bi.nth=function(e,t){return e&&e.length?jn(e,Eo(t)):i},Bi.noConflict=function(){return gt._===this&&(gt._=Ve),this},Bi.noop=fl,Bi.now=Os,Bi.pad=function(e,t,i){e=wo(e);var n=(t=Eo(t))?pi(e):0;if(!t||n>=t)return e;var r=(t-n)/2;return qr(ht(r),i)+e+qr(ct(r),i)},Bi.padEnd=function(e,t,i){e=wo(e);var n=(t=Eo(t))?pi(e):0;return t&&n<t?e+qr(t-n,i):e},Bi.padStart=function(e,t,i){e=wo(e);var n=(t=Eo(t))?pi(e):0;return t&&n<t?qr(t-n,i)+e:e},Bi.parseInt=function(e,t,i){return i||null==t?t=0:t&&(t=+t),Ci(wo(e).replace(ae,""),t||0)},Bi.random=function(e,t,n){if(n&&"boolean"!=typeof n&&Ia(e,t,n)&&(t=n=i),n===i&&("boolean"==typeof t?(n=t,t=i):"boolean"==typeof e&&(n=e,e=i)),e===i&&t===i?(e=0,t=1):(e=_o(e),t===i?(t=e,e=0):t=_o(t)),e>t){var r=e;e=t,t=r}if(n||e%1||t%1){var a=_i();return Kt(e+a*(t-e+dt("1e-"+((a+"").length-1))),t)}return Jn(e,t)},Bi.reduce=function(e,t,i){var n=Qs(e)?xt:Jt,r=arguments.length<3;return n(e,ga(t,4),i,r,hn)},Bi.reduceRight=function(e,t,i){var n=Qs(e)?Ft:Jt,r=arguments.length<3;return n(e,ga(t,4),i,r,pn)},Bi.repeat=function(e,t,n){return t=(n?Ia(e,t,n):t===i)?1:Eo(t),Qn(wo(e),t)},Bi.replace=function(){var e=arguments,t=wo(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Bi.result=function(e,t,n){var r=-1,a=(t=_r(t,e)).length;for(a||(a=1,e=i);++r<a;){var s=null==e?i:e[ja(t[r])];s===i&&(r=a,s=n),e=ro(s)?s.call(e):s}return e},Bi.round=kl,Bi.runInContext=e,Bi.sample=function(e){return(Qs(e)?Yi:Xn)(e)},Bi.size=function(e){if(null==e)return 0;if(Xs(e))return mo(e)?pi(e):e.length;var t=Ca(e);return t==b||t==P?e.size:Fn(e).length},Bi.snakeCase=tl,Bi.some=function(e,t,n){var r=Qs(e)?Ut:sr;return n&&Ia(e,t,n)&&(t=i),r(e,ga(t,3))},Bi.sortedIndex=function(e,t){return or(e,t)},Bi.sortedIndexBy=function(e,t,i){return lr(e,t,ga(i,2))},Bi.sortedIndexOf=function(e,t){var i=null==e?0:e.length;if(i){var n=or(e,t);if(n<i&&qs(e[n],t))return n}return-1},Bi.sortedLastIndex=function(e,t){return or(e,t,!0)},Bi.sortedLastIndexBy=function(e,t,i){return lr(e,t,ga(i,2),!0)},Bi.sortedLastIndexOf=function(e,t){if(null!=e&&e.length){var i=or(e,t,!0)-1;if(qs(e[i],t))return i}return-1},Bi.startCase=il,Bi.startsWith=function(e,t,i){return e=wo(e),i=null==i?0:on(Eo(i),0,e.length),t=ur(t),e.slice(i,i+t.length)==t},Bi.subtract=Dl,Bi.sum=function(e){return e&&e.length?Yt(e,ul):0},Bi.sumBy=function(e,t){return e&&e.length?Yt(e,ga(t,2)):0},Bi.template=function(e,t,n){var r=Bi.templateSettings;n&&Ia(e,t,n)&&(t=i),e=wo(e),t=Po({},t,r,ia);var a,s,o=Po({},t.imports,r.imports,ia),l=Bo(o),c=ei(o,l),d=0,u=t.interpolate||_e,h="__p += '",p=Re((t.escape||_e).source+"|"+u.source+"|"+(u===X?pe:_e).source+"|"+(t.evaluate||_e).source+"|$","g"),g="//# sourceURL="+(Le.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++st+"]")+"\n";e.replace(p,(function(t,i,n,r,o,l){return n||(n=r),h+=e.slice(d,l).replace(Ee,si),i&&(a=!0,h+="' +\n__e("+i+") +\n'"),o&&(s=!0,h+="';\n"+o+";\n__p += '"),n&&(h+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),d=l+t.length,t})),h+="';\n";var m=Le.call(t,"variable")&&t.variable;if(m){if(ue.test(m))throw new Te("Invalid `variable` option passed into `_.template`")}else h="with (obj) {\n"+h+"\n}\n";h=(s?h.replace(j,""):h).replace(z,"$1").replace(W,"$1;"),h="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(a?", __e = _.escape":"")+(s?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var f=sl((function(){return be(l,g+"return "+h).apply(i,c)}));if(f.source=h,no(f))throw f;return f},Bi.times=function(e,t){if((e=Eo(e))<1||e>p)return[];var i=m,n=Kt(e,m);t=ga(t),e-=m;for(var r=Qt(n,t);++i<e;)t(i);return r},Bi.toFinite=_o,Bi.toInteger=Eo,Bi.toLength=To,Bi.toLower=function(e){return wo(e).toLowerCase()},Bi.toNumber=bo,Bi.toSafeInteger=function(e){return e?on(Eo(e),-p,p):0===e?e:0},Bi.toString=wo,Bi.toUpper=function(e){return wo(e).toUpperCase()},Bi.trim=function(e,t,n){if((e=wo(e))&&(n||t===i))return Zt(e);if(!e||!(t=ur(t)))return e;var r=gi(e),a=gi(t);return Tr(r,ii(r,a),ni(r,a)+1).join("")},Bi.trimEnd=function(e,t,n){if((e=wo(e))&&(n||t===i))return e.slice(0,mi(e)+1);if(!e||!(t=ur(t)))return e;var r=gi(e);return Tr(r,0,ni(r,gi(t))+1).join("")},Bi.trimStart=function(e,t,n){if((e=wo(e))&&(n||t===i))return e.replace(ae,"");if(!e||!(t=ur(t)))return e;var r=gi(e);return Tr(r,ii(r,gi(t))).join("")},Bi.truncate=function(e,t){var n=30,r="...";if(oo(t)){var a="separator"in t?t.separator:a;n="length"in t?Eo(t.length):n,r="omission"in t?ur(t.omission):r}var s=(e=wo(e)).length;if(oi(e)){var o=gi(e);s=o.length}if(n>=s)return e;var l=n-pi(r);if(l<1)return r;var c=o?Tr(o,0,l).join(""):e.slice(0,l);if(a===i)return c+r;if(o&&(l+=c.length-l),po(a)){if(e.slice(l).search(a)){var d,u=c;for(a.global||(a=Re(a.source,wo(ge.exec(a))+"g")),a.lastIndex=0;d=a.exec(u);)var h=d.index;c=c.slice(0,h===i?l:h)}}else if(e.indexOf(ur(a),l)!=l){var p=c.lastIndexOf(a);p>-1&&(c=c.slice(0,p))}return c+r},Bi.unescape=function(e){return(e=wo(e))&&J.test(e)?e.replace(q,fi):e},Bi.uniqueId=function(e){var t=++xe;return wo(e)+t},Bi.upperCase=nl,Bi.upperFirst=rl,Bi.each=Is,Bi.eachRight=ws,Bi.first=Xa,ml(Bi,(Pl={},_n(Bi,(function(e,t){Le.call(Bi.prototype,t)||(Pl[t]=e)})),Pl),{chain:!1}),Bi.VERSION="4.17.21",At(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Bi[e].placeholder=Bi})),At(["drop","take"],(function(e,t){Gi.prototype[e]=function(n){n=n===i?1:Bt(Eo(n),0);var r=this.__filtered__&&!t?new Gi(this):this.clone();return r.__filtered__?r.__takeCount__=Kt(n,r.__takeCount__):r.__views__.push({size:Kt(n,m),type:e+(r.__dir__<0?"Right":"")}),r},Gi.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),At(["filter","map","takeWhile"],(function(e,t){var i=t+1,n=1==i||3==i;Gi.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:ga(e,3),type:i}),t.__filtered__=t.__filtered__||n,t}})),At(["head","last"],(function(e,t){var i="take"+(t?"Right":"");Gi.prototype[e]=function(){return this[i](1).value()[0]}})),At(["initial","tail"],(function(e,t){var i="drop"+(t?"":"Right");Gi.prototype[e]=function(){return this.__filtered__?new Gi(this):this[i](1)}})),Gi.prototype.compact=function(){return this.filter(ul)},Gi.prototype.find=function(e){return this.filter(e).head()},Gi.prototype.findLast=function(e){return this.reverse().find(e)},Gi.prototype.invokeMap=Zn((function(e,t){return"function"==typeof e?new Gi(this):this.map((function(i){return kn(i,e,t)}))})),Gi.prototype.reject=function(e){return this.filter($s(ga(e)))},Gi.prototype.slice=function(e,t){e=Eo(e);var n=this;return n.__filtered__&&(e>0||t<0)?new Gi(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),t!==i&&(n=(t=Eo(t))<0?n.dropRight(-t):n.take(t-e)),n)},Gi.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Gi.prototype.toArray=function(){return this.take(m)},_n(Gi.prototype,(function(e,t){var n=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),a=Bi[r?"take"+("last"==t?"Right":""):t],s=r||/^find/.test(t);a&&(Bi.prototype[t]=function(){var t=this.__wrapped__,o=r?[1]:arguments,l=t instanceof Gi,c=o[0],d=l||Qs(t),u=function(e){var t=a.apply(Bi,Lt([e],o));return r&&h?t[0]:t};d&&n&&"function"==typeof c&&1!=c.length&&(l=d=!1);var h=this.__chain__,p=!!this.__actions__.length,g=s&&!h,m=l&&!p;if(!s&&d){t=m?t:new Gi(this);var f=e.apply(t,o);return f.__actions__.push({func:Cs,args:[u],thisArg:i}),new $i(f,h)}return g&&m?e.apply(this,o):(f=this.thru(u),g?r?f.value()[0]:f.value():f)})})),At(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Me[e],i=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",n=/^(?:pop|shift)$/.test(e);Bi.prototype[e]=function(){var e=arguments;if(n&&!this.__chain__){var r=this.value();return t.apply(Qs(r)?r:[],e)}return this[i]((function(i){return t.apply(Qs(i)?i:[],e)}))}})),_n(Gi.prototype,(function(e,t){var i=Bi[t];if(i){var n=i.name+"";Le.call(Mi,n)||(Mi[n]=[]),Mi[n].push({name:t,func:i})}})),Mi[Gr(i,2).name]=[{name:"wrapper",func:i}],Gi.prototype.clone=function(){var e=new Gi(this.__wrapped__);return e.__actions__=kr(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=kr(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=kr(this.__views__),e},Gi.prototype.reverse=function(){if(this.__filtered__){var e=new Gi(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Gi.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,i=Qs(e),n=t<0,r=i?e.length:0,a=function(e,t,i){for(var n=-1,r=i.length;++n<r;){var a=i[n],s=a.size;switch(a.type){case"drop":e+=s;break;case"dropRight":t-=s;break;case"take":t=Kt(t,e+s);break;case"takeRight":e=Bt(e,t-s)}}return{start:e,end:t}}(0,r,this.__views__),s=a.start,o=a.end,l=o-s,c=n?o:s-1,d=this.__iteratees__,u=d.length,h=0,p=Kt(l,this.__takeCount__);if(!i||!n&&r==l&&p==l)return fr(e,this.__actions__);var g=[];e:for(;l--&&h<p;){for(var m=-1,f=e[c+=t];++m<u;){var v=d[m],S=v.iteratee,y=v.type,C=S(f);if(2==y)f=C;else if(!C){if(1==y)continue e;break e}}g[h++]=f}return g},Bi.prototype.at=_s,Bi.prototype.chain=function(){return ys(this)},Bi.prototype.commit=function(){return new $i(this.value(),this.__chain__)},Bi.prototype.next=function(){this.__values__===i&&(this.__values__=Co(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?i:this.__values__[this.__index__++]}},Bi.prototype.plant=function(e){for(var t,n=this;n instanceof Hi;){var r=Wa(n);r.__index__=0,r.__values__=i,t?a.__wrapped__=r:t=r;var a=r;n=n.__wrapped__}return a.__wrapped__=e,t},Bi.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Gi){var t=e;return this.__actions__.length&&(t=new Gi(this)),(t=t.reverse()).__actions__.push({func:Cs,args:[os],thisArg:i}),new $i(t,this.__chain__)}return this.thru(os)},Bi.prototype.toJSON=Bi.prototype.valueOf=Bi.prototype.value=function(){return fr(this.__wrapped__,this.__actions__)},Bi.prototype.first=Bi.prototype.head,Qe&&(Bi.prototype[Qe]=function(){return this}),Bi}();ft?((ft.exports=Si)._=Si,mt._=Si):gt._=Si}).call(a)})),m=s((function(e,t){var i=window;!function(t,i){e.exports=i()}(0,((e,t)=>{var n={},r={exports:n},a=Object.create,s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,c=Object.getPrototypeOf,d=Object.prototype.hasOwnProperty,u=(e,t)=>function(){return t||(0,e[l(e)[0]])((t={exports:{}}).exports,t),t.exports},h=(e,t)=>{for(var i in t)s(e,i,{get:t[i],enumerable:!0})},m=(e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of l(t))d.call(e,r)||r===i||s(e,r,{get:()=>t[r],enumerable:!(n=o(t,r))||n.enumerable});return e},f=(e,t,i)=>(i=null!=e?a(c(e)):{},m(!t&&e&&e.__esModule?i:s(i,"default",{value:e,enumerable:!0}),e)),v=(e,t,i,n)=>{for(var r,a=n>1?void 0:n?o(t,i):t,l=e.length-1;l>=0;l--)(r=e[l])&&(a=(n?r(t,i,a):r(a))||a);return n&&a&&s(t,i,a),a},S=(e,t)=>(i,n)=>t(i,n,e),y=u({"../node_modules/axios/lib/helpers/bind.js"(e,t){t.exports=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}}}}),C=u({"../node_modules/axios/lib/utils.js"(e,t){var i=y(),n=Object.prototype.toString;function r(e){return"[object Array]"===n.call(e)}function a(e){return void 0===e}function s(e){return null!==e&&"object"==typeof e}function o(e){return"[object Function]"===n.call(e)}function l(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),r(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.call(null,e[a],a,e)}t.exports={isArray:r,isArrayBuffer:function(e){return"[object ArrayBuffer]"===n.call(e)},isBuffer:function(e){return null!==e&&!a(e)&&null!==e.constructor&&!a(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:s,isUndefined:a,isDate:function(e){return"[object Date]"===n.call(e)},isFile:function(e){return"[object File]"===n.call(e)},isBlob:function(e){return"[object Blob]"===n.call(e)},isFunction:o,isStream:function(e){return s(e)&&o(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:l,merge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]=i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},deepMerge:function e(){var t={};function i(i,n){"object"==typeof t[n]&&"object"==typeof i?t[n]=e(t[n],i):t[n]="object"==typeof i?e({},i):i}for(var n=0,r=arguments.length;n<r;n++)l(arguments[n],i);return t},extend:function(e,t,n){return l(t,(function(t,r){e[r]=n&&"function"==typeof t?i(t,n):t})),e},trim:function(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}}}}),_=u({"../node_modules/axios/lib/helpers/buildURL.js"(e,t){var i=C();function n(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(e,t,r){if(!t)return e;var a;if(r)a=r(t);else if(i.isURLSearchParams(t))a=t.toString();else{var s=[];i.forEach(t,(function(e,t){null!=e&&(i.isArray(e)?t+="[]":e=[e],i.forEach(e,(function(e){i.isDate(e)?e=e.toISOString():i.isObject(e)&&(e=JSON.stringify(e)),s.push(n(t)+"="+n(e))})))})),a=s.join("&")}if(a){var o=e.indexOf("#");-1!==o&&(e=e.slice(0,o)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}}}),E=u({"../node_modules/axios/lib/core/InterceptorManager.js"(e,t){var i=C();function n(){this.handlers=[]}n.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},n.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},n.prototype.forEach=function(e){i.forEach(this.handlers,(function(t){null!==t&&e(t)}))},t.exports=n}}),T=u({"../node_modules/axios/lib/core/transformData.js"(e,t){var i=C();t.exports=function(e,t,n){return i.forEach(n,(function(i){e=i(e,t)})),e}}}),b=u({"../node_modules/axios/lib/cancel/isCancel.js"(e,t){t.exports=function(e){return!(!e||!e.__CANCEL__)}}}),I=u({"../node_modules/axios/lib/helpers/normalizeHeaderName.js"(e,t){var i=C();t.exports=function(e,t){i.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))}}}),w=u({"../node_modules/axios/lib/core/enhanceError.js"(e,t){t.exports=function(e,t,i,n,r){return e.config=t,i&&(e.code=i),e.request=n,e.response=r,e.isAxiosError=!0,e.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:this.config,code:this.code}},e}}}),R=u({"../node_modules/axios/lib/core/createError.js"(e,t){var i=w();t.exports=function(e,t,n,r,a){var s=new Error(e);return i(s,t,n,r,a)}}}),A=u({"../node_modules/axios/lib/core/settle.js"(e,t){var i=R();t.exports=function(e,t,n){var r=n.config.validateStatus;!r||r(n.status)?e(n):t(i("Request failed with status code "+n.status,n.config,null,n.request,n))}}}),P=u({"../node_modules/axios/lib/helpers/isAbsoluteURL.js"(e,t){t.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}}}),M=u({"../node_modules/axios/lib/helpers/combineURLs.js"(e,t){t.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}}}),k=u({"../node_modules/axios/lib/core/buildFullPath.js"(e,t){var i=P(),n=M();t.exports=function(e,t){return e&&!i(t)?n(e,t):t}}}),D=u({"../node_modules/axios/lib/helpers/parseHeaders.js"(e,t){var i=C(),n=["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"];t.exports=function(e){var t,r,a,s={};return e?(i.forEach(e.split("\n"),(function(e){if(a=e.indexOf(":"),t=i.trim(e.substr(0,a)).toLowerCase(),r=i.trim(e.substr(a+1)),t){if(s[t]&&n.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s}}}),O=u({"../node_modules/axios/lib/helpers/isValidXss.js"(e,t){t.exports=function(e){return/(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi.test(e)}}}),N=u({"../node_modules/axios/lib/helpers/isURLSameOrigin.js"(e,t){var i=C(),n=O();t.exports=i.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function a(e){var i=e;if(n(e))throw new Error("URL contains XSS injection attempt");return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=a(window.location.href),function(t){var n=i.isString(t)?a(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}}}),L=u({"../node_modules/axios/lib/helpers/cookies.js"(e,t){var i=C();t.exports=i.isStandardBrowserEnv()?{write:function(e,t,n,r,a,s){var o=[];o.push(e+"="+encodeURIComponent(t)),i.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),i.isString(r)&&o.push("path="+r),i.isString(a)&&o.push("domain="+a),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}}),x=u({"../node_modules/axios/lib/adapters/xhr.js"(e,t){var i=C(),n=A(),r=_(),a=k(),s=D(),o=N(),l=R();t.exports=function(e){return new Promise((function(t,c){var d=e.data,u=e.headers;i.isFormData(d)&&delete u["Content-Type"];var h=new XMLHttpRequest;if(e.auth){var p=e.auth.username||"",g=e.auth.password||"";u.Authorization="Basic "+btoa(p+":"+g)}var m=a(e.baseURL,e.url);if(h.open(e.method.toUpperCase(),r(m,e.params,e.paramsSerializer),!0),h.timeout=e.timeout,h.onreadystatechange=function(){if(h&&4===h.readyState&&(0!==h.status||h.responseURL&&0===h.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in h?s(h.getAllResponseHeaders()):null,r={data:e.responseType&&"text"!==e.responseType?h.response:h.responseText,status:h.status,statusText:h.statusText,headers:i,config:e,request:h};n(t,c,r),h=null}},h.onabort=function(){h&&(c(l("Request aborted",e,"ECONNABORTED",h)),h=null)},h.onerror=function(){c(l("Network Error",e,null,h)),h=null},h.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),c(l(t,e,"ECONNABORTED",h)),h=null},i.isStandardBrowserEnv()){var f=L(),v=(e.withCredentials||o(m))&&e.xsrfCookieName?f.read(e.xsrfCookieName):void 0;v&&(u[e.xsrfHeaderName]=v)}if("setRequestHeader"in h&&i.forEach(u,(function(e,t){void 0===d&&"content-type"===t.toLowerCase()?delete u[t]:h.setRequestHeader(t,e)})),i.isUndefined(e.withCredentials)||(h.withCredentials=!!e.withCredentials),e.responseType)try{h.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&h.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&h.upload&&h.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){h&&(h.abort(),c(e),h=null)})),void 0===d&&(d=null),h.send(d)}))}}}),F=u({"../node_modules/axios/lib/defaults.js"(e,t){var i=C(),n=I(),r={"Content-Type":"application/x-www-form-urlencoded"};function a(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var s={adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=x()),e}(),transformRequest:[function(e,t){return n(t,"Accept"),n(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(a(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(a(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};i.forEach(["delete","get","head"],(function(e){s.headers[e]={}})),i.forEach(["post","put","patch"],(function(e){s.headers[e]=i.merge(r)})),t.exports=s}}),U=u({"../node_modules/axios/lib/core/dispatchRequest.js"(e,t){var i=C(),n=T(),r=b(),a=F();function s(e){e.cancelToken&&e.cancelToken.throwIfRequested()}t.exports=function(e){return s(e),e.headers=e.headers||{},e.data=n(e.data,e.headers,e.transformRequest),e.headers=i.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),i.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||a.adapter)(e).then((function(t){return s(e),t.data=n(t.data,t.headers,e.transformResponse),t}),(function(t){return r(t)||(s(e),t&&t.response&&(t.response.data=n(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))}}}),B=u({"../node_modules/axios/lib/core/mergeConfig.js"(e,t){var i=C();t.exports=function(e,t){t=t||{};var n={},r=["url","method","params","data"],a=["headers","auth","proxy"],s=["baseURL","url","transformRequest","transformResponse","paramsSerializer","timeout","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","maxContentLength","validateStatus","maxRedirects","httpAgent","httpsAgent","cancelToken","socketPath"];i.forEach(r,(function(e){void 0!==t[e]&&(n[e]=t[e])})),i.forEach(a,(function(r){i.isObject(t[r])?n[r]=i.deepMerge(e[r],t[r]):void 0!==t[r]?n[r]=t[r]:i.isObject(e[r])?n[r]=i.deepMerge(e[r]):void 0!==e[r]&&(n[r]=e[r])})),i.forEach(s,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])}));var o=r.concat(a).concat(s),l=Object.keys(t).filter((function(e){return-1===o.indexOf(e)}));return i.forEach(l,(function(i){void 0!==t[i]?n[i]=t[i]:void 0!==e[i]&&(n[i]=e[i])})),n}}}),V=u({"../node_modules/axios/lib/core/Axios.js"(e,t){var i=C(),n=_(),r=E(),a=U(),s=B();function o(e){this.defaults=e,this.interceptors={request:new r,response:new r}}o.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=s(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=[a,void 0],i=Promise.resolve(e);for(this.interceptors.request.forEach((function(e){t.unshift(e.fulfilled,e.rejected)})),this.interceptors.response.forEach((function(e){t.push(e.fulfilled,e.rejected)}));t.length;)i=i.then(t.shift(),t.shift());return i},o.prototype.getUri=function(e){return e=s(this.defaults,e),n(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},i.forEach(["delete","get","head","options"],(function(e){o.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}})),i.forEach(["post","put","patch"],(function(e){o.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}})),t.exports=o}}),H=u({"../node_modules/axios/lib/cancel/Cancel.js"(e,t){function i(e){this.message=e}i.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},i.prototype.__CANCEL__=!0,t.exports=i}}),$=u({"../node_modules/axios/lib/cancel/CancelToken.js"(e,t){var i=H();function n(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;e((function(e){n.reason||(n.reason=new i(e),t(n.reason))}))}n.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},n.source=function(){var e;return{token:new n((function(t){e=t})),cancel:e}},t.exports=n}}),G=u({"../node_modules/axios/lib/helpers/spread.js"(e,t){t.exports=function(e){return function(t){return e.apply(null,t)}}}}),j=u({"../node_modules/axios/lib/axios.js"(e,t){var i=C(),n=y(),r=V(),a=B();function s(e){var t=new r(e),a=n(r.prototype.request,t);return i.extend(a,r.prototype,t),i.extend(a,t),a}var o=s(F());o.Axios=r,o.create=function(e){return s(a(o.defaults,e))},o.Cancel=H(),o.CancelToken=$(),o.isCancel=b(),o.all=function(e){return Promise.all(e)},o.spread=G(),t.exports=o,t.exports.default=o}}),z=u({"../node_modules/axios/index.js"(e,t){t.exports=j()}}),W=u({"../node_modules/@skype/hydra_player_hls_sdk/hydra_player_hls_sdk_bundle.js"(e,t){var i,n;i=e,n=function(){return e={458:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.LiveStreamStatistic=void 0;var r=i(844),a=i(68),s=i(329),o=function(){function e(e,t,i){this.name=e,this.stopCrash=t,this.start(i)}return e.prototype.complete=function(){try{s.assert(this.startTime,"not started",this.stopCrash),s.assert(void 0===this.duration,"already completed",this.stopCrash)}catch(e){if(this.name!==r.PlayerScenarioType.LoadHlsFirstFragment&&this.name!==r.PlayerScenarioType.HlsKeyLoad)throw e}this.duration=Date.now()-this.startTime},e.prototype.fail=function(e){this.failReason=e,this.complete()},e.prototype.setDetail=function(e){this.details=e},e.prototype.getTelemetryEvent=function(){s.assert(this.startTime,"not started",this.stopCrash);var e={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(e.failReason=this.failReason),this.details&&(e.details=this.details),e},e.prototype.getName=function(){return this.name},e.prototype.getDuration=function(){var e;return null!==(e=this.duration)&&void 0!==e?e:0},e.prototype.getFailReason=function(){return this.failReason},e.prototype.getDetails=function(){return this.details},e.prototype.start=function(e){s.assert(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),e&&(this.details=e)},e.prototype.updateDetails=function(e,t){if(this.details&&"object"==typeof this.details)for(var i=0;i<e.length;i++)this.details[e[i]]=t[i]},e}(),l=function(){function e(e,t,i,n,r){this.config=e,this.logFn=t,this.playerDiagnosticsLog=i,this.playerMetadata=n,this.hydraInitResult=r,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.experimentalEvents=[],this.callSetupSucceeded=!1,this.callDropped=!1,this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=e.maxPlayerExperimentalEvents||100,s.getECSSetting(this.config,"stopCrash",!1)?this.stopCrash=!1:this.stopCrash=!0,this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}return e.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e.prototype.registerStatsUpdated=function(e){var t=this;this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((function(i){var n,r=i,a=null!==(n=t.playerDiagnosticsLog[i])&&void 0!==n?n:[];if(Array.isArray(a)){a.push(e[r]);var s="memoryLog"===r&&a.length>t.maxPlayerMemoryTraceLogCount,o="memoryLog"!==r&&a.length>t.maxPlayerDiagnosticsCount;(s||o)&&a.splice(0,1)}else t.playerDiagnosticsLog[i]=e[r]}))},e.prototype.registerEventLoadAttempt=function(e,t){this.registerScenario(e,t)},e.prototype.registerEventLoadFailed=function(e,t){this.completeScenario(e,t)},e.prototype.registerEventLoadSucceeded=function(e,t){this.completeScenario(e,void 0,t),e===r.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e.prototype.registerSdnPluginLoadAttempt=function(e){this.registerScenario(r.PlayerScenarioType.SdnPluginLoad,JSON.stringify(e))},e.prototype.registerSdnPluginLoadFailed=function(e){this.completeScenario(r.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadSucceeded=function(){this.completeScenario(r.PlayerScenarioType.SdnPluginLoad)},e.prototype.registerStreamConnectionAttempt=function(e){this.registerScenario(r.PlayerScenarioType.StreamConnection,{streamUrl:e})},e.prototype.registerStreamConnectionSucceeded=function(e){var t=this.getScenario(r.PlayerScenarioType.StreamConnection);null==t||t.updateDetails(["results"],[s.stringifyObject(e)]),this.completeScenario(r.PlayerScenarioType.StreamConnection)},e.prototype.registerStreamConnectionFailed=function(e,t){var i=this.getScenario(r.PlayerScenarioType.StreamConnection);null==i||i.updateDetails(["results"],[s.stringifyObject(t)]),this.completeScenario(r.PlayerScenarioType.StreamConnection,e)},e.prototype.registerSetSourceAttempt=function(e,t,i){var n=e||"";i&&(n={src:e||"",isPrimary:s.stringifyObject(t),reason:i}),this.registerScenario(r.PlayerScenarioType.SetSource,n)},e.prototype.registerSetSourceSucceeded=function(e,t,i,n){var a=this.getScenario(r.PlayerScenarioType.SetSource);s.assert(a,"no SetSource scenario to update details",this.stopCrash),null==a||a.updateDetails(["src","isPrimary","SwitchingDiagnostics","StepDuration"],[e,s.stringifyObject(t),s.stringifyObject(i),s.stringifyObject(n)]),this.completeScenario(r.PlayerScenarioType.SetSource)},e.prototype.registerSetSourceFailed=function(e,t,i,n,a){var o=null!=t?t:"Failed to find stream url",l=this.getScenario(r.PlayerScenarioType.SetSource);s.assert(l,"no SetSource scenario to update details",this.stopCrash),null==l||l.updateDetails(["src","isPrimary","SwitchingDiagnostics","stepDuration"],[o,s.stringifyObject(i),s.stringifyObject(n),s.stringifyObject(a)]),this.completeScenario(r.PlayerScenarioType.SetSource,e)},e.prototype.registerPlayerDestroyed=function(e){this.registerScenario(r.PlayerScenarioType.Destroyed,e),this.completeScenario(r.PlayerScenarioType.Destroyed)},e.prototype.registerPlaybackStateChanged=function(e){e!==a.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp?e!==a.HydraPlayerPlaybackState.Playing||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),this.registerPlaybackEvent(r.TelemetryEventType.StateChanged,e)},e.prototype.registerHydraInputStateChanged=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.HydraInputStateChanged,e,t)},e.prototype.registerHydraOutputStateChanged=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.HydraOutputStateChanged,e,t)},e.prototype.registerPlaybackBuffering=function(e){this.registerPlaybackEvent(r.TelemetryEventType.Buffering,e)},e.prototype.registerPlaybackError=function(e,t,i){this.registerPlaybackEvent(r.TelemetryEventType.Error,{errorType:e,details:t,errorSource:i})},e.prototype.registerIgnoredPlaybackError=function(e){this.registerPlaybackEvent(r.TelemetryEventType.IgnoredError,e)},e.prototype.registerDownloadBitrateChanged=function(e){this.registerPlaybackEvent(r.TelemetryEventType.BitrateChangedDownload,e)},e.prototype.registerStreamOptionsConfigured=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.StreamOptionsConfigured,e,t)},e.prototype.registerPlaybackBitrateChanged=function(e){this.registerPlaybackEvent(r.TelemetryEventType.BitrateChangedPlayback,e)},e.prototype.registerVolumeChange=function(e){this.registerPlaybackEvent(r.TelemetryEventType.Volume,e)},e.prototype.getSnapshotReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.playerEvents.map((function(e){return e.getTelemetryEvent()}))),r=this.playbackEvents,a={};return this.currentPlayerDiagnosticSnapshot&&(a=this.filterAndPrepareTelemetry()),n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i,r)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),{networkType:this.getClientNetworkType(),callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),a)},e.prototype.getReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.playerEvents.map((function(e){return e.getTelemetryEvent()}))),r=this.playbackEvents;return n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i,r)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),{networkType:this.getClientNetworkType(),callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog())},e.prototype.getHydraLoadEvent=function(){var e,t,i,n={name:r.PlayerScenarioType.LoadHydra,startTime:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initStartTime)||-1,duration:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initDuration)||0};(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)&&(n.failReason=this.hydraInitResult.errorMsg);var a=this.getHydraRuntimeDownloadDetails();return a&&(n.details=a),n},e.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var e=[],t=0,i=this.hydraInitResult.runtimeDownloadResults;t<i.length;t++){var n=i[t],r={success:n.success,url:n.url,startTime:n.startTime,duration:n.duration,trackingReference:n.trackingReference,timeTakenToDownloadScript:n.timeTakenToDownloadScript};n.errorMsg&&(r.errorMsg=n.errorMsg),e.push(r)}return s.stringifyObject(e)}return null},e.prototype.getTotalLoadEvent=function(){var e,t,i,n=this.playerEvents.find((function(e){return e.getName()===r.PlayerScenarioType.LoadPlayer})),a=(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initDuration)||0,s=(null==n?void 0:n.getDuration())||0,o=null==n?void 0:n.getFailReason(),l={name:r.PlayerScenarioType.Load,startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,duration:a+s};return(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)?l.failReason=this.hydraInitResult.errorMsg:o&&(l.failReason=o),l},e.prototype.getPlayerMetadataReport=function(){return{playerId:this.playerMetadata.playerId||"",traceId:this.playerMetadata.playerId?this.playerMetadata.playerId.replace(/-/g,""):"",hydraPlayerRuntimeVersion:this.playerMetadata.hydraPlayerRuntimeVersion||"",hydraPlayerSdkVersion:this.playerMetadata.hydraPlayerSdkVersion,player_playerType:this.playerMetadata.hydraPlayerType}},e.prototype.registerPlaybackEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);e===r.TelemetryEventType.Error&&(null==t?void 0:t.errorType)!==a.HydraPlayerPlaybackErrorType.PlaybackRetried&&(n.fatal=!0,this.callDropped=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getPlayerDiagnosticLog=function(){var e=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var t=this.currentPlayerDiagnosticSnapshot,i=this.playerDiagnosticsLog,r=n(n({},t),i),a={};return Object.keys(r).forEach((function(t){a["player_".concat(t)]=e.prepareForTelemetry(r[t])})),a},e.prototype.getHydraInitializationReport=function(){var e,t,i,n;return{hydraInit_succeeded:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initSucceeded)||!1,hydraInit_startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,hydraInit_errorMessage:(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)||"",hydraInit_duration:(null===(n=this.hydraInitResult)||void 0===n?void 0:n.initDuration)||0}},e.prototype.getPlayerInitializationReport=function(e,t){var i=e.find((function(e){return e.name===r.PlayerScenarioType.Load}));return{init_timeLoadToStreamConnectionEstablished:(null!=i&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-i.startTime:-1)||-1,init_timeLoadToReady:(null!=i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(null!=i&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)}},e.prototype.getHydraInternalReport=function(e){var t=e.filter((function(e){return e.eventType===r.TelemetryEventType.HydraInputStateChanged})),i=e.filter((function(e){return e.eventType===r.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(t),hydra_outputStateChangeEvents:this.prepareForTelemetry(i)}},e.prototype.getPlaybackReport=function(e){var t=e.filter((function(e){return e.eventType===r.TelemetryEventType.StateChanged})),i=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.CanPlayThrough})),n=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Play})),s=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Start})),o=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Playing})),l=null!=i&&null!=n?n.timestamp-i.timestamp:-1,c=null!=n&&null!=s?s.timestamp-n.timestamp:-1,d=null!=s&&null!=o?o.timestamp-s.timestamp:-1,u=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Seeked})),h=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Seeking})),p=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Pause})),g=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Waiting})),m=[r.TelemetryEventType.BitrateChangedDownload,r.TelemetryEventType.BitrateChangedPlayback,r.TelemetryEventType.Error,r.TelemetryEventType.Mute,r.TelemetryEventType.StateChanged,r.TelemetryEventType.Volume,r.TelemetryEventType.StreamOptionsConfigured,r.TelemetryEventType.IgnoredError],f=e.filter((function(e){return e.eventType===r.TelemetryEventType.Error})),v=e.filter((function(e){return e.eventType===r.TelemetryEventType.IgnoredError})),S=e.filter((function(e){return e.eventType===r.TelemetryEventType.Volume||e.eventType===r.TelemetryEventType.Mute})),y=e.filter((function(e){return e.eventType===r.TelemetryEventType.StreamOptionsConfigured})),C=e.filter((function(e){return!m.includes(e.eventType)}));return{playback_timeReadyToPlay:l,playback_timePlayToStart:c,playback_timeStartToPlaying:d,playback_bufferingEvents:this.prepareForTelemetry(g),playback_errorEvents:this.prepareForTelemetry(f),playback_ignoredErrorEvents:this.prepareForTelemetry(v),playback_pauseEvents:this.prepareForTelemetry(p),playback_otherEvents:this.prepareForTelemetry(C),playback_seekedEvents:this.prepareForTelemetry(u),playback_seekingEvents:this.prepareForTelemetry(h),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(S),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(y)}},e.prototype.getBitrateReport=function(e){var t,i,a,s,o=e.filter((function(e){return e.eventType===r.TelemetryEventType.BitrateChangedDownload})),l=o.sort((function(e){return Number(e.payload)})),c=o.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(o),bitrate_downloadChangeCount:o.length>0||-1,bitrate_downloadMin:(null===(t=l[0])||void 0===t?void 0:t.payload)||-1,bitrate_downloadMax:(null===(i=l[l.length-1])||void 0===i?void 0:i.payload)||-1}:{},d=e.filter((function(e){return e.eventType===r.TelemetryEventType.BitrateChangedPlayback})),u=d.sort((function(e){return Number(e.payload)})),h=d.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(d),bitrate_playbackChangeCount:d.length>0||-1,bitrate_playbackMin:(null===(a=u[0])||void 0===a?void 0:a.payload)||-1,bitrate_playbackMax:(null===(s=u[u.length-1])||void 0===s?void 0:s.payload)||-1}:{};return n(n({},c),h)},e.prototype.addNetworkTypeEventListener=function(){var e,t,i,n,r=this;(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)&&(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n||n.addEventListener("change",(function(){r.updateClientNetworkType()})))},e.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e.prototype.getClientNetworkType=function(){var e,t,i,n;if(void 0===this.clientNetworkType){var r="Unknown";if(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)switch(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n?void 0:n.type){case"cellular":r="WWAN";break;case"ethernet":r="Wired";break;case"wifi":r="Wireless";break;default:r="Unknown"}this.clientNetworkType=r}return this.clientNetworkType},e.prototype.getSdnReport=function(e){var t,i,n=e.filter((function(e){return e.name===r.PlayerScenarioType.SdnPluginLoad})),a=n.length>0?n[n.length-1]:void 0;return{sdn_loaded:!(null==a||void 0!==a.failReason),sdn_details:null!==(t=null==a?void 0:a.details)&&void 0!==t?t:"",sdn_error:null!==(i=null==a?void 0:a.failReason)&&void 0!==i?i:"",sdn_events:this.prepareForTelemetry(n)}},e.prototype.getStreamConnectionReport=function(e){var t=e.filter((function(e){return e.name===r.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(t)}},e.prototype.getSetSourceReport=function(e){var t=e.filter((function(e){return e.name===r.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(t)}},e.prototype.registerScenario=function(e,t){var i=this.currentScenarioMap.get(e),n=new o(e,this.stopCrash,t);try{s.assert(null==i,"previous scenario:".concat(s.stringifyObject(i)," is not completed, new scenario:").concat(s.stringifyObject(n)),this.stopCrash)}catch(t){if(e!==r.PlayerScenarioType.LoadHlsFirstFragment&&e!==r.PlayerScenarioType.HlsKeyLoad)throw t}this.currentScenarioMap.set(e,n),this.playerEvents.push(n)},e.prototype.completeScenario=function(e,t,i){var n=this.currentScenarioMap.get(e);try{s.assert(n,"no scenario to complete",this.stopCrash)}catch(t){if(e!==r.PlayerScenarioType.LoadHlsFirstFragment&&e!==r.PlayerScenarioType.HlsKeyLoad)throw t}t?null==n||n.fail(t):(e!==r.PlayerScenarioType.StreamConnection||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),i&&(null==n||n.setDetail(i)),null==n||n.complete()),this.currentScenarioMap.delete(e)},e.prototype.logTelemetryEvent=function(e){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(e))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e.prototype.filterAndPrepareTelemetry=function(){var e=this,t=new Set;t.add("serviceLatencyCdg"),t.add("endToEndLatencyCdg"),t.add("videoEdgeLatencyCdg");var i={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(n){t.has(n)||(i["player_".concat(n)]=e.prepareForTelemetry(e.currentPlayerDiagnosticSnapshot[n]))})),i},e.prototype.prepareForTelemetry=function(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?null!=e?e:-1:JSON.stringify(e)},e.prototype.getScenario=function(e){return this.currentScenarioMap.get(e)},e.prototype.createTelemetryEvent=function(e,t,i){var n,r,a={eventType:e,timestamp:Date.now(),currentPlayPosition:null!==(r=null===(n=this.currentPlayerDiagnosticSnapshot)||void 0===n?void 0:n.currentPlayPosition)&&void 0!==r?r:-1};return void 0!==t&&(a.payload=this.prepareForTelemetry(t)),a.message=i,a},e.prototype.registerExperimentalEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e}();t.LiveStreamStatistic=l},751:function(e,t){var i,n,r,a,s,o;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerType=t.HydraStreamingEventType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=void 0,(o=t.HydraStreamDeliveryPipeline||(t.HydraStreamDeliveryPipeline={})).AMS="AMS",o.HLS="MiddleLaneHttpLiveStreaming",o.Ums="MiddleLaneUltraLowLatency",(s=t.HydraPlayerSetupErrorType||(t.HydraPlayerSetupErrorType={})).MultiplePlayerLoad="MultiplePlayerLoad",s.PlayerInitializationFailed="PlayerInitializationFailed",s.InvalidStream="InvalidStream",s.SetSourceFailed="SetSourceFailed",(a=t.HydraPlayerPlaybackState||(t.HydraPlayerPlaybackState={})).LoadStart="loadstart",a.LoadedData="loadeddata",a.LoadedMetadata="loadedmetadata",a.Start="start",a.CanPlayThrough="canplaythrough",a.Play="play",a.Playing="playing",a.Pause="pause",a.Waiting="waiting",a.Seeking="seeking",a.Seeked="seeked",a.Ended="ended",a.Error="error",a.Destroyed="destroyed",a.Initialized="initialized",a.Stalled="stalled",a.VolumeChange="volumechange",a.PlaybackBitrateChanged="playbackbitratechanged",a.DownloadBitrateChanged="downloadbitratechanged",a.HlsKeyLoading="hlsKeyLoading",a.HlsKeyLoaded="hlsKeyLoaded",a.HlsKeyLoadedFailed="hlsKeyLoadedFailed",a.HlsManifestLoading="hlsManifestLoading",a.HlsManifestLoaded="hlsManifestLoaded",a.HlsManifestLoadedFailed="hlsManifestLoadedFailed",a.HlsFirstFragmentLoading="hlsFragLoading",a.HlsFirstFragmentBuffered="hlsFragBuffered",a.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",a.Online="online",a.Offline="offline",a.NetworkChange="networkChange",(r=t.HydraPlayerPlaybackErrorType||(t.HydraPlayerPlaybackErrorType={})).UnsupportedPlatform="UnsupportedPlatform",r.NetworkError="NetworkError",r.PlaybackRetried="PlaybackRetried",r.PlaybackError="PlaybackError",r.Unknown="Unknown",(n=t.HydraStreamingEventType||(t.HydraStreamingEventType={})).TLE="TLE",n.Overflow="Overflow",n.TownHallBasic="TownHall_Basic",n.TownHallPremium="TownHall_Premium",n.TownHall="TownHall",(i=t.HydraPlayerType||(t.HydraPlayerType={}))[i.Hls=1]="Hls",i[i.Ums=2]="Ums"},855:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),r(i(952),t),r(i(751),t)},952:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){s.label=o[1];break}if(6===o[0]&&s.label<r[1]){s.label=r[1],r=o;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(o);break}r[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},s=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,a=t.length;r<a;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.HlsHydraPlayer=t.getSdkVersion=void 0;var o=i(124),l=i(68),c=i(328),d=i(844),u=i(944),h=i(329),p=i(63),g=i(458);t.getSdkVersion=function(){return"4.2488.1"};var m=function(){function e(e,t){this.playerSettings=e,this.eventHandler=t,this.spinner=null,this.commandResultsMap=new Map,this._onMessage=this.onMessage.bind(this),this.telemetryReportHandler=null,this.playerInternalEventHandler=null,this.playerRuntimeJsUrls=this.getRuntimeJsUrls(),this.playerSettings.hydraPlayerSdkVersion="4.2488.1"}return Object.defineProperty(e.prototype,"contextWindow",{get:function(){var e;return null===(e=this.container)||void 0===e?void 0:e.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e.prototype.getRuntimeJsUrls=function(){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var e=(0,h.getMajorFromVersion)("4.2488.1");return e&&this.playerSettings.playerRuntimeJsUrls[e]||[]}return this.playerSettings.playerRuntimeJsUrls},e.prototype.initializeIFrame=function(e){return r(this,void 0,void 0,(function(){var t;return a(this,(function(i){switch(i.label){case 0:return this.container=e,0===this.playerRuntimeJsUrls.length?[2,{initSucceeded:!1,initStartTime:Date.now(),initDuration:0,runtimeDownloadResults:[],errorMsg:"No compatible runtime URL provided for version ".concat("4.2488.1",', URLs: "').concat((0,h.stringifyObject)(this.playerSettings.playerRuntimeJsUrls),'"')}]:[4,(0,h.createIFrame)(e,this.playerRuntimeJsUrls,this.playerSettings.maxRetryCountForLoadingResources,this.playerSettings.disableSandbox,this.playerSettings.hydraRuntimeFetchTimeout)];case 1:return(t=i.sent()).initResult.initSucceeded&&t.iframe&&(this.iframe=t.iframe,this.contextWindow.addEventListener("message",this._onMessage)),[2,t.initResult]}}))}))},e.prototype.setup=function(e){return r(this,void 0,void 0,(function(){var t;return a(this,(function(i){switch(i.label){case 0:return this.spinner=new h.Spinner(e),[4,this.initializeIFrame(e)];case 1:return t=i.sent(),this.telemetryReportHandler=new v(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),t,this.spinner),this.playerInternalEventHandler=new f(this.spinner,this.telemetryReportHandler),t.initSucceeded?[4,this.sendCommand("createHlsHydraPlayer",this.playerSettings,t)]:[3,3];case 2:return i.sent(),[2,!0];case 3:return this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(t.errorMsg)),this.spinner.hide(),[2,!1]}}))}))},e.prototype.isIFrameCommunicationActive=function(){var e;return!!(null===(e=this.iframe)||void 0===e?void 0:e.contentWindow)&&!!this.contextWindow},e.prototype.getFullTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getFullTelemetryReport())||{}},e.prototype.getSnapshotTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getSnapshotTelemetryReport())||{}},e.prototype.callPlayerApi=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return r(this,void 0,void 0,(function(){return a(this,(function(i){switch(i.label){case 0:return this.iframe?[4,this.sendCommand.apply(this,s([e],t,!1))]:[3,2];case 1:case 3:return[2,i.sent()];case 2:return[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))]}}))}))},e.prototype.dispose=function(){var e;null===(e=this.telemetryReportHandler)||void 0===e||e.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.sendCommand("disposeHydraPlayer")},e.prototype.release=function(){var e;null===(e=this.spinner)||void 0===e||e.hide(),this.contextWindow&&this.contextWindow.removeEventListener("message",this._onMessage),this.iframe&&this.container&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe)},e.prototype.sendCommand=function(e){for(var t,i,n=[],s=1;s<arguments.length;s++)n[s-1]=arguments[s];return r(this,void 0,void 0,(function(){var r,s,l;return a(this,(function(a){switch(a.label){case 0:if(r={msgType:o.MessageType.Command,name:e,args:n},!this.isIFrameCommunicationActive())throw new Error("IFrame MessageAPI communication not active");return void 0!==(s=this.commandResultsMap.get(e.toString()))&&s.reject(new Error("function ".concat(e," is invoked again, before previous call is completed"))),l=u.defer(),this.commandResultsMap.set(e,l),null===(i=null===(t=this.iframe)||void 0===t?void 0:t.contentWindow)||void 0===i||i.postMessage(r,"*"),[4,l.promise];case 1:return[2,a.sent()]}}))}))},e.prototype.onMessage=function(e){switch(e.data.msgType){case o.MessageType.PlayerEvent:this.processPlayerEvent(e.data);break;case o.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(e.data);break;case o.MessageType.CommandSuccessResult:this.processCommandSuccessResult(e.data);break;case o.MessageType.CommandFailureResult:this.processCommandFailureResult(e.data)}},e.prototype.processCommandSuccessResult=function(e){var t=this.commandResultsMap.get(e.name.toString());void 0!==t&&(t.resolve(e.result),this.commandResultsMap.delete(e.name.toString()))},e.prototype.processCommandFailureResult=function(e){var t=this.commandResultsMap.get(e.name.toString());void 0!==t&&(t.reject(e.error),this.commandResultsMap.delete(e.name.toString()))},e.prototype.processPlayerEvent=function(e){this.eventHandler[e.name].apply(this.eventHandler,e.args)},e.prototype.processInternalPlayerEvent=function(e){this.playerInternalEventHandler&&this.playerInternalEventHandler[e.name].apply(this,e.args)},e}();t.HlsHydraPlayer=m;var f=function(){function e(e,t){this.spinner=e,this.telemetryReportHandler=t}return e.prototype.firstPlayerLoadAttemptDone=function(){this.spinner.hide()},e.prototype.fullTelemetryReportUpdated=function(e){this.telemetryReportHandler.setFullTelemetryReport(e)},e.prototype.snapshotTelemetryReportUpdated=function(e){this.telemetryReportHandler.setSnapshotTelemetryReport(e)},e}(),v=function(){function e(e,t,i,n){var r=this;this.logFn=t,this.spinner=n;var a=new g.LiveStreamStatistic(e,(function(e,t){r.logFn(e,t)}),{perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],statsInterval:[],serviceAvgLatency:[],endToEndAvgLatency:[]},{hydraPlayerSdkVersion:e.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:c.HydraPlayerType.Hls},i);this.fullTelemetryReport=a.getReport(),this.snapshotTelemetryReport=a.getSnapshotReport()}return e.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e.prototype.setFullTelemetryReport=function(e){var t,i,r;this.fullTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(t=this.spinner.firstShowTimestamp)&&void 0!==t?t:-1,init_spinnerHideTimestamp:null!==(i=this.spinner.firstHideTimestamp)&&void 0!==i?i:-1,init_spinnerDuration:null!==(r=this.spinner.firstSpinnerDuration)&&void 0!==r?r:-1,init_spinnerVisible:this.spinner.isVisible()})},e.prototype.setSnapshotTelemetryReport=function(e){var t,i,r;this.snapshotTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(t=this.spinner.firstShowTimestamp)&&void 0!==t?t:-1,init_spinnerHideTimestamp:null!==(i=this.spinner.firstHideTimestamp)&&void 0!==i?i:-1,init_spinnerDuration:null!==(r=this.spinner.firstSpinnerDuration)&&void 0!==r?r:-1,init_spinnerVisible:this.spinner.isVisible()})},e.prototype.addDisposeTelemetry=function(){var e=Date.now();try{this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in full telemetry report")}try{this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in snapshot telemetry report")}try{this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in full telemetry report")}try{this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in snapshot telemetry report")}this.fullTelemetryReport.hydraDisposeTimestamp=e,this.snapshotTelemetryReport.hydraDisposeTimestamp=e},e.prototype.updateInitEventsWithDisposeEvent=function(e,t){var i=e.init_allEvents,n=JSON.parse(i);n[n.length-1].name!==d.PlayerScenarioType.Destroyed&&n.push({name:d.PlayerScenarioType.Destroyed,startTime:t,duration:0,details:p.HydraPlayerDestroyedReason.PlayerStopped}),e.init_allEvents=(0,h.stringifyObject)(n)},e.prototype.updateStateChangeEventsWithDisposeEvent=function(e,t){var i=e.playback_stateChangeEvents,n=JSON.parse(i);n[n.length-1].payload!==l.HydraPlayerPlaybackState.Destroyed&&n.push({eventType:d.TelemetryEventType.StateChanged,timestamp:t,currentPlayPosition:-1,payload:l.HydraPlayerPlaybackState.Destroyed}),e.playback_stateChangeEvents=(0,h.stringifyObject)(n)},e}()},124:function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageType=void 0,(i=t.MessageType||(t.MessageType={})).Command="Command",i.CommandSuccessResult="CommandSuccessResult",i.CommandFailureResult="CommandFailureResult",i.PlayerEvent="PlayerEvent",i.InternalPlayerEvent="InternalPlayerEvent"},63:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraSupportedSDN=t.HydraPlayerDestroyedReason=void 0,(n=t.HydraPlayerDestroyedReason||(t.HydraPlayerDestroyedReason={})).PlayerStopped="PlayerStopped",n.PlaybackError="PlaybackError",(i=t.HydraSupportedSDN||(t.HydraSupportedSDN={})).Hive="hive",i.Kollective="kollective",i.Ramp="ramp",i.Peer5="peer5",i.Microsoft="microsoft"},844:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.PlayerScenarioType=t.TelemetryEventType=void 0,(n=t.TelemetryEventType||(t.TelemetryEventType={})).BitrateChangedDownload="BitrateChangedDownload",n.StreamOptionsConfigured="StreamOptionsConfigured",n.BitrateChangedPlayback="BitrateChangedPlayback",n.CaptionsToggled="CaptionsToggled",n.Error="Error",n.IgnoredError="IgnoredError",n.FullscreenChanged="FullscreenChanged",n.Mute="Mute",n.PotentialMediaFreeze="PotentialMediaFreeze",n.StateChanged="StateChanged",n.HydraInputStateChanged="HydraInputStateChanged",n.HydraOutputStateChanged="HydraOutputStateChanged",n.Volume="Volume",n.Buffering="Buffering",n.Online="Online",n.Offline="Offline",n.NetworkChange="NetworkChange",n.HlsEvents="HlsEvents",(i=t.PlayerScenarioType||(t.PlayerScenarioType={})).LoadHydra="LoadHydra",i.LoadHlsScript="LoadHlsScript",i.LoadPlayer="LoadPlayer",i.Load="Load",i.LoadHlsAuthCookie="LoadHlsAuthCookie",i.HlsManifestLoad="HlsManifestLoad",i.HlsKeyLoad="HlsKeyLoad",i.LoadHlsFirstFragment="LoadHlsFirstFragment",i.SetSource="SetSource",i.SdnPluginLoad="SdnPluginLoad",i.ThaPluginLoad="ThaPluginLoad",i.HydraPipelineInitialization="HydraPipelineInitialization",i.Destroyed="Destroyed",i.Setup="Setup",i.StreamConnection="StreamConnection"},328:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerType=t.HydraStreamingEventType=void 0,(n=t.HydraStreamingEventType||(t.HydraStreamingEventType={})).TLE="TLE",n.Overflow="Overflow",n.TownHallBasic="TownHall_Basic",n.TownHallPremium="TownHall_Premium",n.TownHall="TownHall",(i=t.HydraPlayerType||(t.HydraPlayerType={}))[i.Hls=1]="Hls",i[i.Ums=2]="Ums"},68:function(e,t){var i,n,r,a;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=void 0,(a=t.HydraStreamDeliveryPipeline||(t.HydraStreamDeliveryPipeline={})).AMS="AMS",a.HLS="MiddleLaneHttpLiveStreaming",a.Ums="MiddleLaneUltraLowLatency",(r=t.HydraPlayerSetupErrorType||(t.HydraPlayerSetupErrorType={})).MultiplePlayerLoad="MultiplePlayerLoad",r.PlayerInitializationFailed="PlayerInitializationFailed",r.InvalidStream="InvalidStream",r.SetSourceFailed="SetSourceFailed",(n=t.HydraPlayerPlaybackState||(t.HydraPlayerPlaybackState={})).LoadStart="loadstart",n.LoadedData="loadeddata",n.LoadedMetadata="loadedmetadata",n.Start="start",n.CanPlayThrough="canplaythrough",n.Play="play",n.Playing="playing",n.Pause="pause",n.Waiting="waiting",n.Seeking="seeking",n.Seeked="seeked",n.Ended="ended",n.Error="error",n.Destroyed="destroyed",n.Initialized="initialized",n.Stalled="stalled",n.VolumeChange="volumechange",n.PlaybackBitrateChanged="playbackbitratechanged",n.DownloadBitrateChanged="downloadbitratechanged",n.HlsKeyLoading="hlsKeyLoading",n.HlsKeyLoaded="hlsKeyLoaded",n.HlsKeyLoadedFailed="hlsKeyLoadedFailed",n.HlsManifestLoading="hlsManifestLoading",n.HlsManifestLoaded="hlsManifestLoaded",n.HlsManifestLoadedFailed="hlsManifestLoadedFailed",n.HlsFirstFragmentLoading="hlsFragLoading",n.HlsFirstFragmentBuffered="hlsFragBuffered",n.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",n.Online="online",n.Offline="offline",n.NetworkChange="networkChange",(i=t.HydraPlayerPlaybackErrorType||(t.HydraPlayerPlaybackErrorType={})).UnsupportedPlatform="UnsupportedPlatform",i.NetworkError="NetworkError",i.PlaybackRetried="PlaybackRetried",i.PlaybackError="PlaybackError",i.Unknown="Unknown"},944:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(){var e,t;return{promise:new Promise((function(i,n){e=i,t=n})),resolve:e,reject:t}}},329:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){s.label=o[1];break}if(6===o[0]&&s.label<r[1]){s.label=r[1],r=o;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(o);break}r[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createVideoElement=t.createVideoElementDiv=t.showPlayerControls=t.getSdnStats=t.Spinner=t.repeatUntilCancel=t.wait=t.stringifyError=t.stringifyObject=t.getRandomHexString=t.getPlayerSetting=t.getECSSetting=t.assert=t.createIFrame=t.getMajorFromVersion=void 0;var a=i(63),s=i(328);function o(e,t,i,a,s){return n(this,void 0,void 0,(function(){var o,l,d,h,p=this;return r(this,(function(g){switch(g.label){case 0:return o=100,l=Date.now(),[4,c(i,d={trackingRef:"",timeTakenToDownloadScript:-1},s).catch((function(e){return n(p,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return t="Failed to get IFrame source: ".concat(u(e)),a.push({success:!1,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript,errorMsg:t}),a.length>o&&a.shift(),[4,Promise.reject(new Error(t))];case 1:return[2,n.sent()]}}))}))}))];case 1:return h=g.sent(),t.srcdoc=h,e.appendChild(t),[4,new Promise((function(e,n){t.onload=function(){a.push({success:!0,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript}),a.length>o&&a.shift(),e()},t.onerror=function(e){var t="Failed to load HydraPlayer IFrame: ".concat(u(e));a.push({success:!1,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript,errorMsg:t}),a.length>o&&a.shift(),n(new Error(t))}}))];case 2:return g.sent(),[2]}}))}))}function l(e,t){return n(this,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,e(t).catch((function(a){return n(i,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return 0!=--t?[3,2]:[4,Promise.reject(a)];case 1:case 3:return[2,s.sent()];case 2:return[4,new Promise((function(s){return setTimeout((function(){s(l(e,t).catch((function(e){return n(i,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(new Error("".concat(u(a)).concat(", ",u(e))))];case 1:return[2,t.sent()]}}))}))})))}),100)}))]}}))}))}))];case 1:return a.sent(),[2]}}))}))}function c(e,t,i){return n(this,void 0,void 0,(function(){var a,s,o,l=this;return r(this,(function(c){switch(c.label){case 0:return a=Date.now(),[4,d(e,t,i).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(e)];case 1:return[2,t.sent()]}}))}))}))];case 1:return s=c.sent(),o="<script> ".concat(s,"<\/script>"),t.timeTakenToDownloadScript=Date.now()-a,[2,"\n        <html class style='height: 100%; width: 100%; overflow: hidden'>\n        <head></head>\n        <body class style='height: 100%; width: 100%; margin: 0px'>\n            ".concat(o,"\n        </body>\n        </html>\n    ")]}}))}))}function d(e,t,i){return n(this,void 0,void 0,(function(){var a,s,o,l=this;return r(this,(function(c){switch(c.label){case 0:return a=function(e,t){var i,n;return t.includes("vz")?null!==(n=e.headers.get("uuid"))&&void 0!==n?n:"":null!==(i=e.headers.get("X-Azure-Ref"))&&void 0!==i?i:""},i?(s=new AbortController,o=setTimeout((function(){s.abort()}),i),[4,fetch(e,{signal:s.signal,cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return clearTimeout(o),i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=a(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,t.text().then((function(a){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return a?[2,a]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,a.sent()]}}))}))})).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){throw clearTimeout(o),e}))}))}))]):[3,2];case 1:case 3:return[2,c.sent()];case 2:return[4,fetch(e,{cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=a(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,t.text().then((function(a){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return a?[2,a]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,a.sent()]}}))}))}))]}}))}))}function u(e){try{if(!e)return"".concat(e);if(e instanceof Map)return i={},e.forEach((function(e,t){i[t.toString()]=e})),JSON.stringify(i);var t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}catch(e){return""}var i}function h(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){return setTimeout(t,e)}))];case 1:return t.sent(),[2]}}))}))}t.getMajorFromVersion=function(e){var t=e.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return t?t[1]:null},t.createIFrame=function(e,t,i,a,s){return void 0===a&&(a=!1),n(this,void 0,void 0,(function(){var c,d,h,p,g=this;return r(this,(function(m){switch(m.label){case 0:return c=[],d=Date.now(),(h=e.ownerDocument.createElement("iframe")).id="player-iframe",a||h.sandbox.add("allow-scripts"),h.allowFullscreen=!0,h.allow="camera; microphone; autoplay",h.style.height="100%",h.style.width="100%",h.style.border="none",p=function(e){return t[e%t.length]},[4,l((function(t){return n(g,void 0,void 0,(function(){var i;return r(this,(function(n){switch(n.label){case 0:return i=p(t),[4,o(e,h,i,c,s)];case 1:return n.sent(),[2]}}))}))}),i).then((function(){return{iframe:h,initResult:{initSucceeded:!0,initStartTime:d,initDuration:Date.now()-d,runtimeDownloadResults:c}}})).catch((function(e){return n(g,void 0,void 0,(function(){var i;return r(this,(function(n){return i="Failed to load Hydra player runtime scripts, src: ",t.forEach((function(e){return i=i.concat(e,", ")})),i+="errors: ".concat(u(e)),[2,{initResult:{initSucceeded:!1,initStartTime:d,initDuration:Date.now()-d,runtimeDownloadResults:c,errorMsg:i}}]}))}))}))];case 1:return[2,m.sent()]}}))}))},t.assert=function(e,t,i){if(void 0===i&&(i=!1),!e){if(!i)throw new Error("Assert failed".concat(void 0!==t?": ".concat(t):""));console.error("Assert failed".concat(void 0!==t?": ".concat(t):""))}},t.getECSSetting=function(e,t,i){var n,r=i,a=null===(n=e.ecsSettings)||void 0===n?void 0:n[t];return typeof a==typeof r&&(r=a),r},t.getPlayerSetting=function(e,t){var i;return void 0!==(null===(i=e.ecsSettings)||void 0===i?void 0:i[t])?e.ecsSettings[t]:e[t]},t.getRandomHexString=function(e){return Array.from(Array(e)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},t.stringifyObject=u,t.stringifyError=function(e){return e instanceof Error?e.message:u(e)},t.wait=h,t.repeatUntilCancel=function(e,t,i,a){var s=!1,o=a||console.log;return o("RepeatUntilCancel starting task: ".concat(e)),n(this,void 0,void 0,(function(){var n,a,l;return r(this,(function(r){switch(r.label){case 0:return s?[3,2]:(n=new Date,t(),a=(new Date).getTime()-n.getTime(),(l=i-a)<0&&(l=i+l%i,o("Skipping execution for ".concat(e,", last execution took: ").concat(a," ms, delayMs: ").concat(i),"warn")),[4,h(l)]);case 1:return r.sent(),[3,0];case 2:return[2]}}))})),function(){o("RepeatUntilCancel stopping task: ".concat(e)),s=!0}};var p=function(){function e(e){this.container=e,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var t=this.container.ownerDocument.getElementById(this.spinnerId);if(t)return this.spinner=t,void this.show();var i=this.container.ownerDocument.createElement("style");i.textContent="\n            .ml-player-spinner-container {\n                width: 100%;\n                height: 100%;\n                display: flex;\n                justify-content: center;\n                align-items: center;\n                position: absolute;\n                pointer-events: none;\n            }\n            .ml-player-spinner {\n                width: 3.6rem;\n                height: 3.6rem;\n                display: block;\n                overflow-clip-margin: content-box;\n                overflow: hidden;\n                animation: ml-player-spinner-outer-rotate 3s linear infinite;\n            }\n            .ml-player-spinner-dark-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(68, 71, 145);\n                stroke-width: 8px;\n            }\n            .ml-player-spinner-light-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(127, 133, 245);\n                stroke-width: 8px;\n                stroke-dasharray: 283;\n                stroke-dashoffset: 280;\n                stroke-linecap: round;\n                transform-origin: 50% 50%;\n                animation: ml-player-spinner-inner-rotate 1.5s cubic-bezier(0.33, 0, 0.67, 1) infinite;\n            }\n            @keyframes ml-player-spinner-outer-rotate {\n                0% {\n                    transform: rotate(0deg);\n                }\n                100% {\n                    transform: rotate(360deg);\n                }\n            }\n            @keyframes ml-player-spinner-inner-rotate {\n                0% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                25% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                50% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                75% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                100% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(360deg);\n                }\n            }\n        ",this.container.ownerDocument.head.appendChild(i),this.container.style.position="relative";var n=this.container.ownerDocument.createElement("div");n.classList.add("ml-player-spinner-container"),this.container.appendChild(n),this.spinner=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","svg"),this.spinner.style.position="absolute",this.spinner.setAttribute("viewBox","0 0 100 100"),this.spinner.classList.add("ml-player-spinner"),this.spinner.id=this.spinnerId,n.appendChild(this.spinner);var r=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");r.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(r);var a=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");a.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(a),this.show()}return Object.defineProperty(e.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var e=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];e.hideTimestamp||(e.displayDuration=Date.now()-e.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e.prototype.show=function(){var e=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=e),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:e,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e.prototype.hide=function(){var e=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=e),this.spinnerInfoHistory.length>0){var t=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];t.hideTimestamp||(t.hideTimestamp=e,t.displayDuration=e-t.showTimestamp)}this.spinner.style.display="none"},e.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e}();t.Spinner=p,t.getSdnStats=function(e,t){(null==e?void 0:e.peer5)&&(t.sdnName=e.peer5?a.HydraSupportedSDN.Microsoft:"",t.sdnVersion=e.peer5?e.peer5.version:"","function"==typeof e.peer5.getStats&&(t.sdnStats=e.peer5.getStats(),t.isP2PSdnUsed=e.peer5.getStats().numOfPeers>0))},t.showPlayerControls=function(e){return void 0!==e.allowPlayerControls?e.allowPlayerControls:e.streamingEventType===s.HydraStreamingEventType.TLE},t.createVideoElementDiv=function(e,t,i){i("createVideoElementDiv started");var n=t.ownerDocument.createElement("div");return n.id=e,n.style.position="relative",n.style.width="100%",n.style.height="100%",t.appendChild(n),i("createVideoElementDiv done"),n},t.createVideoElement=function(e,t,i,n,r){r("createVideoElement started");var a=t.ownerDocument.createElement("video");a.controls=n,a.id=e,a.setAttribute("playsinline","");var s=i.videoLang;s&&(a.setAttribute("lang",s),r("createVideoElement: language set to ".concat(s)));for(var o=i.videoElementStyles,l=0;l<o.length;l++)a.classList.add(o[l]);return a.style.width="100%",a.style.height="100%",a.style.position="absolute",a.muted=i.muteVideo,a.addEventListener("contextmenu",(function(e){e.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(e){try{navigator.mediaSession.setActionHandler(e,(function(){}))}catch(e){}})),t.appendChild(a),r("createVideoElement done"),a}}},t={},function i(n){var r=t[n];if(void 0!==r)return r.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,i),a.exports}(855);var e,t},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e.hydra_player_hls_sdk=n():i.hydra_player_hls_sdk=n()}}),q=u({"../node_modules/@skype/hydra_player_ums_sdk/hydra_player_ums_sdk_bundle.js"(e,t){var i,n;i=e,n=function(){return e={458:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.LiveStreamStatistic=void 0;var r=i(844),a=i(68),s=i(329),o=function(){function e(e,t,i){this.name=e,this.stopCrash=t,this.start(i)}return e.prototype.complete=function(){try{s.assert(this.startTime,"not started",this.stopCrash),s.assert(void 0===this.duration,"already completed",this.stopCrash)}catch(e){if(this.name!==r.PlayerScenarioType.LoadHlsFirstFragment&&this.name!==r.PlayerScenarioType.HlsKeyLoad)throw e}this.duration=Date.now()-this.startTime},e.prototype.fail=function(e){this.failReason=e,this.complete()},e.prototype.setDetail=function(e){this.details=e},e.prototype.getTelemetryEvent=function(){s.assert(this.startTime,"not started",this.stopCrash);var e={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(e.failReason=this.failReason),this.details&&(e.details=this.details),e},e.prototype.getName=function(){return this.name},e.prototype.getDuration=function(){var e;return null!==(e=this.duration)&&void 0!==e?e:0},e.prototype.getFailReason=function(){return this.failReason},e.prototype.getDetails=function(){return this.details},e.prototype.start=function(e){s.assert(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),e&&(this.details=e)},e.prototype.updateDetails=function(e,t){if(this.details&&"object"==typeof this.details)for(var i=0;i<e.length;i++)this.details[e[i]]=t[i]},e}(),l=function(){function e(e,t,i,n,r){this.config=e,this.logFn=t,this.playerDiagnosticsLog=i,this.playerMetadata=n,this.hydraInitResult=r,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.experimentalEvents=[],this.callSetupSucceeded=!1,this.callDropped=!1,this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxPlayerExperimentalEvents=e.maxPlayerExperimentalEvents||100,s.getECSSetting(this.config,"stopCrash",!1)?this.stopCrash=!1:this.stopCrash=!0,this.config.debugLogging&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}return e.prototype.getPlayerDiagnosticSnapshot=function(){return this.currentPlayerDiagnosticSnapshot},e.prototype.registerStatsUpdated=function(e){var t=this;this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((function(i){var n,r=i,a=null!==(n=t.playerDiagnosticsLog[i])&&void 0!==n?n:[];if(Array.isArray(a)){a.push(e[r]);var s="memoryLog"===r&&a.length>t.maxPlayerMemoryTraceLogCount,o="memoryLog"!==r&&a.length>t.maxPlayerDiagnosticsCount;(s||o)&&a.splice(0,1)}else t.playerDiagnosticsLog[i]=e[r]}))},e.prototype.registerEventLoadAttempt=function(e,t){this.registerScenario(e,t)},e.prototype.registerEventLoadFailed=function(e,t){this.completeScenario(e,t)},e.prototype.registerEventLoadSucceeded=function(e,t){this.completeScenario(e,void 0,t),e===r.PlayerScenarioType.LoadPlayer&&(this.callSetupSucceeded=!0)},e.prototype.registerSdnPluginLoadAttempt=function(e){this.registerScenario(r.PlayerScenarioType.SdnPluginLoad,JSON.stringify(e))},e.prototype.registerSdnPluginLoadFailed=function(e){this.completeScenario(r.PlayerScenarioType.SdnPluginLoad,e)},e.prototype.registerSdnPluginLoadSucceeded=function(){this.completeScenario(r.PlayerScenarioType.SdnPluginLoad)},e.prototype.registerStreamConnectionAttempt=function(e){this.registerScenario(r.PlayerScenarioType.StreamConnection,{streamUrl:e})},e.prototype.registerStreamConnectionSucceeded=function(e){var t=this.getScenario(r.PlayerScenarioType.StreamConnection);null==t||t.updateDetails(["results"],[s.stringifyObject(e)]),this.completeScenario(r.PlayerScenarioType.StreamConnection)},e.prototype.registerStreamConnectionFailed=function(e,t){var i=this.getScenario(r.PlayerScenarioType.StreamConnection);null==i||i.updateDetails(["results"],[s.stringifyObject(t)]),this.completeScenario(r.PlayerScenarioType.StreamConnection,e)},e.prototype.registerSetSourceAttempt=function(e,t,i){var n=e||"";i&&(n={src:e||"",isPrimary:s.stringifyObject(t),reason:i}),this.registerScenario(r.PlayerScenarioType.SetSource,n)},e.prototype.registerSetSourceSucceeded=function(e,t,i,n){var a=this.getScenario(r.PlayerScenarioType.SetSource);s.assert(a,"no SetSource scenario to update details",this.stopCrash),null==a||a.updateDetails(["src","isPrimary","SwitchingDiagnostics","StepDuration"],[e,s.stringifyObject(t),s.stringifyObject(i),s.stringifyObject(n)]),this.completeScenario(r.PlayerScenarioType.SetSource)},e.prototype.registerSetSourceFailed=function(e,t,i,n,a){var o=null!=t?t:"Failed to find stream url",l=this.getScenario(r.PlayerScenarioType.SetSource);s.assert(l,"no SetSource scenario to update details",this.stopCrash),null==l||l.updateDetails(["src","isPrimary","SwitchingDiagnostics","stepDuration"],[o,s.stringifyObject(i),s.stringifyObject(n),s.stringifyObject(a)]),this.completeScenario(r.PlayerScenarioType.SetSource,e)},e.prototype.registerPlayerDestroyed=function(e){this.registerScenario(r.PlayerScenarioType.Destroyed,e),this.completeScenario(r.PlayerScenarioType.Destroyed)},e.prototype.registerPlaybackStateChanged=function(e){e!==a.HydraPlayerPlaybackState.CanPlayThrough||this.firstReadyStateTimestamp?e!==a.HydraPlayerPlaybackState.Playing||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),this.registerPlaybackEvent(r.TelemetryEventType.StateChanged,e)},e.prototype.registerHydraInputStateChanged=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.HydraInputStateChanged,e,t)},e.prototype.registerHydraOutputStateChanged=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.HydraOutputStateChanged,e,t)},e.prototype.registerPlaybackBuffering=function(e){this.registerPlaybackEvent(r.TelemetryEventType.Buffering,e)},e.prototype.registerPlaybackError=function(e,t,i){this.registerPlaybackEvent(r.TelemetryEventType.Error,{errorType:e,details:t,errorSource:i})},e.prototype.registerIgnoredPlaybackError=function(e){this.registerPlaybackEvent(r.TelemetryEventType.IgnoredError,e)},e.prototype.registerDownloadBitrateChanged=function(e){this.registerPlaybackEvent(r.TelemetryEventType.BitrateChangedDownload,e)},e.prototype.registerStreamOptionsConfigured=function(e,t){this.registerPlaybackEvent(r.TelemetryEventType.StreamOptionsConfigured,e,t)},e.prototype.registerPlaybackBitrateChanged=function(e){this.registerPlaybackEvent(r.TelemetryEventType.BitrateChangedPlayback,e)},e.prototype.registerVolumeChange=function(e){this.registerPlaybackEvent(r.TelemetryEventType.Volume,e)},e.prototype.getSnapshotReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.playerEvents.map((function(e){return e.getTelemetryEvent()}))),r=this.playbackEvents,a={};return this.currentPlayerDiagnosticSnapshot&&(a=this.filterAndPrepareTelemetry()),n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!1,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i,r)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),{networkType:this.getClientNetworkType(),callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),a)},e.prototype.getReport=function(){var e,t,i=[this.getTotalLoadEvent(),this.getHydraLoadEvent()].concat(this.playerEvents.map((function(e){return e.getTelemetryEvent()}))),r=this.playbackEvents;return n(n(n(n(n(n(n(n(n(n(n(n(n({isFullReport:!0,configIds:this.config.configIds||"",eTag:this.config.eTag||""},this.getPlayerMetadataReport()),{isIframe:!0,isFullscreenButtonDisabled:!1,telemetryTickMs:null!==(t=null===(e=this.currentPlayerDiagnosticSnapshot)||void 0===e?void 0:e.statsInterval)&&void 0!==t?t:-1}),this.getHydraInitializationReport()),this.getPlayerInitializationReport(i,r)),this.getHydraInternalReport(r)),this.getPlaybackReport(r)),this.getBitrateReport(r)),this.getStreamConnectionReport(i)),this.getSdnReport(i)),this.getSetSourceReport(i)),this.getExperimentalEvents()),{networkType:this.getClientNetworkType(),callSetupSucceeded:this.callSetupSucceeded,callDropped:this.callDropped}),this.getPlayerDiagnosticLog())},e.prototype.getHydraLoadEvent=function(){var e,t,i,n={name:r.PlayerScenarioType.LoadHydra,startTime:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initStartTime)||-1,duration:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initDuration)||0};(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)&&(n.failReason=this.hydraInitResult.errorMsg);var a=this.getHydraRuntimeDownloadDetails();return a&&(n.details=a),n},e.prototype.getHydraRuntimeDownloadDetails=function(){if(this.hydraInitResult){for(var e=[],t=0,i=this.hydraInitResult.runtimeDownloadResults;t<i.length;t++){var n=i[t],r={success:n.success,url:n.url,startTime:n.startTime,duration:n.duration,trackingReference:n.trackingReference,timeTakenToDownloadScript:n.timeTakenToDownloadScript};n.errorMsg&&(r.errorMsg=n.errorMsg),e.push(r)}return s.stringifyObject(e)}return null},e.prototype.getTotalLoadEvent=function(){var e,t,i,n=this.playerEvents.find((function(e){return e.getName()===r.PlayerScenarioType.LoadPlayer})),a=(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initDuration)||0,s=(null==n?void 0:n.getDuration())||0,o=null==n?void 0:n.getFailReason(),l={name:r.PlayerScenarioType.Load,startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,duration:a+s};return(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)?l.failReason=this.hydraInitResult.errorMsg:o&&(l.failReason=o),l},e.prototype.getPlayerMetadataReport=function(){return{playerId:this.playerMetadata.playerId||"",traceId:this.playerMetadata.playerId?this.playerMetadata.playerId.replace(/-/g,""):"",hydraPlayerRuntimeVersion:this.playerMetadata.hydraPlayerRuntimeVersion||"",hydraPlayerSdkVersion:this.playerMetadata.hydraPlayerSdkVersion,player_playerType:this.playerMetadata.hydraPlayerType}},e.prototype.registerPlaybackEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);e===r.TelemetryEventType.Error&&(null==t?void 0:t.errorType)!==a.HydraPlayerPlaybackErrorType.PlaybackRetried&&(n.fatal=!0,this.callDropped=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getPlayerDiagnosticLog=function(){var e=this;if(!this.currentPlayerDiagnosticSnapshot)return{};var t=this.currentPlayerDiagnosticSnapshot,i=this.playerDiagnosticsLog,r=n(n({},t),i),a={};return Object.keys(r).forEach((function(t){a["player_".concat(t)]=e.prepareForTelemetry(r[t])})),a},e.prototype.getHydraInitializationReport=function(){var e,t,i,n;return{hydraInit_succeeded:(null===(e=this.hydraInitResult)||void 0===e?void 0:e.initSucceeded)||!1,hydraInit_startTime:(null===(t=this.hydraInitResult)||void 0===t?void 0:t.initStartTime)||-1,hydraInit_errorMessage:(null===(i=this.hydraInitResult)||void 0===i?void 0:i.errorMsg)||"",hydraInit_duration:(null===(n=this.hydraInitResult)||void 0===n?void 0:n.initDuration)||0}},e.prototype.getPlayerInitializationReport=function(e,t){var i=e.find((function(e){return e.name===r.PlayerScenarioType.Load}));return{init_timeLoadToStreamConnectionEstablished:(null!=i&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-i.startTime:-1)||-1,init_timeLoadToReady:(null!=i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(null!=i&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)}},e.prototype.getHydraInternalReport=function(e){var t=e.filter((function(e){return e.eventType===r.TelemetryEventType.HydraInputStateChanged})),i=e.filter((function(e){return e.eventType===r.TelemetryEventType.HydraOutputStateChanged}));return{hydra_inputStateChangeEvents:this.prepareForTelemetry(t),hydra_outputStateChangeEvents:this.prepareForTelemetry(i)}},e.prototype.getPlaybackReport=function(e){var t=e.filter((function(e){return e.eventType===r.TelemetryEventType.StateChanged})),i=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.CanPlayThrough})),n=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Play})),s=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Start})),o=t.find((function(e){return e.payload===a.HydraPlayerPlaybackState.Playing})),l=null!=i&&null!=n?n.timestamp-i.timestamp:-1,c=null!=n&&null!=s?s.timestamp-n.timestamp:-1,d=null!=s&&null!=o?o.timestamp-s.timestamp:-1,u=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Seeked})),h=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Seeking})),p=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Pause})),g=t.filter((function(e){return e.payload===a.HydraPlayerPlaybackState.Waiting})),m=[r.TelemetryEventType.BitrateChangedDownload,r.TelemetryEventType.BitrateChangedPlayback,r.TelemetryEventType.Error,r.TelemetryEventType.Mute,r.TelemetryEventType.StateChanged,r.TelemetryEventType.Volume,r.TelemetryEventType.StreamOptionsConfigured,r.TelemetryEventType.IgnoredError],f=e.filter((function(e){return e.eventType===r.TelemetryEventType.Error})),v=e.filter((function(e){return e.eventType===r.TelemetryEventType.IgnoredError})),S=e.filter((function(e){return e.eventType===r.TelemetryEventType.Volume||e.eventType===r.TelemetryEventType.Mute})),y=e.filter((function(e){return e.eventType===r.TelemetryEventType.StreamOptionsConfigured})),C=e.filter((function(e){return!m.includes(e.eventType)}));return{playback_timeReadyToPlay:l,playback_timePlayToStart:c,playback_timeStartToPlaying:d,playback_bufferingEvents:this.prepareForTelemetry(g),playback_errorEvents:this.prepareForTelemetry(f),playback_ignoredErrorEvents:this.prepareForTelemetry(v),playback_pauseEvents:this.prepareForTelemetry(p),playback_otherEvents:this.prepareForTelemetry(C),playback_seekedEvents:this.prepareForTelemetry(u),playback_seekingEvents:this.prepareForTelemetry(h),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(S),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(y)}},e.prototype.getBitrateReport=function(e){var t,i,a,s,o=e.filter((function(e){return e.eventType===r.TelemetryEventType.BitrateChangedDownload})),l=o.sort((function(e){return Number(e.payload)})),c=o.length>0?{bitrate_downloadChanges:this.prepareForTelemetry(o),bitrate_downloadChangeCount:o.length>0||-1,bitrate_downloadMin:(null===(t=l[0])||void 0===t?void 0:t.payload)||-1,bitrate_downloadMax:(null===(i=l[l.length-1])||void 0===i?void 0:i.payload)||-1}:{},d=e.filter((function(e){return e.eventType===r.TelemetryEventType.BitrateChangedPlayback})),u=d.sort((function(e){return Number(e.payload)})),h=d.length>0?{bitrate_playbackChanges:this.prepareForTelemetry(d),bitrate_playbackChangeCount:d.length>0||-1,bitrate_playbackMin:(null===(a=u[0])||void 0===a?void 0:a.payload)||-1,bitrate_playbackMax:(null===(s=u[u.length-1])||void 0===s?void 0:s.payload)||-1}:{};return n(n({},c),h)},e.prototype.addNetworkTypeEventListener=function(){var e,t,i,n,r=this;(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)&&(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n||n.addEventListener("change",(function(){r.updateClientNetworkType()})))},e.prototype.updateClientNetworkType=function(){this.clientNetworkType=void 0,this.getClientNetworkType()},e.prototype.getClientNetworkType=function(){var e,t,i,n;if(void 0===this.clientNetworkType){var r="Unknown";if(null===(t=null===(e=window.navigator)||void 0===e?void 0:e.connection)||void 0===t?void 0:t.type)switch(null===(n=null===(i=window.navigator)||void 0===i?void 0:i.connection)||void 0===n?void 0:n.type){case"cellular":r="WWAN";break;case"ethernet":r="Wired";break;case"wifi":r="Wireless";break;default:r="Unknown"}this.clientNetworkType=r}return this.clientNetworkType},e.prototype.getSdnReport=function(e){var t,i,n=e.filter((function(e){return e.name===r.PlayerScenarioType.SdnPluginLoad})),a=n.length>0?n[n.length-1]:void 0;return{sdn_loaded:!(null==a||void 0!==a.failReason),sdn_details:null!==(t=null==a?void 0:a.details)&&void 0!==t?t:"",sdn_error:null!==(i=null==a?void 0:a.failReason)&&void 0!==i?i:"",sdn_events:this.prepareForTelemetry(n)}},e.prototype.getStreamConnectionReport=function(e){var t=e.filter((function(e){return e.name===r.PlayerScenarioType.StreamConnection}));return{stream_connection_events:this.prepareForTelemetry(t)}},e.prototype.getSetSourceReport=function(e){var t=e.filter((function(e){return e.name===r.PlayerScenarioType.SetSource}));return{set_source_events:this.prepareForTelemetry(t)}},e.prototype.registerScenario=function(e,t){var i=this.currentScenarioMap.get(e),n=new o(e,this.stopCrash,t);try{s.assert(null==i,"previous scenario:".concat(s.stringifyObject(i)," is not completed, new scenario:").concat(s.stringifyObject(n)),this.stopCrash)}catch(t){if(e!==r.PlayerScenarioType.LoadHlsFirstFragment&&e!==r.PlayerScenarioType.HlsKeyLoad)throw t}this.currentScenarioMap.set(e,n),this.playerEvents.push(n)},e.prototype.completeScenario=function(e,t,i){var n=this.currentScenarioMap.get(e);try{s.assert(n,"no scenario to complete",this.stopCrash)}catch(t){if(e!==r.PlayerScenarioType.LoadHlsFirstFragment&&e!==r.PlayerScenarioType.HlsKeyLoad)throw t}t?null==n||n.fail(t):(e!==r.PlayerScenarioType.StreamConnection||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),i&&(null==n||n.setDetail(i)),null==n||n.complete()),this.currentScenarioMap.delete(e)},e.prototype.logTelemetryEvent=function(e){this.config.debugLogging&&(this.logFn("debug","PlayerTelemetryEvent: ".concat(JSON.stringify(e))),this.logFn("debug","PlayerDiagnosticData: ".concat(JSON.stringify(this.currentPlayerDiagnosticSnapshot))))},e.prototype.filterAndPrepareTelemetry=function(){var e=this,t=new Set;t.add("serviceLatencyCdg"),t.add("endToEndLatencyCdg"),t.add("videoEdgeLatencyCdg");var i={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((function(n){t.has(n)||(i["player_".concat(n)]=e.prepareForTelemetry(e.currentPlayerDiagnosticSnapshot[n]))})),i},e.prototype.prepareForTelemetry=function(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?null!=e?e:-1:JSON.stringify(e)},e.prototype.getScenario=function(e){return this.currentScenarioMap.get(e)},e.prototype.createTelemetryEvent=function(e,t,i){var n,r,a={eventType:e,timestamp:Date.now(),currentPlayPosition:null!==(r=null===(n=this.currentPlayerDiagnosticSnapshot)||void 0===n?void 0:n.currentPlayPosition)&&void 0!==r?r:-1};return void 0!==t&&(a.payload=this.prepareForTelemetry(t)),a.message=i,a},e.prototype.registerExperimentalEvent=function(e,t,i){var n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.experimentalEvents.length>this.maxPlayerExperimentalEvents&&this.experimentalEvents.splice(0,1),this.logTelemetryEvent(n)},e.prototype.getExperimentalEvents=function(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}},e}();t.LiveStreamStatistic=l},751:function(e,t){var i,n,r,a,s,o;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerType=t.HydraStreamingEventType=t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=void 0,(o=t.HydraStreamDeliveryPipeline||(t.HydraStreamDeliveryPipeline={})).AMS="AMS",o.HLS="MiddleLaneHttpLiveStreaming",o.Ums="MiddleLaneUltraLowLatency",(s=t.HydraPlayerSetupErrorType||(t.HydraPlayerSetupErrorType={})).MultiplePlayerLoad="MultiplePlayerLoad",s.PlayerInitializationFailed="PlayerInitializationFailed",s.InvalidStream="InvalidStream",s.SetSourceFailed="SetSourceFailed",(a=t.HydraPlayerPlaybackState||(t.HydraPlayerPlaybackState={})).LoadStart="loadstart",a.LoadedData="loadeddata",a.LoadedMetadata="loadedmetadata",a.Start="start",a.CanPlayThrough="canplaythrough",a.Play="play",a.Playing="playing",a.Pause="pause",a.Waiting="waiting",a.Seeking="seeking",a.Seeked="seeked",a.Ended="ended",a.Error="error",a.Destroyed="destroyed",a.Initialized="initialized",a.Stalled="stalled",a.VolumeChange="volumechange",a.PlaybackBitrateChanged="playbackbitratechanged",a.DownloadBitrateChanged="downloadbitratechanged",a.HlsKeyLoading="hlsKeyLoading",a.HlsKeyLoaded="hlsKeyLoaded",a.HlsKeyLoadedFailed="hlsKeyLoadedFailed",a.HlsManifestLoading="hlsManifestLoading",a.HlsManifestLoaded="hlsManifestLoaded",a.HlsManifestLoadedFailed="hlsManifestLoadedFailed",a.HlsFirstFragmentLoading="hlsFragLoading",a.HlsFirstFragmentBuffered="hlsFragBuffered",a.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",a.Online="online",a.Offline="offline",a.NetworkChange="networkChange",(r=t.HydraPlayerPlaybackErrorType||(t.HydraPlayerPlaybackErrorType={})).UnsupportedPlatform="UnsupportedPlatform",r.NetworkError="NetworkError",r.PlaybackRetried="PlaybackRetried",r.PlaybackError="PlaybackError",r.Unknown="Unknown",(n=t.HydraStreamingEventType||(t.HydraStreamingEventType={})).TLE="TLE",n.Overflow="Overflow",n.TownHallBasic="TownHall_Basic",n.TownHallPremium="TownHall_Premium",n.TownHall="TownHall",(i=t.HydraPlayerType||(t.HydraPlayerType={}))[i.Hls=1]="Hls",i[i.Ums=2]="Ums"},979:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0}),r(i(165),t),r(i(751),t)},165:function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)},r=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){s.label=o[1];break}if(6===o[0]&&s.label<r[1]){s.label=r[1],r=o;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(o);break}r[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}},s=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,a=t.length;r<a;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.UmsHydraPlayer=t.getSdkVersion=void 0;var o=i(124),l=i(68),c=i(328),d=i(844),u=i(63),h=i(458),p=i(329),g=i(944);t.getSdkVersion=function(){return"4.2488.1"};var m=function(){function e(e,t){this.playerSettings=e,this.eventHandler=t,this.spinner=null,this.commandResultsMap=new Map,this._onMessage=this.onMessage.bind(this),this.telemetryReportHandler=null,this.playerInternalEventHandler=null,this.playerRuntimeJsUrls=this.getRuntimeJsUrls(),this.playerSettings.hydraPlayerSdkVersion="4.2488.1"}return Object.defineProperty(e.prototype,"contextWindow",{get:function(){var e;return null===(e=this.container)||void 0===e?void 0:e.ownerDocument.defaultView},enumerable:!1,configurable:!0}),e.prototype.getRuntimeJsUrls=function(){if(!Array.isArray(this.playerSettings.playerRuntimeJsUrls)){var e=(0,p.getMajorFromVersion)("4.2488.1");return e&&this.playerSettings.playerRuntimeJsUrls[e]||[]}return this.playerSettings.playerRuntimeJsUrls},e.prototype.initializeIFrame=function(e){return r(this,void 0,void 0,(function(){var t;return a(this,(function(i){switch(i.label){case 0:return this.container=e,0===this.playerRuntimeJsUrls.length?[2,{initSucceeded:!1,initStartTime:Date.now(),initDuration:0,runtimeDownloadResults:[],errorMsg:"No compatible runtime URL provided for version ".concat("4.2488.1",', URLs: "').concat((0,p.stringifyObject)(this.playerSettings.playerRuntimeJsUrls),'"')}]:[4,(0,p.createIFrame)(e,this.playerRuntimeJsUrls,this.playerSettings.maxRetryCountForLoadingResources,this.playerSettings.disableSandbox,this.playerSettings.hydraRuntimeFetchTimeout)];case 1:return(t=i.sent()).initResult.initSucceeded&&t.iframe&&(this.iframe=t.iframe,this.contextWindow.addEventListener("message",this._onMessage)),[2,t.initResult]}}))}))},e.prototype.setup=function(e){return r(this,void 0,void 0,(function(){var t;return a(this,(function(i){switch(i.label){case 0:return this.spinner=new p.Spinner(e),[4,this.initializeIFrame(e)];case 1:return t=i.sent(),this.telemetryReportHandler=new v(this.playerSettings,this.eventHandler.log.bind(this.eventHandler),t,this.spinner),this.playerInternalEventHandler=new f(this.spinner,this.telemetryReportHandler),t.initSucceeded?[4,this.sendCommand("createUmsHydraPlayer",this.playerSettings,t)]:[3,3];case 2:return i.sent(),[2,!0];case 3:return this.eventHandler.log("error","Failed to setup HydraPlayer: ".concat(t.errorMsg)),this.spinner.hide(),[2,!1]}}))}))},e.prototype.isIFrameCommunicationActive=function(){var e;return!!(null===(e=this.iframe)||void 0===e?void 0:e.contentWindow)&&!!this.contextWindow},e.prototype.getFullTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getFullTelemetryReport())||{}},e.prototype.getSnapshotTelemetryReport=function(){var e;return(null===(e=this.telemetryReportHandler)||void 0===e?void 0:e.getSnapshotTelemetryReport())||{}},e.prototype.callPlayerApi=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return r(this,void 0,void 0,(function(){return a(this,(function(i){switch(i.label){case 0:return this.iframe?[4,this.sendCommand.apply(this,s([e],t,!1))]:[3,2];case 1:case 3:return[2,i.sent()];case 2:return[4,Promise.reject(new Error("Hydra IFrame not initialized yet"))]}}))}))},e.prototype.dispose=function(){var e;null===(e=this.telemetryReportHandler)||void 0===e||e.addDisposeTelemetry(),this.isIFrameCommunicationActive()&&this.sendCommand("disposeHydraPlayer")},e.prototype.release=function(){var e;null===(e=this.spinner)||void 0===e||e.hide(),this.contextWindow&&this.contextWindow.removeEventListener("message",this._onMessage),this.iframe&&this.container&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe)},e.prototype.sendCommand=function(e){for(var t,i,n=[],s=1;s<arguments.length;s++)n[s-1]=arguments[s];return r(this,void 0,void 0,(function(){var r,s,l;return a(this,(function(a){switch(a.label){case 0:if(r={msgType:o.MessageType.Command,name:e,args:n},!this.isIFrameCommunicationActive())throw new Error("IFrame MessageAPI communication not active");return void 0!==(s=this.commandResultsMap.get(e.toString()))&&s.reject(new Error("function ".concat(e," is invoked again, before previous call is completed"))),l=g.defer(),this.commandResultsMap.set(e,l),null===(i=null===(t=this.iframe)||void 0===t?void 0:t.contentWindow)||void 0===i||i.postMessage(r,"*"),[4,l.promise];case 1:return[2,a.sent()]}}))}))},e.prototype.onMessage=function(e){switch(e.data.msgType){case o.MessageType.PlayerEvent:this.processPlayerEvent(e.data);break;case o.MessageType.InternalPlayerEvent:this.processInternalPlayerEvent(e.data);break;case o.MessageType.CommandSuccessResult:this.processCommandSuccessResult(e.data);break;case o.MessageType.CommandFailureResult:this.processCommandFailureResult(e.data)}},e.prototype.processCommandSuccessResult=function(e){var t=this.commandResultsMap.get(e.name.toString());void 0!==t&&(t.resolve(e.result),this.commandResultsMap.delete(e.name.toString()))},e.prototype.processCommandFailureResult=function(e){var t=this.commandResultsMap.get(e.name.toString());void 0!==t&&(t.reject(e.error),this.commandResultsMap.delete(e.name.toString()))},e.prototype.processPlayerEvent=function(e){this.eventHandler[e.name].apply(this.eventHandler,e.args)},e.prototype.processInternalPlayerEvent=function(e){this.playerInternalEventHandler&&this.playerInternalEventHandler[e.name].apply(this,e.args)},e}();t.UmsHydraPlayer=m;var f=function(){function e(e,t){this.spinner=e,this.telemetryReportHandler=t}return e.prototype.firstPlayerLoadAttemptDone=function(){this.spinner.hide()},e.prototype.fullTelemetryReportUpdated=function(e){this.telemetryReportHandler.setFullTelemetryReport(e)},e.prototype.snapshotTelemetryReportUpdated=function(e){this.telemetryReportHandler.setSnapshotTelemetryReport(e)},e}(),v=function(){function e(e,t,i,n){var r=this;this.logFn=t,this.spinner=n;var a=new h.LiveStreamStatistic(e,(function(e,t){r.logFn(e,t)}),{currentPlayPosition:[],playbackRate:[],statsInterval:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[]},{hydraPlayerSdkVersion:e.hydraPlayerSdkVersion||"Unknown",hydraPlayerType:c.HydraPlayerType.Ums},i);this.fullTelemetryReport=a.getReport(),this.snapshotTelemetryReport=a.getSnapshotReport()}return e.prototype.getFullTelemetryReport=function(){return this.fullTelemetryReport},e.prototype.getSnapshotTelemetryReport=function(){return this.snapshotTelemetryReport},e.prototype.setFullTelemetryReport=function(e){var t,i,r;this.fullTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(t=this.spinner.firstShowTimestamp)&&void 0!==t?t:-1,init_spinnerHideTimestamp:null!==(i=this.spinner.firstHideTimestamp)&&void 0!==i?i:-1,init_spinnerDuration:null!==(r=this.spinner.firstSpinnerDuration)&&void 0!==r?r:-1,init_spinnerVisible:this.spinner.isVisible()})},e.prototype.setSnapshotTelemetryReport=function(e){var t,i,r;this.snapshotTelemetryReport=n(n({},e),{init_spinnerShowTimestamp:null!==(t=this.spinner.firstShowTimestamp)&&void 0!==t?t:-1,init_spinnerHideTimestamp:null!==(i=this.spinner.firstHideTimestamp)&&void 0!==i?i:-1,init_spinnerDuration:null!==(r=this.spinner.firstSpinnerDuration)&&void 0!==r?r:-1,init_spinnerVisible:this.spinner.isVisible()})},e.prototype.addDisposeTelemetry=function(){var e=Date.now();try{this.updateInitEventsWithDisposeEvent(this.fullTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in full telemetry report")}try{this.updateInitEventsWithDisposeEvent(this.snapshotTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to init_allEvents telemetry field in snapshot telemetry report")}try{this.updateStateChangeEventsWithDisposeEvent(this.fullTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in full telemetry report")}try{this.updateStateChangeEventsWithDisposeEvent(this.snapshotTelemetryReport,e)}catch(e){this.logFn("warn","Failed to add player destroyed information to playback_stateChangeEvents telemetry field in snapshot telemetry report")}this.fullTelemetryReport.hydraDisposeTimestamp=e,this.snapshotTelemetryReport.hydraDisposeTimestamp=e},e.prototype.updateInitEventsWithDisposeEvent=function(e,t){var i=e.init_allEvents,n=JSON.parse(i);n[n.length-1].name!==d.PlayerScenarioType.Destroyed&&n.push({name:d.PlayerScenarioType.Destroyed,startTime:t,duration:0,details:u.HydraPlayerDestroyedReason.PlayerStopped}),e.init_allEvents=(0,p.stringifyObject)(n)},e.prototype.updateStateChangeEventsWithDisposeEvent=function(e,t){var i=e.playback_stateChangeEvents,n=JSON.parse(i);n[n.length-1].payload!==l.HydraPlayerPlaybackState.Destroyed&&n.push({eventType:d.TelemetryEventType.StateChanged,timestamp:t,currentPlayPosition:-1,payload:l.HydraPlayerPlaybackState.Destroyed}),e.playback_stateChangeEvents=(0,p.stringifyObject)(n)},e}()},124:function(e,t){var i;Object.defineProperty(t,"__esModule",{value:!0}),t.MessageType=void 0,(i=t.MessageType||(t.MessageType={})).Command="Command",i.CommandSuccessResult="CommandSuccessResult",i.CommandFailureResult="CommandFailureResult",i.PlayerEvent="PlayerEvent",i.InternalPlayerEvent="InternalPlayerEvent"},63:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraSupportedSDN=t.HydraPlayerDestroyedReason=void 0,(n=t.HydraPlayerDestroyedReason||(t.HydraPlayerDestroyedReason={})).PlayerStopped="PlayerStopped",n.PlaybackError="PlaybackError",(i=t.HydraSupportedSDN||(t.HydraSupportedSDN={})).Hive="hive",i.Kollective="kollective",i.Ramp="ramp",i.Peer5="peer5",i.Microsoft="microsoft"},844:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.PlayerScenarioType=t.TelemetryEventType=void 0,(n=t.TelemetryEventType||(t.TelemetryEventType={})).BitrateChangedDownload="BitrateChangedDownload",n.StreamOptionsConfigured="StreamOptionsConfigured",n.BitrateChangedPlayback="BitrateChangedPlayback",n.CaptionsToggled="CaptionsToggled",n.Error="Error",n.IgnoredError="IgnoredError",n.FullscreenChanged="FullscreenChanged",n.Mute="Mute",n.PotentialMediaFreeze="PotentialMediaFreeze",n.StateChanged="StateChanged",n.HydraInputStateChanged="HydraInputStateChanged",n.HydraOutputStateChanged="HydraOutputStateChanged",n.Volume="Volume",n.Buffering="Buffering",n.Online="Online",n.Offline="Offline",n.NetworkChange="NetworkChange",n.HlsEvents="HlsEvents",(i=t.PlayerScenarioType||(t.PlayerScenarioType={})).LoadHydra="LoadHydra",i.LoadHlsScript="LoadHlsScript",i.LoadPlayer="LoadPlayer",i.Load="Load",i.LoadHlsAuthCookie="LoadHlsAuthCookie",i.HlsManifestLoad="HlsManifestLoad",i.HlsKeyLoad="HlsKeyLoad",i.LoadHlsFirstFragment="LoadHlsFirstFragment",i.SetSource="SetSource",i.SdnPluginLoad="SdnPluginLoad",i.ThaPluginLoad="ThaPluginLoad",i.HydraPipelineInitialization="HydraPipelineInitialization",i.Destroyed="Destroyed",i.Setup="Setup",i.StreamConnection="StreamConnection"},328:function(e,t){var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerType=t.HydraStreamingEventType=void 0,(n=t.HydraStreamingEventType||(t.HydraStreamingEventType={})).TLE="TLE",n.Overflow="Overflow",n.TownHallBasic="TownHall_Basic",n.TownHallPremium="TownHall_Premium",n.TownHall="TownHall",(i=t.HydraPlayerType||(t.HydraPlayerType={}))[i.Hls=1]="Hls",i[i.Ums=2]="Ums"},68:function(e,t){var i,n,r,a;Object.defineProperty(t,"__esModule",{value:!0}),t.HydraPlayerPlaybackErrorType=t.HydraPlayerPlaybackState=t.HydraPlayerSetupErrorType=t.HydraStreamDeliveryPipeline=void 0,(a=t.HydraStreamDeliveryPipeline||(t.HydraStreamDeliveryPipeline={})).AMS="AMS",a.HLS="MiddleLaneHttpLiveStreaming",a.Ums="MiddleLaneUltraLowLatency",(r=t.HydraPlayerSetupErrorType||(t.HydraPlayerSetupErrorType={})).MultiplePlayerLoad="MultiplePlayerLoad",r.PlayerInitializationFailed="PlayerInitializationFailed",r.InvalidStream="InvalidStream",r.SetSourceFailed="SetSourceFailed",(n=t.HydraPlayerPlaybackState||(t.HydraPlayerPlaybackState={})).LoadStart="loadstart",n.LoadedData="loadeddata",n.LoadedMetadata="loadedmetadata",n.Start="start",n.CanPlayThrough="canplaythrough",n.Play="play",n.Playing="playing",n.Pause="pause",n.Waiting="waiting",n.Seeking="seeking",n.Seeked="seeked",n.Ended="ended",n.Error="error",n.Destroyed="destroyed",n.Initialized="initialized",n.Stalled="stalled",n.VolumeChange="volumechange",n.PlaybackBitrateChanged="playbackbitratechanged",n.DownloadBitrateChanged="downloadbitratechanged",n.HlsKeyLoading="hlsKeyLoading",n.HlsKeyLoaded="hlsKeyLoaded",n.HlsKeyLoadedFailed="hlsKeyLoadedFailed",n.HlsManifestLoading="hlsManifestLoading",n.HlsManifestLoaded="hlsManifestLoaded",n.HlsManifestLoadedFailed="hlsManifestLoadedFailed",n.HlsFirstFragmentLoading="hlsFragLoading",n.HlsFirstFragmentBuffered="hlsFragBuffered",n.HlsFirstFragmentLoadFailed="hlsFirstFragmentLoadFailed",n.Online="online",n.Offline="offline",n.NetworkChange="networkChange",(i=t.HydraPlayerPlaybackErrorType||(t.HydraPlayerPlaybackErrorType={})).UnsupportedPlatform="UnsupportedPlatform",i.NetworkError="NetworkError",i.PlaybackRetried="PlaybackRetried",i.PlaybackError="PlaybackError",i.Unknown="Unknown"},944:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.defer=void 0,t.defer=function(){var e,t;return{promise:new Promise((function(i,n){e=i,t=n})),resolve:e,reject:t}}},329:function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&o[0]?n.return:o[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,o[1])).done)return r;switch(n=0,r&&(o=[2&o[0],r.value]),o[0]){case 0:case 1:r=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!r||o[1]>r[0]&&o[1]<r[3])){s.label=o[1];break}if(6===o[0]&&s.label<r[1]){s.label=r[1],r=o;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(o);break}r[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{i=r=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createVideoElement=t.createVideoElementDiv=t.showPlayerControls=t.getSdnStats=t.Spinner=t.repeatUntilCancel=t.wait=t.stringifyError=t.stringifyObject=t.getRandomHexString=t.getPlayerSetting=t.getECSSetting=t.assert=t.createIFrame=t.getMajorFromVersion=void 0;var a=i(63),s=i(328);function o(e,t,i,a,s){return n(this,void 0,void 0,(function(){var o,l,d,h,p=this;return r(this,(function(g){switch(g.label){case 0:return o=100,l=Date.now(),[4,c(i,d={trackingRef:"",timeTakenToDownloadScript:-1},s).catch((function(e){return n(p,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return t="Failed to get IFrame source: ".concat(u(e)),a.push({success:!1,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript,errorMsg:t}),a.length>o&&a.shift(),[4,Promise.reject(new Error(t))];case 1:return[2,n.sent()]}}))}))}))];case 1:return h=g.sent(),t.srcdoc=h,e.appendChild(t),[4,new Promise((function(e,n){t.onload=function(){a.push({success:!0,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript}),a.length>o&&a.shift(),e()},t.onerror=function(e){var t="Failed to load HydraPlayer IFrame: ".concat(u(e));a.push({success:!1,url:i,startTime:l,duration:Date.now()-l,trackingReference:d.trackingRef,timeTakenToDownloadScript:d.timeTakenToDownloadScript,errorMsg:t}),a.length>o&&a.shift(),n(new Error(t))}}))];case 2:return g.sent(),[2]}}))}))}function l(e,t){return n(this,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,e(t).catch((function(a){return n(i,void 0,void 0,(function(){var i=this;return r(this,(function(s){switch(s.label){case 0:return 0!=--t?[3,2]:[4,Promise.reject(a)];case 1:case 3:return[2,s.sent()];case 2:return[4,new Promise((function(s){return setTimeout((function(){s(l(e,t).catch((function(e){return n(i,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(new Error("".concat(u(a)).concat(", ",u(e))))];case 1:return[2,t.sent()]}}))}))})))}),100)}))]}}))}))}))];case 1:return a.sent(),[2]}}))}))}function c(e,t,i){return n(this,void 0,void 0,(function(){var a,s,o,l=this;return r(this,(function(c){switch(c.label){case 0:return a=Date.now(),[4,d(e,t,i).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,Promise.reject(e)];case 1:return[2,t.sent()]}}))}))}))];case 1:return s=c.sent(),o="<script> ".concat(s,"<\/script>"),t.timeTakenToDownloadScript=Date.now()-a,[2,"\n        <html class style='height: 100%; width: 100%; overflow: hidden'>\n        <head></head>\n        <body class style='height: 100%; width: 100%; margin: 0px'>\n            ".concat(o,"\n        </body>\n        </html>\n    ")]}}))}))}function d(e,t,i){return n(this,void 0,void 0,(function(){var a,s,o,l=this;return r(this,(function(c){switch(c.label){case 0:return a=function(e,t){var i,n;return t.includes("vz")?null!==(n=e.headers.get("uuid"))&&void 0!==n?n:"":null!==(i=e.headers.get("X-Azure-Ref"))&&void 0!==i?i:""},i?(s=new AbortController,o=setTimeout((function(){s.abort()}),i),[4,fetch(e,{signal:s.signal,cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return clearTimeout(o),i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=a(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,t.text().then((function(a){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return a?[2,a]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,a.sent()]}}))}))})).catch((function(e){return n(l,void 0,void 0,(function(){return r(this,(function(t){throw clearTimeout(o),e}))}))}))]):[3,2];case 1:case 3:return[2,c.sent()];case 2:return[4,fetch(e,{cache:"no-cache"}).then((function(i){return n(l,void 0,void 0,(function(){return r(this,(function(n){switch(n.label){case 0:return i.ok?[3,2]:[4,Promise.reject(new Error("".concat(i.status)))];case 1:return[2,n.sent()];case 2:return t.trackingRef=a(i,e),[2,i]}}))}))})).then((function(t){return n(l,void 0,void 0,(function(){var i=this;return r(this,(function(a){switch(a.label){case 0:return[4,t.text().then((function(a){return n(i,void 0,void 0,(function(){return r(this,(function(i){switch(i.label){case 0:return a?[2,a]:[3,1];case 1:return[4,Promise.reject(new Error("".concat(t.status,", script ").concat(e," contents are null")))];case 2:return[2,i.sent()]}}))}))}))];case 1:return[2,a.sent()]}}))}))}))]}}))}))}function u(e){try{if(!e)return"".concat(e);if(e instanceof Map)return i={},e.forEach((function(e,t){i[t.toString()]=e})),JSON.stringify(i);var t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}catch(e){return""}var i}function h(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,new Promise((function(t){return setTimeout(t,e)}))];case 1:return t.sent(),[2]}}))}))}t.getMajorFromVersion=function(e){var t=e.match(/^(\d+)\.\d+\.\d+(-.*)?$/);return t?t[1]:null},t.createIFrame=function(e,t,i,a,s){return void 0===a&&(a=!1),n(this,void 0,void 0,(function(){var c,d,h,p,g=this;return r(this,(function(m){switch(m.label){case 0:return c=[],d=Date.now(),(h=e.ownerDocument.createElement("iframe")).id="player-iframe",a||h.sandbox.add("allow-scripts"),h.allowFullscreen=!0,h.allow="camera; microphone; autoplay",h.style.height="100%",h.style.width="100%",h.style.border="none",p=function(e){return t[e%t.length]},[4,l((function(t){return n(g,void 0,void 0,(function(){var i;return r(this,(function(n){switch(n.label){case 0:return i=p(t),[4,o(e,h,i,c,s)];case 1:return n.sent(),[2]}}))}))}),i).then((function(){return{iframe:h,initResult:{initSucceeded:!0,initStartTime:d,initDuration:Date.now()-d,runtimeDownloadResults:c}}})).catch((function(e){return n(g,void 0,void 0,(function(){var i;return r(this,(function(n){return i="Failed to load Hydra player runtime scripts, src: ",t.forEach((function(e){return i=i.concat(e,", ")})),i+="errors: ".concat(u(e)),[2,{initResult:{initSucceeded:!1,initStartTime:d,initDuration:Date.now()-d,runtimeDownloadResults:c,errorMsg:i}}]}))}))}))];case 1:return[2,m.sent()]}}))}))},t.assert=function(e,t,i){if(void 0===i&&(i=!1),!e){if(!i)throw new Error("Assert failed".concat(void 0!==t?": ".concat(t):""));console.error("Assert failed".concat(void 0!==t?": ".concat(t):""))}},t.getECSSetting=function(e,t,i){var n,r=i,a=null===(n=e.ecsSettings)||void 0===n?void 0:n[t];return typeof a==typeof r&&(r=a),r},t.getPlayerSetting=function(e,t){var i;return void 0!==(null===(i=e.ecsSettings)||void 0===i?void 0:i[t])?e.ecsSettings[t]:e[t]},t.getRandomHexString=function(e){return Array.from(Array(e)).map((function(){return Math.floor(16*Math.random()).toString(16)})).join("")},t.stringifyObject=u,t.stringifyError=function(e){return e instanceof Error?e.message:u(e)},t.wait=h,t.repeatUntilCancel=function(e,t,i,a){var s=!1,o=a||console.log;return o("RepeatUntilCancel starting task: ".concat(e)),n(this,void 0,void 0,(function(){var n,a,l;return r(this,(function(r){switch(r.label){case 0:return s?[3,2]:(n=new Date,t(),a=(new Date).getTime()-n.getTime(),(l=i-a)<0&&(l=i+l%i,o("Skipping execution for ".concat(e,", last execution took: ").concat(a," ms, delayMs: ").concat(i),"warn")),[4,h(l)]);case 1:return r.sent(),[3,0];case 2:return[2]}}))})),function(){o("RepeatUntilCancel stopping task: ".concat(e)),s=!0}};var p=function(){function e(e){this.container=e,this.spinnerId="hydra-player-spinner",this.firstSpinnerShowTimestamp=null,this.firstSpinnerHideTimestamp=null,this.spinnerInfoHistory=[],this.maxTimestampHistorySize=100;var t=this.container.ownerDocument.getElementById(this.spinnerId);if(t)return this.spinner=t,void this.show();var i=this.container.ownerDocument.createElement("style");i.textContent="\n            .ml-player-spinner-container {\n                width: 100%;\n                height: 100%;\n                display: flex;\n                justify-content: center;\n                align-items: center;\n                position: absolute;\n                pointer-events: none;\n            }\n            .ml-player-spinner {\n                width: 3.6rem;\n                height: 3.6rem;\n                display: block;\n                overflow-clip-margin: content-box;\n                overflow: hidden;\n                animation: ml-player-spinner-outer-rotate 3s linear infinite;\n            }\n            .ml-player-spinner-dark-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(68, 71, 145);\n                stroke-width: 8px;\n            }\n            .ml-player-spinner-light-wheel {\n                fill: none;\n                r: 45%;\n                cx: 50%;\n                cy: 50%;\n                stroke: rgb(127, 133, 245);\n                stroke-width: 8px;\n                stroke-dasharray: 283;\n                stroke-dashoffset: 280;\n                stroke-linecap: round;\n                transform-origin: 50% 50%;\n                animation: ml-player-spinner-inner-rotate 1.5s cubic-bezier(0.33, 0, 0.67, 1) infinite;\n            }\n            @keyframes ml-player-spinner-outer-rotate {\n                0% {\n                    transform: rotate(0deg);\n                }\n                100% {\n                    transform: rotate(360deg);\n                }\n            }\n            @keyframes ml-player-spinner-inner-rotate {\n                0% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                25% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(0deg);\n                }\n                50% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                75% {\n                    stroke-dashoffset: 75;\n                    transform: rotate(45deg);\n                }\n                100% {\n                    stroke-dashoffset: 283;\n                    transform: rotate(360deg);\n                }\n            }\n        ",this.container.ownerDocument.head.appendChild(i),this.container.style.position="relative";var n=this.container.ownerDocument.createElement("div");n.classList.add("ml-player-spinner-container"),this.container.appendChild(n),this.spinner=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","svg"),this.spinner.style.position="absolute",this.spinner.setAttribute("viewBox","0 0 100 100"),this.spinner.classList.add("ml-player-spinner"),this.spinner.id=this.spinnerId,n.appendChild(this.spinner);var r=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");r.classList.add("ml-player-spinner-dark-wheel"),this.spinner.appendChild(r);var a=this.container.ownerDocument.createElementNS("http://www.w3.org/2000/svg","circle");a.classList.add("ml-player-spinner-light-wheel"),this.spinner.appendChild(a),this.show()}return Object.defineProperty(e.prototype,"firstShowTimestamp",{get:function(){return this.firstSpinnerShowTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstHideTimestamp",{get:function(){return this.firstSpinnerHideTimestamp},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"firstSpinnerDuration",{get:function(){return this.firstSpinnerShowTimestamp?this.firstSpinnerHideTimestamp?this.firstSpinnerHideTimestamp-this.firstSpinnerShowTimestamp:Date.now()-this.firstSpinnerShowTimestamp:null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"visibilityHistory",{get:function(){if(this.spinnerInfoHistory.length>0){var e=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];e.hideTimestamp||(e.displayDuration=Date.now()-e.showTimestamp)}return this.spinnerInfoHistory},enumerable:!1,configurable:!0}),e.prototype.show=function(){var e=Date.now();this.firstSpinnerShowTimestamp||(this.firstSpinnerShowTimestamp=e),(0===this.spinnerInfoHistory.length||this.spinnerInfoHistory[this.spinnerInfoHistory.length-1].hideTimestamp)&&(this.spinnerInfoHistory.push({showTimestamp:e,displayDuration:0}),this.spinnerInfoHistory.length>this.maxTimestampHistorySize&&this.spinnerInfoHistory.splice(0,1)),this.spinner.style.display="block"},e.prototype.hide=function(){var e=Date.now();if(this.firstSpinnerHideTimestamp||(this.firstSpinnerHideTimestamp=e),this.spinnerInfoHistory.length>0){var t=this.spinnerInfoHistory[this.spinnerInfoHistory.length-1];t.hideTimestamp||(t.hideTimestamp=e,t.displayDuration=e-t.showTimestamp)}this.spinner.style.display="none"},e.prototype.isVisible=function(){return"none"!==this.spinner.style.display},e}();t.Spinner=p,t.getSdnStats=function(e,t){(null==e?void 0:e.peer5)&&(t.sdnName=e.peer5?a.HydraSupportedSDN.Microsoft:"",t.sdnVersion=e.peer5?e.peer5.version:"","function"==typeof e.peer5.getStats&&(t.sdnStats=e.peer5.getStats(),t.isP2PSdnUsed=e.peer5.getStats().numOfPeers>0))},t.showPlayerControls=function(e){return void 0!==e.allowPlayerControls?e.allowPlayerControls:e.streamingEventType===s.HydraStreamingEventType.TLE},t.createVideoElementDiv=function(e,t,i){i("createVideoElementDiv started");var n=t.ownerDocument.createElement("div");return n.id=e,n.style.position="relative",n.style.width="100%",n.style.height="100%",t.appendChild(n),i("createVideoElementDiv done"),n},t.createVideoElement=function(e,t,i,n,r){r("createVideoElement started");var a=t.ownerDocument.createElement("video");a.controls=n,a.id=e,a.setAttribute("playsinline","");var s=i.videoLang;s&&(a.setAttribute("lang",s),r("createVideoElement: language set to ".concat(s)));for(var o=i.videoElementStyles,l=0;l<o.length;l++)a.classList.add(o[l]);return a.style.width="100%",a.style.height="100%",a.style.position="absolute",a.muted=i.muteVideo,a.addEventListener("contextmenu",(function(e){e.preventDefault()})),["play","pause","stop","seekbackward","seekforward","seekto","previoustrack","nexttrack"].forEach((function(e){try{navigator.mediaSession.setActionHandler(e,(function(){}))}catch(e){}})),t.appendChild(a),r("createVideoElement done"),a}}},t={},function i(n){var r=t[n];if(void 0!==r)return r.exports;var a=t[n]={exports:{}};return e[n].call(a.exports,a,a.exports,i),a.exports}(979);var e,t},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e.hydra_player_ums_sdk=n():i.hydra_player_ums_sdk=n()}}),K=u({"../node_modules/pako/lib/utils/common.js"(e){var t="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(e,t){return Object.prototype.hasOwnProperty.call(e,t)}e.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(var r in n)i(n,r)&&(e[r]=n[r])}}return e},e.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),r);else for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){var t,i,n,r,a,s;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(s=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)a=e[t],s.set(a,r),r+=a.length;return s}},r={arraySet:function(e,t,i,n,r){for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){return[].concat.apply([],e)}};e.setTyped=function(t){t?(e.Buf8=Uint8Array,e.Buf16=Uint16Array,e.Buf32=Int32Array,e.assign(e,n)):(e.Buf8=Array,e.Buf16=Array,e.Buf32=Array,e.assign(e,r))},e.setTyped(t)}}),J=u({"../node_modules/pako/lib/zlib/trees.js"(e){var t=K();function i(e){for(var t=e.length;--t>=0;)e[t]=0}var n=256,r=286,a=30,s=15,o=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],l=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],c=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],d=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],u=new Array(576);i(u);var h=new Array(60);i(h);var p=new Array(512);i(p);var g=new Array(256);i(g);var m=new Array(29);i(m);var f,v,S,y=new Array(a);function C(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function _(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function E(e){return e<256?p[e]:p[256+(e>>>7)]}function T(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function b(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,T(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function I(e,t,i){b(e,i[2*t],i[2*t+1])}function w(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function R(e,t,i){var n,r,a=new Array(16),o=0;for(n=1;n<=s;n++)a[n]=o=o+i[n-1]<<1;for(r=0;r<=t;r++){var l=e[2*r+1];0!==l&&(e[2*r]=w(a[l]++,l))}}function A(e){var t;for(t=0;t<r;t++)e.dyn_ltree[2*t]=0;for(t=0;t<a;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function P(e){e.bi_valid>8?T(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function M(e,i,n,r){P(e),r&&(T(e,n),T(e,~n)),t.arraySet(e.pending_buf,e.window,i,n,e.pending),e.pending+=n}function k(e,t,i,n){var r=2*t,a=2*i;return e[r]<e[a]||e[r]===e[a]&&n[t]<=n[i]}function D(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&k(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!k(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function O(e,t,i){var r,a,s,c,d=0;if(0!==e.last_lit)do{r=e.pending_buf[e.d_buf+2*d]<<8|e.pending_buf[e.d_buf+2*d+1],a=e.pending_buf[e.l_buf+d],d++,0===r?I(e,a,t):(I(e,(s=g[a])+n+1,t),0!==(c=o[s])&&b(e,a-=m[s],c),I(e,s=E(--r),i),0!==(c=l[s])&&b(e,r-=y[s],c))}while(d<e.last_lit);I(e,256,t)}function N(e,t){var i,n,r,a=t.dyn_tree,o=t.stat_desc.static_tree,l=t.stat_desc.has_stree,c=t.stat_desc.elems,d=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<c;i++)0!==a[2*i]?(e.heap[++e.heap_len]=d=i,e.depth[i]=0):a[2*i+1]=0;for(;e.heap_len<2;)a[2*(r=e.heap[++e.heap_len]=d<2?++d:0)]=1,e.depth[r]=0,e.opt_len--,l&&(e.static_len-=o[2*r+1]);for(t.max_code=d,i=e.heap_len>>1;i>=1;i--)D(e,a,i);r=c;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],D(e,a,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,a[2*r]=a[2*i]+a[2*n],e.depth[r]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,a[2*i+1]=a[2*n+1]=r,e.heap[1]=r++,D(e,a,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,r,a,o,l,c=t.dyn_tree,d=t.max_code,u=t.stat_desc.static_tree,h=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,g=t.stat_desc.extra_base,m=t.stat_desc.max_length,f=0;for(a=0;a<=s;a++)e.bl_count[a]=0;for(c[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(a=c[2*c[2*(n=e.heap[i])+1]+1]+1)>m&&(a=m,f++),c[2*n+1]=a,n>d||(e.bl_count[a]++,o=0,n>=g&&(o=p[n-g]),l=c[2*n],e.opt_len+=l*(a+o),h&&(e.static_len+=l*(u[2*n+1]+o)));if(0!==f){do{for(a=m-1;0===e.bl_count[a];)a--;e.bl_count[a]--,e.bl_count[a+1]+=2,e.bl_count[m]--,f-=2}while(f>0);for(a=m;0!==a;a--)for(n=e.bl_count[a];0!==n;)(r=e.heap[--i])>d||(c[2*r+1]!==a&&(e.opt_len+=(a-c[2*r+1])*c[2*r],c[2*r+1]=a),n--)}}(e,t),R(a,d,e.bl_count)}function L(e,t,i){var n,r,a=-1,s=t[1],o=0,l=7,c=4;for(0===s&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=s,s=t[2*(n+1)+1],++o<l&&r===s||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==a&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,a=r,0===s?(l=138,c=3):r===s?(l=6,c=3):(l=7,c=4))}function x(e,t,i){var n,r,a=-1,s=t[1],o=0,l=7,c=4;for(0===s&&(l=138,c=3),n=0;n<=i;n++)if(r=s,s=t[2*(n+1)+1],!(++o<l&&r===s)){if(o<c)do{I(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==a&&(I(e,r,e.bl_tree),o--),I(e,16,e.bl_tree),b(e,o-3,2)):o<=10?(I(e,17,e.bl_tree),b(e,o-3,3)):(I(e,18,e.bl_tree),b(e,o-11,7));o=0,a=r,0===s?(l=138,c=3):r===s?(l=6,c=3):(l=7,c=4)}}function F(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<n;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}i(y);var U=!1;function B(e,t,i,n){b(e,0+(n?1:0),3),M(e,t,i,!0)}e._tr_init=function(e){U||(function(){var e,t,i,n,d,_=new Array(16);for(i=0,n=0;n<28;n++)for(m[n]=i,e=0;e<1<<o[n];e++)g[i++]=n;for(g[i-1]=n,d=0,n=0;n<16;n++)for(y[n]=d,e=0;e<1<<l[n];e++)p[d++]=n;for(d>>=7;n<a;n++)for(y[n]=d<<7,e=0;e<1<<l[n]-7;e++)p[256+d++]=n;for(t=0;t<=s;t++)_[t]=0;for(e=0;e<=143;)u[2*e+1]=8,e++,_[8]++;for(;e<=255;)u[2*e+1]=9,e++,_[9]++;for(;e<=279;)u[2*e+1]=7,e++,_[7]++;for(;e<=287;)u[2*e+1]=8,e++,_[8]++;for(R(u,287,_),e=0;e<a;e++)h[2*e+1]=5,h[2*e]=w(e,5);f=new C(u,o,257,r,s),v=new C(h,l,0,a,s),S=new C(new Array(0),c,0,19,7)}(),U=!0),e.l_desc=new _(e.dyn_ltree,f),e.d_desc=new _(e.dyn_dtree,v),e.bl_desc=new _(e.bl_tree,S),e.bi_buf=0,e.bi_valid=0,A(e)},e._tr_stored_block=B,e._tr_flush_block=function(e,t,i,n){var r,a,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=F(e)),N(e,e.l_desc),N(e,e.d_desc),s=function(e){var t;for(L(e,e.dyn_ltree,e.l_desc.max_code),L(e,e.dyn_dtree,e.d_desc.max_code),N(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*d[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=r&&(r=a)):r=a=i+5,i+4<=r&&-1!==t?B(e,t,i,n):4===e.strategy||a===r?(b(e,2+(n?1:0),3),O(e,u,h)):(b(e,4+(n?1:0),3),function(e,t,i,n){var r;for(b(e,t-257,5),b(e,i-1,5),b(e,n-4,4),r=0;r<n;r++)b(e,e.bl_tree[2*d[r]+1],3);x(e,e.dyn_ltree,t-1),x(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),O(e,e.dyn_ltree,e.dyn_dtree)),A(e),n&&P(e)},e._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(g[i]+n+1)]++,e.dyn_dtree[2*E(t)]++),e.last_lit===e.lit_bufsize-1},e._tr_align=function(e){b(e,2,3),I(e,256,u),function(e){16===e.bi_valid?(T(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}}}),Y=u({"../node_modules/pako/lib/zlib/adler32.js"(e,t){t.exports=function(e,t,i,n){for(var r=65535&e,a=e>>>16&65535,s=0;0!==i;){i-=s=i>2e3?2e3:i;do{a=a+(r=r+t[n++]|0)|0}while(--s);r%=65521,a%=65521}return r|a<<16}}}),Q=u({"../node_modules/pako/lib/zlib/crc32.js"(e,t){var i=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,n,r){var a=i,s=r+n;e^=-1;for(var o=r;o<s;o++)e=e>>>8^a[255&(e^t[o])];return~e}}}),Z=u({"../node_modules/pako/lib/zlib/messages.js"(e,t){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}}}),X=u({"../node_modules/pako/lib/zlib/deflate.js"(e){var t,i=K(),n=J(),r=Y(),a=Q(),s=Z(),o=-2,l=258,c=262,d=103,u=113,h=666;function p(e,t){return e.msg=s[t],t}function g(e){return(e<<1)-(e>4?9:0)}function m(e){for(var t=e.length;--t>=0;)e[t]=0}function f(e){var t=e.state,n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(i.arraySet(e.output,t.pending_buf,t.pending_out,n,e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))}function v(e,t){n._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,f(e.strm)}function S(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function C(e,t,n,s){var o=e.avail_in;return o>s&&(o=s),0===o?0:(e.avail_in-=o,i.arraySet(t,e.input,e.next_in,o,n),1===e.state.wrap?e.adler=r(e.adler,t,o,n):2===e.state.wrap&&(e.adler=a(e.adler,t,o,n)),e.next_in+=o,e.total_in+=o,o)}function _(e,t){var i,n,r=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match,d=e.strstart>e.w_size-c?e.strstart-(e.w_size-c):0,u=e.window,h=e.w_mask,p=e.prev,g=e.strstart+l,m=u[a+s-1],f=u[a+s];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(u[(i=t)+s]===f&&u[i+s-1]===m&&u[i]===u[a]&&u[++i]===u[a+1]){a+=2,i++;do{}while(u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&u[++a]===u[++i]&&a<g);if(n=l-(g-a),a=g-l,n>s){if(e.match_start=t,s=n,n>=o)break;m=u[a+s-1],f=u[a+s]}}}while((t=p[t&h])>d&&0!=--r);return s<=e.lookahead?s:e.lookahead}function E(e){var t,n,r,a,s,o=e.w_size;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=o+(o-c)){i.arraySet(e.window,e.window,o,o,0),e.match_start-=o,e.strstart-=o,e.block_start-=o,t=n=e.hash_size;do{r=e.head[--t],e.head[t]=r>=o?r-o:0}while(--n);t=n=o;do{r=e.prev[--t],e.prev[t]=r>=o?r-o:0}while(--n);a+=o}if(0===e.strm.avail_in)break;if(n=C(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=3)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+3-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<c&&0!==e.strm.avail_in)}function T(e,t){for(var i,r;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-c&&(e.match_length=_(e,i)),e.match_length>=3)if(r=n._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else r=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function b(e,t){for(var i,r,a;;){if(e.lookahead<c){if(E(e),e.lookahead<c&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-c&&(e.match_length=_(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-3,r=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=a&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(v(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=n._tr_tally(e,0,e.window[e.strstart-1]))&&v(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}function I(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}function w(e){e.window_size=2*e.w_size,m(e.head),e.max_lazy_match=t[e.level].max_lazy,e.good_match=t[e.level].good_length,e.nice_match=t[e.level].nice_length,e.max_chain_length=t[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0}function R(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i.Buf16(1146),this.dyn_dtree=new i.Buf16(122),this.bl_tree=new i.Buf16(78),m(this.dyn_ltree),m(this.dyn_dtree),m(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(16),this.heap=new i.Buf16(573),m(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(573),m(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function A(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:u,e.adler=2===t.wrap?0:1,t.last_flush=0,n._tr_init(t),0):p(e,o)}function P(e){var t=A(e);return 0===t&&w(e.state),t}function M(e,t,n,r,a,s){if(!e)return o;var l=1;if(-1===t&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>9||8!==n||r<8||r>15||t<0||t>9||s<0||s>4)return p(e,o);8===r&&(r=9);var c=new R;return e.state=c,c.strm=e,c.wrap=l,c.gzhead=null,c.w_bits=r,c.w_size=1<<c.w_bits,c.w_mask=c.w_size-1,c.hash_bits=a+7,c.hash_size=1<<c.hash_bits,c.hash_mask=c.hash_size-1,c.hash_shift=~~((c.hash_bits+3-1)/3),c.window=new i.Buf8(2*c.w_size),c.head=new i.Buf16(c.hash_size),c.prev=new i.Buf16(c.w_size),c.lit_bufsize=1<<a+6,c.pending_buf_size=4*c.lit_bufsize,c.pending_buf=new i.Buf8(c.pending_buf_size),c.d_buf=1*c.lit_bufsize,c.l_buf=3*c.lit_bufsize,c.level=t,c.strategy=s,c.method=n,P(e)}t=[new I(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(E(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,v(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-c&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(v(e,!1),e.strm.avail_out),1)})),new I(4,4,8,4,T),new I(4,5,16,8,T),new I(4,6,32,32,T),new I(4,4,16,16,b),new I(8,16,32,32,b),new I(8,16,128,128,b),new I(8,32,128,256,b),new I(32,128,258,1024,b),new I(32,258,258,4096,b)],e.deflateInit=function(e,t){return M(e,t,8,15,8,0)},e.deflateInit2=M,e.deflateReset=P,e.deflateResetKeep=A,e.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?o:(e.state.gzhead=t,0):o},e.deflate=function(e,i){var r,s,c,C;if(!e||!e.state||i>5||i<0)return e?p(e,o):o;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||s.status===h&&4!==i)return p(e,0===e.avail_out?-5:o);if(s.strm=e,r=s.last_flush,s.last_flush=i,42===s.status)if(2===s.wrap)e.adler=0,S(s,31),S(s,139),S(s,8),s.gzhead?(S(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),S(s,255&s.gzhead.time),S(s,s.gzhead.time>>8&255),S(s,s.gzhead.time>>16&255),S(s,s.gzhead.time>>24&255),S(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),S(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(S(s,255&s.gzhead.extra.length),S(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(S(s,0),S(s,0),S(s,0),S(s,0),S(s,0),S(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),S(s,3),s.status=u);else{var _=8+(s.w_bits-8<<4)<<8;_|=(s.strategy>=2||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(_|=32),_+=31-_%31,s.status=u,y(s,_),0!==s.strstart&&(y(s,e.adler>>>16),y(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(c=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),f(e),c=s.pending,s.pending!==s.pending_buf_size));)S(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){c=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),f(e),c=s.pending,s.pending===s.pending_buf_size)){C=1;break}C=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,S(s,C)}while(0!==C);s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),0===C&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){c=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),f(e),c=s.pending,s.pending===s.pending_buf_size)){C=1;break}C=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,S(s,C)}while(0!==C);s.gzhead.hcrc&&s.pending>c&&(e.adler=a(e.adler,s.pending_buf,s.pending-c,c)),0===C&&(s.status=d)}else s.status=d;if(s.status===d&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&f(e),s.pending+2<=s.pending_buf_size&&(S(s,255&e.adler),S(s,e.adler>>8&255),e.adler=0,s.status=u)):s.status=u),0!==s.pending){if(f(e),0===e.avail_out)return s.last_flush=-1,0}else if(0===e.avail_in&&g(i)<=g(r)&&4!==i)return p(e,-5);if(s.status===h&&0!==e.avail_in)return p(e,-5);if(0!==e.avail_in||0!==s.lookahead||0!==i&&s.status!==h){var T=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(E(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(s,i):3===s.strategy?function(e,t){for(var i,r,a,s,o=e.window;;){if(e.lookahead<=l){if(E(e),e.lookahead<=l&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=o[a=e.strstart-1])===o[++a]&&r===o[++a]&&r===o[++a]){s=e.strstart+l;do{}while(r===o[++a]&&r===o[++a]&&r===o[++a]&&r===o[++a]&&r===o[++a]&&r===o[++a]&&r===o[++a]&&r===o[++a]&&a<s);e.match_length=l-(s-a),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=n._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(v(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(v(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(v(e,!1),0===e.strm.avail_out)?1:2}(s,i):t[s.level].func(s,i);if(3!==T&&4!==T||(s.status=h),1===T||3===T)return 0===e.avail_out&&(s.last_flush=-1),0;if(2===T&&(1===i?n._tr_align(s):5!==i&&(n._tr_stored_block(s,0,0,!1),3===i&&(m(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),f(e),0===e.avail_out))return s.last_flush=-1,0}return 4!==i?0:s.wrap<=0?1:(2===s.wrap?(S(s,255&e.adler),S(s,e.adler>>8&255),S(s,e.adler>>16&255),S(s,e.adler>>24&255),S(s,255&e.total_in),S(s,e.total_in>>8&255),S(s,e.total_in>>16&255),S(s,e.total_in>>24&255)):(y(s,e.adler>>>16),y(s,65535&e.adler)),f(e),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?0:1)},e.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==d&&t!==u&&t!==h?p(e,o):(e.state=null,t===u?p(e,-3):0):o},e.deflateSetDictionary=function(e,t){var n,a,s,l,c,d,u,h,p=t.length;if(!e||!e.state)return o;if(2===(l=(n=e.state).wrap)||1===l&&42!==n.status||n.lookahead)return o;for(1===l&&(e.adler=r(e.adler,t,p,0)),n.wrap=0,p>=n.w_size&&(0===l&&(m(n.head),n.strstart=0,n.block_start=0,n.insert=0),h=new i.Buf8(n.w_size),i.arraySet(h,t,p-n.w_size,n.w_size,0),t=h,p=n.w_size),c=e.avail_in,d=e.next_in,u=e.input,e.avail_in=p,e.next_in=0,e.input=t,E(n);n.lookahead>=3;){a=n.strstart,s=n.lookahead-2;do{n.ins_h=(n.ins_h<<n.hash_shift^n.window[a+3-1])&n.hash_mask,n.prev[a&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=a,a++}while(--s);n.strstart=a,n.lookahead=2,E(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=d,e.input=u,e.avail_in=c,n.wrap=l,0},e.deflateInfo="pako deflate (from Nodeca project)"}}),ee=u({"../node_modules/pako/lib/utils/strings.js"(e){var t=K(),i=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}var r,a=new t.Buf8(256);for(r=0;r<256;r++)a[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;function s(e,r){if(r<65534&&(e.subarray&&n||!e.subarray&&i))return String.fromCharCode.apply(null,t.shrinkBuf(e,r));for(var a="",s=0;s<r;s++)a+=String.fromCharCode(e[s]);return a}a[254]=a[254]=1,e.string2buf=function(e){var i,n,r,a,s,o=e.length,l=0;for(a=0;a<o;a++)55296==(64512&(n=e.charCodeAt(a)))&&a+1<o&&56320==(64512&(r=e.charCodeAt(a+1)))&&(n=65536+(n-55296<<10)+(r-56320),a++),l+=n<128?1:n<2048?2:n<65536?3:4;for(i=new t.Buf8(l),s=0,a=0;s<l;a++)55296==(64512&(n=e.charCodeAt(a)))&&a+1<o&&56320==(64512&(r=e.charCodeAt(a+1)))&&(n=65536+(n-55296<<10)+(r-56320),a++),n<128?i[s++]=n:n<2048?(i[s++]=192|n>>>6,i[s++]=128|63&n):n<65536?(i[s++]=224|n>>>12,i[s++]=128|n>>>6&63,i[s++]=128|63&n):(i[s++]=240|n>>>18,i[s++]=128|n>>>12&63,i[s++]=128|n>>>6&63,i[s++]=128|63&n);return i},e.buf2binstring=function(e){return s(e,e.length)},e.binstring2buf=function(e){for(var i=new t.Buf8(e.length),n=0,r=i.length;n<r;n++)i[n]=e.charCodeAt(n);return i},e.buf2string=function(e,t){var i,n,r,o,l=t||e.length,c=new Array(2*l);for(n=0,i=0;i<l;)if((r=e[i++])<128)c[n++]=r;else if((o=a[r])>4)c[n++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i<l;)r=r<<6|63&e[i++],o--;o>1?c[n++]=65533:r<65536?c[n++]=r:(r-=65536,c[n++]=55296|r>>10&1023,c[n++]=56320|1023&r)}return s(c,n)},e.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}}}),te=u({"../node_modules/pako/lib/zlib/zstream.js"(e,t){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}}}),ie=u({"../node_modules/pako/lib/deflate.js"(e){var t=X(),i=K(),n=ee(),r=Z(),a=te(),s=Object.prototype.toString;function o(e){if(!(this instanceof o))return new o(e);this.options=i.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var l=this.options;l.raw&&l.windowBits>0?l.windowBits=-l.windowBits:l.gzip&&l.windowBits>0&&l.windowBits<16&&(l.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var c=t.deflateInit2(this.strm,l.level,l.method,l.windowBits,l.memLevel,l.strategy);if(0!==c)throw new Error(r[c]);if(l.header&&t.deflateSetHeader(this.strm,l.header),l.dictionary){var d;if(d="string"==typeof l.dictionary?n.string2buf(l.dictionary):"[object ArrayBuffer]"===s.call(l.dictionary)?new Uint8Array(l.dictionary):l.dictionary,0!==(c=t.deflateSetDictionary(this.strm,d)))throw new Error(r[c]);this._dict_set=!0}}function l(e,t){var i=new o(t);if(i.push(e,!0),i.err)throw i.msg||r[i.err];return i.result}o.prototype.push=function(e,r){var a,o,l=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=r===~~r?r:!0===r?4:0,"string"==typeof e?l.input=n.string2buf(e):"[object ArrayBuffer]"===s.call(e)?l.input=new Uint8Array(e):l.input=e,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new i.Buf8(c),l.next_out=0,l.avail_out=c),1!==(a=t.deflate(l,o))&&0!==a)return this.onEnd(a),this.ended=!0,!1;0!==l.avail_out&&(0!==l.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(n.buf2binstring(i.shrinkBuf(l.output,l.next_out))):this.onData(i.shrinkBuf(l.output,l.next_out)))}while((l.avail_in>0||0===l.avail_out)&&1!==a);return 4===o?(a=t.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,0===a):2!==o||(this.onEnd(0),l.avail_out=0,!0)},o.prototype.onData=function(e){this.chunks.push(e)},o.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Deflate=o,e.deflate=l,e.deflateRaw=function(e,t){return(t=t||{}).raw=!0,l(e,t)},e.gzip=function(e,t){return(t=t||{}).gzip=!0,l(e,t)}}}),ne=u({"../node_modules/pako/lib/zlib/inffast.js"(e,t){t.exports=function(e,t){var i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S,y,C,_,E,T,b,I,w;i=e.state,n=e.next_in,I=e.input,r=n+(e.avail_in-5),a=e.next_out,w=e.output,s=a-(t-e.avail_out),o=a+(e.avail_out-257),l=i.dmax,c=i.wsize,d=i.whave,u=i.wnext,h=i.window,p=i.hold,g=i.bits,m=i.lencode,f=i.distcode,v=(1<<i.lenbits)-1,S=(1<<i.distbits)-1;e:do{g<15&&(p+=I[n++]<<g,g+=8,p+=I[n++]<<g,g+=8),y=m[p&v];t:for(;;){if(p>>>=C=y>>>24,g-=C,0==(C=y>>>16&255))w[a++]=65535&y;else{if(!(16&C)){if(!(64&C)){y=m[(65535&y)+(p&(1<<C)-1)];continue t}if(32&C){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}_=65535&y,(C&=15)&&(g<C&&(p+=I[n++]<<g,g+=8),_+=p&(1<<C)-1,p>>>=C,g-=C),g<15&&(p+=I[n++]<<g,g+=8,p+=I[n++]<<g,g+=8),y=f[p&S];i:for(;;){if(p>>>=C=y>>>24,g-=C,!(16&(C=y>>>16&255))){if(!(64&C)){y=f[(65535&y)+(p&(1<<C)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(E=65535&y,g<(C&=15)&&(p+=I[n++]<<g,(g+=8)<C&&(p+=I[n++]<<g,g+=8)),(E+=p&(1<<C)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=C,g-=C,E>(C=a-s)){if((C=E-C)>d&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(T=0,b=h,0===u){if(T+=c-C,C<_){_-=C;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}}else if(u<C){if(T+=c+u-C,(C-=u)<_){_-=C;do{w[a++]=h[T++]}while(--C);if(T=0,u<_){_-=C=u;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}}}else if(T+=u-C,C<_){_-=C;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}for(;_>2;)w[a++]=b[T++],w[a++]=b[T++],w[a++]=b[T++],_-=3;_&&(w[a++]=b[T++],_>1&&(w[a++]=b[T++]))}else{T=a-E;do{w[a++]=w[T++],w[a++]=w[T++],w[a++]=w[T++],_-=3}while(_>2);_&&(w[a++]=w[T++],_>1&&(w[a++]=w[T++]))}break}}break}}while(n<r&&a<o);n-=_=g>>3,p&=(1<<(g-=_<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=a<o?o-a+257:257-(a-o),i.hold=p,i.bits=g}}}),re=u({"../node_modules/pako/lib/zlib/inftrees.js"(e,t){var i=K(),n=15,r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],a=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],o=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,l,c,d,u,h,p){var g,m,f,v,S,y,C,_,E,T=p.bits,b=0,I=0,w=0,R=0,A=0,P=0,M=0,k=0,D=0,O=0,N=null,L=0,x=new i.Buf16(16),F=new i.Buf16(16),U=null,B=0;for(b=0;b<=n;b++)x[b]=0;for(I=0;I<c;I++)x[t[l+I]]++;for(A=T,R=n;R>=1&&0===x[R];R--);if(A>R&&(A=R),0===R)return d[u++]=20971520,d[u++]=20971520,p.bits=1,0;for(w=1;w<R&&0===x[w];w++);for(A<w&&(A=w),k=1,b=1;b<=n;b++)if(k<<=1,(k-=x[b])<0)return-1;if(k>0&&(0===e||1!==R))return-1;for(F[1]=0,b=1;b<n;b++)F[b+1]=F[b]+x[b];for(I=0;I<c;I++)0!==t[l+I]&&(h[F[t[l+I]]++]=I);if(0===e?(N=U=h,y=19):1===e?(N=r,L-=257,U=a,B-=257,y=256):(N=s,U=o,y=-1),O=0,I=0,b=w,S=u,P=A,M=0,f=-1,v=(D=1<<A)-1,1===e&&D>852||2===e&&D>592)return 1;for(;;){C=b-M,h[I]<y?(_=0,E=h[I]):h[I]>y?(_=U[B+h[I]],E=N[L+h[I]]):(_=96,E=0),g=1<<b-M,w=m=1<<P;do{d[S+(O>>M)+(m-=g)]=C<<24|_<<16|E}while(0!==m);for(g=1<<b-1;O&g;)g>>=1;if(0!==g?(O&=g-1,O+=g):O=0,I++,0==--x[b]){if(b===R)break;b=t[l+h[I]]}if(b>A&&(O&v)!==f){for(0===M&&(M=A),S+=w,k=1<<(P=b-M);P+M<R&&!((k-=x[P+M])<=0);)P++,k<<=1;if(D+=1<<P,1===e&&D>852||2===e&&D>592)return 1;d[f=O&v]=A<<24|P<<16|S-u}}return 0!==O&&(d[S+O]=b-M<<24|64<<16),p.bits=A,0}}}),ae=u({"../node_modules/pako/lib/zlib/inflate.js"(e){var t=K(),i=Y(),n=Q(),r=ne(),a=re(),s=-2,o=12,l=30;function c(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function d(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new t.Buf16(320),this.work=new t.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function u(e){var i;return e&&e.state?(i=e.state,e.total_in=e.total_out=i.total=0,e.msg="",i.wrap&&(e.adler=1&i.wrap),i.mode=1,i.last=0,i.havedict=0,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new t.Buf32(852),i.distcode=i.distdyn=new t.Buf32(592),i.sane=1,i.back=-1,0):s}function h(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,u(e)):s}function p(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?s:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,h(e))):s}function g(e,t){var i,n;return e?(n=new d,e.state=n,n.window=null,0!==(i=p(e,t))&&(e.state=null),i):s}var m,f,v=!0;function S(e){if(v){var i;for(m=new t.Buf32(512),f=new t.Buf32(32),i=0;i<144;)e.lens[i++]=8;for(;i<256;)e.lens[i++]=9;for(;i<280;)e.lens[i++]=7;for(;i<288;)e.lens[i++]=8;for(a(1,e.lens,0,288,m,0,e.work,{bits:9}),i=0;i<32;)e.lens[i++]=5;a(2,e.lens,0,32,f,0,e.work,{bits:5}),v=!1}e.lencode=m,e.lenbits=9,e.distcode=f,e.distbits=5}function y(e,i,n,r){var a,s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new t.Buf8(s.wsize)),r>=s.wsize?(t.arraySet(s.window,i,n-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):((a=s.wsize-s.wnext)>r&&(a=r),t.arraySet(s.window,i,n-r,a,s.wnext),(r-=a)?(t.arraySet(s.window,i,n-r,r,0),s.wnext=r,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=a))),0}e.inflateReset=h,e.inflateReset2=p,e.inflateResetKeep=u,e.inflateInit=function(e){return g(e,15)},e.inflateInit2=g,e.inflate=function(e,d){var u,h,p,g,m,f,v,C,_,E,T,b,I,w,R,A,P,M,k,D,O,N,L,x,F=0,U=new t.Buf8(4),B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return s;(u=e.state).mode===o&&(u.mode=13),m=e.next_out,p=e.output,v=e.avail_out,g=e.next_in,h=e.input,f=e.avail_in,C=u.hold,_=u.bits,E=f,T=v,N=0;e:for(;;)switch(u.mode){case 1:if(0===u.wrap){u.mode=13;break}for(;_<16;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(2&u.wrap&&35615===C){u.check=0,U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0),C=0,_=0,u.mode=2;break}if(u.flags=0,u.head&&(u.head.done=!1),!(1&u.wrap)||(((255&C)<<8)+(C>>8))%31){e.msg="incorrect header check",u.mode=l;break}if(8!=(15&C)){e.msg="unknown compression method",u.mode=l;break}if(_-=4,O=8+(15&(C>>>=4)),0===u.wbits)u.wbits=O;else if(O>u.wbits){e.msg="invalid window size",u.mode=l;break}u.dmax=1<<O,e.adler=u.check=1,u.mode=512&C?10:o,C=0,_=0;break;case 2:for(;_<16;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(u.flags=C,8!=(255&u.flags)){e.msg="unknown compression method",u.mode=l;break}if(57344&u.flags){e.msg="unknown header flags set",u.mode=l;break}u.head&&(u.head.text=C>>8&1),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,_=0,u.mode=3;case 3:for(;_<32;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.head&&(u.head.time=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,U[2]=C>>>16&255,U[3]=C>>>24&255,u.check=n(u.check,U,4,0)),C=0,_=0,u.mode=4;case 4:for(;_<16;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.head&&(u.head.xflags=255&C,u.head.os=C>>8),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,_=0,u.mode=5;case 5:if(1024&u.flags){for(;_<16;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.length=C,u.head&&(u.head.extra_len=C),512&u.flags&&(U[0]=255&C,U[1]=C>>>8&255,u.check=n(u.check,U,2,0)),C=0,_=0}else u.head&&(u.head.extra=null);u.mode=6;case 6:if(1024&u.flags&&((b=u.length)>f&&(b=f),b&&(u.head&&(O=u.head.extra_len-u.length,u.head.extra||(u.head.extra=new Array(u.head.extra_len)),t.arraySet(u.head.extra,h,g,b,O)),512&u.flags&&(u.check=n(u.check,h,b,g)),f-=b,g+=b,u.length-=b),u.length))break e;u.length=0,u.mode=7;case 7:if(2048&u.flags){if(0===f)break e;b=0;do{O=h[g+b++],u.head&&O&&u.length<65536&&(u.head.name+=String.fromCharCode(O))}while(O&&b<f);if(512&u.flags&&(u.check=n(u.check,h,b,g)),f-=b,g+=b,O)break e}else u.head&&(u.head.name=null);u.length=0,u.mode=8;case 8:if(4096&u.flags){if(0===f)break e;b=0;do{O=h[g+b++],u.head&&O&&u.length<65536&&(u.head.comment+=String.fromCharCode(O))}while(O&&b<f);if(512&u.flags&&(u.check=n(u.check,h,b,g)),f-=b,g+=b,O)break e}else u.head&&(u.head.comment=null);u.mode=9;case 9:if(512&u.flags){for(;_<16;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(C!==(65535&u.check)){e.msg="header crc mismatch",u.mode=l;break}C=0,_=0}u.head&&(u.head.hcrc=u.flags>>9&1,u.head.done=!0),e.adler=u.check=0,u.mode=o;break;case 10:for(;_<32;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}e.adler=u.check=c(C),C=0,_=0,u.mode=11;case 11:if(0===u.havedict)return e.next_out=m,e.avail_out=v,e.next_in=g,e.avail_in=f,u.hold=C,u.bits=_,2;e.adler=u.check=1,u.mode=o;case o:if(5===d||6===d)break e;case 13:if(u.last){C>>>=7&_,_-=7&_,u.mode=27;break}for(;_<3;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}switch(u.last=1&C,_-=1,3&(C>>>=1)){case 0:u.mode=14;break;case 1:if(S(u),u.mode=20,6===d){C>>>=2,_-=2;break e}break;case 2:u.mode=17;break;case 3:e.msg="invalid block type",u.mode=l}C>>>=2,_-=2;break;case 14:for(C>>>=7&_,_-=7&_;_<32;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if((65535&C)!=(C>>>16^65535)){e.msg="invalid stored block lengths",u.mode=l;break}if(u.length=65535&C,C=0,_=0,u.mode=15,6===d)break e;case 15:u.mode=16;case 16:if(b=u.length){if(b>f&&(b=f),b>v&&(b=v),0===b)break e;t.arraySet(p,h,g,b,m),f-=b,g+=b,v-=b,m+=b,u.length-=b;break}u.mode=o;break;case 17:for(;_<14;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(u.nlen=257+(31&C),C>>>=5,_-=5,u.ndist=1+(31&C),C>>>=5,_-=5,u.ncode=4+(15&C),C>>>=4,_-=4,u.nlen>286||u.ndist>30){e.msg="too many length or distance symbols",u.mode=l;break}u.have=0,u.mode=18;case 18:for(;u.have<u.ncode;){for(;_<3;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.lens[B[u.have++]]=7&C,C>>>=3,_-=3}for(;u.have<19;)u.lens[B[u.have++]]=0;if(u.lencode=u.lendyn,u.lenbits=7,L={bits:u.lenbits},N=a(0,u.lens,0,19,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid code lengths set",u.mode=l;break}u.have=0,u.mode=19;case 19:for(;u.have<u.nlen+u.ndist;){for(;A=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,P=65535&F,!((R=F>>>24)<=_);){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(P<16)C>>>=R,_-=R,u.lens[u.have++]=P;else{if(16===P){for(x=R+2;_<x;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(C>>>=R,_-=R,0===u.have){e.msg="invalid bit length repeat",u.mode=l;break}O=u.lens[u.have-1],b=3+(3&C),C>>>=2,_-=2}else if(17===P){for(x=R+3;_<x;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}_-=R,O=0,b=3+(7&(C>>>=R)),C>>>=3,_-=3}else{for(x=R+7;_<x;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}_-=R,O=0,b=11+(127&(C>>>=R)),C>>>=7,_-=7}if(u.have+b>u.nlen+u.ndist){e.msg="invalid bit length repeat",u.mode=l;break}for(;b--;)u.lens[u.have++]=O}}if(u.mode===l)break;if(0===u.lens[256]){e.msg="invalid code -- missing end-of-block",u.mode=l;break}if(u.lenbits=9,L={bits:u.lenbits},N=a(1,u.lens,0,u.nlen,u.lencode,0,u.work,L),u.lenbits=L.bits,N){e.msg="invalid literal/lengths set",u.mode=l;break}if(u.distbits=6,u.distcode=u.distdyn,L={bits:u.distbits},N=a(2,u.lens,u.nlen,u.ndist,u.distcode,0,u.work,L),u.distbits=L.bits,N){e.msg="invalid distances set",u.mode=l;break}if(u.mode=20,6===d)break e;case 20:u.mode=21;case 21:if(f>=6&&v>=258){e.next_out=m,e.avail_out=v,e.next_in=g,e.avail_in=f,u.hold=C,u.bits=_,r(e,T),m=e.next_out,p=e.output,v=e.avail_out,g=e.next_in,h=e.input,f=e.avail_in,C=u.hold,_=u.bits,u.mode===o&&(u.back=-1);break}for(u.back=0;A=(F=u.lencode[C&(1<<u.lenbits)-1])>>>16&255,P=65535&F,!((R=F>>>24)<=_);){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(A&&!(240&A)){for(M=R,k=A,D=P;A=(F=u.lencode[D+((C&(1<<M+k)-1)>>M)])>>>16&255,P=65535&F,!(M+(R=F>>>24)<=_);){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}C>>>=M,_-=M,u.back+=M}if(C>>>=R,_-=R,u.back+=R,u.length=P,0===A){u.mode=26;break}if(32&A){u.back=-1,u.mode=o;break}if(64&A){e.msg="invalid literal/length code",u.mode=l;break}u.extra=15&A,u.mode=22;case 22:if(u.extra){for(x=u.extra;_<x;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.length+=C&(1<<u.extra)-1,C>>>=u.extra,_-=u.extra,u.back+=u.extra}u.was=u.length,u.mode=23;case 23:for(;A=(F=u.distcode[C&(1<<u.distbits)-1])>>>16&255,P=65535&F,!((R=F>>>24)<=_);){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(!(240&A)){for(M=R,k=A,D=P;A=(F=u.distcode[D+((C&(1<<M+k)-1)>>M)])>>>16&255,P=65535&F,!(M+(R=F>>>24)<=_);){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}C>>>=M,_-=M,u.back+=M}if(C>>>=R,_-=R,u.back+=R,64&A){e.msg="invalid distance code",u.mode=l;break}u.offset=P,u.extra=15&A,u.mode=24;case 24:if(u.extra){for(x=u.extra;_<x;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}u.offset+=C&(1<<u.extra)-1,C>>>=u.extra,_-=u.extra,u.back+=u.extra}if(u.offset>u.dmax){e.msg="invalid distance too far back",u.mode=l;break}u.mode=25;case 25:if(0===v)break e;if(b=T-v,u.offset>b){if((b=u.offset-b)>u.whave&&u.sane){e.msg="invalid distance too far back",u.mode=l;break}b>u.wnext?(b-=u.wnext,I=u.wsize-b):I=u.wnext-b,b>u.length&&(b=u.length),w=u.window}else w=p,I=m-u.offset,b=u.length;b>v&&(b=v),v-=b,u.length-=b;do{p[m++]=w[I++]}while(--b);0===u.length&&(u.mode=21);break;case 26:if(0===v)break e;p[m++]=u.length,v--,u.mode=21;break;case 27:if(u.wrap){for(;_<32;){if(0===f)break e;f--,C|=h[g++]<<_,_+=8}if(T-=v,e.total_out+=T,u.total+=T,T&&(e.adler=u.check=u.flags?n(u.check,p,T,m-T):i(u.check,p,T,m-T)),T=v,(u.flags?C:c(C))!==u.check){e.msg="incorrect data check",u.mode=l;break}C=0,_=0}u.mode=28;case 28:if(u.wrap&&u.flags){for(;_<32;){if(0===f)break e;f--,C+=h[g++]<<_,_+=8}if(C!==(4294967295&u.total)){e.msg="incorrect length check",u.mode=l;break}C=0,_=0}u.mode=29;case 29:N=1;break e;case l:N=-3;break e;case 31:return-4;default:return s}return e.next_out=m,e.avail_out=v,e.next_in=g,e.avail_in=f,u.hold=C,u.bits=_,(u.wsize||T!==e.avail_out&&u.mode<l&&(u.mode<27||4!==d))&&y(e,e.output,e.next_out,T-e.avail_out),E-=e.avail_in,T-=e.avail_out,e.total_in+=E,e.total_out+=T,u.total+=T,u.wrap&&T&&(e.adler=u.check=u.flags?n(u.check,p,T,e.next_out-T):i(u.check,p,T,e.next_out-T)),e.data_type=u.bits+(u.last?64:0)+(u.mode===o?128:0)+(20===u.mode||15===u.mode?256:0),(0===E&&0===T||4===d)&&0===N&&(N=-5),N},e.inflateEnd=function(e){if(!e||!e.state)return s;var t=e.state;return t.window&&(t.window=null),e.state=null,0},e.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,0):s},e.inflateSetDictionary=function(e,t){var n,r=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?s:11===n.mode&&i(1,t,r,0)!==n.check?-3:y(e,t,r,r)?(n.mode=31,-4):(n.havedict=1,0):s},e.inflateInfo="pako inflate (from Nodeca project)"}}),se=u({"../node_modules/pako/lib/zlib/constants.js"(e,t){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}}}),oe=u({"../node_modules/pako/lib/zlib/gzheader.js"(e,t){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}}}),le=u({"../node_modules/pako/lib/inflate.js"(e){var t=ae(),i=K(),n=ee(),r=se(),a=Z(),s=te(),o=oe(),l=Object.prototype.toString;function c(e){if(!(this instanceof c))return new c(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var d=this.options;d.raw&&d.windowBits>=0&&d.windowBits<16&&(d.windowBits=-d.windowBits,0===d.windowBits&&(d.windowBits=-15)),!(d.windowBits>=0&&d.windowBits<16)||e&&e.windowBits||(d.windowBits+=32),d.windowBits>15&&d.windowBits<48&&!(15&d.windowBits)&&(d.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new s,this.strm.avail_out=0;var u=t.inflateInit2(this.strm,d.windowBits);if(u!==r.Z_OK)throw new Error(a[u]);if(this.header=new o,t.inflateGetHeader(this.strm,this.header),d.dictionary&&("string"==typeof d.dictionary?d.dictionary=n.string2buf(d.dictionary):"[object ArrayBuffer]"===l.call(d.dictionary)&&(d.dictionary=new Uint8Array(d.dictionary)),d.raw&&(u=t.inflateSetDictionary(this.strm,d.dictionary))!==r.Z_OK))throw new Error(a[u])}function d(e,t){var i=new c(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}c.prototype.push=function(e,a){var s,o,c,d,u,h=this.strm,p=this.options.chunkSize,g=this.options.dictionary,m=!1;if(this.ended)return!1;o=a===~~a?a:!0===a?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=n.binstring2buf(e):"[object ArrayBuffer]"===l.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(p),h.next_out=0,h.avail_out=p),(s=t.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(s=t.inflateSetDictionary(this.strm,g)),s===r.Z_BUF_ERROR&&!0===m&&(s=r.Z_OK,m=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),this.ended=!0,!1;h.next_out&&(0!==h.avail_out&&s!==r.Z_STREAM_END&&(0!==h.avail_in||o!==r.Z_FINISH&&o!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=n.utf8border(h.output,h.next_out),d=h.next_out-c,u=n.buf2string(h.output,c),h.next_out=d,h.avail_out=p-d,d&&i.arraySet(h.output,h.output,c,d,0),this.onData(u)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(m=!0)}while((h.avail_in>0||0===h.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(o=r.Z_FINISH),o===r.Z_FINISH?(s=t.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):o!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),h.avail_out=0,!0)},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},e.Inflate=c,e.inflate=d,e.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},e.ungzip=d}}),ce=u({"../node_modules/pako/index.js"(e,t){var i={};(0,K().assign)(i,ie(),le(),se()),t.exports=i}}),de=u({"../signaling-agent/node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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:/^(\S*) (\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:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d 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:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{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")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],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}},{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":"")+(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"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"x-signaling-fb:"+("*"===e.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ue=u({"../signaling-agent/node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var a=0;a<n.length;a+=1)null!=e[a+1]&&(i[n[a]]=t(e[a+1]))})(n.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},n=de(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),s=a[a.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,s,r)}})),t.media=a,t};var a=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),he=u({"../signaling-agent/node_modules/sdp-transform/lib/writer.js"(e,t){var i=de(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},a=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?n.push(i[t.name][s]):n.push(i[t.names[a]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=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 n=t.outerOrder||s,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(a(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(a(t,i,e))}))}))})),e.media.forEach((function(e){l.push(a("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(a(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(a(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),pe=u({"../signaling-agent/node_modules/sdp-transform/lib/index.js"(e){var t=ue(),i=he();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),ge=u({"../skype-calling-utilities/dist/skype-calling-utilities.bundle.js"(e,t){var i,n;i=e,n=(e,t)=>{var i={},n={exports:i},r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,l={};((e,t)=>{for(var i in t)r(e,i,{get:t[i],enumerable:!0})})(l,{SlimCoreElectronControlCapturer:()=>f}),n.exports=(e=>((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let l of s(t))o.call(e,l)||l===i||r(e,l,{get:()=>t[l],enumerable:!(n=a(t,l))||n.enumerable});return e})(r({},"__esModule",{value:!0}),e))(l);var c=g;function d(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}var u,h=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new p(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",d(e))}}))}},p=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,c.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},m=class extends h{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}};(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,a=(e.buttonDown?1:0)<<5,s=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|a|s),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,a=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|a),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(u||(u={}));var f=class extends m{constructor(e,t,i=!0,n=1){super(),this._logger=e,this._element=t,this._captureRegionPreserveAspectRatio=i,this._mouseMoveCount=0,this._mouseMoveStartTime=0,this._isMouseDown=!1,this._isMouseOnRenderer=!1,this._captureMode=0,this._pollTimerID=0,this._resizeTimerID=0,this._mouseMoveThrottlingEnabled=!1,this._handleResizeEvents=()=>{clearTimeout(this._resizeTimerID),this._resizeTimerID=window.setTimeout((()=>{this.updateCaptureRegion()}),250)},this._handleMouseLeave=e=>{!this._isOnScreenContent(e)&&this._isMouseOnRenderer&&(this._raiseCaptureEvent(2),this._logger.info("Mouse leaving render region")),this._isMouseOnRenderer=!1},this._handleMouseEnter=e=>{this._isOnScreenContent(e)&&(this._isMouseOnRenderer=!0,this._raiseCaptureEvent(1),this._logger.info("Mouse entering render region"))},this._handleLosingFocus=()=>{this._syncKeyStates(!0)},this._handleClick=e=>{this._isOnScreenContent(e)&&(this._raiseCaptureEvent(0),this._logger.info("Mouse clicked"))},this._handleMouseMove=e=>{if(!this._isOnScreenContent(e)&&this._isMouseOnRenderer)return this._raiseCaptureEvent(2),this._isMouseOnRenderer=!1,void this._logger.info("Mouse leaving render region");if(this._isOnScreenContent(e)&&!this._isMouseOnRenderer&&(this._raiseCaptureEvent(1),this._isMouseOnRenderer=!0,this._logger.info("Mouse entering render region")),2!==this._captureMode&&3!==this._captureMode)return;if(this._mouseMoveCount++,this._mouseMoveThrottlingEnabled){if(!this._isOnScreenContent(e)||!this._shouldMoveMouse())return}else if(!this._isOnScreenContent(e)||this._mouseMoveCount%2==0)return;const t={type:0};this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseDown=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:v(e.button),buttonDown:!0};this._isMouseDown=!0,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleMouseUp=e=>{if(2!==this._captureMode&&3!==this._captureMode)return;if(!this._isOnScreenContent(e))return;const t={type:2,buttonType:v(e.button),buttonDown:!1};this._isMouseDown=!1,this._normalizeMousePosition(e,t),this._raiseMouseEvent(t)},this._handleKeyDown=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!1}),e.stopPropagation(),e.preventDefault()},this._handleKeyUp=e=>{this._raiseKeyboardEvent({codeType:1,code:e.keyCode,repeat:e.repeat,keyUp:!0}),e.stopPropagation(),e.preventDefault()},this._handleWheel=e=>{this._raiseMouseEvent({type:1,wheelRotation:e.deltaY>0?-120:120})},this._handleContextMenu=e=>{e.preventDefault()},this._ensureCanReceiveKeyboardInput(),this._element.ownerDocument?.defaultView?.addEventListener("resize",this._handleResizeEvents,!1),this._captureRegion={left:0,top:0,width:this._element.clientWidth,height:this._element.clientHeight},this._videoSize={width:Math.floor(t.clientHeight*n),height:t.clientHeight},this._origElementSize={width:0,height:0},this._checkElementSize(),this._mouseMoveStartTime=new Date(0).getTime()}get captureMode(){return this._captureMode}get captureRegion(){return this._captureRegion}setMouseMoveThrottlingFeatureFlag(e){this._mouseMoveThrottlingEnabled=e}dispose(e){this._logger.info(`dispose causeId: ${e}`),window.clearTimeout(this._pollTimerID),this._element.ownerDocument?.defaultView?.removeEventListener("resize",this._handleResizeEvents,!1),super.dispose(e)}updateVideoSize(e,t){this._videoSize.width=e,this._videoSize.height=t,this.updateCaptureRegion()}updateCaptureRegion(){this._captureRegionPreserveAspectRatio?(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientWidth*this._videoSize.height/this._videoSize.width,this._captureRegion.height>this._element.clientHeight?(this._captureRegion.width=this._element.clientHeight*this._videoSize.width/this._videoSize.height,this._captureRegion.height=this._element.clientHeight,this._captureRegion.left=(this._element.clientWidth-this._captureRegion.width)/2,this._captureRegion.top=0):(this._captureRegion.left=0,this._captureRegion.top=(this._element.clientHeight-this._captureRegion.height)/2)):(this._captureRegion.width=this._element.clientWidth,this._captureRegion.height=this._element.clientHeight,this._captureRegion.top=0,this._captureRegion.left=0)}setCaptureMode(e){3===this._captureMode&&3!==e&&this._syncKeyStates(!0),this._captureMode=e,0!==e?("none"===this._element.style.pointerEvents&&this._logger.warn("Element pointer-events is 'none', event handlers will not work"),this._element.addEventListener("click",this._handleClick),this._element.addEventListener("pointermove",this._handleMouseMove),this._element.addEventListener("pointerdown",this._handleMouseDown),this._element.addEventListener("pointerup",this._handleMouseUp),this._element.addEventListener("pointerenter",this._handleMouseEnter),this._element.addEventListener("pointerleave",this._handleMouseLeave),3===e?(this._element.addEventListener("wheel",this._handleWheel),this._element.addEventListener("keydown",this._handleKeyDown),this._element.addEventListener("keyup",this._handleKeyUp),this._element.addEventListener("contextmenu",this._handleContextMenu),this._element.addEventListener("blur",this._handleLosingFocus)):(this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))):(this._element.removeEventListener("pointermove",this._handleMouseMove),this._element.removeEventListener("pointerdown",this._handleMouseDown),this._element.removeEventListener("pointerup",this._handleMouseUp),this._element.removeEventListener("pointerenter",this._handleMouseEnter),this._element.removeEventListener("pointerleave",this._handleMouseLeave),this._element.removeEventListener("click",this._handleClick),this._element.removeEventListener("wheel",this._handleWheel),this._element.removeEventListener("keydown",this._handleKeyDown),this._element.removeEventListener("keyup",this._handleKeyUp),this._element.removeEventListener("contextmenu",this._handleContextMenu),this._element.removeEventListener("blur",this._handleLosingFocus))}_ensureCanReceiveKeyboardInput(){this._element.tabIndex=this._element.tabIndex}_checkElementSize(){this._origElementSize.width===this._element.clientWidth&&this._origElementSize.height===this._element.clientHeight||(this.updateCaptureRegion(),this._origElementSize.width=this._element.clientWidth,this._origElementSize.height=this._element.clientHeight),this._pollTimerID=window.setTimeout((()=>{this._checkElementSize()}),3e3)}_raiseMouseEvent(e){this.event("mouseControlEvent").raise(e)}_raiseKeyboardEvent(e){this.event("keyboardControlEvent").raise(e)}_raiseCaptureEvent(e){this.event("ctrlCaptureEvent").raise(e)}_normalizeMousePosition(e,t){t.xPos=(e.offsetX-this._captureRegion.left)/this._captureRegion.width*65535,t.yPos=(e.offsetY-this._captureRegion.top)/this._captureRegion.height*65535}_isOnScreenContent(e){const t=this._captureRegion.left,i=this._captureRegion.left+this._captureRegion.width,n=this._captureRegion.top,r=this._captureRegion.top+this._captureRegion.height;return t<=e.offsetX&&e.offsetX<i&&n<=e.offsetY&&e.offsetY<r}_shouldMoveMouse(){if(this._mouseMoveStartTime){const e=(new Date).getTime(),t=e-this._mouseMoveStartTime;if(this._isMouseDown&&t>=30||!this._isMouseDown&&t>=50)return this._mouseMoveStartTime=e,!0}else this._mouseMoveStartTime=(new Date).getTime();return!1}_syncKeyStates(e){this._raiseKeyboardEvent({codeType:1,code:17,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:16,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:18,repeat:!1,keyUp:e}),this._raiseKeyboardEvent({codeType:1,code:91,repeat:!1,keyUp:e}),this._logger.info("Synced Key states.")}static formatMouseEvent(e){return u.encodeMouseEvent(e)}static formatKeyboardEvent(e){return u.encodeKeyboardEvent(e)}};function v(e){switch(e){case 0:return 0;case 2:return 1;case 1:return 2;default:return}}if("object"==typeof n.exports&&"object"==typeof i){n.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,r)||r===i||Object.defineProperty(e,r,{get:()=>t[r],enumerable:!(n=Object.getOwnPropertyDescriptor(t,r))||n.enumerable});return e})(n.exports,i)}return n.exports},"object"==typeof e&&"object"==typeof t?t.exports=n():"object"==typeof e?e["skype-calling-utilities"]=n():i["skype-calling-utilities"]=n(i["@skype/rt-js-bindings"],i.lodash)}}),me=u({"../node_modules/synctasks/dist/SyncTasks.js"(e){function t(e){return null!=e&&"function"==typeof e.then}function i(e){return null!=e&&"function"==typeof e.cancel}function n(t,i){if(!e.config.catchExceptions)return t();try{return t()}catch(e){return i(e)}}Object.defineProperty(e,"__esModule",{value:!0}),e.config={exceptionsToConsole:!0,catchExceptions:!0,traceEnabled:!1,exceptionHandler:void 0,unhandledErrorHandler:function(e){throw e}},e.fromThenable=function(e){var t=u();return e.then((function(e){t.resolve(e)}),(function(e){t.reject(e)})),t.promise().thenAsync((function(e){return e}))};var r,a,s,o=[],l="undefined"!=typeof setImmediate;function c(e){o.push(e),1===o.length&&(l?setImmediate(d):setTimeout(d,0))}function d(){var e=o;o=[];for(var t=0;t<e.length;t++)e[t]()}function u(){return new r.SyncTask}function h(e){return(new r.SyncTask).resolve(e).promise()}function p(e){var n=u(),a=!1;return n.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))})),e.forEach((function(e){t(e)?e.then((function(e){a||(a=!0,n.resolve(e))}),(function(e){a||(a=!0,n.reject(e))})):a||(a=!0,n.resolve(e))})),n.promise()}e.asyncCallback=c,a=r||(r={}),s=function(){function r(){this._completedSuccess=!1,this._completedFail=!1,this._traceEnabled=!1,this._cancelCallbacks=[],this._wasCanceled=!1,this._wasExplicitlyCanceled=!1,this._resolving=!1,this._storedCallbackSets=[],this._mustHandleError=!0}return r.prototype._addCallbackSet=function(e,t){var i=this,n=new r;return n.onCancel((function(t){e.wasCanceled=!0,e.cancelContext=t,i._cancelInternal(t)})),e.task=n,this._storedCallbackSets.push(e),t?this._mustHandleError=!1:n._mustHandleError=!1,this._resolving||(this._completedSuccess?this._resolveSuccesses():this._completedFail&&this._resolveFailures()),n.promise()},r.prototype.onCancel=function(e){return this._completedSuccess||this._completedFail||(this._wasCanceled?e(this._cancelContext):this._cancelCallbacks.push(e)),this},r.prototype.then=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t},!0)},r.prototype.thenAsync=function(e,t){return this._addCallbackSet({successFunc:e,failFunc:t,asyncCallback:!0},!0)},r.prototype.catch=function(e){return this._addCallbackSet({failFunc:e},!0)},r.prototype.always=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!0)},r.prototype.setTracingEnabled=function(e){return this._traceEnabled=e,this},r.prototype.finally=function(e){return this._addCallbackSet({successFunc:e,failFunc:e},!1),this},r.prototype.done=function(e){return this._addCallbackSet({successFunc:e},!1),this},r.prototype.fail=function(e){return this._addCallbackSet({failFunc:e},!1),this},r.prototype.resolve=function(e){return this._checkState(!0),this._completedSuccess=!0,this._storedResolution=e,this._cancelCallbacks=[],this._resolveSuccesses(),this},r.prototype.reject=function(e){return this._checkState(!1),this._completedFail=!0,this._storedErrResolution=e,this._cancelCallbacks=[],this._resolveFailures(),r._enforceErrorHandled(this),this},r.prototype._checkState=function(t){if(this._completedSuccess||this._completedFail){this._completeStack&&console.error(this._completeStack.message,this._completeStack.stack);var i="Failed to "+(t?"resolve":"reject")+": the task is already "+(this._completedSuccess?"resolved":"rejected");throw new Error(i)}(e.config.traceEnabled||this._traceEnabled)&&(this._completeStack=new Error("resolve"))},r._enforceErrorHandled=function(t){t._mustHandleError&&(r._rejectedTasks.push(t),r._enforceErrorHandledTimer||(r._enforceErrorHandledTimer=setTimeout((function(){r._enforceErrorHandledTimer=void 0;var t=r._rejectedTasks;r._rejectedTasks=[],t.forEach((function(t,i){t._mustHandleError&&e.config.unhandledErrorHandler(t._storedErrResolution)}))}),0)))},r.prototype.cancel=function(e){if(this._wasExplicitlyCanceled)throw new Error("Already Canceled");this._wasExplicitlyCanceled=!0,this._cancelInternal(e)},r.prototype._cancelInternal=function(e){var t=this;if(!this._wasCanceled){this._wasCanceled=!0,this._cancelContext=e;var i=this._cancelCallbacks;this._cancelCallbacks=[],i.length>0&&i.forEach((function(e){t._completedSuccess||t._completedFail||e(t._cancelContext)}))}},r.cancelOtherInternal=function(e,t){var i=e;i._storedCallbackSets&&i._cancelInternal?i._cancelInternal(t):e.cancel(t)},r.prototype.promise=function(){return this},r.prototype._resolveSuccesses=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveSuccessCallback(t)})):e._resolveSuccessCallback(t)}))}this._resolving=!1},r.prototype._resolveSuccessCallback=function(e){var a=this;e.successFunc?n((function(){var n=e.successFunc(a._storedResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){a._handleException(t,"SyncTask caught exception in success block: "+t.toString()),e.task.reject(t)})):e.task.resolve(this._storedResolution)},r.prototype._resolveFailures=function(){var e=this;for(this._resolving=!0;this._storedCallbackSets.length;){var t=this._storedCallbackSets;this._storedCallbackSets=[],t.forEach((function(t){t.asyncCallback?c((function(){return e._resolveFailureCallback(t)})):e._resolveFailureCallback(t)}))}this._resolving=!1},r.prototype._resolveFailureCallback=function(e){var a=this;e.failFunc?n((function(){var n=e.failFunc(a._storedErrResolution);i(n)&&(e.wasCanceled?r.cancelOtherInternal(n,e.cancelContext):e.task.onCancel((function(e){return r.cancelOtherInternal(n,e)}))),t(n)?n.then((function(t){e.task.resolve(t)}),(function(t){e.task.reject(t)})):e.task.resolve(n)}),(function(t){a._handleException(t,"SyncTask caught exception in failure block: "+t.toString()),e.task.reject(t)})):e.task.reject(this._storedErrResolution)},r.prototype._handleException=function(t,i){e.config.exceptionsToConsole&&console.error(i),e.config.exceptionHandler&&e.config.exceptionHandler(t)},r.prototype.toEs6Promise=function(){var e=this;return new Promise((function(t,i){return e.then(t,i)}))},r._rejectedTasks=[],r}(),a.SyncTask=s,e.all=function(e){if(0===e.length)return h([]);var n,a=u(),s=e.length,o=Array(e.length);a.onCancel((function(t){e.forEach((function(e){i(e)&&r.SyncTask.cancelOtherInternal(e,t)}))}));var l=function(){0==--s&&(void 0!==n?a.reject(n):a.resolve(o))};return e.forEach((function(e,i){t(e)?e.then((function(e){o[i]=e,l()}),(function(e){void 0===n&&(n=void 0===e||e),l()})):(o[i]=e,l())})),a.promise()},e.Defer=u,e.Resolved=h,e.Rejected=function(e){return(new r.SyncTask).reject(e).promise()},e.race=p,e.raceTimer=function(e,t){var i=u(),n=setTimeout((function(){i.resolve({timedOut:!0})}),t);return p([e.then((function(e){return clearTimeout(n),{timedOut:!1,result:e}})),i.promise()])}}}),fe=u({"../node_modules/sdp-transform/lib/grammar.js"(e,t){var i=t.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:/^(\S*) (\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:"rtcpFbXMessage",reg:/^rtcp-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"rtcp-fb:"+("*"===e.payload?"%s":"%d")+" x-message %s"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%d 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:"cryptoscale",reg:/^cryptoscale:(\d*) (client|server) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","flavor","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"cryptoscale:%d %s %s %s %s":"cryptoscale:%d %s %s %s"}},{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")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{push:"xCandidatesIpv6",reg:/^x-candidate-ipv6:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation"],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}},{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":"")+(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"},{name:"xMediaBw",reg:/^x-mediabw:(\S*) send=(\d*);recv=(\d*)/,names:["label","sendBw","receiveBw"],format:"x-mediabw:%s send=%d;recv=%d"},{name:"xSsrcRange",reg:/^x-ssrc-range:(\d*)-(\d*)/,names:["ssrcMin","ssrcMax"],format:"x-ssrc-range:%d-%d"},{name:"xSource",reg:/^x-source:(\S*)/,format:"x-source:%s"},{name:"xSourceStreamId",reg:/^x-source-streamid:(\S*)/,format:"x-source-streamid:%s"},{name:"xCaps",reg:/^x-caps:(\d*) (\S*)/,names:["payloadType","value"],format:"x-caps:%d %s"},{name:"signalingFbXMessage",reg:/^x-signaling-fb:(\*|\d*) x-message ([\S| ]*)/,names:["payload","param"],format:function(e){return"x-signaling-fb:"+("*"===e.payload?"%s":"%d")+" x-message %s"}},{push:"xMediaSettings",reg:/^x-mediasettings:([\S| ]*)/,names:["settings"],format:"x-mediasettings:%s"},{name:"xDataProtocol",reg:/^x-data-protocol:\s?(.*)/,format:"x-data-protocol:%s"},{name:"xMultiStream",reg:/^x-multi-stream:(\d*) (\d*) (\d*) (\d*)/,names:["numberOfStreams","startSsrc","ssrcRange","ssrcGroupRange"],format:"x-multi-stream:%d %d %d %d"},{push:"invalid",names:["value"]}]};Object.keys(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),ve=u({"../node_modules/sdp-transform/lib/parser.js"(e){var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var a=e.push?{}:r?i[e.name]:i;(function(e,i,n,r){if(r&&!n)i[r]=t(e[1]);else for(var a=0;a<n.length;a+=1)null!=e[a+1]&&(i[n[a]]=t(e[a+1]))})(n.match(e.reg),a,e.names,e.name),e.push&&i[e.push].push(a)},n=fe(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},a=[],s=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach((function(e){var t=e[0],r=e.slice(2);"m"===t&&(a.push({rtp:[],fmtp:[]}),s=a[a.length-1]);for(var o=0;o<(n[t]||[]).length;o+=1){var l=n[t][o];if(l.reg.test(r))return i(l,s,r)}})),t.media=a,t};var a=function(e,i){var n=i.split(/=(.+)/,2);return 2===n.length?e[n[0]]=t(n[1]):1===n.length&&i.length>1&&(e[n[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(a,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],n=e.split(" ").map(t),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(a,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,n=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),n=!0),{scid:i,paused:n}}))}))}}}),Se=u({"../node_modules/sdp-transform/lib/writer.js"(e,t){var i=fe(),n=/%[sdv%]/g,r=function(e){var t=1,i=arguments,r=i.length;return e.replace(n,(function(e){if(t>=r)return e;var n=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}}))},a=function(e,t,i){var n=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var a=0;a<t.names.length;a+=1){var s=t.names[a];t.name?n.push(i[t.name][s]):n.push(i[t.names[a]])}else n.push(i[t.name]);return r.apply(null,n)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=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 n=t.outerOrder||s,r=t.innerOrder||o,l=[];return n.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(a(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(a(t,i,e))}))}))})),e.media.forEach((function(e){l.push(a("m",i.m[0],e)),r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?l.push(a(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){l.push(a(t,i,e))}))}))}))})),l.join("\r\n")+"\r\n"}}}),ye=u({"../node_modules/sdp-transform/lib/index.js"(e){var t=ve(),i=Se();e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),Ce={};h(Ce,{HttpRequestDispatcherImplementation:()=>Ve,generateCauseId:()=>Te,getOvb:()=>Xt,getVersion:()=>Zt,pluginlessStackFactory:()=>aU}),r.exports=(e=>m(s({},"__esModule",{value:!0}),e))(Ce);var _e=f(z()),Ee=8;function Te(){const e="abcdef0123456789";let t="";for(let i=0;i<Ee;i++)t+=e.charAt(Math.floor(16*Math.random()));return t}var be=p,Ie=g,we=class e{constructor(e,t,i=""){this.ulLogComponent=e,this.ulSafeComponent=t,this._getPrefix=(0,Ie.isFunction)(i)?i:()=>i,this.logComponent=be.LogFactory.instance().component(this.ulLogComponent),be.LogFactory.instance().declareComponentSafe(this.ulLogComponent,t)}createChild(t){const i=(0,Ie.isFunction)(t)?t:()=>t;return new e(this.ulLogComponent,this.ulSafeComponent,(()=>this._getPrefix()?`${this._getPrefix()}/${i()}`:i()))}log(...e){this._apply((e=>this.logComponent.debug2(null,e)),e)}debug(...e){this._apply((e=>this.logComponent.debug4(null,e)),e)}info(...e){this._apply((e=>this.logComponent.debug1(null,e)),e)}warn(...e){this._apply((e=>this.logComponent.warn(null,e)),e)}error(...e){this._apply((e=>this.logComponent.error(null,e)),e)}_apply(e,t=[]){this._addPrefix(t),e(t.map((e=>e instanceof DOMException?e.toString():e)).map((e=>(0,Ie.isObject)(e)?JSON.stringify(e):e)).join(", "))}_addPrefix(e){if(e&&e[0]){const t=`${this._getPrefix()} ${e[0]}`;e[0]=t}}},Re=p;function Ae(e){return"string"==typeof e?Re.pii.Mri(e):Re.pii.Omit(e)}function Pe(e){return e&&Re.pii.Mri(e)}function Me(e){const t=function(e){const t="99:";return e&&e.substr(0,3)===t?Re.pii.Omit(e):e}(e);return t&&t.substr(0,8)}var ke=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason"];function De(e){try{return JSON.parse(JSON.stringify(e,ke,4))}catch(e){return{error:"failed to parse object"}}}var Oe=e=>{try{return e.split("\n")[0]}catch(e){return"invalid stack"}};function Ne(e,t=!1){if(null==e)return"void";if(e instanceof Error)return e.toString();if(e instanceof String||e instanceof Number||e instanceof Boolean)return e.toString();try{return e.stack&&(e.stack=Oe(e.stack)),(t?JSON.stringify(e):JSON.stringify(e,ke,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(t){return`failed to get error information:${e&&"function"==typeof e.toString&&e.toString()} ${e?.response&&JSON.stringify(e.response)}`}}function Le(e){try{return JSON.stringify(e,null,2)}catch(t){return`failed to stringify obj ${e}`}}function xe(e,t){try{return e.substring(0,length)}catch(t){return e}}function Fe(e){return e||!1===e||""===e||0===e}function Ue(e){if(!e)return!1;try{return atob(e),!0}catch(e){return!1}}function Be(e){if(!e)return`${e}`;if(e instanceof Map)return function(e){const t={};return e.forEach(((e,i)=>{t[i.toString()]=e})),JSON.stringify(t)}(e);const t=e.toString();return t.endsWith("[object Object]")?JSON.stringify(e):t}var Ve=class{constructor(e){e&&"function"==typeof e.createChild?this.logger=e.createChild("RequestDispatcher"):this.logger=new we("JS.TsCalling.RequestDispatcher",!1)}getRequestOptions(e,t,i,n,r){return{headers:t||{},timeout:n,payload:i||null,responseType:r}}getAsync(e,t){return this.sendRequest(e,t,"GET")}postAsync(e,t){return this.sendRequest(e,t,"POST")}putAsync(e,t){return this.sendRequest(e,t,"PUT")}removeAsync(e,t){return this.sendRequest(e,t,"DELETE")}async sendRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||Te()}][Request]`);n.info(`sending, ${i}-${e}`);const r=Date.now();let a;t.headers=t.headers||{},t.headers["content-type"]||(t.headers["content-type"]=t.contentType||"application/json");try{const s=_e.default.request({url:e,method:i,headers:t.headers||{},timeout:"number"==typeof t.timeout?t.timeout:45e3,data:t.payload||"",responseType:t.responseType||t.dataType||"json",withCredentials:He(t.withCredentials,!1),cancelToken:new _e.default.CancelToken((e=>{a=e}))});(function(e){return!!e&&"function"==typeof e.then})(t.timeout)&&t.timeout.then((()=>{n.info("Aborting pending request"),a()}),(()=>{n.info("Timeout promise rejected, ignoring")}));const o=await s;return n.info(`success, status=${o.status}`),{response:o.data,request:o.request,duration:Date.now()-r}}catch(e){if(n.info("failed"),_e.default.isCancel(e))throw n.info(`response=${Le(e.response)}`),{aborted:!0};throw e.response?n.info(`response=${Le(e.response)}`):e.request?n.info(`no response, request=${Le(e.request)}`):n.info(`request not made, error=${Le(e)}`),e||new Error("Request failed")}}};function He(e,t){return void 0!==e?e:t}var $e=g,Ge=g,je=class{constructor(e){this.eventLogger=e,this.subscriptions=[]}subscribe(e){return new ze(this.subscriptions,e)}dispose(e){this.subscriptions=[]}raiseEvents(e){this.subscriptions.slice().forEach((t=>{try{void 0!==t.eventHandler&&e(t.eventHandler)}catch(e){this.eventLogger?.warn?.("Event handler exception caught!",Be(e))}}))}},ze=class{constructor(e,t){this.subscriptions=e,this.eventHandler=t,this.subscriptions.push(this)}dispose(){(0,Ge.remove)(this.subscriptions,(e=>e===this)),this.eventHandler=void 0}},We=class extends je{constructor(e){super(e)}changed(e,t){return this.subscribe({changed:{skipEventConfig:t,handler:e},on:void 0})}on(e,t){return this.subscribe({changed:void 0,on:{name:String(e),handler:this._toEventCallback(t)}})}once(e,t,i){let n;return n=this.on(e,this._fromEventCallback(((...e)=>{n.dispose(i),this._toEventCallback(t)(...e)}))),n}raiseChanged(e){this.raiseEvents((t=>{if(!t.changed)return;const{skipEventConfig:i,handler:n}=t.changed;!this.getShouldSkipChangedEvent(e,i)&&n()}))}event(e){return{raise:this._fromEventCallback(((...t)=>this._raiseEventImpl(String(e),...t)))}}_raiseEventImpl(e,...t){this.raiseEvents((i=>i.on&&i.on.name===e&&i.on.handler(...t)))}_toEventCallback(e){return e}_fromEventCallback(e){return e}getShouldSkipChangedEvent(e,t){return e?.skipDominantSpeakerUpdatesOnCall?!!t?.skipDominantSpeakerUpdatesOnCall:!!e?.skipParticipantsUpdatesOnCall&&!!t?.skipParticipantsUpdatesOnCall}},qe=We,Ke="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",Je="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",Ye="http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00",Qe={MEDIA_STATE:{send:"sendonly",receive:"recvonly",sendReceive:"sendrecv",inactive:"inactive"},MEDIA_DIRECTION:{SEND:"send",RECV:"recv"},MEDIA_DEVICE_KIND:{audioInput:"audioinput",audioOutput:"audiooutput",videoInput:"videoinput",compositeAudio:"compositeAudio",virtualDevice:"virtualDevice"},MEDIA_DEVICE:{camera:"camera",microphone:"microphone",speaker:"speaker",compositeAudio:"compositeAudio",defaultId:"default",communicationsId:"communications",defaultDeviceLabel:"Default",audioIngestDevice:"audioIngestDevice",virtualDevice:"virtualDevice"},MEDIA_ERROR:{constraintNotSatisfiedError:"ConstraintNotSatisfiedError",iceConnectionError:"iceConnectionError",srtpError:"srtpError",permissionDeniedError:"permissionDeniedError",internalError:"internalError",sourceUnavailableError:"SourceUnavailableError",devicesNotFoundError:"DevicesNotFoundError",noDeviceSelected:"noDeviceSelected",noNetworkError:"noNetworkError",incompatibleOffer:"IncompatibleOffer",mediaStreamRequestError:"MediaStreamRequestError",extensionNotFoundError:"ExtensionNotFoundError",sharingCancelledError:"SharingCancelledError",permissionDeniedBySystemError:"PermissionsDeniedBySystem",chromeRuntimeNotDefinedError:"ChromeRuntimeNotDefinedError",mediaStreamRequestTimedOut:"MediaStreamRequestTimedout",unsupportedStream:"UnsupportedStream",webGlRendererError:"WebGlRendererError",audioPlaybackError:"audioPlaybackError",unexpectedClose:"unexpectedClose",incompatibleOriginator:"incompatibleOriginator"},HISTOGRAM_BATCH:{seconds1to3:2,seconds3to5:4,seconds5to8:7,seconds8to15:14,seconds15to60:59,seconds60toMax:1e6},RENEGOTIATION_ERROR:{local:"local",glare:"glare",signaling:"signaling",media:"media",escalation:"escalation"},MSI:{unsubscribe:-1,subscribeAny:-2},MEDIA_LABEL:{audio:"main-audio",video:"main-video",sharing:"applicationsharing-video",data:"data"},MEDIA_TYPE:{audio:"audio",video:"video",sharing:"sharing",data:"x-data",dataChannel:"application"},MODALITY:{audio:"audio",video:"video",sharing:"sharing",data:"data"},TRACK_KIND:{audio:"audio",video:"video"},ICE_TRANSPORT_POLICY:{all:"all",relay:"relay"},RENDERER_TYPE:{video:"video",sharing:"sharing"},CONTENT_TYPE:{SDP:"application/sdp"},ALLOWED_CONTENT_TYPES:{SDP_ONLY:["application/sdp"],SDP_NGC:["application/sdp","application/sdp-ngc-0.5","application/sdp-ngc-1.0"]},STREAMING_STATE:{created:"created",started:"started",active:"active",inactive:"inactive",stopped:"stopped",removed:"removed",failed:"failed"},TIME_INTERVAL:{SEC_1:1},DISPLAY_SOURCE_ID:"display",EMPTY_DEVICE_ID:"0",SYSTEM_AUDIO_SOURCE_ID:"system",MULTIPLE_RECV_STREAMS:"multipleVideoStreams",PROFILES:{udpTlsRtpSavpf:"UDP/TLS/RTP/SAVPF",rtpSavpf:"RTP/SAVPF",rtpSavp:"RTP/SAVP",udpDtlsSctp:"UDP/DTLS/SCTP"},REPORTING_PROFILE:{RT_PROFILE:"REAL_TIME",BE_PROFILE:"BEST_EFFORT",NRT_PROFILE:"NEAR_REAL_TIME"},PAYLOAD_TYPE:{DATA_CHANNEL:"webrtc-datachannel",X_DATA:"127 126",MSRTC_RED:97,MSRTC_CNFB:120},VIDEO_CAPABILITIES:{MAX_FS_PATH:"max-fs",MAX_MBPS_PATH:"max-mbps",MAX_FPS_PATH:"max-fps",MAX_BR_PATH:"max-br",SSRC_PATH:"ssrc",RID_PATH:"rid",KEYFRAME_PATH:"KeyFrame",MAX_WIDTH:"max-width",MAX_HEIGHT:"max-height",VLA_DEBUG:"vla-debug"},TRANSPORT_CC:{EXT_URI:Ke,MSSDP_ENCODED_URI:Ke.replace(/\//g,"\\"),ATTRIBUTE:"transport-cc"},ABS_SEND_TIME:{EXT_URI:Je,MSSDP_ENCODED_URI:Je.replace(/\//g,"\\")},VLA:{EXT_URI:Ye,EXT_URI_NON_ADV:Ye+"-non-advertised",DEFAULT_VALUE:10},AUDIO_DECODER:{MUCHv2:{CODEC:{NAME:"x-much2",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:113},SatinFB:{CODEC:{NAME:"SATINFB",RATE:48e3,ENCODING:2},SUBSTITUTION:{NAME:"L16",RATE:48e3,ENCODING:2},PT:109}},MACROBLOCK_SIZE:16,MEDIA_EVENT_FIELDS:{Extensions:["IceConnectionState","IceConnectionStatePrevious","SignalingState","SignalingStatePrevious"],metrics:["ReconnectInProgress","IceConnectedStateTime","ErrorType","ErrorDetail","InitialNegotiationType","InitialNegotiationCompleted"]},RES_TABLE:{SEND:[{w:320,h:180,minBr:2e4,maxBr:175e3},{w:416,h:234,minBr:125e3,maxBr:5e5},{w:640,h:360,minBr:4e5,maxBr:575e3},{w:960,h:540,minBr:5e5,maxBr:1125e3},{w:1280,h:720,minBr:1e6,maxBr:25e5},{w:1920,h:1080,minBr:175e4,maxBr:1e8}],RECV:[{w:320,h:180,minBr:2e4,maxBr:175e3},{w:426,h:240,minBr:125e3,maxBr:5e5},{w:640,h:360,minBr:4e5,maxBr:575e3},{w:960,h:540,minBr:5e5,maxBr:1125e3},{w:1280,h:720,minBr:1e6,maxBr:25e5},{w:1920,h:1080,minBr:175e4,maxBr:1e8}]}};function Ze(e,t){for(const i in e)e.hasOwnProperty(i)&&t(e[i],i)}function Xe(e,t){for(const i in e)e.hasOwnProperty(i)&&("object"==typeof e[i]?Xe(e[i],t):t(e[i],i,e))}function et(e){return null!=e&&!Number.isNaN(e)}function tt(e,t){return et(t)?et(e)?Math.min(e,t):t:e}function it(e){let t=0;return e.forEach((e=>t+=e)),t/=e.length,t}function nt(e,t){let i=!1;for(let n=e.length;n-- >0;)t(e[n],n,e)&&(e.splice(n,1),i=!0);return i}function rt(e){const t=[];for(const i in e)e.hasOwnProperty(i)&&t.push(e[i]);return t}function at(e){return!Object.keys(e).length}function st(e){return Object.keys(e)}function ot(e){const t={};return Ze(e,((e,i)=>{t[i]=e})),t}function lt(e){let t;if(!e||"object"!=typeof e)return e;if(e instanceof Date)return t=new Date,t.setTime(e.getTime()),t;if(e instanceof Array){t=[];for(let i=0,n=e.length;i<n;i++)t[i]=lt(e[i]);return t}if(e instanceof Object)return t={},Ze(e,(function(e,i){t[i]=lt(e)})),t;throw new Error("Unable to copy: "+Be(e))}function ct(e){return Object.keys(e).forEach((t=>{void 0===e[t]&&delete e[t]})),e}function dt(){const e=()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1);return e()+e()+e()+"4"+e().substring(1)+"b"+e().substring(1)+e()+e()+e()}function ut(e,t){let i;const n=typeof e;if(e===t)return!0;if(n!==typeof t||"object"!==n&&"function"!==n)return!1;if(null===e||null===t)return e===t;if(e instanceof Date&&t instanceof Date)return+e==+t;if(e instanceof Map&&t instanceof Map)return function(e,t){let i;if(e.size!==t.size)return!1;let n=!0;return e.forEach(((e,r)=>{i=t.get(r),(i!==e||void 0===i&&!t.has(r))&&(n=!1)})),n}(e,t);for(i in e)if(!(i in t)||!ut(e[i],t[i]))return!1;for(i in t)if(!(i in e)||!ut(e[i],t[i]))return!1;return!0}function ht(e,t){if(-1===t.indexOf(e))throw{detail:`${e} mediaContent.contentType is not supported`,type:Qe.MEDIA_ERROR.incompatibleOffer}}function pt(e,t){e.forEach((e=>{if(""!==e&&-1!==t.findIndex((t=>t===e)))throw{detail:`Required feature '${e}' is not acceptable.`,type:Qe.MEDIA_ERROR.incompatibleOffer}}))}function gt(e,t,i,n=0){for(let r=1;r<e.length;r++)if(e[r-1]+n<t&&t<=e[r]+n)return i?e[r]:e[r-1];return e[0]}function mt(e,t,i){return t<=e&&e<=i}function ft(e,...t){for(const i of t)if(i.hasOwnProperty(e))return i[e]}function vt(e,t){return e.filter((e=>!t.some((t=>t===e))))}function St(e,t){if(e===t)return e;let i=0,n=0,r="";for(let a=0;a<e.length&&!(r.length>e.length-a);a++){let s=a;n-i>r.length&&(r=e.substring(i,n),a=n-1),i=a,n=a;for(let o=0;o<t.length;o++)s<e.length&&t[o]===e[s++]?n=s:(s=a,n-i>r.length&&(r=e.substring(i,n),a=n-1),i=a,n=a)}return r}function yt(e,t){const i=new Array(e.length+1);for(let n=0;n<e.length+1;n++){i[n]=new Array(t.length+1);for(let e=0;e<t.length+1;e++)i[n][e]=0}for(let t=1;t<e.length+1;t++)i[t][0]=t;for(let e=1;e<t.length+1;e++)i[0][e]=e;for(let n=1;n<e.length+1;n++)for(let r=1;r<t.length+1;r++){let a=1;e[n-1]===t[r-1]&&(a=0),i[n][r]=Math.min(i[n-1][r]+1,i[n][r-1]+1,i[n-1][r-1]+a)}return i[e.length][t.length]}function Ct(e,t=3){return e&&parseFloat(e.toFixed(t))}function _t(e,t){if(!e)return"";if(e.length<3)return e;const i=[],n=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);n&&i.push(n[1]);try{if(t?.length){const n=new RegExp(`(${t.join("|")})`,"gi");let r=n.exec(e);for(;r;)i.push(r[1]),r=n.exec(e)}else i.push("no_keywords")}catch(e){i.push(`Error: ${Be(e)}`)}return 0===i.length?"unknown":i.join(" ")}function Et(e,t,i=0){return e&&void 0!==t&&t>-1&&e.length>t&&e.splice(i,e.length-t),e}function Tt(e,t,i,n=0){Et(e,0===i?0:i-1,n),0!==i&&e.push(t)}function bt(e,t){const i={};for(const e in t)i[e]={get:t[e],configurable:!1,enumerable:!0};Object.defineProperties(e,i)}function It(e){return e?.length>0?e[e.length-1]:void 0}var wt=window?.performance?.now&&window?.performance?.timeOrigin,Rt=wt?()=>window.performance.now():()=>Date.now(),At=wt?window.performance.timeOrigin:0,Pt=Rt,Mt=At;function kt(e,t,i){if(e?.length>0){const n=[];for(const r of e){const e=lt(r);e[t]=e[t]&&e[t]-i,n.push(e)}return n}return e}function Dt(e,t){if(!e)return;const i={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]};for(const[n,r]of Object.entries(e))for(const e of r)i[n].push(e-t);return i}function Ot(e,t,i=!1){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e&&""!==e&&(!1===i||0!==e)));return n?.length?n.join(","):void 0}function Nt(e,t,i){const n=e?.map(t).filter((e=>void 0!==e&&!isNaN(e)&&null!==e&&""!==e)).splice(-i);return n?.length?n:void 0}function Lt(e,t){const i=[];for(const n of e.keys())t.has(n)||i.push(n);for(const t of i)e.delete(t)}function xt(e){return"object"==typeof e?Be(e):e}function Ft(e){const t=Object.keys(e).map(Number).sort(((e,t)=>e-t)),i=t.reduce(((t,i)=>t+(e[i]??0)),0);return{getPercentile:n=>{const r=i*n;let a=0;for(const i of t)if(a+=e[i],a>=r)return i}}}function Ut(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}function Bt(e){const t=e.toLowerCase(),i='token_types="',n=t.indexOf(i);if(-1===n)return[];const r=t.indexOf('"',n+13);if(-1===r)return[];const a=t.substring(n+13,r).trim();return""===a?[]:a.split(" ")}var Vt=g,Ht={numVideoChannelsGvc:({current:e,constraints:t})=>jt(e,t),specCompliantSimulcast:({current:e,constraints:t})=>Wt(e,t),multiviewResolutionLimits:({current:e,constraints:t,logger:i})=>zt(e,t,i),enableVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Jt(e,t,i,n),allowRemoteVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Jt(e,t,i,n),enableNonAdvVla:({current:e,settings:t,constraints:i,settingsSuffix:n})=>Jt(e,t,i,n),outgoingVideoLimit:({current:e,constraints:t})=>Kt(e,t)},$t=(e,t,i)=>({...Gt(e,t,i),...Gt(e,t,i,"1on1"),...Gt(e,t,i,"Multiparty")}),Gt=(e,t,i,n)=>{const r={};for(const a of Object.keys(Ht)){const s=`${a}${n??""}`;n&&!et(t[s])||(r[s]=Ht[a]({current:t[s],settings:t,constraints:i,settingsSuffix:n,logger:e}))}return r},jt=(e,t)=>tt(e,t.maxIncomingStreams),zt=(e,t,i)=>{const n=t.maxParticipantResolutions;if(!n)return e;const r={more:e.more};if(Number.isInteger(n))Object.keys(e).forEach((t=>{r[t]=tt(n,e[t])}));else{const t=Object.keys(n);if(!t.length)return i.warn(`ignoring invalid value provided for maxParticipantResolutions: ${n}}`),e;t.forEach((t=>{r[t]=tt(n[t],e[t]||e.more)}))}return r},Wt=(e,t)=>void 0!==t.maxSimulcastLayers||e.allowOverride?{...e,video:qt(e.video,t),sharing:qt(e.sharing,t)}:e,qt=(e,t)=>{const i=e?.layerScaleFactors?.filter((e=>e<=t.maxSimulcastLayers));return i?.length>1?{...e,layerScaleFactors:i}:{...e,enableLocally:!1,allowEnableRemotely:!1}},Kt=(e,t)=>{const{outgoingVideoLimit:i,maxOutgoingResolution:n}=t,r=(0,Vt.isNumber)(i),a=tt(r?i:i?.maxResolution,n),s=tt(e?.maxResolution,a),o=tt(e?.maxBitrate,r?void 0:i?.maxBitrate),l=tt(e?.maxFramerate,r?void 0:i?.maxFramerate);return{...e,maxResolution:s,maxBitrate:o,maxFramerate:l}},Jt=(e,t,i,n)=>!((t.specCompliantSimulcast.constraintsDisableVla||t[`specCompliantSimulcast${n}`]?.constraintsDisableVla)&&i.maxSimulcastLayers<2)&&e,Yt=class extends qe{constructor(e){super(e),this.logger=e,this._constraints={},this._callConstraintsTelemetry=[]}get constraints(){return this._constraints}get callConstraintsTelemetry(){return this._callConstraintsTelemetry}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};this._callConstraintsTelemetry.push(i)}setConstraints(e){this.logger.debug("Setting new platform call constraints",JSON.stringify(e)),this._constraints=e,this.addCallConstraintsTelemetryEvent(e,"requested"),this.raiseChanged()}getSettings(e){return $t(this.logger,e,this._constraints)}},Qt=class e{constructor(e){this._callingLogger=e,this._maybeLog=(e,...t)=>{try{this._callingLogger[e](...t)}catch(e){this._callingLogger.info("[failed to log]",Ne(e))}}}getPrefix(e,t){let i="";return t&&(i+=`[${t}]`),e&&(i+=`[${e}]`),i}createChild(t,i){return new e(this._callingLogger.createChild(t,i))}createFnLogger(t,i,...n){return new e(this._callingLogger.createChild(this.getPrefix(t,i)+n.join(""),!1))}logSuccess(e){this._maybeLog("info",`success=${e}}`)}logFailure(e){const t=Ne(e);this._maybeLog("info",`failed=${t}}`)}log(...e){this._maybeLog("log",...e)}debug(...e){this._maybeLog("debug",...e)}info(...e){this._maybeLog("info",...e)}warn(...e){this._maybeLog("warn",...e)}error(...e){this._maybeLog("error",...e)}};function Zt(){return"2024.14.01.23"}function Xt(){return"7b433484b6052f263c376357e5f0a7c2fecbb27f"}var ei=g,ti="0.0";function ii(e,t){let i=[];if(t.some((t=>(i=e.match(t),!!i))),!i||i.length<2)return ti;const n=i[1]?.replace(/_/g,".");return n||ti}function ni(e){return"136"===function(){const e="os-sku",t=window.external;return t?.getHostEnvironmentValue?JSON.parse(t.getHostEnvironmentValue(e))[e]:"-1"}()?"Hololens":/hostAudio-Processing/i.test(e)?"RoomAudioProcessing":/iPhone|iPad|iPod|Android|Mobi/i.test(e)?"Mobile":"Desktop"}function ri(){const e="((\\d+\\.?){2,4})",t={name:"Unknown",engine:"Unknown",version:ti,formFactor:"Unknown"},i=[{name:"WebView2",engine:"Chromium",key:"maglev",masks:[new RegExp(`maglev/${e}`)]},{name:"Edge",engine:"Edge",key:"Edge",masks:[new RegExp(`Edge/${e}`)]},{name:"EdgeAnaheim",engine:"Chromium",key:"EdgA",masks:[new RegExp(`Chrome/${e}`)]},{name:"EdgeAnaheim",engine:"Chromium",key:"Edg",masks:[new RegExp(`Edg/${e}`)]},{name:"Chromium",engine:"Chromium",key:"Chromium",masks:[new RegExp(`Chromium/${e}`)]},{name:"Opera",engine:"Chromium",key:"OPR",masks:[new RegExp(`Chrome/${e}`)]},{name:"YandexBrowser",engine:"Chromium",key:"YaBrowser",masks:[new RegExp(`Chrome/${e}`)]},{name:"Electron",engine:"Chromium",key:"Electron",masks:[new RegExp(`Electron/${e}`)]},{name:"CiscoOS",engine:"Chromium",key:"Cisco",masks:[new RegExp(`Chrome/${e}`)]},{name:"ZoomRoom",engine:"Chromium",key:"ZoomRoom",masks:[new RegExp(`Chrome/${e}`)]},{name:"SamsungTV",engine:"Chromium",key:"TeamsSamsungTVBrowser",masks:[new RegExp(`Chrome/${e}`)]},{name:"Chrome",engine:"Chromium",key:"Chrome",masks:[new RegExp(`Chrome/${e}`)]},{name:"Firefox",engine:"Firefox",key:"Firefox",masks:[new RegExp(`Firefox/${e}`)]},{name:"Safari",engine:"Safari",key:"Safari",masks:[new RegExp(`Version/${e}.*?Safari/`)]},{name:"AppleWebView",engine:"Safari",key:"Mac OS X",masks:[new RegExp("(\\d+_\\d+(_\\d+)?).*Mac OS X"),new RegExp("(\\d+_\\d+(_\\d+)?).*")]},{name:"MSIE",engine:"MSIE",key:"Trident",masks:[new RegExp(`MSIE ${e}`),new RegExp(`rv:${e}`)]}],n=navigator.userAgent;let r=t;return i.some((e=>{if(-1!==n.indexOf(e.key)){const t=window.navigator.mediaDevices?.isRemote;return r={name:e.name,engine:t?"ChromiumAVD":e.engine,version:ii(n,e.masks),formFactor:ni(n)},!0}return!1})),r}var ai={src:["//amp.azure.net/libs/amp/2.3.8.4/azuremediaplayer.min.js","https://amsglob0cdnstream13.azureedge.net/1-0-3013-17/bundles/player-skin.min.js"],css:["https://amsglob0cdnstream13.azureedge.net/1-0-3013-17/bundles/player-skin.min.css","https://statics.teams.cdn.office.net/evergreen-assets/broadcast/video-player.css?v=2"],styles:["azuremediaplayer","amp-stream-skin","amp-big-play-centered"],lang:"en-us",disableFullscreenButton:!1,playerType:0},si={src:["https://azuremdncdnhlsendpoint.azureedge.net/hlsjsv115/hls.js","https://vzmdncdnendpoint.azureedge.net/hlsjsv115/hls.js"],css:[],styles:[],lang:"en-us",disableFullscreenButton:!1,muteVideo:!1,playerType:1,hydraPlayerWebSdkUrls:["https://afdhls.playerscript.prod.ml.cdn.office.net/hlsrt2023-1208-2/hydra_player_hls_bundle.js","https://vzhls.playerscript.prod.ml.cdn.office.net/hlsrt2023-1208-2/hydra_player_hls_bundle.js"]},oi={src:[],css:[],styles:[],playerType:2,hydraPlayerWebSdkUrls:["https://afdhls.playerscript.prod.ml.cdn.office.net/umsrt2023-1207-3/hydra_player_ums_bundle.js","https://vzhls.playerscript.prod.ml.cdn.office.net/umsrt2023-1207-3/hydra_player_ums_bundle.js"]},li=class{constructor(e,t,i,n){this.configIds=i,this.logger=n,this.defaultSettings=function(){let e;return e="Safari"===ri().engine?new di:new ci,e.getSettings()}(),this.logger.info(`client settings: ${JSON.stringify(t)}`),this.defaultSettings.debug=t?.debug||!1,this.defaultSettings.playerType=t?.playerConfig?.playerType||this.defaultSettings.playerType,t?.playerConfig&&(0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration=t.playerConfig:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration=t.playerConfig:2===this.defaultSettings.playerType&&(this.defaultSettings.umsSettings.liveStreamPlayerConfiguration=t.playerConfig)),(0,ei.mergeWith)(this.defaultSettings,e,ui),this.logger.info(`applied settings: ${JSON.stringify(this.defaultSettings)}`)}get playerConfig(){return 0===this.defaultSettings.playerType?this.defaultSettings.ampSettings.liveStreamPlayerConfiguration:1===this.defaultSettings.playerType?this.defaultSettings.hlsSettings.liveStreamPlayerConfiguration:2===this.defaultSettings.playerType?this.defaultSettings.umsSettings.liveStreamPlayerConfiguration:null}get config(){return this.defaultSettings}},ci=class{constructor(){this.defaultSettings={allowSdnPlugins:!0,capturePlayerLogs:!0,playerType:0,loadType:1,maxPlayerDiagnosticsCount:50,maxPlayerMemoryTraceLogCount:1e3,maxPlayerPlaybackEventCount:50,maxRetryCount:10,playerTelemetryTickMs:1e3,removeEmptyDefaultTextTrack:!0,sendSnapshotTelemetry:!1,sendSnapshotTelemetryEveryMs:1e4,sendInitialTelemetryAfterMs:6e4,sendTelemetry:!0,textTrackKind:"subtitles",maxRetryCountForLoadingResources:5,maxVideoTrackHistoryLogCount:100,ampSettings:{errorCodesEligibleForStreamingUrlSwitch:[4194309,2097564,2097556,2097752,2097753,5242884],liveStreamPlayerConfiguration:ai,sourceResetTimeoutInMs:1e3,streamingUrlSwitchMaxCount:2,resetStreamingUrlSwitchCount:!1,useBrowserWindowSizeForBitRate:!0,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,collectUserInitiatedSeekEventsTelemetry:!0,maxUserInitiatedSeekEventCount:100,noMediaTimeoutMs:-1},hlsSettings:{liveStreamPlayerConfiguration:si,timeoutForSwitchingUrl:9e3,estimateAbsoluteTime:!0,maxAbsoluteTimeOffsetEstimationResultsLogCount:100,playlistInitialSequenceNumber:1,skipNonce:!1,maxStreamConnectionResultsLogCount:100,logHlsJsEvents:!1,logHlsJsEventsEveryMs:5e3,maxPlayerExperimentalEvents:100},umsSettings:{liveStreamPlayerConfiguration:oi,timeoutForSwitchingUrl:9e3,maxStreamConnectionResultsLogCount:100,minTargetEdgeLatency:.2,maxEdgeLatencyHistoryLength:300,latencyCompensationThreshold:.5,maxPlayerExperimentalEvents:100}}}getSettings(){return this.defaultSettings}},di=class extends ci{constructor(){super(),this.settings=super.getSettings(),this.settings.loadType=0,this.settings.allowSdnPlugins=!1,this.settings.umsSettings.minTargetEdgeLatency=.6,this.settings.umsSettings.latencyCompensationThreshold=.9}getSettings(){return this.settings}};function ui(e,t){if((0,ei.isArray)(e))return t.slice()}function hi(e){return!!e&&!!e.url&&!!e.decryptionToken}function pi(e,t,i){if(!e&&!i)throw new Error("Assert failed"+(void 0!==t?`: ${t}`:""))}var gi=class{constructor(e,t,i){this.name=e,this.stopCrash=t,this.start(i)}complete(){pi(this.startTime,"not started",this.stopCrash),pi(void 0===this.duration,"already completed",this.stopCrash),this.duration=Date.now()-this.startTime}updateDetails(e,t){if(this.details&&"object"==typeof this.details)for(let i=0;i<e.length;i++)this.details[e[i]]=t[i]}fail(e){this.failReason=e,this.complete()}set detail(e){this.details=e}getTelemetryEvent(){pi(this.startTime,"not started",this.stopCrash);try{pi(void 0!==this.duration,"not completed",this.stopCrash)}catch(e){if("SetSource"!==this.name&&"Load"!==this.name)throw e}const e={name:this.name,startTime:this.startTime,duration:this.duration};return this.failReason&&(e.failReason=this.failReason),this.details&&(e.details=this.details),e}start(e){pi(!this.startTime,"already started",this.stopCrash),this.startTime=Date.now(),this.details=e}},mi=class{constructor(e,t,i){this.config=e,this.logger=t,this.playerDiagnosticsLog=i,this.currentScenarioMap=new Map,this.playerEvents=[],this.playbackEvents=[],this.userInitiatedSeekEvents=[],this.experimentalEvents=[],this.clientNetworkType=void 0,this.maxPlayerPlaybackEventCount=e.maxPlayerPlaybackEventCount||5,this.maxPlayerDiagnosticsCount=e.maxPlayerDiagnosticsCount||5,this.maxPlayerMemoryTraceLogCount=e.maxPlayerMemoryTraceLogCount||100,this.maxUserInitiatedSeekEventCount=e.ampSettings?.maxUserInitiatedSeekEventCount||100,this.stopCrash=e.stopCrash||!1,this.config.debug&&(this.playerDiagnosticsLog.memoryLog=[]),this.addNetworkTypeEventListener()}getPlayerDiagnosticSnapshot(){return this.currentPlayerDiagnosticSnapshot}registerStatsUpdated(e){this.currentPlayerDiagnosticSnapshot=e,Object.keys(this.playerDiagnosticsLog).forEach((t=>{const i=t,n=this.playerDiagnosticsLog[t];if(Array.isArray(n)){n.push(e[i]);const t="memoryLog"===i&&n.length>this.maxPlayerMemoryTraceLogCount,r="memoryLog"!==i&&n.length>this.maxPlayerDiagnosticsCount;(t||r)&&n.splice(0,1)}else this.playerDiagnosticsLog[t]=e[i]}))}registerEventLoadAttempt(e,t){this.registerScenario(e,t)}registerEventLoadFailed(e,t){this.completeScenario(e,t)}registerEventLoadSucceeded(e,t){this.completeScenario(e,void 0,t)}registerPlayerLoadAttempt(){this.registerScenario("Load")}registerPlayerLoadSucceeded(e){this.completeScenario("Load",void 0,e)}registerPlayerLoadFailed(e){this.completeScenario("Load",e)}registerPlayerSetupAttempt(){this.registerScenario("Setup")}registerPlayerSetupSucceeded(){this.completeScenario("Setup")}registerPlayerSetupFailed(e){this.completeScenario("Setup",e)}registerStreamConnectionAttempt(e){this.registerScenario("StreamConnection")}registerStreamConnectionSucceeded(){this.completeScenario("StreamConnection")}registerStreamConnectionFailed(e){this.completeScenario("StreamConnection",e)}registerSetSourceAttempt(e,t){let i=e;t&&(i={src:e,reason:t}),this.registerScenario("SetSource",i)}registerSetSourceSucceeded(e){this.getScenario("SetSource").updateDetails(["src"],[e]),this.completeScenario("SetSource")}registerSetSourcedFailed(e,t){this.getScenario("SetSource").updateDetails(["src"],[t]),this.completeScenario("SetSource",e)}registerSdnPluginLoad(e,t,i){this.registerScenario("SdnPluginLoad",e);const n=t?void 0:i;this.completeScenario("SdnPluginLoad",n)}registerPlayerDestroyed(e){this.registerScenario("Destroyed",e),this.completeScenario("Destroyed")}registerPlaybackStateChanged(e,t){let i;"Ready"!==e||this.firstReadyStateTimestamp?"Playing"!==e||this.firstPlayingStateTimestamp||(this.firstPlayingStateTimestamp=Date.now()):this.firstReadyStateTimestamp=Date.now(),t&&"Buffering"===e&&(t?i=t.message:this.logger.debug(`Unexpected buffering payload: ${JSON.stringify(t)}`)),this.registerPlaybackEvent("StateChanged",e,i)}registerPlaybackError(e,t){this.registerPlaybackEvent("Error",{errorType:e,details:t})}registerDownloadBitratechanged(e){this.registerPlaybackEvent("BitrateChangedDownload",e)}registerStreamOptionsConfigured(e,t){this.registerPlaybackEvent("StreamOptionsConfigured",this.generateCleanedStreamOption(e),t)}registerPlaybackBitratechanged(e){this.registerPlaybackEvent("BitrateChangedPlayback",e)}registerPotentialMediaFreeze(e){this.registerPlaybackEvent("PotentialMediaFreeze",e)}registerCaptionToggle(e,t,i){const n={isEnabled:e,culture:t,playerTime:i};this.registerPlaybackEvent("CaptionsToggled",n)}registerFullScreenChange(e){this.registerPlaybackEvent("FullscreenChanged",e)}registerMute(e){this.registerPlaybackEvent("Mute",e)}registerVolumeChange(e){this.registerPlaybackEvent("Volume",e)}getExperimentalEvents(){return{playback_experimentalEvents:this.prepareForTelemetry(this.experimentalEvents)}}getUserInitiatedSeekEvents(){return{playback_userInitiatedSeekEvents:this.prepareForTelemetry(this.userInitiatedSeekEvents)}}getSnapshotReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;let n={};return this.currentPlayerDiagnosticSnapshot&&(n=this.filterAndPrepareTelemetry()),{isFullReport:!1,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2024.14.01.23",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...n}}getReport(e={}){const t=this.playerEvents.map((e=>e.getTelemetryEvent())),i=this.playbackEvents;return{callendReason:e.callendReason,isFullReport:!0,configIds:e.configIds||"",playerId:e.playerId||"",correlationId:e.correlationId||"",traceId:e.correlationId?e.correlationId.replace(/-/g,""):"",eTag:e.eTag||"",isFinal:e.isFinal??!1,isIframe:1===this.config.loadType,isFullscreenButtonDisabled:e.disableFullscreenButton??!1,threadId:e.threadId||"",telemetryTickMs:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.statsInterval?this.currentPlayerDiagnosticSnapshot.statsInterval:-1,tsCallingVersion:"2024.14.01.23",...this.getInitializationReport(t,i),...this.getPlaybackReport(i),...this.getBitrateReport(i),...this.getSdnReport(t),...this.getSetSourceReport(t),...this.getExperimentalEvents(),...this.getUserInitiatedSeekEvents(),networkType:this.getClientNetworkType(),callSetupSucceeded:this.getCallSetupSucceeded(t),callDropped:this.getCallDropped(i),...this.getPlayerDiagnosticLog()}}registerExperimentalEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);this.experimentalEvents.push(n),this.logTelemetryEvent(n)}registerUserInitiatedSeek(e){const t=(this.currentPlayerDiagnosticSnapshot?.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1)<e.newCurrentPlayPosition,i={...e,seekForward:t},n=this.createTelemetryEvent("UserInitiatedSeek",i);this.userInitiatedSeekEvents.push(n),this.userInitiatedSeekEvents.length>this.maxUserInitiatedSeekEventCount&&this.userInitiatedSeekEvents.splice(0,1)}createTelemetryEvent(e,t,i){const n={eventType:e,timestamp:Date.now(),currentPlayPosition:this.currentPlayerDiagnosticSnapshot&&this.currentPlayerDiagnosticSnapshot.currentPlayPosition?this.currentPlayerDiagnosticSnapshot.currentPlayPosition:-1};return void 0!==t&&(n.payload=this.prepareForTelemetry(t)),n.message=i,n}registerPlaybackEvent(e,t,i){const n=this.createTelemetryEvent(e,t,i);"Error"===e&&"PlaybackRetried"!==t?.errorType&&(n.fatal=!0),this.playbackEvents.push(n),this.playbackEvents.length>this.maxPlayerPlaybackEventCount&&this.playbackEvents.splice(0,1),this.logTelemetryEvent(n)}getPlayerDiagnosticLog(){if(!this.currentPlayerDiagnosticSnapshot)return{};const e={...this.currentPlayerDiagnosticSnapshot,...this.playerDiagnosticsLog},t={};return Object.keys(e).forEach((i=>{t[`player_${i}`]=this.prepareForTelemetry(e[i])})),t}getCallSetupSucceeded(e){const t=e.find((e=>"Load"===e.name));return!!t&&!t.failReason}getCallDropped(e){return!!e.filter((e=>"Error"===e.eventType)).find((e=>e.fatal))}getInitializationReport(e,t){const i=e.find((e=>"Load"===e.name));return{init_timeLoadToStreamConnectionEstablished:(i&&this.initialStreamConnectionEstablishedTimestamp?this.initialStreamConnectionEstablishedTimestamp-i.startTime:-1)||-1,init_timeLoadToReady:(i&&this.firstReadyStateTimestamp?this.firstReadyStateTimestamp-i.startTime:-1)||-1,init_timeLoadToPlaying:(i&&this.firstPlayingStateTimestamp?this.firstPlayingStateTimestamp-i.startTime:-1)||-1,init_allEvents:this.prepareForTelemetry(e)}}getPlaybackReport(e){const t=e.filter((e=>"StateChanged"===e.eventType)),i=t.find((e=>"Ready"===e.payload)),n=t.find((e=>"Play"===e.payload)),r=t.find((e=>"Start"===e.payload)),a=t.find((e=>"Playing"===e.payload)),s=i&&n?n.timestamp-i.timestamp:-1,o=n&&r?r.timestamp-n.timestamp:-1,l=r&&a?a.timestamp-r.timestamp:-1,c=t.filter((e=>"Seeked"===e.payload)),d=t.filter((e=>"Seeking"===e.payload)),u=t.filter((e=>"Paused"===e.payload)),h=t.filter((e=>"Resume"===e.payload)),p=t.filter((e=>"Buffering"===e.payload)),g=["BitrateChangedDownload","BitrateChangedPlayback","Error","Mute","StateChanged","Volume","StreamOptionsConfigured"],m=e.filter((e=>"Error"===e.eventType)),f=e.filter((e=>"Volume"===e.eventType||"Mute"===e.eventType)),v=e.filter((e=>"StreamOptionsConfigured"===e.eventType)),S=e.filter((e=>!g.includes(e.eventType)));return{playback_timeReadyToPlay:s,playback_timePlayToStart:o,playback_timeStartToPlaying:l,playback_bufferingEvents:this.prepareForTelemetry(p),playback_errorEvents:this.prepareForTelemetry(m),playback_pauseEvents:this.prepareForTelemetry(u),playback_resumeEvents:this.prepareForTelemetry(h),playback_otherEvents:this.prepareForTelemetry(S),playback_seekedEvents:this.prepareForTelemetry(c),playback_seekingEvents:this.prepareForTelemetry(d),playback_stateChangeEvents:this.prepareForTelemetry(t),playback_volumeEvents:this.prepareForTelemetry(f),playback_streamOptionsConfiguredEvents:this.prepareForTelemetry(v)}}generateCleanedStreamOption(e){return{...e,stream:{...e?.stream,decryptionToken:e?.stream?.decryptionToken?"valid":"empty",sdnContext:e?.stream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"},altStream:e?.altStream?{...e?.altStream,decryptionToken:e?.altStream?.decryptionToken?"valid":"empty",sdnContext:e?.altStream?.sdnContext?"valid":"empty",keyAuthorizationToken:e?.stream?.keyAuthorizationToken?"valid":"empty"}:void 0}}getBitrateReport(e){const t=e.filter((e=>"BitrateChangedDownload"===e.eventType)),i=t.sort((e=>Number(e.payload))),n=t.length?{bitrate_downloadChanges:this.prepareForTelemetry(t),bitrate_downloadChangeCount:t.length||-1,bitrate_downloadMin:i[0].payload||-1,bitrate_downloadMax:i[i.length-1].payload||-1}:{},r=e.filter((e=>"BitrateChangedPlayback"===e.eventType)),a=r.sort((e=>Number(e.payload)));return{...n,...r.length?{bitrate_playbackChanges:this.prepareForTelemetry(r),bitrate_playbackChangeCount:r.length||-1,bitrate_playbackMin:a[0].payload||-1,bitrate_playbackMax:a[a.length-1].payload||-1}:{}}}addNetworkTypeEventListener(){window.navigator?.connection?.type&&window.navigator?.connection?.addEventListener("change",(()=>this.updateClientNetworkType()))}updateClientNetworkType(){this.clientNetworkType=void 0,this.getClientNetworkType()}getClientNetworkType(){if(void 0===this.clientNetworkType){let e="Unknown";if(window.navigator?.connection?.type){const t=window.navigator?.connection?.type;switch(t){case"cellular":e="WWAN";break;case"ethernet":e="Wired";break;case"wifi":e="Wireless";break;default:e="Unknown"}}this.clientNetworkType=e}return this.clientNetworkType}getSdnReport(e){const t=e.filter((e=>"SdnPluginLoad"===e.name)),i=t.length?t[t.length-1]:void 0;return{sdn_loaded:!(!i||void 0!==i.failReason),sdn_details:i&&i.details||"",sdn_error:i&&i.failReason||"",sdn_events:this.prepareForTelemetry(t)}}getSetSourceReport(e){const t=e.filter((e=>"SetSource"===e.name));return{set_source_events:this.prepareForTelemetry(t)}}registerScenario(e,t){const i=this.currentScenarioMap.get(e),n=new gi(e,this.stopCrash,t);pi(!i,`previous scenario:${Be(i)} is not completed, new scenario:${Be(n)}`,this.stopCrash),this.currentScenarioMap.set(e,n),this.playerEvents.push(n)}getScenario(e){return this.currentScenarioMap.get(e)}completeScenario(e,t,i){const n=this.currentScenarioMap.get(e);pi(n,"no scenario to complete",this.stopCrash),t?n.fail(t):("StreamConnection"!==e||this.initialStreamConnectionEstablishedTimestamp||(this.initialStreamConnectionEstablishedTimestamp=Date.now()),i&&(n.detail=i),n.complete()),this.currentScenarioMap.delete(e)}logTelemetryEvent(e){this.config.debug&&(this.logger.debug(`PlayerTelemetryEvent: ${JSON.stringify(e)}`),this.logger.debug(`PlayerDiagnosticData: ${JSON.stringify(this.currentPlayerDiagnosticSnapshot)}`))}filterAndPrepareTelemetry(){const e=new Set;e.add("serviceLatencyCdg"),e.add("endToEndLatencyCdg"),e.add("videoEdgeLatencyCdg");const t={};return Object.keys(this.currentPlayerDiagnosticSnapshot).forEach((i=>{e.has(i)||(t[`player_${i}`]=this.prepareForTelemetry(this.currentPlayerDiagnosticSnapshot[i]))})),t}prepareForTelemetry(e){return"boolean"==typeof e?e:"string"==typeof e||void 0===e?e||"":"number"==typeof e?e??-1:JSON.stringify(e)}},fi=g;function vi(e){return new Promise((t=>{t(e())}))}function Si(){let e,t;return{promise:new Promise(((i,n)=>{e=i,t=n})),resolve:e,reject:t}}function yi(e){return new Promise((t=>setTimeout(t,e)))}function Ci(){const e=Ri(),t=Ai();let i;return(i||(i={})).CaptionFunctionalityNotSupported="CaptionFunctionalityNotSupported",class{constructor(e,t){this.container=e,this.eventsHandler=t,this.videoElementEvents=[],this.playerEvents=[],this.maxMemoryTraceLogCount=1e4,this.videoSourceType="application/dash+xml",this.sdnPluginLoaded=!1,this.statsTimer=-1,this.statsInterval=1e3,this.videoSourceSetAttemptCount=0,this.totalBufferingTime=0,this.isBuffering=!1,this.totalPlayingTime=0,this.isPlaying=!1,this.videoTrackTotalDurations=[]}get contextWindow(){return this.container.ownerDocument.defaultView}configure(e,t,i){this.liveStreamOptions=e,this.playerId=i,t&&(this.configProvider=t,this.statsInterval=t.config.playerTelemetryTickMs||this.statsInterval,this.maxMemoryTraceLogCount=t.config.maxPlayerMemoryTraceLogCount||this.maxMemoryTraceLogCount)}getIceCandidates(){let e=[];try{const t=this.liveStreamOptions.stream.sdnContext||this.liveStreamOptions.altStream?.sdnContext||"",i=JSON.parse(t),n=JSON.parse(i.sdnConfig);if(!n.RTCIceCandidates)throw new Error("RTCIceCandidates not present in SDN Context");e=n.RTCIceCandidates}catch(e){this.log(`getIceCandidates failed: ${JSON.stringify(e.message)}`,"error")}return this.log(`getIceCandidates: ${JSON.stringify(e)}`,"debug"),e}loadPlayerScript(){let e=Promise.resolve("");const t=this.configProvider.playerConfig.nonce,i=this.configProvider.playerConfig.css;for(let n=0;n<i.length;n++)e=e.then((()=>this.retry((()=>this.loadCss(this.container.ownerDocument,i[n],t)))));return e=e.then((()=>this.loadAmpScript())),e}loadAmpScript(){this.log("loadPlayerScript started");let e=Promise.resolve("");const t=this.configProvider.playerConfig?.nonce,i=this.configProvider.playerConfig?.src||[],n=Math.max(2,this.configProvider.config.maxRetryCountForLoadingResources);if(0===i.length)return Promise.reject("AMP Player Src is empty");for(let r=0;r<i.length;++r)e=e.then((()=>this.loadScriptPromise(i,r,t,n)));return e}loadScriptPromise(e,t,i,n,r=""){return this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i} `.concat(r))).catch((a=>this.retry((()=>this.setScriptByBlob(this.container.ownerDocument,e[t],i)),n).then((i=>`${e[t]}: ${i}`.concat(` ${a} `,` ${r} `))).catch((s=>this.retry((()=>this.setScriptByInnerHtml(this.container.ownerDocument,e[t],i)),1).then((i=>`${e[t]}: ${i}`.concat(` ${a} `,`${s} `,` ${r} `))).catch((a=>{let o=r;return t<e.length&&(o=o.concat(`Failed to load script, nonce: ${i}, src: ${e[t]} index: ${t} `),o=o.concat(`${n} attempts LoadFailure `,`${n} attempts BlobFetchFailure: `,s,", 1 attempt InnerHtmlFailure: ",`${a} `)),Promise.reject(o)}))))))}retry(e,t=this.configProvider.config.maxRetryCountForLoadingResources,i=1,n=200){return e(t).then((e=>`${e}, succeeded on load number: ${i} `)).catch((r=>(this.log(`Error loading resource: ${r} -- ${t} retriesLeft`),0==--t?Promise.reject(`${r}`):new Promise((a=>setTimeout((()=>a(this.retry(e,t,i+1).then((e=>"string"==typeof e?`${e}, succeeded on load number: ${i}`:e)).catch((e=>Promise.reject(`${r}`.concat(", ",e)))))),n))))))}setScriptByLoad(e,t,i){const n=e.createElement("script"),r=this.getElementLoadPromise(n,t);return n.src=t,i&&(n.nonce=i),e.head.appendChild(n),r.then((()=>Promise.resolve("Success: setScriptByLoad")))}setScriptByBlob(e,t,i){return this.safeResponse(t).then((t=>t.blob().then((n=>{if(n){const t=URL.createObjectURL(n);return this.setScriptByLoad(e,t,i).then((()=>Promise.resolve("Success: setScriptByBlob")))}return Promise.reject(`${t.status}, blob is null`)}))))}setScriptByInnerHtml(e,t,i){return this.safeResponse(t).then((t=>t.text().then((n=>{if(n){const t=document.createElement("script");return t.innerHTML=n,i&&!this.configProvider.config.hlsSettings.skipNonce&&(t.nonce=i),e.head.appendChild(t),Promise.resolve("Success: setScriptByInnerHtml")}return Promise.reject(`status code:${t.status}, text is null`)}))))}safeResponse(e){return fetch(e).then((e=>e.ok?e:Promise.reject(`${e.status}`)))}tryLoadSdnPlugin(){return this.sdnPluginLoaded||!this.liveStreamOptions.sdn?Promise.resolve():this.configProvider.config.allowSdnPlugins?(this.log("tryLoadSdnPlugin started"),this.retry((()=>this.setScriptByLoad(this.container.ownerDocument,this.liveStreamOptions.sdn.url,this.configProvider.playerConfig.nonce))).then((()=>{this.log("SDN script loaded"),this.sdnPluginLoaded=!0,this.log("tryLoadSdnPlugin done")}))):(this.log("Loading SDN plugins is not allowed"),Promise.reject("Loading SDN plugins is not allowed"))}createAmp(){this.log("createAmp started"),this.createVideoElement();const i=this.getAmpOptions();if(this.playerInstance=this.contextWindow.amp(this.video.id,i),!this.playerInstance)throw this.log("createAmp failed","error"),new Error("playerInstance is null");"html5"===this.playerInstance.currentTechName()?.toLowerCase()&&this.configProvider.config.ampSettings.estimateAbsoluteTime&&this.isControlsDisabled()?(this.absoluteTimeOffsetEstimator=new Ii(this.log.bind(this)),this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider,this.absoluteTimeOffsetEstimator),this.absoluteTimeOffsetEstimator.setEstimationResultCallback(this.onAbsoluteTimeOffsetEstimation.bind(this))):this.diagnosticProvider=new e(this.playerInstance,this.contextWindow,new Date,this.configProvider);const n={controlsEnabled:!this.isControlsDisabled(),logFn:this.log.bind(this),removeEmptyDefaultTextTrack:this.configProvider.config.removeEmptyDefaultTextTrack};this.diagnosticProvider.setValue("streamingEventType",this.liveStreamOptions.streamingEventType),this.diagnosticProvider.setValue("playerControlsEnabled",!this.isControlsDisabled()),this.captionsControl=new t(this.playerInstance,this,n,this.diagnosticProvider),this.registerPlayerEvents(),this.log("createAmp done")}isControlsDisabled(){return void 0!==this.liveStreamOptions.allowPlayerControls?!this.liveStreamOptions.allowPlayerControls:"Overflow"===this.liveStreamOptions.streamingEventType||"TownHall_Basic"===this.liveStreamOptions.streamingEventType||"TownHall_Premium"===this.liveStreamOptions.streamingEventType||"TownHall"===this.liveStreamOptions.streamingEventType}onAbsoluteTimeOffsetEstimation(e){if(this.diagnosticProvider.appendAbsoluteTimeOffsetEstimation(e),!e.isSuccess){const e=this.addEvent("CaptionFunctionalityNotSupported",{detail:{data:{fatal:!0,details:"absolute time offset estimation failed - captions will fail"}}});this.video.dispatchEvent(e)}}addEvent(e,t){let i={};return t?.detail&&(i={detail:t.detail}),new CustomEvent(e,i)}setSource(e){if(this.log("setSource started"),!this.playerInstance)throw this.log("setSource failed: playerInstance is null","error"),new Error("playerInstance is null");this.videoSourceSetAttemptCount++,this.videoSourceSetAttemptCount>0&&this.diagnosticProvider.setValue("retryCount",this.videoSourceSetAttemptCount-1);const t={src:e.url,type:this.videoSourceType,protectionInfo:e.decryptionToken?[{type:"AES",authenticationToken:e.decryptionToken}]:null};this.configureSdnSource(t,e),this.diagnosticProvider.setValue("streamUrl",e.url),this.diagnosticProvider.setValue("streamId",this.getStreamIdFromStreamUrl(e.url)),this.diagnosticProvider.setValue("streamDeliveryPipeline",e.streamDeliveryPipeline||""),this.playerInstance.src([t],this.getTextTracks()),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.setManifestFileURL(e.url+"(format=m3u8-aapl-v4)"),this.log("setSource done")}getStreamIdFromStreamUrl(e){try{const t=new URL(e).pathname;if(t){const e=t.split("/");if(e?.length>1)return e[1]}return this.log(`unable to parse stream ID from stream URL: ${e}`,"warn"),""}catch{return this.log(`cannot parse stream ID from invalid stream URL: ${e}`,"warn"),""}}setPlayTime(e){e&&(this.log(`setPlayerTime: ${e}`),this.playerInstance.currentTime(e))}dispose(){this.log("dispose started"),this.diagnosticProvider&&(this.stopStatsCollection(),this.diagnosticProvider.dispose(),this.diagnosticProvider=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.removePlayerEventListeners(),this.playerInstance.getMemoryLog(!0),this.playerInstance.dispose(),this.playerInstance=null),this.eventsHandler.ampDisposed(),this.video&&(this.removeVideoEventListeners(),this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.video=null),this.absoluteTimeOffsetEstimator&&(this.absoluteTimeOffsetEstimator.stopStreamAbsoluteTimeOffsetRetrieval(),this.absoluteTimeOffsetEstimator=null),this.log("dispose done"),this.eventsHandler=null}updatePlaybackDiagnostics(){this.updateTotalPlayingTimeStatistic(),this.updateBufferingRateStatistic(),this.updateVideoTrackHistoryStatistic()}handlePlaybackStopped(){this.isBuffering=!1,this.isPlaying=!1,this.currentVideoPlaybackBitrate=null}showCaptions(e){this.log(`showCaptions: ${e}`),this.captionsControl.showCaptions(e)}addCues(e){e=e.filter((e=>e.text&&0!==e.text.trim().length)),this.captionsControl.addCues(e)}clearCues(){this.captionsControl.clearCues()}captionsToggled(e,t,i){this.log(`captionsToggled: ${e} for culture ${t} at ${i}`),this.eventsHandler.message("captionsToggled").send(e,t,i)}createVideoElement(){this.log("createVideoElement started"),this.video=this.container.ownerDocument.createElement("video"),this.video.id="amp-player",this.video.setAttribute("playsinline","");const e=this.configProvider.playerConfig.lang;e&&(this.video.setAttribute("lang",e),this.log(`createVideoElement: language set to ${e}`));const t=this.configProvider.playerConfig.styles;for(let e=0;e<t.length;e++)this.video.classList.add(t[e]);this.container.appendChild(this.video),this.log("createVideoElement done")}getAmpOptions(){const e=[];this.configProvider.config.debug?e.push({target:"memory",maxMemoryTraceCount:this.maxMemoryTraceLogCount}):e.push({target:"console"});const t={TraceTargets:e,maxLogLevel:this.configProvider.config.debug?3:2},i={techOrder:["azureHtml5JS","html5"],nativeControlsForTouch:!1,autoplay:!0,preload:"auto",controls:!this.isControlsDisabled(),logo:{enabled:!1},height:"100%",width:"100%",traceConfig:t,disableFullscreenButton:this.configProvider.playerConfig?.disableFullscreenButton,staleDataTimeLimitInSec:30,heuristicProfile:this.contextWindow.amp.Player.HeuristicProfile.HighQuality,customPlayerSettings:{customHeuristicSettings:{bandwidthTestWithTimeThresholdDuringLive:!1,windowSizeHeuristics:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useBrowserWindowForWindowSizeRule:this.configProvider.config.ampSettings.useBrowserWindowSizeForBitRate,useVariableFragmentSizeMode:!0}},plugins:{}};return this.initializePluginOptions(i),i}isStreamValid(e){return e&&!!e.url&&!!e.decryptionToken}initializePluginOptions(e){if(!this.sdnPluginLoaded||!this.liveStreamOptions.sdn)return;const t=this.isStreamValid(this.liveStreamOptions.stream)?this.liveStreamOptions.stream:this.liveStreamOptions.altStream;this.log(`initializePluginOptions, receivedSDNContext: ${JSON.stringify(t?.sdnContext)}`,"info");try{switch(this.liveStreamOptions.sdn.name){case"hive":if(e.plugins={hive:{debugLevel:this.configProvider.config.debug?"debug":"notice",telemetryId:this.playerId}},t&&t.sdnContext)try{const i=JSON.parse(t.sdnContext);if(i.sdnConfig){const t=JSON.parse(i.sdnConfig);t.candidateTopicName="RequestIceCandidates",delete t.RTCIceCandidates,Object.assign(e.plugins.hive,t)}}catch(e){this.log(`initializePluginOptions, failed to parse Hive sdnConfig Json from sdnContext Json, error: ${e}`,"warn")}break;case"kollective":if(t&&t.sdnContext){let i=null,n=null,r=null;try{i=this.parseJson(t.sdnContext,"kollective sdn context")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext Json, error: ${e}`,"error")}if(i){try{n=this.parseJson(i.playbackinfo,"kollective sdn playback info")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext playbackinfo Json, error: ${e}`,"error")}try{r=this.parseJson(i.sdnConfig,"kollective sdn config")}catch(e){this.log(`initializePluginOptions, failed to parse Kollective sdnContext sdnConfig Json, error: ${e}`,"error")}}e.plugins={kollectiveSDN:{playbackInfo:n,sdnConfig:r,reportSessionId:this.playerId}}}break;case"ramp":t&&t.sdnContext&&(e.plugins={RampMOPlugin:this.parseJson(t.sdnContext,"ramp sdn context")},this.configProvider.config.debug&&(e.plugins.RampMOPlugin.verbose=!0));break;case"peer5":t.sdnContext&&(e.plugins={peer5:this.parseJson(t.sdnContext,"peer5 sdn context")})}}catch(e){this.log(`initializePluginOptions failed, error: ${e.message}`,"error")}this.log(`initializePluginOptions, configured plugin options: ${JSON.stringify(e.plugins)}`,"info")}getTextTracks(){const e=[];if(this.isControlsDisabled())e.push({id:"amp-player_default",kind:"captions",label:"default-text-track",src:"",srclang:"en"});else if(this.liveStreamOptions.supportedSubtitleLanguages){const t=this.liveStreamOptions.supportedSubtitleLanguages;for(let i=0;i<t.length;i++)e.push({id:`amp-player_${t[i].culture}`,kind:this.configProvider.config.textTrackKind,label:t[i].name||t[i].culture,src:"",srclang:t[i].culture.substr(0,2)})}return e}configureSdnSource(e,t){if(this.sdnPluginLoaded&&this.liveStreamOptions.sdn){switch(this.liveStreamOptions.sdn.name){case"hive":if(!t.sdnContext){e.sdnList=[];break}try{const i=JSON.parse(t.sdnContext);i.playbackinfo&&(e.sdnList=[{sdnName:"hive",sdnUrl:i.playbackinfo}])}catch(i){e.sdnList=[{sdnName:"hive",sdnUrl:t.sdnContext}]}break;case"kollective":if(!t.sdnContext){e.sdnList=[];break}try{const i=this.parseJson(t.sdnContext,"kollective sdn list context"),n=this.parseJson(i.playbackinfo,"kollective sdn list playback info"),r=this.parseJson(i.sdnConfig,"kollective sdn list sdn config");e.sdnList=[{sdnName:"kollectiveSDN",playbackInfo:n,sdnConfig:r}]}catch(t){return e.sdnList=[],void this.log(`configureSdnSource failed, error: ${t}`,"error")}break;case"ramp":case"peer5":e.sdnList=[];break;default:return}this.log(`configureSdnSource, configured source context: ${JSON.stringify(e)}`,"info")}}registerPlayerEvents(){this.registerPlayerEvent(this.contextWindow.amp.eventName.error,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.error)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.canplaythrough,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.canplaythrough)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.play,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.play)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playing,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playing)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.pause,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.pause)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.resume,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.resume)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.start,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.start)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.ended,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.ended)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeking,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeking)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.seeked,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.seeked)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadedmetadata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadedmetadata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.waiting,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.waiting)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.playbackbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.playbackbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.downloadbitratechanged,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.downloadbitratechanged)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.fullscreenchange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.fullscreenchange)})),this.registerPlayerEvent("potentialMediaFreeze",(()=>{this.onAmpEvent("potentialMediaFreeze")})),this.registerPlayerEvent(this.contextWindow.amp.eventName.mute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.mute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.unmute,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.unmute)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.volumechange,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.volumechange)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadeddata,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadeddata)})),this.registerPlayerEvent(this.contextWindow.amp.eventName.loadstart,(()=>{this.onAmpEvent(this.contextWindow.amp.eventName.loadstart)})),Object.values(i).forEach((e=>{this.registerVideoEvent(e,(t=>{this.handleUserExperienceErrorEvent(e,t.detail.data.details,t.detail.data.fatal)}))})),this.configProvider.config.ampSettings.collectUserInitiatedSeekEventsTelemetry&&(this.playerEvents.push("currentTimeChanging"),this.playerInstance.addEventListener("currentTimeChanging",((e,t)=>this.onAmpCurrentTimeChangingEvent(e,t))))}onAmpCurrentTimeChangingEvent(e,t){if("currentTimeChanging"!==e.type||!t.time)return;const i={newCurrentPlayPosition:t.time};this.eventsHandler.message("stateChanged").send("UserInitiatedSeek",i)}registerPlayerEvent(e,t){this.playerEvents.push(e),this.playerInstance.addEventListener(e,t)}registerVideoEvent(e,t){this.videoElementEvents.push({name:e,callback:t}),this.video.addEventListener(e,t)}removePlayerEventListeners(){this.playerEvents.forEach((e=>{this.playerInstance.removeEventListener(e)}))}removeVideoEventListeners(){this.videoElementEvents.forEach((e=>{this.video.removeEventListener(e.name,e.callback)}))}onAmpEvent(e){let t,i;switch(e){case this.contextWindow.amp.eventName.error:i=this.playerInstance.error(),t={currentTime:this.playerInstance.currentTime(),errorCode:i?i.code:0,message:i?i.message:""};break;case this.contextWindow.amp.eventName.canplaythrough:this.initializeStatsColletion();break;case this.contextWindow.amp.eventName.loadedmetadata:this.captionsControl.initialize(),this.absoluteTimeOffsetEstimator&&this.absoluteTimeOffsetEstimator.restartStreamAbsoluteTimeOffsetRetrieval();break;case this.contextWindow.amp.eventName.fullscreenchange:t={isFullscreen:this.playerInstance.isFullscreen()};break;case this.contextWindow.amp.eventName.playbackbitratechanged:t={bitrate:this.playerInstance.currentPlaybackBitrate()};break;case this.contextWindow.amp.eventName.downloadbitratechanged:t={bitrate:this.playerInstance.currentDownloadBitrate()};break;case this.contextWindow.amp.eventName.seeked:t={captionsTimestamp:this.isControlsDisabled()?this.playerInstance.currentMediaTime():this.playerInstance.currentTime()};break;case this.contextWindow.amp.eventName.volumechange:t={value:this.playerInstance.volume()}}this.updatePlaybackDiagnostics(),this.updatePlayerState(e),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(e,t)}updatePlayerState(e){this.updatePlayingState(e),this.updateBufferingState(e),this.updateCurrentVideoTrackBitrate(e),e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error||this.handlePlaybackStopped()}handleUserExperienceErrorEvent(e,t,i){const n={currentTime:this.video?this.video.currentTime:0,message:t,type:e,errorCode:0,fatal:i};this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),this.eventsHandler.message("stateChanged").send(this.contextWindow.amp.eventName.error,n)}updatePlayingState(e){this.isPlaying?e!==this.contextWindow.amp.eventName.pause&&e!==this.contextWindow.amp.eventName.seeking&&e!==this.contextWindow.amp.eventName.ended&&e!==this.contextWindow.amp.eventName.error&&e!==this.contextWindow.amp.eventName.waiting||(this.isPlaying=!1):e===this.contextWindow.amp.eventName.playing&&(this.isPlaying=!0)}updateBufferingState(e){this.isBuffering?(e===this.contextWindow.amp.eventName.pause&&"html5"===this.playerInstance.currentTechName()?.toLowerCase()||e===this.contextWindow.amp.eventName.seeking||e===this.contextWindow.amp.eventName.ended||e===this.contextWindow.amp.eventName.error||e===this.contextWindow.amp.eventName.playing)&&(this.isBuffering=!1):e===this.contextWindow.amp.eventName.waiting&&(this.isBuffering=!0)}updateCurrentVideoTrackBitrate(e){e===this.contextWindow.amp.eventName.playbackbitratechanged&&this.playerInstance.currentPlaybackBitrate()!==this.currentVideoPlaybackBitrate&&(this.currentVideoPlaybackBitrate=this.playerInstance.currentPlaybackBitrate(),this.updateVideoTrackHistoryStatistic())}initializeStatsColletion(){this.diagnosticProvider.initialize(),this.statsTimer=window.setInterval((()=>{this.eventsHandler&&(this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()))}),this.statsInterval)}stopStatsCollection(){this.updatePlaybackDiagnostics(),this.eventsHandler.message("statsUpdated").send(this.getPlayerDiagnostics()),-1!==this.statsTimer&&window.clearInterval(this.statsTimer),this.statsTimer=-1}updateVideoTrackHistoryStatistic(){const e=new Date;if(this.currentVideoPlaybackBitrate){const t=this.diagnosticProvider.getValue("videoTrackHistory"),i=this.diagnosticProvider.getValue("videoTrackTotalDurations");if(t.length>0&&this.currentVideoPlaybackBitrate===t[t.length-1].trackPlaybackBitrate){if(this.videoTrackHistoryUpdatedTimestamp){this.latestVideoTrackDuration+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,t[t.length-1].durationInSeconds=Number(this.latestVideoTrackDuration.toFixed(0));const n=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate)),r=i.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));n&&r&&(n.totalDurationInSeconds+=(e.getTime()-this.videoTrackHistoryUpdatedTimestamp.getTime())/1e3,r.totalDurationInSeconds=Number(n.totalDurationInSeconds.toFixed(0)))}}else{const n=this.playerInstance.videoBufferData();let r=null;n&&n.perceivedBandwidth&&(r=n.perceivedBandwidth),t.push({trackPlaybackBitrate:this.currentVideoPlaybackBitrate,trackSwitchTimestamp:e.getTime(),trackSwitchMeasuredBandwidth:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredBandwidth():null,trackSwitchMeasuredByteSize:this.diagnosticProvider?this.diagnosticProvider.getAverageMeasuredVideoDownloadSize():null,trackSwitchPerceivedBandwidth:r,durationInSeconds:0}),this.latestVideoTrackDuration=0,t.length>this.configProvider.config.maxVideoTrackHistoryLogCount&&t.splice(0,1);const a=this.videoTrackTotalDurations.find((e=>e.trackPlaybackBitrate===this.currentVideoPlaybackBitrate));if(!a){const e={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0},t={trackPlaybackBitrate:this.currentVideoPlaybackBitrate,totalDurationInSeconds:0};this.videoTrackTotalDurations.push(e),i.push(t)}}}this.videoTrackHistoryUpdatedTimestamp=e}updateTotalPlayingTimeStatistic(){const e=new Date;this.isPlaying&&this.totalPlayingTimeUpdatedTimestamp&&(this.totalPlayingTime+=e.getTime()-this.totalPlayingTimeUpdatedTimestamp.getTime()),this.totalPlayingTimeUpdatedTimestamp=e,this.diagnosticProvider.setValue("totalPlayingTimeInSeconds",Number((this.totalPlayingTime/1e3).toFixed(0)))}updateBufferingRateStatistic(){const e=new Date;this.isBuffering&&this.bufferingRateStatUpdatedTimestamp&&(this.totalBufferingTime+=e.getTime()-this.bufferingRateStatUpdatedTimestamp.getTime()),this.bufferingRateStatUpdatedTimestamp=e;const t=this.totalPlayingTime>0||this.totalBufferingTime>0?this.totalBufferingTime/(this.totalPlayingTime+this.totalBufferingTime):0;this.diagnosticProvider.setValue("bufferingRate",Number(t.toFixed(3)))}getPlayerDiagnostics(){const e=this.diagnosticProvider.getPlayerDiagnosticSnapshot();return e.statsInterval=this.statsInterval,this.configProvider.config.debug&&(e.memoryLog=this.playerInstance.getMemoryLog(!0)),e}log(e,t="info"){const i=`[AmpPlayer${1===this.configProvider.config.loadType?"IFrame":""}]: ${e}`;this.configProvider.config.debug&&console.log(i),this.eventsHandler.message("log").send(t,i)}getElementLoadPromise(e,t){return new Promise(((i,n)=>{e.onload=()=>{i("Element Load success")},e.onerror=()=>{n(`Failed to load script: ${t}`)}}))}loadCss(e,t,i){const n=e.createElement("link"),r=this.getElementLoadPromise(n,t);return n.href=t,n.rel="stylesheet",i&&(n.nonce=i),e.head.appendChild(n),r}parseJson(e,t){try{return JSON.parse(e)}catch(e){throw this.log(`Error parsing JSON for ${t}, error: ${JSON.stringify(e)}`),e}}}}function _i(){const e=Ci();return class{constructor(t,i){this.pipe=t,this.amp=new e(i,this)}processMessage(e){"Command"===e.msgType&&Promise.resolve().then((()=>this.amp[e.cmd].apply(this.amp,e.args))).then((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,result:JSON.stringify(t)})})).catch((t=>{this.pipe&&this.pipe.sendMsg({msgType:"CommandResult",cmd:e.cmd,error:t})}))}message(e){return{send:this.fromMessage(((...t)=>{this.sendMessageImpl(e,t)}))}}ampDisposed(){this.pipe.dispose(),this.pipe=null,this.amp=null}fromMessage(e){return e}sendMessageImpl(e,t){this.pipe.sendMsg({msgType:"PlayerNotification",name:e,args:t})}}}Ci();var Ei=_i();function Ti(){function e(e){let t="unknown";try{t="string"==typeof e?e:"toString"in e&&0!==e.toString().indexOf("[object")?e.toString():JSON.stringify(e)}catch(t){console.error("Failed to stringify error",e)}return t}return class{constructor(){this.processMsg=this.processMsg.bind(this),window.addEventListener("message",this.processMsg)}sendMsg(t){try{let i=t;(function(e){return"CommandResult"===e.msgType})(t)&&t.error instanceof Event&&(console.debug("Stringifying error Event before trying to postMessage:",t),i={msgType:t.msgType,cmd:t.cmd,error:`Event: ${e(t.error)}`}),this.postMessage(i)}catch(i){console.error("Unexpected exception caught from postMessage.\n","message:",t,"\n","exception:",i);const n={msgType:"PlayerNotification",name:"log",args:["error",`Unexpected error with postMessage: ${e(i)}`]};throw this.postMessage(n),i}}registerObserver(e){this.observer=e}dispose(){window.removeEventListener("message",this.processMsg),this.observer=null}processMsg(e){this.observer.processMessage(e.data)}postMessage(e){window.parent.postMessage(e,"*")}}}function bi(){const e=wi();return class{constructor(t){this.playlistFileDownloadPromise=Promise.resolve(),this.playlistFileDownloadRetryWaitTime=250,this.playlistFileDownloadMaxRetryCount=20,this.playlistFileDownloadCancellationFlag=!1,this.logFn=(e,i)=>t(`[HlsAbsoluteTimeOffsetEstimator]: ${e}`,i),this.hlsFileParser=new e(t)}get absoluteTimeOffset(){return this.estimatedAbsoluteTimeOffset}setEstimationResultCallback(e){this.onAbsoluteTimeOffsetEstimation=e}restartStreamAbsoluteTimeOffsetRetrieval(){this.stopStreamAbsoluteTimeOffsetRetrieval().then((()=>this.startStreamAbsoluteTimeOffsetRetrieval()))}setManifestFileURL(e){this.cachedManifestUrl=e}startStreamAbsoluteTimeOffsetRetrieval(){this.playlistFileDownloadPromise=this.retryPlaylistFileDownload((()=>this.estimateStreamTimeFromPlaylist(this.currentManifestUrl))).then((()=>{this.logFn(`Succeeded in downloading playlist files to estimate\n                    absolute stream time offset as: ${this.estimatedAbsoluteTimeOffset}`)})).catch((e=>{this.logFn(`Failed to download playlist files to estimate absolute stream time offset: ${e.message}`,"error")}))}stopStreamAbsoluteTimeOffsetRetrieval(){return this.playlistFileDownloadCancellationFlag=!0,this.playlistFileDownloadPromise.then((()=>{this.playlistFileDownloadCancellationFlag=!1,this.currentManifestUrl=this.cachedManifestUrl,this.cachedManifestUrl=null}))}retryPlaylistFileDownload(e,t=0){let i=Promise.resolve();return i=e().then((()=>(this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!0,absoluteTimeOffsetEstimation:this.absoluteTimeOffset}),Promise.resolve()))).catch((i=>(t++,this.logFn(`Error loading playlist file: ${i} -- attempt ${t}`),this.onAbsoluteTimeOffsetEstimation&&this.onAbsoluteTimeOffsetEstimation({timestamp:Date.now(),retries:t,isSuccess:!1,error:i.message}),t===this.playlistFileDownloadMaxRetryCount?Promise.reject(new Error(`${i} after ${t} attempts`)):this.playlistFileDownloadCancellationFlag?Promise.reject(new Error("cancelling playlist file download")):new Promise((i=>setTimeout((()=>i(this.retryPlaylistFileDownload(e,t))),this.playlistFileDownloadRetryWaitTime)))))),i}estimateStreamTimeFromPlaylist(e){return this.hlsFileParser.getStreamRenditionsUrlsFromManifest(e).then((t=>{if(0===t.audioRenditions.length&&0===t.videoRenditions.length)throw new Error(`Unable to retrieve renditions URLs from manifest: ${e}`);return Promise.all([t.videoRenditions.length>0?this.hlsFileParser.getTextFileContent(t.videoRenditions[0]):Promise.resolve(null),t.audioRenditions.length>0?this.hlsFileParser.getTextFileContent(t.audioRenditions[0]):Promise.resolve(null)])})).then((e=>{let t;for(let i=0;i<e.length;i++){const n=e[i];if(n){this.logFn("Using segment duration and sequence number to calculate absolute time offset","debug");const e=this.hlsFileParser.getHlsFieldByName("SequenceNumber",n);if(0==e.length)throw new Error("Unable to retrieve sequence number from playlist file");const i=this.hlsFileParser.getHlsFieldByName("SegmentDuration",n,10);if(0==i.length)throw new Error("Unable to retrieve segment durations from playlist file");const r=i.map(Number);r.sort(((e,t)=>e-t));const a=r[Math.floor(r.length/2)],s=Number(e[0])*Number(a);t=t?Math.max(t,s):s}}this.estimatedAbsoluteTimeOffset=t}))}}}var Ii=bi();function wi(){return class{constructor(e){this.fieldNameRegexMap={BaseUrl:/(.*)\/.*/,AudioManifestFile:/#EXT-X-MEDIA:TYPE=AUDIO.*URI=\"(.*)\"/,SequenceNumber:/#EXT-X-MEDIA-SEQUENCE:(\d+)/,SegmentDuration:/#EXTINF:(\d+(\.\d+)?)/},this.logFn=(t,i)=>e(`[HlsFileParser]: ${t}`,i)}getHlsFieldByName(e,t,i=1){const n=[];for(let r=1;r<=i;r++){const i=this.fieldNameRegexMap[e].exec(t);if(!(i&&i.length>0))break;n.push(i[1]),t=t.substring(i.index+i[0].length)}return n}getStreamRenditionsUrlsFromManifest(e){return e?this.getTextFileContent(e).then((t=>{const i={audioRenditions:[],videoRenditions:[]},n=t.split("\n"),r=this.getHlsFieldByName("BaseUrl",e);for(let e=0;e<n.length;e++)if(n[e].includes("#EXT-X-STREAM-INF")){const t=n[e+1];t.includes("http")?i.videoRenditions.push(t):r.length>0&&i.videoRenditions.push(`${r[0]}/${t}`)}else if(n[e].includes("EXT-X-MEDIA:TYPE")){const t=this.getHlsFieldByName("AudioManifestFile",n[e]);if(t.length>0){const e=t[0];e.includes("http")?i.audioRenditions.push(e):r.length>0&&i.audioRenditions.push(`${r[0]}/${e}`)}}return i})).catch((e=>(this.logFn(`Failed to extract stream renditions from manifest, error: ${e.message}`,"error"),{audioRenditions:[],videoRenditions:[]}))):(this.logFn("No manifest URL provided to parse"),Promise.resolve({audioRenditions:[],videoRenditions:[]}))}getTextFileContent(e){return fetch(e).then((t=>{if(!t.ok)throw new Error(`http-error ${t.status} when downloading: ${e}`);return t.text()})).catch((e=>(this.logFn(`Error downloading resource: ${e}`,"error"),Promise.reject(e))))}}}function Ri(){return class{constructor(e,t,i,n,r){this.playerInstance=e,this.contextWindow=t,this.streamingStartedTimestamp=i,this.configProvider=n,this.absoluteTimeOffsetEstimator=r,this.currentDiagnosticSnapshot={playerType:0,currentPlayPosition:null,tech:null,perceivedBandwidth:null,playerHeight:null,playerWidth:null,mediaHeight:null,mediaWidth:null,windowHeight:null,windowWidth:null,videoStream:null,audioStream:null,totalDurationInSeconds:null,avgVideoDownloadLatency:null,avgAudioDownloadLatency:null,avgVideoDownloadBytes:null,avgAudioDownloadBytes:null,avgAudioDownloadBandwidth:null,avgVideoDownloadBandwidth:null,maxVideoDownloadBytes:null,minVideoDownloadBytes:null,videoDownloadSuccessCount:null,audioDownloadSuccessCount:null,videoDownloadFailureCount:null,audioDownloadFailureCount:null,videoBufferLength:null,videoCachedLength:null,audioBufferLength:null,audioCachedLength:null,videoEdgeLatency:null,audioEdgeLatency:null,playbackRate:null,playbackBitrate:null,downloadBitrate:null,audioDownloadBitrate:null,audioPlaybackBitrate:null,isFullscreen:null,streamType:null,playerVersion:null,isP2PSdnUsed:null,sdnName:null,livePosition:null,muted:null,volume:null,errorCode:null,currentMediaTime:null,currentAbsoluteTime:null,absoluteTimeOffsetEstimationResults:null,estimatedAbsoluteTimeOffset:null,videoDownloadFailures:null,audioDownloadFailures:null,heuristicProfile:null,encryption:null,retryFrequency:null,averageDownloadBitrate:null,totalDownloadedBytes:0,streamId:null,streamUrl:null,streamingEventType:null,playerControlsEnabled:null,streamDeliveryPipeline:null,retryCount:0,totalPlayingTimeInSeconds:0,bufferingRate:0,videoTrackHistory:[],videoTrackTotalDurations:[],memoryLog:null,statsInterval:null},this.videoDownloadLatencies=[],this.audioDownloadLatencies=[],this.audioDownloadBytes=[],this.videoDownloadBytes=[],this.audioDownloadBandwidths=[],this.videoDownloadBandwidths=[],this.videoDownloadSuccessCount=0,this.audioDownloadSuccessCount=0,this.videoDownloadFailureCount=0,this.audioDownloadFailureCount=0,this.audioDownloadFailures=[],this.videoDownloadFailures=[],this.totalDownloadedBytes=0,this.slidingWindowLengthForLatency=5,this.slidingWindowLengthForDownloadBytes=30,this.slidingWindowLengthForDownloadBandwidth=10,this.absoluteTimeOffsetEstimationResults=[],this.downloadFailuresLimit=10,this.onAudioDownloadCompleted=this.onAudioDownloadCompleted.bind(this),this.onAudioDownloadError=this.onAudioDownloadError.bind(this),this.onVideoDownloadCompleted=this.onVideoDownloadCompleted.bind(this),this.onVideoDownloadError=this.onVideoDownloadError.bind(this)}initialize(){this.playerVideoBuffer=this.playerInstance.videoBufferData(),this.playerAudioBuffer=this.playerInstance.audioBufferData(),this.registerForPlayerBufferEvents()}setValue(e,t){this.currentDiagnosticSnapshot[e]=t}getValue(e){return this.currentDiagnosticSnapshot[e]}appendAbsoluteTimeOffsetEstimation(e){this.absoluteTimeOffsetEstimationResults.push(e),this.absoluteTimeOffsetEstimationResults.length>this.configProvider.config.ampSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount&&this.absoluteTimeOffsetEstimationResults.splice(0,1)}getPlayerDiagnosticSnapshot(){if(!this.playerInstance)return null;const e=window.screen,t=this.playerInstance.error(),i=e=>{const t=e.slice().sort();return t[Math.floor(t.length/2)]};this.currentDiagnosticSnapshot.errorCode=t&&t.code||0,this.currentDiagnosticSnapshot.currentPlayPosition=this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentMediaTime=this.playerInstance.currentMediaTime()??this.playerInstance.currentTime(),this.currentDiagnosticSnapshot.currentAbsoluteTime=this.getCurrentAbsoluteTime(),this.currentDiagnosticSnapshot.absoluteTimeOffsetEstimationResults=this.absoluteTimeOffsetEstimationResults,this.currentDiagnosticSnapshot.estimatedAbsoluteTimeOffset=this.getCurrentAbsoluteTimeOffset(),this.currentDiagnosticSnapshot.playbackBitrate=this.playerInstance.currentPlaybackBitrate(),this.currentDiagnosticSnapshot.downloadBitrate=this.playerInstance.currentDownloadBitrate(),this.currentDiagnosticSnapshot.audioDownloadBitrate=this.lastAudioDownloadBitrate,this.currentDiagnosticSnapshot.perceivedBandwidth=this.playerVideoBuffer?this.playerVideoBuffer.perceivedBandwidth:0,this.currentDiagnosticSnapshot.tech=this.playerInstance.currentTechName(),this.currentDiagnosticSnapshot.playerVersion=this.playerInstance.getAmpVersion(),this.currentDiagnosticSnapshot.isP2PSdnUsed=this.isP2PSdnUsed(),this.currentDiagnosticSnapshot.sdnName=this.sdnName(),this.currentDiagnosticSnapshot.heuristicProfile=this.playerInstance.currentHeuristicProfile(),this.currentDiagnosticSnapshot.encryption=this.playerInstance.currentProtectionInfo()?this.playerInstance.currentProtectionInfo().type:"",this.currentDiagnosticSnapshot.streamType=this.getStreamType(this.currentDiagnosticSnapshot.streamType),this.currentDiagnosticSnapshot.totalDurationInSeconds=this.getTotalDurationInSeconds(),this.currentDiagnosticSnapshot.audioStream=this.getAudioStreamData(),this.currentDiagnosticSnapshot.videoStream=this.getVideoStreamData(),this.currentDiagnosticSnapshot.muted=this.playerInstance.muted(),this.currentDiagnosticSnapshot.volume=this.playerInstance.volume(),this.currentDiagnosticSnapshot.playbackRate=this.playerInstance.playbackRate();const n=this.getPlayerCachedLength(),r=this.getPlayerEdgeLatency();this.currentDiagnosticSnapshot.audioBufferLength=this.playerAudioBuffer?this.playerAudioBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.audioCachedLength=n,this.currentDiagnosticSnapshot.audioEdgeLatency=r,this.currentDiagnosticSnapshot.videoBufferLength=this.playerVideoBuffer?this.playerVideoBuffer.bufferLevel:0,this.currentDiagnosticSnapshot.videoCachedLength=n,this.currentDiagnosticSnapshot.videoEdgeLatency=r,this.currentDiagnosticSnapshot.livePosition=this.getLivePosition(),this.currentDiagnosticSnapshot.mediaHeight=this.playerInstance.videoHeight(),this.currentDiagnosticSnapshot.mediaWidth=this.playerInstance.videoWidth(),this.currentDiagnosticSnapshot.playerHeight=this.playerInstance.height(),this.currentDiagnosticSnapshot.playerWidth=this.playerInstance.width(),this.currentDiagnosticSnapshot.windowHeight=e?e.height:0,this.currentDiagnosticSnapshot.windowWidth=e?e.width:0,this.currentDiagnosticSnapshot.isFullscreen=this.playerInstance.isFullscreen(),this.currentDiagnosticSnapshot.avgAudioDownloadLatency=i(this.audioDownloadLatencies),this.currentDiagnosticSnapshot.avgVideoDownloadLatency=i(this.videoDownloadLatencies),this.currentDiagnosticSnapshot.avgAudioDownloadBytes=i(this.audioDownloadBytes),this.currentDiagnosticSnapshot.avgVideoDownloadBytes=i(this.videoDownloadBytes),this.currentDiagnosticSnapshot.maxVideoDownloadBytes=Math.max.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.minVideoDownloadBytes=Math.min.apply(null,this.videoDownloadBytes),this.currentDiagnosticSnapshot.avgAudioDownloadBandwidth=i(this.audioDownloadBandwidths),this.currentDiagnosticSnapshot.avgVideoDownloadBandwidth=i(this.videoDownloadBandwidths),this.currentDiagnosticSnapshot.audioDownloadFailureCount=this.audioDownloadFailureCount,this.currentDiagnosticSnapshot.audioDownloadSuccessCount=this.audioDownloadSuccessCount,this.currentDiagnosticSnapshot.videoDownloadFailureCount=this.videoDownloadFailureCount,this.currentDiagnosticSnapshot.videoDownloadSuccessCount=this.videoDownloadSuccessCount,this.currentDiagnosticSnapshot.audioDownloadFailures=this.audioDownloadFailures,this.currentDiagnosticSnapshot.videoDownloadFailures=this.videoDownloadFailures,this.currentDiagnosticSnapshot.totalDownloadedBytes=this.totalDownloadedBytes,this.currentDiagnosticSnapshot.retryFrequency=this.getRetryFrequency(),this.currentDiagnosticSnapshot.averageDownloadBitrate=this.getAverageDownloadBitrate();const a=this.getDiagnosticWritableField();return Object.keys(a).forEach((e=>{this.currentDiagnosticSnapshot[e]=a[e]})),this.currentDiagnosticSnapshot}getDiagnosticWritableField(){return{streamUrl:this.currentDiagnosticSnapshot.streamUrl,streamId:this.currentDiagnosticSnapshot.streamId,streamingEventType:this.currentDiagnosticSnapshot.streamingEventType,playerControlsEnabled:this.currentDiagnosticSnapshot.playerControlsEnabled,streamDeliveryPipeline:this.currentDiagnosticSnapshot.streamDeliveryPipeline,retryCount:this.currentDiagnosticSnapshot.retryCount,totalPlayingTimeInSeconds:this.currentDiagnosticSnapshot.totalPlayingTimeInSeconds,bufferingRate:this.currentDiagnosticSnapshot.bufferingRate,videoTrackHistory:this.currentDiagnosticSnapshot.videoTrackHistory,videoTrackTotalDurations:this.currentDiagnosticSnapshot.videoTrackTotalDurations}}dispose(){this.unsubscribeFromPlayerBufferEvents()}registerForPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.addEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}unsubscribeFromPlayerBufferEvents(){this.playerVideoBuffer&&(this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onVideoDownloadCompleted),this.playerVideoBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onVideoDownloadError)),this.playerAudioBuffer&&(this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadcompleted,this.onAudioDownloadCompleted),this.playerAudioBuffer.removeEventListener(this.contextWindow.amp.bufferDataEventName.downloadfailed,this.onAudioDownloadError))}isP2PSdnUsed(){return!!this.sdnName()}sdnName(){const e="options_";return this.playerInstance[e]&&this.playerInstance[e].sdn&&this.playerInstance[e].sdn.name}getStreamType(e){let t="";return this.playerInstance&&(t=this.playerInstance.isLive()?"LIVE":"DVR"),""===t||"LIVE"===e&&t!==e?e||"":t}getCurrentAbsoluteTime(){return this.absoluteTimeOffsetEstimator?this.absoluteTimeOffsetEstimator.absoluteTimeOffset?this.absoluteTimeOffsetEstimator.absoluteTimeOffset+this.playerInstance.currentTime():this.playerInstance.currentTime():this.playerInstance.currentAbsoluteTime()??this.playerInstance.currentTime()}getCurrentAbsoluteTimeOffset(){return this.getCurrentAbsoluteTime()-this.playerInstance.currentTime()}getTotalDurationInSeconds(){const e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;return Number(e.toFixed(0))}onVideoDownloadCompleted(){this.videoDownloadSuccessCount++,this.addToList(this.videoDownloadLatencies,this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.videoDownloadBytes,this.playerVideoBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.videoDownloadBandwidths,8*this.playerVideoBuffer.downloadCompleted.totalBytes*1e3/this.playerVideoBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerVideoBuffer.downloadCompleted.totalBytes}onAudioDownloadCompleted(){this.audioDownloadSuccessCount++,this.addToList(this.audioDownloadLatencies,this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForLatency),this.addToList(this.audioDownloadBytes,this.playerAudioBuffer.downloadCompleted.totalBytes,this.slidingWindowLengthForDownloadBytes),this.addToList(this.audioDownloadBandwidths,8*this.playerAudioBuffer.downloadCompleted.totalBytes*1e3/this.playerAudioBuffer.downloadCompleted.totalDownloadMs,this.slidingWindowLengthForDownloadBandwidth),this.totalDownloadedBytes+=this.playerAudioBuffer.downloadCompleted.totalBytes;const e=this.playerAudioBuffer.downloadCompleted.mediaDownload.bitrate;e!==this.lastAudioDownloadBitrate&&(this.lastAudioDownloadBitrate=e)}addToList(e,t,i){e.push(t),e.length>i&&e.shift()}onVideoDownloadError(){this.videoDownloadFailureCount++,this.addDownloadFailureInfo(this.playerVideoBuffer.downloadFailed,this.videoDownloadFailures)}onAudioDownloadError(){this.audioDownloadFailureCount++,this.addDownloadFailureInfo(this.playerAudioBuffer.downloadFailed,this.audioDownloadFailures)}addDownloadFailureInfo(e,t){const i={bitrate:e.mediaDownload.bitrate,errorCode:e.code,mediaTime:e.mediaDownload.mediaTime,message:e.message,timestamp:Date.now()};this.addToList(t,i,this.downloadFailuresLimit)}getAudioStreamData(){const e=this.playerInstance.currentAudioStreamList();if(e)try{const t=e.streams[e.enabledIndices[0]];return{bitrate:t.bitrate,codec:t.codec,enabled:t.enabled,name:t.name,language:t.language}}catch(e){return}}getVideoStreamData(){const e=this.playerInstance.currentVideoStreamList();if(e)try{const t=e.streams[e.selectedIndex],i=this.playerInstance.currentPlaybackBitrate(),n=e=>({bitrate:e.bitrate,height:e.height,id:e.id,selectable:e.selectable,width:e.width}),r=t.tracks?t.tracks.map(n).find((e=>e.bitrate===i)):null;return{codec:t.codec,name:t.name,currentTrack:r}}catch(e){return}}getLivePosition(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t}getAverageDownloadBitrate(){if(this.streamingStartedTimestamp&&this.totalDownloadedBytes){const e=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/1e3;if(e>0)return 8*this.totalDownloadedBytes/e}return 0}getRetryFrequency(){const e=this.currentDiagnosticSnapshot.retryCount;if(this.streamingStartedTimestamp&&e){const t=((new Date).getTime()-this.streamingStartedTimestamp.getTime())/6e4;if(t>0)return e/t}return 0}getAverageMeasuredBandwidth(){if(0===this.videoDownloadBandwidths.length)return null;let e=0;for(let t=0;t<this.videoDownloadBandwidths.length;t++)e+=this.videoDownloadBandwidths[t];return e/this.videoDownloadBandwidths.length}getAverageMeasuredVideoDownloadSize(){if(0===this.videoDownloadBytes.length)return null;let e=0;for(let t=0;t<this.videoDownloadBytes.length;t++)e+=this.videoDownloadBytes[t];return e/this.videoDownloadBytes.length}getPlayerCachedLength(){const e=this.playerInstance.buffered();let t=0;for(let i=0;i<e.length;i++)t+=e.end(i)-e.start(i);return t}getPlayerEdgeLatency(){const e=this.playerInstance.buffered();if(0===e.length)return 0;let t=e.end(0);for(let i=1;i<e.length;i++)t=Math.max(t,e.end(i));return t-this.playerInstance.currentTime()}}}function Ai(){return class{constructor(e,t,i,n){this.player=e,this.toggleListener=t,this.config=i,this.diagnosticProvider=n,this.onTextTrackChanged=this.onTextTrackChanged.bind(this),this.isHtml5Tech="html5"===this.player.currentTechName()?.toLowerCase()}dispose(){this.unsubscribeFromTrackEvents(),this.player=null,this.toggleListener=null}initialize(){const e=this.getPlayerTextTracksAsArray();if(!this.config.controlsEnabled&&e.length>0)e[0].mode="showing";else for(let t=0;t<e.length;t++)e[t].mode="disabled";this.subscribeOnTrackEvents()}addCues(e){const t=this.player.getCurrentTextTrack();if(!t)return;const i=this.getCurrentAbsoluteTime()||1,n=this.getCurrentTime(),r=this.config.controlsEnabled?i-n:Math.max(i-n,0),a=this.isHtml5Tech?window.VTTCue:window.vttjs&&window.vttjs.VTTCue||window.VTTCue;for(let i=0;i<e.length;i++){const{start:n,end:s,text:o}=e[i],l=2,c=new a(Number((n-r).toFixed(l)),Number((s-r).toFixed(l)),o);c.size=100,!this.containsCue(t,c)&&t.addCue(c)}}clearCues(){const e=this.player.getCurrentTextTrack();if(e)try{if(e.activeCues&&e.removeCue)for(;e.activeCues.length>0;)e.removeCue(e.activeCues[0]);const t="setCues_";if(e.cues[t]){e.cues_&&(e.cues_.length=0),e.cues[t]([]);const i=Object.getOwnPropertyNames(e.cues);for(let t=0;t<i.length;t++)"length"!==i[t]&&"length_"!==i[t]&&"cues_"!==i[t]&&delete e.cues[i[t]]}}catch(e){this.config.logFn(`[clearCues]: ${e}`,"warn")}}showCaptions(e){this.config.logFn(`[CaptionsControl]: showCaptions(${e})`),e?this.show():this.hide()}hide(){this.previouslyVisibleTextTrack=this.player.getCurrentTextTrack(),this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="disabled"),this.player.captionToggle&&this.player.captionToggle.hide&&this.player.captionToggle.hide(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.hide&&this.player.MoreOptionscaptionSubtitleButton.hide(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.hide&&this.player.MoreOptionscaptionSettingsButton.hide()}show(){this.previouslyVisibleTextTrack&&(this.previouslyVisibleTextTrack.mode="showing"),this.player.captionToggle&&this.player.captionToggle.show&&this.player.captionToggle.show(),this.player.MoreOptionscaptionSubtitleButton&&this.player.MoreOptionscaptionSubtitleButton.show&&this.player.MoreOptionscaptionSubtitleButton.show(),this.player.MoreOptionscaptionSettingsButton&&this.player.MoreOptionscaptionSettingsButton.show&&this.player.MoreOptionscaptionSettingsButton.show()}subscribeOnTrackEvents(){const e=this.player.textTracks(),t="addEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}unsubscribeFromTrackEvents(){const e=this.player.textTracks(),t="removeEventListener";e&&e[t]&&(this.config.controlsEnabled&&e[t]("change",this.onTextTrackChanged),this.isHtml5Tech&&this.config.removeEmptyDefaultTextTrack&&e[t]("addtrack",this.onAddTrack.bind(this)))}onTextTrackChanged(){const e=this.player.getCurrentTextTrack();if(!e||!this.currentTextTrack||this.currentTextTrack.label!==e.label||this.currentTextTrack.mode!==e.mode){if(e||this.currentTextTrack){const t=!!e&&"showing"===e.mode,i=this.getCulture(e||this.currentTextTrack),n=this.getCurrentTime();this.toggleListener.captionsToggled(t,i,n),this.config.logFn(`[CaptionsControl]: track changed: culture '${i}', timestamp '${n}'`)}this.currentTextTrack=e}}onAddTrack(e){const t=e?.track;"captions"===t?.kind&&!t.label&&!t.id&&(this.player?.textTracks_?.removeTrack_(t),this.config.logFn("[CaptionsControl]: removing default empty text track"))}getCurrentTime(){return this.isHtml5Tech?this.player.currentTime():(this.config.controlsEnabled?this.player.currentTime():this.player.currentMediaTime())||1}getCurrentAbsoluteTime(){return this.diagnosticProvider.getCurrentAbsoluteTime()}getCulture(e){if(!e)return"";if(e.id){const t=e.id.split("_")[1];if(t)return t}return""}getPlayerTextTracksAsArray(){const e=this.player.textTracks();return e&&e.tracks_||[]}containsCue(e,t){return Array.from(e?.cues||[]).some((e=>this.areCueEquals(e,t)))}areCueEquals(e,t){function i(e){return{start:e.start?e.start:e.startTime,end:e.end?e.end:e.endTime,text:e.text}}const n=i(e),r=i(t);return n.start===r.start&&n.end===r.end&&n.text===r.text}}}function Pi(){const e=Ti(),t=_i(),i=new e,n=new t(i,document.body);i.registerObserver(n)}function Mi(){let e=`(${Pi.toString()})();`;return e+=Ci.toString()+";",e+=Ti.toString()+";",e+=_i.toString()+";",e+=Ai.toString()+";",e+=Ri.toString()+";",e+=bi.toString()+";",e+=wi.toString()+";",e+="//# sourceURL=TsCallingAmpPlayer.js",e}var ki=class{sendMsg(e){this.peer.onMsg(e)}registerObserver(e){this.observer=e}onMsg(e){this.observer&&this.observer.processMessage(e)}connect(e){this.peer=e}dispose(){this.peer=null,this.observer=null}},Di=class{constructor(e){this.container=e}get contextWindow(){return this.container.ownerDocument.defaultView}sendMsg(e){this.iframe?.contentWindow?.postMessage(e,"*")}registerObserver(e){this.observer=e}dispose(){this.contextWindow&&this.contextWindow.removeEventListener("message",this.processMsg),this.iframe&&this.container.hasChildNodes()&&this.container.removeChild(this.iframe),this.iframe=null}initializeAmpIframe(e){const t=this.initializeIframe();return this.setAmpIframeContent(e),this.finalizeIframe(t)}initializeIframe(){const e=Si();return this.iframe=this.container.ownerDocument.createElement("iframe"),this.iframe.id="player-iframe",this.iframe.sandbox.add("allow-scripts"),this.iframe.allowFullscreen=!0,this.iframe.allow="camera; microphone; autoplay",this.iframe.style.height="100%",this.iframe.style.width="100%",this.iframe.style.border="none",this.iframe.onload=()=>{e.resolve()},this.iframe.onerror=()=>{e.reject("iframe load failed")},e}finalizeIframe(e){return this.container.appendChild(this.iframe),this.processMsg=this.processMsg.bind(this),this.contextWindow.addEventListener("message",this.processMsg),e.promise}processMsg(e){"null"===e.origin&&e.source===this.iframe.contentWindow&&this.observer&&("RequestIceCandidates"===e.data?this.observer.processMessage({msgType:"Command",cmd:"getIceCandidates",args:[]}):this.observer.processMessage(e.data))}setAmpIframeContent(e){const t=Mi(),i=`\n            <html class style='height: 100%; width: 100%; overflow: hidden'>\n            <head></head>\n            <body class style='height: 100%; width: 100%; margin: 0px'>\n                ${e?`<script nonce='${e}'> ${t}<\/script>`:`<script> ${t}<\/script>`}\n            </body>\n            </html>\n        `;this.iframe.srcdoc=i}};var Oi=class extends We{constructor(e){super(e),this.logger=e,this.resultsMap=new Map,this.on("log",((e,t)=>{this.logger[e](t)}))}async initialize(e,t,i,n){const r={config:i.config,playerConfig:i.playerConfig},a=i.playerConfig?.nonce||"";this.pipe=await async function(e,t,i){if(0===t){const t=new ki,i=new ki;return t.connect(i),i.connect(t),i.registerObserver(new Ei(i,e)),t}if(1===t){const t=new Di(e);return await t.initializeAmpIframe(i),t}throw new Error(`Unsupported communication type ${t}`)}(e,i.config.loadType,a),this.pipe.registerObserver(this),await this.message("configure").send(t,r,n)}message(e){return{send:this.fromMessage(((...t)=>this.sendMessageImpl(e,...t)))}}dispose(){super.dispose(),this.pipe.sendMsg(this.buildMsg("dispose")),this.pipe.dispose()}processMessage(e){let t;switch(e.msgType){case"CommandResult":t=this.getDeferred(e.cmd.toString()),t&&(e.error?(t.reject(e.error),this.logger.warn(`remote command failed: ${String(e.cmd)}, ${e.error}`)):e.result?t.resolve(e.result):t.resolve(),this.processCommandResult(e),this.resultsMap.delete(e.cmd.toString()));break;case"PlayerNotification":{const t=this.event(e.name);t.raise.apply(t,e.args);break}case"Command":this.processCommand(e).catch((t=>this.logger.warn(`error while processing command: ${JSON.stringify(e)}: ${t}`)));break;default:this.logger.warn(`unexpected message received: ${JSON.stringify(e)}`)}}async processCommand(e){"getIceCandidates"===e.cmd.toString()?await this.message("getIceCandidates").send():this.logger.warn(`unsupported command received: ${JSON.stringify(e)}`)}processCommandResult(e){"getIceCandidates"===e.cmd.toString()?this.pipe.sendMsg({topic:"RequestIceCandidates",candidates:e.result}):this.logger.debug(`ignoring command result for: ${JSON.stringify(e)}`)}fromMessage(e){return e}sendMessageImpl(e,...t){return this.pipe.sendMsg(this.buildMsg(e,t)),this.waitForCompletion(e.toString())}buildMsg(e,t){return{msgType:"Command",cmd:e,args:t}}getDeferred(e){return this.resultsMap.get(e)}waitForCompletion(e){const t=this.getDeferred(e);t&&t.reject(new Error(`function ${e} is invoked again, before previous call is completed`));const i=Si();return this.resultsMap.set(e,i),i.promise}},Ni=class extends We{constructor(e,t){super(),this.player=e,this.logger=t,this.playerSubs=[],this.subscribeForPlayerEvents()}get isRendering(){return!!this.player&&this.player.isRendering()}get streamSize(){return this.player?this.player.getStreamSize():{width:0,height:0}}get rendererType(){return 0}get frameType(){return-1}dispose(){this.stopPlayer(),super.dispose()}captions(){return this.player.getCaptionsControl()}getStats(){throw new Error("Method not implemented.")}setScalingMode(e,t){throw new Error("Method not implemented.")}captureFrame(e,t){throw new Error("Method not implemented.")}stopPlayer(){const e=this.player;this.player=null,e&&(this.logger.info("stopPlayer"),this.unsubscribeFromPlayerEvents(),e.stop())}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("fullscreenToggled",(e=>this.onFullScreenToggled(e)))),this.playerSubs.push(this.player.on("captionsToggled",((e,t,i)=>this.onCaptionsToggled(e,t,i))))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onFullScreenToggled(e){this.event("fullScreenToggled").raise(e)}onCaptionsToggled(e,t,i){this.logger.info(`Turned captions ${e?"ON":"OFF"} for culture [${t}] at player time [${i}]`),this.event("captionsToggled").raise(e,t,i)}},Li=class{constructor(e,t){this.player=e,this.availableCultures=t,this.selectedCulture="",this.disposable=this.player.on("captionsToggled",((e,t,i)=>{this.selectedCulture=e?t:""}))}async addCues(e){await this.player.message("addCues").send(e)}async clearCues(){await this.player.message("clearCues").send()}async showCaptions(e){await this.player.message("showCaptions").send(e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.disposable.dispose(),this.player=null}};function xi(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}var Fi=[2097152,2097552,2097556,2097557,2097564,2097652,2097654,2097655,2097656,2097752,3145728,4194305,4194306,4194307,4194308,4194309,5242880,5242881,5242882,5242884,5242885,5242886],Ui=2097753,Bi=class extends We{constructor(e,t,i){super(),this.logger=e,this.liveStreamStatistic=t,this.configProvider=i,this.playerState="Destroyed",this.retryCount=0,this.captionsTimestamp=0,this.isSwitchStreamingUrlOngoing=!1,this.streamingUrlSwitchCount=0,this.isPlaybackUnsupported=!1,this.noMediaTimeoutId=-1,this.lastPlaybackError=void 0,this.id=xi(),this.logger.info(`AmpLiveStreamPlayer created: ID: ${this.id}`)}get playerId(){return this.id}async configure(e){if(!hi(e.stream)&&!hi(e.altStream))return void this.logger.error("Invalid Live Stream configuration provided: no valid primary or alternative stream");this.logger.info("Live Stream configuration provided"),this.liveStreamOptions=e;const t=hi(e.stream)?e.stream:e.altStream;if(this.playerInstance&&!this.isPlaybackUnsupported){try{await this.playerInstance.message("configure").send(e)}catch(e){const t=Be(e);this.logger.error(`configure failed: ${t}`)}await this.handleStreamInfoUpdate(t)}else this.selectedStreamDetails=t}async loadPlayer(e){if(this.playerInstance)return this.logger.error("playerLoadFailed: cannot load a player while current one is still active"),{setupSucceeded:!1,playerSetupError:{errorType:"MultiplePlayerLoad",errorMessage:"cannot load a player while current one is still active"}};if(!this.liveStreamOptions||!this.selectedStreamDetails||!hi(this.selectedStreamDetails))return this.logger.error("playerLoadFailed: empty/invalid primary and alternate stream info configured"),{setupSucceeded:!1,playerSetupError:{errorType:"InvalidStream",errorMessage:"empty/invalid primary and alternate stream info configured"}};this.playerInstance=new Oi(this.logger.createChild("AmpPlayerWrapper")),this.playerInstance.on("stateChanged",((e,t)=>this.ampStateChanged(e,t))),this.playerInstance.on("captionsToggled",((e,t,i)=>this.captionsToggled(e,t,i))),this.playerInstance.on("statsUpdated",(e=>this.liveStreamStatistic.registerStatsUpdated(e)));const t=this.configProvider.config.ampSettings.noMediaTimeoutMs;let i;-1!==t&&-1===this.noMediaTimeoutId&&(this.noMediaTimeoutId=self.setTimeout((()=>this.callDropDueToMediaTimeout()),t)),await this.playerInstance.initialize(e,this.liveStreamOptions,this.configProvider,this.id),this.liveStreamStatistic.registerPlayerLoadAttempt(),this.loadSucceeded=!1,this.liveStreamStatistic.registerEventLoadAttempt("LoadScript"),this.srcLoadPromise||(this.srcLoadPromise=this.playerInstance.message("loadPlayerScript").send());try{i=await this.srcLoadPromise}catch(e){const t=Be(e);return this.logger.error(`playerLoadFailed: player scripts load failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("LoadScript",`Load Script failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`script load failed: ${i}`),this.srcLoadPromise=null,{setupSucceeded:!1,playerSetupError:{errorType:"PlayerScriptLoadFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("LoadScript"),await this.tryLoadSdnPlugin(),this.liveStreamStatistic.registerEventLoadAttempt("CreateAmp");try{await this.playerInstance.message("createAmp").send()}catch(e){const t=Be(e);return this.logger.error(`playerLoadFailed: createAmp failed: ${t}`),this.liveStreamStatistic.registerEventLoadFailed("CreateAmp",`createAmp failed: ${e}`),this.liveStreamStatistic.registerPlayerLoadFailed(`create amp failed ${t}, script load: ${i}`),{setupSucceeded:!1,playerSetupError:{errorType:"PlayerInitializationFailed",errorMessage:t}}}this.liveStreamStatistic.registerEventLoadSucceeded("CreateAmp");try{return await this.setPlayerSource(this.selectedStreamDetails),this.loadSucceeded=!0,this.logger.info(`loadPlayer succeeded: ${this.loadSucceeded}`),this.liveStreamStatistic.registerPlayerLoadSucceeded(i),this.playerState="Initialized",{setupSucceeded:this.loadSucceeded}}catch(e){const t=Be(e);return this.loadSucceeded=!1,this.logger.error(`loadPlayer succeeded: ${this.loadSucceeded}: setSource failed: ${t}`),this.liveStreamStatistic.registerPlayerLoadFailed(`setPlayerSource failed; script load: ${i}`),{setupSucceeded:this.loadSucceeded,playerSetupError:{errorType:"SetSourceFailed",errorMessage:t}}}}getRenderer(){return!this.renderer&&this.playerInstance&&(this.renderer=new Ni(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}stop(){this.destroy("PlayerStopped")}getPlaybackState(){return this.playerState}getCaptionsTimestamp(){return this.captionsTimestamp}getCaptionsControl(){if(!this.captionsControl&&this.playerInstance){const e=this.liveStreamOptions.supportedSubtitleLanguages?this.liveStreamOptions.supportedSubtitleLanguages.map((e=>e.culture)):[];this.captionsControl=new Li(this.playerInstance,e)}return this.captionsControl}getStreamSize(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e?{width:e.mediaWidth,height:e.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.height>0}ampStateChanged(e,t){switch(e){case"error":return this.handlePlaybackError(t);case"canplaythrough":return this.onCanplaythrough();case"play":return this.onPlay();case"playing":return this.onPlaying();case"pause":return this.onPause();case"resume":return this.onResume();case"start":return this.onStart();case"ended":return this.onEnded();case"seeking":return this.onSeeking();case"seeked":return this.onSeeked(t);case"loadedmetadata":return this.onMetadataLoaded();case"waiting":return this.onWaiting();case"playbackbitratechanged":return this.onPlaybackBitrateChanged(t);case"downloadbitratechanged":return this.onDownloadBitrateChanged(t);case"fullscreenchange":return this.onFullscreenChange(t);case"potentialMediaFreeze":return this.onPotentialMediaFreeze();case"mute":return this.onMute();case"unmute":return this.onUnmute();case"volumechange":return this.onVolumeChange(t);case"loadstart":return this.onLoadStart();case"loadeddata":return this.onLoadedData();case"UserInitiatedSeek":return this.onUserInitiatedSeek(t);default:this.logger.warn(`Unknown amp event ${e}`)}}onUserInitiatedSeek(e){this.liveStreamStatistic.registerUserInitiatedSeek(e)}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i),this.liveStreamStatistic.registerCaptionToggle(e,t,i)}async tryLoadSdnPlugin(){if(this.sdnPluginLoadPromise)return void this.raiseSdnPluginSkippedEvent("SDN plugin already loaded");if(!this.liveStreamOptions.sdn)return void this.raiseSdnPluginSkippedEvent("No SDNs configured in liveStreamOptions");if(!this.configProvider.config.allowSdnPlugins)return void this.raiseSdnPluginSkippedEvent("Client configured to not allow SDN plugins");switch(this.liveStreamOptions.sdn.name){case"hive":case"kollective":case"ramp":case"peer5":break;default:return this.logger.warn(`unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`),void this.liveStreamStatistic.registerSdnPluginLoad(this.liveStreamOptions.sdn.name,!1,`Unsupported SDN provider: ${this.liveStreamOptions.sdn.name}`)}let e;this.liveStreamStatistic.registerEventLoadAttempt("SdnPluginLoad");try{this.sdnPluginLoadPromise=this.playerInstance.message("tryLoadSdnPlugin").send(),await this.sdnPluginLoadPromise}catch(t){e=Be(t),this.sdnPluginLoadPromise=void 0,this.logger.error(`loadSdnPlugin failed: ${e}`),this.liveStreamStatistic.registerEventLoadFailed("SdnPluginLoad",e),this.event("sdnPluginLoadFailed").raise(e)}this.liveStreamStatistic.registerEventLoadSucceeded("SdnPluginLoad",this.liveStreamOptions.sdn.name)}raiseSdnPluginSkippedEvent(e){this.logger.warn(`skipping SDN plugin load: ${e}`),this.event("sdnPluginLoadSkipped").raise(e)}async setPlayerSource(e){if(!e)throw this.logger.error("setPlayerSource: streamDetails is undefined"),new Error("setPlayerSource: streamDetails is undefined");if(!this.playerInstance)throw this.logger.error("setPlayerSource: playerInstance is null"),new Error("playerInstance is null");this.logger.info(`setPlayerSource: AMP source set to: [${e.url}]`),this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;try{this.logger.info("setPlayerSource: src changed"),this.selectedStreamDetails=e,this.liveStreamStatistic.registerSetSourceAttempt(e.url),await this.playerInstance.message("setSource").send(e),this.liveStreamStatistic.registerSetSourceSucceeded()}catch(e){const t=Be(e);throw this.logger.error(`setPlayerSource: failed with error [${t}]`),this.liveStreamStatistic.registerSetSourcedFailed(t),e}}async handleStreamInfoUpdate(e){this.loadSucceeded&&e.url!==this.selectedStreamDetails.url?await this.setPlayerSource(e):this.loadSucceeded&&this.playerInstance&&this.getCurrentTime()>0&&this.setPlaybackState("Start")}async switchStreamingUrl(e,t){if(this.streamingUrlSwitchCount>=this.configProvider.config.ampSettings.streamingUrlSwitchMaxCount||!(0,fi.includes)(this.configProvider.config.ampSettings.errorCodesEligibleForStreamingUrlSwitch,e)&&!t)return!1;const i=this.selectedStreamDetails.url===this.liveStreamOptions.stream?.url,n=i?this.liveStreamOptions.altStream:this.liveStreamOptions.stream;return hi(n)?(this.isSwitchStreamingUrlOngoing=!0,this.streamingUrlSwitchCount++,this.setPlayerSource(n).then((()=>!0)).catch((()=>!1))):(this.logger.error(`Stream to switch (${i?"alternative":"primary"}) is not valid`),!1)}destroy(e){this.srcLoadPromise=null,this.sdnPluginLoadPromise=null,this.renderer&&(this.renderer.dispose(),this.renderer=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null),this.playerInstance&&(this.liveStreamStatistic.registerPlayerDestroyed(e),this.playerInstance.dispose(),this.playerInstance=null,this.setPlaybackState("Destroyed"))}getCurrentTime(){const e=this.liveStreamStatistic.getPlayerDiagnosticSnapshot();return e&&e.currentPlayPosition||0}onCanplaythrough(){this.setPlaybackState("Ready")}onPlay(){(this.retryCount>0||this.lastKnownPlayTime)&&(this.logger.info(`Playing after retry count ${this.retryCount}, Setting current time to ${this.lastKnownPlayTime}`),this.playerInstance.message("setPlayTime").send(this.lastKnownPlayTime),this.retryCount=0,this.lastKnownPlayTime=void 0),this.setPlaybackState("Play")}onPlaying(){this.setPlaybackState("Playing")}onPause(){this.setPlaybackState("Paused")}onResume(){this.setPlaybackState("Resume")}onStart(){this.logger.info(`Playback started, retry count: ${this.retryCount}`),this.setPlaybackState("Start"),this.event("playbackStarted").raise(),self.clearTimeout(this.noMediaTimeoutId),this.isSwitchStreamingUrlOngoing&&(this.logger.info(`Playback started, switch count: ${this.streamingUrlSwitchCount}`),this.event("urlSwitched").raise(this.selectedStreamDetails===this.liveStreamOptions.altStream),this.isSwitchStreamingUrlOngoing=!1)}onEnded(){this.setPlaybackState("Ended")}onSeeking(){this.setPlaybackState("Seeking")}onSeeked(e){this.captionsTimestamp=e.captionsTimestamp,this.setPlaybackState("Seeked")}onMetadataLoaded(){this.setPlaybackState("LoadedMetadata")}onWaiting(){this.setPlaybackState("Buffering")}onLoadedData(){this.setPlaybackState("LoadedData")}onLoadStart(){this.setPlaybackState("LoadStart")}setPlaybackState(e){this.playerState=e,this.logger.debug(`playback state changed: ${e}`),this.liveStreamStatistic.registerPlaybackStateChanged(e),this.event("playbackStateChanged").raise()}onPlaybackBitrateChanged(e){this.liveStreamStatistic.registerPlaybackBitratechanged(e.bitrate)}onDownloadBitrateChanged(e){this.liveStreamStatistic.registerDownloadBitratechanged(e.bitrate)}onFullscreenChange(e){this.logger.debug(`fullscreenchange, isFullscreen=${e.isFullscreen}`),this.event("fullscreenToggled").raise(e.isFullscreen),this.liveStreamStatistic.registerFullScreenChange(e.isFullscreen)}onPotentialMediaFreeze(){this.logger.warn("Player detected a potential media freeze"),this.liveStreamStatistic.registerPotentialMediaFreeze()}onMute(){this.liveStreamStatistic.registerMute(!0)}onUnmute(){this.liveStreamStatistic.registerMute(!1)}onVolumeChange(e){this.liveStreamStatistic.registerVolumeChange(e.value)}stringifyPlayerError(e){return JSON.stringify(e,(function(e,t){return"errorCode"===e?t.toString(16):t}))}async handlePlaybackError(e){const t=4194307;this.playerState="Error",this.lastPlaybackError=e;const i=this.stringifyPlayerError(e);if(this.logger.info(`Playback error ${i}`),!e.errorCode&&null==e.fatal)return void this.logger.error("onError: error details are not available");if((e.errorCode&t)===t)return this.isPlaybackUnsupported=!0,this.raisePlaybackError("UnsupportedPlatform",i),void this.destroy("PlaybackError");this.lastKnownPlayTime=this.getCurrentTime()||this.lastKnownPlayTime;const n=e.errorCode,r=268435455&n;this.logger.error(`onError: errorCode: 0x${n.toString(16)}, errorCodeExcludingTech: 0x${r.toString(16)}, message: ${e.message}`),this.retryCount<this.configProvider.config.maxRetryCount&&(!1===e.fatal||-1!==(0,fi.indexOf)(Fi,r))?setTimeout((async()=>{this.logger.info(`Retry loading stream because of error code: 0x${n.toString(16)}`),this.retryCount++,this.raisePlaybackError("PlaybackRetried",i),this.setPlayerSource(this.selectedStreamDetails)}),this.configProvider.config.ampSettings.sourceResetTimeoutInMs):await this.switchStreamingUrl(r,e.fatal)?this.configProvider.config.ampSettings.resetStreamingUrlSwitchCount&&(this.streamingUrlSwitchCount=0):(r===Ui||e.message?.includes(Ui.toString(16))?this.raisePlaybackError("NetworkError",i):this.raisePlaybackError("PlaybackError",i),this.destroy("PlaybackError"))}raisePlaybackError(e,t){this.liveStreamStatistic.registerPlaybackError(e,t),this.event("playbackError").raise(e,t)}callDropDueToMediaTimeout(){const e={currentTime:-1,errorCode:0,message:JSON.stringify({state:this.playerState,error:this.stringifyPlayerError(this.lastPlaybackError)}),fatal:!0},t=this.stringifyPlayerError(e);this.raisePlaybackError("MediaTimeout",t),this.destroy("MediaTimeout")}},Vi=class extends We{constructor(e,t){super(),this.logger=e,this.telemetryLogger=t,this.playbackState="Destroyed",this.playerSubs=[],this.isFinalTelemetrySent=!1,this.captionsTimestamp=0}initialize(e,t,i,n){this.getTelemetryReportFn=e,this.getSnapshotTelemetryReportFn=t,this.disposePlayerFn=i,this.releaseFn=n}startTelemetryGathering(){let e,t;this.statsSub=window.setTimeout((async()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs),1===this.configProvider.playerConfig.playerType?(e=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerHlsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs):(e=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetry||this.configProvider.config.sendSnapshotTelemetry,t=this.configProvider.config.hydraPlayerUmsSettings?.ecsSettings?.sendSnapshotTelemetryEveryMs||this.configProvider.config.sendSnapshotTelemetryEveryMs),e&&(this.diagSub=window.setInterval((async()=>{this.sendSnapshotTelemetry()}),t))}stop(){this.clearPlayerEventSubscribers(),this.destroyPlayer()}destroyPlayer(){this.renderer&&(this.renderer.dispose(),this.renderer=null),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.disposePlayerFn(),this.sendFinalTelemetry(),this.releaseFn()}getPlaybackState(){return this.playbackState}getCaptionsTimestamp(){return this.captionsTimestamp}sendFinalTelemetry(){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0))}sendTelemetry(e){if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const t={...this.getTelemetryReportFn(),isFinal:e,threadId:this.threadId,tsCallingVersion:"2024.14.01.23",correlationId:this.streamOptions.correlationId};this.logger.debug("generated live stream report: ",t),this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}else this.logger.info("telemetry not sent")}sendSnapshotTelemetry(){if(this.telemetryLogger){const e={...this.getSnapshotTelemetryReportFn(),isFinal:!1,threadId:this.threadId,tsCallingVersion:"2024.14.01.23",correlationId:this.streamOptions.correlationId};this.logger.debug("sending snapshot telemetry: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set")}clearPlayerEventSubscribers(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackSeeked(e){this.captionsTimestamp=e}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}onPlaybackStarted(){this.event("playbackStarted").raise()}},Hi=f(W());function $i(e){if(e.playbackCoordinates)return e.playbackCoordinates;if(!e.url&&!e.hlsUrls)return[];const t=[];return(e.hlsUrls?e.hlsUrls:[e.url]).forEach((i=>{t.push({url:i,ecdnProviderData:e.sdnContext})})),t}function Gi(e){return e.url?[{url:e.url,ecdnProviderData:e.sdnContext}]:[]}var ji=class extends Vi{constructor(e,t,i){super(e,i),this.eventHandler=new zi,this.playerLoaded=!1,this.initialize(this.getTelemetryReport.bind(this),this.getSnapshotTelemetryReport.bind(this),this.disposePlayer.bind(this),this.releasePlayer.bind(this)),this.addPlayerEventSubscribers(),this.configProvider=t;const n=this.createHydraPlayerSettings(t);this.hydraPlayer=new Hi.HlsHydraPlayer(n,this.eventHandler)}async configure(e){if(this.streamOptions=e,this.threadId=e.threadId,this.playerLoaded){const t=this.createHydraStreamOptions(e);await this.hydraPlayer.callPlayerApi("configureHydraPlayer",t)}}async loadPlayer(e){if(!await this.hydraPlayer.setup(e))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const e=this.createHydraStreamOptions(this.streamOptions);await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}else this.logger.warn("No stream options configured before Hydra player loaded");const t=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return t.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(t)}onCaptionsToggled(e,t,i){this.captionsControl&&this.captionsControl.toggleCaptions(e,t),this.event("captionsToggled").raise(e,t,i)}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}getCaptionsControl(){if(!this.captionsControl&&this.hydraPlayer){const e=this.streamOptions?.supportedSubtitleLanguages?this.streamOptions.supportedSubtitleLanguages.map((e=>e.culture)):["en","es"];this.captionsControl=new Wi(this.hydraPlayer,e)}return this.captionsControl}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(e=>{this.onPlaybackStateChanged(e)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(e=>{this.onPlaybackSeeked(e)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("captionsToggled",((e,t,i)=>{this.onCaptionsToggled(e,t,i)}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(e=>{this.onStatsUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("log",((e,t)=>{this.onLog(e,t)})))}createHydraPlayerSettings(e){return{hlsJsSources:e.playerConfig?.src,hydraRuntimeFetchTimeout:e.playerConfig?.hydraRuntimeFetchTimeout,capturePlayerLogs:e.config.capturePlayerLogs,allowSdnPlugins:e.config.allowSdnPlugins,debugLogging:e.config.debug??!1,muteVideo:e.playerConfig?.muteVideo??!1,videoLang:e.playerConfig?.lang,videoElementStyles:e.playerConfig?.styles,maxPlayerDiagnosticsCount:e.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:e.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:e.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:e.config.hlsSettings.maxPlayerExperimentalEvents,maxRetryCount:e.config.maxRetryCount,playerTelemetryTickMs:e.config.playerTelemetryTickMs,removeEmptyDefaultTextTrack:e.config.removeEmptyDefaultTextTrack,maxRetryCountForLoadingResources:e.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:e.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:e.config.hlsSettings.maxStreamConnectionResultsLogCount,maxAbsoluteTimeOffsetEstimationResultsLogCount:e.config.hlsSettings.maxAbsoluteTimeOffsetEstimationResultsLogCount,skipNonce:e.config.hlsSettings.skipNonce,configIds:e.configIds,estimateAbsoluteTime:e.config.hlsSettings.estimateAbsoluteTime,playlistInitialSequenceNumber:e.config.hlsSettings.playlistInitialSequenceNumber,timeoutForSwitchingUrl:e.config.hlsSettings.timeoutForSwitchingUrl,hlsConfig:e.config.hlsSettings.hlsConfig,logHlsJsEvents:e.config.hlsSettings.logHlsJsEvents,logHlsJsEventsEveryMs:e.config.hlsSettings.logHlsJsEventsEveryMs,switchingPolicy:e.config.hydraPlayerHlsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:e.config.hlsSettings.enableUuidTrace,thaScript:e.config.hlsSettings.thaScript,enableOffsetComputeBasedOfStreamTime:e.config.hlsSettings.enableOffsetComputeBasedOfStreamTime,stopCrash:e.config.stopCrash,stopTerminating:e.config.hlsSettings.stopTerminating,stallDetectionPolicy:e.config.hydraPlayerHlsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:e.config.hydraPlayerHlsSettings?.runtimeUrls??e.playerConfig.hydraPlayerWebSdkUrls,disableSandbox:e.config.hlsSettings.disableSandbox,ecsSettings:e.config.hydraPlayerHlsSettings?.ecsSettings}}createHydraStreamOptions(e){let t=Hi.HydraStreamingEventType.TLE;return t=e.streamingEventType?this.convertStreamingEventType(e.streamingEventType):e.overflow?Hi.HydraStreamingEventType.Overflow:Hi.HydraStreamingEventType.TLE,{stream:{playbackCoordinates:$i(e.stream),urls:e.stream.hlsUrls?e.stream.hlsUrls:[e.stream.url],keyAuthorizationToken:e.stream.keyAuthorizationToken,keyDeliveryUrl:e.stream.keyDeliveryUrl,sdnContext:e.stream.sdnContext,streamDeliveryPipeline:e.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(e.stream.streamDeliveryPipeline):void 0},altStream:e.altStream?{playbackCoordinates:$i(e.altStream),urls:e.altStream.hlsUrls?e.altStream.hlsUrls:[e.altStream.url],keyAuthorizationToken:e.altStream.keyAuthorizationToken,keyDeliveryUrl:e.altStream.keyDeliveryUrl,sdnContext:e.altStream.sdnContext,streamDeliveryPipeline:e.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(e.altStream.streamDeliveryPipeline):void 0}:void 0,supportedSubtitleLanguages:e.supportedSubtitleLanguages,streamingEventType:t,allowPlayerControls:e.allowPlayerControls,sdn:e.sdn?{name:e.sdn.name,url:e.sdn.url,plugin:e.sdn.plugin}:void 0,thaContext:e.thaContext?{eventId:e.thaContext.eventId,organizer:{userId:e.thaContext.organizer?.userId,tenantId:e.thaContext.organizer?.tenantId},attendee:{userId:e.thaContext.attendee?.userId,tenantId:e.thaContext.attendee?.tenantId},coOrganizers:e.thaContext.coOrganizers}:void 0,meetingMetadata:e.meetingMetadata}}convertStreamDeliveryPipeline(e){switch(e){case"AMS":return Hi.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return Hi.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return Hi.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${e} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(e){switch(e){case"TLE":return Hi.HydraStreamingEventType.TLE;case"Overflow":return Hi.HydraStreamingEventType.Overflow;case"TownHall_Basic":return Hi.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return Hi.HydraStreamingEventType.TownHallPremium;case"TownHall":return Hi.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${e} to HydraStreamingEventType`)}}getHydraPlayerSetupResult(e){return{setupSucceeded:e.setupSucceeded,playerSetupError:e.playerSetupError?{errorType:this.convertHydraPlayerSetupError(e.playerSetupError.errorType),errorMessage:e.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(e){switch(e){case Hi.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case Hi.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case Hi.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case Hi.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new Ni(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(e){this.playerStats=e}getStats(){return this.playerStats}onLog(e,t){this.logger[e](t)}onPlaybackStateChanged(e){try{this.playbackState=this.convertHydraPlaybackState(e),this.event("playbackStateChanged").raise()}catch(e){this.logger.warn(`Not handling playback state changed event: ${Be(e)}`)}}convertHydraPlaybackState(e){switch(e){case Hi.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case Hi.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case Hi.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case Hi.HydraPlayerPlaybackState.Start:return"Start";case Hi.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case Hi.HydraPlayerPlaybackState.Play:return"Play";case Hi.HydraPlayerPlaybackState.Playing:return"Playing";case Hi.HydraPlayerPlaybackState.Pause:return"Paused";case Hi.HydraPlayerPlaybackState.Waiting:return"Buffering";case Hi.HydraPlayerPlaybackState.Seeking:return"Seeking";case Hi.HydraPlayerPlaybackState.Seeked:return"Seeked";case Hi.HydraPlayerPlaybackState.Ended:return"Ended";case Hi.HydraPlayerPlaybackState.Error:return"Error";case Hi.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case Hi.HydraPlayerPlaybackState.Initialized:return"Initialized";case Hi.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${e} to PlaybackState`)}}onPlaybackError(e,t){try{const i=this.convertHydraPlaybackErrorType(e);this.event("playbackError").raise(i,t)}catch(e){this.logger.warn(`Not handling playback error event: ${Be(e)}`)}}convertHydraPlaybackErrorType(e){switch(e){case Hi.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case Hi.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case Hi.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case Hi.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case Hi.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${e} to PlaybackErrorType`)}}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.height>0}disposePlayer(){this.hydraPlayer?.dispose()}releasePlayer(){this.hydraPlayer&&(this.hydraPlayer.release(),this.hydraPlayer=null),this.captionsControl&&(this.captionsControl.dispose(),this.captionsControl=null)}},zi=class extends We{constructor(){super()}playbackStateChanged(e){this.event("playbackStateChanged").raise(e)}playbackSeeked(e){this.event("playbackSeeked").raise(e)}log(e,t){this.event("log").raise(e,t)}playbackError(e,t){this.event("playbackError").raise(e,t)}captionsToggled(e,t,i){this.event("captionsToggled").raise(e,t,i)}urlSwitched(e){this.event("urlSwitched").raise(e)}sdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}sdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}statsUpdated(e){this.event("statsUpdated").raise(e)}playbackStarted(){this.event("playbackStarted").raise()}},Wi=class{constructor(e,t){this.hydraPlayer=e,this.availableCultures=t,this.selectedCulture=""}async addCues(e){const t=this.convertCues(e);await this.hydraPlayer.callPlayerApi("addHydraPlayerCues",t)}convertCues(e){const t=[];return e.forEach((e=>{t.push({start:e.start,end:e.end,text:e.text})})),t}async clearCues(){await this.hydraPlayer.callPlayerApi("clearHydraPlayerCues")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("showHydraPlayerCaptions",e)}getSelectedCulture(){return this.selectedCulture}getAvailableCultures(){return this.availableCultures}dispose(){this.hydraPlayer=null}toggleCaptions(e,t){this.selectedCulture=e?t:""}},qi=f(q()),Ki=class extends Vi{constructor(e,t,i){super(e,i),this.eventHandler=new Yi,this.playerLoaded=!1,this.initialize(this.getTelemetryReport.bind(this),this.getSnapshotTelemetryReport.bind(this),this.disposePlayer.bind(this),this.releasePlayer.bind(this)),this.addPlayerEventSubscribers(),this.configProvider=t;const n=this.createHydraPlayerSettings(t);this.hydraPlayer=new qi.UmsHydraPlayer(n,this.eventHandler)}get tracks(){return this.trackInfo}async configure(e){if(this.streamOptions=e,this.threadId=e.threadId,this.playerLoaded){const t=this.createHydraStreamOptions(e);await this.hydraPlayer.callPlayerApi("configureHydraPlayer",t)}}async loadPlayer(e){if(!await this.hydraPlayer.setup(e))return{setupSucceeded:!1,playerSetupError:{errorType:"HydraRuntimeLoadFailed",errorMessage:"Failed to create IFrame with Hydra runtime script"}};if(this.streamOptions){const e=this.createHydraStreamOptions(this.streamOptions);await this.hydraPlayer.callPlayerApi("configureHydraPlayer",e)}else this.logger.warn("No stream options configured before Hydra player loaded");const t=await this.hydraPlayer.callPlayerApi("loadHydraPlayer");return t.setupSucceeded&&(this.playerLoaded=!0,this.startTelemetryGathering()),this.getHydraPlayerSetupResult(t)}getTelemetryReport(){return this.hydraPlayer?.getFullTelemetryReport()}getSnapshotTelemetryReport(){return this.hydraPlayer?.getSnapshotTelemetryReport()}getCaptionsControl(){return!this.captionsControl&&this.hydraPlayer&&(this.captionsControl=new Ji(this.hydraPlayer,this.logger.createChild("CaptionsControl"))),this.captionsControl}addPlayerEventSubscribers(){this.playerSubs.push(this.eventHandler.on("playbackStateChanged",(e=>{this.onPlaybackStateChanged(e)}))),this.playerSubs.push(this.eventHandler.on("playbackError",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.eventHandler.on("playbackSeeked",(e=>{this.onPlaybackSeeked(e)}))),this.playerSubs.push(this.eventHandler.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.eventHandler.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.eventHandler.on("playbackStarted",(()=>{this.onPlaybackStarted()}))),this.playerSubs.push(this.eventHandler.on("statsUpdated",(e=>{this.onStatsUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("trackListUpdated",(e=>{this.onTrackListUpdated(e)}))),this.playerSubs.push(this.eventHandler.on("trackSelected",(e=>{this.onTrackSelected(e)}))),this.playerSubs.push(this.eventHandler.on("log",((e,t)=>{this.onLog(e,t)})))}onTrackListUpdated(e){this.trackInfo=e;const t=Be(e);this.logger.info(`[onTrackListUpdated]: Track list updated to: ${t}`)}onTrackSelected(e){const t=Be(e);this.logger.info(`[onTrackSelected]: Track selected: ${t}`)}createHydraPlayerSettings(e){return{hydraRuntimeFetchTimeout:e.playerConfig?.hydraRuntimeFetchTimeout,allowSdnPlugins:e.config.allowSdnPlugins,debugLogging:e.config.debug??!1,muteVideo:e.playerConfig?.muteVideo??!1,videoLang:e.playerConfig?.lang,videoElementStyles:e.playerConfig?.styles,maxPlayerDiagnosticsCount:e.config.maxPlayerDiagnosticsCount,maxPlayerMemoryTraceLogCount:e.config.maxPlayerMemoryTraceLogCount,maxPlayerPlaybackEventCount:e.config.maxPlayerPlaybackEventCount,maxPlayerExperimentalEvents:e.config.umsSettings.maxPlayerExperimentalEvents,maxRetryCount:e.config.maxRetryCount,playerTelemetryTickMs:e.config.playerTelemetryTickMs,maxRetryCountForLoadingResources:e.config.maxRetryCountForLoadingResources,maxVideoTrackHistoryLogCount:e.config.maxVideoTrackHistoryLogCount,maxStreamConnectionResultsLogCount:e.config.umsSettings.maxStreamConnectionResultsLogCount,configIds:e.configIds,timeoutForSwitchingUrl:e.config.umsSettings.timeoutForSwitchingUrl,minTargetEdgeLatency:e.config.umsSettings.minTargetEdgeLatency,latencyCompensationThreshold:e.config.umsSettings.latencyCompensationThreshold,maxEdgeLatencyHistoryLength:e.config.umsSettings.maxEdgeLatencyHistoryLength,switchingPolicy:e.config.hydraPlayerUmsSettings?.ecsSettings?.switchingPolicy,enableUuidTrace:e.config.umsSettings.enableUuidTrace,thaScript:e.config.umsSettings.thaScript,stopCrash:e.config.stopCrash,stopTerminating:e.config.umsSettings.stopTerminating,stallDetectionPolicy:e.config.hydraPlayerUmsSettings?.ecsSettings?.stallDetectionPolicy,playerRuntimeJsUrls:e.config.hydraPlayerUmsSettings?.runtimeUrls??e.playerConfig.hydraPlayerWebSdkUrls,disableSandbox:e.config.hlsSettings.disableSandbox,ecsSettings:e.config.hydraPlayerUmsSettings?.ecsSettings}}createHydraStreamOptions(e){let t=qi.HydraStreamingEventType.TLE;return t=e.streamingEventType?this.convertStreamingEventType(e.streamingEventType):e.overflow?qi.HydraStreamingEventType.Overflow:qi.HydraStreamingEventType.TLE,{stream:{playbackCoordinates:Gi(e.stream),urls:[e.stream.url],decryptionKey:e.stream.decryptionKey,sdnContext:e.stream.sdnContext,streamDeliveryPipeline:e.stream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(e.stream.streamDeliveryPipeline):void 0},altStream:e.altStream?{urls:[e.altStream.url],playbackCoordinates:Gi(e.altStream),decryptionKey:e.altStream.decryptionKey,sdnContext:e.altStream.sdnContext,streamDeliveryPipeline:e.altStream.streamDeliveryPipeline?this.convertStreamDeliveryPipeline(e.altStream.streamDeliveryPipeline):void 0}:void 0,streamingEventType:t,allowPlayerControls:e.allowPlayerControls,sdn:e.sdn?{name:e.sdn.name,url:e.sdn.url,plugin:e.sdn.plugin}:void 0,thaContext:e.thaContext?{eventId:e.thaContext.eventId,organizer:{userId:e.thaContext.organizer?.userId,tenantId:e.thaContext.organizer?.tenantId},attendee:{userId:e.thaContext.attendee?.userId,tenantId:e.thaContext.attendee?.tenantId},coOrganizers:e.thaContext.coOrganizers}:void 0,meetingMetadata:e.meetingMetadata}}convertStreamDeliveryPipeline(e){switch(e){case"AMS":return qi.HydraStreamDeliveryPipeline.AMS;case"MiddleLaneHttpLiveStreaming":return qi.HydraStreamDeliveryPipeline.HLS;case"MiddleLaneUltraLowLatency":return qi.HydraStreamDeliveryPipeline.Ums;default:throw new Error(`Unable to convert StreamDeliveryPipeline ${e} to HydraStreamDeliveryPipeline`)}}convertStreamingEventType(e){switch(e){case"TLE":return qi.HydraStreamingEventType.TLE;case"Overflow":return qi.HydraStreamingEventType.Overflow;case"TownHall_Basic":return qi.HydraStreamingEventType.TownHallBasic;case"TownHall_Premium":return qi.HydraStreamingEventType.TownHallPremium;case"TownHall":return qi.HydraStreamingEventType.TownHall;default:throw new Error(`Unable to convert StreamingEventType ${e} to HydraStreamingEventType`)}}getHydraPlayerSetupResult(e){return{setupSucceeded:e.setupSucceeded,playerSetupError:e.playerSetupError?{errorType:this.convertHydraPlayerSetupError(e.playerSetupError.errorType),errorMessage:e.playerSetupError.errorMessage}:void 0}}convertHydraPlayerSetupError(e){switch(e){case qi.HydraPlayerSetupErrorType.InvalidStream:return"InvalidStream";case qi.HydraPlayerSetupErrorType.MultiplePlayerLoad:return"MultiplePlayerLoad";case qi.HydraPlayerSetupErrorType.PlayerInitializationFailed:return"PlayerInitializationFailed";case qi.HydraPlayerSetupErrorType.SetSourceFailed:return"SetSourceFailed";default:return}}getRenderer(){return!this.renderer&&this.hydraPlayer&&(this.renderer=new Ni(this,this.logger.createChild("LiveStreamRenderer"))),this.renderer}onStatsUpdated(e){this.playerStats=e}getStats(){return this.playerStats}onLog(e,t){this.logger[e](t)}onPlaybackStateChanged(e){try{this.playbackState=this.convertHydraPlaybackState(e),this.event("playbackStateChanged").raise()}catch(e){this.logger.warn(`Not handling playback state changed event: ${Be(e)}`)}}convertHydraPlaybackState(e){switch(e){case qi.HydraPlayerPlaybackState.LoadStart:return"LoadStart";case qi.HydraPlayerPlaybackState.LoadedData:return"LoadedData";case qi.HydraPlayerPlaybackState.LoadedMetadata:return"LoadedMetadata";case qi.HydraPlayerPlaybackState.Start:return"Start";case qi.HydraPlayerPlaybackState.CanPlayThrough:return"Ready";case qi.HydraPlayerPlaybackState.Play:return"Play";case qi.HydraPlayerPlaybackState.Playing:return"Playing";case qi.HydraPlayerPlaybackState.Pause:return"Paused";case qi.HydraPlayerPlaybackState.Waiting:return"Buffering";case qi.HydraPlayerPlaybackState.Seeking:return"Seeking";case qi.HydraPlayerPlaybackState.Seeked:return"Seeked";case qi.HydraPlayerPlaybackState.Ended:return"Ended";case qi.HydraPlayerPlaybackState.Error:return"Error";case qi.HydraPlayerPlaybackState.Destroyed:return"Destroyed";case qi.HydraPlayerPlaybackState.Initialized:return"Initialized";case qi.HydraPlayerPlaybackState.Stalled:return"Stalled";default:throw new Error(`Unable to convert HydraPlayerPlaybackState ${e} to PlaybackState`)}}onPlaybackError(e,t){try{const i=this.convertHydraPlaybackErrorType(e);this.event("playbackError").raise(i,t)}catch(e){this.logger.warn(`Not handling playback error event: ${Be(e)}`)}}convertHydraPlaybackErrorType(e){switch(e){case qi.HydraPlayerPlaybackErrorType.UnsupportedPlatform:return"UnsupportedPlatform";case qi.HydraPlayerPlaybackErrorType.NetworkError:return"NetworkError";case qi.HydraPlayerPlaybackErrorType.PlaybackRetried:return"PlaybackRetried";case qi.HydraPlayerPlaybackErrorType.PlaybackError:return"PlaybackError";case qi.HydraPlayerPlaybackErrorType.Unknown:return"Unknown";default:throw new Error(`Unable to convert HydraPlayerPlaybackErrorType ${e} to PlaybackErrorType`)}}getStreamSize(){return this.playerStats?{width:this.playerStats.mediaWidth,height:this.playerStats.mediaHeight}:{width:0,height:0}}isRendering(){const e=this.getStreamSize();return e.width>0&&e.height>0}disposePlayer(){this.hydraPlayer?.dispose()}releasePlayer(){this.hydraPlayer&&(this.hydraPlayer.release(),this.hydraPlayer=null)}},Ji=class{constructor(e,t){this.hydraPlayer=e,this.logger=t}async addCues(e){this.logger.warn("[addCues]: not implemented for UMS player")}async clearCues(){this.logger.warn("[clearCues]: not implemented for UMS player")}async showCaptions(e){await this.hydraPlayer.callPlayerApi("toggleHydraPlayerCaptions",e)}getSelectedCulture(){return this.logger.warn("[getSelectedCulture]: not implemented for UMS player"),""}getAvailableCultures(){return this.logger.warn("[getAvailableCultures]: not implemented for UMS player"),[]}dispose(){this.hydraPlayer=null}async selectTextTrack(e){await this.hydraPlayer.callPlayerApi("selectHydraPlayerTextTrack",e)}},Yi=class extends We{constructor(){super()}playbackStateChanged(e){this.event("playbackStateChanged").raise(e)}playbackSeeked(e){this.event("playbackSeeked").raise(e)}log(e,t){this.event("log").raise(e,t)}playbackError(e,t){this.event("playbackError").raise(e,t)}trackListUpdated(e){this.event("trackListUpdated").raise(e)}trackSelected(e){this.event("trackSelected").raise(e)}urlSwitched(e){this.event("urlSwitched").raise(e)}sdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}sdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}statsUpdated(e){this.event("statsUpdated").raise(e)}playbackStarted(){this.event("playbackStarted").raise()}},Qi=class extends We{constructor(e,t,i){super(),this.configProvider=e,this.logger=t,this.getTelemetryLogger=i,this.isAvailable=!0,this._isStreaming=!1,this.playerSubs=[],this.isFinalTelemetrySent=!1,this.telemetryLogger=this.getTelemetryLogger(),1===this.configProvider.playerConfig.playerType?this.player=new ji(this.logger.createChild("HlsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):2===this.configProvider.playerConfig.playerType?this.player=new Ki(this.logger.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger):(this.initializeAmpTelemetry(),this.player=new Bi(this.logger.createChild("AmpLiveStreamPlayer"),this.liveStreamStatistic,this.configProvider)),this.subscribeForPlayerEvents()}get isStreaming(){return this._isStreaming}isActive(){return this.isAvailable&&this.isStreaming}async start(e,t){await this.setOptions(t),this.isFinalTelemetrySent=!1;const i=await this.player.loadPlayer(e);if(!i.setupSucceeded){this.player.stop(),this.logger.error("playerLoadFailed");const e=JSON.stringify(i.playerSetupError);throw this.sendFinalTelemetry(e),new Error(e)}return this._isStreaming=!0,this.liveStreamStatistic&&(this.statsSub=window.setTimeout((()=>{clearTimeout(this.statsSub),this.logger.debug(`initial telemetry report after ${this.configProvider.config.sendInitialTelemetryAfterMs} ms`),this.sendTelemetry(!1)}),this.configProvider.config.sendInitialTelemetryAfterMs),this.configProvider.config.sendSnapshotTelemetry&&(this.diagSub=window.setInterval((()=>{this.sendSnapshotTelemetry()}),this.configProvider.config.sendSnapshotTelemetryEveryMs))),this.player.getRenderer()}initializeAmpTelemetry(){this.liveStreamStatistic=new mi(this.configProvider.config,this.logger.createChild("LiveStreamStatistic"),{perceivedBandwidth:[],videoBufferLength:[],videoCachedLength:[],videoEdgeLatency:[],playerHeight:[],playerWidth:[],mediaHeight:[],mediaWidth:[],windowHeight:[],windowWidth:[],playbackRate:[],currentPlayPosition:[],currentMediaTime:[],statsInterval:[]})}async stop(){}async setOptions(e){return void 0!==e.overflow&&(e.streamingEventType||(e.streamingEventType=e.overflow?"Overflow":"TLE"),delete e.overflow),this.options=e,this.player.configure(e)}getStats(){return this.liveStreamStatistic?this.liveStreamStatistic.getPlayerDiagnosticSnapshot():this.player?.getStats?.()}dispose(){this.unsubscribeFromPlayerEvents(),this.player.stop(),this.statsSub&&(clearTimeout(this.statsSub),this.statsSub=null),this.diagSub&&(clearInterval(this.diagSub),this.diagSub=null),this.logger.debug("stopping live event"),this.sendFinalTelemetry("graceful disposed"),super.dispose()}sendFinalTelemetry(e){this.isFinalTelemetrySent||(this.isFinalTelemetrySent=!0,this.sendTelemetry(!0,e))}sendTelemetry(e,t){if(this.liveStreamStatistic)if(this.configProvider.config.sendTelemetry&&this.telemetryLogger){const i={configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:e,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton,callendReason:t},n=this.liveStreamStatistic?.getReport(i);this.logger.debug("generated live stream report",n),this.telemetryLogger.sendEvent({eventName:"live_events",props:n})}else this.logger.info("telemetry not sent");else this.logger.info("telemetry not tracked in ILiveStream object")}sendSnapshotTelemetry(){if(this.liveStreamStatistic)if(this.telemetryLogger){const e=this.liveStreamStatistic.getSnapshotReport({configIds:this.configProvider.configIds,playerId:this.player.playerId,correlationId:this.options?.correlationId,eTag:this.configProvider.etag,isFinal:!1,threadId:this.options?.threadId,disableFullscreenButton:this.configProvider.playerConfig.disableFullscreenButton});this.logger.debug("sending snapshot telemetry: ",e),this.telemetryLogger.sendEvent({eventName:"live_events",props:e})}else this.logger.error("snapshot telemetry not sent, telemetryLogger is not set");else this.logger.info("telemetry not tracked in ILiveStream object")}subscribeForPlayerEvents(){this.playerSubs.push(this.player.on("playbackStateChanged",(()=>{this.onPlaybackStateChanged()}))),this.playerSubs.push(this.player.on("playbackError",((e,t)=>{this.onPlaybackError(e,t)}))),this.playerSubs.push(this.player.on("urlSwitched",(e=>{this.onUrlSwitched(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadSkipped",(e=>{this.onSdnPluginLoadSkipped(e)}))),this.playerSubs.push(this.player.on("sdnPluginLoadFailed",(e=>{this.onSdnPluginLoadFailed(e)}))),this.playerSubs.push(this.player.on("playbackStarted",(()=>{this.onPlaybackStarted()})))}unsubscribeFromPlayerEvents(){for(const e of this.playerSubs)e.dispose();this.playerSubs=[]}onPlaybackStarted(){this.event("playbackStarted").raise()}onPlaybackStateChanged(){const e=this.player.getPlaybackState();switch(e){case"Start":this.event("playbackStarted").raise();break;case"Ended":this.event("playbackNotLive").raise(),this.sendFinalTelemetry("playback ended");break;case"Seeked":this.event("playbackSeeked").raise(this.player.getCaptionsTimestamp());break;default:this.logger.debug(`playbackStateChanged: ${e}`)}this.event("playbackStateChanged").raise(this.player.getPlaybackState())}onPlaybackError(e,t){this.event("error").raise(e,t)}onUrlSwitched(e){this.event("urlSwitched").raise(e)}onSdnPluginLoadSkipped(e){this.event("sdnPluginLoadSkipped").raise(e)}onSdnPluginLoadFailed(e){this.event("sdnPluginLoadFailed").raise(e)}},Zi=class{constructor(e,t,i){this.ecsConfig=e,this.logger=t,this.getTelemetryLogger=i}configure(e){this.configuration=e}async initialize(){const e="MDN_MIDDLELANE_TEAMS",t="liveStream",i=this.ecsConfig.getString(e,t);let n={};try{n=JSON.parse(i)}catch(i){this.logger.warn(`failed to parse ECS configuration for ${e}/${t}`)}const r=this.ecsConfig.getString("ConfigIDs",e);this._configProvider=new li(n,this.configuration,r,this.logger.createChild("LiveStreamConfigProvider"))}createLiveStream(){return new Qi(this._configProvider,this.logger.createChild("LiveStream"),this.getTelemetryLogger)}dispose(){}},Xi=class extends We{constructor(){super(...arguments),this.isAudioOutputSelectionSupported=!1}createAudioPlayer(){return null}createAudioRenderer(){return null}getRawDeviceMediaStream(e){return null}askDevicePermission(){return Promise.resolve({audio:!1,video:!1})}getPermissionState(e){return"granted"}enumerateDevicesAsync(){return Promise.resolve([])}getPreferredCamera(){return null}selectDevices(){}getSelectedDevices(){return{}}createPreview(){return Promise.resolve(new en)}createPreviewRenderer(){return Promise.resolve(new en)}createScreenSharingPreviewRenderer(){return Promise.resolve(new en)}getDeviceNameAsync(){return Promise.resolve("")}setDeviceEffectsAsync(){return Promise.resolve()}getDeviceEffectsCapabilityAsync(){return Promise.resolve(0)}setBackgroundImageAsync(){return Promise.resolve()}getImagePropertyAsync(){return Promise.resolve({width:0,height:0,uri:" "})}getMicrophoneGeometryArrayInfoAsync(e){return Promise.resolve({})}transformImageAsync(){return Promise.resolve(!1)}sendMessageDeviceVideoEffectsAsync(){return Promise.resolve({code:0})}sendMessageDeviceVideoExtensibilityAsync(){return Promise.resolve({code:0,type:"Error",response:{details:"The API has not been implemented."}})}setVideoCaptureConfigAsync(){return Promise.resolve()}captureVideoFrameWithoutEffectsAsync(){return Promise.resolve(new ImageData(0,0))}setAudioProcessingFlags(e){}getSpeakerVolume(){return Promise.resolve(0)}getSpeakerSystemVolume(){return Promise.resolve(0)}setSpeakerVolume(e){return Promise.resolve()}setSpeakerSystemVolume(e){return Promise.resolve()}unmuteMicrophone(){return Promise.resolve()}unmuteSpeaker(){return Promise.resolve()}getNrgLevelsForDeviceTuner(e){return Promise.resolve(0)}setAudioEffectsAsync(){return Promise.resolve()}getAudioFeatureCapability(e){return Promise.resolve(0)}getMicrophoneVolume(){return Promise.resolve(0)}setMicrophoneVolume(e){return Promise.resolve()}setDeviceTelemetryData(e,t,i,n=0){return Promise.resolve()}getSpeakerDeviceDomIdAsync(e,t){return Promise.reject()}getSourceFormats(e){return Promise.resolve([])}enableShellSharing(){return Promise.resolve()}disableShellSharing(){return Promise.resolve()}enableParticipantCameras(){return Promise.resolve()}registerDerivedSource(e,t){return Promise.resolve()}unregisterDerivedSource(e){return Promise.resolve()}startAudioLoopbackDevice(e){return Promise.resolve()}async dispose(e){return Promise.resolve()}},en=class extends We{constructor(){super(...arguments),this.isRendering=!1,this.streamSize={width:0,height:0},this.rendererType=-1,this.frameType=-1}captureFrame(){return Promise.resolve(new tn)}getStats(){return Promise.resolve({framesDropped:0,framesTotal:0})}setScalingMode(){return Promise.resolve()}cameraAutoControl(e){return Promise.resolve(!1)}getCameraManualControlStates(e){return Promise.resolve([])}setCameraManualControlStates(e){return Promise.resolve([])}enumerateCameraManualControls(){return Promise.resolve([])}dispose(){}},tn=class extends We{getSize(){return{width:0,height:0}}isMirrored(){return!1}},nn="skypecosi_concore_web_ts_calling_registry",rn="*11",an="*12",sn="*13",on="*14",ln={totalParticipants:0,preheatedParticipants:0,lobbyParticipants:0,totalPresenters:0,requestingAttentionPresenters:0,totalAttendees:0,requestingAttentionAttendees:0,overflowAttendees:0},cn=p,dn=class{constructor(e,t,i,n,r){this.eventName=e,this.eventStartTime=t,this.type=i,this.causeId=n,this.status="Pending",this.eventStartTimestamp=(new Date).getTime(),this.data=[],this.causeId=n?.substring(0,8),"Event"===this.type&&delete this.status,r&&this.data.push(r)}set variant(e){this.eventVariant=e}recordSuccess(e,t){this.recordResult("Success",e,t)}recordFailure(e,t){this.recordResult("Failure",e,t)}recordTimeout(e,t){this.recordResult("Timeout",e,t)}addData(e){this.data.push(e)}isPending(){return"Pending"===this.status}getEvent(){const e={start:this.eventStartTime,duration:this.duration,status:this.status,result:this.result,causeId:this.causeId,resultCauseId:this.resultCauseId,variant:this.eventVariant,data:this.data.map((e=>this.prepareData(e,!0))).filter((e=>!!e))};return"Event"===this.type&&delete e.status,e.data.length||delete e.data,e.causeId||delete e.causeId,e.resultCauseId||delete e.resultCauseId,e.result||delete e.result,e.variant||delete e.variant,{[this.eventName]:e}}recordResult(e,t,i){this.status=e,this.result=this.prepareData(t),this.causeId!==i&&(this.resultCauseId=i),this.duration=(new Date).getTime()-this.eventStartTimestamp}prepareData(e,t=!1){if(null==e)return"";if("string"==typeof e)return Ae(e);if("number"==typeof e||"boolean"==typeof e)return String(e);if("function"==typeof e)return"";if(e instanceof Error)return e.toString();try{return Object.keys(e).length?t?e:De(e):""}catch(e){return"invalid"}}},un=class{constructor(e,t,i,n){this.logger=e,this.startTime=t,this.maxEventsExceeded=i,this.perfModule=n,this.recordedEvents=[],this.ipcStats=[],this.ongoingOperations={}}recordEvent(e,t,i=Te()){this.logger.debug("Event:",e,cn.pii.Omit(t));const n=new dn(e,this.getEventStartTime(),"Event",i,t);return this.pushToRecordedEvents(n),n}recordOperationSuccess(e,t=null,i,n,r){this.logger.info("Event success:",n,e,cn.pii.Omit(i),cn.pii.Omit(t)),this.recordOperationResult(e,t,"Success",i,n,r)}recordOperationFailure(e,t,i,n,r){this.logger.info("Event failure:",e,cn.pii.Omit(i),t),this.recordOperationResult(e,t,"Failure",i,n,r)}recordOperationTimeout(e,t,i,n,r){this.logger.info("Event timeout:",e,cn.pii.Omit(i),t),this.recordOperationResult(e,t,"Timeout",i,n,r)}maybeRecordOperationSuccess(e,t=null,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationSuccess(e,t,i,n,r)}maybeRecordOperationFailure(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationFailure(e,t,i,n,r)}maybeRecordOperationTimeout(e,t,i,n,r){this.hasOngoingEvent(e,i)&&this.recordOperationTimeout(e,t,i,n,r)}recordOperationResult(e,t,i,n,r,a){this.hasOngoingEvent(e,n)||this.recordOperation(e,r,n);let s=this.ongoingOperations[e];switch(n&&(s=s[n]),a&&s.addData(a),i){case"Success":s.recordSuccess(t,r);break;case"Failure":s.recordFailure(t,r);break;case"Timeout":s.recordTimeout(t,r);break;default:this.logger.error("Unknown operation record state in record operation result.")}n?delete this.ongoingOperations[e][n]:delete this.ongoingOperations[e]}recordOperation(e,t,i,n){this.logger.debug("Event create:",t,e,cn.pii.Omit(i),n);const r=new dn(e,this.getEventStartTime(),"Operation",t,n);return this.ongoingOperations[e]||(this.ongoingOperations[e]={}),i?this.ongoingOperations[e][i]=r:this.ongoingOperations[e]=r,this.pushToRecordedEvents(r),r}setOperationVariant(e,t,i){let n;n=i?this.ongoingOperations[e][i]:this.ongoingOperations[e],n?n.variant=t:this.logger.error(`Could not find operation ${e} to set variant ${t}`)}updateOperationData(e,t,i,n){try{if(!this.ongoingOperations[e])return void this.recordEvent(e,t,i);n?this.ongoingOperations[e][n]&&this.ongoingOperations[e][n].addData(t):this.ongoingOperations[e].addData(t)}catch(t){return void this.logger.info(`Unable to update operation: ${e} data`)}}pushToRecordedEvents(e){if(this.maxEventsExceeded&&this.maxEventsExceeded()&&this.recordedEvents.shift(),this.recordedEvents.push(e),this.perfModule&&this.ipcStats.length<=30){const e=this.perfModule.getIpcStats();e&&this.ipcStats.push({ingestionTime:this.getEventStartTime(),stats:e})}}hasOngoingEvent(e,t){return this.ongoingOperations[e]?!(t&&!this.ongoingOperations[e][t]&&(this.logger.warn(`Unable to find event for name\\id ${e}\\${cn.pii.Omit(t)}`),1)):(this.logger.warn(`Unable to find event for name ${e}`),!1)}getEventStartTime(){return(new Date).getTime()-this.startTime}getEventTimestampBag(e,t){const i=t?[t.getEvent()]:this.recordedEvents.filter((t=>!e||!t.isPending())).map((e=>e.getEvent())),n=JSON.stringify({eventStart:this.startTime,events:i});return this.logger.info(`Call eventTimestampBag ${cn.pii.Omit(n)}`),n}getIPCStats(){return 0!==this.ipcStats.length?JSON.stringify(this.ipcStats):""}removeRecordedEvent(e){const t=this.recordedEvents.indexOf(e);t>-1&&this.recordedEvents.splice(t,1)}},hn=class extends un{constructor(e,t){super(e,t,(()=>this.recordedEvents.length>150)),this.getHostName=()=>{try{return"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>"}catch(e){return"unknown"}},this.tsCallingVersion="2024.14.01.23",this.logger=e.createChild("CallRegistryTelemetry")}setClientType(e){this.clientType=e}setEndpointId(e){this.endpointId=e}setSkypeId(e){this.skypeId=Ae(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}getEvent(e,t){const i=e=>void 0===e?"":e;return{EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),userHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),TsCallingVersion:i(this.tsCallingVersion),HostName:this.getHostName(),EventTimestampBag:this.getEventTimestampBag(e,t),DiagnosticInfo:this.callEndDiagnosticInfo,ClientType:i(this.clientType)}}removeNonPendingOperations(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending()))}},pn=class extends un{constructor(e,t,i){super(e,t,(()=>this.inCallMode&&this.recordedEvents.length>150),i),this.inCallMode=!1,this.tsCallingVersion="2024.14.01.23",this.logger=e.createChild("CallTelemetry")}setClientType(e){this.clientType=e}setCallId(e){this.currentCallId&&(this.previousCallId=this.currentCallId),this.currentCallId=e}setConsultativeCallId(e){this.consultativeCallId=e}setEndpointId(e){this.endpointId=e}setParticipantId(e){this.participantId=e}setPreheatFlags(e){this.preheatFlags=e}setCallOrigin(e){this.origin=e}setGroupId(e){this.groupId=e}setThreadId(e){this.threadId=e}setBackroomThreadId(e){this.backroomThreadId=e}setComplianceRecordingContentLength(e){this.complianceRecordingContentLength=e}setMesageId(e){this.messageId=e}setSkypeId(e){this.skypeId=Ae(e)}setApplicationType(e){this.applicationType=e}setRing(e){this.ring=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setAcsResourceId(e){this.acsResourceId=e}setRegion(e){this.region=e}setPartition(e){this.partition=e}setFailureType(e){this.failureType=e}setIsCast(e){this.isCast=e?"True":"False"}setIsHuddleGroupCall(e){this.isHuddleGroupCall=e?"True":"False"}setIsEmergency(e){this.isEmergency=e?"True":"False"}setRole(e){this.isAnonymous="admin"===e?"False":"True"}setCallType(e){this.callType=e}setConversationType(e){this.conversationType=e}setDirection(e){this.direction=e}setSelfParticipantRole(e){this.selfParticipantRole=e}setTerminationState(e){this.terminationState=e}setTerminationReason(e){this.terminationReason=e}setCallEndDiagnosticInfo(e){this.callEndDiagnosticInfo=e}setStackConfig(e){this.stackConfig=e}setJoinedFrom(e){this.joinedFrom=e}setMeetingCode(e){this.meetingCode=e}setMeetingUrl(e){this.meetingUrl=e}setHasMeetingRegistrationId(e){this.hasMeetingRegistrationId=e?"True":"False"}setHasParticipantPin(e){this.hasParticipantPin=e?"True":"False"}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.currentCallId),PreviousCorrelationId:i(this.previousCallId),ConsultativeCallId:i(this.consultativeCallId),EndpointId:i(this.endpointId),SkypeId:i(this.skypeId),ParticipantId:i(this.participantId),PreheatFlags:i(this.preheatFlags),CallType:i(this.callType),ConversationType:i(this.conversationType),Direction:i(this.direction),Origin:i(this.origin),SelfParticipantRole:i(this.selfParticipantRole),IsAnonymous:i(this.isAnonymous),GroupId:Ae(i(this.groupId)),ThreadId:Me(i(this.threadId)),MessageId:i(this.messageId),ApplicationType:i(this.applicationType),Ring:i(this.ring),TenantId:i(this.tenantId),userHexCID:i(this.userHexCID),AcsResourceId:i(this.acsResourceId),Region:i(this.region),Partition:i(this.partition),FailureType:i(this.failureType),IsCast:i(this.isCast),IsHuddleGroupCall:i(this.isHuddleGroupCall),IsEmergency:i(this.isEmergency),TsCallingVersion:i(this.tsCallingVersion),TerminationState:i(this.terminationState),TerminationReason:i(this.terminationReason),StackConfig:i(this.stackConfig),EventTimestampBag:this.getEventTimestampBag(e,t),HostName:this.getHostName(),DiagnosticInfo:this.callEndDiagnosticInfo,JoinedFrom:this.joinedFrom,MeetingCode:this.meetingCode,MeetingUrl:this.meetingUrl,HasMeetingRegistrationId:this.hasMeetingRegistrationId,HasParticipantPin:this.hasParticipantPin,IPCStats:this.getIPCStats(),ComplianceRecordingContentLength:i(this.complianceRecordingContentLength),BackroomThreadId:Me(i(this.backroomThreadId)),ClientType:i(this.clientType)}}switchToInCallTelemetry(){this.recordedEvents=this.recordedEvents.filter((e=>e.isPending())),this.inCallMode=!0}getHostName(){try{return location.host}catch(e){return"unknown"}}},gn=e=>Array.isArray(e)?e.map((e=>({endpointId:e.endpointId,participantId:e.participantId}))):null;function mn(e,t,i){if(!e)return i.info(`sanitizeMeetingCode[${t}] empty / undefined meeting code parameter`),e;let n=e.replace(/\s/g,"");return n=n.replace(/-/g,""),i.info(`sanitizeMeetingCode[${t}] meetingCode: ${e}, sanitizedMeetingCode: ${n}`),n}function fn(e,t,i){if(!e)return i.info(`getMeetingCodeFromMeetingUrl[${t}] empty / undefined meeting Url parameter`),e;const n=new URL(e);let r="";if(n&&n.pathname&&n.pathname.split("/").length>=2){const e=n.pathname.split("/");"meet"===e[e.length-2]&&(r=e[e.length-1])}return i.info(`getMeetingCodeFromMeetingUrl[${t}] meetingUrl: ${e}, meetingUrlObject: ${Le(n)}, meetingCode: ${r}`),r}function vn(e,t,i,n){const r=mn(e&&e.meetingCode||"",i,n),a=mn(t&&t.meetingCode||"",i,n),s=(e,t)=>!!e&&!!t&&e===t;if(s(r,a))return!0;let o=fn(e&&e.meetingUrl||"",i,n);o=mn(o,i,n);let l=fn(t&&t.meetingUrl||"",i,n);if(l=mn(l,i,n),s(o,l))return!0;if(s(o,a)||s(l,r))return!0;if(e&&e.meetingUrl&&t&&t.meetingUrl){const i=new URL(e.meetingUrl),n=new URL(t.meetingUrl);if(i.hostname===n.hostname&&i.pathname===n.pathname)return!0}return!1}function Sn(){}var yn={SUCCESS:0,MEDIA_ERROR:410,CLIENT_ERROR_CODE:499,UNKNOWN_ERROR:497},Cn={VDI_DISCONNECTED:3e3,ACTION_NOT_ALLOWED:3548,ABANDONED:4990,ENDED_BY_REMOTE_ENDPOINT:5028,BEACON:4521,UNKNOWN_FAILURE:3545},_n=4294967294,En="_operationIdValue_",Tn="_causeIdValue_",bn="_callStartOptionsValue_",In="_clientReasonValue_";function wn(e,t,i=!1){return Dn(0,e,t,i)}function Rn(e,t){return Dn(1,e,t)}var An=(e,t,i)=>{if(e[t][En])throw new Error("can not specify more than one operation id");e[t][En]=i},Pn=(e,t,i)=>{if(e[t][Tn])throw new Error("can not specify more than one cause id");e[t][Tn]=i},Mn=(e,t,i)=>{if(e[t][bn])throw new Error("can not specify options more than once");e[t][bn]=i},kn=(e,t,i)=>{if(e[t][In])throw new Error("can not specify reason more than once");e[t][In]=i},Dn=(e,t,i,n=!1)=>(r,a,s)=>{const o=s.value,l=r[a]?.[En],c=r[a]?.[Tn],d=r[a]?.[bn],u=r[a]?.[In],h=i?.type||"Async";return s.value=function(...r){const a=this;let s=n?xi():Te();void 0!==c&&(r[c]&&(function(e){return new RegExp("^[a-f0-9]{8}$").test(e)&&e.length===Ee}(r[c])||function(e){return new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$").test(e)&&36===e.length}(r[c]))?s=r[c]:r[c]=s);let p,g=void 0!==l?r[l]:void 0;if(void 0!==g)if(Array.isArray(g))try{const e=g.map((e=>e.toString())).sort().concat().toString();g=function(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}(e).toString()}catch{const e=`[${g}]${t} failed in array parsing in operationDecorator`,i={terminatedReason:32,terminatedReasonCode:yn.UNKNOWN_ERROR,terminatedReasonSubCode:Cn.UNKNOWN_FAILURE,errorMessage:e};return Promise.reject(i)}else if(g&&"object"==typeof g)try{let e=JSON.stringify(g);i&&i.operationIdKey&&g.hasOwnProperty(i.operationIdKey)&&(e=g[i.operationIdKey]),g=e}catch{const e=`[${g}]${t} failed in object parsing in operationDecorator`,i={terminatedReason:32,terminatedReasonCode:yn.UNKNOWN_ERROR,terminatedReasonSubCode:Cn.UNKNOWN_FAILURE,errorMessage:e};return Promise.reject(i)}void 0!==u&&r[u]&&(p=r[u]);const m=On(a,e);if(m.logOperation(s,t),i&&i.singular&&m.hasPendingOperation(t))return m.logOperation(s,t,"Not allowed, pending operation exists"),Promise.reject(60);if(i&&i.idempotencyLevel&&m.getRecord(t)>0)switch(m.logOperation(s,t,`Called multiple times, handling operation according to specified policy: idempotency=${i.idempotencyLevel}`),i.idempotencyLevel){case"NoOp":return Promise.resolve();case"Error":return Promise.reject(60)}try{void 0!==d&&r[d]&&a.processCallStartOptions(r[d],s)}catch{const e=`${t} failed in processCallStartOptions`,i={terminatedReason:32,terminatedReasonCode:yn.UNKNOWN_ERROR,terminatedReasonSubCode:Cn.UNKNOWN_FAILURE,errorMessage:e};return Promise.reject(i)}const f=!(!i||!i.convertError),v=()=>"Chained"===h?m.executeChained(o.bind(this,...r),t,g,s,f,p,i):"Sync"===h?m.executeSync(o.bind(this,...r),t,g,s,f,p):m.execute(o.bind(this,...r),t,g,s,f,p,i);if("StartCall"!==t&&"JoinCall"!==t||m.hasPendingOperation("_CallStartOrJoinInitiated")||m.createPendingOperation("_CallStartOrJoinInitiated").catch(Sn),i&&i.triggerAttach&&(m.hasPendingOperation("_ElectronSlimcoreReady")||m.createPendingOperation("_ElectronSlimcoreReady").catch(Sn)),i&&"Sync"!==i.type){const e=i&&i.waitFor;if(Array.isArray(e))return Promise.all(e.map((e=>e&&m.hasPendingOperation(e)&&m.waitForOperation(e,void 0,s)))).then(v,v);if(e&&m.hasPendingOperation(e))return m.waitForOperation(e,void 0,s).then(v,v)}return v()},s},On=(e,t)=>{if(0===t)return e._callOperationHandler;if(1===t)return e._participantOperationHandler;throw new Error("Unsupported operation handler type!")};var Nn=class{constructor(e){this._disposed=!1,this._logger=e.createChild("[ASYNC]"),this._endOperationDeferred=Si(),this._endOperationDeferred.promise.catch((e=>{this._logger.info("Rejected all operations")})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._deferredOperationsWithCauseId={},this._logger=e}registerPromise(e,t){let i=!1;const n=()=>{i=!0};t.then(n,n);const r=this._endOperationDeferred.promise.catch((t=>{if(!i)throw new Error(`Operation ${e} did not complete, reason:${t}`)}));return Promise.race([r,t])}updateOperationId(e,t){this._logger.info(`updateOperationId ${e} ${t}`),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{i&&this._deferredOperationsWithOperationId[i]&&(this._logger.info(`_deferredOperationsWithOperationId ${i}`),Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{n&&this._deferredOperationsWithOperationId[i][n]&&(this._logger.info(`_deferredOperationsWithOperationId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))})),Object.keys(this._deferredOperationsWithCauseId).forEach((i=>{i&&this._deferredOperationsWithCauseId[i]&&(this._logger.info(`_deferredOperationsWithCauseId ${i}`),Object.keys(this._deferredOperationsWithCauseId[i]).forEach((n=>{n&&this._deferredOperationsWithCauseId[i][n]&&(this._logger.info(`_deferredOperationsWithCauseId ${n} ${t}`),n===e&&(this._deferredOperationsWithOperationId[i][t]=this._deferredOperationsWithOperationId[i][n],delete this._deferredOperationsWithOperationId[i][n]))})))}))}createPendingOperation(e,t,i=Te(),n={}){const r=Si();r.promise.catch(Sn);const a=this.getOperationInfoForLogging(i,e,t);let s;if(this._logger.info(`${a}[creating...]`),this._disposed)return this._logger.info(`${a}[create failed, call is disposed]`),Promise.reject(60);if(t){if(this._deferredOperationsWithOperationId[e]||(this._deferredOperationsWithOperationId[e]={}),this._deferredOperationsWithOperationId[e][t])return this._logger.warn(`${a} Deferred operation with given name and operation id is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}/${Ae(t)}`));this._deferredOperationsWithOperationId[e][t]={deferred:r,causeId:i},this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][t]={deferred:r,options:n,operationName:e},s=this._endOperationDeferred.promise.catch((i=>{if(this.hasPendingOperationWithOperationId(e,t))throw new Error(`Operation ${e} ${t} did not complete, reason:${i}`)}))}else{if(this._deferredOperations[e])return this._logger.warn(`${a} Deferred operation with given name is already defined`),Promise.reject(new Error(`Deferred operation with given name is already defined:${e}`));this._deferredOperationsWithCauseId[i]||(this._deferredOperationsWithCauseId[i]={}),this._deferredOperationsWithCauseId[i][""]={deferred:r,options:n,operationName:e},this._deferredOperations[e]={deferred:r,causeId:i},s=this._endOperationDeferred.promise.catch((t=>{if(this.hasPendingOperation(e))throw new Error(`Operation ${e} did not complete, reason:${t}`)}))}return Promise.race([s,r.promise])}hasPendingOperation(e){return!!this._deferredOperations[e]}hasAtleastOneOfPendingOperation(e){for(const t of e)if(this.hasPendingOperation(t))return!0;return!1}hasPendingOperationWithOperationId(e,t){return!(!t||!this._deferredOperationsWithOperationId[e]||!this._deferredOperationsWithOperationId[e][t])}hasPendingOperationWithCauseId(e,t){const i=t||"";return this._deferredOperationsWithCauseId[e]&&!!this._deferredOperationsWithCauseId[e][i]}getPendingOperationWithCauseId(e,t){return this.hasPendingOperationWithCauseId(e,t)?this._deferredOperationsWithCauseId[e][t].deferred.promise:Promise.reject(`[${e}][${t}]: getPendingOperationWithCauseId for given causeId, operationId`)}resolveOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return t.deferred.resolve(i),this._logger.info(`[${e}][${n}] resolved, result=${Ne(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] resolveOperationWithCauseId failed, operation not found`)}rejectOperationWithCauseId(e,t,i){const n=t||"";if(this.hasPendingOperationWithCauseId(e,n)){const t=this._deferredOperationsWithCauseId[e][n],r=t.deferred.promise;return r.catch(Sn),t.deferred.reject(i),this._logger.info(`[${e}][${n}] rejected, result=${Ne(i)||"void"}`),delete this._deferredOperationsWithCauseId[e][n],r}return Promise.reject(`[${e}][${n}] rejectOperationWithCauseId failed, operation not found`)}maybeResolveOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.resolveOperationWithCauseId(e,t,i).catch((t=>{this._logger.info(`${e}maybeResolveOperationWithCauseId failed, reason=${Ne(t)}`)})):this._logger.info(`${e}maybeResolveOperationWithCauseId ignored, operation does not exist`)}maybeRejectOperationWithCauseId(e,t,i){this.hasPendingOperationWithCauseId(e,t)?this.rejectOperationWithCauseId(e,t,i).catch(Sn):this._logger.info(`${e}maybeRejectOperationWithCauseId ignored, operation does not exist`)}getPendingOperation(e,t,i=Te()){return!t&&this._deferredOperations[e]?this._deferredOperations[e].deferred.promise:t&&this._deferredOperationsWithOperationId[e]&&this._deferredOperationsWithOperationId[e][t]?this._deferredOperationsWithOperationId[e][t].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}: Deferred operation with given name and operation does not exist`)}waitForOperation(e,t,i=Te()){return t&&this.hasPendingOperationWithOperationId(e,t)?this._deferredOperationsWithOperationId[e][t].deferred.promise:this.hasPendingOperation(e)?this._deferredOperations[e].deferred.promise:Promise.reject(`${this.getOperationInfoForLogging(i,e,t)}failed=wait failed, operation not found`)}resolveOperation(e,t,i,n=Te(),r=!1){if(!e)return Promise.reject("Unable to resolve deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],a=n.deferred.promise;return n.deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${Ne(t)||"void"}`),r||delete this._deferredOperationsWithOperationId[e][i],a}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],a=this._deferredOperations[e].deferred.promise;return this._deferredOperations[e].deferred.resolve(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}resolved, result=${Ne(t)||"void"}`),r||delete this._deferredOperations[e],a}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=resolve failed, operation not found`)}rejectOperation(e,t,i,n=Te()){if(!e)return Promise.reject("Unable to reject deferred operation with empty name");if(i&&this.hasPendingOperationWithOperationId(e,i)){const n=this._deferredOperationsWithOperationId[e][i],r=n.deferred.promise;return r.catch(Sn),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${Ne(t)||"void"}`),delete this._deferredOperationsWithOperationId[e][i],r}if(this.hasPendingOperation(e)){const n=this._deferredOperations[e],r=n.deferred.promise;return r.catch(Sn),n.deferred.reject(t),this._logger.info(`${this.getOperationInfoForLogging(n.causeId,e,i)}rejected, reason=${Ne(t)||"void"}`),delete this._deferredOperations[e],r}return Promise.reject(`${this.getOperationInfoForLogging(n,e,i)}failed=reject failed, operation not found`)}maybeResolveOperation(e,t,i,n=Te()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.resolveOperation(e,t,i,n).catch((e=>{this._logger.info(`${r}maybeResolveOperation failed, reason=${Ne(e)}`)})):this._logger.info(`${r}maybeResolveOperation ignored, operation does not exist`)}maybeResolveOperations(e,t,i,n=Te()){for(const r of e)this.maybeResolveOperation(r,t,i,n)}maybeRejectOperation(e,t,i,n=Te()){const r=this.getOperationInfoForLogging(n,e,i);i&&this.hasPendingOperationWithOperationId(e,i)||this.hasPendingOperation(e)?this.rejectOperation(e,t,i,n).catch(Sn):this._logger.info(`${r}maybeRejectOperation ignored, operation does not exist`)}maybeRejectOperations(e,t,i,n=Te()){for(const r of e)this.maybeRejectOperation(r,t,i,n)}rejectPendingOperations(e,t=Te()){this._disposed=!0,this._logger.info(`[${t}]rejectPendingOperations=${JSON.stringify(e)}`),Object.keys(this._deferredOperations).forEach((i=>{this.maybeRejectOperation(i,e,void 0,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][""]})),Object.keys(this._deferredOperationsWithOperationId).forEach((i=>{Object.keys(this._deferredOperationsWithOperationId[i]).forEach((n=>{this.maybeRejectOperation(i,e,n,t),this._deferredOperationsWithOperationId[t]&&delete this._deferredOperationsWithOperationId[t][n]}))})),this._deferredOperations={},this._deferredOperationsWithOperationId={},this._endOperationDeferred.reject(e)}maybeRejectPendingOperationsWithPredicate(e,t=Te(),i){this._logger.info(`[${t}]rejectPendingOperationsWithPredicate`),Object.keys(this._deferredOperationsWithCauseId).forEach((t=>{Object.keys(this._deferredOperationsWithCauseId[t]).forEach((n=>{const r=this._deferredOperationsWithCauseId[t][n];r&&i(r.operationName,r.options)&&(this.maybeRejectOperation(r.operationName,e,n),this.maybeRejectOperationWithCauseId(t,n,e))}))}))}getOperationInfoForLogging(e,t,i=""){const n=i?`[${Ae(i)}]`:"";return`[${e.substring(0,8)}][${t}]${n}`}},Ln=g,xn=class{constructor(e){this._logger=e,this._promise=Promise.resolve(void 0),this._actionQueue=[]}chainPromise(e,t,i=Te(),n=!1){const r=Date.now(),a=(("function"==typeof t?t():t)||"").toString();this._actionQueue.push(a),this._logger.info(`[${i}][${a}]enqueueing, queue=[${this._actionQueue}], reset=${n}`);const s=()=>{this._actionQueue=this._actionQueue.filter((e=>e!==a))};return n&&this.reset(i),this._promise=this._promise.catch(Ln.noop).then((()=>{const t=Date.now()-r;return this._logger.info(`[${i}][${a}]begin, delayMs=${t}`),e()})),this._promise.then((()=>{s();const e=Date.now()-r;this._logger.info(`[${i}][${a}]success, durationMs=${e}`)}),(e=>{s();const t=Date.now()-r;this._logger.warn(`[${i}][${a}]failed=${Le(e)}, durationMs=${t}`)})),this._promise}reset(e){this._logger.info(`[${e}] resetting`),this._promise=Promise.resolve(void 0)}};function Fn(e){return!(!e||!e.code)}function Un(e,t){let i;return i=Fn(e)?e:{code:499,subCode:void 0!==t?t:0,phrase:"string"==typeof e?e:Ne(e)},i}var Bn=class{constructor(){this.msElapsed=0,this.isPaused=!1,this._startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this._startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this._startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this._startTime,this.durationInMinutes=()=>{const e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}get startTime(){return this._startTime}};function Vn(){return new Bn}var Hn=class extends Nn{constructor(e,t,i,n,r){super(e),this.callTelemetry=t,this._ecsConfig=i,this._publishCallback=n,this._preconditionFunction=r,this._record={},this.logSuccess=(e,t,i)=>{this._logger.info(`${e} execution succeeded, result=${t?this.stringifyForLogging(t):"void"}, time=${i.duration()}`)},this.logFailure=(e,t,i)=>{this._logger.info(`${e} execution failed, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.logTimeout=(e,t,i)=>{this._logger.info(`${e} execution timed out, reason=${this.stringifyForLogging(t)}, time=${i.duration()}`)},this.stringifyForLogging=e=>{let t;if(e instanceof Error)t=e.toString()||"Unknown Error";else try{t=JSON.stringify(e)}catch(e){t="Unable to stringify data"}return t},this.convertToTransactionEndIfErrorOrString=(e,t,i)=>{if(this._logger.info(`ecsEnableErrorConversion in operationHandler is: ${this._ecsConfig&&this._ecsConfig.enableErrorConversion}`),t&&this._ecsConfig&&this._ecsConfig.enableErrorConversion&&("string"==typeof e||e instanceof Error)){const t=Un(e);return this._logger.info(`${i} Error converted from ${e} to ${Ne(t)}`),t}return e},this._logger=e.createChild("[Operation]"),this._chainedPromise=new xn(this._logger.createChild("[Chained]"))}resetOperationChain(e){this._chainedPromise.reset(e)}executeSync(e,t,i,n=Te(),r,a){const s=this.getOperationInfoForLogging(n,t,i),o=Vn();this._logger.info(`${s}API calledSync`);const l=this.callTelemetry.recordOperation(t,n,i,a);let c;try{this._setRecord(t),c=e(),l.recordSuccess(c,n),this.logSuccess(s,c,o)}catch(e){const t=this.convertToTransactionEndIfErrorOrString(e,r,s);l.recordFailure(t,n),this.logFailure(s,t,o)}return c}async executeChained(e,t,i,n=Te(),r,a,s){return this.checkPendingOperationAndExecute(e,!0,t,i,n,r,a,s)}async execute(e,t,i,n=Te(),r,a,s){return this.checkPendingOperationAndExecute(e,!1,t,i,n,r,a,s)}logOperation(e,t,...i){const n=i.length&&i.map((e=>this.stringifyForLogging(Ae(e))));this._logger.info(`[${e.substring(0,8)}][${t}]API called, ${n?`with args=${n}`:""}`)}rejectPendingOperations(e,t=Te(),i){if(i){for(const e of Object.keys(this._deferredOperations))this.callTelemetry.maybeRecordOperationFailure(e,i,void 0,t);for(const e of Object.keys(this._deferredOperationsWithOperationId))for(const n of Object.keys(this._deferredOperationsWithOperationId[e]))this.callTelemetry.maybeRecordOperationFailure(e,i,n,t)}super.rejectPendingOperations(e,t)}maybeRejectOperations(e,t,i,n=Te(),r){if(r)for(const t of e)this.callTelemetry.maybeRecordOperationFailure(t,r,void 0,n);super.maybeRejectOperations(e,t,i,n)}checkPendingOperationAndExecute(e,t,i,n,r=Te(),a,s,o){const l=this.getOperationInfoForLogging(r,i,n);let c=null,d=null;return this.hasPendingOperationWithOperationId(i,n)||this.hasPendingOperation(i)?(this._logger.info(`${l}already pending, returning existing operation`),c=this.waitForOperation(i,n,r)):d=this.createPendingOperation(i,n,r,o),t?(this._logger.info(`${l}chained`),this._chainedPromise.chainPromise((()=>c||this.executeInternal(d,r,e,i,n,a,s,o)),i,r)):c||this.executeInternal(d,r,e,i,n,a,s,o)}_setRecord(e){this._record.hasOwnProperty(e)||(this._record[e]=0),this._record[e]+=1}getRecord(e){return this._record[e]}_recordTelemetryTimeoutAndPublish(e,t,i,n,r,a,s){const o=e||60;return window.setTimeout((()=>{if(!this._publishCallback)return void this._logger.warn(`${r} is marked to publish telemetry but no publish callback is defined.`);if(!this.hasPendingOperationWithOperationId(n,s)&&!this.hasPendingOperation(n))return;const e=new Error(`${r} execution did not complete before telemetry timeout of ${o}s.`);this.logTimeout(r,e,a),this.callTelemetry.maybeRecordOperationTimeout(n,e,s,i),this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)}),1e3*o)}_instantTelemetryPublish(e,t){this._publishCallback?(this._publishCallback(t),this.callTelemetry.removeRecordedEvent(t)):this._logger.warn(`${e} is marked to publish telemetry but no publish callback is defined.`)}parseInstantTelemetryParameters(e){let t,i=!1;return e&&(i=e.enableInstantTelemetry,t=e.telemetryTimeout),[i,t]}async executeInternal(e,t,i,n,r,a,s,o){const l=this.getOperationInfoForLogging(t,n,r);this._logger.info(`${l} executing operation...`);const c=Vn(),d=this.callTelemetry.recordOperation(n,t,r,s),[u,h]=this.parseInstantTelemetryParameters(o);try{let e;this._setRecord(n),u&&(e=this._recordTelemetryTimeoutAndPublish(h,d,t,n,l,c,r)),o?.preconditionTags?.length&&this._preconditionFunction&&this._preconditionFunction(n,o.preconditionTags);const a=await i();e&&clearTimeout(e),this.callTelemetry.maybeRecordOperationSuccess(n,a,r),this.logSuccess(l,a,c),this.maybeResolveOperation(n,a,r,t)}catch(e){const i=this.convertToTransactionEndIfErrorOrString(e,a,l);this.callTelemetry.maybeRecordOperationFailure(n,i,r),this.logFailure(l,i,c),this.maybeRejectOperation(n,i,r,t)}return u&&this._instantTelemetryPublish(l,d),e}getEcsConfig(){return this._ecsConfig}},$n={Cancel:487,Reject:603,NoNgcEndpoint:480,Forbidden:403,PreconditionFailed:412,Success:0,CallRedirected:302,BadRequest:400,NotFound:404,NotAcceptable:406,Timeout:408,Conflict:409,MediaError:410,ConfParticipantCountLimitReached:413,CallAccepted:450,CallForwarded:451,CallForwardedToVoicemail:452,P2pRejectCall:453,P2pFallbackForScreensharing:460,P2pFallbackDueToGroupCall:461,CallLegEndedOnService:470,CallDoesNotExist:481,NotAcceptableHere:488,NetworkError:490,GlareError:491,SkypeTokenError:495,LocalHttpStackError:496,UnknownError:497,LocalError:498,InternalServerError:500,CallModalityFailure:580,ServiceUnavailable:503},Gn={Success:0,CallRedirectedSuccess:3020,InsufficientCapabilities:5204,PolicyRestriction:5448,UserBlocked:10005,MaxLobbyParticipantLimitReached:5807,MaxParticipantLimitReached:5808,MaxParticipantLimitReached2:5817,SharingStolenError:10029,DowngradeToStreamingClient:3099,MediaDropDuringConnect:3100,MediaDropAfterConnect:3101,MediaAnswerProcessingError:3102,MediaFinalAnswerProcessingError:3103,MediaOfferTimeout:3104,MediaFinalAnswerTimeout:3105,MediaOfferNull:3106,MediaAudioDeviceError:3107,MediaRenegotiationError:3108,MediaPermissionError:3109,MediaUnknownError:3110,MediaOfferProcessingError:3111,MediaWhiteListingIssue:3112,MediaMuteMicrophoneError:3113,MediaMuteSpeakerError:3114,MediaUnmuteMicrophoneError:3115,MediaUnmuteSpeakerError:3115,AttachActionFailed:4103,AttachFailed:4105,PreheatedCallTimedout:4113,RemovedFromConversation:5e3,DeniedInLobby:5854,RemovedFromCall:5300,TimedOutInLobby:5855,AnonymousJoinDisabledByPolicy:5723,B2bJoinDisabledByPolicy:5724,NoLobbyForBroadcastJoin:5354,NotAllowedDueToInformationBarrier:5810,TeamParkPolicyDisabled:10193,BroadcastLimitReached:800100,Suspended:58e4},jn={[$n.Success]:1,[$n.Cancel]:12,[$n.Reject]:10,[$n.NoNgcEndpoint]:2,[$n.Timeout]:6,[$n.CallAccepted]:30,[$n.CallRedirected]:75,[$n.NotFound]:24,[$n.CallDoesNotExist]:46,[$n.NotAcceptable]:5,[$n.BadRequest]:5,[$n.MediaError]:4,[$n.ConfParticipantCountLimitReached]:59,[$n.CallModalityFailure]:4,[$n.NetworkError]:3,[$n.LocalHttpStackError]:31,[$n.LocalError]:25,[$n.CallForwarded]:27,[$n.CallForwardedToVoicemail]:28,[$n.SkypeTokenError]:29,[$n.InternalServerError]:7,[$n.Conflict]:7,[$n.GlareError]:7,[$n.CallLegEndedOnService]:7,[$n.NotAcceptableHere]:26,[$n.UnknownError]:32,[$n.Forbidden]:8,[$n.PreconditionFailed]:65},zn={9401:33,9422:33,6102:1,6423:14,9402:14,9432:14,6519:3,9403:15,9410:36,9411:37,1e3:2,9407:17,13430:18,6009:19,10484:19,10604:19,10404:19,10420:19,10403:20,17401:20,10408:9,10486:11,10600:11,10686:11,10487:21,10500:3,10501:3,10502:3,10503:3,10504:3,10480:22,10482:22,10603:10,13406:23,13416:23},Wn={500:39,403:41,404:42,480:40},qn={INCOMING_SKYPE_NGC_CALL:107,INCOMING_SKYPE_NGC_GVC_CALL:109,INCOMING_PSTN_NGC_CALL:111,INCOMING_SCREENSHARE_WITH_CHAT:119,INCOMING_TFL_TFW_CALL:126},Kn={SHARED_LINE_CALL_RECORD:121,SHARED_LINE_V2_CALL_RECORD:123,MEETING_STARTED_NOTIFICATION:128},Jn={LOG_UPLOAD_EVENT:120},Yn="CallEndReasonUnknown",Qn="CallEndReasonMediaError",Zn="CallEndReasonMediaPermissionError",Xn="CallEndReasonMediaDropDuringConnectError",er="CallEndReasonMediaDropAfterConnectError",tr="CallEndReasonMediaOfferProcessingError",ir="DowngradeToStreamingClient",nr="CallEndReasonIncompatibleOffer",rr="MediaWhitelistingIssue",ar="CallEndReasonAttachFailed",sr="CallEndReasonBadNotificationPayload",or="RetargetNotSupported",lr="CallEndReasonLocalUserInitiated",cr="EndedByRemoteEndpoint",dr="CallEndReasonRedirected",ur="CallEndReasonVDIdisconnect",hr="CallEndReasonSuspended",pr=(e=>(e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.CallStart="CallStart",e.WaitForAnswer="WaitForAnswer",e.WaitForConnect="WaitForConnect",e.Accept="Accept",e))(pr||{}),gr=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.UpdateMediaModalities="UpdateMediaModalities",e.CreateOffer="CreateOffer",e.CreateAnswer="CreateAnswer",e.ProcessAnswer="ProcessAnswer",e.GetSignalingMediaTypes="GetSignalingMediaTypes",e.MuteUnmute="MuteUnmute",e.MuteUnmuteSpeakers="MuteUnmuteSpeakers",e.StartVideoSafe="StartVideoSafe",e.CompleteNegotiation="CompleteNegotiation",e.MuteInput="MuteInput",e.MuteOutput="MuteOutput",e.UnmuteInput="UnmuteInput",e.UnmuteOutput="UnmuteOutput",e.evaluateEndpointStatesForAccept="evaluateEndpointStatesForAccept",e.handleEndpointStatesForAccept="handleEndpointStatesForAccept",e))(gr||{}),mr=(e=>(e.InitializeMediaSession="InitializeMediaSession",e.ProcessOffer="ProcessOffer",e.ProcessOfferedModalities="ProcessOfferedModalities",e.TrySendingProvisionalAnswer="TrySendingProvisionalAnswer",e))(mr||{}),fr=g,vr=f(g),Sr=f(g),yr=f(ce()),Cr="Success",_r="ExpectedError",Er="UnexpectedClientError",Tr="UnexpectedServerError",br={INCOMING_MESSAGE_ORIGIN:{TROUTER:"Trouter",BROKER:"Broker"},INVITATION_TYPE:{NUDGE:"nudge"},KNOWN_PAYLOAD_ENCODINGS:{GZIP:!0},WEBRTC_NOTIFICATION_TYPE:{CONTROL_VIDEO_STREAMING:"ControlVideoStreaming",DOMINANT_SPEAKER_INFO:"DominantSpeakerInfo",CSRC_INFO:"CsrcInfo"},PARTICIPANT_AUDIO_STATE:{CONNECTING:"Connecting",RINGING:"Ringing",CONNECTED:"Connected",OTHER:"Other"},HEADERS:{MESSAGE_ID:"X-Microsoft-Skype-Message-ID",ORIGINAL_MESSAGE_ID:"X-Microsoft-Skype-Original-Message-ID",CONTENT_ENCODING:"X-Microsoft-Skype-Content-Encoding",CORRELATION_ID:"X-Microsoft-Skype-Chain-ID",CONTENT_SHARING_CORRELATION_ID:"X-Microsoft-Skype-ContentSharing-Chain-ID",CLIENT_USER_AGENT:"X-Microsoft-Skype-Client",SKYPE_TOKEN:"X-Skypetoken",AUTHORIZATION:"Authorization",BEARER_KEYWORD:"Bearer",AAD_KEYWORD:"Aad",CAE_KEYWORD:"Cae",SKYPE_KEYWORD:"Skype",CACHE_SKYPE_TOKEN:"X-CacheSkypeToken",AUTHENTICATE:"www-authenticate",TOKEN_MIGRATION:"X-MS-Migration",BROKER_USE_BATCHING_HEADER_NAME:"X-UseBatching",PARTICIPANT_ID:"X-Microsoft-Skype-Participant-ID",CONTENT_TYPE:"Content-Type",RING:"MS-Teams-Ring",REGION:"MS-Teams-Region",PARTITION:"MS-Teams-Partition"},KNOWN_BOTS:{VOICEMAIL_BOT_ID:"28:14524421-25b4-403a-a0f7-e62d4379cabc"},HTTP_STACK_ERROR:{NONE:0,CANNOT_CONNECT:7,REQUEST_TIMEOUT:10,ATTEMPT_TIMEOUT:30,REQUEST_ABORTED:16,ATTEMPT_ABORTED:31,ABORTED_OTHER_ATTEMPT_SUCCESSFUL:32},HTTP_STATUS_CODES:{UNKNOWN:0,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,NOT_FOUND:404,FORBIDDEN:403,PRECONDITION_FAILED:412,UNPROCESSABLE_ENTITY:422,NETWORK_ERROR:490,SKYPE_TOKEN_ERROR:495,OFFLINE:496,TIMEOUT:498,ABORTED:498,OTHER:499,INTERNAL_SERVER_ERROR:500,CONFLICT:409,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504},CALL_END_SKYPE_TOKEN_ERROR:{code:495,subCode:4507,phrase:"CallEndReasonSkypeTokenFetchError",resultCategories:[Er]},CALL_END_TOKEN_TIMEOUT_ERROR:{code:499,subCode:3119,phrase:"CallEndReasonTokenFetchTimeout",resultCategories:[Er]},CALL_END_UNSUPPORTED_TOKEN_ERROR:{code:499,subCode:3126,phrase:"CallEndReasonUnsupportedTokenError",resultCategories:[Er]},CALL_END_TOKEN_ERROR:{code:499,subCode:3127,phrase:"CallEndReasonTokenFetchError",resultCategories:[Er]},CALL_END_LOCAL_HTTP_STACK_ERROR:{code:496,subCode:4520,phrase:"LocalHTTPStackError",resultCategories:[Er]},CALL_END_UNKNOWN_ERROR:{code:497,subCode:3121,phrase:"CallEndReasonUnknownError",resultCategories:[Er]},CALL_END_NETWORK_ERROR:{code:490,subCode:4502,phrase:"CallEndReasonNetworkError",resultCategories:[Er]},CALL_END_LOCAL_DECLINE:{code:486,subCode:4508,phrase:"LocalDecline",resultCategories:[Cr]},RESOURCE_NOT_FOUND_ERROR:{code:404,subCode:404,phrase:"ResourceNotFound",resultCategories:[_r]},CALL_STATUS:{IDLE:"Idle",RINGING:"Ringing",CONNECTING:"Connecting",CONNECTED:"Connected",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly",LOCAL_TERMINATED:"LocalTerminated",REMOTE_TERMINATED:"RemoteTerminated"},MEDIA_TYPES:{AUDIO:"Audio",VIDEO:"Video",SCREEN_SHARER:"ScreenSharer",SCREEN_VIEWER:"ScreenViewer"},MUTE_SCOPE:{MYSELF:"Myself",EVERYONE_ELSE:"EveryoneElse",SPECIFIED_PARTICIPANTS:"SpecifiedParticipants"},URL_BASE:{CALLAGENT:"callAgent"},LINKS:{HANGUP:"hangup",MEDIA_REJECTION:"mediaRejection",MEDIA_ANSWER:"mediaAnswer",MEDIA_RENEGOTIATION:"mediaRenegotiation",ACCEPT:"accept",ATTACH:"attach",REJECT:"reject",REDIRECT:"redirect",REPLACE:"replace",TRANSFER:"transfer",NEW_OFFER:"newOffer",TRANSFER_ACCEPTANCE:"transferAcceptance",TRANSFER_COMPLETION:"transferCompletion",CONVERSATION_CONTROLLER:"conversationController",ADD_PARTICIPANT:"addParticipant",ADD_PARTICIPANTS_AND_MODALITY:"addParticipantsAndModality",LEAVE:"leave",NOTIFICATION_LINKS:"notificationLinks",REMOVE_PARTICIPANT:"removeParticipant",KEEPALIVE:"keepAlive",ADD_MODALITY:"AddModality",REMOVE_MODALITY:"RemoveModality",CONTENT_SHARING_CONTROLLER:"contentSharingController",CONTENT_SHARING_TAKE_CONTROL:"contentSharingTakeControl",CONTENT_SHARING_UPDATE_SESSION_STATE:"contentSharingUpdateSessionState",CONTENT_SHARING_UPDATE_PARTICIPANT_STATE:"contentSharingUpdateParticipantState",CONTENT_SHARING_NOTIFICATION_LINKS:"contentSharingNotificationLinks",CONTENT_SHARING_LEAVE:"contentSharingLeave",MUTE:"mute",UNMUTE:"unmute",ADMIT:"admit",ADMIT_ALL:"admitAll",CONTROL_VIDEO_STREAMING:"controlVideoStreaming",APPLY_CHANNEL_PARAMETERS:"applyChannelParameters",UPDATE_ENDPOINT_STATE:"updateEndpointState",UPDATE_ENDPOINT_METADATA:"updateEndpointMetadata",LMC_NOTIFICATION_LINKS:"lmcNotificationLinks",UPDATE_PARTICIPANT_ROLE:"updateParticipantRole",PUBLISH_STATE:"publishState",REMOVE_STATE:"removeState",UPDATE_MEETING_SETTINGS:"updateMeetingSettings",SEARCH_PARTICIPANTS:"searchParticipants",GET_ALL_PARTICIPANTS:"getAllParticipants",PARK:"park",UNPARK:"unpark",UPDATE_MEETING_LIVE_STATE:"updateMeetingLiveState",UPDATE_MEETING_GROUPS:"updateMeetingGroups",SET_MEETING_LAYOUT:"setMeetingLayout",UPDATE_PARTICIPANT_INTERPRETATION_STATE:"updateParticipantInterpretationState",JOIN_MEETING_GROUP:"joinMeetingGroup",LEAVE_MEETING_GROUP:"leaveMeetingGroup",SEND_MESSAGE:"sendMessage",UPDATE_PARTICIPANTS_PROPERTIES:"updateParticipantsProperties",UPDATE_MEDIA_DESCRIPTIONS:"updateMediaDescriptions",UPDATE_MEETING_STATES:"updateMeetingStates"},CONTENT_TYPE:{JSON:"application/json",SDP:"application/sdp"},TROUTER_EVENT_TYPE:{SKYPE_SKYPE_CALL:107,LYNC_SKYPE_CALL:105},MISC:{CONVERSATION:"conversation",LOBBY_CALL_CONTROLLER:"lobby",LOBBY_PARTICIPANT_STATE:"lobby"},SIGNALING_FSM_STATE:{IDLE:"Idle",INCOMING:"Incoming",WAITING_CALL_ACCEPTANCE_ACK:"WaitingCallAcceptanceAck",OUTGOING:"Outgoing",CONNECTED:"Connected",OUTGOING_FOR_ROSTER_ONLY:"OutgoingForRosterOnly",CONNECTED_FOR_ROSTER_ONLY:"ConnectedForRosterOnly"},MEDIA_RENEGOTIATION_FSM_STATE:{IDLE:"Idle",CALL_CONNECTED:"Connected",INCOMING_RENEGOTIATION:"IncomingRenegotiation",OUTGOING_RENEGOTIATION:"OutgoingRenegotiation",RENEGOTIATION_GLARE:"RenegotiationGlare"},CONTENT_SHARING_FSM_STATE:{IDLE:"Idle",CONTENT_SHARING_START_INITIATED:"ContentSharingStartInitiated",CONTENT_SHARING_JOIN_INITIATED:"ContentSharingJoinInitiated",CONTENT_SHARING_LEAVE_INITIATED:"ContentSharingLeaveInitiated",CONTENT_SHARING_DELETE_INITIATED:"ContentSharingDeleteInitiated",CONTENT_SHARING_CONNECTED:"ContentSharingConnected"},TIMEOUT_OPERATIONS:{ADD_PARTICIPANT:"AddParticipant",NUDGE_PARTICIPANT:"NudgeParticipant",REMOVE_PARTICIPANT:"RemoveParticipant",ADMIT_PARTICIPANT:"AdmitParticipant",ADMIT:"Admit",CALL_REDIRECT:"CallRedirect",CALL_ME_BACK:"CallMeBack",INCOMING_CALL_ESTABLISHMENT:"IncomingCallEstablishment",OUTGOING_CALL_ESTABLISHMENT:"OutgoingCallEstablishment",MEDIA_ANSWER:"MediaAnswer",MEDIA_ANSWER_ACKNOWLEDGEMENT:"MediaAnswerAcknowledgement",ADD_MODALITY:"AddModality",UNMUTE:"Unmute",UPDATE_MEETING_ROLE:"UpdateMeetingRole",MAX_PREAHEATED_TIMEOUT:"MaxPreheateadTimeout",PARK_COMPLETION:"ParkCompletion",UNPARK_COMPLETION:"UnparkCompletion",UPDATE_MEETING_LIVE_STATE_COMPLETION:"UpdateMeetingLiveStateCompletion",UPDATE_MEETING_GROUPS_COMPLETION:"UpgradeMeetingGroupsCompletion",UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION:"UpdateParticipantInterpretationStateCompletion",UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION:"UpdateParticipantsPropertiesCompletion",JOIN_MEETING_GROUP_COMPLETION:"JoinMeetingGroupCompletion",LEAVE_MEETING_GROUP_COMPLETION:"LeaveMeetingGroupCompletion",SET_MEETING_LAYOUT_COMPLETION:"SetMeetingLayoutCompletion",SEND_MESSAGE_COMPLETION:"SendMessageCompletion",DISABLE_PREHEAT_ASYNC_TIMEOUT:"DisablePreheatAsyncTimeout",UPDATE_MEETING_STATES_COMPLETION:"UpdateMeetingStatesCompletion"},TIMEOUT_VALUES_IN_SECONDS:{ADD_PARTICIPANT_TIMEOUT:130,REMOVE_PARTICIPANT_TIMEOUT:60,INCOMING_CALL_ESTABLISHMENT_TIMEOUT:75,OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:90,LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:185,MEDIA_ANSWER_TIMEOUT:35,MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT:15,ADD_MODALITY_TIMEOUT:65,UNMUTE_TIMEOUT:35,ADMIT_PARTICIPANT_TIMEOUT:120,ADMIT_TIMEOUT:60,UPDATE_MEETING_ROLE_TIMEOUT:15,NUDGE_PARTICIPANT_TIMEOUT:60,CALL_ME_BACK_TIMEOUT:120,MAX_PREAHEATED_TIMEOUT:90,PARK_COMPLETION_TIMEOUT:45,UNPARK_COMPLETION_TIMEOUT:45,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:45,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:45,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT:45,UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT:45,JOIN_MEETING_GROUP_COMPLETION_TIMEOUT:45,LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT:45,CONVERSATION_KEEP_ALIVE_TIMEOUT:2700,TOKEN_REQUIRED_TIMEOUT:20,SEND_MESSAGE_COMPLETION_TIMEOUT:15,DISABLE_PREHEAT_TIMEOUT:45,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:45},CALL_END_CODE:{REJECT:603,SUCCESS:0,CALL_REDIRECTED:302,CANCEL:487,TIMEOUT:408,SERVICE_UNAVAILABLE:500,BAD_REQUEST:406,NO_NGC_ENDPOINT:480,P2P_FALLBACK_FOR_SCREENSHARING:460,CONFLICT:409,MEDIA_ERROR:410,CONF_PARTICIPANT_COUNT_LIMIT_REACHED:413,CALL_DOES_NOT_EXIST:481,CALL_ACCEPTED:450,CALL_FORWARDED:451,CALL_FORWARDED_TO_VOICEMAIL:452,P2P_REJECT_CALL:453,P2P_FALLBACK_DUE_TO_GROUPCALL:461,CALL_LEG_ENDED_ON_SERVICE:470,NOT_ACCEPTABLE_HERE:488,NETWORK_ERROR:490,UNKNOWN_ERROR:497,LOCAL_ERROR:498,CALL_MODALITY_FAILURE:580,ATC_CONTROLLER_FAILURE:581,CVA_CONTROLLER_FAILURE:586,GLARE_ERROR:491,NOT_FOUND:404,SKYPE_TOKEN_ERROR:495,LOCAL_HTTP_STACK_ERROR:496,HTTP_OTHER_ERROR:499,DECODING_FAILED:407,NOT_AUTHORIZED:403,BAD_SERVICE_RESPONSE:400},CALL_END_SUB_CODE:{SUCCESS:0,CALL_REDIRECTED_SUCCESS:3020,DOWNGRADE_TO_STREAMING_CLIENT:3099,MEDIA_DROP_DURING_CONNECT:3100,MEDIA_DROP_AFTER_CONNECT:3101,MEDIA_ANSWER_PROCESSING_ERROR:3102,MEDIA_FINAL_ANSWER_PROCESSING_ERROR:3103,MEDIA_OFFER_TIMEOUT:3104,MEDIA_FINAL_ANSWER_TIMEOUT:3105,MEDIA_OFFER_NULL:3106,MEDIA_AUDIO_DEVICE_ERROR:3107,MEDIA_RENEGOTIATION_ERROR:3108,MEDIA_PERMISSION_ERROR:3109,MEDIA_UNKNOWN_ERROR:3110,MEDIA_OFFER_PROCESSING_ERROR:3111,MEDIA_WHITELISTING_ISSUE:3112,MEDIA_MUTE_MICROPHONE_ERROR:3114,MEDIA_MUTE_SPEAKER_ERROR:3115,MEDIA_UNMUTE_MICROPHONE_ERROR:3116,MEDIA_UNMUTE_SPEAKER_ERROR:3117,MEDIA_GLARE_ERROR:3118,CONVERSATION_TERMINATION_UNKNOWN_ERROR:3121,CONVERSATION_NOTIFICATION_TIMEOUT:3125,CALL_NOT_ATTEMPTED:4500,CONV_URL_NOT_SET:4501,FAILED_TO_REACH_SERVICE:4502,PLACE_CALL_FAILED:4503,ATTACH_CALL_FAILED:4504,BAD_NOTIFICATION_PAYLOAD:4505,CALL_ESTABLISHMENT_TIMEOUT:4506,SKYPE_TOKEN_ERROR:4507,CONVERSATION_RESOLUTION_CONFLICT:5704,CALL_PARTICIPANT_REMOVAL_TIMEOUT:4507,UNMUTE_REQUEST_TIMEOUT:4509,UNMUTE_REQUEST_REJECTED:4510,CONFLICT_IN_NG:4090,CONFLICT_WITH_P2P:4091,CONVERSATION_END_RECEIVED_FROM_SERVICE:4100,TRANSFER_COMPLETE_TIMEOUT:4101,ATTACH_TO_NON_EXISTENT_CALL:4102,ATTACH_ACTION_FAILED:4103,ATTACH_FAILED:4105,CONVERSATION_ESTABLISHMENT_FAILED:4106,BEFORE_CONNECT:4107,AFTER_CONNECT:4108,AFTER_ACCEPT:4109,TROUTER_CONNECTION_DROPPED:4111,DUE_TO_CALL_ASSIMILATION:4112,PREHEATED_CALL_TIMEDOUT:4113,UNPARK_COMPLETION_TIMEOUT:4114,PARK_COMPLETION_TIMEOUT:4115,UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:4116,UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:4117,SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:4118,UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:4119,JOIN_MEETING_GROUP_TIMEOUT:4120,LEAVE_MEETING_GROUP_TIMEOUT:4121,UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:4122,UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:4123,MISSING_REQUEST_URI:4511,LOCAL_HTTP_STACK_ERROR:4520,BEACON:4521,CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:5014,UNABLE_TO_GENERATE_MEETUP_ID:5015,UPDATE_MEETING_ROLE_REJECTED:5651,UPDATE_MEETING_ROLE_TIMEOUT:5652,PUBLISH_STATE_LINK_MISSING:5653,PUBLISH_STATE_INVALID_CONTENT:5654,PUBLISH_STATE_INVALID_SERVICE_RESPONSE:5655,REMOVE_STATE_LINK_MISSING:5656,REMOVE_STATE_MISSING_ARGUMENTS:5657,UPDATE_MEETING_SETTINGS_LINK_MISSING:5658,UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS:5659,ADMIT_ALL_LINK_MISSING:5660,ADMIT_TIMEOUT:5661,CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE:5670,ROSTER_HANDLING_INVALID_SERVICE_RESPONSE:5671,SEARCH_PARTICIPANTS_LINK_MISSING:5672,SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5673,GET_ALL_PARTICIPANTS_LINK_MISSING:5674,GET_ALL_PARTICIPANTS_INVALID_SCOPE:5675,GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE:5676,PARK_UNPARK_TYPE_MISSING:5680,PARK_UNPARK_V2_DISABLED:5682,UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING:5683,DISABLE_PREHEAT_TIMEOUT:5684,CALL_ENDED_BY_PLATFORM_AGENT:7e3},CALL_END_PHRASE:{UNKNOWN:"CallEndReasonUnknown",MEDIA_ERROR:"CallEndReasonMediaError",MEDIA_OFFER_TIMEOUT:"CallEndReasonMediaOfferTimeout",MEDIA_FINAL_ANSWER_TIMEOUT:"CallEndReasonMediaFinalAnswerTimeout",MEDIA_ANSWER_ERROR:"CallEndReasonMediaAnswerError",MEDIA_FINAL_ANSWER_ERROR:"CallEndReasonFinalAnswerError",MEDIA_PERMISSION_ERROR:"CallEndReasonMediaPermissionError",MEDIA_RENEGOTIATION_ERROR:"CallEndReasonRenegotiationError",MEDIA_DROP_DURING_CONNECT:"CallEndReasonMediaDropDuringConnectError",MEDIA_DROP_AFTER_CONNECT:"CallEndReasonMediaDropAfterConnectError",MEDIA_OFFER_PROCESSING_ERROR:"CallEndReasonMediaOfferProcessingError",MEDIA_WHITELISTING_ISSUE:"MediaWhitelistingIssue",AUDIO_ERROR:"CallEndReasonAudioDeviceError",CONVERSATION_NOTIFICATION_TIMEOUT:"ConversationNotificationTimeout",BAD_NOTIFICATION_PAYLOAD:"BadCallNotificationPayload",NETWORK_ERROR:"CallEndReasonNetworkError",LOCAL_USER_INITIATED:"CallEndReasonLocalUserInitiated",REMOTE_USER_INITIATED:"CallEndReasonRemoteUserInitiated",ESTABLISHMENT_TIMEOUT:"CallEndReasonEstablishmentTimeout",PARTICIPANT_REMOVAL_TIMEOUT:"CallParticipantRemovalTimeout",LOCAL_ERROR:"CallEndReasonLocalError",CALL_UPDATE_ERROR:"CallEndReasonCallUpdateError",CALL_REDIRECT_IS_NOT_ALLOWED:"CallRedirectisNotAllowed",P2P_FORK_CONNECTED:"CallEndReasonP2pForkConnected",P2P_FORK_FORWARDED:"CallEndReasonP2pForkForwarded",P2P_FORK_FORWARDED_TO_VOICEMAIL:"CallEndReasonP2pForkForwardedToVoiceMail",P2P_FALLBACK_FOR_SCREENSHARING:"CallEndReasonP2pFallbackForScreensharing",P2P_FALLBACK_FOR_GROUPCALL:"CallEndReasonP2pFallbackForGroupCall",P2P_FALLBACK_FOR_CALL_ASSIMILATION:"CallEndReasonP2pFallbackForCallAssimilation",P2P_FALLBACK_FOR_TRANSLATION:"CallEndReasonP2pFallbackForCallTranslation",P2P_FORK_REJECTED:"CallEndReasonP2pForkRejected",TROUTER_CONNECTION_DROPPED:"CallEndReasonTrouterConnectionDropped",REMOVED_FROM_CALL:"CallEndReasonRemovedFromCall",TRANSFER_COMPLETION_TIMEOUT:"CallEndReasonTransferCompletionTimeout",CALL_DOES_NOT_EXIST:"CallEndReasonCallDoesNotExist",ATTACH_ACTION_FAILED:"CallEndReasonAttachActionFailed",ATTACH_FAILED:"CallEndReasonAttachFailed",CONVERSATION_ESTABLISHMENT_FAILED:"CallEndReasonConversationEstablishmentFailed",CONV_END_FROM_SERVICE:"CallEndReasonConversationEndReceivedFromService",CONV_END_FROM_SERVICE_WITH_ERROR:"CallEndReasonConversationEndReceivedFromServiceWithError",SERVICE_ERROR:"CallEndReasonServiceError",CONFLICT:"CallEndReasonConflict",CALL_ALREADY_IN_P2P:"CallEndReasonCallAlreadyExistsInP2p",CONV_END_NO_MODALITY:"ConversationEndNoModalityConnected",CONV_END_FOR_ALL_INITIATED:"ConversationEndForAllInitiated",RENEGOTIATION_IN_PROGRESS:"NegotiationIsInProgress",ADD_PARTICIPANT_URL_MISSING:"AddParticipantUrlMissing",ADMIT_PARTICIPANT_URL_MISSING:"AdmitParticipantUrlMissing",ADMIT_ALL_URL_MISSING:"AdmitAllUrlMissing",UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING:"UpdateParticipantInterpretationStateUrlMissing",UPDATE_PARTICIPANTS_PROPERTIES_URL_MISSING:"UpdateParticipantsPropertiesUrlMissing",ADMIT_TIMEOUT:"AdmitTimeout",UNABLE_TO_GENERATE_MEETUP_ID:"Unable to generate GroupChat meetup id.",ENDED_BY_PMA:"Call ended by media agent.",OWNERSHIP_RESOLUTION_CONFLICT:"Conversation cannot be created due to a failure to resolve ownership.",CONVERSATION_ENDED_NO_NEW_OWNER_FOUND:"This conversation has ended since we were unable to determine a potential host for the group call.",UNMUTE_REQUEST_TIMEOUT:"UnmuteRequestTimeout",UNMUTE_REQUEST_REJECTED:"UnmuteRequestRejected",UPDATE_MEETING_ROLE_TIMEOUT:"UpdateMeetingRoleTimeout",UPDATE_MEETING_ROLE_REJECTED:"Update meeting role operation failed due to insufficient privileges.",PARK_REQUEST_FAILED:"Park Request Failed",PARK_COMPLETION_TIMEOUT:"ParkCompletionTimeout",PARK_COMPLETION_FAILED:"ParkCompletionFailed",UNPARK_REQUEST_FAILED:"UnparkFailed",UNPARK_COMPLETION_TIMEOUT:"UnparkCompletionTimeout",UNPARK_COMPLETION_FAILED:"UnparkCompletionFailed",BAD_SERVICE_RESPONSE:"BadServiceResponse",UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT:"UpdateMeetingLiveStateCompletionTimeout",UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT:"UpdateMeetingGroupsCompletionTimeout",SET_MEETING_LAYOUT_COMPLETION_TIMEOUT:"SetMeetingLayoutCompletionTimeout",UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT:"UpdateParticipantInterpretationTimeout",JOIN_MEETING_GROUP_TIMEOUT:"JoinMeetingGroupTimeout",LEAVE_MEETING_GROUP_TIMEOUT:"LeaveMeetingGroupTimeout",DOWNGRADE_TO_STREAMING_CLIENT:"DowngradeToStreamingClient",MESSAGE_STATUS_WITH_FAILURE_COUNT:"NotZeroFailureCount",UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT:"UpdateParticipantsPropertiesTimeout",DISABLE_PREHEAT_TIMEOUT:"DisablePreheatTimeout",UPDATE_MEETING_STATES_COMPLETION_TIMEOUT:"UpdateMeetingStatesCompletionTimeout"},TRANSACTION_END_CODE:{SUCCESS:0},URL_DEFAULTS:{UPLOAD_LOG_URL:"https://api.cc.skype.com/cc/v1/uploadlog/"},SUCCESS_TRANSACTION_END:{code:0,resultCategories:[Cr]},VALIDATION:{VALIDATION_FAILED:6e3,NULL_OR_EMPTY:6001}},Ir={REQUEST_TIMEOUT:{status:br.HTTP_STATUS_CODES.TIMEOUT,statusText:"Request timed out",readyState:0,response:br.HTTP_STACK_ERROR.REQUEST_TIMEOUT},ATTEMPT_TIMEOUT:{status:br.HTTP_STATUS_CODES.TIMEOUT,statusText:"Attempt timed out",readyState:0,response:br.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT},REQUEST_ABORTED:{status:br.HTTP_STATUS_CODES.ABORTED,statusText:"Request Aborted",readyState:0,response:br.HTTP_STACK_ERROR.REQUEST_ABORTED},ATTEMPT_ABORTED:{status:br.HTTP_STATUS_CODES.ABORTED,statusText:"Attempt Aborted",readyState:0,response:br.HTTP_STACK_ERROR.ATTEMPT_ABORTED}},wr={MEDIA_ACKNOWLEDGEMENT:"/call/mediaAcknowledgement/",MEDIA_REJECTION:"/call/rejection/",ACKNOWLEDGEMENT:"/call/acknowledgement/",MEDIA_RENEGOTIATION:"/call/mediaRenegotiation/",REPLACE:"/call/replacement/",PROGRESS:"/call/progress/",MEDIA_ANSWER:"/call/mediaAnswer/",NEW_MEDIA_OFFER:"/call/newMediaOffer/",REDIRECTION:"/call/redirection/",BALANCE_UPDATE:"/call/balanceUpdate/",ACCEPT:"/call/acceptance/",CONTROL_VIDEO_STREAMING:"/call/controlVideoStreaming/",DOMINANT_SPEAKER_INFO:"/call/dominantSpeakerInfo/",CSRC_INFO:"/call/csrcInfo/",END:"/call/end/",RETARGET_COMPLETION:"/call/retargetCompletion/",TRANSFER:"/call/transfer/",TRANSFER_ACCEPTANCE:"/call/transferAcceptance/",TRANSFER_COMPLETION:"/call/transferCompletion/",PARK_COMPLETION:"/call/holdCompletion/",UNPARK_COMPLETION:"/call/resumeCompletion/",UPDATE_MEDIA_DESCRIPTIONS:"/call/updateMediaDescriptions"},Rr={CONV_END:"/conversation/conversationEnd/",CONV_UPDATE:"/conversation/conversationUpdate/",CONV_LOCAL_PARTICIPANT_UPDATE:"/conversation/localParticipantUpdate/",CONV_ROSTER_UPDATE:"/conversation/rosterUpdate/",CONV_ADD_PARTICIPANT_SUCCESS:"/conversation/addParticipantSuccess/",CONV_ADD_PARTICIPANT_FAILURE:"/conversation/addParticipantFailure/",CONV_NUDGE_PARTICIPANT_SUCCESS:"/conversation/nudgeParticipantSuccess/",CONV_NUDGE_PARTICIPANT_FAILURE:"/conversation/nudgeParticipantFailure/",CONV_ADMIT_PARTICIPANT_SUCCESS:"/conversation/admitParticipantSuccess/",CONV_ADMIT_PARTICIPANT_FAILURE:"/conversation/admitParticipantFailure/",CONV_ADMIT_ALL_STATUS:"/conversation/admitAllStatus/",CONV_REMOVE_PARTICIPANT_SUCCESS:"/conversation/removeParticipantSuccess/",CONV_REMOVE_PARTICIPANT_FAILURE:"/conversation/removeParticipantFailure/",CONV_ADD_MODALITY_SUCCESS:"/conversation/addModalitySuccess/",CONV_ADD_MODALITY_FAILURE:"/conversation/addModalityFailure/",CONV_CONTENT_SHARING_UPDATE:"/conversation/contentSharingUpdate/",CONV_CONTENT_SHARING_END:"/conversation/contentSharingEnd/",CONV_BROADCAST_UPDATE:"/conversation/broadcastUpdate/",CONV_CONFIRM_UNMUTE:"/conversation/confirmUnmute/",CONV_UNMUTE_SUCCESS:"/conversation/unmuteSuccess/",CONV_UNMUTE_FAILURE:"/conversation/unmuteFailure/",UPDATE_MEETING_LIVE_STATE_STATUS:"/conversation/updateMeetingLiveStateStatus/",UPDATE_MEETING_GROUPS_STATUS:"/conversation/updateMeetingGroupsStatus/",SET_MEETING_LAYOUT_STATUS:"/conversation/setMeetingLayoutStatus/",UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS:"/conversation/updateParticipantInterpretationStateStatus/",UPDATE_PARTICIPANT_PROPERTIES_STATUS:"/conversation/updateParticipantPropertiesStatus/",JOIN_MEETING_GROUP_STATUS:"/conversation/joinMeetingGroupStatus/",LEAVE_MEETING_GROUP_STATUS:"/conversation/leaveMeetingGroupStatus/",RECEIVE_MESSAGE:"/conversation/receiveMessage/",SEND_MESSAGE_STATUS:"/conversation/sendMessageStatus/",DISABLE_PREHEAT_ASYNC_STATUS:"/conversation/disablePreheatAsyncStatus/",UPDATE_MEETING_STATES_STATUS:"/conversation/updateMeetingStatesStatus/",MUTE_UNMUTE_ASYNC:"/conversation/muteUnmuteAsync/"},Ar={...wr,...Rr},Pr="callNotification",Mr="mediaAnswer",kr="mediaAcknowledgement",Dr="callAcceptance",Or="callEnd",Nr="callProgress",Lr="callAcceptanceAcknowledgement",xr="mediaNegotiation",Fr="mediaNegotiationFailure",Ur="balanceUpdate",Br="retargetCompleted",Vr="callTransfer",Hr="transferCompletion",$r="transferAcceptance",Gr="holdCompletion",jr="resumeCompletion",zr="updateMeetingLiveStateResponse",Wr="updateMeetingGroupsResponse",qr="setMeetingLayoutResponse",Kr="updateMeetingStatesResponse",Jr=br,Yr=f(g),Qr=class e{constructor(e){this.headers={},e&&Object.keys(e).forEach((t=>{this.headers[this.getLowerCaseName(t)]=e[t]}))}isEmpty(){return Yr.isEmpty(this.headers)}set(e,t){this.headers[this.getLowerCaseName(e)]=t}get(t,i){return i?e.getHeaderValue(this.headers,t)||i:e.getHeaderValue(this.headers,t)}delete(e){delete this.headers[e],delete this.headers[e.toLowerCase()]}hasOwnPropertyCaseInsensitive(e){return Object.keys(this.headers).filter((function(t){return t.toUpperCase()===e.toUpperCase()})).length>0}getAll(){return this.headers}getLowerCaseName(t){return e.useLowerCaseHeaders?t.toLowerCase():t}static getHeaderValue(e,t){return e.hasOwnProperty(t)?e[t]:e.hasOwnProperty(t.toLowerCase())?e[t.toLowerCase()]:void 0}};function Zr(e,t,i=na()){return sa(t,"trailingPath cannot be null"),oa(e,"signalingSession cannot be null"),oa(e.baseMessagingChannelUrl,"messaging channel url is not set"),`${e.baseMessagingChannelUrl}${Jr.URL_BASE.CALLAGENT}/${e.sessionId}/${i}${t}`}function Xr(e){let t=1;return e.callingServiceSupportsAADTokens&&(t|=4),e.callingServiceSupportsCAETokens&&(t|=8),t}function ea(e){const t=e.toLowerCase(),i='token_types="',n=t.indexOf(i);if(-1===n)return[];const r=t.indexOf('"',n+13);if(-1===r)return[];const a=t.substring(n+13,r).trim();return""===a?[]:a.split(" ")}function ta(e){return!!e.match(/^8:/)}function ia(e){return e.replace(/^\d+:/,"")}function na(){return ra().substr(0,8)}function ra(){const e="0123456789abcdef";let t="",i=0,n=0;for(;n<36;){const r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"[n];switch(i=n%8==0?4294967295*Math.random()|0:i>>4,r){case"x":t+=e[15&i];break;case"y":t+=e[3&i|8];break;case"4":case"-":t+=r}n++}return t}function aa(e,t){if(!e)throw new Error("Assert failed"+(void 0!==t?`:${t}`:""))}function sa(e,t){if(!e||e instanceof String&&""===e||e instanceof Array&&0===e.length)throw new Error("AssertNotNullOrEmpty failed. "+(void 0!==t?`: ${t}`:""))}function oa(e,t){if(!e)throw new Error("AssertNotNull failed. "+(void 0!==t?`: ${t}`:""))}function la(e){if(sa(e,"callEndReason cannot be null or empty"),void 0===e.code||void 0===e.subCode||void 0===e.phrase||e.code<0||e.subCode<0||" "===e.phrase)throw new Error(`callEndReason must specify code, subCode and phrase. Invalid reason : ${Ne(e)}`)}function ca(e){oa(e,"MediaTypes passed cannot be null");const t=[],i=Jr.MEDIA_TYPES;for(const n of Object.keys(i))ha(e,i[n])&&t.push(i[n]);return t}function da(e,t){const i={};for(const n of Object.values(t)){const t=n.split("/");i[t[t.length-2]]=Zr(e,n)}return i}function ua(e,t){return e.length>=t.length&&e.indexOf(t,e.length-t.length)>-1}function ha(e,t){const i=t.toString().toLowerCase();return e.map((e=>e.toString().toLowerCase())).indexOf(i)>-1}function pa(e,t,i){return!e.hasOwnProperty(t)&&(e[t]=i,!0)}function ga(e,t){return!!e.hasOwnProperty(t)&&(delete e[t],!0)}function ma(e){let t=null;try{return t=JSON.parse(e),"object"==typeof t?t:null}catch(e){return null}}function fa(e,t){if(!e)return{telemetryEndSubCode:Jr.CALL_END_CODE.UNKNOWN_ERROR,error:Jr.CALL_END_UNKNOWN_ERROR};let i;if("object"==typeof e.response)i=e.response;else try{i=JSON.parse(e.response)}catch(e){}if(e.skypeTokenError)return{telemetryEndSubCode:Jr.CALL_END_CODE.SKYPE_TOKEN_ERROR,error:Jr.CALL_END_SKYPE_TOKEN_ERROR};if(e.tokenTimeoutError)return{telemetryEndSubCode:Jr.CALL_END_CODE.HTTP_OTHER_ERROR,error:Jr.CALL_END_TOKEN_TIMEOUT_ERROR};if(e.tokenError)return{telemetryEndSubCode:Jr.CALL_END_CODE.HTTP_OTHER_ERROR,error:Jr.CALL_END_TOKEN_ERROR};if(i&&(i.operationFailure||i.broadcastOperationFailure)){const e=i.operationFailure||i.broadcastOperationFailure;return{telemetryEndSubCode:e.code,error:e}}return i?.code?{telemetryEndSubCode:i.code,error:i}:isNaN(e.status)||e.status!==Jr.CALL_END_CODE.NOT_FOUND?!isNaN(e.status)&&e.status?{telemetryEndSubCode:e.status,error:{code:e.status,subCode:isNaN(e.response)?0:e.response,phrase:e.statusText,resultCategories:[Er]}}:!isNaN(e.response)&&e.response?{telemetryEndSubCode:0,error:{code:0,subCode:e.response,phrase:e.statusText,resultCategories:[Er]}}:{telemetryEndSubCode:Jr.CALL_END_CODE.NETWORK_ERROR,error:Jr.CALL_END_NETWORK_ERROR}:{telemetryEndSubCode:Jr.CALL_END_CODE.NOT_FOUND,error:Jr.RESOURCE_NOT_FOUND_ERROR}}function va(e,t){if(e&&!e.isEmpty()&&t){const i=e.get(Jr.HEADERS.ORIGINAL_MESSAGE_ID),n=e.get(Jr.HEADERS.MESSAGE_ID);if(n&&ha(t,n)||i&&ha(t,i))return!0;t.length>9&&t.shift(),t.push(i||n)}return!1}function Sa(e){const t="unknown";return e.headers?e.headers.get(Jr.HEADERS.ORIGINAL_MESSAGE_ID,t):t}function ya(e){try{return e.headers.get(Jr.HEADERS.ORIGINAL_MESSAGE_ID).replace("-","").substr(0,8)}catch(e){return na()}}function Ca(e){return e&&e.hasOwnPropertyCaseInsensitive(Jr.HEADERS.CONTENT_ENCODING)}function _a(e){return e&&Jr.KNOWN_PAYLOAD_ENCODINGS.hasOwnProperty(e.get(Jr.HEADERS.CONTENT_ENCODING).toUpperCase())}function Ea(e){const t=atob(e);return yr.inflate(t,{to:"string"})}function Ta(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)}}}function ba(e){let t=!1;try{if(t=e&&2===e.state(),navigator.onLine&&t)return 3;if(!navigator.onLine&&t)return 2;if(navigator.onLine&&!t)return 1}catch{}return 0}function Ia(e){return[Jr.HTTP_STATUS_CODES.UNKNOWN,Jr.HTTP_STATUS_CODES.UNAUTHORIZED,Jr.HTTP_STATUS_CODES.NETWORK_ERROR,Jr.HTTP_STATUS_CODES.OFFLINE,Jr.HTTP_STATUS_CODES.TIMEOUT,Jr.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,Jr.HTTP_STATUS_CODES.BAD_GATEWAY,Jr.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE,Jr.HTTP_STATUS_CODES.GATEWAY_TIMEOUT].indexOf(e)>=0}function wa(e,t){switch(e){case Jr.HEADERS.CAE_KEYWORD.toLowerCase():return 8;case Jr.HEADERS.AAD_KEYWORD.toLowerCase():return 4;case Jr.HEADERS.SKYPE_KEYWORD.toLowerCase():return 1;default:return t?.info("unexpected: unrecognized token type ${tokenType}"),null}}function Ra(e){switch(e){case 0:return"GET";case 1:return"POST";case 2:return"PUT";case 3:return"DELETE"}}function Aa(e,t,i,n,r=!1,a,s){s?.createChild("[utils.ts]");const o={verb:Ra(i),path:n.url},l=JSON.stringify(o),c=function(e){let t={};if(e){const i=Qr.getHeaderValue(e,Jr.HEADERS.AUTHENTICATE);i&&(t={authenticationHeaders:[i]})}return t}(a),d=function(e,t,i,n,r){if(!t)return 1;const{callingServiceSupportsAADTokens:a,callingServiceSupportsCAETokens:s,supportMissingTokenTypesInResponse:o,useSkypeTokenWhenNoAuthenticateHeader:l}=e,c=r?.authenticationHeaders;n?.info(`[getAuthHeadersTokenTypes] UnauthorizedResponse=${i} and authHeaders=${c}`);let d=null;if(!c&&i)l?(n?.info("[getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),d=1):(n?.info("[getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),d=Xr(e));else if(c||i){if(c&&i)for(const t of c){const i=ea(t);if(o&&0===i.length)n?.info("[getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),d=Xr(e);else for(const e of i){const t=wa(e.toLowerCase(),n);s&&8===t&&(d|=8),a&&4===t&&(d|=4),1===t&&(d|=1)}}}else n?.info("[getAuthHeadersTokenTypes] first time requesting token, request client supported token types"),d=Xr(e);return d}(e,t,r,s,c);return s?.info(`[getTokenMetadata] return token type=${d}, factoJson=${l}, headers=${c?.authenticationHeaders}`),{tokenType:d,factorsJson:l,requestMetadataJson:c,isUnauthorized:r}}function Pa(){return Math.floor(Date.now()/1e3)}function Ma(e){return 1e3*e}function ka(e){switch(e){case"none":return"None";case"teamPark":return"TeamPark";case"callPark":return"CallParkV2";case"serverHold":return"ServerHold";case"serverHoldV2":return"MusicOnHoldV2";case"sharedLinePark":return"SharedLinePark";case"sharedLineParkV2":return"SharedLineAppearanceV2";default:return"UnknownType"}}function Da(e){switch(e){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";default:throw"Invalid state type when converting PublishType to PublishStateType."}}function Oa(e){switch(e){case"raiseHands":return"raiseHands";case"ufd":return"ufd";case"attendeeModalitiesUnrestricted":return"attendeeModalitiesUnrestricted";case"attendeeAudioRestricted":return"attendeeAudioRestricted";case"attendeeVideoRestricted":return"attendeeVideoRestricted";case"attendeeVideoUnrestricted":return"attendeeVideoUnrestricted";case"spotlight":return"spotlight";case"weatherPerson":return"weatherPerson";case"sharingLayoutType":return"sharingLayoutType";case"manageBreakoutRooms":return"manageBreakoutRooms";case"togetherMode":return"togetherMode";case"consentToRecording":return"consentToRecording";case"denyConsentToRecording":return"denyConsentToRecording";case"clientMediaUfd":return"clientMediaUfd";case"serverMediaUfd":return"serverMediaUfd";default:throw"Invalid state type when converting PublishStateType to PublishType."}}var Na=class e{static isInLobby(e,t){for(const i of e)if(i.endpointId===t&&i.isLobby)return!0;return!1}static isParticipantServerMuted(e){for(const t of e)if(t.mediaStreams&&!t.mappedTo)for(const e of t.mediaStreams)if("audio"===e.type&&!0===e.serverMuted)return!0;return!1}static fromWireParticipant(t){return oa(t,"invalid wireParticipant"),sa(t.id,"participant must have valid Id"),new e({id:t.id,displayName:t.displayName,languageId:t.languageId,acceptedBy:t.acceptedBy})}static getPluginlessStateTypeFromWire(e){return Da(e)}static findOrCreateTypeState(e,t){let i=t.typeStates.findIndex((t=>t.type===e));if(-1===i){const n={participantStates:[],type:e};t.typeStates.push(n),i=t.typeStates.length-1}return i}static processPublishedStates(e,t){const i={typeStates:[]},n=e;return vr.forEach(n,(e=>{const n=this.findOrCreateTypeState(this.getPluginlessStateTypeFromWire(e.stateType),i),r={id:t,publishedState:{content:e.content,stateId:e.stateId,typeRank:e.typeRank}};i.typeStates[n].participantStates.push(r)})),i}static fromRosterEndpoints(e){let t=[],i=!1,n=!1,r=!1,a=!1;return t=Object.keys(e).map((t=>{let s,o,l=[],c=!1,d=0;if(e[t].call&&(i=!0,l=e[t].call.mediaStreams||null,d=e[t].call.serverMuteVersion||0,o=e[t].call.appliedInteractivityLevel||"unknown"),e[t].lobby&&(c=!0,n=!0,l=e[t].lobby.mediaStreams||null),e[t].broadcast?.sessionInformation&&(s=e[t].broadcast.sessionInformation.role||null),e[t].mappedParticipant&&(r=!0,l=e[t].mappedParticipant.mediaStreams||null),!e[t].capabilities&&e[t].endpointCapabilities){const i=e[t].endpointCapabilities;e[t].capabilities={implicitCallback:16&i?"enabled":"disabled",cloudAudioVideoConference:1&i?"enabled":"disabled",cloudScreenSharing:2&i?"enabled":"disabled",hostlessConference:4&i?"enabled":"disabled",autoJoinOnConflict:32&i?"enabled":"disabled",serverMuteUnmute:64&i?"enabled":"disabled",supportsCompressedServicePayload:128&i?"enabled":"disabled",cloudMerge:8&i?"enabled":"disabled"}}return a=a||!!e[t].streamLobby||!!e[t].stream,{endpointId:t,participantId:e[t].participantId||null,clientVersion:e[t].clientVersion||null,endpointMetadata:e[t].endpointMetadata||null,originalId:e[t].originalId||null,contentSharing:e[t].contentSharing||null,capabilities:e[t].capabilities||null,endpointType:e[t].endpointType||"default",deviceType:e[t].deviceType||void 0,clientEndpointCapabilities:e[t].clientEndpointCapabilities||void 0,mediaStreams:l,serverMuteVersion:d,broadcastMeetingRole:s,isLobby:c,endpointState:e[t].endpointState||null,publishedStates:e[t].publishedStates||null,callLinks:e[t].callLinks||null,appliedInteractivityLevel:o||"unknown",mappedTo:e[t].mappedTo||null,meetingGroupDetails:e[t].meetingGroupDetails,streamInformation:e[t].streamInformation,propertyBag:e[t].propertyBag,streamLobby:e[t].streamLobby,stream:e[t].stream}})),{endpointDetails:t,participantHasCallModality:i,participantIsInLobby:n,participantHasMappedEndpoint:r,participantHasStreamEndpoint:a}}static fromRoster(t,i=!1){oa(t,`invalid rosterParticipant ${JSON.stringify(t)}`),sa(t.details.id,"participant must have valid Id");const n=t.endpoints||{},r=this.fromRosterEndpoints(n),a=r.endpointDetails,s=r.participantHasCallModality,o=r.participantHasMappedEndpoint,l=r.participantHasStreamEndpoint;let c=r.participantIsInLobby;return s||c||o||i||l?(s&&(c=!1),new e({id:t.details.id,displayName:t.details.displayName,version:t.version||0,propertyBag:t.details.propertyBag||null,languageId:t.details.languageId,role:t.role||"",tenantId:t.details.tenantId||"",endpointDetails:a||[],acceptedBy:t.acceptedBy||"",isLobby:c,meetingRole:t.meetingRole,advancedMeetingRole:t.advancedMeetingRole,participantType:t.details.participantType,publishedStates:t.publishedStates||null,isIdentityMasked:t.details.isIdentityMasked,nonMaskedId:t.details.nonMaskedId||"",nonMaskedObjectId:t.details.nonMaskedObjectId||"",nonMaskedDisplayName:t.details.nonMaskedDisplayName||"",maskedIdSeqNumber:t.details.maskedIdSeqNumber||0,maskedId:t.details.maskedId||"",joinAsStreamingUser:t.joinAsStreamingUser,enableCaptcha:t.enableCaptcha})):null}static fromRosterSearchResults(e){oa(e,`invalid rosterParticipant ${JSON.stringify(e)}`),sa(e.details.id,"participant must have valid Id");const t=e.endpoints,{endpointDetails:i,participantHasCallModality:n,participantIsInLobby:r,participantHasMappedEndpoint:a,participantHasStreamEndpoint:s}=this.fromRosterEndpoints(t);let o=0;return n||s?o=3:r?o=10:a&&(o=3),{id:e.details.id,state:o,tenantId:e.details.tenantId||"",displayName:e.details.displayName,role:e.role||"",meetingRole:e.meetingRole,advancedMeetingRole:e.advancedMeetingRole,participantType:e.details.participantType,isServerMuted:this.isParticipantServerMuted(i),publishedStates:this.processPublishedStates(e.publishedStates,e.details.id),endpoints:i||[],isIdentityMasked:e.details.isIdentityMasked,nonMaskedId:e.details.nonMaskedId||"",nonMaskedDisplayName:e.details.nonMaskedDisplayName||"",nonMaskedObjectId:e.details.nonMaskedObjectId||"",maskedIdSeqNumber:e.details.maskedIdSeqNumber||0,maskedId:e.details.maskedId||"",joinAsStreamingUser:e.joinAsStreamingUser}}constructor(e){this.id=e.id,this.displayName=e.displayName||"",this.version=e.version,this.propertyBag=e.propertyBag,this.languageId=e.languageId||null,this.endpointDetails=e.endpointDetails||[],this.acceptedBy=e.acceptedBy,this.role=e.role,this.tenantId=e.tenantId,this.isLobby=e.isLobby,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.participantType=e.participantType,this.publishedStates=e.publishedStates,this.isIdentityMasked=e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,this.enableCaptcha=e.enableCaptcha}},La="HandleMediaAcknowledgement",xa="HandleMediaNegotiationFailure",Fa="HandleMediaAnswer",Ua="HandleMediaAnswerFailed",Ba="HandleMediaOffer",Va="RejectRenegotiation",Ha="HandleRetargetCompleted",$a="HandleMediaAnswerTimeout",Ga="HandleMediaAcknowledgementTimeout",ja="AcceptRenegotiation",za="StartRenegotiation",Wa="MediaFsmStateChanged",qa="AddModalityTimeout",Ka="AddParticipant",Ja="AddParticipantTimeout",Ya="AddParticipantWithReplaces",Qa="AddParticipantWithReplacesTimeout",Za="AddParticipantsAndModality",Xa="AdmitParticipant",es="AdmitParticipantTimeout",ts="Admit",is="AdmitTimeout",ns="AdmitFailure",rs="AdmitSuccess",as="CallMeBack",ss="CallMeBackTimeout",os="RemoveParticipant",ls="RemoveParticipantOthers",cs="RemoveParticipantSpecified",ds="RemoveParticipantTimeout",us="HandleAddParticipantSuccess",hs="HandleAddParticipantFailure",ps="HandleAdmitParticipantSuccess",gs="HandleAdmitParticipantFailure",ms="HandleAddParticipantModalityFailure",fs="HandleRemoveParticipantSuccess",vs="HandleRemoveParticipantFailure",Ss="HandleRosterUpdate",ys="HandleRosterUpdateFail",Cs="HandleConversationUpdate",_s="HandleLocalParticipantUpdate",Es="SetSubject",Ts="SetJoinedFrom",bs="SetDeviceType",Is="GetEmergencyContent",ws="SetMultiparty",Rs="SetGroupId",As="SetThreadId",Ps="SetCallOptions",Ms="SetTransferContext",ks="StartCall",Ds="JoinCall",Os="JoinConversationWithoutCallModality",Ns="HandleIncomingCall",Ls="EndCall",xs="EndWithBeacon",Fs="ConflictedCall",Us="SetProvisionalAnswer",Bs="SetProvisionalAnswerFailed",Vs="AcceptCall",Hs="AcceptCallFailed",$s="HandleCallAcceptanceAck",Gs="HandleCallAcceptance",js="HandleCallAcceptanceSync",zs="HandleCallAcceptanceFailed",Ws="HandleCallEstablishmentTimeout",qs="HandleCallEnd",Ks="HandleCallProgress",Js="TrouterUrlChanged",Ys="TrouterStateChanged",Qs="TrouterUrlChangedToInvalid",Zs="TrouterUrlUpdateFailed",Xs="AddContentSharingModality",eo="AcceptedBeforeRinging",to="DeleteContentSharing",io="TakeControlContentSharing",no="UpdateSessionStateContentSharing",ro="JoinContentSharing",ao="UpdateParticipantStateContentSharing",so="HandleContentSharingUpdate",oo="HandleContentSharingEnd",lo="ContentSharingStartFromRoster",co="ContentSharingEndFromRoster",uo="HandleAddModalitySuccess",ho="HandleAddModalityFailure",po="AddBroadcastModality",go="UpdateBroadcastDetails",mo="WaitingForAddBroadcastModalityCompletion",fo="Mute",vo="NudgeParticipantTimeout",So="Unmute",yo="UnmuteTimeout",Co="HandleUnmuteConfirm",_o="ApproveUnmute",Eo="RejectUnmute",To="HandleControlVideoStreaming",bo="HandleDominantSpeakerChangedCount",Io="HandleCsrcInfo",wo="SendWebRtcMediaNotification",Ro="TransferCall",Ao="ParkCall",Po="CallRedirect",Mo="CallRedirectRequestFailed",ko="TransferCompletionFailed",Do="TransferRequestReceived",Oo="HandleParkRequested",No="DuplicateMessageIgnored",Lo="CorrelationIdUpdated",xo="UnkownMessageType",Fo="FailedToHandleMessage",Uo="ConnectivityChanged",Bo="TrouterDecodePayloadFailure",Vo="UpdateEndpointState",Ho="BrokerDecodePayloadFailure",$o="BrokerSubscriptionTimeout",Go="BrokerSubscriptionSuccessful",jo="BrokerSubscriptionFailed",zo="FailedToHandleTrouterMessage",Wo="FailedToHandleBrokerMessage",qo="BrokerDisabledSubscribeUrlPresent",Ko="Connected",Jo="InLobby",Yo="Staging",Qo="MessageMissingBody",Zo="BroadcastStateChanged",Xo="HandleCallNotification",el="HandleIncomingCallReplacement",tl="HandlePstnBalanceUpdate",il="IgnoreOldRoster",nl="HandleMediaAck",rl="HandleMediaProvisionalAck",al="UpdateCallStatus",sl="SendAttach",ol="RequestNewOffer",ll="HandleNewOffer",cl="UpdateConversationLinks",dl="UpdateConversationLinksSuccess",ul="UpdateConversationLinksFailed",hl="ProcessInitialOffer",pl="SendProgress",gl="SendProgressFailed",ml="ProcessCallAcceptance",fl="AcceptanceUserInLobby",vl="RejectIncomingCall",Sl="SendKeepAlive",yl="SendKeepAliveFailed",Cl="StartAudio",_l="StopAudio",El="UpdateMeetingRole",Tl="EnablingPreheat",bl="DisablingPreheat",Il="PreheatDisabled",wl="TransferRequestSent",Rl="CallRedirectRequestSent",Al="TransferRequestFailed",Pl="SendAcceptTransfer",Ml="SendAcceptTransferFail",kl="WaitingForTransferCompletion",Dl="WaitingForTransferCompletionFail",Ol="WaitingForTransferAcceptanceFail",Nl="WaitingForTransferAcceptance",Ll="TransferCompleted",xl="SendCompleteTransfer",Fl="SendCompleteTransferFailed",Ul="PickupCodeSet",Bl="AddParticipantWithPickupCode",Vl="AddParticipantWithPickupCodeTimeout",Hl="PublishState",$l="PublishStateFailure",Gl="RemoveState",jl="RemoveStateFailure",zl="UpdateMeetingSettings",Wl="UpdateMeetingSettingsFailure",ql="UpdateEndpointMetadataSuccess",Kl="UpdateEndpointMetadataFailure",Jl="SearchParticipants",Yl="GetAllParticipants",Ql="SearchParticipantsFailure",Zl="GetAllParticipantsFailure",Xl="ParkRequestFailed",ec="WaitingForParkCompletion",tc="WaitingForParkCompletionTimeout",ic="ParkCompleted",nc="ParkFailed",rc="UnparkRequestFailed",ac="WaitingForUnparkCompletion",sc="WaitingForUnparkCompletionTimeout",oc="UnparkCompleted",lc="UnparkFailed",cc="UpdateMeetingLiveState",dc="WaitingForUpdateMeetingLiveStateCompletion",uc="UpdateMeetingLiveStateRequestFailed",hc="UpdateMeetingLiveStateResponseFailure",pc="UpdateMeetingLiveStateResponseSuccess",gc="UpdateMeetingGroups",mc="UpdateParticipantInterpretationState",fc="UpdateParticipantsProperties",vc="JoinMeetingGroup",Sc="LeaveMeetingGroup",yc="incomingProxiedMessages",Cc="WaitingForUpdateMeetingGroupsCompletion",_c="UpdateMeetingGroupsRequestFailed",Ec="UpdateMeetingGroupsRequestFailure",Tc="UpdateMeetingGroupsResponseSuccess",bc="SetMeetingLayout",Ic="WaitingForSetMeetingLayoutCompletion",wc="SetMeetingLayoutRequestFailed",Rc="SetMeetingLayoutResponseFailure",Ac="SetMeetingLayoutResponseSuccess",Pc="UpdateParticipantInterpretationStateTimeout",Mc="UpdateParticipantInterpretationStateResponseFailed",kc="UpdateParticipantInterpretationStateResponseCompleted",Dc="UpdateParticipantsPropertiesTimeout",Oc="UpdateParticipantsPropertiesResponseFailed",Nc="UpdateParticipantsPropertiesResponseCompleted",Lc="WaitingForJoinMeetingGroupCompletion",xc="JoinMeetingGroupRequestFailed",Fc="JoinMeetingGroupRequestFailed",Uc="JoinMeetingGroupRequestCompleted",Bc="WaitingForLeaveMeetingGroupCompletion",Vc="LeaveMeetingGroupRequestFailed",Hc="LeaveMeetingGroupRequestFailed",$c="LeaveMeetingGroupRequestCompleted",Gc="SubscribeUrlFound",jc="SubscribeUrlMissing",zc="SendMessageCompletion",Wc="SendMessageTimeout",qc="DiablePreheatSucceeded",Kc="AsyncDisablePreheatSucceeded",Jc="DiablePreheatFailed",Yc="AsyncDiablePreheatFailed",Qc="DisablePreheatResponseReceived",Zc="StreamInformationReceived",Xc="UpdateMediaDescriptions",ed="UpdateMediaDescriptionsFailed",td="NudgeToJoinAsRealtime",id="UpdateMeetingStates",nd="WaitingForUpdateMeetingStatesCompletion",rd="UpdateMeetingStatesResponseSuccess",ad="UpdateMeetingStatesResponseFailure",sd={SEND_MEDIA_ANSWER:{name:"SendMediaAnswer",controller:0},START_RENEGOTIATION:{name:"StartRenegotiation",controller:0},SEND_MEDIA_ACKNOWLEDGEMENT:{name:"SendMediaAcknowledgement",controller:0},SEND_MEDIA_REJECTION:{name:"SendMediaRejection",controller:0},ADD_PARTICIPANT:{name:"AddParticipant",controller:1},ADD_PARTICIPANT_WITH_REPLACES:{name:"AddParticipantWithReplaces",controller:1},NUDGE_PARTICIPANT:{name:"NudgeParticipant",controller:1},REMOVE_PARTICIPANT_NONE:{name:"RemoveParticipant",controller:1},REMOVE_PARTICIPANT_OTHERS:{name:"RemoveParticipantOthers",controller:1},REMOVE_PARTICIPANT_SPECIFIED:{name:"RemoveParticipantSpecified",controller:1},ADMIT_PARTICIPANT:{name:"AdmitParticipant",controller:1},ADMIT:{name:"Admit",controller:1},BROKER_SUBSCRIBE:{name:"BrokerSubscribe",controller:2},CALL_ME_BACK:{name:"CallMeBack",controller:1},SEND_ACCEPTANCE:{name:"SendAcceptance",controller:0},SEND_ACCEPTANCE_ACKNOWLEDGEMENT:{name:"SendAcceptanceAcknowledgement",controller:0},END_CALL:{name:"EndCall",controller:1},CANCEL_CALL:{name:"CancelCall",controller:1},REJECT_CALL:{name:"RejectCall",controller:0},JOIN_CONVERSATION:{name:"JoinConversation",controller:1},JOIN_CONVERSATION_WITHOUT_CALL_MODALITY:{name:"JoinConversationWithoutCallModality",controller:1},LEAVE_CONVERSATION:{name:"LeaveConversation",controller:1},DELETE_CONVERSATION:{name:"DeleteConversation",controller:1},START_CALL:{name:"StartCall",controller:1},PLACE_NUDGE_CALL:{name:"PlaceNudgeCall",controller:5},UPDATE_CONVERSATION_LINKS:{name:"UpdateConversationLinks",controller:1},SEND_CONVERSATION_KEEP_ALIVE:{name:"SendConversationKeepAlive",controller:1},SEND_CALL_ATTACH:{name:"SendCallAttach",controller:0},SEND_CALL_PROGRESS:{name:"SendCallProgress",controller:0},SEND_KEEP_ALIVE:{name:"SendKeepAlive",controller:0},ADD_CONTENT_SHARING_MODALITY:{name:"AddContentSharingModality",controller:1},DELETE_CONTENT_SHARING:{name:"DeleteContentSharing",controller:3},TAKE_CONTROL_CONTENT_SHARING:{name:"TakeControlContentSharing",controller:3},UPDATE_SESSION_STATE_CONTENT_SHARING:{name:"UpdateSessionStateContentSharing",controller:3},JOIN_CONTENT_SHARING:{name:"JoinContentSharing",controller:3},UPDATE_PARTICIPANT_STATE_CONTENT_SHARING:{name:"UpdateParticipantStateContentSharing",controller:3},UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS:{name:"UpdateContentSharingNotificationLinks",controller:3},MUTE_ALL:{name:"MuteAll",controller:1},MUTE_ALL_SYNC:{name:"MuteAllSync",controller:1},MUTE_SPECIFIED:{name:"MuteSpecified",controller:1},MUTE_SPECIFIED_SYNC:{name:"MuteSpecifiedSync",controller:1},MUTE_MYSELF:{name:"MuteMyself",controller:1},UNMUTE:{name:"Unmute",controller:1},UNMUTE_SYNC:{name:"UnmuteMyselfSync",controller:1},SEND_CONTROL_VIDEO_STREAMING:{name:"SendControlVideoStreaming",controller:0},SEND_APPLY_CHANNEL_PARAMETERS:{name:"SendApplyChannelParameters",controller:0},APPROVE_UNMUTE:{name:"ApproveUnmute",controller:5},REJECT_UNMUTE:{name:"RejectUnmute",controller:5},SEND_CALL_REDIRECT_REQUEST:{name:"SendCallRedirectRequest",controller:0},SEND_TRANSFER_REQUEST:{name:"SendTransferRequest",controller:0},SEND_PARK_REQUEST:{name:"SendParkRequest",controller:0},SEND_SHARED_LINE_PARK_REQUEST:{name:"SharedLinePark",controller:0},SEND_SERVER_HOLD_REQUEST:{name:"ServerHoldRequest",controller:0},PARK_REQUEST:{name:"ParkRequest",controller:0},SEND_UNPARK_REQUEST:{name:"UnparkRequest",controller:0},TRANSFER_ACCEPTANCE:{name:"TransferAcceptance",controller:0},TRANSFER_COMPLETION:{name:"TransferCompletion",controller:0},TRANSFER_COMPLETION_FAILED:{name:"TransferCompletionFailed",controller:0},UPDATE_ENDPOINT_STATE:{name:"UpdateEndpointState",controller:1},DISABLE_PREHEAT:{name:"DisablePreheat",controller:5},REQUEST_NEW_OFFER:{name:"RequestNewOffer",controller:0},UPDATE_ENDPOINT_METADATA:{name:"UpdateEndpointMetadata",controller:1},UPDATE_MEETING_ROLE_ATTENDEE:{name:"UpdateMeetingRoleToAttendee",controller:1},UPDATE_MEETING_ROLE_PRESENTER:{name:"UpdateMeetingRoleToPresenter",controller:1},UPDATE_MEETING_ROLE_ORGANIZER:{name:"UpdateMeetingRoleToOrganizer",controller:1},ADD_PARTICIPANT_WITH_PICKUP_CODE:{name:"AddParticipantWithPickupCode",controller:1},PUBLISH_STATE:{name:"PublishState",controller:1},REMOVE_STATE:{name:"RemoveState",controller:1},UPDATE_MEETING_SETTINGS:{name:"UpdateMeetingSettings",controller:1},ADD_PARTICIPANTS_AND_MODALITY:{name:"AddParticipantsAndModality",controller:1},ADD_BROADCAST_MODALITY:{name:"AddBroadcastModality",controller:1},SEARCH_PARTICIPANTS:{name:"SearchParticipants",controller:1},GET_ALL_PARTICIPANTS:{name:"GetAllParticipants",controller:1},UPDATE_MEETING_LIVE_STATE:{name:"UpdateMeetingLiveState",controller:1},UPDATE_MEETING_GROUPS:{name:"UpdateMeetingGroups",controller:1},SET_MEETING_LAYOUT:{name:"SetMeetingLayout",controller:1},UPDATE_PARTICIPANT_INTERPRETATION_STATE:{name:"UpdateParticipantInterpretationState",controller:1},JOIN_MEETING_GROUP:{name:"JoinMeetingGroup",controller:1},LEAVE_MEETING_GROUP:{name:"LeaveMeetingGroup",controller:1},SEND_PROXIED_MESSAGE:{name:"SendProxiedMessage",controller:1},UPDATE_PARTICIPANTS_PROPERTIES:{name:"UpdateParticipantsProperties",controller:1},UPDATE_MEDIA_DESCRIPTIONS:{name:"UpdateMediaDescriptions",controller:0},UPDATE_MEETING_STATES:{name:"UpdateMeetingStates",controller:1}},od={TROUTER:"Trouter",BROKER:"Broker",UDP:"UDP",LOCAL:"Local"},ld={NGC_SOURCE:"SkypeConcore"},cd={CONVERSATION_CALL_MODALITY:"skypecosi_concore_web_csa_conversation_callmodality",CONVERSATION_CONTENT_SHARING:"skypecosi_concore_web_csa_conversation_contentsharing",CONVERSATION_HTTP_REQUEST:"skypecosi_concore_web_csa_conversation_httprequest",CONVERSATION_TOKEN:"skypecosi_concore_web_csa_conversation_token"},dd={DATA_VERSION:"DataVersion",DIRECTION:"Direction",CONTENT_SHARING_DIRECTION:"ContentSharingDirection",CONNECTED_DURATION_IN_MS:"ConnectedDurationInMsecs",PREHEATED_CALL_SETUP_DURATION_IN_S:"PreheatedCallSetupDurationInSeconds",CALL_CANCELATION_DURATION_IN_S:"CallCancelationDurationInSeconds",IS_PREHEATED:"IsPreheated",TIME_TO_RING_IN_MS:"TimeToRingInMsecs",CALL_TERMINATING_END:"CallTerminatingEnd",NETWORK_REQUESTS_PENDING:"NetworkRequestsPending",NETWORK_REQUESTS_COMPLETED:"NetworkRequestsCompleted",LOCAL_OPERATIONS_PERFORMED:"LocalOperationsPerformed",TROUTER_WAIT_OPERATIONS:"TrouterWaitOperations",CALL_START_TIME:"CallStartTime",CALL_END_TIME:"CallEndTime",IS_GROUP_CALL:"IsGroupCall",IS_HOSTLESS_CALL:"IsHostLessCall",IS_CAST_CALL:"IsCastCall",IS_HUDDLE_GROUP_CALL:"IsHuddleGroupCall",IS_MEETUP_CALL:"IsMeetupCall",IS_ON_BEHALF_OF_CALL:"IsOnBehalfOfCall",IS_SDP_IN_CALL_NOTIFICATION:"SdpInCallNotification",CALL_END_CODE:"Code",CALL_END_SUB_CODE:"SubCode",CALL_PHRASE:"Phrase",CALL_END_RESULT_CATEGORIES:"ResultCategories",CALL_END_CAUSE_ID:"CauseId",CONTENT_SHARING_END_CODE:"ContentSharingEndReasonServiceCode",CONTENT_SHARING_END_SUB_CODE:"ContentSharingEndReasonServiceSubCode",CONVERSATION_SERVICE_URL:"ConversationServiceUrl",CONTENT_SHARING_SERVICE_URL:"ContentSharingServiceUrl",MEETING_INFO:"MeetingInfo",JOINED_FROM:"JoinedFrom",RESULT_VALUE:"ResultValue",RESULT_DETAIL:"ResultDetail",RESULT_CAUSE_ID:"ResultCauseId",RESULT_CODE:"ResultCode",LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS:"LocalOfferAnswerGenerationTimestamps",SELF_PARTICIPANT_ROLE:"SelfParticipantRole",SCENARIO:"Scenario",CALLER_TYPE:"Caller_Type",CALLEE_TYPE:"Callee_Type",CALL_TYPE:"Call_Type",TEST_CONTEXT_ID:"Test_Context_Id",OUTGOING_MODALITIES:"Outgoing_Modalities",INCOMING_MODALITIES:"Incoming_Modalities",OFFERED_MODALITIES:"CallOfferredModalities",ANSWERED_MODALITIES:"CallAnsweredModalities",VBSS_OPERATIONS:"VBSS_Operations",CHANGING_CORRELATION_ID_NEW_ID:"ChangingCorrelationId_NewId",CHANGING_CORRELATION_ID_OLD_ID:"ChangingCorrelationId_OldId",MESSAGING_CHANNEL:"MessagingChannel",EVENT_TIMESTAMP_BAG:"EventTimestampBag",ROSTER_UPDATES_BAG:"RosterUpdatesBag",NETWORK_REQUESTS_BAG:"NetworkRequestBag",CLIENT_INFORMATION:"ClientInformation",ECS_ETAG:"EcsEtag",APPLICATION_TYPE:"ApplicationType",RING:"Ring",TENANT_ID:"TenantId",USER_HEX_CID:"UserHexCID",ACS_RESOURCE_ID:"AcsResourceId",REGION:"Region",PARTITION:"Partition",CALL_END_CLIENT_SUB_CODE:"CallEventCallEndClientSubCode",CALL_END_CLIENT_PHRASE:"CallEventCallEndClientPhrase",MEETING_CODE:"MeetingCode",MEETING_URL:"MeetingJoinUrl",BROADCAST_MEETING_ROLE:"BroadcastMeetingRole",MEETING_ROLE:"MeetingRole",ADVANCED_MEETING_ROLE:"AdvancedMeetingRole",PARTICIPANT_TYPE:"ParticipantType",AUDIO_ONLY_WATERMARK:"ClientSupportsAudioOnlyWatermark",CLIENT_SUPPORT_WATERMARK:"ClientSupportsWatermark",TARGET_APPLICATION_TYPE:"TargetApplicationType",IS_REINVITELESS:"IsReinviteless",CLIENT_TYPE:"ClientType",CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE:"ClientSupportsPreventScreenCapture"},ud={TROUTER:"Trouter",BROKER:"Broker"},hd="JsCsaConfig",pd={BROKER_OUTGOING_ENABLED:"BrokerOutgoingEnabled",BROKER_INCOMING_ENABLED:"BrokerIncomingEnabled",BROKER_REQUEST_BATCHING_ENABLED:"BrokerRequestBatchingEnabled",BROKER_EXCLUSIVELY_ENABLED:"BrokerExclusivelyEnabled",SUPPORTS_COMPRESSED_PAYLOAD:"SupportsCompressedPayload",SYNC_TROUTER_RESPONSE:"SyncTrouterResponse",SERVER_MUTE_UNMUTE:"serverMuteUnmute",HANDLE_OFFER_FROM_NOTIFICATION:"handleMediaOfferFromPushNotification",HANDLE_NEW_OFFER_REQUEST:"handleNewOfferRequest",SEND_PROGRESS_FROM_CC:"sendProgressFromCC",INTERNAL_HTTP_DISPATCHER:"internalHttpDispatcher",ENABLE_TOKEN_CACHE:"enableTokenCache",ENABLE_TOKEN_PREFETCH:"enableTokenPrefetch",REQUEST_HEDGING:"requestHedging",SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION:"supportMediaRetargetWhileIncomingRenegotiation",ENABLE_ERROR_CODE_IMPROVEMENTS_FOR_NETWORK_FAILURES:"enableErrorCodeImprovementsForNetworkFailures",ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL:"enableCallEstablishmentTimeoutsForStartJoinCall",ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API:"enableTokenCacheForGenericTokenAPI",ENABLE_LONG_OUTGOING_1TO1_SETUP:"enableLongOutgoing1To1SetupTimeoutForWeb"},gd={CORRELATION_ID:"CorrelationId",SHARED_CORRELATION_ID:"SharedCorrelationId",SIGNALING_SESSION_ID:"SignalingSessionId",GROUP_ID:"GroupId",THREAD_ID:"ThreadId",TEAMS_MESSAGEID:"TeamsMessageId",TEAMS_MEETINGINFO:"TeamsMeetingInfo",ENDPOINT_ID:"EndpointId",PARTICIPANT_ID:"ParticipantId",DATA_VERSION:"DataVersion",CONTENT_SHARING_ID:"ContentSharingSessionId",CONTENT_SHARING_CORRELATION_ID:"ContentSharingCorrelationId"},md={LOCAL:"Local",REMOTE:"Remote"},fd={SUCCESS:"Success",FAILURE:"Failure"},vd={INCOMING:"Incoming",OUTGOING:"Outgoing"},Sd={CALLER:"caller",CALLEE:"callee",JOIN:"join",JOIN_FOR_ROSTER_ONLY:"joinForRosterOnly",PREHEAT:"preheat"},yd={START:"Start",STOP:"Stop",REJECTED:"Rejected",REMOTE_START:"RemoteStart",TIMEOUT:"Timeout",CALL_END:"CallEnd"},Cd={STARTED:"Started",ENDED:"Ended",FAILED:"Failed"},_d={TOKEN_TELEMETRY:"TokenTelemetry"};function Ed(e){e.cloudScreenSharingFlag="disabled"===e.cloudScreenSharingFlag?e.cloudScreenSharingFlag:"enabled",e.isWebRtcEnabled="undefined"==typeof RTCIceGatherer,e.shouldServiceSendNGCUpgradeMessages=Td(e.shouldServiceSendNGCUpgradeMessages,!0),e.isGVCOutgoingEnabled=Td(e.isGVCOutgoingEnabled,!0),e.supportsCompressedServicePayload=Td(e.supportsCompressedServicePayload,!0),e.supportsSynchronousTrouterResponse=Td(e.supportsSynchronousTrouterResponse,!0),e.supportsHostlessGroupCalls=Td(e.supportsHostlessGroupCalls,!0),e.doHostlessCalling=Td(e.doHostlessCalling,!1),e.brokerExclusively=Td(e.brokerExclusively,!1),e.brokerEnabledOutgoing=Td(e.brokerEnabledOutgoing,!0),e.brokerEnabledIncoming=Td(e.brokerEnabledIncoming,!0),e.brokerRequestBatching=Td(e.brokerRequestBatching,!0),e.handleMediaOfferFromPushNotification=Td(e.handleMediaOfferFromPushNotification,!0),e.handleNewOfferRequest=Td(e.handleNewOfferRequest,!1),e.autoJoinOnConflict=Td(e.autoJoinOnConflict,!0),e.endConflictedCall=Td(e.endConflictedCall,!1),e.autoResolveConflictedCall=Td(e.autoResolveConflictedCall,!1),e.shouldServiceSendCallEventMessages=Td(e.shouldServiceSendCallEventMessages,!1),e.forceTrouterReconnectOnNetworkOnline=Td(e.forceTrouterReconnectOnNetworkOnline,!0),e.attemptHttpRequestWithCachedSkypetoken=Td(e.attemptHttpRequestWithCachedSkypetoken,!0),e.useInternalHttpDispatcher=Td(e.useInternalHttpDispatcher,!1),e.enableTokenCache=Td(e.enableTokenCache,!1),e.enableTokenPrefetch=Td(e.enableTokenPrefetch,!1),e.hedgeDelayMs=Td(e.hedgeDelayMs,4e3),e.hedgeMaxParallelAttempts=Td(e.hedgeMaxParallelAttempts,3),e.useInternalHttpDispatcher&&(e.httpRequestDispatcher=new Ve(e.logger)),e.enableQuickSendAcceptanceAck=Td(e.enableQuickSendAcceptanceAck,!1),e.supportMediaRetargetWhileIncomingRenegotiation=Td(e.supportMediaRetargetWhileIncomingRenegotiation,!1),e.callingServiceSupportsAADTokens=Td(e.callingServiceSupportsAADTokens,!1),e.callingServiceSupportsCAETokens=Td(e.callingServiceSupportsCAETokens,!1),e.aadTokenExpirationTimeInSeconds=Td(e.aadTokenExpirationTimeInSeconds,3600),e.caeTokenExpirationTimeInSeconds=Td(e.caeTokenExpirationTimeInSeconds,86400),e.disableTokenMigrationHeader=Td(e.disableTokenMigrationHeader,!1),e.enablePublishTokenTelemetry=Td(e.enablePublishTokenTelemetry,!1),e.forceClearExpiredTokens=Td(e.forceClearExpiredTokens,!1),e.enableRefreshToken=Td(e.enableRefreshToken,!0),e.refreshTimeBeforeTokenTimeoutInSeconds=Td(e.refreshTimeBeforeTokenTimeoutInSeconds,30),e.enableCallEstablishmentTimeoutsForStartJoinCall=Td(e.enableCallEstablishmentTimeoutsForStartJoinCall,!1),e.csaTimeoutConfiguration=function(e,t){return(t||e)&&{...t,...e}}(e.csaTimeoutConfiguration,{conversationKeepAliveTimeoutSec:2700,promotionUnmuteTimeoutSec:1e4}),e.reportPreviousErrorsForTimeout=Td(e.reportPreviousErrorsForTimeout,!1),e.callingTokenLogicalUrl=Td(e.callingTokenLogicalUrl,"https://calling.teams.microsoft.com"),e.enableAsyncDisablePreheat=Td(e.enableAsyncDisablePreheat,!1),e.forceLowercaseHttpHeaders=Td(e.forceLowercaseHttpHeaders,!1),e.enableResolveScreenSharingWhenNegotiationComplete=Td(e.enableResolveScreenSharingWhenNegotiationComplete,!1),e.maxReinvitelessMediaForVideoForWeb=Td(e.maxReinvitelessMediaForVideoForWeb,0),e.maxReinvitelessMediaForVBSSForWeb=Td(e.maxReinvitelessMediaForVBSSForWeb,0),e.enableRefreshTokenRetry=Td(e.enableRefreshTokenRetry,!0),e.enableRefreshTokenRetryInSeconds=Td(e.enableRefreshTokenRetryInSeconds,60),e.enableConversationTypeUpdateOnCallEnd=Td(e.enableConversationTypeUpdateOnCallEnd,!1),e.supportMissingTokenTypesInResponse=Td(e.supportMissingTokenTypesInResponse,!0),e.useSkypeTokenWhenNoAuthenticateHeader=Td(e.useSkypeTokenWhenNoAuthenticateHeader,!1),e.enableAutoPromotion=Td(e.enableAutoPromotion,!1),e.enableBatchedSendMessageStatus=Td(e.enableBatchedSendMessageStatus,!1),e.enableBatchedReceiveMessage=Td(e.enableBatchedReceiveMessage,!1),e.enableAddParticipantEnhancements=Td(e.enableAddParticipantEnhancements,!1),e.enableTokenCacheForGenericTokenAPI=Td(e.enableTokenCacheForGenericTokenAPI,!1),e.disableRealTimeModeFromRoster=Td(e.disableRealTimeModeFromRoster,!0),e.enableLongOutgoing1To1SetupTimeoutForWeb=Td(e.enableLongOutgoing1To1SetupTimeoutForWeb,!1)}function Td(e,t){return null==e?t:e}var bd=class{constructor(){this.skypeTokenContext={},this.aadTokenContext={},this.caeTokenContext={}}getTokenContext(e){return 4===e?this.aadTokenContext:8===e?this.caeTokenContext:1===e?this.skypeTokenContext:void 0}getTokenExpiry(e,t){return 4===e?this.aadTokenContext?.expiryTime:8===e?this.caeTokenContext?.expiryTime:1===e?this.skypeTokenContext?.expiryTime:(t.info("[getTokenExpiry] unrecognized token type, return Number.MAX_VALUE"),Number.MAX_VALUE)}getToken(e,t,i,n){return 8&e&&this.caeTokenContext?.token&&this.caeTokenContext.token!==n?{token:this.caeTokenContext.token,tokenType:8}:4&e&&this.aadTokenContext?.token&&this.aadTokenContext.token!==n?{token:this.aadTokenContext.token,tokenType:4}:1&e&&this.skypeTokenContext?.token&&this.skypeTokenContext.token!==n?{token:this.skypeTokenContext.token,tokenType:1}:(i.info("[getToken] no cached token found of token type: ${tokenType}"),null)}setToken(e,t,i,n){switch(e){case 4:this.aadTokenContext.factorsJson=i,this.aadTokenContext.tokenType=e,this.aadTokenContext.token=t,this.aadTokenContext.expiryTime=n;break;case 1:this.skypeTokenContext.factorsJson=i,this.skypeTokenContext.tokenType=e,this.skypeTokenContext.token=t,this.skypeTokenContext.expiryTime=n;break;case 8:this.caeTokenContext.factorsJson=i,this.caeTokenContext.tokenType=e,this.caeTokenContext.token=t,this.caeTokenContext.expiryTime=n;break;default:throw new Error(`Invalid tokenType ${e}`)}}clearExpiredTokens(e){const t=Math.round(Date.now()/1e3);this.caeTokenContext?.expiryTime<=t&&(this.resetToken(8),e?.info("[cacheTokenManager] reset expired cae token")),this.aadTokenContext?.expiryTime<=t&&(this.resetToken(4),e?.info("[cacheTokenManager] reset expired aad token")),this.skypeTokenContext?.expiryTime<=t&&(this.resetToken(1),e?.info("[cacheTokenManager] reset expired skype token"))}resetToken(e){8===e?this.caeTokenContext={}:4===e?this.aadTokenContext={}:1===e&&(this.skypeTokenContext={})}},Id=class{constructor(e){this.timers={},this.startTimer=(e,t,i,n)=>{this.logger.info(`startTimer called for :  ${e}`);const r=window.setTimeout(t,1e3*i),a=n?`${e}${n}`:e;this.timers[a]=r},this.stopTimer=(e,t)=>{this.logger.info(`stopTimer called for : ${e}`);const i=t?`${e}${t}`:e;this.timers.hasOwnProperty(i)&&(clearTimeout(this.timers[i]),delete this.timers[i])},this.dispose=()=>{this.logger.info("timeoutManager :: dispose"),Object.keys(this.timers).forEach((e=>{this.stopTimer(e)}))},this.logger=e}},wd=class{constructor(e,t,i,n){this.tokenProvider=t,this.tokenCachingEnabled=!1,this.enableTokenCacheForGenericTokenAPI=!1,this.cachedToken="",this.lastTokenType=1,this.lastToken="",this.clientSupportsGenericTokenAPI=!1,this.stopTimerFlag=!1,this.tokensPromiseMap={},this.logger=e.createChild("TokenManager"),i&&this.updateTokenSettings(i),this.cacheTimers=new Id(e),this.cacheTokenManager=new bd,this.telemetryManager=n,this.nextRefreshTimePointInSeconds=Number.MAX_VALUE}deletePromisesByTriggeredByRefresh(e,t){if(this.tokensPromiseMap[e]){const i=this.tokensPromiseMap[e];for(let n=i.length-1;n>=0;n--)i[n]?.tokenRequestOptions.triggeredByRefresh===t&&this.tokensPromiseMap[e].splice(n,1)}}startTokenRefreshTimer(e){const t="startTokenRefreshTimer";if(!this.enableRefreshToken)return void this.logger.info("[startTokenRefreshTimer] token refresh is disabled");if(this.stopTimerFlag)return this.logger.info("[startTokenRefreshTimer] stopTimerFlag=true so cancel timer"),void this.cacheTimers.dispose();this.logger.info(`[startTokenRefreshTimer] starting token refresh timer timeToStartInMilliseconds=${e}`);const i=Pa(),n=function(e){return e/1e3}(e),r=i+n;this.nextRefreshTimePointInSeconds===Number.MAX_VALUE||this.nextRefreshTimePointInSeconds<i||r<this.nextRefreshTimePointInSeconds?(this.logger.info("[startTokenRefreshTimer] cancelling current refresh timer to create new one with shorter time"),this.cacheTimers.stopTimer(t),this.nextRefreshTimePointInSeconds=r,this.logger.info(`[startTokenRefreshTimer] start new timer with timeout=${n} at time=${i}`),this.cacheTimers.startTimer(t,(()=>{this.nextRefreshTimePointInSeconds=Number.MAX_VALUE,this.refreshToken()}),n)):this.logger.info("[startTokenRefreshTimer] no need to set a new refresh timer")}async refreshTokenWithContext(e){const t={triggeredByRefresh:!0},i=ra(),n={causeId:i},r=Date.now();let a,s,o,l=2;this.logger.info(`[${i}][refreshTokenWithContext] refreshing token tokenType=${e.tokenType} factorsJson=${e.factorsJson}`);try{const t=this.onTokenRequired({factorsJson:e.factorsJson,tokenType:e.tokenType,requestMetadataJson:n,invalidToken:void 0,isUnauthorized:void 0,triggeredByRefresh:!0}),r=await this.timeoutPromiseRace(t,this.enableRefreshTokenRetryInSeconds,"ActiveRefresh Token Timeout");a=Date.now(),o=r?.causeId,this.lastTokenType=r?.tokenType,l=1,a=Date.now(),this.logger.info(`[${i}][refreshTokenWithContext] refresh token success for factorsJson ${e.factorsJson} and tokenType ${e.tokenType}`)}catch(t){s=t,o=s?.causeId,t?.timeOut?(this.logger.info(`[${i}][refreshTokenWithContext] refresh token timeout, UI did not respond with token in time ${Ne(t)}`),l=5):(this.logger.info(`[${i}][refreshTokenWithContext] failed to refresh token, UI did not respond with token ${Ne(t)}`),l=2),a=Date.now(),this.deletePromisesByTriggeredByRefresh(e.factorsJson,!0)}finally{t&&(t.requestCauseId=i,t.responseCauseId=o,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=e.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=a,t.tokenRequestStatus=l,t.requestTokenType=e.tokenType,t.foundInCache=!1,t.responseTokenType=e.tokenType,t.errorCode=s?.errorCode,t.errorSubCode=s?.errorSubCode,this.sendTokenTelemetry(t))}}refreshToken(){const e=this.cacheTokenManager.getTokenContext(4),t=this.cacheTokenManager.getTokenContext(8),i=this.cacheTokenManager.getTokenContext(1);if(!this.clientSupportsGenericTokenAPI)return void this.logger.info("[refreshToken] new Token Api is not spported");if(!e&&!t&&!i)return void this.logger.info("[refreshToken] no cached tokens available to refresh");const n=Pa()+this.refreshTimeBeforeTokenTimeoutInSeconds;let r=Number.MAX_VALUE,a=!1;if(e)if(e.expiryTime>n){const t=e?.expiryTime-n;t<r&&(r=t)}else e.expiryTime<=n&&(this.refreshTokenWithContext(e),a=!0);if(t)if(t.expiryTime>n){const e=t?.expiryTime-n;e<r&&(r=e)}else t.expiryTime<=n&&(this.refreshTokenWithContext(t),a=!0);if(i)if(i.expiryTime>n){const e=i?.expiryTime-n;e<r&&(r=e)}else i.expiryTime<=n&&(this.refreshTokenWithContext(i),a=!0);a&&this.enableRefreshTokenRetry&&this.enableRefreshTokenRetryInSeconds>0&&this.enableRefreshTokenRetryInSeconds<r&&(r=this.enableRefreshTokenRetryInSeconds),r>=0&&r!==Number.MAX_VALUE&&this.startTokenRefreshTimer(Ma(r))}async getTokenWithTokenType(e,t=!1,i,n){this.logger.info(`[${e}][getTokenWithTokenType] call with factorJson=${i?.factorsJson} and request tokenType ${i?.tokenType}`);const{factorsJson:r,requestMetadataJson:a,invalidToken:s,isUnauthorized:o}=i||{},l=Date.now(),c=i?.tokenType;let d,u,h,p=2;this.clearExpiredTokens(),this.startTokenRefreshTimer(1);try{if(t)this.invalidateCachedTokenWithTokenType(c,s,r);else if(this.enableTokenCacheForGenericTokenAPI){const t=this.cacheTokenManager.getToken(c,r,this.logger,s);if(t?.token)return this.logger.info(`[${e}][getTokenWithTokenType] returning cached token for factorsJson ${r} and request tokenType ${c}, response tokenType ${t.tokenType}`),p=3,d=Date.now(),this.lastTokenType=t.tokenType,t}this.logger.info(`[${e}][getTokenWithTokenType] fetching new token for factorsJson ${r} and tokenType ${c}`);const i=a||{};i.causeId=e;const n=this.onTokenRequired({factorsJson:r,tokenType:c,requestMetadataJson:i,invalidToken:s,isUnauthorized:o,triggeredByRefresh:!1}),l=await this.timeoutPromiseRace(n,Jr.TIMEOUT_VALUES_IN_SECONDS.TOKEN_REQUIRED_TIMEOUT,"Token not received from UI in time");return d=Date.now(),h=l?.causeId,this.lastTokenType=l?.tokenType,p=1,this.logger.info(`[${e}][getTokenWithTokenType] fetching new token success for factorsJson ${r} and tokenType ${c}`),l}catch(t){throw this.logger.info(`[${e}][getTokenWithTokenType] failed to fetch token ${Ne(t)}`),u=t,h=u?.causeId,u.timeOut&&(p=4),this.deletePromisesByTriggeredByRefresh(r,!1),t}finally{const t=!n?.tokenTelemetryData,r=t?{}:n?.tokenTelemetryData;r&&(r.requestCauseId=e,r.responseCauseId=h,r.supportTokenApi=this.clientSupportsGenericTokenAPI,r.requestTokenFactors=i?.factorsJson,r.tokenRequestTime=l,r.tokenResponseTime=d,r.tokenRequestStatus=p,r.requestTokenType=i?.tokenType,r.foundInCache=3===p,r.responseTokenType=this.lastTokenType,r.timeToResponse=d?d-l:d,r.errorCode=u?.errorCode,r.errorSubCode=u?.errorSubCode),(!n||t&&!n.signalingSession)&&(this.logger.info("[getTokenWithTokenType] TokenContext is not provided, sending token telemetry to Token table"),this.sendTokenTelemetry(r))}}async onTokenRequired(e){const{factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:a,triggeredByRefresh:s}=e;if(this.logger.info(`[onTokenRequired] factorsJson=${t} tokenType=${i}`),!i)return this.logger.info(`[onTokenRequired] factorsJson=${t} with no token type`),Promise.reject({errorCode:Jr.HTTP_STATUS_CODES.UNAUTHORIZED,errorSubCode:0,causeId:n?.causeId});if(this.tokensPromiseMap[t]&&!s)for(const e of this.tokensPromiseMap[t])if(e.tokenRequestOptions.tokenType===i)return this.logger.info(`[onTokenRequired] factorsJson=${t} and tokenType ${i} has pending request`),e.defered.promise;this.tokensPromiseMap[t]||(this.tokensPromiseMap[t]=[]);const o=Si();return this.tokensPromiseMap[t].push({tokenRequestOptions:e,defered:o}),this.tokenCallback({factorsJson:t,tokenType:i,requestMetadataJson:n,invalidToken:r,isUnauthorized:a}),o.promise}setTokenCaching(e,t){this.tokenCachingEnabled!==e&&(this.logger.info(`[authTokenManager]setTokenCaching=${e}`),this.tokenCachingEnabled=e)}setTokenCachingForGenericTokenAPI(e,t){this.enableTokenCacheForGenericTokenAPI!==e&&(this.logger.info(`[authTokenManager]setTokenCachingForGenericTokenAPI=${e}`),this.enableTokenCacheForGenericTokenAPI=e)}calculateTokenExpiry(e,t,i){const{factorsJson:n,tokenType:r}=t;let a=i-Pa(),s=a,o=i;if(a&&a>0&&a>this.refreshTimeBeforeTokenTimeoutInSeconds){switch(r){case 4:a>this.aadTokenExpirationTimeInSeconds&&(a=this.aadTokenExpirationTimeInSeconds);break;case 8:a>this.caeTokenExpirationTimeInSeconds&&(a=this.caeTokenExpirationTimeInSeconds);break;default:a>3600&&(a=3600)}s=a-this.refreshTimeBeforeTokenTimeoutInSeconds,o=s+Pa()}return this.logger.info(`[${e}][calculateTokenExpiry] calculate expiry to ${o} tokenType=${r} factorsJson=${n}`),o}addToCache(e,t,i,n){this.clearExpiredTokens(),this.cacheTokenManager.setToken(e,t,i,n)}clearExpiredTokens(){this.forceClearExpiredTokens&&this.cacheTokenManager.clearExpiredTokens(this.logger)}async getToken(e,t=!1,i,n){if(this.clientSupportsGenericTokenAPI){this.logger.info(`[${e}][getToken] callingTokenAPI is enabled so using new API to fetch it`);const{token:r}=await this.getTokenWithTokenType(e,t,i,n);return r}const r=Date.now();let a,s,o=2;try{if(t&&this.invalidateCachedToken(e),this.cachedToken&&this.tokenCachingEnabled)return this.logger.info(`[${e}][getToken] returning cached token`),o=3,Promise.resolve(this.cachedToken);this.logger.info(`[${e}][getToken] fetching new token`);const i=await this.tokenProvider();return a=Date.now(),i?(this.tokenCachingEnabled&&(this.cachedToken=i),o=1,this.lastToken=i,this.lastTokenType=1,this.logger.info(`[${e}][getToken] fetching new token success`),i):(this.logger.info(`[${e}][getToken] received empty token`),Promise.reject("Received empty token"))}catch(t){throw this.logger.info(`[${e}][getToken] failed to fetch token=${Ne(t)}`),s=t,this.cachedToken="",t}finally{const t=n?.tokenTelemetryData;t&&(t.requestCauseId=e,t.supportTokenApi=this.clientSupportsGenericTokenAPI,t.requestTokenFactors=i?.factorsJson,t.tokenRequestTime=r,t.tokenResponseTime=a,t.tokenRequestStatus=o,t.requestTokenType=i?.tokenType,t.foundInCache=3===o,t.responseTokenType=this.lastTokenType,t.timeToResponse=a?a-r:a,t.errorCode=s?.errorCode,t.errorSubCode=s?.errorSubCode)}}invalidateCachedToken(e){this.cachedToken&&(this.logger.info(`[${e}][invalidateCachedToken]`),this.cachedToken="")}invalidateCachedTokenWithTokenType(e,t,i){8===e&&this.cacheTokenManager.getToken(8,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(8)),4===e&&this.cacheTokenManager.getToken(4,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(4)),1===e&&this.cacheTokenManager.getToken(1,i,this.logger)?.token===t&&(this.cacheTimers.stopTimer(i,e.toString()),this.cacheTokenManager.resetToken(1))}getLastToken(e){return this.logger.info(`[${e}][getLastToken]`),this.lastToken}getLastTokenWithTokenType(e,t,i){return this.logger.info(`[${e}][getLastTokenWithTokenType] with Token Type: ${t}`),this.cacheTokenManager.getToken(t,i,this.logger)?.token}async timeoutPromiseRace(e,t,i){let n;const r=new Promise(((e,r)=>{n=window.setTimeout((()=>{r({phrase:i,timeOut:!0})}),Ma(t))}));return Promise.race([e.then((e=>(clearTimeout(n),e))),r])}getLastTokenType(e){return this.logger.info(`[${e}][getLastTokenType] lastTokenType=${this.lastTokenType}`),this.lastTokenType}updateTokenSettings(e){const{clientSupportsGenericTokenAPI:t,aadTokenExpirationTimeInSeconds:i,caeTokenExpirationTimeInSeconds:n,refreshTimeBeforeTokenTimeoutInSeconds:r,enablePublishTokenTelemetry:a,enableRefreshToken:s,forceClearExpiredTokens:o,enableRefreshTokenRetry:l,enableRefreshTokenRetryInSeconds:c}=e;this.logger.info(`updateTokenSettings ${JSON.stringify(e)}`),this.clientSupportsGenericTokenAPI=t??this.clientSupportsGenericTokenAPI,this.aadTokenExpirationTimeInSeconds=i??this.aadTokenExpirationTimeInSeconds,this.caeTokenExpirationTimeInSeconds=n??this.caeTokenExpirationTimeInSeconds,this.refreshTimeBeforeTokenTimeoutInSeconds=r??this.refreshTimeBeforeTokenTimeoutInSeconds,this.enablePublishTokenTelemetry=a??this.enablePublishTokenTelemetry,this.forceClearExpiredTokens=o??this.forceClearExpiredTokens,this.enableRefreshToken=s??this.enableRefreshToken,this.enableRefreshTokenRetry=l??this.enableRefreshTokenRetry,this.enableRefreshTokenRetryInSeconds=c??this.enableRefreshTokenRetryInSeconds}updateToken(e,t,i,n,r){if(this.logger.info(`[${n}][updateToken] UI replies a token with factorsJson=${e} updateMetadata=${JSON.stringify(t)} tokenExpirySecSinceEpoch?=${r}`),t.error){this.logger.info(`[${n}][updateToken] UI replies with error ${t.error} for factorsJson ${e}`);for(const i of this.tokensPromiseMap[e])i.tokenRequestOptions.requestMetadataJson.causeId===n&&i.defered.reject({phrase:t.error?.phrase,errorCode:t.error?.code,errorSubCode:t.error?.subCode,causeId:n});return}if(!i){this.logger.info(`[${n}][updateToken] received empty token`);for(const t of this.tokensPromiseMap[e])t.tokenRequestOptions.requestMetadataJson.causeId===n&&t.defered.reject({phrase:"Received empty token",causeId:n});return}if(r>Pa()&&this.enableTokenCacheForGenericTokenAPI){this.logger.info(`[${n}][updateToken] caching Token with tokenType=${t.tokenType}`);const a={factorsJson:e,tokenType:t.tokenType,invalidToken:i};this.addToCache(t.tokenType,i,e,this.calculateTokenExpiry(n,a,r))}if(!this.tokensPromiseMap[e]){this.logger.warn(`[updateToken]: UI try to update token with invalid factorsJson=${e}`);const i={responseCauseId:n,supportTokenApi:this.clientSupportsGenericTokenAPI,requestTokenFactors:e,tokenResponseTime:Date.now(),tokenRequestStatus:6,responseTokenType:t.tokenType};return void this.sendTokenTelemetry(i)}if(this.tokensPromiseMap[e]){const r=this.tokensPromiseMap[e];for(let a=r.length-1;a>=0;a--)(r[a]?.tokenRequestOptions.tokenType&t.tokenType)>0&&(r[a].defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),this.tokensPromiseMap[e].splice(a,1))}if(this.logger.info(`[${n}][updateToken] resolved and upateToken with factorsJson=${e} tokenType=${t.tokenType}`),0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e],4!==t.tokenType&&8!==t.tokenType&&1!==t.tokenType)return;if(Object.keys(this.tokensPromiseMap).length>0)for(const r of Object.values(this.tokensPromiseMap))for(let a=r.length-1;a>=0;a--){const s=r[a];s.tokenRequestOptions.factorsJson!==e&&(s.tokenRequestOptions.tokenType&t.tokenType)>0&&!s.tokenRequestOptions.isUnauthorized&&(s.defered.resolve({token:i,tokenType:t.tokenType,causeId:n}),r.splice(a,1))}for(const e of Object.keys(this.tokensPromiseMap))0===this.tokensPromiseMap[e].length&&delete this.tokensPromiseMap[e];const a=r-Pa();this.startTokenRefreshTimer(a>=0?Ma(a):0)}setTokenRequiredCallBack(e){this.tokenCallback=e}setDisableTimerFlag(e){this.logger.info(`[setDisableTimerFlag] set disableTimerFlag to ${e}`),this.stopTimerFlag=e}sendTokenTelemetry(e){if(!this.enablePublishTokenTelemetry)return;const t={};t[_d.TOKEN_TELEMETRY]=JSON.stringify(e),this.telemetryManager?(this.logger.info("[sendTokenTelemetry] sending token telemetry:",t),this.telemetryManager.sendEvent(cd.CONVERSATION_TOKEN,t)):this.logger.warn("[sendTokenTelemetry] telemetryManager is undefined, cannot send token telemetry")}dispose(){this.cacheTimers&&this.cacheTimers.dispose()}},Rd=(e,t,i,n)=>new wd(e,t,i,n),Ad=class{constructor(e){this.piiScrubber=this.getPiiScrubber(e)}scrubParticipantsList(e){const t=[];return Array.isArray(e)&&e.forEach((e=>t.push(this.scrubMriOrOmit(e)))),t}scrubMriOrOmit(e){return"string"==typeof e?this.piiScrubber.mri(e):this.piiScrubber.omit(e)}static scrubDisplayNamesFromResponse(e){return Le(e).replace(/"displayName": "[a-z]+"/gi,'"displayName": "(redacted)"')}getPiiScrubber(e){return e&&"function"==typeof e.omit&&"function"==typeof e.mri?e:{omit:()=>"<pii:omit/>",mri:()=>"<pii:mri/>"}}},Pd=f(g);function Md(e){switch(e){case 0:return"main-audio";case 1:return"main-video";case 2:return"applicationsharing-video";case 3:return"data"}throw new Error("Invalid media type")}function kd(e){switch(e){case"audio":return 0;case"video":return 1;case"applicationsharing-video":return 2;case"data":return 3;default:return}}function Dd(e,t){return e.endpoints?.endpointDetails.find((e=>e.participantId===t))}function Od(e,t){return e.participants.find((e=>function(e,t){return e.endpoints?.endpointDetails?.some((e=>e.participantId===t))??!1}(e,t)))}function Nd(e){return!!e?.meetingGroupDetails?.groups&&Object.keys(e.meetingGroupDetails.groups).some((e=>"stagingGroup"===e))}function Ld(e,t){let i=-1;try{if(e.endpoints)e:for(const n of e.endpoints.endpointDetails)if(null!==n&&void 0!==n.mediaStreams){for(const e of n.mediaStreams)if(kd(e.type)===t){i=e.sourceId;break e}}else i=_n}catch(e){return-1}return i}function xd(e,t,i){try{if(!e.endpoints)return;for(const n of e.endpoints.endpointDetails)if(n?.mediaStreams)for(const e of n.mediaStreams)if(i===e.sourceId&&kd(e.type)===t)return n.participantId??null;return}catch(e){return}}function Fd(e){return"sendonly"===e.direction&&"applicationsharing-video"===e.label}function Ud(e){if(e.endpoints?.endpointDetails)return 1===e.endpoints.endpointDetails.length?e.endpoints.endpointDetails[0].participantId:e.endpoints.endpointDetails.find((e=>e?.mediaStreams?.some(Fd)))?.participantId}function Bd(e){let t={};if(e.stateId)t.result=e.stateId;else if(e.results){const{results:i}=e;1===i.length&&i[0].stateId&&(t.result=i[0].stateId);const n={};e.results.forEach((e=>{const{result:i}=e,r=function(e){return e.participantId||e.participant&&e.participant.id}(e);(void 0===t.code||i.code>t.code)&&(t.code=i.code,t.subCode=i.subCode),n[r]=e})),t.result=JSON.stringify(n)}else e.result&&(t={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode,resultCategories:e.result.resultCategories},e.additionalDetail&&(t.result=e.additionalDetail));return t}var Vd=class{constructor(e,t){this.broadcastContext=null,this.broadcastControllerUrl="",this.broadcastCallbackUrl="",this.broadcastState=null,this.setContext=(e=null)=>{this.logger.info("BroadcastSession :: set broadcast context",e),this.broadcastContext=e},this.getContext=()=>(this.logger.info("BroadcastSession :: get broadcast context",this.broadcastContext||null),this.broadcastContext||null),this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[Broadcast]"))}handleBroadcastStateChanged(e){const t=e.body;this.broadcastState=t;const i=ya(e);this.signalingSession.telemetryHelper.recordIncomingEvent(Zo,e),this.logger.info(`[${i}] broadcast state changed=${this.broadcastState}`),this.updateBroadcastMetadata(i)}updateBroadcastCallbackUrl(e){const t=Zr(this.signalingSession,Ar.CONV_BROADCAST_UPDATE);this.broadcastCallbackUrl!==t&&(this.broadcastCallbackUrl=t,this.logger.info(`[${e}] broadcast callback url changed=${this.broadcastCallbackUrl}`),this.updateBroadcastMetadata(e))}handleBroadcastDetailsChanged(e,t){this.signalingSession.telemetryHelper.recordEvent(go,{causeId:t}),e.activeModalities&&e.activeModalities.broadcast&&e.activeModalities.broadcast.controller!==this.broadcastControllerUrl&&(this.broadcastControllerUrl=e.activeModalities.broadcast.controller,this.broadcastAdditionalData=e.activeModalities.broadcast,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.signalingSessionCallback.onBroadcastMeetingConnected(Jr.SUCCESS_TRANSACTION_END,t),this.updateBroadcastMetadata(t)),!this.broadcastControllerUrl||e.activeModalities&&e.activeModalities.broadcast||(this.broadcastControllerUrl="",this.broadcastContext=null,this.logger.info(`[${t}] broadcast controller changed=${this.broadcastControllerUrl}`),this.updateBroadcastMetadata(t),this.signalingSessionCallback.onBroadcastMeetingEnded(Jr.SUCCESS_TRANSACTION_END,t))}handleAddBroadcastModalitySuccess(e,t){this.logger.info(`[${t}][handleAddBroadcastModalitySuccess]`)}handleAddBroadcastModalityFailure(e,t){this.logger.info(`[${t}][handleAddBroadcastModalityFailure]`);const i={...e.modalityFailure.broadcast};this.signalingSessionCallback.onBroadcastMeetingEnded(i,t)}updateBroadcastMetadata(e){const t={broadcastControllerUrl:this.broadcastControllerUrl,broadcastStateCallbackUrl:this.broadcastCallbackUrl,broadcastState:this.broadcastState,broadcastAdditionalData:this.broadcastAdditionalData};this.logger.info(`[${e}] update broadcast metadata=${t}`),this.signalingSessionCallback.onBroadcastMeetingUpdated&&this.signalingSessionCallback.onBroadcastMeetingUpdated(t,e)}},Hd=class{static build(e,t){return new $d(e,t)}},$d=class{constructor(e,t){this.ontimeout=e,this.name=t}start(e){if(void 0!==this.timeoutId)throw new Error(`Timer ${this.name} already started`);return this.timeoutId=window.setTimeout((()=>this.ontimeout()),e),this}stop(){if(void 0===this.timeoutId)throw new Error(`Timer ${this.name} is not defined`);clearTimeout(this.timeoutId),this.timeoutId=void 0}},Gd=class{constructor(e){this._signalingSession=e,this.baseUrl="http://broker.invalid/",this.currentSubscriptionUrl=null,this._currentSubscriptionTimeoutInSec=30,this._subscribers=[],this._disposed=!1,this._reportedResultCount=0,this._subscriptionRetryBackoffInSec=5,this._notifySubscribers=e=>{this._logger.info("_notifySubscribers"),Promise.resolve().then((()=>{e.split(",").forEach((e=>{const t=function(e){const t=e.split(/\r?\n\r?\n/),i=t[0].split(/\r?\n/),n=t[1].split(/\r?\n/),r=i.shift().split(" "),a=r[0],s=r[1]||"",o=new Qr;for(const e of i)try{const[t,i]=e.split(":").map((e=>Sr.trim(e)));o.set(t,i)}catch(t){throw new Error(`Malformed header: ${e+t}`)}return{url:s,headers:o,method:a,body:n.join("")}}(Ea(e));let i=t.body;Ca(t.headers)&&_a(t.headers)&&(i=Ea(i));const n={url:t.url,body:JSON.parse(i),headers:t.headers};this._logger.info("message length=",i.length,"n. of subscribers",this._subscribers.length),this._subscribers.forEach((e=>e(n)))}))})).catch((e=>{this._logger.error("_notifySubscribers, failed to decode message",e),this._signalingSession.telemetryHelper.recordEvent(Ho)}))},this._subscribeToBroker=(e,t)=>{if(this._disposed)return void this._logger.warn("_subscribeToBroker, disposed, ignore subscription");const i=na();this._logger.info("_subscribeToBroker, url: ",e,",timeout in sec",t),this.currentSubscriptionUrl=e,this._currentSubscriptionTimeoutInSec=t,this._clearAllPendingTimeouts(),this._setSubscriptionTimeout(t),this._signalingSession.http.sendGetRequest({url:this.currentSubscriptionUrl,requestName:sd.BROKER_SUBSCRIBE.name,customHeaders:this._getBrokerRequestHeaders(i),payload:null,skipHttpTelemetry:!this._reportSubscriptionInTelemetry(),causeId:na(),operationType:"BrokerSubscribe"}).then(this._handleSubscriptionSuccess).catch(this._handleSubscriptionFailure)},this._clearAllPendingTimeouts=()=>{this._cancelRequestTimer&&(this._cancelRequestTimer.stop(),this._cancelRequestTimer=null),this._retryRequestTimer&&(this._retryRequestTimer.stop(),this._retryRequestTimer=null)},this._abortPendingRequest=()=>{this._signalingSession.http.cancelRequestIfPending(sd.BROKER_SUBSCRIBE.name,na())},this._setSubscriptionTimeout=e=>{this._cancelRequestTimer=Hd.build((()=>{this._disposed||(this._signalingSession.http.hasPendingRequest(sd.BROKER_SUBSCRIBE.name)?(this._logger.warn("timeout subscription"),this._signalingSession.telemetryHelper.recordEvent($o),this._signalingSession.http.cancelRequestIfPending(sd.BROKER_SUBSCRIBE.name,na())):this._logger.error("Unable to resolve timeout deferred, it is not defined!"))}),"TIMEOUT").start(1e3*e)},this._handleSubscriptionSuccess=e=>{if(this._disposed)this._logger.warn("_handleSubscriptionSuccess, disposed, ignore subscription success");else if(this._reportSubscriptionInTelemetry(e)&&this._signalingSession.telemetryHelper.recordEvent(Go),e&&e.response){const t=e.response;this._logger.info("_handleSubscriptionSuccess, response",t),t.message&&this._notifySubscribers(t.message);const i=t.nextSubscribeUrl||this.currentSubscriptionUrl,n=t.expirationTimeInSec||this._currentSubscriptionTimeoutInSec;this._subscribeToBroker(i,n)}else this._logger.info("_handleSubscriptionSuccess, empty response")},this._handleSubscriptionFailure=e=>{if(this._disposed)return void this._logger.warn("_handleSubscriptionFailure, disposed, ignore subscription");if(e.status>=400&&e.status<500&&401!==e.status&&this.isNotNetworkErrors(e.status))return void this._logger.warn(`_handleSubscriptionFailure, received status ${e.status}, stop subscribing`);const t=Ne(e);this._logger.error("_handleSubscriptionFailure failed, re-subscribing",t),this._reportSubscriptionInTelemetry()&&this._signalingSession.telemetryHelper.recordEvent(jo),this._retryRequestTimer=Hd.build((()=>{this._subscribeToBroker(this.currentSubscriptionUrl,this._currentSubscriptionTimeoutInSec)}),"RETRY").start(1e3*this._subscriptionRetryBackoffInSec)},this._reportSubscriptionInTelemetry=e=>(this._reportedResultCount++,this._reportedResultCount<=1),this._getBrokerRequestHeaders=e=>{const t=new Qr;return t.set(Jr.HEADERS.CONTENT_TYPE,Jr.CONTENT_TYPE.JSON),this._signalingSession.signalingAgentConfig.brokerRequestBatching&&t.set(Jr.HEADERS.BROKER_USE_BATCHING_HEADER_NAME,"1"),t},this._logger=this._signalingSession.logger.createChild("Broker"),this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration?.brokerRetryBackOffInSec&&(this._subscriptionRetryBackoffInSec=this._signalingSession.signalingAgentConfig.csaTimeoutConfiguration.brokerRetryBackOffInSec)}subscribeToBroker(e){this._logger.info("subscribeToBroker called."),this._abortPendingRequest(),this._clearAllPendingTimeouts(),this._subscribeToBroker(e,this._currentSubscriptionTimeoutInSec)}onBrokerMessage(e){this._logger.info("onBrokerMessage callback added"),this._subscribers.push(e)}dispose(){this._disposed=!0,this._logger.info("dispose"),this._subscribers=[],this._clearAllPendingTimeouts(),this._abortPendingRequest()}isNotNetworkErrors(e){return 490!==e&&496!==e&&498!==e&&499!==e}},jd=class{constructor(e){this.requests={},this.logger=e}clear(e,t){const i=t||{code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{try{const n=parseInt(t,10);Object.keys(this.requests[n]).forEach((t=>{this.rejectOperation(n,t,e,i)}))}catch(e){this.logger.warn(`CallOperations: clear error = ${e}`)}}))}hasOperation(e,t){return this.requests.hasOwnProperty(e.valueOf())&&this.requests[e.valueOf()].hasOwnProperty(t)}getAllOperations(){return this.requests}getOperation(e,t){return this.hasOperation(e,t)?this.requests[e.valueOf()][t]:null}setOperation(e,t,i){return!this.hasOperation(e,t)&&(this.hasOwnProperty(e.valueOf())||(this.requests[e.valueOf()]={}),this.requests[e.valueOf()][t]=i,!0)}rejectOperation(e,t,i,n){if(this.hasOperation(e,t)){const i=e.valueOf(),r=this.requests[i][t].promise;delete this.requests[i][t],r.reject(n)}}resolveOperation(e,t,i,n){if(this.hasOperation(e,t)){const n=e.valueOf(),r=this.requests[n][t].promise;delete this.requests[n][t],r.resolve(i)}}},zd=class{constructor(e){this.logger=e,this.localRequests=new jd(e)}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}hasPendingOperation(e,t,i){return this.logger.info(`[${i}][hasPendingOperation] ${e} ${Ae(t)}}`),this.localRequests.hasOperation(e,t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${t} reason: ${i} endCode: ${n}`),this.localRequests.rejectOperation(e,t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${Ae(t)}`),this.localRequests.resolveOperation(e,t,i,n)}setPendingOperation(e,t,i,n){return this.logger.info(`[${n}][setPendingOperation] ${e} value: ${i}`),this.localRequests.setOperation(e,t,i)}rejectAllPendingOperations(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localRequests.clear(e,t)}};function Wd(e,t){return oa(e,"signalingSession cannot be null"),oa(t,"content cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[]},contentSharing:{identifier:t.contentIdentifier,subject:t.subject,sessionState:t.sessionState,sequenceNumber:t.sequenceNumber,links:{sessionUpdate:Zr(e,Ar.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Zr(e,Ar.CONV_CONTENT_SHARING_END)}},links:{addModalitySuccess:Zr(e,Ar.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Zr(e,Ar.CONV_ADD_MODALITY_FAILURE)}}}}function qd(e){return oa(e,"signalingSession cannot be null"),{payload:{contentSharing:{links:{sessionUpdate:Zr(e,Ar.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Zr(e,Ar.CONV_CONTENT_SHARING_END)}},participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Kd(e,t){return oa(e,"signalingSession cannot be null"),la(t),{payload:{contentSharingTransactionEnd:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Jd(e){return oa(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Yd(e){return oa(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{sessionUpdate:Zr(e,Ar.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Zr(e,Ar.CONV_CONTENT_SHARING_END)}}}}function Qd(e){return oa(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}function Zd(e,t,i){return oa(e,"signalingSession cannot be null"),oa(t,"sessionState cannot be null"),oa(i,"sequenceNumber cannot be null"),{payload:{sessionUpdateSequenceNumber:i,sessionState:t,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}}}}var Xd=class{constructor(){this.msElapsed=0,this.isPaused=!1,this.startTime=(new Date).getTime(),this.pause=()=>{this.isPaused||(this.msElapsed+=(new Date).getTime()-this.startTime,this.isPaused=!0)},this.resume=()=>{this.isPaused&&(this.isPaused=!1,this.startTime=(new Date).getTime())},this.duration=()=>this.isPaused?this.msElapsed:this.msElapsed+(new Date).getTime()-this.startTime,this.durationInMinutes=()=>{const e=this.duration()/6e4;return Math.ceil(e)},this.durationInSeconds=()=>{const e=this.duration()/1e3;return Math.ceil(e)}}};function eu(){return new Xd}var tu=class{constructor(e,t,i,n){this.signalingSession=e,this.correlationId=t,this.sessionId=null,this.fsmState=Jr.CONTENT_SHARING_FSM_STATE.IDLE,this.addSessionPromise=null,this.removeSessionPromise=null,this.confirmInRosterPromise=null,this.links={},this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.disposed=!1,this.isPresenter=!1,this.FSM_STATES=Jr.CONTENT_SHARING_FSM_STATE,this.logger=e.logger.createChild((()=>`[${this.fsmState}][cs=${this.sessionId}][cc=${this.correlationId}]`)),i&&(this.sessionId=i),n&&(this.links=n)}start(e,t,i,n){if(this.logger.info(`[${n}][start]`),sa(e,"Correct addModality url is not provided"),!this.checkState("start",this.FSM_STATES.IDLE,this.addSessionPromise))return Promise.reject(null);this.addSessionPromise=i,this.confirmInRosterPromise=Ta(),this.fsmState=this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.addTelemetryOperation(sd.ADD_CONTENT_SHARING_MODALITY.name,{causeId:n});const r=new Qr;return r.set(Jr.HEADERS.CONTENT_SHARING_CORRELATION_ID,this.correlationId),this.signalingSession.http.sendPostRequest({url:e,payload:Wd(this.signalingSession,t),requestName:sd.ADD_CONTENT_SHARING_MODALITY.name,customHeaders:r,onceTrouterReady:()=>{this.startContentSharingTimer(n)},causeId:n}).then((()=>{this.disposed||(this.presenterMri=this.signalingSession.participantManager.localParticipant.id,this.isPresenter=!0)})).catch((e=>{const t=fa(e,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${n}][start] error: ${Ne(t)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise(Ne(e),t.error)),Promise.reject(null)}))}delete(e,t){this.logger.info(`[${t}][delete]`);let i=!1;if(this.fsmState===this.FSM_STATES.IDLE)return this.logger.info(`[${t}][delete] skipped because state is already ${this.fsmState}`),e.resolve(),Promise.resolve();if(this.fsmState===this.FSM_STATES.CONTENT_SHARING_START_INITIATED)i=!0,this.rejectPendingPromise("Session delete called before start was finished");else if(!this.checkState("delete",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return Promise.reject(null);i||sa(this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER],"Correct controller url is not set"),this.removeSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_DELETE_INITIATED;const n=eu(),r=this.addTelemetryOperation(sd.DELETE_CONTENT_SHARING.name,{causeId:t});return(i?Promise.resolve(void 0):this.signalingSession.http.sendDeleteRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER],requestName:sd.DELETE_CONTENT_SHARING.name,payload:Kd(this.signalingSession,{code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED}),causeId:t})).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};i&&(e.skipReason="Session delete called before start was finished"),this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}})).catch((e=>{const i=fa(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][delete] error: ${Ne(i)}`),!this.disposed){const e={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,e),this.fsmState=this.FSM_STATES.IDLE,this.resolvePendingPromise()}return Promise.reject(null)}))}join(e,t){if(this.logger.info(`[${t}][join]`),sa(this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER],"Correct joinContentSharing url is not provided"),!this.checkState("join",this.FSM_STATES.IDLE,e))return;this.lastUpdateSequenceNumber=-1,this.nextClientSequenceNumberToUse=1,this.addSessionPromise=e,this.fsmState=this.FSM_STATES.CONTENT_SHARING_JOIN_INITIATED;const i=eu(),n=this.addTelemetryOperation(sd.JOIN_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER],payload:qd(this.signalingSession),requestName:sd.JOIN_CONTENT_SHARING.name,causeId:t}).then((e=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),this.processStartOrJoinSuccess(e.response),this.resolvePendingPromise(e.response)}})).catch((e=>{const r=fa(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][join] error: ${Ne(r)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const a=r.error;this.rejectPendingPromise(Ne(e),a)}}))}takeControl(e,t){if(this.logger.info(`[${t}][takeControl]`),sa(this.links[Jr.LINKS.CONTENT_SHARING_TAKE_CONTROL],"correct contentSharingTakeControl url is not provided"),!this.checkState("takeControl",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=eu(),n=this.addTelemetryOperation(sd.TAKE_CONTROL_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_TAKE_CONTROL],payload:Jd(this.signalingSession),requestName:sd.TAKE_CONTROL_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((t=>{if(!this.disposed){const r={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,r);const a={contentIdentifier:t.response.identifier,presenter:t.response.presenter.id,subject:t.response.subject||null,sessionState:t.response.sessionState||null};e.resolve(a)}})).catch((r=>{const a=fa(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][takeControl] error: ${Ne(a)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const s=new Error(Ne(r));s.endCode=a.error,e.reject(s)}}))}updateSessionState(e,t,i){if(this.logger.info(`[${i}][updateSessionState]`),sa(this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],"Correct sendUpdateSessionState url is not provided"),!this.checkState("updateSessionState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,t))return;const n=eu(),r=this.addTelemetryOperation(sd.UPDATE_SESSION_STATE_CONTENT_SHARING.name,{causeId:i});this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE],payload:Zd(this.signalingSession,e,this.nextClientSequenceNumberToUse++),requestName:sd.UPDATE_SESSION_STATE_CONTENT_SHARING.name,causeId:i}).then((()=>{if(!this.disposed){const e={success:!0,duration:n.duration()};this.updateTelemetryOperation(r,e),t.resolve()}})).catch((e=>{const a=fa(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${i}][updateSessionState] error: ${Ne(a)}`),!this.disposed){const i={success:!1,duration:n.duration()};this.updateTelemetryOperation(r,i);const s=new Error(Ne(e));s.endCode=a.error,t.reject(s)}}))}updateParticipantState(e,t){if(this.logger.info(`[${t}][updateParticipantState]`),sa(this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],"correct confirmContentSharingView url is not provided"),!this.checkState("updateParticipantState",this.FSM_STATES.CONTENT_SHARING_CONNECTED,e))return;const i=eu(),n=this.addTelemetryOperation(sd.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,{causeId:t});this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE],payload:Qd(this.signalingSession),requestName:sd.UPDATE_PARTICIPANT_STATE_CONTENT_SHARING.name,withoutTrouter:!0,causeId:t}).then((()=>{if(!this.disposed){const t={success:!0,duration:i.duration()};this.updateTelemetryOperation(n,t),e.resolve()}})).catch((r=>{const a=fa(r,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${t}][updateParticipantState] error: ${Ne(a)}`),!this.disposed){const t={success:!1,duration:i.duration()};this.updateTelemetryOperation(n,t);const s=new Error(Ne(r));s.endCode=a.error,e.reject(s)}}))}updateNotificationLinks(e){if(this.logger.info(`[${e}][updateNotificationLinks]`),sa(this.links[Jr.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],"correct notificationLinks url is not provided"),!this.checkState("updateState",this.FSM_STATES.CONTENT_SHARING_CONNECTED))return;const t=eu(),i=this.addTelemetryOperation(sd.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,{causeId:e});this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS],payload:Yd(this.signalingSession),requestName:sd.UPDATE_CONTENT_SHARING_NOTIFICATION_LINKS.name,withoutTrouter:!0,causeId:e}).then((()=>{if(!this.disposed){const e={success:!0,duration:t.duration()};this.updateTelemetryOperation(i,e)}})).catch((n=>{const r=fa(n,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${e}][updateNotificationLinks] error: ${Ne(r)}`),!this.disposed){const e={success:!1,duration:t.duration()};this.updateTelemetryOperation(i,e)}}))}confirmInRoster(){this.confirmInRosterPromise&&this.confirmInRosterPromise.isPending&&(this.logger.info("Confirmed in roster"),this.confirmInRosterPromise.resolve())}handleAddModalitySuccess(e,t){return this.logger.info(`[${t}][handleAddModalitySuccess]`),this.checkState("handleAddModalitySuccess",this.FSM_STATES.CONTENT_SHARING_START_INITIATED)?e.modalitySuccess&&e.modalitySuccess.contentSharing?(this.addTelemetryOperation(uo,{causeId:t}),this.processStartOrJoinSuccess(e.modalitySuccess.contentSharing),this.confirmInRosterPromise.promise.then((()=>{delete this.confirmInRosterPromise,this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_MODALITY),this.resolvePendingPromise(e.modalitySuccess.contentSharing)})),!0):(this.addTelemetryOperation(uo,{causeId:t,skipReason:"no content sharing blob"}),this.logger.info(`[${t}][handleAddModalitySuccess] ignored because modalitySuccess was missing or did not contain content sharing blob`),!1):(this.logger.info(`[${t}][handleAddModalitySuccess] ignored because session is not waiting to start`),!1)}handleAddModalityFailure(e,t){if(this.logger.info(`[${t}][handleAddModalityFailure]`),!this.checkState("handleAddModalityFailure",[this.FSM_STATES.CONTENT_SHARING_START_INITIATED,this.FSM_STATES.CONTENT_SHARING_CONNECTED]))return!1;if(!e.modalityFailure||!e.modalityFailure.contentSharing)return this.addTelemetryOperation(ho,{causeId:t,skipReason:"no content sharing blob"}),!1;const i=e.modalityFailure.contentSharing;this.addTelemetryOperation(ho,{reason:i,causeId:t});const n={...i};return this.sendTelemetryData(n),this.rejectPendingPromise(n.phrase,n),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_MODALITY),!0}handleStartFromRoster(e,t){this.logger.info(`[${t}][handleStartFromRoster]`),this.addTelemetryOperation(lo,{causeId:t})}handleStopFromRoster(e,t){this.logger.info(`[${t}][handleStopFromRoster]`),this.addTelemetryOperation(co,{causeId:t}),this.sendTelemetryData(e)}handleStop(e,t){if(this.logger.info(`[${t}][handleStop]`),this.isSelfInitiatedAction(e))return this.logger.info(`[${t}][handleStop]handleStop skipped because session was ended by self`),!1;const i={...e.contentSharingTransactionEnd};return this.addTelemetryOperation(oo,{causeId:t}),this.sendTelemetryData(i),!0}handleUpdate(e,t){return this.logger.info(`[${t}][handleUpdate]`),e.sequenceNumber<=this.lastUpdateSequenceNumber?(this.logger.info(`handleUpdate skipped because of old sequence number: last received ${this.lastUpdateSequenceNumber}, update contained ${e.sequenceNumber}`),this.addTelemetryOperation(so,{causeId:t,skipReason:"old sequence number"}),!1):(this.lastUpdateSequenceNumber=e.sequenceNumber,this.isPresenter=e.presenter.id===this.signalingSession.participantManager.localParticipant.id,this.addTelemetryOperation(so,{causeId:t}),!0)}dispose(e,t){this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.rejectPendingPromise("call ended",e||{code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED}),this.addTelemetryOperation(qs,{causeId:t}),this.sendTelemetryData(e)}rejectPendingPromise(e,t){this.logger.info("rejectPendingPromise");const i=new Error(e);t&&(i.endCode=t),this.removeSessionPromise&&(this.removeSessionPromise.reject(i),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.reject(i),this.addSessionPromise=null)}resolvePendingPromise(e){this.logger.info("resolvePendingPromise");let t=null;e&&(t={sessionId:e.sessionId,correlationId:e.contentSharingCorrelationId,contentIdentifier:e.identifier,presenter:e.presenter.id,subject:e.subject||null,sessionState:e.sessionState||null}),this.removeSessionPromise&&(this.removeSessionPromise.resolve(t),this.removeSessionPromise=null),this.addSessionPromise&&(this.addSessionPromise.resolve(t),this.addSessionPromise=null)}processStartOrJoinSuccess(e){this.logger.info("processStartOrJoinSuccess"),this.sessionId=e.sessionId,this.fsmState=this.FSM_STATES.CONTENT_SHARING_CONNECTED,this.lastUpdateSequenceNumber=-1,this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER]=e.links.contentSharingController,this.links[Jr.LINKS.CONTENT_SHARING_TAKE_CONTROL]=e.links.takeControl,this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_SESSION_STATE]=e.links.updateSessionState,this.links[Jr.LINKS.CONTENT_SHARING_UPDATE_PARTICIPANT_STATE]=e.links.sync,this.links[Jr.LINKS.CONTENT_SHARING_NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[Jr.LINKS.CONTENT_SHARING_LEAVE]=e.links.leave}checkState(e,t,i){let n;if(n="string"==typeof t?this.fsmState===t:t.indexOf(this.fsmState)>-1,n)return!0;{const n=`${e} requires state ${t}, but state is ${this.fsmState}`;return this.logger.error(n),i&&i.reject(n),!1}}isSelfInitiatedAction(e){return e.presenter.participantId===this.signalingSession.participantManager.localParticipant.participantId}startContentSharingTimer(e){this.logger.info("startContentSharingTimer"),this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.ADD_MODALITY,(()=>{this.addTelemetryOperation(qa,{causeId:e}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_MODALITY),this.rejectPendingPromise("timed out waiting for ContentSharing to start",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT})}),Jr.TIMEOUT_VALUES_IN_SECONDS.ADD_MODALITY_TIMEOUT)}addTelemetryOperation(e,t){return this.signalingSession.telemetryHelper.addContentSharingOperation(this.correlationId,e,t)}updateTelemetryOperation(e,t){this.signalingSession.telemetryHelper.updateContentSharingOperation(this.correlationId,e,t)}sendTelemetryData(e){this.signalingSession.telemetryHelper.sendContentSharingTelemetryData(this.correlationId,this.signalingSession.sessionId,this.isPresenter,e,this.links[Jr.LINKS.CONTENT_SHARING_CONTROLLER],this.sessionId)}},iu=class{constructor(e,t){this.contentSharingToStartCallWith=null,this.contentSharingSessions={},this.DEFAULT_STOP_REASON={code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.REMOTE_USER_INITIATED},this.DEFAULT_STOP_ID="8:unknown",this.deleteContentSharingAsync=(e,t)=>{this.logger.info(`[${t}][deleteContentSharingAsync]`);const i=Ta();let n=this.contentSharingSessions[e];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===e&&(n=this.pendingSessionToStart),n){const r=()=>{this.contentSharingSessions[e]&&delete this.contentSharingSessions[e]};n.delete(i,t).then(r,r)}else this.rejectBecauseOfMissingSession(e,i);return i.promise},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>"[ContentSharingManager]")),this.lastProcessedSequenceNumber=-1,this.lastProcessedSequenceNumberForParticipant={}}startContentSharingAsync(e,t,i,n,r,a,s){if(this.logger.info(`startContentSharingAsync called for: ${e}`),this.pendingSessionToStart){const e="There is already a ContentSharing session start pending";return this.logger.error(e),Promise.reject(new Error(e))}const o={contentIdentifier:e,subject:i||null,sessionState:t||null,sequenceNumber:1},l=Ta(),c=new tu(this.signalingSession,s||ra());return this.pendingSessionToStart=c,r?(this.logger.info("Call connected, send content sharing request out immediately"),c.start(n,o,l,a)):(this.logger.info("Content sharing is to be started when startOutgoingCall is called"),c.addSessionPromise=l,c.fsmState=Jr.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED,this.contentSharingToStartCallWith=o),l.promise.then((()=>{this.contentSharingSessions.hasOwnProperty(c.correlationId)||(this.contentSharingSessions[c.correlationId]=c),this.pendingSessionToStart=null})).catch((()=>{this.pendingSessionToStart=null})),l.promise}joinContentSharingAsync(e,t){this.logger.info(`[${t}][joinContentSharingAsync]`);const i=Ta(),n=this.contentSharingSessions[e];return n?n.join(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingSessionStateAsync(e,t,i){this.logger.info(`[${i}][updateContentSharingSessionStateAsync][sessionState=${JSON.stringify(t)}]`);const n=Ta(),r=this.contentSharingSessions[e];return r?r.updateSessionState(t,n,i):this.rejectBecauseOfMissingSession(e,n),n.promise}takeContentSharingControlAsync(e,t){this.logger.info(`[${t}][takeContentSharingControlAsync]`);const i=Ta(),n=this.contentSharingSessions[e];return n?n.takeControl(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingParticipantStateAsync(e,t){this.logger.info(`[${t}][updateContentSharingParticipantStateAsync]`);const i=Ta(),n=this.contentSharingSessions[e];return n?n.updateParticipantState(i,t):this.rejectBecauseOfMissingSession(e,i),i.promise}updateContentSharingNotificationLinksAsync(e){this.logger.info(`[${e}][updateContentSharingNotificationLinksAsync]`);for(const t of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(t)){const i=this.contentSharingSessions[t];i&&i.updateNotificationLinks(e)}}getContentSharingInfoToStartSharing(){if(this.contentSharingToStartCallWith){const e=this.pendingSessionToStart,t=Jr.CONTENT_SHARING_FSM_STATE.CONTENT_SHARING_START_INITIATED;e&&e.fsmState===t||(this.contentSharingToStartCallWith=null,this.pendingSessionToStart=null)}return this.contentSharingToStartCallWith}dispose(e,t){this.logger.info(`[${t}][dispose]`);for(const i of Object.keys(this.contentSharingSessions))if(this.contentSharingSessions.hasOwnProperty(i)){const n=this.contentSharingSessions[i];n&&n.dispose(e,t)}}handleContentSharingUpdate(e){const t=e.body,i=ya(e),n=this.contentSharingSessions[t.contentSharingCorrelationId];n?n.handleUpdate(t,i)&&this.signalingSessionCallback.onContentSharingUpdated({sessionId:t.sessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:t.presenter.id,subject:t.subject||null,sessionState:t.sessionState||null},i):this.logger.info(`[${i}][handleContentSharingUpdate][failed][reason=no session with correlation ID ${t.correlationId}]`)}handleAddModalitySuccess(e,t){this.logger.info(`[${t}][handleAddModalitySuccess]`);const i=this.pendingSessionToStart;i?i.handleAddModalitySuccess(e,t):this.logger.info(`[${t}][handleAddModalitySuccess]Ignoring handleAddModalitySuccess because not waiting for one`)}handleAddModalityFailure(e,t){this.logger.info(`[${t}][handleAddModalityFailure]`);const i=this.pendingSessionToStart;i?i.handleAddModalityFailure(e,t):this.logger.info(`[${t}][handleAddModalityFailure]Ignoring handleAddModalityFailure because not waiting for one`)}handleIncomingContentSharingFromRoster(e,t,i){if(this.logger.info(`[${i}] handleIncomingContentSharingFromRoster: isFullRoster ${t} content ${Ne(e)}`),("MultiPartyEndpoint"===e.type||t)&&this.lastProcessedSequenceNumber>e.sequenceNumber)return void this.logger.info(`[${i}] handleIncomingContentSharingFromRoster invalid roster current sequenceNumber ${e.sequenceNumber} lastProcessedSequenceNumber ${this.lastProcessedSequenceNumber}`);const{sessionsWithPresenters:n,sessionsWithoutPresenters:r}=this.parseContentSharingSessionsFromRoster(e);this.startSessionsFromRoster(n,i),this.stopSessionsFromRoster(r,i),this.lastProcessedSequenceNumber=e.sequenceNumber}handleContentSharingEnd(e){const t=e.body,i=ya(e);this.logger.info("handleContentSharingEnd : ",Ne(t));const n=this.contentSharingSessions[t.contentSharingCorrelationId];if(!n)return void this.logger.info("Ignoring contentSharingEnd since there is no corresponding sharing ongoing");if(!n.handleStop(t,i))return;const r={...t.contentSharingTransactionEnd};this.raiseContentSharingStopped(t.contentSharingCorrelationId,i,t.presenter.id,r)}parseContentSharingSessionsFromRoster(e){const t={},i={},n=new Set;for(const i of Object.keys(e.participants)){const r=e.participants[i];if("Delta"===e.type&&this.lastProcessedSequenceNumberForParticipant.hasOwnProperty(i)&&r.version<=this.lastProcessedSequenceNumberForParticipant[i])continue;if(r.version=r.version||-1,this.lastProcessedSequenceNumberForParticipant[i]=r.version,n.add(r.details.id),!r.endpoints)continue;const a=this.signalingSession.participantManager.localParticipant.participantId;for(const e of Object.keys(r.endpoints)){const i=r.endpoints[e],n=i?.contentSharing?.sessionInformation;"presenter"===n?.role&&(t[n.contentSharingCorrelationId]={presenterId:r.details.id,sessionInfo:n,selfEndpointIsPresenter:i.participantId===a})}}for(const e of Object.keys(this.contentSharingSessions))!t[e]&&n.has(this.contentSharingSessions[e].presenterMri)&&(i[e]=this.contentSharingSessions[e]);return{sessionsWithPresenters:t,sessionsWithoutPresenters:i}}stopSessionsFromRoster(e,t){this.logger.info(`[${t}][stopSessionsFromRoster]`);for(const i of Object.keys(e))this.logger.info(`[${t}][stopSessionsFromRoster] stopping session with correlationId ${i}`),this.stopSession(e[i],t)}stopSession(e,t){this.logger.info(`[${t}][stopSession] Stopping session ${e.sessionId}`),e.handleStopFromRoster(this.DEFAULT_STOP_REASON,t),this.raiseContentSharingStopped(e.correlationId,t)}startSessionsFromRoster(e,t){this.logger.info(`[${t}][startSessionsFromRoster]`);for(const i of Object.keys(e)){this.logger.info(`[${t}][startSessionsFromRoster]`);const n=this.contentSharingSessions[i],r=e[i];if(this.pendingSessionToStart&&this.pendingSessionToStart.correlationId===i?this.pendingSessionToStart.confirmInRoster():n&&n.confirmInRoster(),n)n&&(this.contentSharingSessions[i].presenterMri=r.presenterId,this.logger.info(`[${t}][startSessionsFromRoster]Session ${i} is already present locally`));else{if(r.selfEndpointIsPresenter){this.logger.info(`[${t}][startSessionsFromRoster]This endpoint is presenting, dont fire callback`);continue}this.logger.info(`[${t}][startSessionsFromRoster]New sharing session found. Raising ContentSharingStarted`),this.raiseContentSharingStarted(r.presenterId,r.sessionInfo,t).handleStartFromRoster(r.presenterId,t)}}}raiseContentSharingStopped(e,t,i,n){this.logger.info(`[${t}][raiseContentSharingStopped]`),this.signalingSessionCallback.onContentSharingStopped({sessionId:this.contentSharingSessions[e].sessionId,correlationId:e,endedBy:i||this.DEFAULT_STOP_ID,reason:n||this.DEFAULT_STOP_REASON},t),delete this.contentSharingSessions[e]}raiseContentSharingStarted(e,t,i){this.logger.info(`[${i}][raiseContentSharingStarted]`);const n=new tu(this.signalingSession,t.contentSharingCorrelationId,t.contentSharingSessionId,{[Jr.LINKS.CONTENT_SHARING_CONTROLLER]:t.contentSharingController});n.presenterMri=e,this.contentSharingSessions[n.correlationId]=n;const r={sessionId:t.contentSharingSessionId,correlationId:t.contentSharingCorrelationId,contentIdentifier:t.identifier,presenter:e,subject:t.subject||null,sessionState:t.sessionState||null};return this.signalingSessionCallback.onContentSharingStarted(r,i),n}rejectBecauseOfMissingSession(e,t){const i=`There is no ContentSharing session with the correlation ID ${e}`;this.logger.error(i),t&&t.reject(new Error(i))}},nu={Default:{retryIntervalsMs:[200,1e3,5e3],maxRequestAttempts:4,perRequestTimeoutMs:45e3,perAttemptTimeoutMs:15e3,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4,hedgeDelayMs:4e3},BrokerSubscribe:{retryIntervalsMs:[100,200,500],maxRequestAttempts:4,perRequestTimeoutMs:3e4,perAttemptTimeoutMs:3e4,perRequestTimeoutWithHedgingMs:45e3,perAttemptTimeoutWithHedgingMs:3e4}},ru={CallSetup:{requestHedgingCapability:["disabled"],hedgeDelayMs:4e3},Other:{requestHedgingCapability:["disabled"]},BrokerSubscribe:{requestHedgingCapability:["disabled"]}},au="HttpRequestDispatcherFactory";function su(e,t,i){t?.signalingSession?t.signalingSession.telemetryHelper?.addTokenTelemetry(e,t?.tokenTelemetryData):i?.info("[reportTokenTelemetryData] signaling session is not available, cannot send token telemetry")}function ou(e,t){const{signalingSession:i,operation:n,causeId:r,data:a,customHeaders:s={},forceFetchToken:o,tokenRequestOptions:l}=e;if(i.disposed)return Promise.reject("Session already disposed");const c=e=>{const t="string"==typeof e?new Error(e):e;throw i.signalingAgent.clientSupportsGenericTokenAPI?e.timeOut?t.tokenTimeoutError=!0:t.tokenError=!0:t.skypeTokenError=!0,t};let d=!1;const u={signalingSession:i,tokenTelemetryData:{}};return i.signalingAgent.authTokenManager.getToken(r,o,l,u).catch((n=>(su(e.requestId,u,t),!o&&function(e){const t=ba(e.signalingAgentConfig.trouterServiceProvider);return 3===t||1===t}(i)&&i.signalingAgentConfig.attemptHttpRequestWithCachedSkypetoken&&i.signalingAgent.authTokenManager.getLastToken(r)?(d=!0,Promise.resolve(i.signalingAgent.authTokenManager.getLastToken(r))):(t?.info(`[${r}] getToken failed with error ${n}`),c(n))))).then((o=>{if(i.disposed)throw new Error("token returned too late. Object is already disposed");su(e.requestId,u,t);const l=new Qr;if(l.set(Jr.HEADERS.CORRELATION_ID,i.correlationId),l.set(Jr.HEADERS.MESSAGE_ID,function(e){return e&&/^[a-z0-9]{8}$/.test(e)?e+ra().substr(8):ra()}(r)),l.set(Jr.HEADERS.CLIENT_USER_AGENT,i.signalingAgentConfig.clientInformation),i.signalingAgent.clientSupportsGenericTokenAPI){const e=i.signalingAgent.authTokenManager.getLastTokenType(r);switch(i.signalingAgentConfig.disableTokenMigrationHeader||l.set(Jr.HEADERS.TOKEN_MIGRATION,"True"),e){case 8:case 4:l.set(Jr.HEADERS.AUTHORIZATION,`${Jr.HEADERS.BEARER_KEYWORD} ${o}`),l.delete(Jr.HEADERS.SKYPE_TOKEN);break;case 1:l.set(Jr.HEADERS.SKYPE_TOKEN,o),l.delete(Jr.HEADERS.AUTHORIZATION);break;default:throw new Error(`Error in RequestBuilder. TokenType ${e} is not supported`)}}else l.set(Jr.HEADERS.SKYPE_TOKEN,o);const c=i.participantManager.localParticipant;c&&(c.ring&&l.set(Jr.HEADERS.RING,c.ring),c.region&&l.set(Jr.HEADERS.REGION,c.region),c.partition&&l.set(Jr.HEADERS.PARTITION,c.partition));const h=a?.payload?JSON.stringify(a.payload):null,p={headers:{...l?.getAll(),...s},payload:h,usedCachedSkypetoken:d,reporting:{serviceName:n?`${au}-${n}`:au}};return i.telemetryHelper.addNetworkOperationStarted(n),p})).catch(c)}var lu=class{constructor(e,t,i,n,r,a,s,o,l){this.causeId=e,this.logger=t,this.dispatcher=i,this.requestType=n,this.url=r,this.request=a,this.onRequestFailed=s,this.authRequiredCallback=o,this.settings=l,this.requestsSent=0,this.otherAttemptSuccessful=!1,this.pendingAttempts=[],this.hedgeDelayMs=3e3,this.hedgeMaxParallelAttempts=3,this.stopStandardRetryTimer=()=>{this.standardRetryTimer&&(this.standardRetryTimer.stop(),this.standardRetryTimer=null)},this.stopHedgeTimer=()=>{this.hedgeTimer&&(this.hedgeTimer.stop(),this.hedgeTimer=null)},this.stopAttemptTimeoutTimer=e=>{try{e.timeoutTimer&&(e.timeoutTimer.stop(),this.logger.info("attempt timer stopped"))}catch(e){this.logger.info(`stopAttemptTimeoutTimer error ${e}`)}},this.stopRequestTimer=()=>{try{this.requestTimer&&(this.requestTimer.stop(),this.logger.info("Request timer stopped"))}catch(e){this.logger.info(`stopRequestTimer error ${e}`)}this.requestTimer=null},this.canScheduleNextAttempt=()=>{if(this.stackError===Jr.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful||this.requestsSent>=this.settings.maxRequestAttempts)return this.logger.info(`canScheduleNextAttempt stack error ${this.stackError} otherAttemptSuccessful ${this.otherAttemptSuccessful} exceeded max attempt ${this.requestsSent>=this.settings.maxRequestAttempts}`),!1;if(this.settings.enableRequestHedging){const e=this.pendingAttempts.length<this.hedgeMaxParallelAttempts;return e||this.logger.info(`canScheduleNextAttempt enableRequestHedging attempts sent: ${this.pendingAttempts.length} max attempts: ${this.hedgeMaxParallelAttempts}`),e}{const e=this.requestsSent<this.settings.retryIntervalsMs.length;return e||this.logger.info(`canScheduleNextAttempt attempts sent: ${this.requestsSent} max attempts: ${this.settings.retryIntervalsMs.length}`),e}},this.scheduleNextRequest=e=>{this.settings.enableRequestHedging?(this.logger.info("scheduleNextRequest with hedging"),this.hedgeTimer=Hd.build((()=>{this.attempt(),this.canScheduleNextAttempt()&&this.scheduleNextRequest(!1)}),"HEDGE").start(this.getNextDelay(e))):(this.logger.info("scheduleNextRequest with retry"),this.standardRetryTimer=Hd.build((()=>{this.attempt()}),"RETRY").start(this.getNextDelay(e)))},this.standardizeFailedRequest=(e,t)=>{let i;const n=this.logger.createChild("[standardizeFailedRequest]");try{if(this.stackError===Jr.HTTP_STACK_ERROR.REQUEST_TIMEOUT)n.info("request timed out"),i=Ir.REQUEST_TIMEOUT;else if(this.stackError===Jr.HTTP_STACK_ERROR.REQUEST_ABORTED)n.info("request aborted"),i=Ir.REQUEST_ABORTED;else if(t&&t.status===Jr.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT)n.info("request attempt timed out"),i=Ir.ATTEMPT_TIMEOUT;else if(t&&[Jr.HTTP_STACK_ERROR.ATTEMPT_ABORTED,Jr.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL].indexOf(t.status)>-1)n.info("request attempt aborted"),i=Ir.ATTEMPT_ABORTED;else if(e){if(n.info(`request ${Le(e)}`),"function"==typeof XMLHttpRequest&&e instanceof XMLHttpRequest)i=e;else if("function"==typeof XMLHttpRequest&&e&&e.request instanceof XMLHttpRequest){const t=e;i={response:{...t?.request?.response,headers:t.response?.headers},status:t.request.status,statusText:t.request.statusText,readyState:t.request.readyState}}else e.status||e.statusCode||e.response?i={response:e.response,status:[void 0,null,""].indexOf(e.status)>-1?e.statusCode:e.status,statusText:e.statusText,readyState:e.readyState}:(n.info("Local http stack error"),i={response:Jr.CALL_END_SUB_CODE.LOCAL_HTTP_STACK_ERROR,status:Jr.CALL_END_CODE.LOCAL_HTTP_STACK_ERROR,statusText:"LocalHTTPStackError",readyState:e.readyState||0});this.isBrowserOffline()&&0===i.status&&4===i.readyState&&(n.info("offline"),i={response:Jr.HTTP_STACK_ERROR.CANNOT_CONNECT,status:Jr.HTTP_STATUS_CODES.OFFLINE,statusText:"offline",readyState:i.readyState}),e.response?.message&&(e.response.message.operationFailure||e.response.message.broadcastOperationFailure)?i={response:e.response.message}:!e.response&&e.body?.operationFailure&&(i={response:e.body})}else n.info("no response"),i={response:Jr.HTTP_STACK_ERROR.NONE,status:Jr.HTTP_STATUS_CODES.OTHER,statusText:"Empty Response",readyState:0}}catch(e){n.info(`Failed to handle error ${e}`),i={response:"",status:Jr.HTTP_STATUS_CODES.OTHER,statusText:"FailedToHandleError",readyState:0}}return i},this.hasPendingAttempts=()=>this.pendingAttempts.some((e=>e.pending)),this.getRequestFromStatus=e=>e&&e.request&&e.request.status||0,this.isBrowserOffline=()=>navigator&&!1===navigator.onLine,this.logger=t.createChild(`[${this.causeId}][Dispatcher]`),this.logger.info(`created request, url=${r}`),!isNaN(this.settings.hedgeDelayMs)&&this.settings.hedgeDelayMs>=500&&this.settings.hedgeDelayMs<=1e4&&(this.hedgeDelayMs=this.settings.hedgeDelayMs),!isNaN(this.settings.hedgeMaxParallelAttempts)&&this.settings.hedgeMaxParallelAttempts>=0&&this.settings.hedgeMaxParallelAttempts<=4&&(this.hedgeMaxParallelAttempts=this.settings.hedgeMaxParallelAttempts),(isNaN(this.settings.perAttemptTimeoutMs)||this.settings.perAttemptTimeoutMs<=0)&&(this.settings.perAttemptTimeoutMs=15e3),(isNaN(this.settings.perRequestTimeoutMs)||this.settings.perRequestTimeoutMs<=0)&&(this.settings.perRequestTimeoutMs=45e3),(isNaN(this.settings.maxRequestAttempts)||this.settings.maxRequestAttempts<=0)&&(this.settings.maxRequestAttempts=4),(isNaN(this.settings.perRequestTimeoutWithHedgingMs)||this.settings.perRequestTimeoutWithHedgingMs<=0)&&(this.settings.perRequestTimeoutWithHedgingMs=45e3),(isNaN(this.settings.perAttemptTimeoutWithHedgingMs)||this.settings.perAttemptTimeoutWithHedgingMs<=0)&&(this.settings.perAttemptTimeoutWithHedgingMs=3e4)}sendRequest(){this.stackError=Jr.HTTP_STACK_ERROR.NONE;return this.logger.info("send api called"),this.requestTimer=Hd.build((()=>{this.stackError=Jr.HTTP_STACK_ERROR.REQUEST_TIMEOUT,this.cancelAllAttempts(Jr.HTTP_STACK_ERROR.REQUEST_TIMEOUT)}),"REQUEST_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perRequestTimeoutWithHedgingMs:this.settings.perRequestTimeoutMs),new Promise(((e,t)=>{this.resolve=e,this.reject=t,this.scheduleNextRequest(!0)}))}cancelRequest(){this.logger.info("cancelRequest"),this.stackError=Jr.HTTP_STACK_ERROR.REQUEST_ABORTED,this.cancelAllAttempts(Jr.HTTP_STACK_ERROR.ATTEMPT_ABORTED)}cancelOtherAttempts(e){this.pendingAttempts.splice(e-1,1),this.cancelAllAttempts(Jr.HTTP_STACK_ERROR.ABORTED_OTHER_ATTEMPT_SUCCESSFUL)}cancelAllAttempts(e){this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.pendingAttempts.forEach((t=>{t.status=e,t.cancelDeferred.resolve(),this.stopAttemptTimeoutTimer(t)})),this.stopRequestTimer()}getRequestMethod(e){switch(e){case 0:return this.dispatcher.getAsync.bind(this.dispatcher);case 1:return this.dispatcher.postAsync.bind(this.dispatcher);case 2:return this.dispatcher.putAsync.bind(this.dispatcher);case 3:return this.dispatcher.removeAsync.bind(this.dispatcher);default:return null}}async queueAttempt(e){const t=e&&this.isNotRetryable(e);if(this.logger.info("queueAttempt"),t||!this.canScheduleNextAttempt())return this.logger.info(`unable to retry isNotRetryable ${t} ${JSON.stringify(e)}`),this.stopHedgeTimer(),this.stopRequestTimer(),void(this.hasPendingAttempts()||(this.settings.reportPreviousErrorsForTimeout&&e===Ir.ATTEMPT_TIMEOUT&&this.previousAttempt?this.reject(this.previousAttempt):this.reject(e)));if(this.isAuthFailedStatus(e)){this.logger.info("auth failed"),this.stopHedgeTimer(),this.stopStandardRetryTimer(),this.stopRequestTimer();try{const t=e?.response?.headers,i=function(e){const t=Qr.getHeaderValue(e,Jr.HEADERS.SKYPE_TOKEN);if(t)return t;const i=Qr.getHeaderValue(e,Jr.HEADERS.AUTHORIZATION);if(i){const e=i.split(" ");if(2===e.length)return e[1]}}(this.request?.headers),n=await this.authRequiredCallback(t,i);this.request=n}catch(t){return void this.reject(e)}}this.previousAttempt=e,this.hedgeTimer?this.logger.info("scheduleNextRequest ignored as there's already active hedge timer"):this.scheduleNextRequest(!1)}attempt(){if(this.logger.info("attempt to send request"),this.stackError===Jr.HTTP_STACK_ERROR.REQUEST_ABORTED||this.otherAttemptSuccessful)return;const e=(new Date).getTime();this.requestsSent++;const t=this.requestsSent,i=Ta();this.request.timeout=i.promise;const n={cancelDeferred:i,status:Jr.HTTP_STACK_ERROR.NONE,timeoutTimer:null,pending:!0},r=Hd.build((()=>{n.status=Jr.HTTP_STACK_ERROR.ATTEMPT_TIMEOUT,n.cancelDeferred.resolve()}),"ATTEMPT_TIMEOUT").start(this.settings.enableRequestHedging?this.settings.perAttemptTimeoutWithHedgingMs:this.settings.perAttemptTimeoutMs);n.timeoutTimer=r,this.pendingAttempts.push(n),this.getRequestMethod(this.requestType)(this.url,this.request).then((i=>{if(this.logger.info(`attempt successful, request response=${Ad.scrubDisplayNamesFromResponse(i)} status=${this.getRequestFromStatus(i)}`),this.otherAttemptSuccessful)throw"Other attempt succesful";if(this.stackError===Jr.HTTP_STACK_ERROR.REQUEST_ABORTED)throw"Session disposed";if(!i)throw"Invalid response";n.pending=!1,this.otherAttemptSuccessful=!0,this.stopRequestTimer(),this.stopHedgeTimer(),this.stopAttemptTimeoutTimer(n),this.cancelOtherAttempts(t),this.resolve({success:!0,request:i.request,response:i.response,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()})})).catch((t=>{n.pending=!1,this.stopAttemptTimeoutTimer(n);const i=this.standardizeFailedRequest(t,n);this.logger.info(`attempt failed, request: ${Le(t)} status=${i.status}`),this.onRequestFailed({abandoned:this.otherAttemptSuccessful,success:!1,request:i,attempt:this.requestsSent,attemptStartTimestamp:e,attemptResponseTimestamp:(new Date).getTime()}),this.queueAttempt(i)}))}getNextDelay(e){let t;if(e)t=0;else if(this.settings.enableRequestHedging)t=this.hedgeDelayMs;else{if(!(this.requestsSent<=this.settings.retryIntervalsMs.length))throw"Unable to get next delay";t=this.settings.retryIntervalsMs[this.requestsSent-1]}return this.logger.info(`next delay= ${t} ms`),t}isRequestWithStatus(e,t){return!!e&&t.indexOf(e.status)>-1}isNotRetryable(e){return!Ia(e&&e.status)}isAuthFailedStatus(e){return this.isRequestWithStatus(e,[Jr.HTTP_STATUS_CODES.UNAUTHORIZED])}},cu={1:"POST",0:"GET",2:"PUT",3:"DELETE"},du=class{constructor(e,t){this.signalingSession=e,this.callStartTime=t,this.pendingRequests={},this.sendGetRequest=e=>this.sendRequest(0,e),this.sendPostRequest=e=>this.sendRequest(1,e),this.sendPutRequest=e=>this.sendRequest(2,e),this.sendDeleteRequest=e=>this.sendRequest(3,e),this.cancelRequestIfPending=(e,t,i,n)=>{this.logger.info(`[${t}][cancelRequestIfPending]`),this.pendingRequests[e]?i?this.hasPendingRequest(e,i)&&this.cancelRequest(e,i,t,n):Object.keys(this.pendingRequests[e]).forEach((i=>this.cancelRequest(e,i,t,n))):this.logger.info(`[${t}][cancelRequestIfPending]no pending request with name=${e}`)},this.cancelAllRequests=e=>{this.logger.info(`[${e}][cancelAllRequests]`);const t=[];return Object.keys(this.pendingRequests).forEach((i=>{Object.keys(this.pendingRequests[i]).forEach((n=>{t.push(this.cancelRequest(i,n,e))}))})),Promise.all(t).catch((()=>{}))},this.hasPendingRequest=(e,t)=>!!this.pendingRequests[e]&&Boolean(t?this.pendingRequests[e][t]:this.pendingRequests[e]),this.cancelRequest=(e,t,i,n)=>{try{return this.pendingRequests[e][t].dispatcher&&this.pendingRequests[e][t].dispatcher.cancelRequest(),this.pendingRequests[e][t].aborted=!0,this.pendingRequests[e][t].errorDetails=n,this.logger.info(`[${i}][cancelRequest]Request=${e} aborted ${n?`with errorDetails ${JSON.stringify(n)}`:""}`),this.pendingRequests[e][t].requestPromise.catch((()=>{}))}catch(n){return this.logger.warn(`[${i}][cancelRequest]Unable to cancel request=${e}, requestId=${t}`),Promise.resolve()}},this.buildRequestTelemetry=(e,t,i,n)=>({name:`${cu[e]}-${t.requestName}`,url:t.url,eventStart:i-this.callStartTime,trouterReady:-1,requestReady:-1,status:-1,attempts:[],rtt:-1,uid:t.requestId,causeId:t.causeId,requestDispatcherConfig:n,enableRequestHedging:this.shouldEnableRequestHedging(n)}),this.addPendingRequest=e=>(this.pendingRequests[e.requestName]||(this.pendingRequests[e.requestName]={}),this.pendingRequests[e.requestName][e.requestId]={dispatcher:null,requestPromise:null,aborted:!1},this.pendingRequests[e.requestName][e.requestId]),this.sendRequest=(e,t)=>{if(!t.url){this.logger.error(t.requestName,"Link does not exist");const e={code:Jr.CALL_END_CODE.HTTP_OTHER_ERROR,subCode:Jr.CALL_END_SUB_CODE.MISSING_REQUEST_URI,phrase:`Link does not exist for requestName: ${t.requestName}.`};return Promise.reject(e)}t.requestId||(t.requestId=ra()),t.causeId||(t.causeId=na());const i=this.logger.createChild(`[${t.causeId}][${t.requestName}]`);i.info("[scheduled]");const n=this.getInternalHttpDispatcherConfig(t.requestName,t.operationType);let r;t.skipHttpTelemetry||(t.skipHttpTelemetry=!1);const a=eu(),s=(new Date).getTime(),o=[],l=this.buildRequestTelemetry(e,t,s,n),c=()=>{this.signalingSession.disposed?this.logger.info("Unable to record telemetry, session disposed"):this.signalingSession.telemetryHelper.updateNetworkRequest(l)},d=()=>{this.signalingSession.telemetryHelper.deleteNetworkRequest(l)};c();const u=(e,n)=>{if(!e?.request)return void this.logger.warn(t.requestName,"missing request details, unable to record for telemetry!");i.info(`[finished][status=${e.request.status}][statusText=${e.request.statusText}][retryCount=${e.attempt}]`);const r={status:e.request.status,statusSubCode:e.request.response?.operationFailure?.subCode,start:e.attemptStartTimestamp-s,end:e.attemptResponseTimestamp-s,online:ba(this.signalingSession.signalingAgentConfig.trouterServiceProvider)};e.abandoned&&(r.abandoned=!0),e.request.statusText&&(r.statusText=e.request.statusText),(n||-1===l.status)&&(l.status=e.request.status),l.attempts.push(r),c()};if(this.hasPendingRequest(t.requestName,t.requestId))return this.logger.warn(t.requestName,t.requestId,"is already pending request!!"),this.pendingRequests[t.requestName][t.requestId].requestPromise;r=this.addPendingRequest(t);const h=(e,n,r,s)=>{if(e&&t.skipHttpTelemetry)return this.logger.info("Skipping telemetry"),void d();i.info(`[steps=${o}]`),this.pendingRequests[t.requestName][t.requestId].aborted&&(l.aborted=!0),this.hasPendingRequest(t.requestName,t.requestId)?(delete this.pendingRequests[n][r],Object.keys(this.pendingRequests[n]).length||delete this.pendingRequests[n]):this.logger.warn("Unable to clean up!"),this.signalingSession.disposed||(s&&(l.error=s),l.rtt=a.duration(),this.signalingSession.telemetryHelper.addNetworkOperationCompleted(t.requestName,e,a.duration()),c(),this.signalingSession.telemetryHelper.sendHttpTelemetryData(l.uid))},p=e=>(...n)=>{if(this.signalingSession.disposed){const e=`[${t.causeId}][${t.requestName}][failed][reason=Session disposed]`;throw i.info("[failed][reason=Session disposed]"),new Error(e)}if(this.hasPendingRequest(t.requestName,t.requestId)&&this.pendingRequests[t.requestName][t.requestId].aborted){let e;const n=`[${t.causeId}][${t.requestName}][failed][reason=request already aborted]`,r=this.pendingRequests[t.requestName][t.requestId].errorDetails;throw r?(e=r,e.phrase=n):e=n,i.info(`${n}`),new Error(JSON.stringify(e))}return e(...n)},g=p((()=>(o.push("[waitForTrouter]"),t.withoutTrouter?Promise.resolve():this.signalingSession.ensureMessageChannelReady(t.requestName)))),m=p((()=>(o.push("[trouterReady]"),l.trouterReady=a.duration(),t.onceTrouterReady&&t.onceTrouterReady(),c(),Promise.resolve()))),f=p((()=>{const i=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,n=Aa(this.signalingSession.signalingAgentConfig,i,e,t,!1,void 0,this.logger);return o.push("[buildRequest]"),ou({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,tokenRequestOptions:n,requestId:t.requestId},this.logger)})),v=p((e=>{o.push("[failedToBuildRequestOptions]");const t={request:{status:Jr.HTTP_STATUS_CODES.OTHER,statusText:"Local error"},attempt:1,success:!1,attemptResponseTimestamp:(new Date).getTime(),attemptStartTimestamp:(new Date).getTime()};return e&&(e.skypeTokenError?t.request={status:Jr.CALL_END_SKYPE_TOKEN_ERROR.code,statusText:Jr.CALL_END_SKYPE_TOKEN_ERROR.phrase}:e.tokenError?t.request={status:Jr.CALL_END_TOKEN_ERROR.code,statusText:Jr.CALL_END_TOKEN_ERROR.phrase}:e.tokenTimeoutError&&(t.request={status:Jr.CALL_END_TOKEN_TIMEOUT_ERROR.code,statusText:Jr.CALL_END_TOKEN_TIMEOUT_ERROR.phrase})),u(t,!1),Promise.reject(e)})),S=p((e=>(o.push("[requestBuilt]"),l.requestReady=a.duration(),e.usedCachedSkypetoken&&(l.usedCachedSkypetoken=e.usedCachedSkypetoken),c(),Promise.resolve(e)))),y=(i,n)=>{o.push("[authRequired]");const r=this.signalingSession.signalingAgent.clientSupportsGenericTokenAPI,a=Aa(this.signalingSession.signalingAgentConfig,r,e,t,!0,i,this.logger);return a.invalidToken=n,ou({signalingSession:this.signalingSession,operation:t.requestName,data:t.payload,customHeaders:t.customHeaders?.getAll(),causeId:t.causeId,forceFetchToken:!0,tokenRequestOptions:a,requestId:t.requestId},this.logger)},C=p((i=>{o.push("[sendRequest]");const a={...n,enableRequestHedging:this.shouldEnableRequestHedging(n),hedgeDelayMs:n.hedgeDelayMs,hedgeMaxParallelAttempts:this.signalingSession.signalingAgentConfig.hedgeMaxParallelAttempts,retryIntervalsMs:t.disableRetry||!n.retryIntervalsMs?[]:n.retryIntervalsMs,reportPreviousErrorsForTimeout:this.signalingSession.signalingAgentConfig.reportPreviousErrorsForTimeout},s=function(e){return new lu(e.causeId,e.logger,e.dispatcher,e.requestType,e.url,e.request,e.attemptFailureCallback,e.authRequiredCallback,e.settings)}({logger:this.logger,causeId:t.causeId,dispatcher:this.signalingSession.signalingAgentConfig.httpRequestDispatcher,url:t.url,request:i,requestType:e,authRequiredCallback:y,attemptFailureCallback:e=>{u(e,!1)},settings:a});return r.dispatcher=s,c(),s.sendRequest()})),_=p((async e=>(u(e,!0),i.info("[success]"),h(!0,t.requestName,t.requestId),e))),E=Promise.resolve().then(g).then(m).then(f).catch(v).then(S).then(C).then(_).catch((e=>{const n=Ne(e);return h(!1,t.requestName,t.requestId,n),!e||e.readyState||e.status?i.info(`[failed][reason=${n}]`):i.info(`[failed][offline][reason=${n}]`),Promise.reject(e)}));return r.requestPromise=E,E},this.logger=this.signalingSession.logger.createChild("[HTTP]")}getInternalHttpDispatcherConfig(e,t="Other"){let i={...nu.Default,...ru[t],...nu[e]};return this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.operationTypeHttpDispatcherConfigMap[t]}),this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap&&(i={...i,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap.Default,...this.signalingSession.signalingAgentConfig.requestTypeHttpDispatcherConfigMap[e]}),this.logger.info(`getInternalHttpDispatcherConfig request type: ${e} config: ${Le(i)}`),i}shouldEnableRequestHedging(e){return!!(this.signalingSession.getMeetingInfo()&&e.requestHedgingCapability.indexOf("enabledForMeetings")>-1)||!this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForP2PCalls")>-1||!!(this.signalingSession.multiParty&&e.requestHedgingCapability.indexOf("enabledForGroupCalls")>-1)||e.requestHedgingCapability.indexOf("enabled")>-1}};function uu(e,t,i){oa(e,"signalingSession cannot be null");let n=[];i&&(n=ca(i),e.telemetryHelper.addOutgoingModalities(n));const r=na();return{payload:{mediaNegotiation:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAnswer:Zr(e,Ar.MEDIA_ANSWER,r),rejection:Zr(e,Ar.MEDIA_REJECTION,r)},mediaContent:t}}}}function hu(e,t){return oa(e,"signalingSession cannot be null"),la(t),{payload:{mediaNegotiationFailure:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},code:t.code,subCode:t.subCode,phrase:t.phrase},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}function pu(e,t,i){oa(e,"signalingSession cannot be null");let n=[];return i&&(n=ca(i),e.telemetryHelper.addOutgoingModalities(n)),{payload:{mediaAnswer:{callModalities:n,sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},links:{mediaAcknowledgement:Zr(e,Ar.MEDIA_ACKNOWLEDGEMENT)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t},debugContent:{callId:e.correlationId,endpointId:e.participantManager.localParticipant.endpointId}}}}var gu=class{constructor(e,t,i){this.telemetryHelper=i,this.vbssInitiated=!1,this.disposed=!1,this.fsmState=Jr.MEDIA_RENEGOTIATION_FSM_STATE.IDLE,this.fsmStateCauseId="",this.links={},this.renegotiationOffersSeenSoFar=[],this.isOutgoingRenegotiationInProgress=()=>this.fsmState===Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION||this.fsmState===Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.isIncomingRenegotiationInProgress=()=>this.fsmState===Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION||this.fsmState===Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,this.acceptRenegotiationAsync=(e,t,i)=>{this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.signalingSession.telemetryHelper.recordEvent(ja,{mediaTypes:t,causeId:i}),sa(this.links[Jr.LINKS.MEDIA_ANSWER],"MediaAnswer link not set");const n=Ta();switch(this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,i);break;default:return this.logger.info(`[${i}][acceptRenegotiationAsync]there is no incoming media renegotiation offer to accept`),n.reject(new Error("there is no incoming media renegotiation offer to accept")),n.promise}return this.signalingSession.http.sendPostRequest({url:this.links[Jr.LINKS.MEDIA_ANSWER],payload:pu(this.signalingSession,e,t),requestName:sd.SEND_MEDIA_ANSWER.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT,this.handleMediaAnswerAcknowledgmentTimeout.bind(this,i),Jr.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_ACKNOWLEDGEMENT_TIMEOUT)},causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=fa(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][acceptRenegotiationAsync] error: ${Ne(t)}`),this.disposed||this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),n.reject(new Error(`acceptRenegotiationAsync failed because : ${Ne(e)}`))})),n.promise},this.startRenegotiationAsync=(e,t,i,n)=>{this.logger.info(`[${n}][startRenegotiationAsync][mediaTypes=${i}]`),this.signalingSession.telemetryHelper.recordEvent(za,{causeId:n,mediaTypes:i}),sa(t,"MediaRenegotiation link not set");const r=Ta();switch(this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,n);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:case Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed with no current outstanding renegotiations, previous negotiation causeId=${this.fsmStateCauseId}`),this.signalingSessionCallback.onMediaRenegotiationRejection(this.getGlareError(),n),Promise.resolve(null);default:return this.logger.info(`[${n}][startRenegotiationAsync][failed] can only be performed on an established call`),r.reject(new Error("media renegotiation can only be performed on an established call")),r.promise}const a=i&&ha(i,Jr.MEDIA_TYPES.SCREEN_SHARER);a?(this.vbssInitiated=!0,this.signalingSession.telemetryHelper.addVbssOperations(yd.START)):!a&&this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(yd.STOP));return this.signalingSession.http.sendPostRequest({url:t,payload:uu(this.signalingSession,e,i),requestName:sd.START_RENEGOTIATION.name,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER,this.handleMediaAnswerTimeout.bind(this),Jr.TIMEOUT_VALUES_IN_SECONDS.MEDIA_ANSWER_TIMEOUT)},causeId:n}).then((e=>{r.resolve(e.response)})).catch((e=>{const t=fa(e,this.signalingSession.signalingAgentConfig);if(this.logger.info(`[${n}][startRenegotiationAsync] error: ${Ne(t)}`),!this.disposed){switch(this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,n);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n)}this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER)}r.reject(new Error(`startRenegotiationAsync failed because : ${Ne(e)}`))})),r.promise},this.handleMediaAcknowledgment=(e,t)=>{this.signalingSession.telemetryHelper.recordEvent(La,{causeId:t}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT),this.signalingSession.saveMediaControllerLinksIfAny(e),this.signalingSession.saveUpdatedCallLinksIfAny(e),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!0,t)},this.onCallConnected=e=>{this.logger.info("onCallConnected"),this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,e)},this.handleMediaNegotiationFailure=e=>{const t=ya(e);this.signalingSession.telemetryHelper.recordIncomingEvent(xa,e),this.handleMediaNegotiationFailureInternal(e.body.mediaNegotiationFailure,e.origin,t)},this.handleMediaAnswer=(e,t)=>{switch(this.logger.info(`[${t}][handleMediaAnswer]`),this.signalingSession.telemetryHelper.recordEvent(Fa,{causeId:t}),this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,t);break;default:return}this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER);let i=[];e.mediaAnswer.callModalities&&e.mediaAnswer.callModalities.length>0&&(i=ca(e.mediaAnswer.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i));const n={provisional:!1,renegotiation:!0,mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaAnswer.mediaContent),mediaContent:e.mediaAnswer.mediaContent};this.signalingSession.http.sendPostRequest({url:e.mediaAnswer.links.mediaAcknowledgement,payload:null,requestName:sd.SEND_MEDIA_ACKNOWLEDGEMENT.name,causeId:t}).catch((e=>{const i=fa(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${t}][handleMediaAnswer] error: ${Ne(i)}`),this.signalingSession.disposed||this.signalingSession.telemetryHelper.recordEvent(Ua,{causeId:t})})),this.signalingSessionCallback.onAnswer(n,t)},this.handleMediaNegotiationOffer=e=>{const t=e.body,i=e.headers,n=ya(e);this.logger.info(`[${n}][handleMediaNegotiationOffer]`),this.signalingSession.telemetryHelper.recordIncomingEvent(Ba,e);const r=va(i,this.renegotiationOffersSeenSoFar);switch(this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE,n),this.raiseMediaRenegotiationOffer(t,n);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,n),this.raiseMediaRenegotiationOffer(t,n);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:if(this.signalingSession&&this.signalingSession.signalingAgentConfig&&this.signalingSession.signalingAgentConfig.supportMediaRetargetWhileIncomingRenegotiation){this.raiseMediaRenegotiationOffer(t,n);break}this.rejectAndLog(n,r,t);break;default:this.rejectAndLog(n,r,t)}},this.rejectRenegotiationAsync=(e,t)=>{this.logger.info(`[${t}][rejectRenegotiationAsync]`),this.signalingSession.telemetryHelper.recordEvent(Va,{rejectionData:e,causeId:t}),sa(this.links[Jr.LINKS.MEDIA_REJECTION],"MediaRejection link not set");const i=e||{code:Jr.CALL_END_CODE.NOT_ACCEPTABLE_HERE,subCode:Jr.CALL_END_SUB_CODE.MEDIA_ANSWER_PROCESSING_ERROR,phrase:Jr.CALL_END_PHRASE.MEDIA_ANSWER_ERROR};switch(this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION:return this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,t),this.rejectMediaRenegotiation(this.links[Jr.LINKS.MEDIA_REJECTION],i,t);case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:return this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION,t),this.rejectMediaRenegotiation(this.links[Jr.LINKS.MEDIA_REJECTION],i,t);default:return this.logger.error(`[${t}][rejectRenegotiationAsync][failed] There is no incoming media renegotiation offer to reject`),Promise.resolve(null)}},this.handleRetargetCompleted=e=>{const t=e.body.retargetCompleted,i=ya(e);this.logger.info(`[${i}][handleRetargetCompleted][details=${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(Ha,e,De(t)),0===t.code?this.signalingSessionCallback.onReTargetCompletedSuccess(i):this.signalingSessionCallback.onReTargetCompletedFailure(t,i)},this.dispose=()=>{this.logger.info("mediaRenegotiationManager :: dispose"),this.disposed=!0},this.getGlareError=()=>({code:Jr.CALL_END_CODE.GLARE_ERROR,subCode:Jr.CALL_END_SUB_CODE.MEDIA_GLARE_ERROR,phrase:Jr.CALL_END_PHRASE.RENEGOTIATION_IN_PROGRESS,previousNegotiationCauseId:this.fsmStateCauseId}),this.handleMediaNegotiationFailureInternal=(e,t,i)=>{switch(this.logger.info(`[${i}][handleMediaNegotiationFailureInternal][failureData=${De(e)}]`),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.fsmState){case Jr.MEDIA_RENEGOTIATION_FSM_STATE.OUTGOING_RENEGOTIATION:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.CALL_CONNECTED,i);break;case Jr.MEDIA_RENEGOTIATION_FSM_STATE.RENEGOTIATION_GLARE:this.setFsmState(Jr.MEDIA_RENEGOTIATION_FSM_STATE.INCOMING_RENEGOTIATION,i);break;default:return}this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(yd.REJECTED)),this.signalingSession.telemetryHelper.addIncomingModalities(["Rejected"]),this.signalingSessionCallback.onMediaRenegotiationRejection({code:e.code,subCode:e.subCode,phrase:e.phrase},i)},this.signalingSession=e,this.signalingSessionCallback=t,this.logger=e.logger.createChild((()=>`[RenegotiationManager][${this.fsmState}][stateCauseId=${this.fsmStateCauseId}]`))}rejectAndLog(e,t,i){this.logger.error(`[${e}][handleMediaNegotiationOffer] Cannot handle the incoming mediaRenegotiation offer in present callstate. Either call not connected or renegotiation in progress. isDuplicateOffer=${t}`),t||this.rejectMediaRenegotiation(i.mediaNegotiation.links.rejection,this.getGlareError(),e)}setFsmState(e,t){this.fsmState=e,this.fsmStateCauseId=t,this.logger.info(`[setFsmState]state=${e}`),this.telemetryHelper.recordEvent(Wa,{state:e,causeId:t})}raiseMediaRenegotiationOffer(e,t){this.logger.info(`[${t}][raiseMediaRenegotiationOffer]`),this.links[Jr.LINKS.MEDIA_ANSWER]=e.mediaNegotiation.links.mediaAnswer,this.links[Jr.LINKS.MEDIA_REJECTION]=e.mediaNegotiation.links.rejection;let i=[];e.mediaNegotiation.callModalities&&e.mediaNegotiation.callModalities.length>0&&(i=ca(e.mediaNegotiation.callModalities),this.signalingSession.telemetryHelper.addIncomingModalities(i),ha(i,Jr.MEDIA_TYPES.SCREEN_SHARER)&&this.signalingSession.telemetryHelper.addVbssOperations(yd.REMOTE_START));const n={mediaTypes:i,remoteParticipantId:this.signalingSession.getParticipantIdForOfferAnswer(e.mediaNegotiation.mediaContent),mediaContent:e.mediaNegotiation.mediaContent,renegotiation:!0};this.signalingSessionCallback.onOffer(n,t)}rejectMediaRenegotiation(e,t,i){this.logger.info(`[${i}][rejectMediaRenegotiation][rejectionData=${De(t)}]`);const n=Ta();return this.signalingSession.http.sendPostRequest({url:e,payload:hu(this.signalingSession,t),requestName:sd.SEND_MEDIA_REJECTION.name,causeId:i}).then((e=>{n.resolve(e.response)})).catch((e=>{const t=fa(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][rejectMediaRenegotiation] error: ${Ne(t)}`),n.reject(new Error(`rejectMediaRenegotiation failed because : ${Ne(e)}`))})),n.promise}handleMediaAnswerTimeout(e){this.logger.info(`[${e}][handleMediaAnswerTimeout]`),this.vbssInitiated&&(this.vbssInitiated=!1,this.signalingSession.telemetryHelper.addVbssOperations(yd.TIMEOUT)),this.signalingSession.telemetryHelper.addIncomingModalities(["Timeout"]),this.signalingSession.telemetryHelper.recordEvent($a),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER),this.handleMediaNegotiationFailureInternal({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.MEDIA_FINAL_ANSWER_TIMEOUT,phrase:Jr.CALL_END_PHRASE.MEDIA_FINAL_ANSWER_TIMEOUT},od.LOCAL,e)}handleMediaAnswerAcknowledgmentTimeout(e){this.logger.info(`[${e}][handleMediaAnswerAcknowledgmentTimeout]`),this.signalingSession.telemetryHelper.recordEvent(Ga),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MEDIA_ANSWER_ACKNOWLEDGEMENT);this.signalingSessionCallback.onMediaAcknowledgementFailure(!0,{reason:"timed out waiting for Media Answer Acknowledgement"},e)}},mu=class{constructor(){this.requests={}}clear(e,t){const i=t||{code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED};Object.keys(this.requests).forEach((t=>{this.rejectOperation(t,e,i)}))}hasOperation(e){return this.requests.hasOwnProperty(e)}getAllOperations(){return this.requests}getOperation(e){return this.hasOperation(e)?this.requests[e]:null}setOperation(e,t){return!this.hasOperation(e)&&(this.requests[e]=t,!0)}rejectOperation(e,t,i){const n=new Error(t);if(i&&(n.endCode=i),this.hasOperation(e)){const t=this.requests[e].promise;delete this.requests[e],t.reject(n)}}resolveOperation(e,t){if(this.hasOperation(e)){const i=this.requests[e].promise;delete this.requests[e],i.resolve(t)}}},fu=class{constructor(e){this.logger=e,this.localAddParticipantRequests=new mu,this.localAdmitParticipantRequests=new mu,this.localCallMeBackRequests=new mu,this.localRemoveParticipantEndpointRequests=new mu,this.localRemoveParticipantRequests=new mu,this.localUpdateParticipantInterpretationStateRequest=new mu,this.participantIdMriMap=new Map}dispose(e,t,i){this.logger.info(`[${i}][dispose]`),this.rejectAllPendingOperations(e,t)}getAllPendingOperations(e,t){this.logger.info(`[${t}][getAllPendingOperations] ${e}`);const i=this.getOperationTable(e);return i?i.getAllOperations():null}getPendingOperation(e,t,i){this.logger.info(`[${i}][getPendingOperation] ${e} ${t}`);const n=this.getOperationTable(e);return n?n.getOperation(t):null}getRnlMri(e,t){this.logger.info(`[${t}][getRnlMri] ${e}`);for(const t of e)if(this.participantIdMriMap.has(t))return this.participantIdMriMap.get(t);return""}hasPendingOperation(e,t,i){this.logger.info(`[${i}][hasPendingOperation] ${e} ${Ae(t)}`);const n=this.getOperationTable(e);return!!n&&n.hasOperation(t)}rejectPendingOperation(e,t,i,n,r){this.logger.info(`[${r}][rejectPendingOperation] ${e} ${Ae(t)} reason: ${i}`);const a=this.getOperationTable(e);a&&a.rejectOperation(t,i,n)}resolvePendingOperation(e,t,i,n){this.logger.info(`[${n}][resolvePendingOperation]: ${Ae(t)}`);const r=this.getOperationTable(e);r&&r.resolveOperation(t,i)}setPendingOperation(e,t,i,n){this.logger.info(`[${n}][setPendingOperation] ${e} ${Ae(t)} value: ${i}`);const r=this.getOperationTable(e);if(!r)return!1;if(0===e){const e=i&&i.participant&&i.participant.participantId;e&&this.participantIdMriMap.set(e,t)}return r.setOperation(t,i)}setParticipantIdToMriMapping(e,t,i,n){n?(this.logger.info(`[${i}][setParticipantIdMriMap] ${Pe(e)}: ${Ae(t)} clear mapping.`),this.participantIdMriMap.delete(e)):e&&t&&(this.logger.info(`[${i}][setParticipantIdMriMap] ${Pe(e)}: ${Ae(t)}`),this.participantIdMriMap.set(e,t))}getOperationTable(e){switch(e){case 0:return this.localAddParticipantRequests;case 1:return this.localAdmitParticipantRequests;case 2:return this.localCallMeBackRequests;case 4:return this.localRemoveParticipantEndpointRequests;case 3:return this.localRemoveParticipantRequests;case 5:return this.localUpdateParticipantInterpretationStateRequest;default:return null}}rejectAllPendingOperations(e,t){this.logger.info("rejectLocalQueuedOperations"),this.localAddParticipantRequests.clear(e,t),this.localAdmitParticipantRequests.clear(e,t),this.localCallMeBackRequests.clear(e,t),this.localRemoveParticipantRequests.clear(e,t),this.localRemoveParticipantEndpointRequests.clear(e,t),this.localUpdateParticipantInterpretationStateRequest.clear(e,t)}};function vu(e,t,i,n){oa(e,"signalingSession cannot be null");const r=i.groupId?{id:i.groupId}:null,a=i.threadId?{threadId:i.threadId,messageId:i.messageId||null}:null;let s=[],o={};t&&t.length>0?(s=t.map((t=>({id:t.nonMaskedId?t.nonMaskedId:t.id,assertedId:t.assertedId,displayName:t.displayName,participantId:t.participantId,replacementDetails:3===i.replacementType?e.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,t.id,t.replacementParticipantId):void 0}))),o={addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE)}):o={addModalitySuccess:Zr(e,Ar.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Zr(e,Ar.CONV_ADD_MODALITY_FAILURE)};const l={payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:s},participantInvitationData:i.additionalData,replacementDetails:3===i.replacementType?void 0:n,groupContext:r,groupChat:a,links:o}};return i&&i.alternateId&&(l.payload.participants.from.alternateId=i.alternateId),i?.clientScenario&&(l.payload.debugContent={clientScenario:i.clientScenario}),l}function Su(e,t,i){return oa(e,"signalingSession cannot be null"),oa(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{admitFailure:Zr(e,Ar.CONV_ADMIT_PARTICIPANT_FAILURE),admitSuccess:Zr(e,Ar.CONV_ADMIT_PARTICIPANT_SUCCESS)},debugContent:{causeId:i}}}}function yu(e,t,i){return oa(e,"signalingSession cannot be null"),oa(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,toEndpoints:[{id:t.id,endpointId:t.endpointId}]},links:{removeParticipantSuccess:Zr(e,Ar.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Zr(e,Ar.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function Cu(e,t){return oa(e,"signalingSession cannot be null"),oa(t,"remoteParticipant cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},to:[{id:t.id,displayName:t.displayName}]},links:{removeParticipantSuccess:Zr(e,Ar.CONV_REMOVE_PARTICIPANT_SUCCESS),removeParticipantFailure:Zr(e,Ar.CONV_REMOVE_PARTICIPANT_FAILURE)}}}}function _u(e,t,i,n=""){oa(i&&"specified"===i,"Only non-null non-empty scope of 'specified' is supported."),oa(e,"signalingSession cannot be null"),oa(t,"participantsIds cannot be null");const r=[];return t.forEach((e=>{const t={id:e,meetingRole:n};r.push(t)})),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:i,to:r}}}var Eu=f(g),Tu=class{constructor(e,t){this.participantManager=e,this.logger=t,this.setStaleCheckForFullRoster=e=>{this.checkStaleRosterFromFull=e},this.handleRosterUpdate=(e,t,i,n)=>{if("Delta"===e.type||"MultiPartyEndpoint"===e.type){if(void 0===e.sequenceNumber&&(e.sequenceNumber=this.lastRosterUpdateSeqNumber),this.logger.info(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}]`),this.rostersInLifetime.add(e.sequenceNumber),"Delta"===e.type)this.logger.info(`[${n}][handleRosterUpdate], RosterType: Delta, isFullRoster: ${i}`),this.handleDeltaRoster(e,i,t,n);else{if(this.logger.info(`[${n}][handleRosterUpdate], RosterType: MultiPartyEndpoint`),this.isRosterStale(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(il,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const i of Object.keys(e.participants)){const r=Na.fromRoster(e.participants[i]);this.handleRosterParticipant(r,t,n)}this.checkForRemovedParticipants(t,e.participants,n),this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n)}if(e.sequenceNumber>this.lastRosterUpdateSeqNumber){this.checkStaleRosterFromFull&&this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n),this.lastRosterUpdateSeqNumber=e.sequenceNumber,this.firstRosterUpdateSeqNumber<0&&(this.firstRosterUpdateSeqNumber=this.lastRosterUpdateSeqNumber);const t=Object.keys(e.participants||0).length;this.participantCountInFirstRoster<0&&(this.participantCountInFirstRoster=t),this.maxConcurrentParticipantsDuringLeg=Math.max(this.maxConcurrentParticipantsDuringLeg,t)}this.recordTelemetry(e,i,n),this.participantManager.signalingSessionCallback.onRosterHandlingComplete()}else this.logger.warn(`[${n}][handleRosterUpdate][sequenceNumber=${e.sequenceNumber}] invalid roster type ${e.type}`)},this.isRosterStaleFromFull=(e,t)=>!!this.checkStaleRosterFromFull&&(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastFullRosterSeqNumber}`),e.sequenceNumber<this.lastFullRosterSeqNumber),this.isRosterStale=(e,t)=>(this.logger.info(`[${t}][isRosterStale] ${e.sequenceNumber<this.lastRosterUpdateSeqNumber}`),e.sequenceNumber<this.lastRosterUpdateSeqNumber),this.updateLocalParticipantFromSubscribe=(e,t)=>{this.logger.info(`[${t}][updateLocalParticipantFromSubscribe]`),this.updateLocalParticipant(e,t)},this.handleParticipantAcceptedBy=(e,t,i)=>{const n=t.hasOwnProperty(e.id),r=e.id===e.acceptedBy.id;this.logger.info(`[${i}][RosterManager::handleParticipantAcceptedBy] oldParticipantInRoster: ${n}`),this.participantManager.participantOperationHandler.setParticipantIdToMriMapping(e.participantId,e.id,i,!0),n&&!r&&this.handleRemovedDeltaRosterParticipant(new Na({id:e.id}),this.lastRosterUpdateSeqNumber,t,i)},this.lastRosterUpdateSeqNumber=-1,this.lastFullRosterSeqNumber=-1,this.firstRosterUpdateSeqNumber=-1,this.tombstoneSequence=new Map,this.latestRosterVersionForActiveParticipants=new Map,this.rostersInLifetime=new Set,this.maxConcurrentParticipantsDuringLeg=-1,this.participantCountInFirstRoster=-1,this.checkStaleRosterFromFull=!1}recordTelemetry(e,t,i){const n={participantCountInLastRoster:Object.keys(e.participants||0).length,participantCountInFirstRoster:this.participantCountInFirstRoster,sequenceNumberOfLastRoster:this.lastRosterUpdateSeqNumber,sequenceNumberOfLastFullRoster:this.lastFullRosterSeqNumber,sequenceNumberOfFirstRoster:this.firstRosterUpdateSeqNumber,rosterType:e.type,isFullRoster:t,maxConcurrentParticipantsDuringLeg:this.maxConcurrentParticipantsDuringLeg,totalParticipantsDuringLifetimeOfLeg:this.tombstoneSequence.size+this.latestRosterVersionForActiveParticipants.size,countOfMissingNotifications:this.getMissingNotificiations()};this.logger.info(`[recordTelemetry] data ${JSON.stringify(n,null,4)}`),this.participantManager.signalingSession.telemetryHelper.recordRosterEvent(n,Ss,i)}getMissingNotificiations(){const e=this.lastRosterUpdateSeqNumber-this.firstRosterUpdateSeqNumber+1-this.rostersInLifetime.size;return e>0?e:0}isParticipantRosterStale(e,t){if(this.logger.info(`[isParticipantRosterStale], rosterParticipantVersion ${t}`),t){if(this.tombstoneSequence.has(e))return t<=this.tombstoneSequence.get(e);if(this.latestRosterVersionForActiveParticipants.has(e))return t<=this.latestRosterVersionForActiveParticipants.get(e)}return!1}handleDeltaRoster(e,t,i,n){if(this.logger.info(`[${n}][handleDeltaRoster] isFullRoster ${t}`),this.isRosterStaleFromFull(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(il,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,lastFullRosterSeqNumber:this.lastFullRosterSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled full roster ${this.lastFullRosterSeqNumber}`);if(t){if(!this.checkStaleRosterFromFull&&this.isRosterStale(e,n))return this.participantManager.signalingSession.telemetryHelper.recordEvent(il,{lastRosterUpdateSeqNumber:this.lastRosterUpdateSeqNumber,sequenceNumber:e.sequenceNumber,causeId:n}),void this.logger.info(`[${n}][handleRosterUpdate] Ignoring old roster update: received ${e.sequenceNumber}, but already handled ${this.lastRosterUpdateSeqNumber}`);for(const t of Object.keys(i))if(!(e.participants.hasOwnProperty(t)||this.checkStaleRosterFromFull&&this.isParticipantRosterStale(t,e.sequenceNumber))){const r=new Na({id:t});this.logger.info(`[${n}][handleRosterUpdate] participant missing from delta, full roster`),this.handleRemovedDeltaRosterParticipant(r,e.sequenceNumber,i,n)}this.lastFullRosterSeqNumber=e.sequenceNumber}else if(!e?.participants)return void this.logger.warn(`[${n}][handleRosterUpdate] participants blob empty in delta roster`);for(const t of Object.keys(e.participants)){const r=e.participants[t];if(!this.isParticipantRosterStale(t,r.version)){let e=Na.fromRoster(r);r.state&&"active"===r.state?(this.logger.info(`[${n}][handleDeltaRoster] participant active`),this.handleRosterParticipant(e,i,n),this.tombstoneSequence.has(t)&&this.tombstoneSequence.delete(t),this.latestRosterVersionForActiveParticipants.set(t,r.version)):r.state&&"inactive"===r.state?(e=e||new Na({id:r.details.id}),this.logger.info(`[${n}][handleDeltaRoster] participant inactive`),this.handleRemovedDeltaRosterParticipant(e,r.version,i,n)):this.logger.info(`[${n}][handleDeltaRoster] unexpected participant state ${r.state}`)}}this.handleRemoveParticipantRequests(this.getActiveParticipants(e.participants),n),this.checkStaleRosterFromFull||this.participantManager.signalingSessionCallback.onParticipantCountsUpdated(e.participantCounts,n)}getRnlMri(e,t){const i=this.participantManager.participantOperationHandler;if(e){const n=this.getRnlParticipantIdsFromRoster(e,t);return i.getRnlMri(n,t)}return""}handleRemovedDeltaRosterParticipant(e,t,i,n){const r=e.id,a=this.getRnlMri(e,n);let s="";i.hasOwnProperty(r)?s=r:i.hasOwnProperty(a)&&(s=a),s&&this.handleRemovedParticipant(i,s,n),this.tombstoneSequence.set(r,t),this.latestRosterVersionForActiveParticipants.has(r)&&this.latestRosterVersionForActiveParticipants.delete(r)}handleRemovedParticipant(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession;!1!==e[t]&&(ga(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][handleRemovedParticipant] ${Ae(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t))}getActiveParticipants(e){const t={};for(const i of Object.keys(e))"inactive"!==e[i].state&&(t[i]=e[i]);return t}handleRosterParticipant(e,t,i){if(!e)return void this.logger.info(`[handleRosterParticipant][${i}] rosterParticipant processing skipped because null.`);if(e.id===this.participantManager.localParticipant.id){this.updateLocalParticipant(e,i);const t=this.getLocalEndpoint(),n=!(!t?.stream&&!t?.streamLobby),r=0===this.participantManager.signalingSession.callMode;return this.logger.info(`[handleRosterParticipant][${i}] isStreaming:${n} isInitialMode:${r}`),void(n&&r?this.participantManager.signalingSession.configureStreamingMode(i):n||this.participantManager.signalingSession.setRealTimeState(1,i))}const n=this.participantManager.participantOperationHandler,r=this.participantManager.signalingSession,a=this.participantManager.signalingSessionCallback,s=e.id,o=this.getRnlMri(e,i),l=this.getRnlParticipantIdsFromRoster(e,i);r.remoteCaller&&-1!==l.indexOf(r.remoteCaller.participantId)&&(e.displayName=r.remoteCaller.displayName),pa(this.participantManager.connectedRemoteParticipantIds,e.id,!0);const c=t.hasOwnProperty(e.id),d=t.hasOwnProperty(o);(c||d)&&(t[e.id]=!1),n.hasPendingOperation(0,e.id,i)&&this.isParticipantInCall(e)?(this.logger.info(`participant ${Ae(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e.id),n.resolvePendingOperation(0,e.id,e,i)):o&&n.hasPendingOperation(0,o,i)&&this.isParticipantInCall(e)?(this.logger.info(`RNL participant ${Ae(o)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,o),n.resolvePendingOperation(0,o,e,i)):n.hasPendingOperation(1,e.id,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant: ${Ae(e.id)} appears in roster. Resolving AdmitParticipant request`),r.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),n.resolvePendingOperation(1,e.id,e,i));for(const t of e.endpointDetails)n.hasPendingOperation(0,t.participantId,i)&&this.isParticipantInCall(e)&&(this.logger.info(`participant ${Ae(e.id)} appears in roster. Resolving AddParticipant request`),r.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t.participantId),n.resolvePendingOperation(0,t.participantId,e,i));c?(this.logger.info(`participantIds=[${l}] updated ${Ae(e.id)}`),a.onParticipantUpdated(e,i),r.setParticipantCallLinks(e)):d?(this.logger.info(`RNL participant participantIds=[${l}] removed old ${Ae(o)} and added new ${Ae(s)}`),a.onParticipantRemoved({id:o},i,!0),r.clearParticipantCallLinks(o),a.onParticipantJoined(e,i),r.setParticipantCallLinks(e)):n.hasPendingOperation(3,e.id,i)?this.logger.info(`participantIds=[${l}] ignored ${Ae(e.id)}`):(this.logger.info(`participantIds=[${l}] joined ${Ae(e.id)}`),a.onParticipantJoined(e,i),r.setParticipantCallLinks(e))}getLocalEndpoint(){return Eu.find(this.participantManager.localParticipant.endpointDetails,(e=>this.participantManager.localParticipant.endpointId===e.endpointId))}getRnlParticipantIdsFromRoster(e,t){const i=[];for(const t of e.endpointDetails)i.push(t.participantId);return this.logger.info(`[${t}][getRnlParticipantIdsFromRoster] ${JSON.stringify(i)}`),i}isParticipantInCall(e){return e.endpointDetails?.[0]&&!e.endpointDetails[0].isLobby}updateLocalParticipant(e,t){const i=this.participantManager.localParticipant,n=this.participantManager.signalingSession,r=this.participantManager.signalingSessionCallback;n.setParticipantCallLinks(e),this.logger.info(`[${t}][updateLocalParticipant]`);let a=!1;if(e?.endpointDetails){const s=Eu.find(e.endpointDetails,(e=>i.endpointId===e.endpointId)),o=Eu.find(i.endpointDetails,(e=>i.endpointId===e.endpointId));a=Nd(s),s?.isLobby&&!o?.isLobby?n.telemetryHelper.recordEvent(Jo,{causeId:t}):!s||s.isLobby||o&&!o.isLobby||(a?n.telemetryHelper.recordEvent(Yo,{causeId:t}):n.telemetryHelper.recordEvent(Ko,{causeId:t})),s?.broadcastMeetingRole&&i&&i.broadcastMeetingRole!==s.broadcastMeetingRole&&(i.broadcastMeetingRole=s.broadcastMeetingRole,n.telemetryHelper.setBroadcastMeetingRole(s.broadcastMeetingRole)),r.onMeetingGroupDetailsUpdated(s?.meetingGroupDetails,t)}if(e?.meetingRole&&n.telemetryHelper.setMeetingRole(e.meetingRole),e?.advancedMeetingRole&&n.telemetryHelper.setAdvancedMeetingRole(e.advancedMeetingRole),e?.participantType&&n.telemetryHelper.setParticipantType(e.participantType),e&&(i.endpointDetails=e.endpointDetails||[],i.acceptedBy=e.acceptedBy,i.role=e.role,i.meetingRole=e.meetingRole,i.advancedMeetingRole=e.advancedMeetingRole,i.participantType=e.participantType,i.tenantId=e.tenantId,i.isLobby=e.isLobby,i.publishedStates=e.publishedStates,i.isStaging=a,i.version=e.version,i.propertyBag=e.propertyBag,i.isIdentityMasked=e.isIdentityMasked,i.maskedIdSeqNumber=e.maskedIdSeqNumber,i.maskedId=e.maskedId,void 0!==e?.joinAsStreamingUser&&(i.joinAsStreamingUser=e.joinAsStreamingUser),void 0!==e?.enableCaptcha&&(i.enableCaptcha=e.enableCaptcha),this.participantManager.localParticipant.fromRoster=!0,r.onSelfParticipantUpdated(i,t)),this.isParticipantInCall(e)){const i=this.participantManager.participantOperationHandler,r=this.getRnlMri(e,t);r&&i.hasPendingOperation(0,r,t)&&(this.logger.info(`RNL participant ${Ae(r)} appears in roster. Resolving AddParticipant request`),n.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,r),i.resolvePendingOperation(0,r,e,t))}}checkForRemovedParticipants(e,t,i){const n=this.participantManager.signalingSessionCallback,r=this.participantManager.signalingSession,a=this.participantManager.participantOperationHandler;this.logger.info(`[${i}][checkForRemovedParticipants]`);for(const t of Object.keys(e))e.hasOwnProperty(t)&&!1!==e[t]&&!a.hasPendingOperation(0,t,i)&&(ga(this.participantManager.connectedRemoteParticipantIds,t),this.logger.info(`[${i}][checkForRemovedParticipants] ${Ae(t)} removed from roster`),n.onParticipantRemoved({id:t},i),r.clearParticipantCallLinks(t));this.handleRemoveParticipantRequests(t,i)}handleRemoveParticipantRequests(e,t){const i=this.participantManager.signalingSession,n=this.participantManager.participantOperationHandler;this.logger.info(`handleRemoveParticipantRequests [${t}] dynamicRosterParticipants`);const r=[];Object.keys(e).forEach((t=>{const i=Na.fromRoster(e[t]);i&&i.endpointDetails&&i.endpointDetails.forEach((e=>{e.originalId&&r.push(e.originalId)}))}));const a=n.getAllPendingOperations(3,t);for(const s of Object.keys(a))-1!==r.indexOf(s)||e.hasOwnProperty(s)||(this.logger.info(`[${t}][handleRemoveParticipantRequests] ${Ae(s)} no longer appears in roster. Resolving RemoveParticipant request`),ga(this.participantManager.connectedRemoteParticipantIds,s),i.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,s),n.resolvePendingOperation(3,s,{id:s},t))}},bu=class{constructor(e,t,i,n){this.connectedRemoteParticipantIds={},this.disposed=!1,this.unmuteApprovalLinks={},this._asyncMuteUnmuteDefers=new Map,this.muteAsyncEnabled=!1,this.unmuteAsyncEnabled=!1,this.setLocalParticipantId=(e,t)=>{e&&(this.logger.info(`[${t}][setLocalParticipantId][participantId=${e}]`),this.localParticipant.participantId=e,this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId))},this.setStaleCheckForFullRoster=e=>{this.rosterManager.setStaleCheckForFullRoster(e)},this.setEnableMuteAsync=e=>{this.muteAsyncEnabled=e},this.setEnableUnmuteAsync=e=>{this.unmuteAsyncEnabled=e},this.admitParticipantAsync=(e,t,i)=>{const n=`[${i}][admitParticipantAsync]`;this.logger.info(`${n}${this.piiUtils.scrubMriOrOmit(e.id)}`);const r=Ta();return this.participantOperationHandler.hasPendingOperation(1,e.id,i)?(this.logger.info(`${n}there is an existing pending request to admit the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),r.reject(new Error("there is an existing pending request to admit the participant"))):(this.participantOperationHandler.setPendingOperation(1,e.id,{participant:e,promise:r,causeId:i},i),this.sendNetworkRequestForAdmittingParticipant(e,t,i)),r.promise},this.addParticipantsAsync=(e,t,i,n,r)=>{const a=`[${r}][addParticipantsAsync]`,s=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${a} remoteParticipantsIds: ${s}`);const o=[],l=[];return e.forEach((e=>{const t=Ta(),i=3===n.replacementType?e.participantId:e.id;this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`${a}the given participant is already connected to the call ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(0,i,r)?(this.logger.info(`${a}there is an existing pending request to add the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to add the participant"))):(e.participantId||(e.participantId=ra(),this.logger.info(`participantId created ${e.participantId}`)),this.participantOperationHandler.setPendingOperation(0,i,{participant:e,promise:t,causeId:r},r),o.push(e)),l.push(t.promise)})),i&&this.sendNetworkRequestForAddingParticipant(o,t,n,r),l},this.nudgeParticipantsAsync=(e,t,i,n,r,a,s,o)=>(this.logger.info(`[${n}][nudgeParticipantAsync] ${this.piiUtils.scrubParticipantsList(e)}`),i?this.sendNetworkRequestForNudgingParticipants(e,t,n,r,a,s,o):Promise.reject(`[${n}][nudgeParticipantAsync] Call not started`)),this.updateMeetingRolesAsync=(e,t,i,n=na())=>{const r=Ta();if(!e||e.length<1){const e=`[${n}][updateMeetingRolesAsync] participantsInfo cannot be empty or null`,t=new Error(e);t.endCode={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else if(t)if(i){let a;"attendee"===t?a=sd.UPDATE_MEETING_ROLE_ATTENDEE.name:"presenter"===t?a=sd.UPDATE_MEETING_ROLE_PRESENTER.name:"organizer"===t?a=sd.UPDATE_MEETING_ROLE_ORGANIZER.name:r.reject(new Error(`[${n}] Invalid meetingRole value(${t})`)),this.logger.info(`[${n}][updateMeetingRolesAsync][meetingRole=${t}]`),this.signalingSession.ensureMessageChannelReady(a).then((()=>{this.sendNetworkRequestForUpdatingMeetingRoles(e,t,i,a,n,r)})).catch((e=>{const t=Ne(e);this.logger.info(`[${n}][updateMeetingRolesAsync][failed][reason=${t}]`);const i={...fa(e,this.signalingSession.signalingAgentConfig).error};r.reject(i)}))}else{const e=`[${n}][updateMeetingRolesAsync] updateMeetingRoleUrl cannot be empty or null`,t=new Error(e);t.endCode={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}else{const e=`[${n}][updateMeetingRolesAsync] meetingRole cannot be empty or null`,t=new Error(e);t.endCode={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),r.reject(t)}return r.promise},this.updateParticipantInterpretationStateAsync=(e,t,i)=>{const n=`[${i}][updateParticipantInterpretationStateAsync]`,r=e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)));this.logger.info(`${n} remoteParticipantsIds: ${r}`);const a=[],s=[];return e.forEach((e=>{const t=Ta();this.participantOperationHandler.hasPendingOperation(5,e.id,i)?(this.logger.info(`${n}there is an existing pending request to update the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),t.reject(new Error("there is an existing pending request to update the participant"))):(this.participantOperationHandler.setPendingOperation(5,e.id,{option:e,promise:t,causeId:i},i),a.push(e)),s.push(t.promise)})),this.sendNetworkRequestToUpdateParticipantInterpretationState(a,t,e,i),s},this.callMeBackAsync=(e,t,i)=>{this.logger.info(`[${i}][callMeBackAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`);const n=Ta();return this.connectedRemoteParticipantIds.hasOwnProperty(e.id)?(this.logger.info(`the given participant is already connected to the call : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("the given participant is already connected to the call"))):this.participantOperationHandler.hasPendingOperation(2,e.id,i)?(this.logger.info(`there is an existing pending request to call back the participant : ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to call back the participant"))):(this.participantOperationHandler.setPendingOperation(2,e.id,{participant:e,promise:n},i),this.sendNetworkRequestForCallMeBack(e,t,i)),n.promise},this.isRosterStale=(e,t)=>this.rosterManager.isRosterStale(e,t),this.removeParticipantAsync=(e,t,i)=>{this.logger.info(`[${i}][removeParticipantAsync] ${this.piiUtils.scrubMriOrOmit(e.id)}`),sa(t,"correct removeParticipantUrl is not provided");const n=Ta();if(this.participantOperationHandler.hasPendingOperation(3,e.id,i))this.logger.info(`there is an existing pending request to remove the participant ${this.piiUtils.scrubMriOrOmit(e.id)}`),n.reject(new Error("there is an existing pending request to remove the participant"));else{this.participantOperationHandler.setPendingOperation(3,e.id,{participant:e,promise:n},i);const r=()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession.telemetryHelper.recordEvent(ds),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,"timed out waiting for participant to not show up in roster",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:Jr.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},i)}),Jr.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:Cu(this.signalingSession,e),requestName:sd.REMOVE_PARTICIPANT_NONE.name,onceTrouterReady:r,causeId:i}).catch((t=>{const n=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][removeParticipantAsync][failed][reason=${Ne(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(3,e.id,t,n.error,i))}))}return n.promise},this.removeParticipantEndpointAsync=(e,t,i,n)=>{this.logger.info(`[${n}][removeParticipantEndpointAsync] ${xe(e.endpointId)} [endPointScope] ${i}`),sa(t,"correct removeParticipantUrl is not provided");const r=Ta();let a="";switch(i){case"all":a=sd.REMOVE_PARTICIPANT_OTHERS.name;break;case"specified":a=sd.REMOVE_PARTICIPANT_SPECIFIED.name;break;default:return Promise.reject(`invalid scope ${i} removeParticipantEndpointAsync`)}this.participantOperationHandler.setPendingOperation(4,e.endpointId,{participant:e,promise:r,scope:i},n);return this.signalingSession.http.sendPostRequest({url:t,payload:yu(this.signalingSession,e,i),requestName:a,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(ds),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,"timed out waiting for participant endpoint sync response from service",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_PARTICIPANT_REMOVAL_TIMEOUT,phrase:Jr.CALL_END_PHRASE.PARTICIPANT_REMOVAL_TIMEOUT},n))}),Jr.TIMEOUT_VALUES_IN_SECONDS.REMOVE_PARTICIPANT_TIMEOUT,e.endpointId)},causeId:n}).then((e=>{if(e.response?.code)if(-1!==[Jr.HTTP_STATUS_CODES.OK,Jr.HTTP_STATUS_CODES.CREATED].indexOf(e.response.code))this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [passed][reason=${Ne(e.response)}]`),r.resolve(e.response);else{const t=new Error("invalid service response for removeParticipantEndpoint");t.endCode={code:e.response.code,subCode:e.response.subcode,phrase:e.response.reason},this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${Ne(e.response)}]`),r.reject(t)}r.resolve()})).catch((t=>{const r=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][removeParticipantEndpointAsync][endPointScope] ${i} [failed][reason=${Ne(r)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e.endpointId),this.participantOperationHandler.rejectPendingOperation(4,e.endpointId,Ne(t),r.error,n))})),r.promise},this.getParticipantsToInitiateCallWith=()=>{this.logger.info("getParticipantsToInitiateCallWith");const e=[],t=this.participantOperationHandler.getAllPendingOperations(0,na());for(const i of Object.keys(t))t.hasOwnProperty(i)&&t[i]&&e.push(t[i].participant);return e},this.initializeForIncomingCall=e=>{this.logger.info("initializeForIncomingCall"),this.participantOperationHandler.dispose("incoming calls cannot add/remove participants until call is connected",null,na())},this.handleAddParticipantSuccess=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAddParticipantSuccess(${t.participantInfos?"new format":"old format"})]${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(us,e),this.internalHandleCallMeBackSuccess(t,i)||this.signalingSession.telemetryHelper.recordEvent(us),this.signalingSession.signalingAgentConfig.enableAddParticipantEnhancements&&this.internalHandleAcceptedByParticipants(t,i)},this.handleAddParticipantFailure=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAddParticipantFailure(${t.participantInfos?"new format":"old format"})][${Ne(t)}]`),t.modalityFailure?(this.logger.info(`[${i}][handleAddParticipantFailure][modalityFailure=${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(ms,e)):this.internalHandleAddParticipantFailure(e,i)},this.handleAdmitParticipantSuccess=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAdmitParticipantSuccess][${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(ps,e),t.participants&&this.internalHandleAdmitParticipantSuccess(e,i)},this.handleAdmitParticipantFailure=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAdmitParticipantFailure][${Ne(t)}]`),t.participants&&this.internalHandleAdmitParticipantFailure(e,i)},this.handleRemoveParticipantFailure=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleRemoveParticipantFailure][${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(vs,e);for(const e of Object.keys(t.participants))t.participants.hasOwnProperty(e)&&this.internalHandleRemoveParticipantFailure(e,t.participants[e],i)},this.handleRemoveParticipantSuccess=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleRemoveParticipantSuccess][${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(fs,e)},this.handleUnmuteConfirmRequest=e=>{const t=e.body,i=ya(e);this.logger.info(`[${i}][handleUnmuteConfirmRequest][${Ne(t)}]`),this.signalingSession.telemetryHelper.recordIncomingEvent(Co,e),this.unmuteApprovalLinks[t.from.id]={approve:t.links.approveUnmute,reject:t.links.rejectUnmute},this.signalingSessionCallback.onUnmuteRequested(t.from.id,i)},this.approveUnmuteRequestAsync=(e,t)=>{this.logger.info(`[${t}][approveUnmuteRequestAsync]`);const i=Ta();return this.unmuteApprovalLinks.hasOwnProperty(e)?(this.signalingSession.ensureMessageChannelReady(sd.APPROVE_UNMUTE.name).then((()=>{this.muteUnmute(sd.APPROVE_UNMUTE.name,function(e){return oa(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]}}}(this.signalingSession),i,this.unmuteApprovalLinks[e].approve,t)})).catch((e=>{const n=Ne(e);this.logger.info(`[${t}][approveUnmuteRequestAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise):(i.reject(new Error("no unmute links found for given participant")),i.promise)},this.rejectUnmuteRequestAsync=(e,t,i)=>{this.logger.info(`[${t}][rejectUnmuteRequestAsync]`);const n=Ta();if(!this.unmuteApprovalLinks.hasOwnProperty(e))return n.reject(new Error("no unmute links found for given participant")),n.promise;const r=i||{code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UNMUTE_REQUEST_REJECTED,phrase:Jr.CALL_END_PHRASE.UNMUTE_REQUEST_REJECTED};return this.signalingSession.ensureMessageChannelReady(sd.REJECT_UNMUTE.name).then((()=>{this.muteUnmute(sd.REJECT_UNMUTE.name,function(e,t){return oa(e,"signalingSession cannot be null"),la(t),{payload:{transactionEnd:t}}}(this.signalingSession,r),n,this.unmuteApprovalLinks[e].reject,t)})).catch((e=>{const i=Ne(e);this.logger.info(`[${t}][rejectUnmuteRequestAsync][failed][reason=${i}]`),n.reject(new Error(e))})),n.promise},this.handleRosterUpdate=(e,t,i)=>{const n=this.getCurrentParticipantsInCallModality(!1);this.rosterManager.handleRosterUpdate(e,n,t,i)},this.updateLocalParticipantFromSubscribe=(e,t)=>{this.localParticipant.fromRoster||this.rosterManager.updateLocalParticipantFromSubscribe(e,t)},this.muteAsync=(e,t,i,n)=>{this.logger.info(`[${n}][muteAsync][muteScope=${t}]`);let r="specified";const a=[];let s=sd.MUTE_SPECIFIED;switch(t){case Jr.MUTE_SCOPE.MYSELF:s=sd.MUTE_MYSELF,a.push({id:this.localParticipant.id});break;case Jr.MUTE_SCOPE.EVERYONE_ELSE:s=sd.MUTE_ALL_SYNC,r="all",i.forEach((e=>{a.push({id:e})}));break;case Jr.MUTE_SCOPE.SPECIFIED_PARTICIPANTS:sa(i,`[${n}]array of participantIds must be specified for SPECIFIED_PARTICIPANTS mute scope`),s=sd.MUTE_SPECIFIED_SYNC,i.forEach((e=>{a.push({id:e})}));break;default:aa(!1,`[${n}]muteScope is a required param. please pass in a valid value.`)}const o=Ta();if(t===Jr.MUTE_SCOPE.SPECIFIED_PARTICIPANTS){const e=this.areParticipantsConnectedToCall(i);if(!e.result)return o.reject(new Error(`[${n}]specified participant is not connected to call yet. Id = ${e.participant}`)),o.promise}const l=this.muteAsyncEnabled&&(t===Jr.MUTE_SCOPE.SPECIFIED_PARTICIPANTS||t===Jr.MUTE_SCOPE.EVERYONE_ELSE);return this.signalingSession.ensureMessageChannelReady(s.name).then((()=>{this.muteUnmute(s.name,function(e,t,i,n=!1,r=null){oa(e,"signalingSession cannot be null"),oa(t,"muteScope be null"),oa(i,"participantList cannot be null");const a={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t,muteParticipants:i,mediaTypes:["audio"]};return n&&(a.links={clientCallback:Zr(e,Ar.MUTE_UNMUTE_ASYNC,r)},a.operationId=r),{payload:a}}(this.signalingSession,r,a,l,n),o,e,n,!1,l)})).catch((e=>{const t=Ne(e),i=fa(e,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][muteAsync][failed][reason=${t}]`),o.reject(i)})),o.promise},this.unmuteAsync=(e,t)=>{this.logger.info(`[${t}][unmuteAsync]`);const i=Ta();return this.signalingSession.ensureMessageChannelReady(sd.UNMUTE_SYNC.name).then((()=>{this.muteUnmute(sd.UNMUTE_SYNC.name,function(e,t=!1,i=null){oa(e,"signalingSession cannot be null");const n={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaTypes:["audio"]};return t&&(n.links={clientCallback:Zr(e,Ar.MUTE_UNMUTE_ASYNC,i)},n.operationId=i),{payload:n}}(this.signalingSession,this.unmuteAsyncEnabled,t),i,e,t,!0,this.unmuteAsyncEnabled)})).catch((e=>{const n=Ne(e);this.logger.info(`[${t}][unmuteAsync][failed][reason=${n}]`),i.reject(new Error(e))})),i.promise},this.dispose=(e,t)=>{this.logger.info(`[${t}][dispose]`),this.disposed=!0,this.participantOperationHandler.dispose("call ended",e,t),this.signalingSession.telemetryHelper.setParticipantId(this.localParticipant.participantId)},this.handleMuteUnmuteAsyncResponse=e=>{const t=ya(e),i=this.logger.createFnLogger("handleMuteUnmuteAsyncResponse",t);if(!e.body)return void i.error("ignored. Empty message body.");const n={info:e.body.muteUnmuteResponseAsync,operationId:e.body.operationId};if(i.info(`Received async response for mute/unmute operation, operation id = ${n.operationId}.`),this.disposed)return void i.info("ignored. Call disposed.");if(!n.operationId)return void i.error("operationId is undefined.");const r=this._asyncMuteUnmuteDefers.get(n.operationId);r?(r.resolve(n),this._asyncMuteUnmuteDefers.delete(n.operationId)):i.warn(`cannot find deferred promise for operation id [${n.operationId}].`)},this.internalHandleAcceptedByParticipants=(e,t)=>{if(e?.participantInfos){const i=e.participantInfos,n=this.getCurrentParticipantsInCallModality(!1);this.logger.info(`[${t}][internalHandleAcceptedByParticipants] handling participants with acceptedBy blob.`);for(const e of i)if(e?.acceptedBy){const i=e.id;this.participantOperationHandler.hasPendingOperation(0,i,t)&&(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,i),this.logger.info(`[${t}][internalHandleAcceptedByParticipants] ${this.piiUtils.scrubMriOrOmit(i)} added using a different MRI. Resolving operation.`),this.participantOperationHandler.resolvePendingOperation(0,i,void 0,t)),this.rosterManager.handleParticipantAcceptedBy(e,n,t)}}},this.internalHandleCallMeBackSuccess=(e,t)=>{let i=!1;if(e?.participantInfos){const n=e.participantInfos;for(const e of n){const n=e.id;this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0)}}else if(e?.participants)for(const n of e.participants)this.internalHandleCallMeBackSuccessHelper(n,t)&&(i=!0);return i},this.signalingSession=e,this.signalingSessionCallback=t,this.localParticipant=i,this.localParticipant.endpointId||(this.localParticipant.endpointId=this.signalingSession.getEndpointId());const r=xe(this.localParticipant.endpointId);this.logger=n.createChild((()=>`[PM][${r}]`)),this.piiUtils=e.piiUtils,this.participantOperationHandler=new fu(e.logger.createChild((()=>`[ParticipantOperationHandler][${r}]`))),this.rosterManager=new Tu(this,e.logger.createChild((()=>`[RosterManager][${r}]`))),this.localParticipant.participantId||(this.localParticipant.participantId=ra()),"string"==typeof e.signalingAgentConfig.languageCode?this.localParticipant.languageId=e.signalingAgentConfig.languageCode:"function"==typeof e.signalingAgentConfig.languageCode&&(this.localParticipant.languageId=e.signalingAgentConfig.languageCode()),e.telemetryHelper.setParticipantId(this.localParticipant.participantId),e.telemetryHelper.setEndPointId(this.localParticipant.endpointId)}handleUpdateParticipantInterpretationStateCompletion(e){const t=e.body,i=ya(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateParticipantInterpretationStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateParticipantInterpretationStateCompletion] starts`);const r=e.body;if(r.participantInfos)for(const t of r.participantInfos)if(this.logger.info(t),this.participantOperationHandler.hasPendingOperation(5,t.participant.id,i))if(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,t.participant.id),t.transactionEnd.code===Jr.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}]Update participant interpretation state succeeded for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)}`),this.signalingSession.telemetryHelper.recordIncomingEvent(kc,e),this.participantOperationHandler.resolvePendingOperation(5,t.participant.id,void 0,i);else{const n=t.transactionEnd.reason;this.logger.info(`[${i}]Update participant interpretation state failed for: ${this.piiUtils.scrubMriOrOmit(t.participant.id)} reason : ${Ne(n)}`);const r=this.getCallEndGivenParticipantFailure(n);this.signalingSession.telemetryHelper.recordIncomingEvent(Mc,e,r),this.participantOperationHandler.rejectPendingOperation(5,t.participant.id,r.phrase,r,i)}}areParticipantsConnectedToCall(e){this.logger.info(`areParticipantsConnectedToCall : ${Ne(e)}`);const t=this.getCurrentParticipantsInCallModality(!0);for(const i of e)if(!t.hasOwnProperty(i))return this.logger.info(`areParticipantsConnectedToCall : returning false for :${this.piiUtils.scrubMriOrOmit(i)}`),{result:!1,participant:i};return this.logger.info("areParticipantsConnectedToCall : returning true"),{result:!0}}muteUnmute(e,t,i,n,r,a,s=!1){const o=this.logger.createFnLogger("muteUnmute",r);aa(2!==this.signalingSession.callMode,"mute/unmute operations are not allowed in streaming mode"),o.info(`operation=${e}, isAsync=${s}`),n?(a&&this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UNMUTE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(yo),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UNMUTE);const e=new Error("timed out waiting for response to request");e.endCode={code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UNMUTE_REQUEST_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UNMUTE_REQUEST_TIMEOUT},i.reject(e)}}),Jr.TIMEOUT_VALUES_IN_SECONDS.UNMUTE_TIMEOUT),s&&this._asyncMuteUnmuteDefers.set(r,i),this.signalingSession.http.sendPostRequest({url:n,payload:t,requestName:e,withoutTrouter:!0,causeId:r}).then((t=>{if(!this.disposed)if(s)o.info(`Inline response received for async operation, operation id: ${r}.`);else{if(t.response?.muteUnmuteResponse){const n={info:t.response.muteUnmuteResponse,operationId:t.response.operationId};switch(e){case sd.UNMUTE_SYNC.name:case sd.MUTE_ALL_SYNC.name:case sd.MUTE_SPECIFIED_SYNC.name:i.resolve(n)}}i.resolve()}})).catch((e=>{const t=fa(e,this.signalingSession.signalingAgentConfig);o.info(`operation failed, reason=${Ne(t)}`),this.disposed||(a&&this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UNMUTE),i.reject(t.error))}))):i.reject(new Error(`[${r}][muteUnmute] cannot be performed now, the link is not yet available`))}sendNetworkRequestForUpdatingMeetingRoles(e,t,i,n,r,a){if(!i){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because correct updateMeetingRoleUrl is not provided`;new Error(e).endCode={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),a.reject()}if(!e){const e=`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed because participants list is empty or null`,t=new Error(e);t.endCode={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_REJECTED,phrase:e},this.logger.info(e),a.reject(t)}this.signalingSession.http.sendPostRequest({url:i,payload:_u(this.signalingSession,e,"specified",t),requestName:n,onceTrouterReady:()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE,(()=>{if(this.signalingSession&&!this.signalingSession.disposed){this.signalingSession.telemetryHelper.recordEvent(El,{causeId:r}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE);const e=new Error(`[${r}] Timed out waiting for response to request`);e.endCode={code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_ROLE_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_MEETING_ROLE_TIMEOUT},a.reject(e)}}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_ROLE_TIMEOUT)},causeId:r}).then((e=>{a.resolve(e.response)})).catch((e=>{const t=Ne(e);this.logger.info(`[${r}][sendNetworkRequestForUpdatingMeetingRoles] failed: ${t}`);const i=new Error(`[${r}][CS response] Forbidden request`),n=fa(e,this.signalingSession.signalingAgentConfig);i.code=n.error.code,i.subCode=n.error.subCode,i.phrase=n.error.phrase,this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_ROLE),a.reject(i))}))}sendNetworkRequestForNudgingParticipants(e,t,i,n,r,a,s){if(t){const o=()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(vo),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""))}),Jr.TIMEOUT_VALUES_IN_SECONDS.NUDGE_PARTICIPANT_TIMEOUT,e?e.join():"")},l=a||r?function(e,t,i,n,r,a){oa(e,"signalingSession cannot be null"),oa(t,"participantsIds cannot be null");const s=e.groupId?{id:e.groupId}:null,o=n?{threadId:n,messageId:r||null}:null,l=[];return t.forEach((e=>{const t={id:e};l.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:Jr.INVITATION_TYPE.NUDGE,to:l},participantInvitationData:a,groupContext:s,groupChat:o,links:{nudgeParticipantSuccess:Zr(e,Ar.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Zr(e,Ar.CONV_NUDGE_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,0,a,s,n):function(e,t,i){oa(e,"signalingSession cannot be null"),oa(t,"participantsIds cannot be null");const n=[];return t.forEach((e=>{const t={id:e};n.push(t)})),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},invitationType:Jr.INVITATION_TYPE.NUDGE,to:n},participantInvitationData:i,links:{nudgeParticipantSuccess:Zr(e,Ar.CONV_NUDGE_PARTICIPANT_SUCCESS),nudgeParticipantFailure:Zr(e,Ar.CONV_NUDGE_PARTICIPANT_FAILURE),addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE)}}}}(this.signalingSession,e,n);return this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:sd.NUDGE_PARTICIPANT.name,onceTrouterReady:o,causeId:i}).then((()=>{})).catch((t=>{const n=fa(t,this.signalingSession.signalingAgentConfig);return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant][failed][reason=${Ne(n)}]`),this.disposed||this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.NUDGE_PARTICIPANT,e?e.join():""),Promise.reject(n.error)}))}return this.logger.info(`[${i}][sendNetworkRequestForNudgingParticipant] failed because correct nudgeParticipantUrl is not provided`),Promise.reject("Missing nudgeParticipant url")}sendNetworkRequestForAddingParticipant(e,t,i,n=na()){if(t){let r=sd.ADD_PARTICIPANT.name,a=Ja,s={};switch(i.replacementType){case 2:r=sd.ADD_PARTICIPANT_WITH_PICKUP_CODE.name,a=Vl,s.unparkContent={pickupCode:i.pickupCode};break;case 1:r=sd.ADD_PARTICIPANT_WITH_REPLACES.name,a=Qa,s=this.signalingSession.getCallReplacementDetailsForCall(i.callIdToReplace,n);break;case 3:r=sd.ADD_PARTICIPANT_WITH_REPLACES.name,a=Qa,s=this.signalingSession.getReplacementDetailsByParticipantLegOfCall(i.callIdToReplace,e[0].id,e[0].replacementParticipantId,n);break;default:r=sd.ADD_PARTICIPANT.name,a=Ja,s=null}const o=()=>{e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(a,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,t),this.participantOperationHandler.rejectPendingOperation(0,t,"timed out waiting for participant to show up in roster",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},n))}),Jr.TIMEOUT_VALUES_IN_SECONDS.ADD_PARTICIPANT_TIMEOUT,t)}))},l=i.threadId||i.groupId?vu(this.signalingSession,e,i,s):function(e,t,i,n){oa(e,"signalingSession cannot be null");const r=t.map((e=>(oa(e,"remoteParticipant cannot be null"),{id:e.id,assertedId:e.assertedId,displayName:e.displayName,participantId:e.participantId})));return{payload:{disableUnmute:i&&i.disableUnmute,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,alternateId:i?i.alternateId:null},to:r},participantInvitationData:i.additionalData,replacementDetails:n,links:{addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE)},debugContent:{clientScenario:i.clientScenario}}}}(this.signalingSession,e,i,s);this.signalingSession.http.sendPostRequest({url:t,payload:l,requestName:r,onceTrouterReady:o,causeId:n}).catch((t=>{const r=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestForAddingParticipant] failed:${Ne(t)}`),this.disposed||e.forEach((e=>{const a=3===i.replacementType?e.participantId:e.id;this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,a),this.participantOperationHandler.rejectPendingOperation(0,a,t,r.error,n)}))}))}else this.logger.info(`[${n}][sendNetworkRequestForAddingParticipants] failed because correct addParticipantUrl is not provided`),e.forEach((e=>{const t=3===i.replacementType?e.participantId:e.id;this.participantOperationHandler.rejectPendingOperation(0,t,"correct addParticipantUrl is not provided",{code:Jr.CALL_END_CODE.LOCAL_ERROR,subCode:Jr.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:Jr.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},n)}))}sendNetworkRequestToUpdateParticipantInterpretationState(e,t,i,n=na()){if(t){const r=sd.UPDATE_PARTICIPANT_INTERPRETATION_STATE.name,a=Pc,s=()=>{const t={code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_TIMEOUT};e.forEach((e=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] timed out`),this.signalingSession.telemetryHelper.recordEvent(a,{causeId:n}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,"timed out waiting to update particiant interpretation state",t,n))}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION_TIMEOUT,e.id)}))},o=function(e,t,i){return oa(e,"signalingSession cannot be null"),oa(t,"options cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id},to:t,links:{updateParticipantInterpretationStateStatus:Zr(e,Ar.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS)},operationId:i}}}(this.signalingSession,i,n);this.signalingSession.http.sendPostRequest({url:t,payload:o,requestName:r,onceTrouterReady:s,causeId:n}).catch((t=>{const i=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed:${Ne(t)}`),this.disposed||e.forEach((e=>{this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANT_INTERPRETATION_STATE_COMPLETION,e.id),this.participantOperationHandler.rejectPendingOperation(5,e.id,t,i.error,n)}))}))}else{this.logger.info(`[${n}][sendNetworkRequestToUpdateParticipantInterpretationState] failed because correct updateParticipantUrl is not provided`);const t={code:Jr.CALL_END_CODE.LOCAL_ERROR,subCode:Jr.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:Jr.CALL_END_PHRASE.UPDATE_PARTICIPANT_INTERPRETATION_STATE_URL_MISSING};e.forEach((e=>{this.participantOperationHandler.rejectPendingOperation(5,e.id,"correct updateParticipantUrl is not provided",t,n)}))}}sendNetworkRequestForCallMeBack(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.CALL_ME_BACK,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(ss,{causeId:i}),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,"timed out waiting for call me back success response",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),Jr.TIMEOUT_VALUES_IN_SECONDS.CALL_ME_BACK_TIMEOUT,e.id)},r={groupId:this.signalingSession.groupId,threadId:this.signalingSession.threadId,messageId:this.signalingSession.teamsMessageId};this.signalingSession.http.sendPostRequest({url:t,payload:vu(this.signalingSession,[e],r),requestName:sd.CALL_ME_BACK.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed: ${Ne(n)}`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.CALL_ME_BACK,e.id),this.participantOperationHandler.rejectPendingOperation(2,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForCallMeBack] failed because correct addParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(2,e.id,"correct addParticipantUrl is not provided",{code:Jr.CALL_END_CODE.LOCAL_ERROR,subCode:Jr.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:Jr.CALL_END_PHRASE.ADD_PARTICIPANT_URL_MISSING},i)}sendNetworkRequestForAdmittingParticipant(e,t,i){if(t){const n=()=>{this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,(()=>{this.signalingSession&&!this.signalingSession.disposed&&(this.signalingSession.telemetryHelper.recordEvent(es),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,"timed out waiting for participant to show up in roster",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT},i))}),Jr.TIMEOUT_VALUES_IN_SECONDS.ADMIT_PARTICIPANT_TIMEOUT,e.id)};this.signalingSession.http.sendPostRequest({url:t,payload:Su(this.signalingSession,e,i),requestName:sd.ADMIT_PARTICIPANT.name,onceTrouterReady:n,causeId:i}).catch((t=>{const n=fa(t,this.signalingSession.signalingAgentConfig);this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant][failed][reason=${Ne(n)}]`),this.disposed||(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e.id),this.participantOperationHandler.rejectPendingOperation(1,e.id,t,n.error,i))}))}else this.logger.info(`[${i}][sendNetworkRequestForAdmittingParticipant] failed because correct admitParticipantUrl is not provided`),this.participantOperationHandler.rejectPendingOperation(1,e.id,"correct admitParticipantUrl is not provided",{code:Jr.CALL_END_CODE.LOCAL_ERROR,subCode:Jr.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED,phrase:Jr.CALL_END_PHRASE.ADMIT_PARTICIPANT_URL_MISSING},i)}getCurrentParticipantsInCallModality(e){const t={},i=[Jr.PARTICIPANT_AUDIO_STATE.CONNECTED];return e||i.push(Jr.PARTICIPANT_AUDIO_STATE.CONNECTING,Jr.PARTICIPANT_AUDIO_STATE.RINGING),this.signalingSessionCallback.getRemoteParticipantCollection()?.forEach((e=>{i.some((t=>t===e.audioState))&&(t[e.mri]=!0)})),t}internalHandleRemoveParticipantFailure(e,t,i){if(this.participantOperationHandler.hasPendingOperation(3,e,i)){this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.REMOVE_PARTICIPANT,e),this.logger.info(`[${i}][internalHandleRemoveParticipantFailure] failed for ${this.piiUtils.scrubMriOrOmit(e)} reason ${Ne(t)}`);const n=this.getCallEndGivenParticipantFailure(t);this.participantOperationHandler.rejectPendingOperation(3,e,n.phrase,n,i)}}internalHandleCallMeBackSuccessHelper(e,t){if(this.participantOperationHandler.hasPendingOperation(2,e,t)){const i={id:e};return this.logger.info(`participant : ${this.piiUtils.scrubMriOrOmit(e)} was successfully added. Resolving CallMeBack request`),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.participantOperationHandler.resolvePendingOperation(2,i.id,i,t),!0}return!1}internalHandleAddParticipantFailure(e,t=na()){const i=e.body;if(i.participantInfos)i.participantInfos.forEach((i=>{const n=[i.participant.participantId],r=this.participantOperationHandler.getRnlMri(n,t)||i.participant.id;this.rejectAddParticipantFailure(r,i.transactionEnd,e,t)}));else if(i.participants)for(const n of Object.keys(i.participants))this.rejectAddParticipantFailure(n,i.participants[n],e,t)}rejectAddParticipantFailure(e,t,i,n){const r=this.getCallEndGivenParticipantFailure(t);this.signalingSession.telemetryHelper.recordIncomingEvent(hs,i,r),this.participantOperationHandler.hasPendingOperation(0,e,n)?(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADD_PARTICIPANT,e),this.logger.info(`participantAdd failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${Ne(t)}`),this.participantOperationHandler.rejectPendingOperation(0,e,r.phrase,r,n)):this.participantOperationHandler.hasPendingOperation(2,e,n)&&(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.CALL_ME_BACK,e),this.logger.info(`callMeBack failed for : ${this.piiUtils.scrubMriOrOmit(e)} reason : ${Ne(t)}`),this.participantOperationHandler.rejectPendingOperation(2,e,r.phrase,r,n))}internalHandleAdmitParticipantSuccess(e,t){const i=e.body;for(const e of i.participants)this.participantOperationHandler.hasPendingOperation(1,e,t)&&(this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,e),this.logger.info(`Admit participant success for : ${this.piiUtils.scrubMriOrOmit(e)}`),this.participantOperationHandler.resolvePendingOperation(1,e,void 0,t))}internalHandleAdmitParticipantFailure(e,t){const i=e.body;for(const n of Object.keys(i.participants))if(this.participantOperationHandler.hasPendingOperation(1,n,t)){this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT_PARTICIPANT,n);const r=i.participants[n];this.logger.info(`Admit participant failed for : ${this.piiUtils.scrubMriOrOmit(n)} reason : ${Ne(r)}`);const a=this.getCallEndGivenParticipantFailure(r);this.signalingSession.telemetryHelper.recordIncomingEvent(gs,e,a),this.participantOperationHandler.rejectPendingOperation(1,n,a.phrase,a,t)}}getCallEndGivenParticipantFailure(e){let t={code:e.code,subCode:e.subCode,phrase:e.phrase,resultCategories:e.resultCategories};return e.code===Jr.CALL_END_CODE.CALL_MODALITY_FAILURE&&e.callControllerTransactionEnd?t={...e.callControllerTransactionEnd}:e.code===Jr.CALL_END_CODE.ATC_CONTROLLER_FAILURE&&e.atcControllerTransactionEnd?t={...e.atcControllerTransactionEnd}:e.code===Jr.CALL_END_CODE.CVA_CONTROLLER_FAILURE&&e.cvaControllerTransactionEnd&&(t={...e.cvaControllerTransactionEnd}),t}};function Iu(e,t){return`${e}-${t}`}function wu(e,t){return`${e}-${t}`}function Ru(e,t,i){return`${e}_${t}_${i}`}var Au=class{constructor(e){this.signalingSession=e,this.scopeAllOperations=new Map,this.mriOperations=new Map,this.legOperations=new Map,this.logger=e.logger.createChild((()=>"[ProxiedMessageNotificationManager]"))}sendProxiedMessageAsync(e,t,i){this.logger.createChild("sendProxiedMessageAsync",e).info(`Url: ${i}`);const n=[],r=[];for(const i of t)if(0!==i.scope){if(1===i.scope)for(const t in i.to)if("participant"===i.to[t].level){const a=Iu(t,i.operationId),s=Ta();this.mriOperations.set(a,s),n.push(s.promise),r.push(a),this.startTimeout(e,"participant",a)}else if("endpoint"===i.to[t].level)for(const a in i.to[t].participantLegIdMap){const t=wu(a,i.operationId),s=Ta();this.legOperations.set(t,s),n.push(s.promise),r.push(t),this.startTimeout(e,"endpoint",t)}}else{const t=Ta();this.scopeAllOperations.set(i.operationId,t),n.push(t.promise),r.push(i.operationId),this.startTimeout(e,"all",i.operationId)}return this.sendProxiedMessageNetworkRequest(e,t,i,r),n}sendProxiedMessageNetworkRequest(e,t,i,n){const r=function(e,t){oa(e,"signalingSession cannot be null"),sa(t,"sendMessageOptions cannot be null or empty");const i=[];for(const n of t){const t=0===n.scope?"all":"specified",r=[];n.to&&Object.keys(n.to).forEach((e=>{n.to[e].participantLegIdMap?Object.keys(n.to[e].participantLegIdMap).forEach((t=>{r.push({id:e,level:n.to[e].level,endpointId:n.to[e].participantLegIdMap[t].endpointId,participantId:t})})):r.push({id:e,level:n.to[e].level})})),i.push({links:{sendMessageStatus:Zr(e,Ar.SEND_MESSAGE_STATUS)},operationId:n.operationId,payload:n.payload,scope:t,to:r,type:n.type})}return{payload:{from:{displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,id:e.participantManager.localParticipant.id,languageId:e.participantManager.localParticipant.languageId??"",participantId:e.participantManager.localParticipant.participantId},messageContent:i}}}(this.signalingSession,t),a=this.logger.createChild("sendProxiedMessageNetworkRequest",e);a.info(`Url: ${i}`),this.signalingSession.http.sendPostRequest({url:i,requestName:sd.SEND_PROXIED_MESSAGE.name,payload:r,causeId:e}).catch((t=>{const i=fa(t,this.signalingSession.signalingAgentConfig);if(a.info(`failed:${Ne(t)}`),this.signalingSession.disposed)a.info("signaling session is already disposed.");else for(const t of n){this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,t);let n=null;this.scopeAllOperations.has(t)?(n=this.scopeAllOperations.get(t),this.scopeAllOperations.delete(t)):this.mriOperations.has(t)?(n=this.mriOperations.get(t),this.mriOperations.delete(t)):this.legOperations.get(t)?(n=this.legOperations.get(t),this.legOperations.delete(t)):a.warn(`could not find resolveString:${t} to reject it.`),null!==n&&n.reject({transactionEnd:i.error,causeId:e,resolveString:t})}}))}startTimeout(e,t,i){const n=this.logger.createChild("startTimeout",e);n.info(`Creating timeout for level ${t} message with resolveString ${i}`),this.signalingSession.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,(()=>{this.signalingSession.telemetryHelper.recordEvent(Wc,{causeId:e,resolveString:i}),n.info(`timed out waiting for level [${t}] message with resolveString [${i}]`),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,i);const r="all"===t?this.scopeAllOperations:"participant"===t?this.mriOperations:"endpoint"===t?this.legOperations:null;null!==r?r.has(i)?(r.get(i).reject({transactionEnd:{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.CONVERSATION_NOTIFICATION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.CONVERSATION_NOTIFICATION_TIMEOUT},causeId:e,resolveString:i}),r.delete(i)):n.warn(`Could not find resolveString [${i}] on map for ${t}. Will not reject promise.`):n.warn(`Could not find a operations map for ${t}. Will not reject promise.`)}),Jr.TIMEOUT_VALUES_IN_SECONDS.SEND_MESSAGE_COMPLETION_TIMEOUT,i)}handleProxiedMessageNotificationItem(e,t,i){if(t.info(`Message contains ${e.participantInfos?.length} participantInfos.`),0===this.scopeAllOperations.size&&0===this.mriOperations.size&&0===this.legOperations.size)return void t.info("Received statusMessage but there is no pending operation.");const n=e.operationId;if(this.scopeAllOperations.has(n)){t.info(`Scope all resolveString:${n}`),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,n);const e={transactionEnd:{code:0,subCode:0,phrase:""},causeId:i,resolveString:n};return this.scopeAllOperations.get(n).resolve(e),this.scopeAllOperations.delete(n),void this.signalingSession.telemetryHelper.recordEvent(zc,{causeId:i,operationId:n,level:"all"})}for(const r of e.participantInfos){const e=0===r.transactionEnd?.code,a=Iu(r.participant.id,n),s=wu(r.participant.participantId,n);if(a&&this.mriOperations.has(a)){t.info(`Scope mri resolveString:${a}`);const s={transactionEnd:r.transactionEnd,causeId:i,resolveString:a};e?this.mriOperations.get(a).resolve(s):this.mriOperations.get(a).reject(s),this.mriOperations.delete(a),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,a),this.signalingSession.telemetryHelper.recordEvent(zc,{causeId:i,operationId:n,level:"mri"})}else if(s&&this.legOperations.has(s)){t.info(`Scope legId resolveString:${s}`);const a={transactionEnd:r.transactionEnd,causeId:i,resolveString:s};e?this.legOperations.get(s).resolve(a):this.legOperations.get(s).reject(a),this.legOperations.delete(s),this.signalingSession.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SEND_MESSAGE_COMPLETION,s),this.signalingSession.telemetryHelper.recordEvent(zc,{causeId:i,operationId:n,level:"leg"})}else t.warn(`Could not map this participantInfo to any pending operation operationId:${n}`)}}handleProxiedMessageNotification(e){const t=ya(e),i=this.logger.createChild("handleProxiedMessageNotification",t);let n;n=Array.isArray(e.body?.statuses)?e.body.statuses:[e.body],i.info(`Received ${n.length} proxied message notification(s).`);for(const e of n)this.handleProxiedMessageNotificationItem(e,i,t)}};function Pu(e,t){return oa(e,"signalingSession cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},links:{admitAllStatus:Zr(e,Ar.CONV_ADMIT_ALL_STATUS)},operationId:t,debugContent:{causeId:t}}}}function Mu(e,t,i=!0){oa(e,"signalingSession cannot be null"),oa(t,"joinUrl cannot be null");const n={type:"Delta",rosterUpdate:Zr(e,Ar.CONV_ROSTER_UPDATE)},r=e.getEndpointCapabilities(),a={payload:{attach:{requireMediaContent:i,links:{end:Zr(e,Ar.END)},locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent()},capabilities:null,endpointCapabilities:r,additionalActions:[{input:{capabilities:null,endpointCapabilities:r,conversationRequest:{applicationType:e.participantManager.localParticipant.applicationType,roster:n,links:{conversationEnd:Zr(e,Ar.CONV_END),conversationUpdate:Zr(e,Ar.CONV_UPDATE),localParticipantUpdate:Zr(e,Ar.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Zr(e,Ar.RECEIVE_MESSAGE)}},endpointMetadata:e.endpointMetadata,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}}},name:"join",url:t,waitForResponse:!0}]}};return e.signalingAgentConfig.ecsEtag&&(a.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),a.payload.additionalActions.length>0&&e.deviceType&&"default"!==e.deviceType&&(a.payload.additionalActions[0].input.conversationRequest.deviceType=e.deviceType),a}function ku(e){return oa(e,"signalingSession cannot be null"),{payload:{callAcceptanceAcknowledgement:{links:{mediaRenegotiation:Zr(e,Ar.MEDIA_RENEGOTIATION),transfer:Zr(e,Ar.TRANSFER),replacement:Zr(e,Ar.REPLACE),balanceUpdate:Zr(e,Ar.BALANCE_UPDATE),retargetCompletion:Zr(e,Ar.RETARGET_COMPLETION),controlVideoStreaming:Zr(e,Ar.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Zr(e,Ar.UPDATE_MEDIA_DESCRIPTIONS)}}}}}function Du(e,t,i,n){oa(e,"signalingSession cannot be null");const r=ca(i);e.telemetryHelper.addOutgoingModalities(r);const a=e.getEndpointCapabilities();return{payload:{callAcceptance:{acceptedBy:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},acceptedCallModalities:r,capabilities:null,endpointCapabilities:a,clientEndpointCapabilities:0!==n?n:null,links:{mediaRenegotiation:Zr(e,Ar.MEDIA_RENEGOTIATION),transfer:Zr(e,Ar.TRANSFER),replacement:Zr(e,Ar.REPLACE),balanceUpdate:Zr(e,Ar.BALANCE_UPDATE),retargetCompletion:Zr(e,Ar.RETARGET_COMPLETION),controlVideoStreaming:Zr(e,Ar.CONTROL_VIDEO_STREAMING),updateMediaDescriptions:Zr(e,Ar.UPDATE_MEDIA_DESCRIPTIONS)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,callKeepAliveInterval:null}}}}function Ou(e){return oa(e,"signalingSession cannot be null"),{payload:{callProgress:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},status:"ringing",phrase:"ringing"}}}}function Nu(e,t,i){oa(e,"signalingSession cannot be null"),la(t);const n={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:Jr.CALL_END_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===Jr.CALL_END_CODE.CANCEL&&(n.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),n}function Lu(e,t){return oa(e,"signalingSession cannot be null"),la(t),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},conversationTransactionEnd:{reason:"noError",code:Jr.CALL_END_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED},callTransactionEnd:t}}}function xu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:t}}}function Fu(e,t,i,n,r){oa(e,"signalingSession cannot be null");const a={type:"Delta",rosterUpdate:Zr(e,Ar.CONV_ROSTER_UPDATE)},s=e.getEndpointCapabilities(),o=e.groupId?{id:e.groupId}:null,l=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,c={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,scenario:n.scenario,applicationType:n.applicationType,roster:a,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Zr(e,Ar.CONV_END),conversationUpdate:Zr(e,Ar.CONV_UPDATE),localParticipantUpdate:Zr(e,Ar.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE),receiveMessage:Zr(e,Ar.RECEIVE_MESSAGE)}},groupContext:o,groupChat:l,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin}},capabilities:null,endpointCapabilities:s,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("joinConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),c.payload.publishedStates=t}if(n?.applyServerMute&&(c.payload.participants.from.applyServerMute=n.applyServerMute.value,n.applyServerMute.mediaTypes&&(c.payload.participants.from.mediaTypes=n.applyServerMute.mediaTypes)),e.deviceType&&"default"!==e.deviceType&&(c.payload.conversationRequest.deviceType=e.deviceType),!n.subscribe){const r=ca(i);e.telemetryHelper.addOutgoingModalities(r),c.payload.callInvitation={callModalities:r,replaces:null,transferor:null,links:{progress:Zr(e,Ar.PROGRESS),mediaAnswer:Zr(e,Ar.MEDIA_ANSWER),acceptance:Zr(e,Ar.ACCEPT),redirection:Zr(e,Ar.REDIRECTION),end:Zr(e,Ar.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),mediaContent:t,pstnContent:e.pstnContent,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent(),sharedLineCallInvitationContent:n.sharedLineCallInvitationContent,invitationData:n.invitationData,callQueueContext:n.callQueueContext}}if(e.signalingAgentConfig.ecsEtag&&(c.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),r&&(c.payload.debugContent||(c.payload.debugContent={}),c.payload.debugContent.causeId=r),n.clientEndpointDebugContent){c.payload.debugContent||(c.payload.debugContent={});try{c.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){aa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{c.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){aa(!1,`Failed to parse ${n.captchaContentJson}`)}return n.callQueueContext&&(c.payload.conversationRequest.callQueueContext=n.callQueueContext),c}function Uu(e,t,i,n){oa(e,"signalingSession cannot be null"),la(t);const r={payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},scope:n&&"all"!==n?void 0:n},conversationTransactionEnd:{reason:"noError",code:Jr.CALL_END_CODE.SUCCESS,phrase:Jr.CALL_END_PHRASE.CONV_END_NO_MODALITY},callTransactionEnd:t}};return i&&t.code===Jr.CALL_END_CODE.CANCEL&&(r.payload.callTransactionEnd.callQualityDiagnosticsInformation=i),r}function Bu(e,t,i){return oa(e,"signalingSession cannot be null"),oa(i,"newOfferLink cannot be null"),{payload:{mediaOfferRequirements:{compatibleContentTypes:t,links:{offerReady:Zr(e,Ar.NEW_MEDIA_OFFER)}}}}}function Vu(e,t){return oa(t,"signalingSession cannot be null"),{payload:{callTransfer:{target:{id:t.participantManager.localParticipant.id},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},parkType:e,links:{transferAcceptance:Zr(t,Ar.TRANSFER_ACCEPTANCE),transferCompletion:Zr(t,Ar.TRANSFER_COMPLETION)}}}}}function Hu(e,t,i){oa(e,"ParkRequestPayload: signalingSession cannot be null");const n={payload:{hold:{holdType:t,links:{holdCompletion:Zr(e,Ar.PARK_COMPLETION)}}}};return i&&(n.payload.debugContent=i),n}function $u(e,t,i,n,r,a){const s={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},publishedState:{content:n,level:i,stateType:t,sequenceNumber:e.getPublishStateSequenceNumber()},scope:r}};if(a&&a.length>0){const e=a.map((e=>({id:e})));s.payload.to=e}return s}function Gu(e,t){return oa(e,"signalingSession cannot be null"),la(t),{payload:{callEnd:t}}}function ju(e,t,i,n){const r={from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},sequenceNumber:e.getPublishStateSequenceNumber(),scope:t};return"specified"===t?r.stateIds=i:r.stateType=n,{payload:r}}function zu(e,t){return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},searchOptions:t}}}function Wu(e,t,i,n,r){return oa(t,"signalingSession cannot be null"),sa(e,"transferTarget cannot be null OR empty"),{payload:{callTransfer:{target:{id:e,endpointType:"TransferTypeVoicemail"===n?"voicemail":void 0},transferor:{details:{id:t.participantManager.localParticipant.id,endpointId:t.participantManager.localParticipant.endpointId,participantId:t.participantManager.localParticipant.participantId,languageId:t.participantManager.localParticipant.languageId},authorizationToken:null},links:{transferAcceptance:Zr(t,Ar.TRANSFER_ACCEPTANCE),transferCompletion:Zr(t,Ar.TRANSFER_COMPLETION)},replacementDetails:i,disableForwardingAndUnanswered:r&&r.disableForwardingAndUnanswered,transferContext:r&&r.clientTransferContext}}}}function qu(e){return{payload:{transferCompletion:e}}}function Ku(e,t){oa(e,"ResumePayload: signalingSession cannot be null");const i={payload:{resume:{links:{resumeCompletion:Zr(e,Ar.UNPARK_COMPLETION)}}}};return t&&(i.payload.debugContent=t),i}function Ju(e,t){return oa(t,"clientMetadataJson cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},endpointMetadata:t}}}function Yu(e,t,i,n){oa(t,"clientStateJson cannot be null");const r={payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},endpointState:t}};if(i?.publishedStates.length>0){let t=[];t=i.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("updateEndpointState getPayload() failed to parse stateType.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),r.payload.publishedStates=t}return n&&(r.payload.links={updateEndpointStateStatus:Zr(e,Ar.DISABLE_PREHEAT_ASYNC_STATUS)}),r}function Qu(e,t){const i={};return void 0!==t.allowRaiseHands&&(i.allowRaiseHands=t.allowRaiseHands),void 0!==t.attendeeRestrictions&&(i.attendeeRestrictions=t.attendeeRestrictions),void 0!==t.lockMeeting&&(i.lockMeeting=t.lockMeeting),void 0!==t.breakoutRoomsEnabled&&(i.breakoutRoomsEnabled=t.breakoutRoomsEnabled),void 0!==t.allowPresentersToManageBreakoutRooms&&(i.allowPresentersToManageBreakoutRooms=t.allowPresentersToManageBreakoutRooms),void 0!==t.disableMdpClientAudioRecording&&(i.disableMdpClientAudioRecording=t.disableMdpClientAudioRecording),void 0!==t.refreshSettings&&(i.refreshSettings=t.refreshSettings),{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingSettings:i,sequenceNumber:e.getPublishStateSequenceNumber()}}}function Zu(e,t){return oa(e,"signalingSession cannot be null"),{payload:{mediaAnswer:{sender:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},mediaContent:t,pstnContent:e.pstnContent}}}}function Xu(e,t){return oa(e,"signalingSession cannot be null"),{payload:{UpdateMediaDescriptions:{mediaDescriptions:t}}}}var eh=f(g),th=f(pe()),ih=class{constructor(e,t){this.signalingSession=e,this.logger=t,this.logConversationCallModalityEvent=e=>{const t=this.createCallModalityEvent(e);this.logger.info("sending modality telemetry:",this.getStringifiedEventData(t)),t.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(cd.CONVERSATION_CALL_MODALITY,t)},this.logConversationContentSharingEvent=e=>{e[gd.CORRELATION_ID]=this.signalingSession.correlationId,e[dd.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,this.logger.info("sending content sharing telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(cd.CONVERSATION_CONTENT_SHARING,e)},this.logHttpTelemetryEvent=e=>{e[dd.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,e[hd]=this.getSignalingAgentConfig(),this.logger.info("sending http telemetry:",this.getStringifiedEventData(e)),e.hostName=this.getHostDomainInfo(),this.telemetryLogger.sendEvent(cd.CONVERSATION_HTTP_REQUEST,e)},this.getHostDomainInfo=()=>"localhost"===location.hostname||"127.0.0.1"===location.hostname?"localhost":"<redacted>",this.getSignalingAgentConfig=()=>{const e=[],t=this.signalingSession.signalingAgentConfig;return t.supportsCompressedServicePayload&&e.push(pd.SUPPORTS_COMPRESSED_PAYLOAD),t.brokerEnabledOutgoing&&e.push(pd.BROKER_OUTGOING_ENABLED),t.brokerEnabledIncoming&&e.push(pd.BROKER_INCOMING_ENABLED),t.brokerRequestBatching&&e.push(pd.BROKER_REQUEST_BATCHING_ENABLED),t.brokerExclusively&&e.push(pd.BROKER_EXCLUSIVELY_ENABLED),t.supportsSynchronousTrouterResponse&&e.push(pd.SYNC_TROUTER_RESPONSE),t.handleMediaOfferFromPushNotification&&e.push(pd.HANDLE_OFFER_FROM_NOTIFICATION),t.handleNewOfferRequest&&e.push(pd.HANDLE_NEW_OFFER_REQUEST),t.sendProgressFromCC&&e.push(pd.SEND_PROGRESS_FROM_CC),t.useInternalHttpDispatcher&&e.push(pd.INTERNAL_HTTP_DISPATCHER),t.enableTokenCache&&e.push(pd.ENABLE_TOKEN_CACHE),t.enableTokenPrefetch&&e.push(pd.ENABLE_TOKEN_PREFETCH),t.supportMediaRetargetWhileIncomingRenegotiation&&e.push(pd.SUPPORT_MEDIA_RETARGET_WHILE_INCOMING_RENEGOTIATION),t.enableCallEstablishmentTimeoutsForStartJoinCall&&e.push(pd.ENABLE_CALL_ESTABLISHMENT_TIMEOUTS_FOR_START_OR_JOIN_CALL),t.enableTokenCacheForGenericTokenAPI&&e.push(pd.ENABLE_TOKEN_CACHE_FOR_GENERIC_TOKEN_API),t.enableLongOutgoing1To1SetupTimeoutForWeb&&e.push(pd.ENABLE_LONG_OUTGOING_1TO1_SETUP),e.push(pd.SERVER_MUTE_UNMUTE),e.join(",")},this.getStringifiedEventData=e=>{try{return JSON.stringify(e)}catch(e){return"invalid data"}},this.telemetryLogger=this.signalingSession.signalingAgentConfig.oneDsTelemetryLogger??this.signalingSession.signalingAgentConfig.telemetryManager}createCallModalityEvent(e){const t={};t.Type=ld.NGC_SOURCE;const i=(i,n=!1)=>{e.hasOwnProperty(i)&&(t[i]=n?JSON.stringify(e[i]):e[i])};if(t.ResultDetail=e[dd.RESULT_DETAIL],t.ResultValue=e[dd.RESULT_VALUE],t.ResultCode=e[dd.CALL_END_CODE],t.ResultCauseId=e[dd.RESULT_CAUSE_ID],t[hd]=this.getSignalingAgentConfig(),t[gd.CORRELATION_ID]=this.signalingSession.correlationId,t[gd.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,t[gd.ENDPOINT_ID]=e[gd.ENDPOINT_ID],t[gd.PARTICIPANT_ID]=e[gd.PARTICIPANT_ID],t[dd.ECS_ETAG]=this.signalingSession.signalingAgentConfig.ecsEtag,t[dd.CONVERSATION_SERVICE_URL]=e[dd.CONVERSATION_SERVICE_URL],t[dd.CALL_START_TIME]=JSON.stringify(e[dd.CALL_START_TIME]),t[dd.CALL_END_TIME]=JSON.stringify(e[dd.CALL_END_TIME]),t[dd.MESSAGING_CHANNEL]=JSON.stringify(e[dd.MESSAGING_CHANNEL]),t[dd.IS_GROUP_CALL]=this.signalingSession.multiParty?"true":"false",t[dd.IS_HOSTLESS_CALL]=this.signalingSession.isHostLessCall?"true":"false",t[dd.IS_CAST_CALL]=this.signalingSession.isCastCall?"true":"false",t[dd.IS_HUDDLE_GROUP_CALL]=this.signalingSession.isHuddleGroupCall?"true":"false",t[dd.IS_ON_BEHALF_OF_CALL]=this.signalingSession.onBehalfOf?"true":"false",t[dd.CLIENT_INFORMATION]=e[dd.CLIENT_INFORMATION],t[dd.IS_SDP_IN_CALL_NOTIFICATION]=e[dd.IS_SDP_IN_CALL_NOTIFICATION],t[dd.CALL_TERMINATING_END]=e[dd.CALL_TERMINATING_END],t[dd.CALL_END_CODE]=JSON.stringify(e[dd.CALL_END_CODE]),t[dd.CALL_END_SUB_CODE]=JSON.stringify(e[dd.CALL_END_SUB_CODE]),i(gd.SHARED_CORRELATION_ID),i(dd.DIRECTION),i(dd.SELF_PARTICIPANT_ROLE),i(dd.CONNECTED_DURATION_IN_MS,!0),i(dd.TIME_TO_RING_IN_MS,!0),i(dd.NETWORK_REQUESTS_COMPLETED),i(dd.NETWORK_REQUESTS_PENDING),i(dd.LOCAL_OPERATIONS_PERFORMED),i(dd.EVENT_TIMESTAMP_BAG),i(dd.ROSTER_UPDATES_BAG),i(dd.NETWORK_REQUESTS_BAG),i(dd.TROUTER_WAIT_OPERATIONS),i(dd.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS),i(dd.OUTGOING_MODALITIES),i(dd.INCOMING_MODALITIES),i(dd.OFFERED_MODALITIES),i(dd.ANSWERED_MODALITIES),i(dd.VBSS_OPERATIONS),i(dd.CALLER_TYPE),i(dd.CALLEE_TYPE),i(dd.SCENARIO),i(dd.PREHEATED_CALL_SETUP_DURATION_IN_S),i(dd.CALL_CANCELATION_DURATION_IN_S),i(dd.IS_PREHEATED),i(dd.ACS_RESOURCE_ID),i(dd.CALL_END_RESULT_CATEGORIES),i(dd.APPLICATION_TYPE),i(dd.RING),i(dd.REGION),i(dd.PARTITION),i(dd.JOINED_FROM),i(dd.MEETING_URL),i(dd.MEETING_CODE),i(dd.USER_HEX_CID),i(dd.BROADCAST_MEETING_ROLE),i(dd.MEETING_ROLE),i(dd.ADVANCED_MEETING_ROLE),i(dd.PARTICIPANT_TYPE),i(dd.AUDIO_ONLY_WATERMARK),i(dd.TARGET_APPLICATION_TYPE),i(dd.IS_REINVITELESS),i(dd.CLIENT_TYPE),this.signalingSession.callType&&(t[dd.CALL_TYPE]=this.signalingSession.callType),this.signalingSession.signalingAgentConfig.testCall&&(t[dd.TEST_CONTEXT_ID]="Test"),this.signalingSession.groupId&&(t[gd.GROUP_ID]=Ae(this.signalingSession.groupId)),this.signalingSession.threadId&&(t[gd.THREAD_ID]=Me(this.signalingSession.threadId)),this.signalingSession.teamsMessageId&&(t[gd.TEAMS_MESSAGEID]=this.signalingSession.teamsMessageId),this.signalingSession.getMeetingInfo()){const e={...this.signalingSession.getMeetingInfo()};e.hasOwnProperty("organizerId")&&(e.organizerId=Ae(e.organizerId)),t[gd.TEAMS_MEETINGINFO]=JSON.stringify(e)}return this.signalingSession.multiParty&&0===this.signalingSession.numberOfOriginalInvitees&&e.hasOwnProperty(dd.SELF_PARTICIPANT_ROLE)&&e[dd.SELF_PARTICIPANT_ROLE]===Sd.CALLER&&(t[dd.IS_MEETUP_CALL]="true"),t}};var nh=class{constructor(e,t,i){this.signalingSession=e,this.callStartTime=i,this.networkRequestsCompleted=[],this.networkRequestsStarted={},this.networkRequests={},this.localOperationsPerformed=[],this.recordedEvents=[],this.rosterUpdates=[],this.contentSharingOperationsPerformed={},this.outgoingModalities=[],this.incomingModalities=[],this.offeredModalities="",this.answeredModalities="",this.vbssOperations=[],this.vbssStarted=!1,this.localOfferAnswerGenerationTimestamps=[],this.trouterWaitOperations=[],this.telemetryData={},this.contentSharingBaseTelemetryData={},this.httpRequestTelemetryData={},this.connectedStopWatch=null,this.preheatedCallSetupDurationWatch=null,this.callCancelationDurationWatch=null,this.timeToRingStopWatch=null,this.isSdpInCallNotification=!1,this.isPreheated=0,this.isReinviteless=0,this.addBrokerChannel=()=>{this.setMessagingChannel(ud.BROKER)},this.addTrouterChannel=()=>{this.setMessagingChannel(ud.TROUTER)},this.addTrouterWaitOperation=e=>{this.trouterWaitOperations.push(this.recordOperation(e))},this.recordIncomingEvent=(e,t,i)=>{const n=ya(t),r={origin:t.origin,causeId:n,data:i};i||delete r.data,this.recordEvent(e,r)},this.recordIncomingEventCount=e=>{this.localOperationsPerformed.push(this.recordOperation(e));const t=this.recordedEvents.findIndex((t=>t[e]));if(-1!==t)this.recordedEvents[t][e]+=1;else{const t={};t[e]=1,this.recordedEvents.push(t)}},this.recordEvent=(e,t)=>{this.logger.debug("Event:",e,t),this.localOperationsPerformed.push(this.recordOperation(e));const i={};i[e]=this.timeSinceCallStart(),t&&(i.data=t),this.recordedEvents.push(i)},this.recordRosterEvent=(e,t,i)=>{this.localOperationsPerformed.push(this.recordOperation(t));const n={data:e,causeId:i},r={eventName:this.timeSinceCallStart(),data:n};this.rosterUpdates.push(r)},this.addOutgoingModalities=e=>{e&&this.outgoingModalities.push(e)},this.addIncomingModalities=e=>{e&&this.incomingModalities.push(e)},this.setOfferedModalities=(e,t)=>{this.offeredModalities=this.sdpTelemetryFormat(e,t)},this.setAnsweredModalities=(e,t)=>{this.answeredModalities=this.sdpTelemetryFormat(e,t)},this.setIsSdpInCallNotification=e=>{this.isSdpInCallNotification=e},this.addVbssOperations=e=>{e&&(e===yd.START?this.vbssStarted=!0:this.vbssStarted=!1,this.vbssOperations.push(this.recordOperation(e)))},this.addNetworkOperationStarted=e=>{pa(this.networkRequestsStarted,e,this.recordOperation(e))},this.addNetworkOperationCompleted=(e,t,i)=>{const n=t?fd.SUCCESS:fd.FAILURE,r=i?`${e}:${n}:${i}`:`${e}:${n}`;this.networkRequestsCompleted.push(this.recordOperation(r)),ga(this.networkRequestsStarted,e)},this.updateNetworkRequest=e=>{this.networkRequests[e.uid]?eh.assign(this.networkRequests[e.uid],e):this.networkRequests[e.uid]=e},this.deleteNetworkRequest=e=>{delete this.networkRequests[e.uid]},this.addContentSharingOperation=(e,t,i)=>{this.contentSharingOperationsPerformed[e]||(this.contentSharingOperationsPerformed[e]=[]);const n={[t]:this.timeSinceCallStart()};this.contentSharingOperationsPerformed[e].push(n);const r=this.contentSharingOperationsPerformed[e].length-1;return i&&this.updateContentSharingOperation(e,r,i),r},this.updateContentSharingOperation=(e,t,i)=>{if(!this.contentSharingOperationsPerformed[e])return;const n=this.contentSharingOperationsPerformed[e][t],r=[];for(const e of Object.keys(i))r.push(`${e}: ${i[e]}`);n.data=r.join(", ")},this.setDirection=e=>{this.telemetryData[dd.DIRECTION]=e},this.setEndPointId=e=>{this.telemetryData[gd.ENDPOINT_ID]=e,this.contentSharingBaseTelemetryData[gd.ENDPOINT_ID]=e,this.httpRequestTelemetryData[gd.ENDPOINT_ID]=e},this.setParticipantId=e=>{this.telemetryData[gd.PARTICIPANT_ID]=e,this.contentSharingBaseTelemetryData[gd.PARTICIPANT_ID]=e,this.httpRequestTelemetryData[gd.PARTICIPANT_ID]=e},this.addTokenTelemetry=(e,t)=>{e?this.networkRequests?.[e]?(this.networkRequests[e].tokenTelemetries||(this.networkRequests[e].tokenTelemetries=[]),this.networkRequests[e].tokenTelemetries.push(t)):this.logger.info(`[addTokenTelemtry] httprequest: ${e} is not found in networkRequests`):this.logger.error("[addTokenTelemetry] httprequest uid is undefined")},this.setConversationServiceUrl=e=>{this.telemetryData[dd.CONVERSATION_SERVICE_URL]=e},this.setMeetingInfo=e=>{e||(this.telemetryData[dd.MEETING_INFO]=e)},this.setJoinedFrom=e=>{this.telemetryData[dd.JOINED_FROM]=e},this.setMeetingCode=e=>{this.telemetryData[dd.MEETING_CODE]=e},this.setMeetingUrl=e=>{this.telemetryData[dd.MEETING_URL]=e},this.setBroadcastMeetingRole=e=>{this.telemetryData[dd.BROADCAST_MEETING_ROLE]=e},this.setMeetingRole=e=>{this.telemetryData[dd.MEETING_ROLE]=e},this.setAdvancedMeetingRole=e=>{this.telemetryData[dd.ADVANCED_MEETING_ROLE]=e},this.setParticipantType=e=>{this.telemetryData[dd.PARTICIPANT_TYPE]=e},this.setSelfParticipantRole=e=>{this.telemetryData[dd.SELF_PARTICIPANT_ROLE]=e},this.setAudioOnlyWatermark=e=>{this.telemetryData[dd.AUDIO_ONLY_WATERMARK]=e},this.setWatermarkSupport=e=>{this.telemetryData[dd.CLIENT_SUPPORT_WATERMARK]=e},this.setClientSupportsPreventScreenCapture=e=>{this.telemetryData[dd.CLIENT_SUPPORTS_PREVENT_SCREEN_CAPTURE]=e},this.setScenario=e=>{this.telemetryData[dd.SCENARIO]=e},this.setTargetApplicationType=e=>{e&&(this.telemetryData[dd.TARGET_APPLICATION_TYPE]=e)},this.setCallerType=e=>{e&&(this.telemetryData[dd.CALLER_TYPE]=e.split(":",1)[0])},this.setCalleeType=e=>{e&&(this.telemetryData[dd.CALLEE_TYPE]=e.split(":",1)[0])},this.setTerminatingData=e=>{this.telemetryData[dd.CALL_TERMINATING_END]=e.terminatingEnd,this.telemetryData[dd.CALL_END_CODE]=e.endCode||Jr.CALL_END_CODE.SUCCESS,this.telemetryData[dd.CALL_END_SUB_CODE]=e.endSubCode||Jr.CALL_END_SUB_CODE.SUCCESS,this.telemetryData[dd.CALL_PHRASE]=e.phrase||Jr.CALL_END_PHRASE.UNKNOWN,this.telemetryData[dd.RESULT_VALUE]=e.resultValue||fd.SUCCESS,this.telemetryData[dd.RESULT_DETAIL]=e.resultDetail||"Call gracefully hungup",this.telemetryData[dd.RESULT_CAUSE_ID]=e.causeId||"unknown",this.telemetryData[dd.CALL_END_RESULT_CATEGORIES]=e.resultCategories||[],this.telemetryData[dd.CALL_END_CLIENT_SUB_CODE]=e.clientReasonSubCode,this.telemetryData[dd.CALL_END_CLIENT_PHRASE]=e.clientReasonPhrase},this.startCallInitializationWatch=e=>{this.timeToRingStopWatch=eu(),e&&(this.timeToRingStopWatch.msElapsed+=e)},this.startCallConnectedWatch=()=>{this.connectedStopWatch=eu()},this.setIsPreheated=()=>{this.isPreheated=1},this.startPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch=eu()},this.stopPreheatedCallSetupDurationWatch=()=>{this.preheatedCallSetupDurationWatch.pause()},this.startCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=eu()},this.stopCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch&&this.callCancelationDurationWatch.pause()},this.getCallCancelationDuration=()=>this.callCancelationDurationWatch?this.callCancelationDurationWatch.durationInSeconds():0,this.resetCallCancelationDurationWatch=()=>{this.callCancelationDurationWatch=null},this.setOfferAnswerGenerationTimestamps=e=>{this.localOfferAnswerGenerationTimestamps.push(this.recordOperation(e))},this.setTimeToRingDuration=()=>{this.timeToRingStopWatch&&(this.telemetryData[dd.TIME_TO_RING_IN_MS]=this.timeToRingStopWatch.duration(),this.timeToRingStopWatch=null)},this.dispose=()=>{this.sendCallModalityTelemetryData()},this.setMessagingChannel=e=>{this.telemetryData[dd.MESSAGING_CHANNEL]||(this.telemetryData[dd.MESSAGING_CHANNEL]=[]),this.telemetryData[dd.MESSAGING_CHANNEL].some((t=>-1!==t.indexOf(e)))||this.telemetryData[dd.MESSAGING_CHANNEL].push(this.recordOperation(e))},this.sendHttpTelemetryData=e=>{const t={...this.httpRequestTelemetryData};t[gd.CORRELATION_ID]=this.signalingSession.correlationId,t[gd.SIGNALING_SESSION_ID]=this.signalingSession.sessionId,t[dd.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation;const i=JSON.stringify({eventStart:this.callStartTime,events:this.networkRequests[e]});ga(this.networkRequests,e),t[dd.NETWORK_REQUESTS_BAG]=i,this.telemetryLogger.logHttpTelemetryEvent(t)},this.sdpTelemetryFormat=(e,t)=>{if(!e)return"";const i=e=>{switch(e){case"main-audio":return"Audio";case"main-video":return"Video";case"applicationsharing-video":return"AppSharing";default:return}},n=e=>{switch(e){case"inactive":return"Inactive";case"sendonly":return t?"ReceiveFromPeer":"SendToPeer";case"recvonly":return t?"SendToPeer":"ReceiveFromPeer";default:return"Bidirectional"}},r={"main-audio":0,"main-video":0,"applicationsharing-video":0},a=[],s=th.parse(e);for(const e of s.media){const t=i(e.label);if(!t)continue;const s=r[e.label]++,o=n(e.direction);a.push(`${t}[${s}] = ${o}`)}return a.join(", ")},this.setReinviteless=e=>{this.isReinviteless=e?1:0},this.logger=e.logger,this.telemetryLogger=function(e,t){return new ih(e,t)}(e,this.logger),this.telemetryData[dd.CALL_START_TIME]=this.callStartTime,this.telemetryData[dd.CONVERSATION_SERVICE_URL]=e.signalingAgentConfig.conversationServiceUrl,this.fillCommonData(t,this.telemetryData),this.fillCommonData(t,this.httpRequestTelemetryData),this.fillCommonData(t,this.contentSharingBaseTelemetryData)}fillCommonData(e,t){t[dd.APPLICATION_TYPE]=e.applicationType,t[dd.RING]=e.ring,t[dd.TENANT_ID]=e.tenantId,t[dd.USER_HEX_CID]=e.userHexCID,t[dd.ACS_RESOURCE_ID]=e.acsResourceId,t[dd.REGION]=e.region,t[dd.PARTITION]=e.partition,t[dd.CLIENT_TYPE]=e.clientType}addChangingCorrelationId(e,t){this.telemetryData[dd.CHANGING_CORRELATION_ID_OLD_ID]=e,this.telemetryData[dd.CHANGING_CORRELATION_ID_NEW_ID]=t}addSharedCorrelationId(e){this.telemetryData[gd.SHARED_CORRELATION_ID]=e}sendContentSharingTelemetryData(e,t,i,n,r,a){const s={...this.contentSharingBaseTelemetryData},o=this.contentSharingOperationsPerformed[e];o&&(s[dd.EVENT_TIMESTAMP_BAG]=JSON.stringify(o)),s[gd.CONTENT_SHARING_CORRELATION_ID]=e,s[gd.SIGNALING_SESSION_ID]=t,s[gd.CONTENT_SHARING_ID]=a||"",s[dd.CONTENT_SHARING_SERVICE_URL]=r,s[dd.CONTENT_SHARING_DIRECTION]=i?vd.OUTGOING:vd.INCOMING,s[dd.CALL_END_CODE]=n.code,s[dd.CALL_END_SUB_CODE]=n.subCode,s[dd.CALL_PHRASE]=n.phrase,s[dd.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(n.resultCategories),s[dd.CALL_END_CAUSE_ID]=n.causeId,s[dd.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,delete this.contentSharingOperationsPerformed[e],this.telemetryLogger.logConversationContentSharingEvent(s)}recordOperation(e){return`${e}:${this.timeSinceCallStart()}`}timeSinceCallStart(){return(new Date).getTime()-this.callStartTime}sendCallModalityTelemetryData(){this.vbssStarted&&this.addVbssOperations(yd.CALL_END);const e=e=>"number"==typeof e?e/1e3:0;if(this.telemetryData[dd.CLIENT_INFORMATION]=this.signalingSession.signalingAgentConfig.clientInformation,this.telemetryData[dd.CALL_END_TIME]=(new Date).getTime(),this.connectedStopWatch&&(this.telemetryData[dd.CONNECTED_DURATION_IN_MS]=this.connectedStopWatch.duration()),this.telemetryData[dd.IS_PREHEATED]=this.isPreheated,this.preheatedCallSetupDurationWatch&&(this.telemetryData[dd.PREHEATED_CALL_SETUP_DURATION_IN_S]=e(this.preheatedCallSetupDurationWatch.duration())),this.callCancelationDurationWatch&&(this.telemetryData[dd.CALL_CANCELATION_DURATION_IN_S]=e(this.callCancelationDurationWatch.duration())),this.networkRequestsCompleted.length&&(this.telemetryData[dd.NETWORK_REQUESTS_COMPLETED]=JSON.stringify(this.networkRequestsCompleted)),this.localOperationsPerformed.length&&(this.telemetryData[dd.LOCAL_OPERATIONS_PERFORMED]=JSON.stringify(this.localOperationsPerformed)),this.trouterWaitOperations.length&&(this.telemetryData[dd.TROUTER_WAIT_OPERATIONS]=JSON.stringify(this.trouterWaitOperations)),this.localOfferAnswerGenerationTimestamps.length&&(this.telemetryData[dd.LOCAL_OFFER_ANSWER_GENERATION_TIMESTAMPS]=JSON.stringify(this.localOfferAnswerGenerationTimestamps)),this.incomingModalities.length&&(this.telemetryData[dd.INCOMING_MODALITIES]=JSON.stringify(this.incomingModalities)),this.outgoingModalities.length&&(this.telemetryData[dd.OUTGOING_MODALITIES]=JSON.stringify(this.outgoingModalities)),this.offeredModalities.length&&(this.telemetryData[dd.OFFERED_MODALITIES]=this.offeredModalities),this.answeredModalities.length&&(this.telemetryData[dd.ANSWERED_MODALITIES]=this.answeredModalities),this.telemetryData[dd.CALL_END_RESULT_CATEGORIES]=this.getResultCategoryString(this.telemetryData[dd.CALL_END_RESULT_CATEGORIES]),this.telemetryData[dd.IS_SDP_IN_CALL_NOTIFICATION]=this.isSdpInCallNotification.toString(),this.vbssOperations.length&&(this.telemetryData[dd.VBSS_OPERATIONS]=JSON.stringify(this.vbssOperations)),this.recordedEvents.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.recordedEvents});this.telemetryData[dd.EVENT_TIMESTAMP_BAG]=e}if(this.rosterUpdates.length){const e=JSON.stringify({eventStart:this.callStartTime,events:this.rosterUpdates});this.telemetryData[dd.ROSTER_UPDATES_BAG]=e}const t=[];for(const e of Object.keys(this.networkRequestsStarted))t.push(this.networkRequestsStarted[e]);t.length>0&&(this.telemetryData[dd.NETWORK_REQUESTS_PENDING]=JSON.stringify(t)),this.telemetryData[dd.IS_REINVITELESS]=this.isReinviteless,this.telemetryLogger.logConversationCallModalityEvent(this.telemetryData)}getResultCategoryString(e){return e&&Array.isArray(e)?e.join(","):""}},rh=class{constructor(e,t){this.disposed=!1,this.lastSeenSeqNumbers={},this.isDominantSpeakerInfoLinkEnabled=!0,this.clientUrlsGenerated=!1,this.getClientUrls=()=>{this.clientUrlsGenerated=!0;let e=null;return this.isWebRtcCall&&(e={controlVideoStreaming:Zr(this.signalingSession,Ar.CONTROL_VIDEO_STREAMING),csrcInfo:Zr(this.signalingSession,Ar.CSRC_INFO)},this.isDominantSpeakerInfoLinkEnabled&&(e.dominantSpeakerInfo=Zr(this.signalingSession,Ar.DOMINANT_SPEAKER_INFO))),e},this.handleDominantSpeakerInfo=e=>{const t=e.body;this.logger.debug("handleDominantSpeakerInfo : ",Ne(t)),this.signalingSession.telemetryHelper.recordIncomingEventCount(bo),this.handleWebRtcNotification(Jr.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO,t.dominantSpeakerInformation)},this.handleControlVideoStreaming=e=>{const t=e.body;this.logger.debug("handleControlVideoStreaming: ",Ne(t)),this.signalingSession.telemetryHelper.recordIncomingEvent(To,e),this.handleWebRtcNotification(Jr.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING,t.controlVideoStreaming,!1)},this.handleCsrcInfo=e=>{const t=e.body;this.logger.debug("handleCsrcInfo : ",Ne(t)),this.signalingSession.telemetryHelper.recordIncomingEvent(Io,e),this.handleWebRtcNotification(Jr.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO,t.csrcInfo)},this.sendWebRtcMediaNotificationAsync=({operation:e,requestUrl:t,requestBody:i,stackRetry:n=!0},r)=>{this.logger.info("sendWebRtcMediaNotificationAsync"),aa(this.isWebRtcCall,"this is not a webrtc call"),sa(t,"correct media notification requestUrl is not provided"),sa(i,"media notification requestBody cannot be null or empty");const a=Ta(),s={url:t,payload:{payload:i},requestName:e,withoutTrouter:!0,causeId:r};return n||(s.disableRetry=!0),this.signalingSession.http.sendPostRequest(s).then((()=>{this.disposed||a.resolve()})).catch((e=>{const t=Ne(e);if(this.logger.error(`sendWebRtcMediaNotificationAsync failed because : ${t}`),!this.disposed){const t=new Error(e);t.endCode=Jr.CALL_END_NETWORK_ERROR,a.reject(t)}})),a.promise},this.dispose=()=>{this.logger.info("WebRtcSignalingManager :: dispose"),this.disposed=!0},this.signalingSession=e,this.signalingSessionCallback=t,this.isWebRtcCall=e.signalingAgentConfig.isWebRtcEnabled,this.logger=e.logger,this.lastSeenSeqNumbers[Jr.WEBRTC_NOTIFICATION_TYPE.CONTROL_VIDEO_STREAMING]=-1,this.lastSeenSeqNumbers[Jr.WEBRTC_NOTIFICATION_TYPE.DOMINANT_SPEAKER_INFO]=-1,this.lastSeenSeqNumbers[Jr.WEBRTC_NOTIFICATION_TYPE.CSRC_INFO]=-1}areClientURLsGenerated(){return this.clientUrlsGenerated}getIsDominantSpeakerInfoLinkEnabled(){return this.isDominantSpeakerInfoLinkEnabled}setIsDominantSpeakerInfoLinkEnabled(e){this.isDominantSpeakerInfoLinkEnabled=e}handleWebRtcNotification(e,t,i=!0){aa(this.isWebRtcCall,"ignoring message in non-webrtc call");const n=this.lastSeenSeqNumbers[e];i&&t.sequenceNumber<=n?this.logger.info(`ignoring ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`):(t.sequenceNumber<=n&&this.logger.info(`let listener to handle older ${e} . Last seen seq = ${n} current seq = ${t.sequenceNumber}`),this.lastSeenSeqNumbers[e]=Math.max(t.sequenceNumber,this.lastSeenSeqNumbers[e]),this.signalingSessionCallback.onWebRtcMediaNotification(e,t))}},ah=class{constructor(e,t,i,n,r,a){this.disposed=!1,this.convSubject=null,this.groupId=null,this.threadId=null,this.incomingCallCallerId=null,this.incomingCallPayload=null,this.multiParty=!0,this.isIncomingCall=!1,this.isHostLessCall=!1,this.isCastCall=!1,this.isHuddleGroupCall=!1,this.numberOfOriginalInvitees=0,this.teamsMessageId=null,this.enableGroupCallMeetupGeneration=!1,this.meetingInfo=null,this.meetingDetails=null,this.emergencyContent=null,this.transferContext=null,this.callType="default",this.callMode=0,this.transferor=null,this.onBehalfOf=null,this.onBehalfOfUserDisplayName=null,this.callQueueContext=null,this.callPhoneLineType=null,this.endpointMetadata={},this.sessionId=ra(),this.remoteCaller=null,this.acceptedElsewhereBy=null,this.parkAdditionalContextJson=null,this.serverHoldLocation=null,this.breakoutDetails=null,this.callLimits=null,this.complianceRecordingContent=null,this.backroomThreadId=null,this.realTimeState=0,this.disposing=!1,this.links={},this.provisionalMediaAnswersSeenSoFar=[],this.incomingTrouterMessagesSeenSoFar=[],this.incomingBrokerMessagesSeenSoFar=[],this.currentCallStatus=null,this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.convJoined=!1,this.keepAliveTimer=null,this.keepAliveInterval=null,this.keepAliveCount=1,this.conversationKeepAliveTimer=null,this.conversationKeepAliveInterval=null,this.conversationKeepAliveCount=1,this.remoteUser=null,this.mediaTypesToUse=null,this.lastUsedOutgoingMediaContent=null,this.lastUsedJoinCallOptions=null,this.originalRoleBeforePreheat="",this.endpointStateSequenceNumber=0,this.publishStateSequenceNumber=0,this.requestedPublishedStatesWhileConnecting=null,this.linkUpdateRequested={conversationLinks:!1,keepAliveLinks:!1},this.incomingMessageSyncResponseCache={},this.isPreheatOnly=!1,this.callStartTime=(new Date).getTime(),this.callUsesMixer=!1,this.disablePreheatDefer=Ta(),this.participantReplacementDetails={},this.meetingLiveStateSequenceNumber=0,this.meetingLayoutSequenceNumber=0,this.localParticipantUpdateSequenceNumber=0,this.isRedirectAllowed=!1,this.updateSequenceNumber=-1,this.isPromotingToRealtime=!1,this.streamInformationReceived=!1,this.startOrJoinConvResponseReceived=!1,this.updateParticipantsPromises={},this.updateEndpointState=(e,t=na(),i)=>{this.logger.info(`[${t}][requestedEndpointState=${Ne(e,!0)}]`);const n=this.links[Jr.LINKS.UPDATE_ENDPOINT_STATE],r=this.getEndpointState();this.logger.info(`[${t}][currentEndpointState=${Ne(r,!0)}] startOrJoinConvResponseReceived=${this.startOrJoinConvResponseReceived}`);const a={...r,...e,endpointStateSequenceNumber:++this.endpointStateSequenceNumber};this.telemetryHelper.recordEvent(Vo,{newEndpointState:a,causeId:t});const s=e=>0===e?.endpointProperties?.preheatProperties;if(s(a)&&this.isPreheatOnly&&(this.telemetryHelper.recordEvent(bl,{causeId:t}),this.telemetryHelper.startPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallCancelationDurationWatch()),2===this.callMode&&s(a))return this.logger.info(`[${t}][updateEndpointState skipped as mode is streaming]`),this.handleEndpointStateUpdated(t,!0),Promise.resolve();if(!this.startOrJoinConvResponseReceived)return this.logger.info(`[${t}][updateEndpointState will be queued as we don't have a link yet]`),this.requestedEndpointStateWhileConnecting=e,s(a)?(this.requestedPublishedStatesWhileConnecting=i,this.disablePreheatDefer.promise):Promise.resolve();if(!this.shouldUpdateEndpointState(r,a)&&!this.http.hasPendingRequest(sd.UPDATE_ENDPOINT_STATE.name))return this.logger.info(`[${t}][updateEndpointState will ignore current update as there is nothing new to send]`),Promise.resolve();if(!n)return this.logger.info(`[${t}][updateEndpointState operation cannot be performed now, the link is not yet available]`),Promise.reject("No link");this.latestEndpointState=a;const o=this.signalingAgentConfig.enableAsyncDisablePreheat&&s(a);o&&this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT,(()=>{const e={code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.DISABLE_PREHEAT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.DISABLE_PREHEAT_TIMEOUT};this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject({response:e})}),Jr.TIMEOUT_VALUES_IN_SECONDS.DISABLE_PREHEAT_TIMEOUT);const l=this.http.sendPostRequest({url:n,requestName:sd.UPDATE_ENDPOINT_STATE.name,payload:Yu(this,a,i,o),causeId:t}).then((()=>(o&&(this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: true`),this.telemetryHelper.recordEvent(Qc,{causeId:t})),Promise.resolve()))).catch((e=>{if(!o)throw e;this.disablePreheatDefer.reject(e)}));return(o?this.disablePreheatDefer.promise:l).then((()=>{this.logger.info(`[${t}][updateEndpointState] asyncDisablePreheat: ${o}`),this.telemetryHelper.recordEvent(o?Kc:qc,{causeId:t}),this.disposed||this.handleEndpointStateUpdated(t,s(a))})).catch((e=>{const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointState] error: ${Ne(i)}`),s(a)&&(this.handleDisablePreheatError(i.error,o?Yc:Jc,t),this.stopCallPreheatTimer(),this.terminateEstablishedCall({code:i.error.code,subCode:i.error.subCode,phrase:i.error.phrase},{forEveryone:!1,causeId:t})),Promise.reject(i.error)}))},this.setParticipantCallLinks=e=>{e&&e.endpointDetails&&(this.participantReplacementDetails[e.id]={},e.endpointDetails.forEach((t=>{t&&t.callLinks&&(this.participantReplacementDetails[e.id][t.participantId]=t.callLinks)})))},this.clearParticipantCallLinks=e=>{this.participantReplacementDetails?.hasOwnProperty(e)&&delete this.participantReplacementDetails[e]},this.getReplacementDetailsByParticipantLeg=(e,t,i=na())=>(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: participantMri ${De(e)} participantLegId ${t}`),this.participantReplacementDetails?.hasOwnProperty(e)&&this.participantReplacementDetails[e].hasOwnProperty(t)?{replaces:this.participantReplacementDetails[e][t].replacement,replacementTargetParticipantId:t}:(this.logger.info(`[${i}]getReplacementDetailsByParticipantLeg: unable to find replacement details for participantLegId ${t}`),{})),this.getReplacementDetailsByParticipantLegOfCall=(e,t,i,n=na())=>{this.logger.info(`[${n}]getReplacementDetailsByParticipantLegOfCall: callId ${e} participantMri ${De(t)} participantLegId ${i}`);const r=this.signalingAgent.getSignalingSession(e);return r?r.getReplacementDetailsByParticipantLeg(t,i,n):{}},this.getMriByParticipantLegOfCall=(e,t,i)=>{this.logger.info(`[${i}]getMriByParticipantLegOfCall: callId: ${e} participantLegId ${t}`);const n=this.signalingAgent.getSignalingSession(e);return n?n.getMriByParticipantLeg(t,i):""},this.getMriByParticipantLeg=(e,t)=>{this.logger.info(`getMriByParticipantLeg[${t}] participantLegId ${e}`);for(const t of Object.keys(this.participantReplacementDetails))if(t&&this.participantReplacementDetails.hasOwnProperty(t)&&this.participantReplacementDetails[t]?.hasOwnProperty(e))return t;return""},this.handleEndpointStateUpdated=(e,t)=>{this.requestedEndpointStateWhileConnecting=null,this.requestedPublishedStatesWhileConnecting=null,t&&this.handlePreheatDisabled(e)},this.handlePreheatDisabled=e=>{this.isPreheatOnly=!1,this.telemetryHelper.setSelfParticipantRole(this.originalRoleBeforePreheat),this.telemetryHelper.recordEvent(Il,{causeId:e}),this.telemetryHelper.resetCallCancelationDurationWatch(),this.telemetryHelper.stopPreheatedCallSetupDurationWatch(),this.telemetryHelper.startCallConnectedWatch(),this.stopCallPreheatTimer(),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.resolve()},this.shouldUpdateEndpointState=(e,t)=>{if(!t)return!1;const i=t.state&&t.state.isMuted?1:0,n=t.endpointProperties&&1===t.endpointProperties.preheatProperties?1:0,r=e&&e.state&&e.state.isMuted?1:0,a=e&&e.endpointProperties&&1===e.endpointProperties.preheatProperties?1:0,s=e?.endpointProperties?.additionalEndpointProperties,o=t?.endpointProperties?.additionalEndpointProperties;return!!(i^r||n^a||o!==s)},this.setInitialTelemetry=(e,t)=>{let i,n;switch(e){case"Subscribe":this.telemetryHelper.recordEvent(Os,{causeId:t.causeId,correlationId:t.correlationId}),this.telemetryHelper.setDirection(vd.INCOMING),this.telemetryHelper.setSelfParticipantRole(Sd.JOIN_FOR_ROSTER_ONLY),this.telemetryHelper.setConversationServiceUrl(t.conversationServiceUrl||this.signalingAgentConfig.conversationServiceUrl),this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);break;case"Acknowledge":this.telemetryHelper.recordEvent(Ns,{causeId:t.causeId}),this.telemetryHelper.setDirection(vd.INCOMING),this.telemetryHelper.setSelfParticipantRole(Sd.CALLEE),this.telemetryHelper.setCalleeType(this.participantManager.localParticipant.id);break;case"JoinCall":i=this.gatherTelemetryForStartOrJoin(t.joinCallOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent(Ds,i),this.telemetryHelper.setDirection(vd.INCOMING),this.telemetryHelper.setSelfParticipantRole(Sd.JOIN);break;case"StartCall":case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":n=this.gatherTelemetryForStartOrJoin(t.callStartOptions,t.causeId,t.offerGenerationTime),this.telemetryHelper.recordEvent(ks,n),this.telemetryHelper.setDirection(vd.OUTGOING),this.telemetryHelper.setSelfParticipantRole(Sd.CALLER),this.telemetryHelper.startCallInitializationWatch(t.offerGenerationTime),this.telemetryHelper.setMeetingInfo(this.getMeetingInfo())}},this.getParticipantIdForOfferAnswer=e=>{oa(e,"mediaContent should be a non null value"),this.logger.info("getParticipantIdForOfferAnswer");let t=null;return!this.remoteUser||this.groupId||this.threadId||e.newOffer||e.escalationOccurring||(t=this.remoteUser.id),t},this.getMeetingInfo=()=>this.meetingInfo,this.getEmergencyContent=()=>(this.telemetryHelper.recordEvent(Is),this.emergencyContent),this.getEndpointId=()=>this.signalingAgent.endpointId,this.getConversationUrl=()=>this.links[Jr.LINKS.CONVERSATION_CONTROLLER],this.setJoinedFrom=e=>{!this.disposed&&e&&(this.telemetryHelper.recordEvent(Ts),this.telemetryHelper.setJoinedFrom(e))},this.setMeetingCode=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingCode(e)},this.setMeetingUrl=e=>{!this.disposed&&e&&this.telemetryHelper.setMeetingUrl(e)},this.setSubject=e=>{this.disposed||(this.telemetryHelper.recordEvent(Es),oa(e,"subject should be a non null value"),this.convSubject=e)},this.setDeviceType=e=>{this.disposed||(this.telemetryHelper.recordEvent(bs),e&&(this.deviceType=e,this.logger.info("setDeviceType",this.deviceType)))},this.setOfferAnswerGenerationTimestamps=e=>{this.disposed||this.telemetryHelper.setOfferAnswerGenerationTimestamps(e)},this.setTimeToRingDuration=()=>{this.disposed||this.telemetryHelper.setTimeToRingDuration()},this.setGroupId=e=>{this.telemetryHelper.recordEvent(Rs),this.groupId!==e&&e&&(aa(!this.groupId,"conversation groupId has already been set. It cannot be overwritten"),this.groupId=e)},this.setThreadId=e=>{this.telemetryHelper.recordEvent(As),oa(e,"threadId should be a non null value"),this.threadId!==e&&(aa(!this.threadId,"conversation threadId has already been set. It cannot be overwritten"),this.threadId=e)},this.setCallOptions=e=>{if(oa(e,"callOptions should be a non null value"),this.logger.info("setCallOptions",Ne(e)),this.telemetryHelper.recordEvent(Ps),e){this.teamsMessageId=e.teamsMessageId,this.meetingInfo=e.meetingInfo||null,this.emergencyContent=e.emergencyContent||null,this.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration||!1,e.broadcastContext&&(this.broadcastSession=new Vd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e.broadcastContext));try{this.endpointMetadata=JSON.parse(e.endpointMetadata)}catch(e){this.logger.warn("Unable to parse endpoint metadata")}}},this.setTransferContext=e=>{oa(e,"transferContext should not be null"),this.logger.info("Transfer: setTransferContext",e),this.telemetryHelper.recordEvent(Ms),this.transferContext=e},this.muteAsync=(e,t,i=na())=>(aa(2!==this.callMode||e!==Jr.MUTE_SCOPE.MYSELF,"mute self operation is not allowed in streaming mode"),this.logger.info(`[${i}][muteAsync][scope=${e}]`),this.telemetryHelper.recordEvent(fo,{causeId:i}),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,`[${i}]mute operation for all or specified only allowed in a connected call`),this.participantManager.muteAsync(this.links[Jr.LINKS.MUTE],e,t,i)),this.unmuteAsync=(e=na())=>(aa(2!==this.callMode,"unmute operation is not allowed in streaming mode"),this.logger.info(`[${e}][unmuteAsync]`),this.telemetryHelper.recordEvent(So,{causeId:e}),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"unmute operation only allowed in a connected call"),this.participantManager.unmuteAsync(this.links[Jr.LINKS.UNMUTE],e)),this.recordTelemetryForStartAudio=(e,t)=>(this.telemetryHelper.recordEvent(Cl,{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.recordTelemetryForStopAudio=(e,t)=>(this.telemetryHelper.recordEvent(_l,{mediaNegotiationStatus:e,causeId:t}),Promise.resolve(null)),this.rejectUnmuteRequestAsync=(e,t=na(),i)=>(aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"rejectUnmute operation only allowed in a connected call"),sa(e,"requestor must be specified"),this.logger.info(`[${t}][rejectUnmuteRequestAsync][rejectionReason=${i}]`),this.telemetryHelper.recordEvent(Eo,{causeId:t,rejectionReason:i}),this.participantManager.rejectUnmuteRequestAsync(e,t,i)),this.approveUnmuteRequestAsync=(e,t=na())=>(aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"approveUnmute operation only allowed in a connected call"),sa(e,"requestor must be specified"),this.logger.info(`[${t}][approveUnmuteRequestAsync]`),this.telemetryHelper.recordEvent(_o,{causeId:t}),this.participantManager.approveUnmuteRequestAsync(e,t)),this.sendWebRtcMediaNotificationAsync=(e,t,i=na())=>(aa(2!==this.callMode,"sendWebRtcMediaNotification operation is not allowed in streaming mode"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"webRtc media notification can only be sent in a connected call"),this.telemetryHelper.recordEvent(wo,{causeId:i}),0===e?this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:sd.SEND_APPLY_CHANNEL_PARAMETERS.name,requestUrl:this.links[Jr.LINKS.APPLY_CHANNEL_PARAMETERS],requestBody:t,stackRetry:!1},i):this.webRtcSignalingManager.sendWebRtcMediaNotificationAsync({operation:sd.SEND_CONTROL_VIDEO_STREAMING.name,requestUrl:this.links[Jr.LINKS.CONTROL_VIDEO_STREAMING],requestBody:t},i)),this.addParticipantsAsync=(e,t,i=na())=>{sa(e,"remoteParticipants should be a non null value"),aa(this.isCallOngoing()||this.isCallIdleOrRosterOnly(),"remoteParticipants can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${i}][addParticipantsAsync][addParticipantOptions=${Ne(t)}]\n            [remoteParticipantId=${e.map((e=>this.piiUtils.scrubMriOrOmit(e.id)))}]`);let n=Ka;switch(t.replacementType){case 2:n=Bl;break;case 1:case 3:n=Ya;break;default:n=Ka}this.telemetryHelper.recordEvent(n,{causeId:i}),t.groupId=this.groupId||t.groupId,t.threadId=this.threadId||t.threadId;const r=t.threadId||t.groupId?this.links[Jr.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[Jr.LINKS.ADD_PARTICIPANT],a=this.participantManager.addParticipantsAsync(e,r,this.isCallConnectedOrConnectedForRoster(),t,i);return this.currentCallStatus||this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i),a},this.addGroupModalityAsync=(e,t)=>{aa(this.isCallOngoing(),"GroupModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addGroupModalityAsync][addGroupModalityOptions=${Ne(e)}]`);const i=Za;this.telemetryHelper.recordEvent(i,{causeId:t});const n=vu(this,null,e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.ADD_PARTICIPANTS_AND_MODALITY],payload:n,requestName:sd.ADD_PARTICIPANTS_AND_MODALITY.name,causeId:t}).then((()=>{Pd.noop()})).catch((e=>{const i=fa(e,this.signalingAgentConfig);throw this.logger.info(`[${t}][sendNetworkRequestForAddingParticipant] failed:${Ne(i)}`),i.error}))},this.addBroadcastModalityAsync=(e,t)=>{if(aa(this.isCallOngoing(),"BroadcastModality can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${t}][addBroadcastModalityAsync][addBroadcastContext=${Ne(this.addBroadcastModalityAsync)}]`),this.telemetryHelper.recordEvent(po,{causeId:t}),this.broadcastSession){const e="There is already a broadcast session";return this.logger.info(e),Promise.resolve(Jr.SUCCESS_TRANSACTION_END)}this.broadcastSession=new Vd(this,this.signalingSessionCallback),this.broadcastSession.setContext(e);const i=function(e,t){return oa(e,"signalingSession cannot be null"),oa(t,"broadcastContext cannot be null"),{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},broadcast:t,links:{addModalitySuccess:Zr(e,Ar.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Zr(e,Ar.CONV_ADD_MODALITY_FAILURE)}}}}(this,e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.ADD_MODALITY],payload:i,requestName:sd.ADD_BROADCAST_MODALITY.name,causeId:t}).then((e=>(this.logger.info(`[${t}][addBroadcastModalityAsync] response: ${Ne(e)}`),this.telemetryHelper.recordEvent(mo,{causeId:t}),Jr.SUCCESS_TRANSACTION_END))).catch((e=>{const i=fa(e);return this.logger.info(`[${t}][sendNetworkRequestForAddBroadcastModalityAsync] failed:${Ne(i)}`),this.endBroadcastMeeting(t),Promise.reject(i.error)}))},this.nudgeParticipantsAsync=e=>{if(oa(e.participantsIds,"ParticipantsIds should be a non null value"),aa(this.isCallOngoing(),"Participants can only be nudged before starting an outgoing call or to an ongoing call"),this.logger.info(`[${e.causeId}][nudgeParticipantsAsync][participantsIds=${this.piiUtils.scrubParticipantsList(e.participantsIds)}][invitationData=${e.invitationData}]`),void 0===e.participantsIds||e.participantsIds.length<1)return Promise.reject("List of participants to nudge is empty");this.telemetryHelper.recordEvent(Ka,{withNudge:Jr.INVITATION_TYPE.NUDGE,causeId:e.causeId});const t=this.groupId||e.newGroupId,i=this.threadId||e.newThreadId,n=this.teamsMessageId||e.newMessageId,r=i||t?this.links[Jr.LINKS.ADD_PARTICIPANTS_AND_MODALITY]:this.links[Jr.LINKS.ADD_PARTICIPANT];return this.participantManager.nudgeParticipantsAsync(e.participantsIds,r,this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,e.causeId,e.invitationData,t,i,n)},this.callMeBackAsync=(e,t=na())=>(oa(e,"remoteParticipant should be a non null value"),this.logger.info(`[${t}][callMeBackAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent(as,{causeId:t}),this.hasGroupModality()||aa(!1,"threadId/groupId must be set before using call me back"),this.participantManager.callMeBackAsync(e,this.links[Jr.LINKS.ADD_PARTICIPANTS_AND_MODALITY],t)),this.removeParticipantAsync=(e,t=na(),i="none")=>{switch(oa(e,"remoteParticipant should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"participants can only be removed from an ongoing call"),this.logger.info(`[${t}][removeParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}] [removeEndpointScope] ${i}`),i){case"all":this.telemetryHelper.recordEvent(ls,{causeId:t});break;case"specified":this.telemetryHelper.recordEvent(cs,{causeId:t});break;default:this.telemetryHelper.recordEvent(os,{causeId:t})}return"none"!==i&&e.endpointId?this.participantManager.removeParticipantEndpointAsync(e,this.links[Jr.LINKS.REMOVE_PARTICIPANT],i,t):this.participantManager.removeParticipantAsync(e,this.links[Jr.LINKS.REMOVE_PARTICIPANT],t)},this.admitParticipantAsync=(e,t=na())=>(oa(e,"remoteParticipant should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"remoteParticipants can only be admitted to an ongoing call"),this.hasGroupModality()||aa(!1,"threadId/groupId must be set before admitting more participants to connected call"),this.logger.info(`[${t}][admitParticipantAsync][remoteParticipantId=${this.piiUtils.scrubMriOrOmit(e.id)}]`),this.telemetryHelper.recordEvent(Xa,{causeId:t}),this.participantManager.admitParticipantAsync(e,this.links[Jr.LINKS.ADMIT],t)),this.admitAsync=e=>{if(this.logger.info(`[${e}][admitAsync]`),this.telemetryHelper.recordEvent(ts,{causeId:e}),!this.links[Jr.LINKS.ADMIT_ALL]){const t={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.ADMIT_ALL_LINK_MISSING,phrase:Jr.CALL_END_PHRASE.ADMIT_ALL_URL_MISSING};return this.telemetryHelper.recordEvent(ns,{causeId:e,transactionEnd:t}),this.logger.warn(`admitAsync error ${JSON.stringify(t)}`),Promise.reject(t)}const t=Ta();return this.callOperationHandler.setPendingOperation(0,e,{promise:t,causeId:e},e),this.sendNetworkRequestForAdmit(e),t.promise},this.updateMeetingRolesAsync=(e,t,i=na())=>(oa(e,"participants array should be a non null value"),oa(t,"meetingRole should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"remote participant roles can only be updated in an ongoing call"),this.logger.info(`[${i}][updateMeetingRolesAsync][participants=${this.piiUtils.scrubMriOrOmit(e)}]`),this.participantManager.updateMeetingRolesAsync(e,t,this.links[Jr.LINKS.UPDATE_PARTICIPANT_ROLE],i)),this.startContentSharingAsync=(e,t,i,n,r=na())=>(oa(e,"contentIdentifier should be a non null value"),aa(this.isCallOngoing(),"contentSharing can only be added before starting an outgoing call or to an ongoing call"),this.logger.info(`[${r}][startContentSharingAsync]`),this.telemetryHelper.recordEvent(Xs,{causeId:r}),this.contentSharingManager.startContentSharingAsync(e,t,i,this.links[Jr.LINKS.ADD_MODALITY],this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,r,n)),this.deleteContentSharingAsync=(e,t=na())=>(this.logger.info(`[${t}][deleteContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent(to,{causeId:t,correlationId:e}),this.contentSharingManager.deleteContentSharingAsync(e,t)),this.joinContentSharingAsync=(e,t=na())=>(this.logger.info(`[${t}][joinContentSharingAsync][correlationId=${e}]`),this.telemetryHelper.recordEvent(ro,{causeId:t,correlationId:e}),this.contentSharingManager.joinContentSharingAsync(e,t)),this.updateContentSharingSessionStateAsync=(e,t,i=na())=>(oa(t,"sessionState should be a non null value"),this.telemetryHelper.recordEvent(no,{causeId:i,correlationId:e}),this.logger.info(`[${i}][updateContentSharingSessionStateAsync][correlationId=${e}][sessionState=${t}]`),this.contentSharingManager.updateContentSharingSessionStateAsync(e,t,i)),this.takeContentSharingControlAsync=(e,t=na())=>(this.telemetryHelper.recordEvent(io,{causeId:t,correlationId:e}),this.logger.info(`[${t}][takeContentSharingControlAsync][correlationId=${e}]`),this.contentSharingManager.takeContentSharingControlAsync(e,t)),this.updateContentSharingParticipantStateAsync=(e,t=na())=>(this.telemetryHelper.recordEvent(ao,{causeId:t}),this.logger.info(`[${t}][updateContentSharingParticipantStateAsync][correlationId=${e}]`),this.contentSharingManager.updateContentSharingParticipantStateAsync(e,t)),this.configureEndpointStateForStartOrJoin=e=>{const t={endpointStateSequenceNumber:this.endpointStateSequenceNumber};let i=!1;if(e&&(e.muted&&(i=!0,Object.assign(t,{state:{isMuted:e.muted}})),e.isPreheatOnly||e.additionalEndpointProperties)){const n={};i=!0,e.isPreheatOnly&&(n.preheatProperties=1),e.additionalEndpointProperties&&(n.additionalEndpointProperties=e.additionalEndpointProperties),Object.assign(t,{endpointProperties:n})}if(i)return t},this.gatherTelemetryForStartOrJoin=(e,t,i)=>{const n={causeId:t};return e&&(e.invitationType===Jr.INVITATION_TYPE.NUDGE&&(n.withNudge=e.invitationType===Jr.INVITATION_TYPE.NUDGE),e.parkContext&&(n.unpark=!0,n.context=e.parkContext),e.isPreheatOnly&&(n.isPreheatOnly=!0),e.targetApplicationType&&(n.targetApplicationType=e.targetApplicationType,this.telemetryHelper.setTargetApplicationType(e.targetApplicationType))),n},this.startOutgoingCall=(e,t,i,n,r=na())=>{if(oa(e,"mediaContent should be a non null value"),oa(e.blob,"outgoingSdp should be a non null value"),aa(this.isCallIdleOrRosterOnly(),"a call is already in progress"),this.logger.info(`[${r}][startOutgoingCall][start] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${r}][startOutgoingCall][failed][reason=Session disposed]`);this.lastUsedJoinCallOptions={muted:i?i.muted:null,scenario:i?i.scenario:null,isPreheatOnly:i?i.isPreheatOnly:null,clientEndpointCapabilities:i?i.clientEndpointCapabilities:null,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null},this.originalRoleBeforePreheat=Sd.CALLER,i&&i.scenario&&this.telemetryHelper.setScenario(i.scenario),this.logger.info(`[${r}][startOutgoingCall]options=${Ne(this.gatherTelemetryForStartOrJoin(i,r,n))}`),this.isBrokerEnabledForOutgoingCall()&&this.setupBrokerChannel(),this.callUsesMixer=!(!i||!i.callUsesMixer),this.fsmState=Jr.SIGNALING_FSM_STATE.OUTGOING,this.meetingData=i?.meetingData,this.meetingPreferences=i?.meetingPreferences;const a={newCall:!0,suppressDialout:i&&i.suppressDialout||!1,conversationServiceUrl:this.signalingAgentConfig.conversationServiceUrl,onBehalfOf:i?i.onBehalfOf:null,onBehalfOfUserDisplayName:i?i.onBehalfOfUserDisplayName:null,callQueueContext:i?i.callQueueContext:null,callToVoicemail:!!i&&i.callToVoicemail,voicemailResourcePath:i?i.voicemailResourcePath:null,voicemailItemId:i?i.voicemailItemId:null,endpointState:this.configureEndpointStateForStartOrJoin(i),invitationType:i&&i.invitationType?i.invitationType:null,participantsToNudge:i&&Array.isArray(i.participantsToNudge)?i.participantsToNudge:null,routingFlags:i?i.routingFlags:null,parkContext:i?i.parkContext:null,pickupCode:i?i.pickupCode:null,scenario:i?i.scenario:null,isPreheatOnly:!!i&&i.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:i?i.clientEndpointCapabilities:0,clientEndpointDebugContent:i?i.clientEndpointDebugContent:null,invitationData:i?i.invitationData:null,conversationType:i?this.getConversationType(i.isEmergency,i.castCall,i.isHuddleGroupCall):null,meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,alternateId:i?i.alternateId:null,meetingRegistrationId:i?i.meetingRegistrationId:null,participantPin:i?i.participantPin:null,publishedStates:i?i.publishedStates:null,targetApplicationType:i?i.targetApplicationType:null,captchaContentJson:i?i.captchaContentJson:null};this.isCastCall=i&&i.castCall,this.isHuddleGroupCall=i&&i.isHuddleGroupCall,this.onBehalfOf=a.onBehalfOf,this.onBehalfOfUserDisplayName=a.onBehalfOfUserDisplayName,this.callQueueContext=a.callQueueContext,this.startOrJoinCall(a,sd.START_CALL.name,r,e,t)},this.joinGivenConversation=(e,t,i,n,r,a={},s=na())=>{if(oa(t,"correlationId should be a non null value"),sa(e||this.getConversationUrl(),"conversationUrl should be a non null value"),oa(i,"mediaContent should be a non null value"),oa(i.blob,"outgoingSdp should be a non null value"),this.isPromotingToRealtime=2===this.callMode,aa(this.isCallIdleOrRosterOnly()||this.isPromotingToRealtime,"a call is already in progress"),this.logger.info(`[${s}][joinGivenConversation][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed)return void this.logger.warn(`[${s}][joinGivenConversation][failed][reason=Session disposed]`);const o=this.gatherTelemetryForStartOrJoin(a,s,r);this.lastUsedJoinCallOptions=a,this.originalRoleBeforePreheat=Sd.JOIN,this.telemetryHelper.startCallInitializationWatch(r),a&&a.scenario&&this.telemetryHelper.setScenario(a.scenario),this.logger.info(`[${s}][joinGivenConversation]options=${Ne(o)}`),this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=Jr.SIGNALING_FSM_STATE.OUTGOING,this.updateCorrelationId(t,s),this.meetingData=a?.meetingData,this.meetingPreferences=a?.meetingPreferences;const l={newCall:!1,suppressDialout:!0,conversationServiceUrl:e,endpointState:this.configureEndpointStateForStartOrJoin(a),scenario:a?a.scenario:null,isPreheatOnly:!!a&&a.isPreheatOnly,applicationType:this.participantManager.localParticipant.applicationType,clientEndpointCapabilities:a?a.clientEndpointCapabilities:0,clientEndpointDebugContent:a?a.clientEndpointDebugContent:null,conversationType:a?this.getConversationType(a.isEmergency,!1):null,meetingPreferences:this.meetingPreferences,meetingData:this.meetingData,meetingRegistrationId:a?.meetingRegistrationId,participantPin:a?.participantPin,sharedLineCallInvitationContent:a?.sharedLineCallInvitationContent,applyServerMute:a?.applyServerMute,publishedStates:a?.publishedStates,invitationData:a?.invitationData,captchaContentJson:a?.captchaContentJson,callQueueContext:a?.callQueueContext};this.isCastCall=!1,this.startOrJoinCall(l,sd.JOIN_CONVERSATION.name,s,i,n)},this.subscribeToCall=(e,t,i=0,n,r=na())=>{oa(t,"correlationId should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.IDLE,"a call is already in progress");let a=e;return a||(a=this.signalingAgentConfig.conversationServiceUrl,this.logger.info(`conversationServiceUrl passed is empty. so it is set to ${a}`)),sa(a,"conversationUrl should be a non null value"),this.logger.info(`[${r}][subscribeToCall][start][correlationId=${t}] applicationType=${this.participantManager.localParticipant.applicationType}`),this.disposed?(this.logger.warn(`[${r}][subscribeToCall][failed][reason=Session disposed]`),Promise.reject(Jr.CALL_END_CODE.CALL_DOES_NOT_EXIST)):(this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.lastUsedJoinCallOptions=n||{},this.lastUsedJoinCallOptions.clientEndpointCapabilities=i||this.lastUsedJoinCallOptions?.clientEndpointCapabilities,this.meetingData=n?.meetingData,this.meetingPreferences=n?.meetingPreferences,this.fsmState=Jr.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY,this.updateCorrelationId(t,r),this.http.sendPostRequest({url:a,requestName:sd.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,operationType:"CallSetup",payload:Fu(this,null,null,{subscribe:!0,clientEndpointCapabilities:i,...n,applicationType:this.participantManager.localParticipant.applicationType,endpointState:this.configureEndpointStateForStartOrJoin({additionalEndpointProperties:n?.additionalEndpointProperties})},r),causeId:r}).then((e=>{this.disposed||(this.fsmState=Jr.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.processConversationServiceResponseHeaders(e,r),this.processConversationServiceResponse(e.response,r,1),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY,r))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return Promise.resolve();const t=fa(e,this.signalingAgentConfig);return this.logger.info(`[${r}][subscribeToCall] error: ${Ne(e)} xhrError: ${Ne(t)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,endCode:t.telemetryEndSubCode,endSubCode:t.error.subCode,resultCategories:t.error.resultCategories,resultDetail:t.error.phrase||this.getTerminatingCallResultDetail("subscribe",t.error),causeId:r}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,r,t.error),Promise.reject(t.error))})))},this.getCallReplacementDetailsForCall=(e,t=na())=>{this.logger.info(`[${t}] getCallReplacementDetailsForCall callId ${e}`);const i=this.signalingAgent.getSignalingSession(e);return i?i.getCallReplacementDetails(t):{replaces:""}},this.getCallReplacementDetails=(e=na())=>(this.logger.info(`[${e}] getCallReplacementDetails`),{replaces:this.links[Jr.LINKS.REPLACE]}),this.transferCallAsync=(e,t,i,n,r=na())=>{this.logger.info(`[${r}] transferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(e)} transferType ${t} callTransferOptions: ${Le(n)}`),this.transferHelper(e,t,i,n,r)},this.redirectCall=(e,t=na(),i)=>{const{id:n,endpointType:r,type:a}=e.redirectOptions;if(this.logger.info(`[${t}] redirectCall: targetId: ${this.piiUtils.scrubMriOrOmit(n)} targetEndpointType ${r}`),!this.isRedirectAllowed){const e={code:Jr.CALL_END_CODE.REJECT,phrase:Jr.CALL_END_PHRASE.CALL_REDIRECT_IS_NOT_ALLOWED};return Promise.reject(e)}this.telemetryHelper.recordEvent(Po,{causeId:t});const s=function(e,t,i,n){oa(e,"signalingSession cannot be null");const r=e.participantManager.localParticipant;return{payload:{invitationRedirection:{target:{type:t,endpointType:n,id:i},sender:{id:r.id,endpointId:r.endpointId,participantId:r.participantId,languageId:r.languageId}}}}}(this,a,n,r);return this.http.sendPostRequest({url:this.links[Jr.LINKS.REDIRECT],requestName:sd.SEND_CALL_REDIRECT_REQUEST.name,payload:s,causeId:t}).then((n=>(this.logger.info(`[${t}][redirectCall] succeeds. Leaving the call...`),this.telemetryHelper.recordEvent(Rl,{causeId:t,targetEndpointType:r}),this.terminateEstablishedCall(i,e)))).catch((e=>{const n=fa(e);this.logger.info(`[${t}][redirectCall] error: ${Ne(n)}`);const a=n.error;return this.telemetryHelper.recordEvent(Mo,{causeId:t,transactionEnd:a,endpointType:r}),this.disposed||(this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,endCode:i.code,endSubCode:i.subCode,clientReasonSubCode:i.clientReasonSubCode,clientReasonPhrase:i.clientReasonPhrase,resultDetail:i.phrase||"RedirectCall",resultCategories:i.resultCategories,causeId:t}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,i),this.dispose(i,t)),Promise.reject(a)}))},this.transferHelper=(e,t,i,n,r=na())=>{aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet");let a=!1;this.logger.info(`[${r}][transferHelper][replacementDetails=${Ne(i)}] disableForwardingAndUnanswered=${n&&n.disableForwardingAndUnanswered}`),this.telemetryHelper.recordEvent(Ro,{causeId:r}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(r,a)}),Jr.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT),this.http.sendPostRequest({url:this.links[Jr.LINKS.TRANSFER],requestName:sd.SEND_TRANSFER_REQUEST.name,payload:Wu(e,this,i,t,n),causeId:r}).then((()=>{this.telemetryHelper.recordEvent(Nl,{causeId:r}),a=!0})).catch((e=>{const t=fa(e,this.signalingAgentConfig);this.logger.info(`[${r}][transferCallAsync] error: ${Ne(t)}`),this.disposed||(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:Jr.CALL_END_CODE.NETWORK_ERROR,reason:Ne(e)}},r),this.telemetryHelper.recordEvent(Al,{causeId:r,...t.error}))})),this.telemetryHelper.recordEvent(wl,{causeId:r,transferType:t})},this.consultTransferCallAsync=(e,t,i,n,r)=>{let a,s;if(this.logger.info(`[${n}] consultTransferCallAsync: transferTargetMri: ${this.piiUtils.scrubMriOrOmit(t)} transferTargetParticipantLegId: ${i}`),i?(s=this.getMriByParticipantLegOfCall(e,i,n),a=this.getReplacementDetailsByParticipantLegOfCall(e,t,i,n)):(s=t,a=this.getCallReplacementDetailsForCall(e,n)),!s||!a){const r=a?"target mri corresponding not found":`unable to retrieve replacementDetails for transferTargetCallId: ${e}, transferTargetMri: ${t}, transferTargetParticipantLegId: ${i}`;return this.logger.info(`[${n}] consultTransferCallAsync: error: ${r}`),void this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:Jr.CALL_END_CODE.BAD_REQUEST,reason:r}},n)}this.transferHelper(s,"TransferTypeStandard",a,r,n)},this.isParkByTransfer=(e,t)=>{const i=["serverHold","sharedLinePark","teamPark"].indexOf(e)>-1;return this.logger.info(`[${t}][isParkByTransfer][context=${e}] result = ${i}`),i},this.parkCallAsync=(e,t=na())=>{if(e&&"none"===e)throw{code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};return aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"call is not connected yet"),this.logger.info(`[${t}][parkCallAsync][context=${e}]`),this.telemetryHelper.recordEvent(Ao,{causeId:t,parkType:ka(e)}),this.isParkByTransfer(e,t)?this.parkByTransfer(e,t):this.park(e,t)},this.unparkAsync=(e,t=na())=>{if(e&&"none"===e)throw{code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark context is missing or none"};if(!this.links[Jr.LINKS.UNPARK])throw{code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.PARK_UNPARK_TYPE_MISSING,phrase:"Unpark link not available"};this.logger.info(`[${t}][unparkAsync][context=${e}]`),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UNPARK_COMPLETION,(()=>{this.handleUnparkError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UNPARK_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UNPARK_COMPLETION_TIMEOUT},sc,t,e)}),Jr.TIMEOUT_VALUES_IN_SECONDS.UNPARK_COMPLETION_TIMEOUT);const i={causeId:t};return this.http.sendPostRequest({url:this.links[Jr.LINKS.UNPARK],requestName:sd.SEND_UNPARK_REQUEST.name,payload:Ku(this,i),causeId:t}).then((e=>(this.logger.info(`[${t}][unparkAsync] response: ${Ne(e)}`),this.telemetryHelper.recordEvent(ac,{causeId:t}),Promise.resolve()))).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${t}][unparkAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUnparkError(n.error,rc,t,e),Promise.reject(n.error))}))},this.handleUpdateParticipantsPropertiesCompletion=e=>{const t=e.body,i=ya(e),n=this.logger.createChild(`[${i}][handleUpdateParticipantsPropertiesCompletion]`,this.correlationId),r={};if(this.disposed)n.info("ignored. Call disposed.");else{if(t.operationId||n.warn("operationId is undefined."),n.info("starts"),t.participantInfos)for(const e of t.participantInfos){if(!e.participant.id){n.warn("participant id is undefined."),this.telemetryHelper.recordEvent(Oc,"participant id is undefined in response, property");continue}if(!e.participant.key){n.warn("property name (key) is undefined."),this.telemetryHelper.recordEvent(Oc,"property name (key) is undefined in response");continue}const a=Ru(e.participant.id,t.operationId,e.participant.key),s={code:e.transactionEnd.code,subCode:e.transactionEnd.subCode,phrase:e.transactionEnd.phrase,resultCategories:e.transactionEnd.resultCategories};n.info(`Update participants properties completed for: ${this.piiUtils.scrubMriOrOmit(e.participant.id)} with transactionEnd ${Ne(s)}`),this.telemetryHelper.recordEvent(Nc,{causeId:i,resolveId:this.piiUtils.scrubMriOrOmit(a),property:e.participant.key,result:Ne(s)}),r[a]=s,this.updateParticipantsPromises[t.operationId].delete(a)}this.checkAndCleanupPromisesForOperationId(t.operationId),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(r,t.operationId,i)}},this.getCallStatus=()=>this.currentCallStatus,this.processIncomingCallRequest=(e,t,i=na())=>{if(oa(e,"request should be a non null value"),sa(e.body,"request should have a valid body"),sa(e.body.gp||e.body.cp,"request body should have payload"),aa(this.isCallIdleOrRosterOnly(),"a call is already in progress"),this.callUsesMixer=e.fromMixer,this.logger.info(`[${i}][processIncomingCallRequest][start]`),this.disposed)return void this.logger.warn("processIncomingCallRequest canceled");this.telemetryHelper.startCallInitializationWatch(),this.isIncomingCall=!0,this.isBrokerEnabledForIncomingCall()&&this.setupBrokerChannel(),this.fsmState=Jr.SIGNALING_FSM_STATE.INCOMING,this.participantManager.initializeForIncomingCall();let n={};try{t&&(n=JSON.parse(t))}catch(e){this.logger.warn("Unable to parse endpoint metadata")}this.endpointMetadata=n;try{let t;if(e?.body?.gp&&!Ue(e.body.gp))this.logger.info(`[${i}][processIncomingCallRequest] unencoded payload, skipping decoding.`),t=e.body.gp;else{const i=e.body.gp?atob(e.body.gp):Ea(e.body.cp);t=JSON.parse(i)}if(!t.callNotification)throw this.logger.info(`[${i}][processIncomingCallRequest][failed][reason=CallNotification missing]`),new Error("CallNotification is missing");this.processIncomingCallPayload(t,i),this.incomingCallPayload=t}catch(e){this.endIncomingCallBecauseOfInvalidPayload(i)}},this.sendAttachToCall=(e=na())=>(this.logger.info(`[${e}][sendAttachToCall]`),this.incomingCallPayload?(this.onCallStatusChanged(Jr.CALL_STATUS.IDLE,e),this.sendAttachToCallInternal(e)):(this.endIncomingCallBecauseOfInvalidPayload(e),Promise.reject(Jr.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD))),this.supportsNewOfferRequest=()=>this.signalingAgentConfig.handleNewOfferRequest,this.requestNewOffer=(e,t=na())=>(this.telemetryHelper.recordEvent(ol,{compatibleContentTypes:e,causeId:t}),this.signalingAgentConfig.handleNewOfferRequest?(sa(this.links[Jr.LINKS.NEW_OFFER],"newOffer link should be a non null value"),this.http.sendPostRequest({url:this.links[Jr.LINKS.NEW_OFFER],requestName:sd.REQUEST_NEW_OFFER.name,payload:Bu(this,e,this.links[Jr.LINKS.NEW_OFFER]),causeId:t}).then((e=>this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):Promise.resolve(e))).catch((e=>{const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[requestNewOffer][${t}] error ${Ne(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||this.getTerminatingCallResultDetail("requestNewOffer",i.error),causeId:t}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,i.error),this.dispose(i.error,t),Promise.reject(i.error))}))):Promise.reject("Disabled")),this.endAsync=(e,t={})=>{t.causeId=t.causeId||na();const i=t.causeId;if(this.logger.info(`[${i}][endAsync][rejectionData=${e&&Ne(e)}][endCallForAll=${t.forEveryone}]`),this.disposed)return this.logger.warn(`[${i}][endAsync] canceled but session already disposed`),Promise.resolve(null);if(this.disposing=!0,this.telemetryHelper.recordEvent(Ls,e?{code:e.code,subCode:e.subCode,causeId:i,callEndClientSubCode:e.clientReasonSubCode,callEndClientPhrase:e.clientReasonPhrase}:{causeId:i}),t.preventAllCallbacks){const e=Object.keys(this.signalingSessionCallback);for(const t of e)this.signalingSessionCallback[t]=Pd.noop}const n=this.mediaRenegotiationManager?.isIncomingRenegotiationInProgress()||this.mediaRenegotiationManager?.isOutgoingRenegotiationInProgress();if(this.telemetryHelper.stopCallCancelationDurationWatch(),this.fsmState===Jr.SIGNALING_FSM_STATE.INCOMING)return e.code===Jr.CALL_END_CODE.CALL_REDIRECTED?this.redirectCall(t,i,e):this.rejectIncomingCall(e,i);if(this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING||this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY)return this.cancelOutgoingCall(e,i);if(this.fsmState===Jr.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK)return this.rejectIncomingCall(e,i);if((this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED||n)&&t.forEveryone)return this.deleteConversation(e,i);if(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY||n)return this.terminateEstablishedCall(e,t);{this.logger.info(`[${i}][endAsync] there is no call to cancel or end or reject in current state`);const t={code:isNaN(e?.code)?Jr.CALL_END_CODE.NOT_FOUND:e.code,subCode:isNaN(e?.subCode)?Jr.CALL_END_SUB_CODE.CALL_NOT_ATTEMPTED:e.subCode,phrase:e?.phrase||Jr.CALL_END_PHRASE.CALL_DOES_NOT_EXIST,resultCategories:e?.resultCategories||[_r],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};return this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultDetail:t.phrase||"CallDoesNotExist",endCode:t.code,endSubCode:t.subCode,resultCategories:t.resultCategories,causeId:i,clientReasonSubCode:t.clientReasonSubCode,clientReasonPhrase:t.clientReasonPhrase}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,i,t),this.dispose(t,i),Promise.resolve(null)}},this.handleIncomingMsgAsync=(e,t=Jr.INCOMING_MESSAGE_ORIGIN.TROUTER)=>{oa(e,"incoming message should be a non null value");const i=Sa(e),n=Ta(),r=e.body,a=e.url,s={...e,origin:t},o=ya(s);if(this.logger.info(`[${o}][handleIncomingMsgAsync][url=${a}][messageId=${i}]`),!r)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(Qo,{origin:t,messageId:i,causeId:o}),n.reject(new Error("received message with no body")),n.promise;if(this.disposed)return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=call is disposed]`),n.reject(this.getCallNotFoundTransactionEnd()),n.promise;if(this.isDuplicatedIncomingMessage(s))return this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=duplicate]`),this.telemetryHelper.recordEvent(No,{origin:t,messageId:i,causeId:o}),n.resolve(new Error("Message was already handled")),n.promise;this.checkCorrelationIdChange(e,o);const l={[Pr]:e=>{this.handleCallNotification(e)},[Mr]:e=>{this.handleMediaAnswer(e)},[kr]:e=>{this.handleMediaAcknowledgement(e)},[Dr]:e=>{this.handleCallAcceptance(e)},[Or]:e=>{this.handleCallEnd(e)},[Nr]:e=>{this.handleCallProgress(e)},[Lr]:e=>{this.handleCallAcceptanceAck(e)},[xr]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationOffer(e)},[Fr]:e=>{this.mediaRenegotiationManager?.handleMediaNegotiationFailure(e)},[Ur]:e=>{this.handlePSTNBalanceUpdate(e)},[Br]:e=>{this.mediaRenegotiationManager?.handleRetargetCompleted(e)},[Vr]:e=>{this.handleTransferRequested(e)},[Hr]:e=>{this.handleTransferCompletion(e)},[$r]:e=>{this.handleTransferAcceptance(e)},[Gr]:e=>{this.handleParkCompletion(e)},[jr]:e=>{this.handleUnparkCompletion(e)},[zr]:e=>{this.handleUpdateMeetingLiveStateCompletion(e)},[Wr]:e=>{this.handleUpdateMeetingGroupsCompletion(e)},[qr]:e=>{this.handleSetMeetingLayoutCompletion(e)},[Kr]:e=>{this.handleUpdateMeetingStatesCompletion(e)}},c={[Ar.CONTROL_VIDEO_STREAMING]:e=>{this.webRtcSignalingManager.handleControlVideoStreaming(e)},[Ar.DOMINANT_SPEAKER_INFO]:e=>{this.webRtcSignalingManager.handleDominantSpeakerInfo(e)},[Ar.CSRC_INFO]:e=>{this.webRtcSignalingManager.handleCsrcInfo(e)},[Ar.CONV_ROSTER_UPDATE]:e=>{this.handleRosterUpdate(e,!1)},[Ar.NEW_MEDIA_OFFER]:e=>{this.handleNewMediaOffer(e)},[Ar.CONV_ADD_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAddParticipantSuccess(e)},[Ar.CONV_ADD_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAddParticipantFailure(e)},[Ar.CONV_ADMIT_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleAdmitParticipantSuccess(e)},[Ar.CONV_ADMIT_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleAdmitParticipantFailure(e)},[Ar.CONV_ADMIT_ALL_STATUS]:e=>{this.handleAdmitAllStatus(e)},[Ar.CONV_REMOVE_PARTICIPANT_SUCCESS]:e=>{this.participantManager.handleRemoveParticipantSuccess(e)},[Ar.CONV_REMOVE_PARTICIPANT_FAILURE]:e=>{this.participantManager.handleRemoveParticipantFailure(e)},[Ar.CONV_CONFIRM_UNMUTE]:e=>{this.participantManager.handleUnmuteConfirmRequest(e)},[Ar.CONV_UPDATE]:e=>{this.handleConversationUpdate(e)},[Ar.CONV_LOCAL_PARTICIPANT_UPDATE]:e=>{this.handleLocalParticipantUpdate(e)},[Ar.CONV_ADD_MODALITY_SUCCESS]:e=>{this.handleAddModalitySuccess(e)},[Ar.CONV_ADD_MODALITY_FAILURE]:e=>{this.handleAddModalityFailure(e)},[Ar.CONV_BROADCAST_UPDATE]:e=>{this.broadcastSession.handleBroadcastStateChanged(e)},[Ar.CONV_CONTENT_SHARING_UPDATE]:e=>{this.contentSharingManager?.handleContentSharingUpdate(e)},[Ar.CONV_CONTENT_SHARING_END]:e=>{this.contentSharingManager?.handleContentSharingEnd(e)},[Ar.CONV_END]:e=>{this.handleCallEnd(e)},[Ar.UPDATE_PARTICIPANT_INTERPRETATION_STATE_STATUS]:e=>{this.participantManager.handleUpdateParticipantInterpretationStateCompletion(e)},[Ar.UPDATE_PARTICIPANT_PROPERTIES_STATUS]:e=>{this.handleUpdateParticipantsPropertiesCompletion(e)},[Ar.JOIN_MEETING_GROUP_STATUS]:e=>{this.handleJoinMeetingGroupCompletion(e)},[Ar.LEAVE_MEETING_GROUP_STATUS]:e=>{this.handleLeaveMeetingGroupCompletion(e)},[Ar.RECEIVE_MESSAGE]:e=>{this.handleReceiveMessage(e)},[Ar.SEND_MESSAGE_STATUS]:e=>{this.proxiedMessageNotificationManager.handleProxiedMessageNotification(e)},[Ar.DISABLE_PREHEAT_ASYNC_STATUS]:e=>{this.handleDisablePreheatCompletion(e)},[Ar.MUTE_UNMUTE_ASYNC]:e=>{this.participantManager.handleMuteUnmuteAsyncResponse(e)}};try{const e=Object.keys(l).filter((e=>r.hasOwnProperty(e)))[0],t=Object.keys(c).filter((e=>s.url&&ua(s.url,e)))[0];e?l[e](s):t?c[t](s):(this.telemetryHelper.recordEvent(xo,{messageId:i}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=received unknown message]`)),n.resolve(!0)}catch(e){this.telemetryHelper.recordEvent(Fo,{messageId:i,error:Ne(e)}),this.logger.info(`[${o}][handleIncomingMsgAsync][failed][reason=${e.message}]`),n.reject(new Error(e.message))}return n.promise},this.canHandleIncomingMsgSync=e=>{if(this.signalingAgentConfig.supportsSynchronousTrouterResponse){const t=e.body;return Boolean(t.callAcceptance)}return!1},this.handleIncomingMsgSync=e=>{const t=Sa(e),i=e.body,n=e.url,r=Jr.INCOMING_MESSAGE_ORIGIN.TROUTER,a={...e,origin:r},s=ya(a);this.logger.info(`[${s}][handleIncomingMsgSync][url=${n}][messageId=${t}]`);const o=a.headers;let l=Jr.HTTP_STATUS_CODES.OK,c="";const d=new Qr;if(va(o,this.incomingTrouterMessagesSeenSoFar)){this.logger.info(`[${s}][handleIncomingMsgSync][failed][reason=duplicate]`);const e=function(e,t){return e&&t[e.get(Jr.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(Jr.HEADERS.MESSAGE_ID)||null]||null}(o,this.incomingMessageSyncResponseCache);if(e)return this.logger.info(`[${s}][handleIncomingMsgSync][cachedResponse]`),e;this.telemetryHelper.recordEvent(No,{origin:r,messageId:t,causeId:s}),this.logger.info(`[${s}][handleIncomingMsgSync][failed][reason=cachedResponseNotFound]`),l=Jr.HTTP_STATUS_CODES.BAD_REQUEST}else if(i){if(i.callAcceptance)try{c=Le(this.handleCallAcceptanceSync(a))}catch(e){this.telemetryHelper.recordEvent(Fo,{messageId:t,origin:r,causeId:s,error:Ne(e)}),this.logger.info(`[${s}][handleIncomingMsgSync][failed][reason=${e?.message}]`),l=Jr.HTTP_STATUS_CODES.BAD_REQUEST}}else this.logger.info(`[${s}][handleIncomingMsgSync][failed][reason=received message with no body]`),this.telemetryHelper.recordEvent(Qo,{origin:r,messageId:t,causeId:s}),l=Jr.HTTP_STATUS_CODES.BAD_REQUEST;o&&(o.get(Jr.HEADERS.CORRELATION_ID)&&d.set(Jr.HEADERS.CORRELATION_ID,o.get(Jr.HEADERS.CORRELATION_ID)),o.get(Jr.HEADERS.MESSAGE_ID)&&d.set(Jr.HEADERS.MESSAGE_ID,o.get(Jr.HEADERS.MESSAGE_ID)));const u={resultCode:l,responseBody:c,responseHeaders:d.getAll()};return function(e,t,i){if(e&&t){const n=e.get(Jr.HEADERS.ORIGINAL_MESSAGE_ID)||e.get(Jr.HEADERS.MESSAGE_ID)||null;n&&(t[n]=i)}}(o,this.incomingMessageSyncResponseCache,u),this.logger.info(`[${s}][handleIncomingMsgSync][success][resultCode=${l}]`),u},this.acceptRenegotiationAsync=(e,t,i=na())=>(oa(e.blob,"finalSdp should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"Renegotation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][acceptRenegotiationAsync][mediaTypes=${t}]`),this.mediaRenegotiationManager.acceptRenegotiationAsync(e,t,i)),this.setProvisionalAnswerAsync=(e,t=na())=>{oa(e.blob,"sdp should be a non null value"),this.telemetryHelper.recordEvent(Us,{causeId:t});const i=Ta();return this.fsmState!==Jr.SIGNALING_FSM_STATE.INCOMING?(this.logger.info(`[setProvisionalAnswerAsync][${t}] there is no incoming call to set provisional answer on.`),i.reject(new Error("there is no incoming call to set provisional answer on.")),i.promise):(this.http.sendPostRequest({url:this.links[Jr.LINKS.MEDIA_ANSWER],requestName:sd.SEND_MEDIA_ANSWER.name,payload:Zu(this,e),causeId:t}).then((e=>{this.disposed||this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTING,t),i.resolve(null),this.disposed||(this.telemetryHelper.recordEvent(La,{causeId:t}),this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(Jr.CALL_STATUS.RINGING,t),this.signalingSessionCallback.onMediaAcknowledgementSuccess(!1,t))})).catch((e=>{const n=fa(e,this.signalingAgentConfig);this.logger.info(`[setProvisionalAnswerAsync][${t}] error: ${Ne(n)}`),this.disposed?i.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(Bs,{causeId:t}),i.reject(n.error))})),i.promise)},this.startRenegotiationAsync=(e,t,i=na())=>(oa(e,"mediaContent should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"Renegotation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${i}][startRenegotiationAsync]`),this.mediaRenegotiationManager.startRenegotiationAsync(e,this.links[Jr.LINKS.MEDIA_RENEGOTIATION],t,i)),this.updateMediaDescriptionsAsync=(e=na(),t)=>{oa(t,"mediaDescriptions should be a non null value"),aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"updateMediaDescriptions operations are only allowed when the call is connected");const i=this.links[Jr.LINKS.UPDATE_MEDIA_DESCRIPTIONS];return oa(i,"updateMediaDescriptionsUrl should be a non null value"),this.telemetryHelper.recordEvent(Xc,{causeId:e}),this.http.sendPostRequest({url:i,requestName:sd.UPDATE_MEDIA_DESCRIPTIONS.name,payload:Xu(this,t),causeId:e}).catch((t=>{const i=fa(t,this.signalingAgentConfig);return this.logger.info(`[updateMediaDescriptionsAsync][${e}] error: ${Ne(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.telemetryHelper.recordEvent(ed,{causeId:e}),Promise.reject(i.error))}))},this.acceptAsync=(e,t,i,n=na())=>{oa(e,"mediaContent should be a non null value"),oa(e.blob,"outgoingSdp should be a non null value"),this.logger.info(`[${n}][acceptAsync][mediaTypes=${t}]`),this.telemetryHelper.recordEvent(Vs,{causeId:n}),this.telemetryHelper.setAnsweredModalities(e.blob);const r=Ta();return this.fsmState!==Jr.SIGNALING_FSM_STATE.INCOMING?(this.logger.warn("acceptAsync, there is no incoming call to accept"),r.reject(new Error("there is no incoming call to accept")),r.promise):(this.fsmState=Jr.SIGNALING_FSM_STATE.WAITING_CALL_ACCEPTANCE_ACK,this.http.sendPostRequest({url:this.links[Jr.LINKS.ACCEPT],requestName:sd.SEND_ACCEPTANCE.name,payload:Du(this,e,t,i),causeId:n}).then((e=>{this.disposed||(this.currentCallStatus===Jr.CALL_STATUS.IDLE&&(this.telemetryHelper.setTimeToRingDuration(),this.telemetryHelper.recordEvent(eo,{causeId:n}),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTING,n)),e.response.callAcceptanceAcknowledgement&&(this.logger.info("acceptAsync, handling inlined callAcceptanceAcknowledgement"),this.internalHandleCallAcceptanceAck(e.response,n))),r.resolve(null)})).catch((e=>{const t=fa(e,this.signalingAgentConfig);this.logger.info(`[acceptAsync][${n}] error: ${Ne(t)}`),this.disposed?r.reject(this.getCallNotFoundTransactionEnd()):(this.fsmState=Jr.SIGNALING_FSM_STATE.INCOMING,this.telemetryHelper.recordEvent(Hs,{causeId:n,xhrError:t}),r.reject(t.error))})),r.promise)},this.rejectRenegotiationAsync=(e,t=na())=>(aa(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED,"Renegotation operations are only allowed when the call is connected and no disconnect operation is in flight"),this.logger.info(`[${t}][rejectRenegotiationAsync][rejectionData=${e}]`),this.mediaRenegotiationManager.rejectRenegotiationAsync(e,t)),this.saveMediaControllerLinksIfAny=e=>{e.links&&(this.links[Jr.LINKS.CONTROL_VIDEO_STREAMING]=e.links.controlVideoStreaming||this.links[Jr.LINKS.CONTROL_VIDEO_STREAMING],this.links[Jr.LINKS.APPLY_CHANNEL_PARAMETERS]=e.links.applyChannelParameters||this.links[Jr.LINKS.APPLY_CHANNEL_PARAMETERS])},this.getInitialMediaOfferFromIncomingCallPayload=(e=na())=>{if(!this.signalingAgentConfig.handleMediaOfferFromPushNotification)return null;const t=this.incomingCallPayload?.callNotification?.mediaContent?this.incomingCallPayload.callNotification.mediaContent:null;return this.telemetryHelper.setIsSdpInCallNotification(!!t),t},this.updateCorrelationId=(e,t=na())=>{if(this.logger.info(`[${t}][updateCorrelationId][old=${this.correlationId}][new=${e}]`),this.correlationId!==e&&!this.disposed){const i=this.correlationId;this.correlationId=e,this.telemetryHelper&&this.telemetryHelper.recordEvent&&this.telemetryHelper.recordEvent(Lo,{newId:this.correlationId,oldId:i,causeId:t}),this.signalingSessionCallback&&this.signalingSessionCallback.onCorrelationIdUpdated&&this.signalingSessionCallback.onCorrelationIdUpdated(this.correlationId,t)}},this.endIncomingCallBecauseOfInvalidPayload=e=>{this.logger.info(`[${e}][endIncomingCallBecauseOfInvalidPayload]`),this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE;const t={code:Jr.CALL_END_CODE.BAD_REQUEST,subCode:Jr.CALL_END_SUB_CODE.BAD_NOTIFICATION_PAYLOAD,phrase:Jr.CALL_END_PHRASE.BAD_NOTIFICATION_PAYLOAD,resultCategories:[Tr]};this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,endCode:t.code,endSubCode:t.subCode,resultDetail:t.phrase||"EndIncomingCall",resultCategories:t.resultCategories,causeId:e}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,e,t),this.dispose(t,e)},this.isDuplicatedIncomingMessage=e=>e.origin===Jr.INCOMING_MESSAGE_ORIGIN.BROKER&&va(e.headers,this.incomingBrokerMessagesSeenSoFar)||e.origin===Jr.INCOMING_MESSAGE_ORIGIN.TROUTER&&va(e.headers,this.incomingTrouterMessagesSeenSoFar),this.getEndpointState=()=>{let e;return e=this.startOrJoinConvResponseReceived?{...this.latestEndpointState}:{...this.requestedEndpointStateWhileConnecting},e},this.setMultiParty=(e,t)=>{const i=!!e;this.multiParty!==i&&(this.telemetryHelper.recordEvent(ws,{isMultiparty:i,causeId:t}),this.multiParty=i)},this.setupTrouterChannel=()=>{this.logger.info(`Broker config: outgoing=${this.signalingAgentConfig.brokerEnabledOutgoing?"enabled":"disabled"}incoming=${this.signalingAgentConfig.brokerEnabledIncoming?"enabled":"disabled"}batching=${this.signalingAgentConfig.brokerRequestBatching?"enabled":"disabled"}exclusive=${this.signalingAgentConfig.brokerExclusively?"enabled":"disabled"}`);const e=e=>{e&&"string"==typeof e&&e.trim()&&(this.baseMessagingChannelUrl=this.previousTrouterUrl=this.currentTrouterUrl=e.trim(),this.telemetryHelper.addTrouterChannel())};this.brokerExclusiveEnabled()||(this.signalingAgentConfig.trouterServiceProvider?(2===this.signalingAgentConfig.trouterServiceProvider.state()&&this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync().then(e),this.signalingAgentConfig.trouterServiceProvider.onStateChanged(this.onTrouterStateChanged)):(e(this.signalingAgentConfig.trouterUrlGetter.trouterUrl()),this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed(this.onTrouterUrlChanged)))},this.isTrouterDisconnected=()=>{try{return 3===this.signalingAgentConfig.trouterServiceProvider.state()}catch(e){return!1}},this.forceTrouterConnectionCheck=()=>{try{return void this.signalingAgentConfig.trouterServiceProvider.checkConnection(!1)}catch(e){return}},this.navigatorOnlineCallback=()=>{this.disposed||(this.reportConnectivityStatus(),this.isTrouterDisconnected()&&this.signalingAgentConfig.forceTrouterReconnectOnNetworkOnline&&this.forceTrouterConnectionCheck())},this.navigatorOfflineCallback=()=>{this.reportConnectivityStatus()},this.reportConnectivityStatus=()=>{if(!this.disposed){const e=ba(this.signalingAgentConfig.trouterServiceProvider);this.logger.info(`[Connectivity] status=${e}`),this.telemetryHelper.recordEvent(Uo,{status:e})}},this.onTrouterStateChanged=(e,t)=>{const i=na();this.logger.info(`[${i}][onTrouterStateChanged][state=${e}]`),this.disposed?this.logger.info("onTrouterStateChanged ignored"):(this.reportConnectivityStatus(),2===e&&(this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(Ys,i)))},this.setupConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.addEventListener&&(window.addEventListener("online",this.navigatorOnlineCallback),window.addEventListener("offline",this.navigatorOfflineCallback))}catch(e){return}},this.tearDownConnectionCheck=()=>{try{navigator&&navigator.onLine&&window&&window.removeEventListener&&(window.removeEventListener("online",this.navigatorOnlineCallback),window.removeEventListener("offline",this.navigatorOfflineCallback))}catch(e){return}},this.getTrouterUrlAsync=()=>this.signalingAgentConfig.trouterServiceProvider?this.signalingAgentConfig.trouterServiceProvider.getTrouterUrlAsync():this.signalingAgentConfig.trouterUrlGetter.getTrouterUrlAsync(),this.brokerExclusiveEnabled=()=>this.signalingAgentConfig.brokerEnabledOutgoing&&this.signalingAgentConfig.brokerEnabledIncoming&&this.signalingAgentConfig.brokerExclusively,this.isBrokerEnabledForOutgoingCall=()=>this.signalingAgentConfig.brokerEnabledOutgoing,this.isBrokerEnabledForIncomingCall=()=>this.signalingAgentConfig.brokerEnabledIncoming,this.setupBrokerChannel=()=>{this.brokerService||(this.logger.info("setupBrokerChannel, Enable broker"),this.brokerService=new Gd(this),this.brokerService.onBrokerMessage((e=>{this.logger.info("setupBrokerChannel, message from broker",e),this.handleIncomingMsgAsync(e,Jr.INCOMING_MESSAGE_ORIGIN.BROKER).catch((e=>{this.telemetryHelper.recordEvent(Wo),this.logger.info("setupBrokerChannel, Failed to handle message from broker",e)}))})),this.baseMessagingChannelUrl||(this.telemetryHelper.addBrokerChannel(),this.baseMessagingChannelUrl=this.brokerService.baseUrl))},this.onTrouterUrlChanged=()=>{const e=na();this.logger.info(`[${e}][onTrouterUrlChanged]`),this.disposed?this.logger.info("onTrouterUrlChanged ignored"):this.getTrouterUrlAsync().then((t=>{this.telemetryHelper.recordEvent(Js,{url:t}),this.telemetryHelper.addTrouterChannel(),this.updateLinksToTrouter(Js,e)})).catch((e=>{this.logger.info(`Failed to update links to trouter: ${e}`)}))},this.updateLinksToTrouter=(e,t)=>{this.logger.info(`[${t}][updateLinksToTrouter][tag=${e}]`),this.ensureLatestTrouterUrl(e).then((()=>{this.previousTrouterUrl!==this.currentTrouterUrl?(this.previousTrouterUrl=this.currentTrouterUrl,this.updateConversationLinks(),this.updateKeepAliveUrl(),this.contentSharingManager?.updateContentSharingNotificationLinksAsync(t),this.broadcastSession&&this.broadcastSession.updateBroadcastCallbackUrl(t)):this.logger.info(`[${t}][updateLinksToTrouter]skip updating links, url did not change`)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Zs,{causeId:t}),this.logger.info(`[${t}][updateLinksToTrouter][failed][reason=${Ne(e)}]`)}))},this.updateLinks=(e,t)=>{this.ensureLatestTrouterUrl(Js).then((()=>{e(t)})).catch((e=>{this.disposed||this.telemetryHelper.recordEvent(Zs,{causeId:t}),this.logger.warn("Failed to update links")}))},this.startCallPreheatTimer=e=>{this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT,(()=>{this.handleCallEstablishmentTimeout(e,Jr.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,"Preheat timed out!"),this.terminateEstablishedCall({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.PREHEATED_CALL_TIMEDOUT,phrase:"Preheat timed out!"},{forEveryone:!1,causeId:e})}),Jr.TIMEOUT_VALUES_IN_SECONDS.MAX_PREAHEATED_TIMEOUT)},this.stopCallPreheatTimer=()=>{this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.MAX_PREAHEATED_TIMEOUT)},this.updateKeepAliveUrl=()=>{this.logger.info("updateKeepAliveUrl"),this.links.hasOwnProperty(Jr.LINKS.KEEPALIVE)?(this.linkUpdateRequested.keepAliveLinks=!1,this.logger.info("updateKeepAliveUrl, sending request"),this.sendToKeepAliveUrl(function(e){return oa(e,"signalingSession cannot be null"),{payload:{callParticipantUpdate:{links:da(e,wr),clientContentForMediaController:e.webRtcSignalingManager.getClientUrls()}}}}(this))):this.linkUpdateRequested.keepAliveLinks=!0},this.updateConversationLinks=(e=na())=>{this.logger.info(`[${e}][updateConversationLinks]`),this.telemetryHelper.recordEvent(cl,{causeId:e}),this.links.hasOwnProperty(Jr.LINKS.NOTIFICATION_LINKS)?(this.linkUpdateRequested.conversationLinks=!1,this.logger.info("updateConversationLinks, sending request"),this.sendToUpdateConversationLinks(!0)):this.linkUpdateRequested.conversationLinks=!0},this.sendAttachToCallInternal=(e=na())=>{this.telemetryHelper.recordEvent(sl,{causeId:e}),this.logger.info(`[${e}][sendAttachToCallInternal]`);const t=new Qr;return this.signalingAgentConfig.sendProgressFromCC&&t.set(Jr.HEADERS.CACHE_SKYPE_TOKEN,"1"),this.http.sendPostRequest({url:this.incomingCallPayload.callNotification.links.attach,customHeaders:t,requestName:sd.SEND_CALL_ATTACH.name,payload:Mu(this,this.incomingCallPayload.conversationInvitation.conversationController,!this.getInitialMediaOfferFromIncomingCallPayload()),causeId:e}).then((t=>{if(!this.disposed){this.processAttachResponse(this.incomingCallPayload,t,e);const i=t.response.additionalActionResponses;i&&i.length>0&&this.processConversationServiceResponse(i[0].output,e,0),this.onCallStatusChanged(Jr.CALL_STATUS.RINGING,e),this.telemetryHelper.setTimeToRingDuration(),this.handleBrokerSubscription(t.response.callInvitation,e)}})).catch((t=>{const i=fa(t,this.signalingAgentConfig);this.logger.info(`[${e}][sendAttachToCallInternal] error: ${Ne(t)} xhrError: ${Ne(i)}`),this.disposed||(this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,endCode:i.telemetryEndSubCode,endSubCode:i.error.subCode,resultCategories:i.error.resultCategories,resultDetail:i.error.phrase||this.getTerminatingCallResultDetail("attach",i.error),causeId:e}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,e,i.error),this.dispose(i.error,e))}))},this._processCallAcceptance=(e,t)=>{if(this.logger.info(`[${t}][_processCallAcceptance]`),this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING){this.processCallAcceptance(e.body,t),this.telemetryHelper.setTimeToRingDuration();try{this.multiParty||this.callUsesMixer||this.participantManager.handleRosterUpdate(this.getFakeRoster(e.body),!0,t)}catch(i){const n={code:Jr.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:Jr.CALL_END_SUB_CODE.CALL_ACCEPTANCE_INVALID_SERVICE_RESPONSE,phrase:i?.toString()};throw this.logger.info(`[${t}][_processCallAcceptance] ${Le(n)}`),this.telemetryHelper.recordRosterEvent(e,ys,t),n}}},this.restartKeepAliveInterval=(e=!1,t)=>{this.disposed||(e&&this.telemetryHelper.recordEvent(yl,t),this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval))},this.isCallOngoing=()=>this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===Jr.SIGNALING_FSM_STATE.IDLE,this.isCallIdleOrRosterOnly=()=>this.fsmState===Jr.SIGNALING_FSM_STATE.IDLE||this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,this.isCallConnectedOrConnectedForRoster=()=>this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED||this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY,a&&(this.callStartTime=a),this.signalingSessionCallback=t,this.signalingAgentConfig=i,this.signalingAgent=r,this.urlIdentifier=n,this.piiUtils=new Ad(i.piiScrubber),this.isHostLessCall=i.doHostlessCalling||!1,this.logger=i.logger.createChild((()=>`CSA[${this.correlationId}][${this.fsmState}]`),this.correlationId,!0),this.updateCorrelationId(n),this.logger.info(`[endpointId=${xe(this.signalingAgent.endpointId)}]`),this.logger.info(`[participantId=${e.participantId}]`),this.callOperationHandler=new zd(this.logger.createChild((()=>`[CallOperationHandler][${e.participantId}]`))),this.http=new du(this,this.callStartTime),this.telemetryHelper=new nh(this,e,this.callStartTime),this.mediaRenegotiationManager=new gu(this,t,this.telemetryHelper),this.participantManager=new bu(this,t,e,new Qt(this.logger)),this.proxiedMessageNotificationManager=new Au(this),this.timeoutManager=new Id(this.logger),this.contentSharingManager=new iu(this,t),this.webRtcSignalingManager=new rh(this,t),this.pstnContent={emergencyCallCountry:i.emergencyCallCountry||"",platformName:i.clientInformation,publicApiCall:!1},this.setupTrouterChannel(),this.setupConnectionCheck()}onPromotionCompleted(e,t,i){this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} error=${Ne(t)}]`),this.isPromotingToRealtime=!1,this.signalingSessionCallback.onPromotionCompleted(e,t,i)}setRealTimeState(e,t){let i=e;(2===e&&1===this.realTimeState||1===e&&2===this.realTimeState)&&(i=3),i!==this.realTimeState&&(this.logger.info(`[${t}][setRealTimeState] changed: input=${e} old=${this.realTimeState}, new=${i}`),this.realTimeState=i,3===i?this.setCallMode(1,t):0!==this.callMode||2!==i&&(this.signalingAgentConfig.disableRealTimeModeFromRoster||1!==i)||this.setCallMode(1,t))}setCallMode(e,t){this.callMode!==e&&(this.logger.info(`[${t}][setCallMode] oldMode=${this.callMode}, newMode=${e}`),this.callMode=e,this.signalingSessionCallback.onCallModeChanged(this.callMode,t))}configureStreamingMode(e){2!==this.callMode?(this.logger.info(`[${e}][configureStreamingMode]`),this.setCallMode(2,e),this.cleanUpDueToStreaming(e),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTED,e)):this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT)}updateDominantSpeakerHistoryMessageSubscription(e){this.webRtcSignalingManager.getIsDominantSpeakerInfoLinkEnabled()!==e&&(this.logger.info(`Signaling dominant speaker history subscription updated: ${e}`),this.webRtcSignalingManager.setIsDominantSpeakerInfoLinkEnabled(e),this.webRtcSignalingManager.areClientURLsGenerated()&&this.updateKeepAliveUrl())}cleanUpDueToStreaming(e){this.setRealTimeState(0,e),this.fsmState=Jr.SIGNALING_FSM_STATE.CONNECTED,this.isPromotingToRealtime=!1,this.provisionalMediaAnswersSeenSoFar=[],this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=new gu(this,this.signalingSessionCallback,this.telemetryHelper),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const t={code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.DOWNGRADE_TO_STREAMING_CLIENT,phrase:Jr.CALL_END_PHRASE.DOWNGRADE_TO_STREAMING_CLIENT},i=sd;for(const n of Object.keys(i))0!==i[n].controller&&4!==i[n].controller&&3!==i[n].controller||this.http.cancelRequestIfPending(i[n].name,e,void 0,t)}updateEndpointMetadata(e,t=na()){let i={};try{i=JSON.parse(e)}catch(e){return Promise.reject("Invalid metadata")}return this.http.sendPutRequest({url:this.links[Jr.LINKS.UPDATE_ENDPOINT_METADATA],requestName:sd.UPDATE_ENDPOINT_METADATA.name,payload:Ju(this,i),causeId:t}).then((()=>{this.telemetryHelper.recordEvent(ql,{causeId:t})})).catch((e=>{const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[${t}][updateEndpointMetadata] error: ${Ne(i)}`),this.telemetryHelper.recordEvent(Kl,{...i.error}),Promise.reject(i.error)}))}isOneToOnePSTNCall(){return this.signalingSessionCallback.isOneToOnePstnCall()}getLocationContent(){return this.isOneToOnePSTNCall()?ma(this.locationInfoContent):null}getNetworkContent(){return this.isOneToOnePSTNCall()?ma(this.networkInfoContent):null}getAreaContent(){return this.isOneToOnePSTNCall()?ma(this.areaContent):null}setLocationInfo(e,t,i){this.locationInfoContent=e,this.networkInfoContent=t,this.areaContent=i}setStreamInformationReceived(){this.disposed||this.streamInformationReceived||(this.streamInformationReceived=!0,this.telemetryHelper.recordEvent(Zc))}getEndpointCapabilities(){let e=0;return this.signalingAgentConfig.brokerEnabledIncoming&&(e|=16),this.signalingAgentConfig.isGVCJoiningEnabled&&(e|=1),"disabled"!==this.signalingAgentConfig.cloudScreenSharingFlag&&(e|=2),this.signalingAgentConfig.supportsHostlessGroupCalls&&(e|=4),this.signalingAgentConfig.autoJoinOnConflict&&(e|=32),this.signalingAgentConfig.supportsCompressedServicePayload&&(e|=128),this.signalingAgentConfig.enableAutoPromotion&&(e|=65536),this.signalingAgentConfig.enableBatchedSendMessageStatus&&(e|=16384),this.signalingAgentConfig.enableBatchedReceiveMessage&&(e|=8192),e|=64,e|=1024,this.signalingAgent?.accountConfig?.clientSupportsAudioOnlyWatermark&&(e|=4096,this.telemetryHelper.setAudioOnlyWatermark(!0)),this.signalingAgent?.accountConfig?.clientSupportsWatermark&&(e|=2048,this.telemetryHelper.setWatermarkSupport(!0)),this.signalingAgent?.accountConfig?.clientSupportsPreventScreenCapture&&(e|=131072,this.telemetryHelper.setClientSupportsPreventScreenCapture(!0)),(this.getMaxReinvitelessMediaForVBSSForWeb()||this.getMaxReinvitelessMediaForVideoForWeb())&&(this.telemetryHelper.setReinviteless(this.callUsesMixer),e|=512),e}handleAdmitAllStatus(e){const t=e.body?.transactionResponse,i=ya(e);this.logger.info(`[${i}][handleAdmitAllStatus][${Ne(t)}]`);const n=t?.operationId;if(n&&this.callOperationHandler.hasPendingOperation(0,n,i)){this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT,n);const e=t?.result?.code,r=t?.result?.subCode,a=t?.result?.resultCategories,s=t?.additionalDetail;if(0===e||e>=200&&e<300){const t={code:e,subCode:r,resultCategories:a,result:Le(s)};this.telemetryHelper.recordEvent(rs,{causeId:n,transactionEnd:t}),this.callOperationHandler.resolvePendingOperation(0,n,t,i)}else{const s={code:e||Jr.CALL_END_CODE.BAD_REQUEST,subCode:r||0,resultCategories:a,result:t,phrase:Jr.CALL_END_PHRASE.BAD_SERVICE_RESPONSE};this.telemetryHelper.recordEvent(ns,{causeId:n,transactionEnd:s}),this.callOperationHandler.rejectPendingOperation(0,n,"AdmitAllStatus response contains failure",s,i)}}else this.logger.warn(`[${i}][handleAdmitAllStatus] invalid admitAllStatus response or no pending operation. operationId=${n}`)}sendNetworkRequestForAdmit(e){this.http.sendPostRequest({url:this.links[Jr.LINKS.ADMIT_ALL],requestName:sd.ADMIT.name,payload:Pu(this,e),causeId:e,onceTrouterReady:()=>{this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.ADMIT,(()=>{this.telemetryHelper.recordEvent(is,{causeId:e}),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,"timed out waiting for admit operation",{code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.ADMIT_TIMEOUT,phrase:Jr.CALL_END_PHRASE.ADMIT_TIMEOUT},e)}),Jr.TIMEOUT_VALUES_IN_SECONDS.ADMIT_TIMEOUT,e)}}).catch((t=>{const i=fa(t,this.signalingAgentConfig);this.telemetryHelper.recordEvent(ns,{causeId:e,...i.error}),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.ADMIT,e),this.callOperationHandler.rejectPendingOperation(0,e,t,i.error,e)}))}getConversationType(e,t,i){return e?"emergencyGroupCall":t?"cast":i?"huddleGroupCall":null}getMaxReinvitelessMediaForVideoForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVideoForWeb}getMaxReinvitelessMediaForVBSSForWeb(){return this.signalingAgentConfig.maxReinvitelessMediaForVBSSForWeb}convertParkType(e){return"teamPark"===e?"TransferTypeTeamPark":"sharedLinePark"===e?"TransferTypeSharedLinePark":"serverHold"===e?"TransferTypeServerHold":(this.logger.info(`convertParkType, parkType: ${e} is unknown`),"none")}parkByTransfer(e,t){this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallTransferTimeout(t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT);const i=this.getNetworkRequestName(e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.TRANSFER],requestName:i,payload:Vu(e,this),causeId:t}).catch((e=>{const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[${t}][parkByTransfer] error: ${Ne(i)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.signalingSessionCallback.onTransferCompleted({transferCompletion:{code:Jr.CALL_END_CODE.NETWORK_ERROR,reason:Ne(e)}},t),this.telemetryHelper.recordEvent(Al,{causeId:t,...i.error}),Promise.reject(i.error))})),this.telemetryHelper.recordEvent(wl,{causeId:t,transferType:this.convertParkType(e)}),Promise.resolve()}park(e,t){this.logger.info(`[${t}][park] context ${e}`),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.PARK_COMPLETION,(()=>{this.handleParkError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.PARK_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.PARK_COMPLETION_TIMEOUT},tc,t,e)}),Jr.TIMEOUT_VALUES_IN_SECONDS.PARK_COMPLETION_TIMEOUT);const i=this.getHoldTypeInRequest(e),n={causeId:t};return this.http.sendPostRequest({url:this.links[Jr.LINKS.PARK],requestName:sd.PARK_REQUEST.name,payload:Hu(this,i,n),causeId:t}).then((e=>{this.logger.info(`[${t}][park] response: ${Ne(e)}`),this.telemetryHelper.recordEvent(ec,{causeId:t}),oa(e.response.holdResponse.links,"server response does not include park links"),this.links[Jr.LINKS.UNPARK]=e.response.holdResponse.links.resume})).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${t}][park] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleParkError(n.error,Xl,t,e),Promise.reject(n.error))})),Promise.resolve()}getHoldTypeInRequest(e){switch(e){case"serverHoldV2":return"musicOnHold";case"sharedLineParkV2":return"sharedLineAppearance";case"callPark":return"callPark";default:return null}}handleParkError(e,t,i,n){this.disposed?this.logger.info("handleParkError ignored"):(this.logger.info(`[${i}] handleParkError reject reason: ${Ne(e)}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.PARK_COMPLETION),this.signalingSessionCallback.onParkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onParkCompleted(e,i)),this.links[Jr.LINKS.UNPARK]=void 0)}handleParkCompletion(e){const t=e.body,i=ya(e),n=t.holdCompletion;this.handleOperationCompletionCommon(n,i,void 0,Ne(t),"handleParkCompletion",Jr.TIMEOUT_OPERATIONS.PARK_COMPLETION,ic,nc,this.signalingSessionCallback.onParkCompleted,this.handleParkError.bind(this))}handleUnparkError(e,t,i,n){this.disposed?this.logger.info("handleUnparkError ignored"):(this.logger.info(`[${i}] handleUnparkError reject reason: ${e}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.signalingSessionCallback.onUnparkCompleted&&(this.telemetryHelper.recordEvent(t,{...e,parkContext:n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(e,i)),this.links[Jr.LINKS.UNPARK]=void 0)}handleUnparkCompletion(e){const t=e.body,i=ya(e);if(this.disposed)return void this.logger.info(`[${i}]handleUnparkCompletion ignored`);this.logger.info(`[${i}][handleUnparkCompletion] body ${Ne(t)}`);const n=t.resumeCompletion;n.code===Jr.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UNPARK_COMPLETION),this.telemetryHelper.recordEvent(oc,{...n,causeId:i}),this.signalingSessionCallback.onUnparkCompleted(n,i),this.links[Jr.LINKS.UNPARK]=void 0):this.handleUnparkError(n,lc,i)}getNetworkRequestName(e){return{none:null,teamPark:sd.SEND_PARK_REQUEST.name,sharedLinePark:sd.SEND_SHARED_LINE_PARK_REQUEST.name,serverHold:sd.SEND_SERVER_HOLD_REQUEST.name}[e]}updateMeetingsGroupsAsync(e,t){this.logger.info(`[${e}][updateMeetingsGroupsAsync] scope=${t.scope}`),this.telemetryHelper.recordEvent(gc,{causeId:e,options:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION,(()=>{this.handleUpdateMeetingGroupsError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT},Cc,e,e,t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_GROUPS_COMPLETION_TIMEOUT);const i=function(e,t,i){oa(e,"signalingSession cannot be null");const{scope:n,toGroup:r,fromGroup:a,participants:s}=t;"specified"===n&&oa(s,"participantsIds cannot be null");const o={from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},scope:n,fromGroup:a,toGroup:r,links:{updateMeetingGroupsStatus:Zr(e,Ar.UPDATE_MEETING_GROUPS_STATUS)},operationId:i};return s&&(o.to=s.map((e=>({id:e.mri,endpointId:e.endpointId,participantId:e.participantId})))),{payload:o}}(this,t,e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.UPDATE_MEETING_GROUPS],requestName:sd.UPDATE_MEETING_GROUPS.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingsGroupsAsync] response: ${Ne(t)}`),this.telemetryHelper.recordEvent(Cc,{causeId:e})})).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingsGroupsAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingGroupsError(n.error,_c,e,e,t),Promise.reject(n.error))}))}updateParticipantInterpretationStateAsync(e,t){return sa(t,"options should be a non null value"),this.logger.info(`[${e}][updateParticipantInterpretationStateAsync]`),this.telemetryHelper.recordEvent(mc,{causeId:e,options:t}),this.participantManager.updateParticipantInterpretationStateAsync(t,this.links[Jr.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE],e)}async sendProxiedMessageAsync(e,t){return t&&0!==t.length?this.links[Jr.LINKS.SEND_MESSAGE]?this.proxiedMessageNotificationManager.sendProxiedMessageAsync(e,t,this.links[Jr.LINKS.SEND_MESSAGE]):Promise.reject({code:Jr.VALIDATION.VALIDATION_FAILED,subCode:Jr.VALIDATION.NULL_OR_EMPTY,phrase:"missing url for CONSTANTS.LINKS.SEND_MESSAGE"}):Promise.reject({code:Jr.VALIDATION.VALIDATION_FAILED,subCode:Jr.VALIDATION.NULL_OR_EMPTY,phrase:"options should be a non empty array"})}async updateParticipantsPropertiesAsync(e,t,i,n){this.telemetryHelper.recordEvent(fc,{causeId:n,updateParticipantsPropertiesContext:e});const r=this.links[Jr.LINKS.UPDATE_PARTICIPANTS_PROPERTIES],a=[],s=e.scope;if("self"===s){const t={id:this.participantManager.localParticipant.id,propertyBag:e.propertyBag};a.push(t)}else{if("specified"!==s)return Promise.reject("This scope is not Supported");{const t=e.participants;for(const e of t){const t={id:e.id,propertyBag:e.propertyBag};a.push(t)}}}return this.sendNetworkRequestForUpdateParticipantsProperties(a,t,r,i,n)}sendNetworkRequestForUpdateParticipantsProperties(e,t,i,n,r){const a=this.logger.createChild(`[${r}][sendNetworkRequestForUpdateParticipantsProperties]`,this.correlationId);if(i){const s=()=>{const e={code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_PARTICIPANTS_PROPERTIES_TIMEOUT};this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,(()=>{this.handleUpdateParticipantsPropertiesOnTimeout(t,e,Dc,n,r)}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION_TIMEOUT,n)},o=function(e,t,i){return oa(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId},to:t,links:{updateParticipantPropertiesStatus:Zr(e,Ar.UPDATE_PARTICIPANT_PROPERTIES_STATUS)},operationId:i}}}(this,e,n);return this.updateParticipantsPromises[n]=t,this.http.sendPostRequest({url:i,payload:o,requestName:sd.UPDATE_PARTICIPANTS_PROPERTIES.name,onceTrouterReady:s,causeId:r}).then((e=>{a.info(`response: ${Ne(e)}`)})).catch((e=>{const t=fa(e,this.signalingAgentConfig);a.info(`failed: ${Ne(t)}`);const i={...t.error};return this.disposed||(this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,n),delete this.updateParticipantsPromises[n]),this.telemetryHelper.recordEvent(Oc,{causeId:r,transactionEnd:i}),Promise.reject(i)}))}{const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_PARTICIPANTS_PROPERTIES_LINK_MISSING,phrase:"updateParticipantsProperties link is missing"};return a.warn(e),this.telemetryHelper.recordEvent(Oc,{causeId:r,error:e}),Promise.reject(e)}}checkAndCleanupPromisesForOperationId(e){this.updateParticipantsPromises[e]&&(0===this.updateParticipantsPromises[e].size?(delete this.updateParticipantsPromises[e],this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_PARTICIPANTS_PROPERTIES_COMPLETION,e)):this.logger.info(`remaining promises for the operation  ${e} (count: ${this.updateParticipantsPromises[e].size}): \n                ${this.piiUtils.scrubMriOrOmit(Le(this.updateParticipantsPromises[e]))}`))}handleUpdateParticipantsPropertiesOnTimeout(e,t,i,n,r){if(this.disposed)return void this.logger.info("handleUpdateParticipantsPropertiesOnTimeout ignored");this.logger.createChild(`[${r}][handleUpdateParticipantsPropertiesOnTimeout]`,this.correlationId).info(`reason: ${t}`),this.telemetryHelper.recordEvent(i,{...t,causeId:r});const a={};e.forEach((e=>{a[e]=t,this.updateParticipantsPromises[n].delete(e)})),this.checkAndCleanupPromisesForOperationId(n),this.signalingSessionCallback.onUpdateParticipantsPropertiesCompleted(a,n,r)}joinMeetingGroupAsync(e,t){this.logger.info(`[${e}][joinMeetingGroupAsync]`),this.telemetryHelper.recordEvent(vc,{causeId:e,options:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION,(()=>{this.handleJoinMeetingGroupError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.JOIN_MEETING_GROUP_TIMEOUT,phrase:Jr.CALL_END_PHRASE.JOIN_MEETING_GROUP_TIMEOUT},Lc,e,e,t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.JOIN_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){oa(e,"signalingSession cannot be null");const{meetingGroupId:n,groupPreferences:r}=t;return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingGroup:n,...r&&{groupPreferences:r},links:{joinMeetingGroupStatus:Zr(e,Ar.JOIN_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.JOIN_MEETING_GROUP],requestName:sd.JOIN_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][joinMeetingGroupAsync] response: ${Ne(t)}`),this.telemetryHelper.recordEvent(Lc,{causeId:e})})).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${e}][joinMeetingGroupAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleJoinMeetingGroupError(n.error,xc,e,e,t),Promise.reject(n.error))}))}leaveMeetingGroupAsync(e,t){this.logger.info(`[${e}][leaveMeetingGroupAsync]`),this.telemetryHelper.recordEvent(Sc,{causeId:e,options:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION,(()=>{this.handleLeaveMeetingGroupError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.LEAVE_MEETING_GROUP_TIMEOUT,phrase:Jr.CALL_END_PHRASE.LEAVE_MEETING_GROUP_TIMEOUT},Bc,e,e,t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.LEAVE_MEETING_GROUP_COMPLETION_TIMEOUT);const i=function(e,t,i){oa(e,"signalingSession cannot be null");const{meetingGroupId:n}=t;return{payload:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId},meetingGroup:n,links:{leaveMeetingGroupStatus:Zr(e,Ar.LEAVE_MEETING_GROUP_STATUS)},operationId:i}}}(this,t,e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.LEAVE_MEETING_GROUP],requestName:sd.LEAVE_MEETING_GROUP.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][leaveMeetingGroupAsync] response: ${Ne(t)}`),this.telemetryHelper.recordEvent(Bc,{causeId:e})})).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${e}][leaveMeetingGroupAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleLeaveMeetingGroupError(n.error,Vc,e,e,t),Promise.reject(n.error))}))}handleUpdateMeetingGroupsError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingGroupsError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingGroupsError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(e,i,n))}handleUpdateMeetingGroupsCompletion(e){const t=e.body,i=ya(e),n=t.updateMeetingGroupsResponse.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleUpdateMeetingGroupsCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] starts`);const{updateMeetingGroupsResponse:r}=t,a=Bd(r);a.code===Jr.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group succeeded`),this.telemetryHelper.recordEvent(Tc,{...a,causeId:i})):(this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] update meeting group failed code=${a.code} subCode=${a.subCode}`),this.telemetryHelper.recordEvent(Ec,{...a,causeId:i})),this.logger.info(`[${i}][handleUpdateMeetingGroupsCompletion] completes`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_GROUPS_COMPLETION),this.signalingSessionCallback.onUpdateMeetingGroupsCompleted(a,i,n)}handleJoinMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleJoinedMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleJoinedMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,joinMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onJoinMeetingGroupCompleted(e,i,n))}handleJoinMeetingGroupCompletion(e){const t=e.body.joinMeetingGroupResponse,i=ya(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleJoinMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] starts`);const r=Bd(t);r.code===Jr.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group succeeded`),this.telemetryHelper.recordEvent(Uc,{...r,causeId:i})):(this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] join meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent(Fc,{...r,causeId:i})),this.logger.info(`[${i}][handleJoinMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.JOIN_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onJoinMeetingGroupCompleted(r,i,n)}handleLeaveMeetingGroupError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleLeaveMeetingGroupError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleLeaveMeetingGroupError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,leaveMeetingGroupOptions:r,causeId:i}),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(e,i,n))}handleLeaveMeetingGroupCompletion(e){const t=e.body.leaveMeetingGroupResponse,i=ya(e),n=t.operationId;if(this.disposed)return void this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] ignored. Call disposed.`);n||this.logger.warn(`[${i}][handleLeaveMeetingGroupCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] starts`);const r=Bd(t);r.code===Jr.TRANSACTION_END_CODE.SUCCESS?(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group succeeded`),this.telemetryHelper.recordEvent($c,{...r,causeId:i})):(this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] leave meeting group failed code=${r.code} subCode=${r.subCode}`),this.telemetryHelper.recordEvent(Hc,{...r,causeId:i})),this.logger.info(`[${i}][handleLeaveMeetingGroupCompletion] complete`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.LEAVE_MEETING_GROUP_COMPLETION),this.signalingSessionCallback.onLeaveMeetingGroupCompleted(r,i,n)}handleDisablePreheatError(e,t,i){this.disposed?this.logger.info(`[${i}][handleDisablePreheatError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleDisablePreheatError] reject reason: ${JSON.stringify(e)}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.disablePreheatDefer.isPending()&&this.disablePreheatDefer.reject(e))}handleDisablePreheatCompletion(e){const t=e.body,i=ya(e),n=t.transactionEnd;if(this.disposed)this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Call disposed.`);else if(this.disablePreheatDefer.isPending()){if(this.logger.info(`[${i}][handleDisablePreheatCompletion] starts`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.DISABLE_PREHEAT_ASYNC_TIMEOUT),n.code===Jr.TRANSACTION_END_CODE.SUCCESS)this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state succeeded`),this.handleEndpointStateUpdated(i,!0);else if(this.logger.info(`[${i}][handleDisablePreheatCompletion] update endpoint state failed code=${n.code} subCode=${n.subCode}`),this.disablePreheatDefer.isPending()){const e={response:n};this.disablePreheatDefer.reject(e)}}else this.logger.info(`[${i}][handleDisablePreheatCompletion] ignored. Disable preheat promise is resolved/rejected.`)}handleReceiveMessage(e){const t=ya(e);if(this.disposed)return void this.logger.info(`[${t}][handleReceiveMessage] ignored. Call disposed.`);let i;i=Array.isArray(e.body?.messageContent)?e.body.messageContent:[e.body];let n="";const r=[];for(let e=0;e<i.length;e++){const t=i[e];n+=t?.operationId,e<i.length-1&&(n+=","),r.push({operationId:t.operationId,messageType:t.type,payload:t.payload,from:{[t.from.id]:{participantLegIdMap:{[t.from.participantId]:{...t.from.endpointId&&{endpointId:t.from.endpointId}}},level:"endpoint"}}})}this.logger.info(`[${t}][handleReceiveMessage] complete. OperationIds:${n}`),this.telemetryHelper.recordEvent(yc,{causeId:t,operationIds:n}),this.signalingSessionCallback.onIncomingProxiedMessages(r,t)}publishStateAsync(e,t,i,n,r,a){this.logger.info(`[${i}][publishStateAsync][publishType=${e} publishLevel=${t}]`),this.telemetryHelper.recordEvent(Hl,{causeId:i,publishType:e,publishLevel:t});const s=this.links[Jr.LINKS.PUBLISH_STATE];if(!s){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.PUBLISH_STATE_LINK_MISSING,phrase:"publish state link is missing"};return this.logger.warn(e),Promise.reject(e)}let o={};try{o=JSON.parse(n)}catch(e){const t={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_CONTENT,phrase:"publish state content is invalid"};return this.logger.warn(t),Promise.reject(t)}return this.http.sendPostRequest({url:s,requestName:sd.PUBLISH_STATE.name,payload:$u(this,e,t,o,r,a),causeId:i,requestId:i}).then((e=>{if(e?.response?.publishStateResponse)return this.parsePublishStateResult(e,i);{const t=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:Jr.CALL_END_CODE.DECODING_FAILED,subCode:Jr.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const t=fa(e,this.signalingAgentConfig);this.logger.info(`[${i}][publishStateAsync] error: ${Ne(t)}`);const n=t.error;return this.telemetryHelper.recordEvent($l,{causeId:i,transactionEnd:n}),Promise.reject(n)}))}getPublishStateSequenceNumber(){return++this.publishStateSequenceNumber}parsePublishStateResult(e,t){let i={};if(e?.response?.publishStateResponse){if(e.response.publishStateResponse.stateId)return e.response.publishStateResponse.stateId;if(e.response.publishStateResponse.results){if(1===e.response.publishStateResponse.results.length){if(e.response.publishStateResponse.results[0].stateId)return e.response.publishStateResponse.results[0].stateId;this.logger.warn("invalid response format")}return e.response.publishStateResponse.results.forEach((e=>{i[e.participantId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})),JSON.stringify(i)}if(e.response.publishStateResponse.result)return i={code:e.response.publishStateResponse.result.code,phrase:e.response.publishStateResponse.result.phrase,subCode:e.response.publishStateResponse.result.subCode,result:e.response.publishStateResponse.additionalDetail},JSON.stringify(i)}const n=`Invalid CS response which does not contains publishStateResponse. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(n),{response:{code:Jr.CALL_END_CODE.DECODING_FAILED,subCode:Jr.CALL_END_SUB_CODE.PUBLISH_STATE_INVALID_SERVICE_RESPONSE,phrase:n}}}removeStateAsync(e,t,i,n){if(this.logger.info(`[${e}][removeStateAsync][scope=${t} publishType=${i} stateIds=${n}]`),this.telemetryHelper.recordEvent(Gl,{causeId:e,scope:t,publishType:i,stateIds:n}),!i&&!n){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.REMOVE_STATE_MISSING_ARGUMENTS,phrase:"remove state operation miss arguments"};return this.logger.warn(e),Promise.reject(e)}const r=this.links[Jr.LINKS.REMOVE_STATE];if(!r){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.REMOVE_STATE_LINK_MISSING,phrase:"remove state link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:r,requestName:sd.REMOVE_STATE.name,payload:ju(this,t,n,i),causeId:e,requestId:e}).then((t=>this.parseRemoveStateResult(t,e))).catch((t=>{const i=fa(t,this.signalingAgentConfig);this.logger.info(`[${e}][removeStateAsync] error: ${Ne(i)}`);const n=i.error;return this.telemetryHelper.recordEvent(jl,{causeId:e,transactionEnd:n}),Promise.reject(n)}))}parseRemoveStateResult(e,t){let i={};return e?.response?.removeStateResponse&&(e.response.removeStateResponse.results?e.response.removeStateResponse.results.forEach((e=>{i[e.stateId]={code:e.result.code,phrase:e.result.phrase,subCode:e.result.subCode}})):e.response.removeStateResponse.result&&(i={code:e.response.removeStateResponse.result.code,phrase:e.response.removeStateResponse.result.phrase,subCode:e.response.removeStateResponse.result.subCode,result:e.response.removeStateResponse.additionalDetail})),JSON.stringify(i)}updateMeetingSettingsAsync(e,t){this.telemetryHelper.recordEvent(zl,{causeId:t,meetingSettings:e});const i=this.links[Jr.LINKS.UPDATE_MEETING_SETTINGS];if(!i){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_LINK_MISSING,phrase:"update meeting settings link is missing"};return this.logger.warn(e),Promise.reject(e)}if(!Object.keys(e).length){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_SETTINGS_MISSING_ARGUMENTS,phrase:"update meeting settings missing arguments"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPutRequest({url:i,requestName:sd.UPDATE_MEETING_SETTINGS.name,payload:Qu(this,e),causeId:t,requestId:t}).then((()=>{Pd.noop()})).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][updateMeetingSettingsAsync] error: ${Ne(i)}`);const n=i.error;throw this.telemetryHelper.recordEvent(Wl,{causeId:t,transactionEnd:n}),n}))}searchParticipantsAsync(e,t){this.logger.info(`[${t}][searchParticipantsAsync][queryOptions=${e}]`),this.telemetryHelper.recordEvent(Jl,{causeId:t,queryOptions:e});const i=this.links[Jr.LINKS.SEARCH_PARTICIPANTS];if(!i){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_LINK_MISSING,phrase:"search participants link is missing"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:sd.SEARCH_PARTICIPANTS.name,payload:zu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response?.participants)return this.parseSearchParticipantsResult(e,t);{const t=`Invalid CS response which does not contain proper search results. Respone: ${e?.response?JSON.stringify(e.response):"no response"}`;throw this.logger.warn(t),{response:{code:Jr.CALL_END_CODE.DECODING_FAILED,subCode:Jr.CALL_END_SUB_CODE.SEARCH_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:t}}}})).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][searchParticipantsAsync] error: ${Ne(i)}`);const n=i.error;return this.telemetryHelper.recordEvent(Ql,{causeId:t,transactionEnd:n}),Promise.reject(n)}))}parseSearchParticipantsResult(e,t){const i=[];if(e?.response){const t=e.response.participants;if(t)for(const n of Object.keys(t))i.push(Na.fromRosterSearchResults(e.response.participants[n]))}return{participants:i}}getAllParticipantsAsync(e,t){this.logger.info(`[${t}][getAllParticipantsAsync][scope=${e}]`),this.telemetryHelper.recordEvent(Yl,{causeId:t,scope:e});const i=this.links[Jr.LINKS.GET_ALL_PARTICIPANTS];if(!i){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_LINK_MISSING,phrase:"get all participants link is missing"};return this.logger.warn(e),Promise.reject(e)}if("lobby"!==e){const e={code:Jr.CALL_END_CODE.REJECT,subCode:Jr.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SCOPE,phrase:"get all participants scope is invalid"};return this.logger.warn(e),Promise.reject(e)}return this.http.sendPostRequest({url:i,requestName:sd.GET_ALL_PARTICIPANTS.name,payload:xu(this,e),causeId:t,requestId:t}).then((e=>{if(e?.response)return{participants:e.response.participants};{const e="Invalid CS response which does not contain results.";throw this.logger.warn(e),{response:{code:Jr.CALL_END_CODE.DECODING_FAILED,subCode:Jr.CALL_END_SUB_CODE.GET_ALL_PARTICIPANTS_INVALID_SERVICE_RESPONSE,phrase:e}}}})).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][getAllParticipantsAsync] error: ${Ne(i)}`);const n=i.error;return this.telemetryHelper.recordEvent(Zl,{causeId:t,transactionEnd:n}),Promise.reject(n)}))}resetState(){this.currentCallStatus=null,this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE}saveUpdatedCallLinksIfAny(e){e.links&&(this.logger.info(`saveUpdatedCallLinksIfAny, updated call links found, update to new links ${Ne(e)}`),this.links[Jr.LINKS.MEDIA_RENEGOTIATION]=e.links.mediaRenegotiation||this.links[Jr.LINKS.MEDIA_RENEGOTIATION],this.links[Jr.LINKS.TRANSFER]=e.links.transfer||this.links[Jr.LINKS.TRANSFER],this.links[Jr.LINKS.REPLACE]=e.links.replacement||this.links[Jr.LINKS.REPLACE],this.links[Jr.LINKS.HANGUP]=e.links.callLeg||this.links[Jr.LINKS.HANGUP],this.links[Jr.LINKS.KEEPALIVE]=e.links.callLeg||this.links[Jr.LINKS.KEEPALIVE],this.links[Jr.LINKS.PARK]=e.links.hold||this.links[Jr.LINKS.PARK],this.links[Jr.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.links.updateMediaDescriptions||this.links[Jr.LINKS.UPDATE_MEDIA_DESCRIPTIONS])}ensureMessageChannelReady(e){return this.disposed?(this.logger.info("ensureMessageChannelReady: error: call already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):this.brokerService?(this.telemetryHelper.addTrouterWaitOperation(`${Cd.STARTED}:${e}`),this.telemetryHelper.addTrouterWaitOperation(`${Cd.ENDED}:${e}`),Promise.resolve()):this.ensureLatestTrouterUrl(e)}ensureLatestTrouterUrl(e){return this.telemetryHelper.addTrouterWaitOperation(`${Cd.STARTED}:${e}`),this.getTrouterUrlAsync().then((t=>!t||"string"==typeof t&&!t.trim()?(this.telemetryHelper.recordEvent(Qs),this.telemetryHelper.addTrouterWaitOperation(`${Cd.ENDED}:${e}`),Promise.reject(new Error("Invalid trouter url"))):this.disposed?(this.logger.info("ensureLatestTrouterUrl, trouterUrlGetter returned too late. Object is already disposed"),Promise.reject(this.getCallNotFoundTransactionEnd())):(this.telemetryHelper.addTrouterWaitOperation(`${Cd.ENDED}:${e}`),this.baseMessagingChannelUrl=this.currentTrouterUrl=t,Promise.resolve()))).catch((t=>(this.disposed||this.telemetryHelper.addTrouterWaitOperation(`${Cd.FAILED}:${e}`),this.logger.info(`ensureLatestTrouterUrl, failed because:${t}`),Promise.reject(t))))}signalTransferAcceptedAsync(e,t=na()){return this.logger.info(`[signalTransferAcceptedAsync][${t}] transferType ${e}`),this.disposed?(this.logger.info(`[signalTransferAcceptedAsync][${t}] Call already ended, skip acceptance request`),Promise.reject({code:Jr.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(this.telemetryHelper.recordEvent(Pl,{causeId:t,transferType:e}),this.http.sendPostRequest({url:this.links[Jr.LINKS.TRANSFER_ACCEPTANCE],requestName:sd.TRANSFER_ACCEPTANCE.name,payload:{payload:{transferAcceptance:{}}},causeId:t}).catch((e=>{const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferAcceptedAsync][${t}] error: ${Ne(i)}`),this.telemetryHelper.recordEvent(Ml,{causeId:t}),Promise.reject(i.error)})))}signalTransferCompletedAsync(e,t=na()){return this.logger.info(`[signalTransferCompletedAsync][${t}] rejectReason ${e}`),this.disposed?(this.logger.info(`[signalTransferCompletedAsync][${t}]  Call already ended by transferor, skip completion request`),Promise.reject({code:Jr.CALL_END_CODE.CALL_DOES_NOT_EXIST,reason:null})):(0!==e.code?this.telemetryHelper.recordEvent(ko,{code:e.code,subcode:e.subCode,causeId:t}):this.telemetryHelper.recordEvent(Ll,{causeId:t}),this.telemetryHelper.recordEvent(xl,{causeId:t}),this.http.sendPostRequest({url:this.links[Jr.LINKS.TRANSFER_COMPLETION],requestName:sd.TRANSFER_COMPLETION.name,payload:qu(e),causeId:t}).catch((e=>{this.telemetryHelper.recordEvent(Fl,{causeId:t});const i=fa(e,this.signalingAgentConfig);return this.logger.info(`[signalTransferCompletedAsync][${t}] error: ${Ne(i)}`),Promise.reject(i.error)})))}endWithBeacon(e){if(navigator&&navigator.sendBeacon&&!this.disposed){const t={code:Jr.CALL_END_CODE.SUCCESS,subCode:Jr.CALL_END_SUB_CODE.BEACON,phrase:Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED};this.telemetryHelper.recordEvent(xs,{causeId:e});const i=JSON.stringify(Uu(this,t).payload),n=-1===this.links[Jr.LINKS.LEAVE].indexOf("?")?"?":"&",r=`skypeToken=${this.signalingAgent.authTokenManager.getLastToken(e)}`;return navigator.sendBeacon(`${this.links[Jr.LINKS.LEAVE]}${n}${r}`,i)}return!1}setFsmState(e){this.fsmState=e}setIsHostless(e,t){const i=!!e;this.isHostLessCall!==i&&(this.logger.info(`[${t}][setIsHostless] isHostless=${i}`),this.isHostLessCall=i)}hasGroupModality(){return this.threadId||this.groupId}processConversationServiceResponseHeaders(e,t){this.logger.info(`[${t}][processConversationServiceResponseHeaders]`);try{const i=e.request.getResponseHeader(Jr.HEADERS.CORRELATION_ID)||e.request.getResponseHeader(Jr.HEADERS.CORRELATION_ID.toLowerCase());this.updateCorrelationId(i,t)}catch(e){this.logger.info(`[${t}][processConversationServiceResponseHeaders] failed, reason=${Ne(e)}`)}}processConversationServiceResponse(e,t,i){const n=this.logger.createChild(`[${t}][processConversationServiceResponse]`);if(n.info(`responseType :${i}`),this.processConversationServiceUpdate(e,t),e.subscriptionDetails?.selfParticipant){const i=Na.fromRoster(e.subscriptionDetails.selfParticipant,!0);n.info("converted selfParticipant to Participant type"),this.participantManager.updateLocalParticipantFromSubscribe(i,t)}this.handleBrokerSubscription(e,t),e.roster&&this.internalHandleRosterUpdate(e.roster,!0,t),0===i&&(this.startOrJoinConvResponseReceived=!0,this.handlePendingEndpointState(t))}processConversationServiceUpdate(e,t){const i=this.logger.createChild(`[${t}][processConversationServiceUpdate]`);i.info(),this.convJoined=!0;const n=e.sequenceNumber>=0?e.sequenceNumber:-1;n<this.updateSequenceNumber?i.info(`seqNum=${n} is less than latest seqNum=${this.updateSequenceNumber}`):(this.updateSequenceNumber=n,this.links[Jr.LINKS.CONVERSATION_CONTROLLER]=e.conversationController,this.links[Jr.LINKS.ADD_PARTICIPANT]=e.links.addParticipant,this.links[Jr.LINKS.ADD_PARTICIPANTS_AND_MODALITY]=e.links.addParticipantAndModality,this.links[Jr.LINKS.LEAVE]=e.links.leave,this.links[Jr.LINKS.NOTIFICATION_LINKS]=e.links.notificationLinks,this.links[Jr.LINKS.REMOVE_PARTICIPANT]=e.links.removeParticipant,this.links[Jr.LINKS.ADD_MODALITY]=e.links.addModality,this.links[Jr.LINKS.REMOVE_MODALITY]=e.links.removeModality,this.links[Jr.LINKS.MUTE]=e.links.mute||null,this.links[Jr.LINKS.UNMUTE]=e.links.unmute||null,this.links[Jr.LINKS.ADMIT]=e.links.admit||null,this.links[Jr.LINKS.ADMIT_ALL]=e.links.admitAll||null,this.links[Jr.LINKS.UPDATE_ENDPOINT_STATE]=e.links.updateEndpointState||null,this.links[Jr.LINKS.UPDATE_ENDPOINT_METADATA]=e.links.updateEndpointMetadata||null,this.links[Jr.LINKS.UPDATE_PARTICIPANT_ROLE]=e.links.updateParticipantRole||null,this.links[Jr.LINKS.PUBLISH_STATE]=e.links.publishState||null,this.links[Jr.LINKS.REMOVE_STATE]=e.links.removeState||null,this.links[Jr.LINKS.UPDATE_MEETING_SETTINGS]=e.links.updateMeetingSettings||null,this.links[Jr.LINKS.SEARCH_PARTICIPANTS]=e.links.searchParticipants||null,this.links[Jr.LINKS.GET_ALL_PARTICIPANTS]=e.links.getAllParticipants||null,this.links[Jr.LINKS.UPDATE_MEETING_LIVE_STATE]=e.links.updateMeetingLiveState||null,this.links[Jr.LINKS.UPDATE_MEETING_GROUPS]=e.links.updateMeetingGroups||null,this.links[Jr.LINKS.SET_MEETING_LAYOUT]=e.links.setMeetingLayout||null,this.links[Jr.LINKS.UPDATE_PARTICIPANT_INTERPRETATION_STATE]=e.links.updateParticipantInterpretationState||null,this.links[Jr.LINKS.UPDATE_PARTICIPANTS_PROPERTIES]=e.links.updateParticipantProperties||null,this.links[Jr.LINKS.JOIN_MEETING_GROUP]=e.links.joinMeetingGroup||null,this.links[Jr.LINKS.LEAVE_MEETING_GROUP]=e.links.leaveMeetingGroup||null,this.links[Jr.LINKS.SEND_MESSAGE]=e.links.sendMessage||null,this.links[Jr.LINKS.UPDATE_MEETING_STATES]=e.links.updateMeetingStates||null,this.convSubject=e.subject,e.state&&(this.setMultiParty(e.state.isMultiParty,t),this.setIsHostless(e.state.isHostless||!1,t),this.conversationType=e.state.conversationType,this.isCastCall="cast"===e.state.conversationType,this.isHuddleGroupCall="huddleGroupCall"===e.state.conversationType),e.activeModalities&&e.activeModalities.groupChat&&this.updateGroupChatIds(e.activeModalities.groupChat,t),e.activeModalities&&e.activeModalities.broadcast&&(this.broadcastSession||(this.broadcastSession=new Vd(this,this.signalingSessionCallback)),this.broadcastSession.handleBroadcastDetailsChanged(e,t)),this.handleMeetingDetailsChanged(e,t),this.handleMeetingStatesChanged(e,t),this.linkUpdateRequested.conversationLinks?(i.info("Updating CS links as requested"),this.updateLinks(this.updateConversationLinks,t)):this.scheduleConversationKeepAlive(),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo),e.region&&(this.region=e.region),e.callLimits&&(this.callLimits=e.callLimits),e.complianceRecordingContent&&(this.complianceRecordingContent=e.complianceRecordingContent),this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,complianceRecordingContent:this.complianceRecordingContent,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId},t))}processLocalParticipantUpdateResponse(e,t){this.logger.info(`[${t}][processLocalParticipantUpdateResponse]`),e.sequenceNumber&&e.sequenceNumber<this.localParticipantUpdateSequenceNumber||(this.breakoutDetails=e.breakoutDetails||{},this.signalingSessionCallback.onBreakoutDetailsUpdated(this.breakoutDetails,t),!0===e.nudgeToJoinAsRealtime&&(this.telemetryHelper.recordEvent(td,{causeId:t}),this.signalingSessionCallback.onNudgeToJoinRealtime(t)))}handlePendingEndpointState(e){this.requestedEndpointStateWhileConnecting&&(this.logger.info(`[${e}][handlePendingEndpointState]sending pending endpoint state now that we are connected.`),this.updateEndpointState(this.requestedEndpointStateWhileConnecting,e,this.requestedPublishedStatesWhileConnecting).catch((e=>{this.isPreheatOnly&&this.disablePreheatDefer.isPending()&&(this.logger.info("handlePendingEndpointState failed"),this.disablePreheatDefer.reject(e))})))}handleMeetingDetailsChanged(e,t){this.logger.info(`[${t}][handleMeetingDetailsChanged]`),e.meetingDetails&&!Pd.isEqual(e.meetingDetails,this.meetingDetails)&&this.signalingSessionCallback.onMeetingDetailsUpdated&&(this.meetingDetails=e.meetingDetails,this.meetingDetails.meetingCapability?.meetingLiveState&&(this.meetingLiveStateSequenceNumber=this.meetingDetails.meetingCapability.meetingLiveState.seqNum,this.logger.info(`[${t}][handleMeetingDetailsChanged] update meeting seqNum as ${this.meetingLiveStateSequenceNumber}`)),this.signalingSessionCallback.onMeetingDetailsUpdated(this.meetingDetails,t))}handleMeetingStatesChanged(e,t){this.logger.info(`[${t}][handleMeetingStatesChanged]`),this.signalingSessionCallback.onMeetingStatesUpdated&&this.signalingSessionCallback.onMeetingStatesUpdated(e.meetingStates,t)}handleBrokerSubscription(e,t){this.logger.info(`[${t}][handleBrokerSubscription]`),e.links.subscribe?(this.telemetryHelper.recordEvent(Gc,t),this.brokerService&&!Pd.isEqual(e.links.subscribe,this.brokerService.currentSubscriptionUrl)?this.brokerService.subscribeToBroker(e.links.subscribe):(this.logger.info(`[${t}][handleBrokerSubscription] broker subscribe ignored. Broker is disabled or subscribe url is same.`),this.telemetryHelper.recordEvent(qo,t))):this.telemetryHelper.recordEvent(jc,t)}cancelOutgoingCall(e,t){const i=Ta();this.logger.info(`[${t}][cancelOutgoingCall][rejectionData=${e&&Ne(e)}]`);const n={code:isNaN(e?.code)?Jr.CALL_END_CODE.CANCEL:e.code,subCode:e?.subCode||Jr.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};if(n.resultCategories=n.resultCategories||[Cr],this.links.hasOwnProperty(Jr.LINKS.LEAVE)){this.logger.info(`[${t}][cancelOutgoingCall] cancelling outgoing call`),this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE;const e={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()},r={terminatingEnd:md.LOCAL,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};this.http.sendPostRequest({url:this.links[Jr.LINKS.LEAVE],requestName:sd.CANCEL_CALL.name,payload:Nu(this,n,e),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const a=fa(e,this.signalingAgentConfig);this.logger.info(`[cancelOutgoingCall][${t}] error: ${Ne(e)} xhrError: ${Ne(a)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)}))}else this.logger.info(`[${t}][cancelOutgoingCall] Conversation Service Leave Url is not yet set. Cannot leave conversation. Disposing anyways.`),n.subCode=Jr.CALL_END_SUB_CODE.CONV_URL_NOT_SET,this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultDetail:n.phrase||"CancelOutgoingCall",endCode:n.code,endSubCode:n.subCode,causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t),i.resolve(null);return i.promise}terminateEstablishedCall(e,t){const i=t.causeId||na();this.logger.info(`[${i}][terminateEstablishedCall]`);const n=Ta();this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE;const r=this.convJoined?sd.LEAVE_CONVERSATION.name:sd.END_CALL.name,a=eu(),s={code:e?.code||Jr.CALL_END_CODE.SUCCESS,subCode:e?.subCode||Jr.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};s.resultCategories=s.resultCategories||[Cr];const o={terminatingEnd:md.LOCAL,endCode:s.code,endSubCode:s.subCode,resultDetail:s.phrase||"TerminateEstablishedCall",causeId:i,clientReasonSubCode:s.clientReasonSubCode,clientReasonPhrase:s.clientReasonPhrase,resultCategories:s.resultCategories};return this.leaveConversation(s,t).then((()=>{this.logger.info(`[${i}][terminateEstablishedCall]success`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!0,a.duration()),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,i,s),this.dispose(s,i)),n.resolve(null)})).catch((e=>{const t=fa(e,this.signalingAgentConfig);this.logger.info(`[${i}][terminateEstablishedCall][failed] error: ${Ne(e)} xhrError: ${Ne(t)}]`),this.disposed||(this.telemetryHelper.setTerminatingData(o),this.telemetryHelper.addNetworkOperationCompleted(r,!1,a.duration()),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,i,s),this.dispose(s,i)),n.resolve(null)})),n.promise}deleteConversation(e,t){this.logger.info(`[${t}][deleteConversation]`);const i=Ta();this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE;const n=sd.DELETE_CONVERSATION.name,r=eu(),a={code:e?.code||Jr.CALL_END_CODE.SUCCESS,subCode:e?.subCode||Jr.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||Jr.CALL_END_PHRASE.CONV_END_FOR_ALL_INITIATED,resultCategories:e?.resultCategories||[Cr],clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase},s={terminatingEnd:md.LOCAL,endCode:a.code,endSubCode:a.subCode,resultDetail:a.phrase,causeId:t,clientReasonSubCode:a.clientReasonSubCode,clientReasonPhrase:a.clientReasonPhrase,resultCategories:a.resultCategories};return this.deleteConversationController(a,t).then((()=>{this.logger.info(`[${t}][deleteConversation]success`),this.disposed||(this.telemetryHelper.setTerminatingData(s),this.telemetryHelper.addNetworkOperationCompleted(n,!0,r.duration()),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,a),this.dispose(a,t)),i.resolve(null)})).catch((e=>{const o=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][deleteConversation][failed] error: ${Ne(e)} xhrError: ${Ne(o)}`),this.disposed||(this.telemetryHelper.setTerminatingData(s),this.telemetryHelper.addNetworkOperationCompleted(n,!1,r.duration()),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,a),this.dispose(a,t)),i.resolve(null)})),i.promise}leaveConversation(e,t){const i=t.causeId||na();if(this.convJoined){this.logger.info(`[${i}][leaveConversation]`);const n={cancelationDuration:this.telemetryHelper.getCallCancelationDuration()};return this.http.sendPostRequest({url:this.links[Jr.LINKS.LEAVE],requestName:sd.LEAVE_CONVERSATION.name,payload:Uu(this,e,n,t.scope),withoutTrouter:!0,causeId:i})}return this.logger.info(`[${i}][leaveConversation] ignore, not joined to conversation`),Promise.resolve(void 0)}deleteConversationController(e,t){return this.convJoined?(this.logger.info(`[${t}][deleteConversationController]`),this.http.sendDeleteRequest({url:this.links[Jr.LINKS.CONVERSATION_CONTROLLER],requestName:sd.DELETE_CONVERSATION.name,payload:Lu(this,e),withoutTrouter:!0,causeId:t})):(this.logger.info(`[${t}][deleteConversationController]ignored, not joined to conversation`),Promise.resolve(void 0))}rejectIncomingCall(e,t){this.telemetryHelper.recordEvent(vl,t),this.logger.info(`[${t}][rejectIncomingCall]`);const i=Ta();this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE;const n={code:isNaN(e?.code)?Jr.CALL_END_CODE.REJECT:e.code,subCode:e?.subCode||Jr.CALL_END_SUB_CODE.SUCCESS,phrase:e?.phrase||Jr.CALL_END_PHRASE.LOCAL_USER_INITIATED,resultCategories:e?.resultCategories,clientReasonSubCode:e?.clientReasonSubCode,clientReasonPhrase:e?.clientReasonPhrase};n.resultCategories=n.resultCategories||[Cr];const r={terminatingEnd:md.LOCAL,endCode:n.code,endSubCode:n.subCode,resultDetail:n.phrase||"RejectCall",causeId:t,clientReasonSubCode:n.clientReasonSubCode,clientReasonPhrase:n.clientReasonPhrase,resultCategories:n.resultCategories};return this.http.sendDeleteRequest({url:this.links[Jr.LINKS.REJECT],requestName:sd.REJECT_CALL.name,payload:Gu(this,n),causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})).catch((e=>{const a=fa(e,this.signalingAgentConfig);this.logger.info(`[rejectIncomingCall][${t}] error: ${Ne(e)} xhrError: ${Ne(a)}`),this.disposed||(this.telemetryHelper.setTerminatingData(r),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,t,n),this.dispose(n,t)),i.resolve(null)})),i.promise}onCallStatusChanged(e,t,i){const n=`[${t}][onCallStatusChanged]`;if(this.logger.info(`${n}${this.currentCallStatus}=>${e}]`),this.disposed)this.logger.info(`${n}Call is already disposed!!`);else if(i&&this.logger.info(`${n}[statusCode=${Ne(i)}]`),this.isPromotingToRealtime)e===Jr.CALL_STATUS.CONNECTED&&this.onPromotionCompleted(!1,void 0,t);else if(this.isValidStateTransitions(e)){this.currentCallStatus=e;const n={callStatus:e,statusCode:i,causeId:t};this.isPreheatOnly&&(n.isPreheatOnly=!0),this.telemetryHelper.recordEvent(al,n),this.signalingSessionCallback.onCallStatusChanged(e,i,t),this.currentCallStatus===Jr.CALL_STATUS.CONNECTED&&(this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.telemetryHelper.resetCallCancelationDurationWatch(),this.isPreheatOnly&&this.startCallPreheatTimer(t))}}updateMeetingLiveStateAsync(e,t){this.logger.info(`[${e}][updateMeetingLiveStateAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent(cc,{causeId:e,meetingLiveStateOptions:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,(()=>{this.handleUpdateMeetingLiveStateError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT},dc,e,e,t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_LIVE_STATE_COMPLETION_TIMEOUT);const i=function(e,t,i){return oa(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingLiveState:t,links:{updateMeetingLiveStateStatus:Zr(e,Ar.UPDATE_MEETING_LIVE_STATE_STATUS)},operationId:i}}}(this,{...t,seqNum:this.meetingLiveStateSequenceNumber},e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.UPDATE_MEETING_LIVE_STATE],requestName:sd.UPDATE_MEETING_LIVE_STATE.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][updateMeetingLiveStateAsync] response: ${Ne(t)}`),this.telemetryHelper.recordEvent(dc,{causeId:e})})).catch((i=>{const n=fa(i,this.signalingAgentConfig);return this.logger.info(`[${e}][updateMeetingLiveStateAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleUpdateMeetingLiveStateError(n.error,uc,e,e,t),Promise.reject(n.error))}))}updateMeetingStatesAsync(e,t){const i=this.logger.createChild(`[${e}][updateMeetingStatesAsync]`,this.correlationId);if(i.info(`meetingStatesOptions: ${JSON.stringify(t)}`),!t)return Promise.reject({code:Jr.VALIDATION.VALIDATION_FAILED,subCode:Jr.VALIDATION.NULL_OR_EMPTY,phrase:"meetingStatesOptions should be a non empty object"});this.telemetryHelper.recordEvent(id,{causeId:e,meetingStatesOptions:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,(()=>{for(const i in t.meetingStates)this.handleUpdateMeetingStatesError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT},nd,e,t.operationId+"_"+i)}),Jr.TIMEOUT_VALUES_IN_SECONDS.UPDATE_MEETING_STATES_COMPLETION_TIMEOUT);const n=function(e,t,i){return oa(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},meetingStates:t,updateMeetingStatesStatus:Zr(e,Ar.UPDATE_MEETING_STATES_STATUS),operationId:i}}}(this,{...t.meetingStates},e);return this.http.sendPostRequest({url:this.links[Jr.LINKS.UPDATE_MEETING_STATES],requestName:sd.UPDATE_MEETING_STATES.name,payload:n,causeId:e}).then((t=>{i.info(`response: ${Ne(t)}`),this.telemetryHelper.recordEvent(nd,{causeId:e})})).catch((n=>{const r=fa(n,this.signalingAgentConfig);if(i.error(`error: ${Ne(r)}`),!this.disposed){for(const i in t.meetingStates)this.handleUpdateMeetingStatesError(r.error,ad,e,t.operationId+"_"+i);return Promise.reject(r.error)}return Promise.reject(this.getCallNotFoundTransactionEnd())}))}handleUpdateMeetingLiveStateError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingLiveStateError] reject reason: ${e}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted&&this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted(e,i,n))}handleUpdateMeetingLiveStateCompletion(e){const t=e.body,i=ya(e),n=t.updateMeetingLiveStateResponse.result,r=t.updateMeetingLiveStateResponse.operationId;r||this.logger.warn(`[${i}][handleUpdateMeetingLiveStateCompletion] operationId is undefined.`),this.logger.info(`[${i}][handleUpdateMeetingLiveStateCompletion] meetingLiveUpdate completes with operationId=${r}`),this.handleOperationCompletionCommon(n,i,r,Ne(t),"handleUpdateMeetingLiveStateCompletion",Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_LIVE_STATE_COMPLETION,pc,hc,this.signalingSessionCallback.onUpdateMeetingLiveStateCompleted,this.handleUpdateMeetingLiveStateError.bind(this))}handleUpdateMeetingStatesError(e,t,i,n){this.disposed?this.logger.info(`[${i}][handleUpdateMeetingStatesError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleUpdateMeetingStatesError] reject reason: ${e}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,causeId:i}),this.signalingSessionCallback.onUpdateMeetingStatesCompleted&&this.signalingSessionCallback.onUpdateMeetingStatesCompleted(e,i,n))}handleUpdateMeetingStatesCompletion(e){const t=e.body,i=ya(e),n=t.updateMeetingStatesResponse,r=t.operationId,a=this.logger.createChild(`[${i}][handleUpdateMeetingStatesCompletion]`,this.correlationId);r||a.warn("operationId is undefined.");for(const e of n)a.info(`UpdateMeetingStates completes with operationId=${r}.`),this.handleOperationCompletionCommon(e.transactionEnd,i,r+"_"+e.meetingStateName,Ne(t),"handleUpdateMeetingStatesCompletion",Jr.TIMEOUT_OPERATIONS.UPDATE_MEETING_STATES_COMPLETION,rd,ad,this.signalingSessionCallback.onUpdateMeetingStatesCompleted,this.handleUpdateMeetingStatesError.bind(this))}setMeetingLayoutAsync(e,t){this.logger.info(`[${e}][setMeetingLayoutAsync][options=${JSON.stringify(t)}]`),this.telemetryHelper.recordEvent(bc,{causeId:e,setMeetingLayoutOptions:t}),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,(()=>{this.handleSetMeetingLayoutError({code:Jr.CALL_END_CODE.TIMEOUT,subCode:Jr.CALL_END_SUB_CODE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT,phrase:Jr.CALL_END_PHRASE.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT},Ic,e,e,t)}),Jr.TIMEOUT_VALUES_IN_SECONDS.SET_MEETING_LAYOUT_COMPLETION_TIMEOUT);const i=function(e,t){return oa(e,"signalingSession cannot be null"),{payload:{from:{id:e.participantManager.localParticipant.id,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,displayName:e.participantManager.localParticipant.displayName},...t,links:{setMeetingLayoutStatus:Zr(e,Ar.SET_MEETING_LAYOUT_STATUS)}}}}(this,{...t,sequenceNumber:this.meetingLayoutSequenceNumber});return this.http.sendPostRequest({url:this.links[Jr.LINKS.SET_MEETING_LAYOUT],requestName:sd.SET_MEETING_LAYOUT.name,payload:i,causeId:e}).then((t=>{this.logger.info(`[${e}][setMeetingLayoutAsync] response: ${Ne(t)}`),this.telemetryHelper.recordEvent(Ic,{causeId:e})})).catch((i=>{const n=fa(i);return this.logger.info(`[${e}][setMeetingLayoutAsync] error: ${Ne(n)}`),this.disposed?Promise.reject(this.getCallNotFoundTransactionEnd()):(this.handleSetMeetingLayoutError(n.error,wc,e,e,t),Promise.reject(n.error))}))}handleSetMeetingLayoutError(e,t,i,n,r){this.disposed?this.logger.info(`[${i}][handleSetMeetingLayoutError] ignored. Call disposed, err: ${JSON.stringify(e)}`):(this.logger.info(`[${i}][handleSetMeetingLayoutError] reject reason: ${e}`),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION),this.telemetryHelper.recordEvent(t,{...e,updateMeetingGroupsOptions:r,causeId:i}),this.signalingSessionCallback.onSetMeetingLayoutCompleted&&this.signalingSessionCallback.onSetMeetingLayoutCompleted(e,i,n))}handleSetMeetingLayoutCompletion(e){const t=e.body,i=ya(e),n=t.setMeetingLayoutResponse.result,r=t.setMeetingLayoutResponse.operationId;r||this.logger.warn(`[${i}][handleSetMeetingLayoutCompletion] operationId is undefined.`),this.handleOperationCompletionCommon(n,i,r,Ne(t),"handleSetMeetingLayoutCompletion",Jr.TIMEOUT_OPERATIONS.SET_MEETING_LAYOUT_COMPLETION,Ac,Rc,this.signalingSessionCallback.onSetMeetingLayoutCompleted,this.handleSetMeetingLayoutError.bind(this))}handleOperationCompletionCommon(e,t,i,n,r,a,s,o,l,c){this.disposed?this.logger.info(`[${t}][${r}] ignored. Call disposed.`):(this.logger.info(`[${t}][${r}] body ${n}`),e.code===Jr.TRANSACTION_END_CODE.SUCCESS?(this.timeoutManager.stopTimer(a),this.telemetryHelper.recordEvent(s,{...e,causeId:t}),l&&l(e,t,i)):c&&c(e,o,t,i))}isValidStateTransitions(e){if(this.currentCallStatus===Jr.CALL_STATUS.LOCAL_TERMINATED&&e===Jr.CALL_STATUS.CONNECTING)return!0;const t=e=>{switch(e){case Jr.CALL_STATUS.IDLE:case Jr.CALL_STATUS.CONNECTED_FOR_ROSTER_ONLY:return 0;case Jr.CALL_STATUS.CONNECTING:return 1;case Jr.CALL_STATUS.RINGING:return 2;case Jr.CALL_STATUS.CONNECTED:return 3;case Jr.CALL_STATUS.LOCAL_TERMINATED:case Jr.CALL_STATUS.REMOTE_TERMINATED:return 4;default:return-1}};return t(e)>t(this.currentCallStatus)}handlePSTNBalanceUpdate(e){const t=e.body.balanceUpdate,i=ya(e);this.logger.info(`[${i}][handlePSTNBalanceUpdate]`),this.telemetryHelper.recordIncomingEvent(tl,e),t.updateBalance?this.signalingSessionCallback.onPSTNBalanceUpdate(t):this.logger.info(tl,"this was a pstn keepAlive message - ignore")}handleCallAcceptanceAck(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleCallAcceptanceAck]`),this.telemetryHelper.recordIncomingEvent($s,e),this.internalHandleCallAcceptanceAck(t,i)}internalHandleCallAcceptanceAck(e,t){this.logger.info(`[${t}][internalHandleCallAcceptanceAck] ${Ne(e)}`),this.fsmState!==Jr.SIGNALING_FSM_STATE.CONNECTED&&(this.links[Jr.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptanceAcknowledgement.links.mediaRenegotiation,this.links[Jr.LINKS.TRANSFER]=e.callAcceptanceAcknowledgement.links.transfer,this.links[Jr.LINKS.REPLACE]=e.callAcceptanceAcknowledgement.links.replacement,this.links[Jr.LINKS.HANGUP]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[Jr.LINKS.KEEPALIVE]=e.callAcceptanceAcknowledgement.links.callLeg,this.links[Jr.LINKS.PARK]=e.callAcceptanceAcknowledgement.links.hold,this.links[Jr.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptanceAcknowledgement.links.updateMediaDescriptions,this.saveMediaControllerLinksIfAny(e.callAcceptanceAcknowledgement),this.scheduleKeepAlives(e.callAcceptanceAcknowledgement.callKeepAliveInterval),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptanceAcknowledgement.callProperties?.isSharedLineAppearanceV2Activated),this.fsmState=Jr.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.INCOMING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTED,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][internalHandleCallAcceptanceAck] updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t)))}isFatalException(e){let t=!0;try{JSON.parse(e.message).code===Jr.CALL_END_CODE.CONFLICT&&(t=!1,this.logger.info("isFatalException: received non-fatal 409 error"))}catch(e){this.logger.error("isFatalException: failed to parse error")}return t}startOrJoinCall(e,t,i,n,r){if(this.logger.info(`[${i}]startOrJoinCall[${t}]`),this.disposed)return void this.logger.info(`[${i}][${t}] session already disposed, ignore`);this.setMultiParty(1!==this.participantManager.getParticipantsToInitiateCallWith().length,i);const a=this.getConversationUrl()?this.getConversationUrl():e.conversationServiceUrl;this.telemetryHelper.setConversationServiceUrl(a),this.logger.info(`options.conversationServiceUrl ${e.conversationServiceUrl} conversationServiceUrl ${a}`),e.isPreheatOnly?(this.isPreheatOnly=!0,this.telemetryHelper.recordEvent(Tl,{causeId:i}),this.telemetryHelper.setSelfParticipantRole(Sd.PREHEAT),this.telemetryHelper.setIsPreheated()):this.telemetryHelper.startCallCancelationDurationWatch(),this.mediaTypesToUse=r,this.lastUsedOutgoingMediaContent=n,this.telemetryHelper.setCallerType(this.participantManager.localParticipant.id);const s=!this.multiParty&&this.signalingAgentConfig.enableLongOutgoing1To1SetupTimeoutForWeb,o=s?Jr.TIMEOUT_VALUES_IN_SECONDS.LONGER_OUTGOING_CALL_ESTABLISHMENT_TIMEOUT:Jr.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT;this.logger.info(`[${i}][${t}]target endpointType = ${this.transferContext&&this.transferContext.target?this.transferContext.target.endpointType:"default"} timeout = ${o} LongerTimeout = ${s}`);const l=e.newCall?function(e,t,i,n){oa(e,"signalingSession cannot be null");let r=[];r=n.invitationType===Jr.INVITATION_TYPE.NUDGE&&Array.isArray(n.participantsToNudge)?n.participantsToNudge.map((e=>({id:e}))):e.participantManager.getParticipantsToInitiateCallWith(),e.signalingAgentConfig.doHostlessCalling||aa(r.length>0,"remoteParticipants need to be set before a call can be made");const a={type:"Delta",rosterUpdate:Zr(e,Ar.CONV_ROSTER_UPDATE)},s=e.groupId?{id:e.groupId}:null,o=e.threadId?{threadId:e.threadId,messageId:e.teamsMessageId||null}:null,l=e.contentSharingManager.getContentSharingInfoToStartSharing(),c=null===l?null:{identifier:l.contentIdentifier,subject:l.subject,sessionState:l.sessionState,sessionUpdateSequenceNumber:l.sequenceNumber,links:{sessionUpdate:Zr(e,Ar.CONV_CONTENT_SHARING_UPDATE),sessionEnd:Zr(e,Ar.CONV_CONTENT_SHARING_END)}},d=e.broadcastSession?.getContext(),u=e.getEndpointCapabilities();1===r.length&&e.telemetryHelper.setCalleeType(r[0].id),e.numberOfOriginalInvitees=r.length;const h=[];r.forEach((t=>{const i={id:t.id};t.displayName&&(i.displayName=t.displayName),t.participantId&&(i.participantId=t.participantId),(n.callToVoicemail||e.transferContext&&e.transferContext.target&&"voicemail"===e.transferContext.target.endpointType)&&(i.endpointType="voicemail"),h.push(i)}));const p=e.transferContext?e.transferContext.transferor:null,g=e.transferContext?e.transferContext.transferContext:null,m={};n.callToVoicemail&&(n.voicemailResourcePath&&(m.localResourcePath=n.voicemailResourcePath),n.voicemailItemId&&(m.voicemailItemId=n.voicemailItemId));const f={payload:{conversationRequest:{conversationType:n.conversationType,subject:e.convSubject,suppressDialout:n.suppressDialout,applicationType:n.applicationType,targetApplicationType:n.targetApplicationType,roster:a,properties:{allowConversationWithoutHost:e.signalingAgentConfig.doHostlessCalling,enableGroupCallEventMessages:e.signalingAgentConfig.shouldServiceSendCallEventMessages,enableGroupCallUpgradeMessage:e.signalingAgentConfig.shouldServiceSendNGCUpgradeMessages,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration},links:{conversationEnd:Zr(e,Ar.CONV_END),conversationUpdate:Zr(e,Ar.CONV_UPDATE),localParticipantUpdate:Zr(e,Ar.CONV_LOCAL_PARTICIPANT_UPDATE),addParticipantSuccess:Zr(e,Ar.CONV_ADD_PARTICIPANT_SUCCESS),addParticipantFailure:Zr(e,Ar.CONV_ADD_PARTICIPANT_FAILURE),addModalitySuccess:Zr(e,Ar.CONV_ADD_MODALITY_SUCCESS),addModalityFailure:Zr(e,Ar.CONV_ADD_MODALITY_FAILURE),confirmUnmute:Zr(e,Ar.CONV_CONFIRM_UNMUTE),receiveMessage:Zr(e,Ar.RECEIVE_MESSAGE)}},broadcast:d,contentSharing:c,participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId,meetingRegistrationId:n.meetingRegistrationId,participantPin:n.participantPin},to:h},capabilities:null,endpointCapabilities:u,clientEndpointCapabilities:n.clientEndpointCapabilities?n.clientEndpointCapabilities:null,endpointMetadata:e.endpointMetadata,groupContext:s,groupChat:o,meetingInfo:e.getMeetingInfo(),meetingData:n.meetingData,meetingPreferences:n.meetingPreferences,endpointState:n.endpointState}};if(n.publishedStates?.publishedStates.length>0){let t=[];t=n.publishedStates.publishedStates.map((t=>{let i={};try{i=JSON.parse(t.content)}catch(t){e.logger.warn("createConversationRequest getPayload() failed to parse state.content")}return{stateType:t.type,level:t.level,content:i,sequenceNumber:e.getPublishStateSequenceNumber()}})),f.payload.publishedStates=t}e.deviceType&&"default"!==e.deviceType&&(f.payload.conversationRequest.deviceType=e.deviceType);const v=ca(i);if(e.telemetryHelper.addOutgoingModalities(v),f.payload.callInvitation={callModalities:v,replaces:null,transferor:p||null,clientTransferContext:g,links:{progress:Zr(e,Ar.PROGRESS),mediaAnswer:Zr(e,Ar.MEDIA_ANSWER),acceptance:Zr(e,Ar.ACCEPT),redirection:Zr(e,Ar.REDIRECTION),end:Zr(e,Ar.END)},clientContentForMediaController:e.webRtcSignalingManager.getClientUrls(),pstnContent:e.pstnContent,emergencyContent:e.getEmergencyContent(),mediaContent:t,voicemailSettings:m,routingFlags:n.routingFlags,invitationData:n.invitationData,locationContent:e.getLocationContent(),networkContent:e.getNetworkContent(),areaContent:e.getAreaContent()},n.pickupCode&&(f.payload.callInvitation.unparkContent={pickupCode:parseInt(n.pickupCode,10)}),n.onBehalfOf&&(f.payload.callInvitation.onBehalfOf={id:n.onBehalfOf},n.onBehalfOfUserDisplayName&&(f.payload.callInvitation.onBehalfOf.displayName=n.onBehalfOfUserDisplayName)),n.callQueueContext&&(f.payload.callInvitation.callQueueContext=n.callQueueContext),n.scenario&&(f.payload.conversationRequest.scenario=n.scenario),n.alternateId&&(f.payload.participants.from.alternateId=n.alternateId),n.invitationType===Jr.INVITATION_TYPE.NUDGE&&(f.payload.participants.invitationType=n.invitationType),e.signalingAgentConfig.ecsEtag&&(f.payload.debugContent={ecsEtag:e.signalingAgentConfig.ecsEtag}),n.clientEndpointDebugContent){f.payload.debugContent||(f.payload.debugContent={});try{f.payload.debugContent.clientDebugContent=JSON.parse(n.clientEndpointDebugContent)}catch(e){aa(!1,`Failed to parse ${n.clientEndpointDebugContent}`)}}if(n.captchaContentJson)try{f.payload.conversationRequest.captchaContent=JSON.parse(n.captchaContentJson)}catch(e){aa(!1,`Failed to parse ${n.captchaContentJson}`)}return f}(this,n,r,e):Fu(this,n,r,e,i);this.signalingAgentConfig.enableCallEstablishmentTimeoutsForStartJoinCall&&this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(i)}),o),this.signalingSessionCallback.onTransferredCallAcceptance(i),e.endpointState&&(this.latestEndpointState=e.endpointState),this.http.sendPostRequest({url:a,requestName:t,operationType:"CallSetup",payload:l,causeId:i}).then((e=>{this.disposed||(this.processConversationServiceResponseHeaders(e,i),this.processConversationServiceResponse(e.response,i,0),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTING,i))})).catch((e=>{if(e.stack&&!this.isFatalException(e))return;const n=fa(e,this.signalingAgentConfig);if(this.logger.info(`[startOrJoinCall][${i}][${t}] error: ${Ne(e)} xhrError: ${Ne(n)}`),!this.disposed){if(this.isPromotingToRealtime)return void this.onPromotionCompleted(!0,n.error,i);this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,endCode:n.telemetryEndSubCode,endSubCode:n.error.subCode,resultCategories:n.error.resultCategories,resultDetail:n.error.phrase||this.getTerminatingCallResultDetail(t,n.error),causeId:i}),this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,i,n.error),this.dispose(n.error,i)}}))}processIncomingCallPayload(e,t){this.remoteUser=Na.fromWireParticipant(e.callNotification.from),this.participantManager.setLocalParticipantId(e.callNotification.to.participantId,t),e?(e.conversationInvitation&&(this.links[Jr.LINKS.CONVERSATION_CONTROLLER]=e.conversationInvitation.conversationController,this.setMultiParty(e.conversationInvitation.isMultiParty,t),this.setIsHostless(!!e.conversationInvitation.isHostless,t)),e.callNotification&&(this.links[Jr.LINKS.ATTACH]=e.callNotification.links?.attach,this.links[Jr.LINKS.REDIRECT]=e.callNotification.links?.redirection,this.onBehalfOf=e.callNotification.onBehalfOf?.id,this.onBehalfOfUserDisplayName=e.callNotification.onBehalfOf?.displayName,this.callQueueContext=e.callNotification.callQueueContext,this.callPhoneLineType=e.callNotification.callPhoneLineType,this.callType=e.callNotification.callType,this.incomingCallCallerId=e.callNotification.from?.id,this.callUsesMixer=!!e.callNotification.mediaContent?.fromMixer,this.isRedirectAllowed=!!e.callNotification.redirectionProperties?.isRedirectAllowed),e.debugContent&&this.updateCorrelationId(e.debugContent.callId,t),e.callNotification.transferor&&(this.transferor=e.callNotification.transferor.details?e.callNotification.transferor.details.id:null),e.groupChat&&this.updateGroupChatIds(e.groupChat,t),e.meetingData&&(this.meetingData=e.meetingData),e.meetingInfo&&(this.meetingInfo=e.meetingInfo)):this.logger.info(`[${t}][processIncomingCallPayload] empty incoming payload content`)}processAttachResponse(e,t,i){this.telemetryHelper.recordEvent(hl,{causeId:i}),this.links[Jr.LINKS.MEDIA_ANSWER]=t.response.callInvitation.links.mediaAnswer,this.links[Jr.LINKS.ACCEPT]=t.response.callInvitation.links.acceptance,this.links[Jr.LINKS.REJECT]=t.response.callInvitation.links.callLeg,this.links[Jr.LINKS.REDIRECT]=t.response.callInvitation.links.redirection,this.links[Jr.LINKS.NEW_OFFER]=t.response.callInvitation.links.newOffer,this.signalingAgentConfig.sendProgressFromCC||this.sendProgress(t),this.remoteCaller=t.response.participants.from;const n=this.getInitialMediaOfferFromIncomingCallPayload()||t.response.callInvitation.mediaContent;this.telemetryHelper.setCallerType(this.getParticipantIdForOfferAnswer(n));const r=ca(t.response.callInvitation.callModalities);this.telemetryHelper.addIncomingModalities(r),this.telemetryHelper.setOfferedModalities(n.blob,!0),this.callUsesMixer=n.fromMixer,this.isRedirectAllowed=!(!t.response.callInvitation.redirectionProperties||!t.response.callInvitation.redirectionProperties.isRedirectAllowed),this.signalingSessionCallback.onOffer({subject:e.conversationInvitation.subject,remoteParticipantId:this.getParticipantIdForOfferAnswer(n),remoteEndpointId:t.response.participants.from.endpointId,transferor:t.response.callInvitation.transferor,clientTransferContext:e.callNotification.transferContext,mediaTypes:r,mediaContent:n,renegotiation:!1,invitationData:t.response.callInvitation.invitationData,riskLevel:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.riskLevel,stirAttestation:t.response.callInvitation.spamProperties&&t.response.callInvitation.spamProperties.stirAttestation,isRedirectAllowed:this.isRedirectAllowed},i)}sendProgress(e,t=na()){this.logger.info(`[${t}][sendProgress]`),this.telemetryHelper.recordEvent(pl,{causeId:t}),this.http.sendPostRequest({url:e.response.callInvitation.links.progress,requestName:sd.SEND_CALL_PROGRESS.name,payload:Ou(this),causeId:t}).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][sendProgress] error: ${Ne(i)}`),this.disposed||this.telemetryHelper.recordEvent(gl,{causeId:t,...i.error})}))}handleCallNotification(e){const t=ya(e);if(this.logger.info(`[${t}][handleCallNotification]`),this.telemetryHelper.recordIncomingEvent(Xo,e),!ua(e.url,Ar.REPLACE))throw new Error(`[${t}][handleCallNotification]IncomingCallNotification should not be received in handleIncomingMsg`);this.telemetryHelper.recordIncomingEvent(el,e),this.logger.info(`[${t}][handleCallNotification]replacementCallNotification`),this.signalingSessionCallback&&this.signalingSessionCallback.onIncomingCallReplacement(e.body,t)}handleMediaAnswer(e){this.telemetryHelper.recordIncomingEvent(Fa,e);const t=e.body,i=ya(e);if(this.logger.info(`[${i}][handleMediaAnswer]`),this.mediaRenegotiationManager.isOutgoingRenegotiationInProgress())this.mediaRenegotiationManager.handleMediaAnswer(t,i);else if(this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED);else if(this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING){if(va(e.headers,this.provisionalMediaAnswersSeenSoFar))return void this.logger.info(`[${i}][handleMediaAnswer] ignoring provisional answer retried by service`);t.mediaAnswer.sender&&(this.remoteUser=t.mediaAnswer.sender),this.resetCallEstablishmentTimeout(i),t.mediaAnswer.noRingBack||(this.telemetryHelper.setTimeToRingDuration(),this.onCallStatusChanged(Jr.CALL_STATUS.RINGING,i));const n=t.mediaAnswer.mediaContent;this.signalingSessionCallback.onAnswer({provisional:!0,renegotiation:!1,remoteEndpointId:t.mediaAnswer.sender?t.mediaAnswer.sender.endpointId:ra(),remoteParticipantId:this.getParticipantIdForOfferAnswer(n),mediaContent:n},i)}}async _sendCallAcceptanceAcknowledgement(e,t){this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:sd.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][_sendCallAcceptanceAcknowledgement] error: ${Ne(i)}`),this.disposed||this.telemetryHelper.recordEvent(zs,{causeId:t,...i.error})}))}handleCallAcceptance(e){const t=ya(e);this.telemetryHelper.recordIncomingEvent(Gs,e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptance]enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?(this._sendCallAcceptanceAcknowledgement(e,t),this._processCallAcceptance(e,t)):(this._processCallAcceptance(e,t),this.http.sendPostRequest({url:e.body.callAcceptance.links.acknowledgement,requestName:sd.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,payload:ku(this),causeId:t}).catch((e=>{const i=fa(e,this.signalingAgentConfig);this.logger.info(`[${t}][handleCallAcceptance] error: ${Ne(i)}`),this.disposed||this.telemetryHelper.recordEvent(zs,{causeId:t,...i.error})})))}handleCallAcceptanceSync(e){const t=ya(e);this.telemetryHelper.recordIncomingEvent(js,e,{enableQuickSendAcceptanceAck:this.signalingAgentConfig.enableQuickSendAcceptanceAck,causeId:t}),this.logger.info(`[${t}][handleCallAcceptanceSync] enableQuickSendAcceptanceAck:\n            ${this.signalingAgentConfig.enableQuickSendAcceptanceAck}`),this.signalingAgentConfig.enableQuickSendAcceptanceAck?Pd.defer(this._processCallAcceptance,e,t):this._processCallAcceptance(e,t);const i=ku(this).payload;return this.telemetryHelper.addNetworkOperationCompleted(sd.SEND_ACCEPTANCE_ACKNOWLEDGEMENT.name,!0),i}getFakeRoster(e){const t=this.participantManager.getParticipantsToInitiateCallWith();let i;i=1===t.length?t[0].id:e.callAcceptance.acceptedBy.id;const n={id:i,displayName:e.callAcceptance.acceptedBy.id===i?e.callAcceptance.acceptedBy.displayName:"",languageId:e.callAcceptance.acceptedBy.languageId},r=e.callAcceptance.acceptedBy.endpointId;return{type:"MultiPartyEndpoint",participants:{[i]:{acceptedBy:e.callAcceptance.acceptedBy.id,details:n,endpoints:{[r]:{call:{},contentSharing:{},capabilities:e.callAcceptance.capabilities,participantId:e.callAcceptance.acceptedBy.participantId}}}}}}processCallAcceptance(e,t){this.logger.info(`[${t}][processCallAcceptance] ${Ne(e)}`),this.telemetryHelper.recordEvent(ml,{causeId:t}),this.fsmState=Jr.SIGNALING_FSM_STATE.CONNECTED,this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.isPreheatOnly||this.telemetryHelper.startCallConnectedWatch(),this.mediaRenegotiationManager.onCallConnected(t);let i=!1;e.callAcceptance.controllerName===Jr.MISC.LOBBY_CALL_CONTROLLER&&(this.logger.info(`[${t}][processCallAcceptance] Controller name is lobby so putting user in lobby`),this.participantManager.localParticipant.isLobby=!0,this.participantManager.localParticipant.endpointDetails.push({isLobby:!0,endpointId:this.participantManager.localParticipant.endpointId,participantId:this.participantManager.localParticipant.participantId}),i=!0,this.telemetryHelper.recordEvent(fl,{causeId:t})),this.participantManager.localParticipant.isStaging=Nd(e.callAcceptance),this.signalingSessionCallback.onMeetingGroupDetailsUpdated(e.callAcceptance.meetingGroupDetails,t),this.signalingSessionCallback.updateIsSharedLineAppearanceV2Activated(e.callAcceptance.callProperties?.isSharedLineAppearanceV2Activated),this.logger.info(`[${t}][processCallAcceptance] for localParticipant, isStaging is set to ${this.participantManager.localParticipant.isStaging}`);let n=this.mediaTypesToUse,r=ra();e.callAcceptance.acceptedBy&&(this.remoteUser=Na.fromWireParticipant(e.callAcceptance.acceptedBy),r=e.callAcceptance.acceptedBy.endpointId),e.callAcceptance.acceptedCallModalities&&e.callAcceptance.acceptedCallModalities.length>0&&(n=e.callAcceptance.acceptedCallModalities);const a=e.callAcceptance.mediaContent;this.callUsesMixer=a.fromMixer;const s=ca(n);this.telemetryHelper.addIncomingModalities(s),this.telemetryHelper.setAnsweredModalities(a.blob,!0),this.links[Jr.LINKS.MEDIA_RENEGOTIATION]=e.callAcceptance.links.mediaRenegotiation,this.links[Jr.LINKS.TRANSFER]=e.callAcceptance.links.transfer,this.links[Jr.LINKS.REPLACE]=e.callAcceptance.links.replacement,this.links[Jr.LINKS.HANGUP]=e.callAcceptance.links.callLeg,this.links[Jr.LINKS.KEEPALIVE]=e.callAcceptance.links.callLeg,this.links[Jr.LINKS.PARK]=e.callAcceptance.links.hold,this.links[Jr.LINKS.UPDATE_MEDIA_DESCRIPTIONS]=e.callAcceptance.links.updateMediaDescriptions,this.saveMediaControllerLinksIfAny(e.callAcceptance),this.scheduleKeepAlives(e.callAcceptance.callKeepAliveInterval);const o=this.getParticipantIdForOfferAnswer(a);this.signalingSessionCallback.onAnswer({provisional:!1,renegotiation:!1,remoteEndpointId:r,remoteParticipantId:o,callAcceptedByNGCVoicemail:o===Jr.KNOWN_BOTS.VOICEMAIL_BOT_ID,mediaTypes:s,mediaContent:a},t),this.setRealTimeState(2,t),this.onCallStatusChanged(Jr.CALL_STATUS.CONNECTED,t),i&&this.signalingSessionCallback.onSelfParticipantUpdated(this.participantManager.localParticipant,t),this.linkUpdateRequested.keepAliveLinks&&(this.logger.info(`[${t}][processCallAcceptance] Updating CC links as requested`),this.updateLinks(this.updateKeepAliveUrl,t))}updateGroupChatIds(e,t){const i=this.groupId,n=this.threadId,r=this.teamsMessageId,a=this.backroomThreadId;this.groupId=e.groupId,this.threadId=e.threadId,this.teamsMessageId=e.messageId,this.backroomThreadId=e.backroomThreadId,this.groupId===i&&this.threadId===n&&this.teamsMessageId===r&&this.backroomThreadId===a||this.signalingSessionCallback.onConversationUpdated({conversationType:this.conversationType,groupId:this.groupId,threadId:this.threadId,teamsMessageId:this.teamsMessageId,isMultiParty:this.multiParty,commandUrlPresence:this.getCommandUrlPresence(),meetingData:this.meetingData,region:this.region,meetingInfo:this.meetingInfo,callLimits:this.callLimits,isHuddleGroupCall:this.isHuddleGroupCall,backroomThreadId:this.backroomThreadId},t)}handleCallEnd(e){let t=e.body.callEnd||e.body;const i=ya(e);if(this.logger.info(`[${i}][handleCallEnd][content=${Ne(t)}]`),this.telemetryHelper.recordEvent(qs,{origin:e.origin,code:t?t.code:"unknown",subCode:t?t.subCode:"unknown",resultCategories:t?t.resultCategories:[],causeId:i}),this.signalingAgentConfig.enableConversationTypeUpdateOnCallEnd&&(this.conversationType=t?.conversationType||this.conversationType),this.fsmState!==Jr.SIGNALING_FSM_STATE.IDLE)if(t.code===Jr.CALL_END_CODE.CONFLICT&&this.multiParty&&t.conversationUrl?.Location)this.handleConversationResolutionConflict(t,i);else{this.disposing=!0,t.callControllerTransactionEnd&&(this.logger.info("handleCallEnd: using CC end details specified in CS end"),t=t.callControllerTransactionEnd),t.broadcastOperationFailure&&(this.logger.info("handleCallEnd: using broadcastOperationFailure end details specified in CS end"),t=t.broadcastOperationFailure);const e=t.code===Jr.CALL_END_CODE.SUCCESS||t.code===Jr.CALL_END_CODE.CANCEL||t.code===Jr.CALL_END_CODE.REJECT;this.telemetryHelper.setTerminatingData({terminatingEnd:md.REMOTE,resultDetail:t.phrase,resultValue:e?fd.SUCCESS:fd.FAILURE,endCode:t.code,endSubCode:t.subCode,resultCategories:t?t.resultCategories:[],causeId:i});const n={code:t.code,subCode:t.subCode,phrase:t.phrase,resultCategories:t.resultCategories,pickupCode:""};this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,t.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:t.acceptedElsewhereBy.id,displayName:t.acceptedElsewhereBy.displayName}),t.unparkContent&&(t.unparkContent.CallParkAdditionalContext&&(this.parkAdditionalContextJson=JSON.stringify(t.unparkContent.CallParkAdditionalContext),this.serverHoldLocation=t.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),t.unparkContent.pickupCode&&(n.pickupCode=t.unparkContent.pickupCode)),this.onCallStatusChanged(Jr.CALL_STATUS.REMOTE_TERMINATED,i,n),this.dispose(n,i)}else this.logger.info(`[${i}][handleCallEnd] not handling incoming callEnd since fsmstate = SIGNALING_FSM_STATE.IDLE`)}handleConversationResolutionConflict(e,t){this.logger.info(`[${t}][handleConversationResolutionConflict]`);const i={...e,phrase:e.phrase||"Conflict Resolution Error"};if(this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING_FOR_ROSTER_ONLY||this.fsmState===Jr.SIGNALING_FSM_STATE.CONNECTED_FOR_ROSTER_ONLY)this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.http.cancelRequestIfPending(sd.JOIN_CONVERSATION_WITHOUT_CALL_MODALITY.name,t,void 0,i),this.subscribeToCall(e.conversationUrl.Location,e.correlationId,this.lastUsedJoinCallOptions?this.lastUsedJoinCallOptions.clientEndpointCapabilities:0,{meetingData:this.meetingData,meetingPreferences:this.meetingPreferences,additionalEndpointProperties:this.lastUsedJoinCallOptions?.additionalEndpointProperties},t);else{this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT);const n={meetingData:this.meetingData,meetingPreferences:this.meetingPreferences};if(this.lastUsedJoinCallOptions){const e=this.lastUsedJoinCallOptions.scenario;n.muted=this.lastUsedJoinCallOptions.muted,n.scenario=`409Redirect${e||""}`,n.isPreheatOnly=this.lastUsedJoinCallOptions.isPreheatOnly,n.clientEndpointCapabilities=this.lastUsedJoinCallOptions.clientEndpointCapabilities,n.clientEndpointDebugContent=this.lastUsedJoinCallOptions.clientEndpointDebugContent,n.additionalEndpointProperties=this.lastUsedJoinCallOptions.additionalEndpointProperties}else n.scenario="409RedirectJoin";this.setInitialTelemetry("JoinCall",{correlationId:e.correlationId,causeId:t,conversationServiceUrl:e.conversationUrl.Location,joinCallOptions:n,offerGenerationTime:void 0}),this.http.cancelRequestIfPending(sd.JOIN_CONVERSATION.name,t,void 0,i),this.http.cancelRequestIfPending(sd.START_CALL.name,t,void 0,i),this.joinGivenConversation(e.conversationUrl.Location,e.correlationId,this.lastUsedOutgoingMediaContent,this.mediaTypesToUse,void 0,n,t)}}handleCallProgress(e){this.telemetryHelper.recordIncomingEvent(Ks,e);const t=ya(e);this.logger.info(`[${t}][handleCallProgress]`);const i=e.body.callProgress;this.fsmState===Jr.SIGNALING_FSM_STATE.OUTGOING&&(this.telemetryHelper.setTimeToRingDuration(),this.resetCallEstablishmentTimeout(t),this.onCallStatusChanged(Jr.CALL_STATUS.RINGING,t),"forwarded"===i.status&&this.signalingSessionCallback.onCallForwarded({destinationType:i.forwardingDestinationType||"user"},t))}resetCallEstablishmentTimeout(e){this.logger.info("resetCallEstablishmentTimeout"),this.timeoutManager.stopTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT),this.timeoutManager.startTimer(Jr.TIMEOUT_OPERATIONS.OUTGOING_CALL_ESTABLISHMENT,(()=>{this.handleCallEstablishmentTimeout(e)}),Jr.TIMEOUT_VALUES_IN_SECONDS.OUTGOING_CALL_ESTABLISHMENT_TIMEOUT)}handleMediaAcknowledgement(e){this.telemetryHelper.recordIncomingEvent(nl,e);const t=e.body,i=ya(e);this.currentCallStatus!==Jr.CALL_STATUS.CONNECTED?this.telemetryHelper.recordEvent(rl,{causeId:i}):this.mediaRenegotiationManager.handleMediaAcknowledgment(t,i)}handleConversationUpdate(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleConversationUpdate]content=${Ne(t)}`),this.telemetryHelper.recordIncomingEvent(Cs,e),this.processConversationServiceResponse(t,i,2)}endBroadcastMeeting(e){this.logger.info(`[${e}][endBroadcastMeeting]`),this.broadcastSession=null}handleLocalParticipantUpdate(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleLocalParticipantUpdate]content=${Ne(t)}`),this.telemetryHelper.recordIncomingEvent(_s,e),this.processLocalParticipantUpdateResponse(t,i)}handleAddModalityFailure(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAddModalityFailure]`),this.telemetryHelper.recordIncomingEvent(ho,e),t.modalityFailure.contentSharing?this.contentSharingManager?.handleAddModalityFailure(t,i):t.modalityFailure.groupChat?this.signalingSessionCallback.onChatModalitySetupFailed({code:t.modalityFailure.groupChat.code,subCode:t.modalityFailure.groupChat.subCode,phrase:t.modalityFailure.groupChat.phrase,resultCategories:t.modalityFailure.groupChat.resultCategories},i):t.modalityFailure.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalityFailure(t,i)}handleAddModalitySuccess(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleAddModalitySuccess]`),this.telemetryHelper.recordIncomingEvent(uo,e),t.modalitySuccess.contentSharing?this.contentSharingManager?.handleAddModalitySuccess(t,i):t.modalitySuccess.groupChat?this.logger.info(`[${i}][handleAddModalitySuccess] group modality ${Ne(t.modalitySuccess.groupChat)}`):t.modalitySuccess.broadcast&&this.broadcastSession&&this.broadcastSession.handleAddBroadcastModalitySuccess(t,i)}handleTransferRequested(e){const t=e.body.callTransfer,i=ya(e);this.logger.info(`[${i}][handleTransferRequested]`),t.parkType?(this.telemetryHelper.recordIncomingEvent(Oo,e,{type:t.parkType}),this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId)):"voicemail"===t.target.endpointType?(this.logger.info(`[${i}][handleTransferRequested] target endpointType = ${t.target.endpointType}`),this.telemetryHelper.recordIncomingEvent(Do,e)):this.telemetryHelper.recordIncomingEvent(Do,e),this.links[Jr.LINKS.TRANSFER_ACCEPTANCE]=t.links.transferAcceptance,this.links[Jr.LINKS.TRANSFER_COMPLETION]=t.links.transferCompletion,this.signalingSessionCallback.onTransferRequested?this.signalingSessionCallback.onTransferRequested(t,i):this.logger.info(`[${i}][handleTransferRequested] failed, no callback defined`)}handleTransferAcceptance(e){const t=ya(e);this.logger.info(`[${t}][handleTransferAcceptance]`),this.telemetryHelper.recordIncomingEvent(kl,e),this.signalingSessionCallback.onTransferAccepted?this.signalingSessionCallback.onTransferAccepted(t):this.logger.info(`[${t}][handleTransferAcceptance]failed, no callback defined`)}handleTransferCompletion(e){const t=e.body,i=ya(e);this.logger.info(`[${i}][handleTransferCompletion]`),t.sharedCorrelationId&&this.telemetryHelper.addSharedCorrelationId(t.sharedCorrelationId),void 0!==t.unparkContent?.pickupCode&&(t.unparkContent.pickupCode=t.unparkContent.pickupCode.toString(),this.telemetryHelper.recordIncomingEvent(Ul,e)),this.signalingSessionCallback.onTransferCompleted?(e.body.transferCompletion&&(0===e.body.transferCompletion.code?this.telemetryHelper.recordIncomingEvent(Ll,e):(this.logger.info(`[${i}][handleTransferCompletion]-1-code: ${t.transferCompletion.code}, message: ${Ne(e)}`),this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories}))),this.signalingSessionCallback.onTransferCompleted(t,i)):(e.body.transferCompletion&&(e.body.transferCompletion.code===Jr.CALL_END_CODE.NETWORK_ERROR?this.telemetryHelper.recordIncomingEvent(Dl,e):this.telemetryHelper.recordIncomingEvent(ko,e,{code:t.transferCompletion.code,subcode:t.transferCompletion.subCode,resultCategories:t.transferCompletion.resultCategories})),this.logger.info(`[${i}][handleTransferCompletion]failed, no callback defined`))}handleRosterUpdate(e,t){const i=e.body,n=ya(e);this.disposing||this.disposed?this.logger.info(`[${n}][handleRosterUpdate]failed=ignore call ending or ended`):this.internalHandleRosterUpdate(i,t,n)}handleNewMediaOffer(e){const t=ya(e);this.telemetryHelper.recordIncomingEvent(ll,e);const i=e.body.mediaOfferReady.mediaContent;this.callUsesMixer=i.fromMixer,this.signalingSessionCallback.onNewOffer({mediaContent:i,renegotiation:!1},t)}internalHandleRosterUpdate(e,t,i){if(e&&"Delta"!==e.type&&"MultiPartyEndpoint"!==e.type)this.logger.warn(`[${i}][internalHandleRosterUpdate] roster.type=${e.type} is invalid`);else{this.logger.info(`[${i}][internalHandleRosterUpdate]`);try{this.participantManager.handleRosterUpdate(e,t,i),this.contentSharingManager?.handleIncomingContentSharingFromRoster(e,t,i)}catch(t){const n={code:Jr.CALL_END_CODE.BAD_SERVICE_RESPONSE,subCode:Jr.CALL_END_SUB_CODE.ROSTER_HANDLING_INVALID_SERVICE_RESPONSE,phrase:t?.toString()};throw this.logger.info(`[${i}][internalHandleRosterUpdate] ${Le(n)}`),this.telemetryHelper.recordRosterEvent(e,ys,i),n}}}scheduleKeepAlives(e){const t=.9*e*1e3;this.logger.info(`scheduleKeepAlives: every ${t} milliseconds`),this.keepAliveInterval=t,this.keepAliveTimer=window.setInterval(this.sendKeepAlive.bind(this),this.keepAliveInterval)}scheduleConversationKeepAlive(){if(!this.conversationKeepAliveTimer&&!this.disposed){if(!this.conversationKeepAliveInterval){const e=function(e){const t=Math.floor(11*Math.random())+10;return Math.floor(e*(1-t/100))}(1e3*this.signalingAgentConfig.csaTimeoutConfiguration.conversationKeepAliveTimeoutSec);this.logger.info(`sendConversationKeepAlive: every ${e} milliseconds`),this.conversationKeepAliveInterval=e}this.conversationKeepAliveTimer=window.setInterval(this.sendConversationKeepAlive.bind(this),this.conversationKeepAliveInterval)}}sendConversationKeepAlive(){this.logger.info("sendConversationKeepAlive"),this.disposed?this.logger.info("sendConversationKeepAlive ignored"):(this.logger.info("sendConversationKeepAlive keepAlive count = "+this.conversationKeepAliveCount++),this.sendToUpdateConversationLinks(!0))}sendKeepAlive(){this.logger.info("sendKeepAlive"),this.disposed?this.logger.info("sendKeepAlive ignored"):(this.logger.info("sendKeepAlive keepAlive count = "+this.keepAliveCount++),this.sendToKeepAliveUrl(null))}sendToUpdateConversationLinks(e,t=na()){if(this.disposed)return;const i=this.logger.createChild(`[${t}][sendToUpdateConversationLinks]`,this.correlationId),n=e?function(e){oa(e,"signalingSession cannot be null");const t={type:"Delta",rosterUpdate:Zr(e,Rr.CONV_ROSTER_UPDATE)};return{payload:{participants:{from:{id:e.participantManager.localParticipant.id,displayName:e.participantManager.localParticipant.displayName,endpointId:e.participantManager.localParticipant.endpointId,participantId:e.participantManager.localParticipant.participantId,languageId:e.participantManager.localParticipant.languageId}},roster:t,links:da(e,Rr)}}}(this):{},r=e?sd.UPDATE_CONVERSATION_LINKS.name:sd.SEND_CONVERSATION_KEEP_ALIVE.name,a=this.links[Jr.LINKS.NOTIFICATION_LINKS];i.info(`shouldUpdateUrl: ${e}, url: ${a}, payload: ${Ne(n)}`),a&&(this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.http.sendPostRequest({url:a,payload:n,withoutTrouter:!0,requestName:r,causeId:t}).then((e=>{this.disposed||(this.telemetryHelper.recordEvent(dl,{causeId:t}),this.processConversationServiceResponse(e.response,t,2))})).catch((e=>{const i=fa(e,this.signalingAgentConfig),n=Ia(i.error.code);this.logger.info(`[${t}][updateConversationLinks] error: ${Ne(i)}, retryable: ${n}`),this.disposed||(this.telemetryHelper.recordEvent(ul,{causeId:t,...i.error}),n?this.scheduleConversationKeepAlive():this.links[Jr.LINKS.NOTIFICATION_LINKS]=null)})))}sendToKeepAliveUrl(e,t=na()){const i=this.logger.createChild(`[${t}][sendToKeepAliveUrl]`,this.correlationId);i.info(`payload: ${Ne(e)}`),window.clearInterval(this.keepAliveTimer),this.disposed||(this.telemetryHelper.recordEvent(Sl),this.http.sendPostRequest({url:this.links[Jr.LINKS.KEEPALIVE],payload:e,requestName:sd.SEND_KEEP_ALIVE.name,withoutTrouter:!0,causeId:t}).then((()=>{this.restartKeepAliveInterval()})).catch((e=>{const t=fa(e,this.signalingAgentConfig);i.info(`error: ${Ne(t)}`),this.restartKeepAliveInterval(!0,t.error)})))}handleCallEstablishmentTimeout(e,t,i){const n={code:Jr.CALL_END_CODE.TIMEOUT,subCode:t||Jr.CALL_END_SUB_CODE.CALL_ESTABLISHMENT_TIMEOUT,phrase:i||Jr.CALL_END_PHRASE.ESTABLISHMENT_TIMEOUT,resultCategories:[Er]};this.isPromotingToRealtime?this.onPromotionCompleted(!0,n,e):(this.telemetryHelper.recordEvent(Ws),this.telemetryHelper.setTerminatingData({terminatingEnd:md.LOCAL,resultValue:fd.FAILURE,resultDetail:n.phrase,endCode:n.code,endSubCode:n.subCode,causeId:e,resultCategories:n.resultCategories}),this.fsmState=Jr.SIGNALING_FSM_STATE.IDLE,this.onCallStatusChanged(Jr.CALL_STATUS.LOCAL_TERMINATED,e,n),this.dispose(n,e))}handleCallTransferTimeout(e,t){if(this.disposed)return void this.logger.info("Transfer: handleCallTransferTimeout ignored");const i={code:Jr.CALL_END_CODE.TIMEOUT,phrase:Jr.CALL_END_PHRASE.TRANSFER_COMPLETION_TIMEOUT};this.signalingSessionCallback.onTransferCompleted&&(!1===t?this.telemetryHelper.recordEvent(ko,{code:Jr.CALL_END_CODE.TIMEOUT,subcode:Jr.CALL_END_SUB_CODE.TRANSFER_COMPLETE_TIMEOUT,causeId:e}):!0===t&&this.telemetryHelper.recordEvent(Ol,{causeId:e}),this.signalingSessionCallback.onTransferCompleted({transferCompletion:i},e))}checkCorrelationIdChange(e,t){if(e&&e.headers){const i=e.headers.get(Jr.HEADERS.CORRELATION_ID);if(i&&i.length){const n=[Ar.CONV_CONTENT_SHARING_UPDATE,Ar.CONV_CONTENT_SHARING_END].some((t=>e.url&&ua(e.url,t)));this.correlationId===i||n||(this.logger.info(`[${t}]checkCorrelationIdChange:${this.correlationId} => ${i}`),this.telemetryHelper.addChangingCorrelationId(this.correlationId,i),this.updateCorrelationId(i,t))}}}getCommandUrlPresence(){let e=0;return this.links[Jr.LINKS.MUTE]&&(e|=1),this.links[Jr.LINKS.UNMUTE]&&(e|=2),e}getCallNotFoundTransactionEnd(){return{code:Jr.CALL_END_CODE.CALL_DOES_NOT_EXIST,subCode:0,phrase:Jr.CALL_END_PHRASE.CALL_DOES_NOT_EXIST}}getTerminatingCallResultDetail(e,t){return Ne({source:e,...t})}dispose(e,t){this.disposed||(this.logger.info(`[${t}][dispose] end reason ${Ne(e)}`),this.disposed=!0,this.disposing=!1,this.tearDownConnectionCheck(),this.conversationKeepAliveTimer&&(window.clearInterval(this.conversationKeepAliveTimer),this.conversationKeepAliveTimer=0),this.keepAliveTimer&&window.clearInterval(this.keepAliveTimer),this.brokerService&&this.brokerService.dispose(),this.http.cancelAllRequests(t).then((()=>{this.signalingAgent.onCallCompleted(this.sessionId,t),this.signalingAgentConfig.trouterUrlGetter&&this.signalingAgentConfig.trouterUrlGetter.trouterUrl.changed.off(this.onTrouterUrlChanged),this.signalingAgentConfig.trouterServiceProvider&&this.signalingAgentConfig.trouterServiceProvider.offStateChanged(this.onTrouterStateChanged),this.timeoutManager.dispose(),this.timeoutManager=null,this.participantManager.dispose(e,t),this.callOperationHandler.dispose("call ended",e,t),this.participantManager=null,this.mediaRenegotiationManager?.dispose(),this.mediaRenegotiationManager=null,this.contentSharingManager?.dispose(e,t),this.contentSharingManager=null,this.telemetryHelper.dispose(),this.telemetryHelper=null,this.webRtcSignalingManager.dispose(),this.webRtcSignalingManager=null})))}};var sh=class{constructor(e){this.endpointId=ra(),this.signalingSessions={},this.clientSupportsGenericTokenAPI=!1,this.getNewSignalingSession=(e,t,i,n)=>{const r=na();oa(e,"selfParticipant should be a non null value"),oa(t,"signalingSessionCallback should be a non null value");const a=i||ra();sa(a,"signalingSession id generated cannot be null or empty"),this.checkConfigChange(r);const s=function(e,t,i,n,r,a){return new ah(e,t,i,n,r,a)}(e,t,this.signalingAgentConfig,a,this,n),o=s.sessionId;return this.signalingSessions[o]=s,this.logger.info(`[${r}]Created new signalingSession with correlation ID ${a} and session ID ${o}`),s},this.resolvePotentialCallConflict=e=>{const t=na();let i;if(this.logger.info(`[${t}][resolvePotentialCallConflict]`),!e.multiParty)return Object.keys(this.signalingSessions).forEach((t=>{this.isSessionInConflictingState(this.signalingSessions[t],!e.isIncomingCall)&&(i=e.isIncomingCall?this.compareAndGetConflictingSession(e,this.signalingSessions[t]):this.compareAndGetConflictingSession(this.signalingSessions[t],e))})),i?(this.logger.info("Call conflict done, conflicting session callId=",i.correlationId,"urlIdentifier=",i.urlIdentifier),i.telemetryHelper.recordEvent(Fs),this.signalingAgentConfig.endConflictedCall?(this.endConflictedSession(i,t),i):void 0):void 0},this.handleIncomingNotification=e=>{if(oa(e,"request should be a non null value"),this.logger.info(`handleIncomingNotification to : ${e.url}`),!e.body&&!e.rawBody)return this.logger.error("request has no body"),this.buildNotificationResponse(Jr.HTTP_STATUS_CODES.BAD_REQUEST);let t=Jr.HTTP_STATUS_CODES.OK;const i=function(e){const t=e.match(new RegExp(`/${function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(Jr.URL_BASE.CALLAGENT)}/+([^/]+)`,"i"));return t?t[1]:null}(e.url);if(i){const n=this.signalingSessions.hasOwnProperty(i);if(this.logger.info(`Is session found:${n}`),n){const t=this.signalingSessions[i];if(e.headers=new Qr(e.headers),Ca(e.headers))try{if(!_a(e.headers))throw new Error("Unsupported encoding");const t=Ea(e.rawBody),i=JSON.parse(t);e.body=i}catch(e){return t.telemetryHelper.recordEvent(Bo),this.buildNotificationResponse(Jr.HTTP_STATUS_CODES.BAD_REQUEST)}if(t.canHandleIncomingMsgSync(e))return t.handleIncomingMsgSync(e);window.setTimeout((()=>{if(this.signalingSessions.hasOwnProperty(i)){const t=this.signalingSessions[i];t.handleIncomingMsgAsync(e).catch((e=>{t&&t.telemetryHelper&&t.telemetryHelper.recordEvent(zo),this.logger.error(`handling IncomingMsg failed with error: ${e}`)}))}}),0)}else this.logger.info(`Incoming message for session ID ${i}, but session was not found!`),t=Jr.HTTP_STATUS_CODES.NOT_FOUND}else this.logger.error(`Could not retrieve session ID from Url path. Path = ${e.url}`),t=Jr.HTTP_STATUS_CODES.BAD_REQUEST;const n=this.buildNotificationResponse(t);return this.logger.info(`Result code:${Ne(n)}`),n},this.onCallCompleted=(e,t)=>{this.signalingSessions.hasOwnProperty(e)?(delete this.signalingSessions[e],this.logger.info(`[${t}][onCallCompleted] Session ID ${e} found. Deleted from signalingSession table`)):this.logger.info(`[${t}][onCallCompleted] Session ID ${e} not found. Could not delete from signalingSession table`)},this.applyAuthTokenCacheConfig=e=>{this.signalingAgentConfig.enableTokenCache?(this.authTokenManager.setTokenCaching(!0,e),this.signalingAgentConfig.enableTokenPrefetch&&this.authTokenManager.getToken(e).then((()=>{this.logger.info(`[${e}] token prefetch success`)})).catch((t=>{this.logger.info(`[${e}] token prefetch failure, error=${Ne(t)}`)}))):this.authTokenManager.setTokenCaching(!1,e),this.signalingAgentConfig.enableTokenCacheForGenericTokenAPI?this.authTokenManager.setTokenCachingForGenericTokenAPI(!0,e):this.authTokenManager.setTokenCachingForGenericTokenAPI(!1,e)},this.endConflictedSession=(e,t)=>{this.logger.info("Call conflict, ending signalingSession with callId=",e.correlationId,"urlIdentifier=",e.urlIdentifier),e.endAsync({code:Jr.CALL_END_CODE.CONFLICT,subCode:Jr.CALL_END_SUB_CODE.CONFLICT_IN_NG,phrase:Jr.CALL_END_PHRASE.CONFLICT},{forEveryone:!1,causeId:t})},this.compareAndGetConflictingSession=(e,t)=>{if(!ta(e.incomingCallCallerId)||!ta(t.participantManager.localParticipant.id))return;const i=ia(e.incomingCallCallerId),n=ia(t.participantManager.getParticipantsToInitiateCallWith().length&&t.participantManager.getParticipantsToInitiateCallWith()[0].id),r=ia(t.participantManager.localParticipant.id);return n===i?r>i?e:t:void 0},this.isSessionInConflictingState=(e,t)=>{if(!e)return this.logger.info("Call conflict, ignore, session already disposed"),!1;const i=[Jr.CALL_STATUS.IDLE,Jr.CALL_STATUS.CONNECTING,Jr.CALL_STATUS.RINGING];return!e.multiParty&&i.indexOf(e.getCallStatus())>-1&&(t&&e.isIncomingCall||!t&&!e.isIncomingCall)},this.buildNotificationResponse=(e,t)=>this.signalingAgentConfig.supportsSynchronousTrouterResponse?{resultCode:e,responseBody:t}:e,Ed(e),this.signalingAgentConfig=e,this.logger=e.logger.createChild("SignalingAgent"),oa(e,"signalingAgentConfig should be a non null value"),this.logger.info(e.isWebRtcEnabled?"webRTC enabled":"ORTC enabled");const t={aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds};this.authTokenManager=Rd(this.logger,e.skypeToken,t,e.telemetryManager),this.applyAuthTokenCacheConfig(na()),Qr.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateSignalingAgentConfig(e){const t=na(),i=JSON.stringify(e,((e,t)=>e?String(t):t));this.logger.info(`[${t}] updateSignalingAgentConfig, SignalingAgentConfig: ${i}`),this.logger.info(`[${t}] ecsEtag=${e.ecsEtag}`),Ed(e),this.updatedSignalingAgentConfig=e,this.authTokenManager?.updateTokenSettings({aadTokenExpirationTimeInSeconds:e.aadTokenExpirationTimeInSeconds,caeTokenExpirationTimeInSeconds:e.caeTokenExpirationTimeInSeconds,refreshTimeBeforeTokenTimeoutInSeconds:e.refreshTimeBeforeTokenTimeoutInSeconds,disableTokenMigrationHeader:e.disableTokenMigrationHeader,enablePublishTokenTelemetry:e.enablePublishTokenTelemetry,forceClearExpiredTokens:e.forceClearExpiredTokens,enableRefreshToken:e.enableRefreshToken,enableRefreshTokenRetry:e.enableRefreshTokenRetry,enableRefreshTokenRetryInSeconds:e.enableRefreshTokenRetryInSeconds}),Qr.useLowerCaseHeaders=e.forceLowercaseHttpHeaders}updateUrls(e,t,i){this.logger.info(`updateUrls: conversationServiceUrl: ${e}, uploadLogRequestUrl: ${t}, enforceUrls: ${i}`),this.updatedSignalingAgentConfig=this.updatedSignalingAgentConfig||this.signalingAgentConfig,i||!this.updatedSignalingAgentConfig.isConversationServiceUrlFromEcs?this.updatedSignalingAgentConfig.conversationServiceUrl=e||this.updatedSignalingAgentConfig.conversationServiceUrl:this.updatedSignalingAgentConfig.conversationServiceUrl=this.updatedSignalingAgentConfig.conversationServiceUrl||e,i||!this.updatedSignalingAgentConfig.isUploadLogRequestUrlFromEcs?this.updatedSignalingAgentConfig.uploadLogRequestUrl=t||this.updatedSignalingAgentConfig.uploadLogRequestUrl:this.updatedSignalingAgentConfig.uploadLogRequestUrl=this.updatedSignalingAgentConfig.uploadLogRequestUrl||t}update(e){this.logger.info(`update accountConfiguration ${JSON.stringify(e)}`),e&&e.clientSupportsGenericTokenAPI!==this.clientSupportsGenericTokenAPI&&(this.clientSupportsGenericTokenAPI=e.clientSupportsGenericTokenAPI,this.authTokenManager.updateTokenSettings({clientSupportsGenericTokenAPI:this.clientSupportsGenericTokenAPI})),this.accountConfig=e}sendPushAsync(e,t,i,n,r=na()){const a=new Ad(this.signalingAgentConfig.piiScrubber),s=`sendPush[local participant mri = ${a.scrubMriOrOmit(e)}][recipientList = ${a.scrubMriOrOmit(t)}][headers = ${i})][causeId = ${r}]`;if(!e?.id)return this.logger.info(`${s} Empty localParticipantId`),Promise.reject("invalid localParticipantId");if(!t||0===t.length||t.every((e=>e&&""===e.id)))return this.logger.info(`${s} Empty recipientList`),Promise.reject("invalid recipientList");if(!i)return this.logger.info(`${s} Empty headers`),Promise.reject("invalid headers");if(!n||null===ma(n))return this.logger.info(`${s} Invalid body.`),Promise.reject("invalid body");const o={...ma(n),To:Array.from(t,(e=>e.id)),From:e.id},l=new Qr(i);l.hasOwnPropertyCaseInsensitive(Jr.HEADERS.CORRELATION_ID)||l.set(Jr.HEADERS.CORRELATION_ID,xi()),l.hasOwnPropertyCaseInsensitive(Jr.HEADERS.MESSAGE_ID)||l.set(Jr.HEADERS.MESSAGE_ID,xi()),l.hasOwnPropertyCaseInsensitive(Jr.HEADERS.PARTICIPANT_ID)||l.set(Jr.HEADERS.PARTICIPANT_ID,xi()),l.hasOwnPropertyCaseInsensitive(Jr.HEADERS.CONTENT_TYPE)||l.set(Jr.HEADERS.CONTENT_TYPE,"application/json"),l.hasOwnPropertyCaseInsensitive(Jr.HEADERS.CLIENT_USER_AGENT)&&l.set(Jr.HEADERS.CLIENT_USER_AGENT,l.get(Jr.HEADERS.CLIENT_USER_AGENT)+"/TsCallingVersion=2024.14.01.23/Ovb=7b433484b6052f263c376357e5f0a7c2fecbb27f");const c=this.signalingAgentConfig.httpRequestDispatcher.getRequestOptions("POST",l?.getAll(),JSON.stringify(o),3e4);return new Promise(((e,t)=>{this.signalingAgentConfig.httpRequestDispatcher.postAsync(this.signalingAgentConfig.uploadLogRequestUrl||Jr.URL_DEFAULTS.UPLOAD_LOG_URL,c).then((()=>{e()})).catch((e=>{t(e)}))}))}getSignalingSession(e){for(const t of Object.keys(this.signalingSessions)){const i=this.signalingSessions[t];if(i.correlationId===e)return i}return null}updateToken(e,t,i,n,r){this.authTokenManager.updateToken(e,t,i,n,r)}setTokenRequiredCallBack(e){this.authTokenManager.setTokenRequiredCallBack(e)}resetAuthTokenManager(){this.setTokenRequiredCallBack(null),this.authTokenManager.setDisableTimerFlag(!0),this.authTokenManager.dispose()}checkConfigChange(e){this.updatedSignalingAgentConfig&&this.updatedSignalingAgentConfig!==this.signalingAgentConfig&&(this.signalingAgentConfig=this.updatedSignalingAgentConfig,this.updatedSignalingAgentConfig=null,this.applyAuthTokenCacheConfig(e))}},oh=/;aliases=.*$/i,lh="8:";function ch(e){return e?e.replace(oh,""):e}function dh(e,t){let i=e;return t&&(i+=";aliases=2:"+t),i}var uh=(e,t)=>t&&void 0!==t.phase&&!!e[t.phase],hh=(e,t)=>t&&void 0!==t.phase&&t.phase===e;function ph(e){const t={},i=e=>{t[e]={status:"Pending"}},n=(e,i)=>{t[e].t=i,delete t[e].status},r=(e,i,n)=>{t[e].status="Failed",t[e].t=i,t[e].reason=Ne(n)};return{execute:async(a,s)=>{const o=e.createChild(`[phase=${a}]`);i(a),o.info("started");const l=(new Date).getTime();try{const e=await s(),t=+new Date-l;return o.logSuccess(`done, time=${t}`),n(a,t),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${Ne(e)}`),r(a,i,e),{phase:a,error:e,phases:t}}},executeSync:(a,s)=>{const o=e.createChild(`[phase=${a}]`);o.info("started"),i(a);const l=(new Date).getTime();try{const e=s(),t=+new Date-l;return n(a,t),o.logSuccess(`done, time=${t}`),e}catch(e){const i=+new Date-l;throw o.logFailure(`time=${i}, error=${Ne(e)}`),r(a,i,e),{phase:a,error:e,phases:t}}},getTelemetryData:()=>t}}function gh(e,t){return-1!==t.indexOf(e)}var mh,fh,vh,Sh={0:[1,2,8,6,10,11,9],1:[2,6,7,10,13],2:[1,3,6,7,9,10,13,14],3:[6,7,4,5,10,13],8:[1,11,10,2,9,6,7],4:[6,7,3,5,10,13],5:[6,7,3,4,10,13],9:[3,6,7,10,13],10:[3,6,7,9,4,5,13,15],13:[3,6,7,4,5],14:[3,6,7,10,13],15:[3,6,7,4,5,13],11:[12,1,2,6,7],12:[2,6,7],6:[7],7:[]};(e=>{let t;var i;let n;var r;let a;var s;let o;var l;(i=t=e.VideoEffectType||(e.VideoEffectType={})).Off="off",i.BackgroundBlur="blur",i.BackgroundReplacement="replacement",(r=n=e.PowerPreference||(e.PowerPreference={})).Default="default",r.HighPerformance="high-performance",r.LowPower="low-power",(s=a=e.ProcessorType||(e.ProcessorType={})).Wasm="Wasm",s.Webgl2="Webgl2",(l=o=e.EffectQualityChangeReason||(e.EffectQualityChangeReason={}))[l.ExternalParam=0]="ExternalParam",l[l.Performance=1]="Performance",l[l.RendererSize=2]="RendererSize"})(mh||(mh={})),(e=>{let t;var i;let n;var r;let a;var s;let o;var l;let c;var d;(i=t=e.CallType||(e.CallType={}))[i.P2P=0]="P2P",i[i.Conference=1]="Conference",i[i.PSTN=2]="PSTN",i[i.BroadcastingConf=3]="BroadcastingConf",(r=n=e.AudioUsageMode||(e.AudioUsageMode={}))[r.Default=0]="Default",r[r.LongRangeSpeaker=1]="LongRangeSpeaker",r[r.Auditorium=2]="Auditorium",(s=a=e.AecPerfProfile||(e.AecPerfProfile={}))[s.Normal=0]="Normal",s[s.Soc=1]="Soc",s[s.Mobile=2]="Mobile",s[s.NoisyTimestamps=3]="NoisyTimestamps",(l=o=e.VqeMode||(e.VqeMode={}))[l.Off=0]="Off",l[l.SkypeNS=1]="SkypeNS",l[l.SkypeAEC=2]="SkypeAEC",l[l.SkypeVQE=3]="SkypeVQE",l[l.DeepNS=4]="DeepNS",l[l.DeepVQE=5]="DeepVQE",(d=c=e.AudioEffectType||(e.AudioEffectType={})).Off="Off",d.NoiseSuppressionDeep="Deep NS",d.NoiseSuppressionClassic="Classic NS",d.EchoCancellationClassic="Classic AEC",d.VoiceQualityEnhancementClassic="Classic VQE",d.VoiceQualityEnhancementDeep="Deep VQE"})(fh||(fh={})),(e=>{let t;var i;let n;var r;(i=t=e.FrameType||(e.FrameType={}))[i.None=0]="None",i[i.Software=1]="Software",i[i.Hardware=2]="Hardware",(r=n=e.LogLevel||(e.LogLevel={}))[r.Default=0]="Default",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warning=3]="Warning",r[r.Error=4]="Error"})(vh||(vh={}));var yh=g,Ch=(e=>(e[e.CallStateChanged=0]="CallStateChanged",e[e.TrouterStateChanged=1]="TrouterStateChanged",e[e.MultiPartyModeSet=2]="MultiPartyModeSet",e[e.MediaRetargetSucceeded=3]="MediaRetargetSucceeded",e[e.MediaRetargetFailed=4]="MediaRetargetFailed",e))(Ch||{}),_h=(e=>(e[e.StartModality=0]="StartModality",e[e.StopModality=1]="StopModality",e[e.StreamStateChanged=2]="StreamStateChanged",e[e.NegotiationStateChanged=3]="NegotiationStateChanged",e))(_h||{}),Eh=(e=>(e[e.SelectSource=0]="SelectSource",e[e.AttachSource=1]="AttachSource",e[e.DetachSource=2]="DetachSource",e))(Eh||{}),Th=(e=>(e[e.Available=0]="Available",e[e.Subscribe=1]="Subscribe",e[e.Subscribed=2]="Subscribed",e[e.Unsubscribe=3]="Unsubscribe",e[e.Unsubscribed=4]="Unsubscribed",e[e.RenderingStarted=5]="RenderingStarted",e[e.RenderingStopped=6]="RenderingStopped",e))(Th||{}),bh=class{constructor(e,t){this.value=e,this.piiKind=t}},Ih=class{};Ih.agentEnvironmentId="agent_environment_id",Ih.correlationId="CorrelationId",Ih.participantId="participant_id",Ih.tenantId="TenantId",Ih.userHexCID="UserHexCID",Ih.acsResourceId="AcsResourceId",Ih.endpointId="endpoint_id",Ih.mediaLegId="media_leg_id",Ih.webMediaConfigIds="web_media_config_ids",Ih.tsCallingVersion="ts_calling_version";var wh=class{};wh.diagnostics="MediaDiagnostic",wh.qoeStats="QoE",wh.webrtcSession="webrtc_session",wh.webrtcSessionInitial="webrtc_session_initial",wh.realtimeTelemetry="realtimetelemetry",wh.webrtcMediaSession="webrtc_call_session",wh.mediaSession="pluginless_modality_session",wh.callSession="pluginless_call_session";var Rh=class{constructor(e){this.eventName=e,this.ended=!1,this.events=[]}setLocalUserId(e){this.localUserId=e}start(){this.ended||(this.startTime=Date.now())}end(e=0){this.ended||(this.ended=!0,this.resultCode=e)}asStatsRecord(e={}){if((0,yh.isEmpty)(this.events))return null;const t=(0,yh.uniqBy)(this.events,(e=>JSON.stringify(e))).map((e=>{const t={[e.type]:e.timestamp-this.startTime};return(0,yh.isEmpty)(e.data)||(t.data=e.data),t}));return{name:this.eventName,record:(0,yh.assign)({LocalUser:this.localUserId,ResultCode:String(this.resultCode),EventTimestampBag:JSON.stringify({eventStart:this.startTime,events:t})},e)}}add(e){!this.ended&&e.type&&((0,yh.isUndefined)(this.startTime)&&(this.startTime=Date.now()),(0,yh.isUndefined)(e.timestamp)&&(e.timestamp=Date.now()),this.events.push(e))}},Ah=class e extends Rh{constructor(){super(wh.callSession)}callStateChanged(t){super.add({type:Ch[0],data:e.callStateToString[t]||t})}event(e){super.add({type:Ch[e]})}};Ah.callStateToString={0:"None",1:"Notified",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",6:"Disconnecting",7:"Disconnected",8:"Observing",10:"Lobby"};var Ph=Ah,Mh=class e extends Rh{constructor(t,i){super(wh.mediaSession),this.mediaType=t,this.mediaDirection=i,this.streamDirection=e.mediaDirectionToStream[this.mediaDirection]}addEvent(e,t){super.add({type:e,data:t})}lifecycle(e){this.addEvent(_h[e])}streamStateChanged(t,i=this.streamDirection){const n=_h[2];this.addEvent(n,{state:e.streamStateToString[t],direction:e.streamDirectionToString[i]})}negotiationStateChanged(t,i,n=this.streamDirection){const r=_h[3];this.addEvent(r,{state:e.negotiationStateToString[t],reason:i})}asStatsRecord(t={}){return super.asStatsRecord((0,yh.assign)({MediaType:e.mediaTypeToString[this.mediaType],Role:e.mediaDirectionToRole[this.mediaDirection]},t))}};Mh.negotiationStateToString={started:"NegotiationStarted",rejected:"NegotiationRejected",completed:"NegotiationCompleted"},Mh.streamStateToString={created:"StreamCreated",started:"StreamStarted",active:"StreamActive",inactive:"StreamInactive",stopped:"StreamStopped",removed:"StreamRemoved",failed:"StreamFailed",cancelled:"StreamCancelled"},Mh.streamDirectionToString={send:"Send",receive:"Receive"},Mh.mediaTypeToString={0:"Audio",1:"Video",2:"ScreenShare",3:"Data"},Mh.mediaDirectionToRole={1:"Receiver",2:"Sender",4:"Bidirectional"},Mh.mediaDirectionToStream={1:"receive",2:"send"};var kh=Mh,Dh=class extends kh{constructor(){super(0,4)}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}},Oh=class extends kh{constructor(e){super(e,2),this.mediaType=e}start(){super.start(),super.lifecycle(0)}stop(){super.lifecycle(1)}event(e){super.addEvent(Eh[e])}},Nh=class extends kh{constructor(e,t){super(e,1),this.mediaType=e,this.remoteParticipantId=t,this.rendererCounter=0}newRendererId(){return this.rendererCounter+=1,String(this.rendererCounter)}event(e,t,i){super.addEvent(Th[e],(0,yh.isUndefined)(i)?{rendererId:t}:{rendererId:t,sourceId:i})}asStatsRecord(){return super.asStatsRecord({TargetUser:this.remoteParticipantId})}},Lh=class{constructor(){this.allStats=[],this.ended=!1}setLocalUserId(e){this.localUserId=e}get call(){return this.callStats||this.startCall()}get audio(){return this.audioStats||this.newSession(0)}get video(){return this.videoStats||this.newSession(1)}get screenShare(){return this.sharingStats||this.newSession(2)}renderer(e,t){let i=this.renderingStats[t];return i||(i=this.renderingStats[t]=this.receive(e,t)),i}startCall(){return this.callStats?this.callStats:(this.callStats=new Ph,this.callStats.start(),this.addStats(this.callStats))}endCall(e=0){this.ended=!0,this.call.end(e),this.allStats.forEach((e=>e.end())),this.cleanUp()}cleanUp(){this.audioStats&&(this.audioStats.stop(),this.audioStats=null),this.videoStats&&(this.videoStats.stop(),this.videoStats=null),this.sharingStats&&(this.sharingStats.stop(),this.sharingStats=null)}newSession(e){let t;switch(e){case 0:t=this.audioStats=new Dh;break;case 1:t=this.videoStats=new Oh(e);break;case 2:t=this.sharingStats=new Oh(e)}return this.addStats(t)}receive(e,t){const i=new Nh(e,t);return i.start(),this.addStats(i)}buildStatsRecords(){return this.allStats.map((e=>e.asStatsRecord())).filter((e=>!!e))}addStats(e){return this.ended||(this.allStats.push(e),e.setLocalUserId(this.localUserId)),e}},xh=class e{constructor(e){this.configProvider=e,this.localStats=new Lh,this.tsCallingVersion="2024.14.01.23"}setCallId(e){this.callId=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}setParticipantId(e){this.participantId=e}setEndpointId(e){this.endpointId=e}setMediaLegId(e){this.mediaLegId=e}setMediaStats(e){this.mediaStats=e}setAcsResourceId(e){this.acsResourceId=e}appendDataChannelInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.DataHandlers=e)}appendSharingControlInfo(e){this.mediaStats?.data&&(this.mediaStats.data.SharingControlEnabled=e?"true":"false")}appendMediaControlPaneInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.MediaControlPlane=e)}appendTerminationInfo(e,t){this.mediaStats?.data&&(this.mediaStats.data.TerminatedReason=`${e}`,this.mediaStats.data.TerminatedState=`${t}`)}appendPictureInPictureInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.PictureInPicture=e)}appendCallDeviceManagerInfo(e){this.mediaStats?.data&&e&&(this.mediaStats.data.CallDeviceManager=e)}buildFromMediaStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,wh.webrtcSession)]:[]}buildShortBeaconEvent(){const e=this.configProvider?.config?.mediaEventDictionary??Qe.MEDIA_EVENT_FIELDS,t={};t[Ih.correlationId]=this.callId||"",t[Ih.participantId]=this.participantId||"",t[Ih.tenantId]=this.tenantId||"",t[Ih.tsCallingVersion]=this.tsCallingVersion||"",t.metrics_TerminationReason_code=new bh(yn.SUCCESS,0),t.metrics_TerminationReason_subCode=new bh(Cn.BEACON,0);const i=this.buildFromDictionary(this.mediaStats.data,e);return[{eventName:wh.webrtcMediaSession,props:this.buildProps(i,null,t)}]}buildShortCallModalityStats(){const e={};return e[Ih.correlationId]=this.callId||"",e[Ih.userHexCID]=this.userHexCID||"",e[Ih.participantId]=this.participantId||"",e[Ih.endpointId]=this.endpointId||"",e[Ih.tenantId]=this.tenantId||"",e[Ih.tsCallingVersion]=this.tsCallingVersion||"",e[Ih.acsResourceId]=this.acsResourceId||"",e.Code=new bh(yn.SUCCESS,0),e.SubCode=new bh(Cn.BEACON,0),[{eventName:"skypecosi_concore_web_csa_conversation_callmodality",props:e}]}buildFromDictionary(e,t){const i={};for(const n in t)e[n]&&(i[n]={},t[n].forEach((t=>{void 0!==e[n][t]&&(i[n][t]=e[n][t])})));return i}buildMediaTelemetry(){if(!this.mediaStats)return;const e=this.buildEvent(this.mediaStats.data,null).props,t={};return Object.keys(e).forEach((i=>{void 0===e[i].piiKind?t[i]=e[i]:t[i]=e[i].value})),t}buildMidCallTelemetry(e){if(!this.mediaStats)return[];const t=this.buildEvent(this.mediaStats.data,wh.webrtcSession),i=t.props,n=e.reduce(((e,t)=>(i[t]&&(e[t]=i[t]),e)),{});return[{eventName:t.eventName,props:n}]}buildFromCallSetupStats(){return"WebRtcMediaStats"===this.mediaStats?.type?[this.buildEvent(this.mediaStats.data,wh.webrtcSessionInitial)]:[]}buildFromLocalStats(){return this.localStats.buildStatsRecords().map((e=>this.buildEvent(e.record,e.name)))}buildEvent(t,i){const n={};return n[Ih.agentEnvironmentId]=e.agentEnvironmentId,n[Ih.correlationId]=this.callId||"",n[Ih.tenantId]=this.tenantId||"",n[Ih.userHexCID]=this.userHexCID||"",n[Ih.participantId]=this.participantId||"",n[Ih.endpointId]=this.endpointId||"",n[Ih.mediaLegId]=this.mediaLegId||"",n[Ih.webMediaConfigIds]=this.webMediaConfigIds||"",n[Ih.tsCallingVersion]=this.tsCallingVersion||"",n[Ih.acsResourceId]=this.acsResourceId||"",{eventName:i,props:this.buildProps(t,null,n)}}normalizeKey(e){return e.replace(/[^a-zA-Z0-9._]/g,"_")}buildProps(e,t,i){return Object.keys(e).forEach((n=>{const r=this.normalizeKey(n),a=t?`${t}_${r}`:r,s=e[n];if((0,yh.isString)(s))i[a]=this.getPiiAwareValue(n,s);else if((0,yh.isArray)(s)){if(s.length>0){const e=s,t=e.map((e=>e.value)).toString();i[a]=new bh(t,e[0].type)}}else if((0,yh.isObject)(s))if(s.__VALUE__){const e=s;(0,yh.isBoolean)(e.value)&&(e.value=e.value?"true":"false"),i[a]=new bh(e.value,e.type)}else this.buildProps(s,a,i)})),i}getPiiAwareValue(t,i){return e.piiProps.hasOwnProperty(t)?new bh(i,e.piiProps[t]):i}build(){return(0,yh.flatten)([this.buildFromMediaStats(),this.buildFromLocalStats()])}};xh.agentEnvironmentId=xi(),xh.piiProps={IPAddr:13,MACAddr:13,IPAddress:13,OpaqueData:0,LocalSite:13,RemoteSite:13,BaseAddress:13,LocalAddress:13,RemoteAddress:13,NetworkName:12,LocalUser:10,TargetUser:10};var Fh=xh,Uh=g;function Bh(e){return e?Hh(e.code,e.subCode):0}function Vh(e,t){const i={clientVersion:e.clientVersion,participantId:e.participantId,endpointId:e.endpointId,endpointType:e.endpointType,endpointMetadata:e.endpointMetadata,originalId:e.originalId,capabilities:e.capabilities,clientEndpointCapabilities:e.clientEndpointCapabilities,mappedTo:e.mappedTo,meetingGroupDetails:e.meetingGroupDetails};return e.mediaStreams&&(i.mediaStreams=e.mediaStreams),e.appliedInteractivityLevel&&(i.appliedInteractivityLevel=e.appliedInteractivityLevel),e.deviceType&&(i.deviceType=e.deviceType),e.streamInformation&&32&t&&(i.streamInformation=e.streamInformation),e.propertyBag&&(i.propertyBag=e.propertyBag),i}function Hh(e,t=null){if(e===$n.Success)switch(t){case Gn.RemovedFromConversation:case Gn.RemovedFromCall:return 44;case Gn.DeniedInLobby:return 55;case Gn.TimedOutInLobby:return 56;default:return 1}if(null!==t&&t>=2e5&&t<=299999){const e=t-2e5;return zn[e]?zn[e]:0}return null!==t&&t>=4e5&&t<=499999?Wn[e]?Wn[e]:43:e===$n.Forbidden?t===Gn.UserBlocked?64:t===Gn.PolicyRestriction?62:t===Gn.AnonymousJoinDisabledByPolicy?66:t===Gn.NoLobbyForBroadcastJoin?67:t===Gn.NotAllowedDueToInformationBarrier?68:t===Gn.TeamParkPolicyDisabled?70:t===Gn.B2bJoinDisabledByPolicy?71:t===$n.Success?8:7:e===$n.PreconditionFailed&&t===Gn.InsufficientCapabilities?63:e===$n.ServiceUnavailable?t===Gn.BroadcastLimitReached?69:48:e===$n.InternalServerError?7:e===$n.ConfParticipantCountLimitReached?t===Gn.MaxLobbyParticipantLimitReached?73:59:jn[e]?jn[e]:e}function $h(e){if(1===e)return $n.Success;const t=Object.keys(jn).filter((t=>jn[t]===e));if(t.length>=1)for(const i of t){const t=parseInt(i);if(t&&jn[t]===e)return t}return $n.UnknownError}function Gh(e,t){if(void 0!==t&&3!==t&&1!==t)return{mediaType:e,isDisabled:0===t,label:Md(e)}}function jh(e){if(e.sendMediaModalities)return e;const t={mediaStates:[]};let i=Gh(0,e.audioDirection?e.audioDirection:4);return i&&t.mediaStates.push(i),i=Gh(1,e.withVideo?4:e.videoDirection),i&&t.mediaStates.push(i),i=Gh(2,e.screenshareDirection?e.screenshareDirection:1),i&&t.mediaStates.push(i),e.sendMediaModalities=t,e}function zh(e){const t=function(e){if("mri"===e)return"mri";throw"Unknown RedirectionTargetIdType"}(e.type),i=function(e){switch(e){case"voicemail":return"voicemail";case"default":return"default";default:throw"Unknown RedirectionEndpointType"}}(e.endpointType);return{type:t,id:e.id,endpointType:i}}var Wh=class{constructor(e){this.mediaStateConfiguration=e}isDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!!t&&!!t.isDisabled}return!1}isInactiveOrDisabled(e){if(this.mediaStateConfiguration?.mediaStates){const t=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));return!t||!!t.isDisabled}return!1}isSending(e){return!!this.mediaStateConfiguration?.mediaStates&&!!this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e&&!t.isDisabled))}disableModality(e){this.setModality(e,!0)}enableModality(e){this.setModality(e,!1)}removeModality(e){this.mediaStateConfiguration?.mediaStates&&(0,Uh.remove)(this.mediaStateConfiguration.mediaStates,(t=>t.mediaType===e))}setCallAcceptOptions(e){const t=this.isDisabled(1),i=this.isDisabled(2),n=this.isSending(3);if(e.sendMediaModalities)this.mediaStateConfiguration=e.sendMediaModalities;else{void 0===e.answerMediaType&&(e.answerMediaType=e.withVideo?1:0);const t={mediaStates:[]};switch(e.answerMediaType){case 0:t.mediaStates.push(Gh(0,4));break;case 1:t.mediaStates.push(Gh(0,4)),t.mediaStates.push(Gh(1,4));break;case 2:t.mediaStates.push(Gh(1,0))}this.mediaStateConfiguration=t}t&&this.setModality(1,!0),i&&this.setModality(2,!0),n&&this.setModality(3,!1),e.sendMediaModalities=this.mediaStateConfiguration}setModality(e,t){if(this.mediaStateConfiguration?.mediaStates){const i=this.mediaStateConfiguration.mediaStates.find((t=>t.mediaType===e));i?i.isDisabled=t:this.mediaStateConfiguration.mediaStates.push({mediaType:e,isDisabled:t,label:Md(e)})}}};function qh(e){return e||!1===e||""===e||0===e}function Kh(e){switch(e){case 0:return"Audio";case 1:return"Video";case 2:return"ScreenShare"}throw new Error("MediaType required")}var Jh=class{constructor(){this.stateInt=0,this.promiseInt=new Promise(((e,t)=>{this.resolveInt=e,this.rejectInt=t}))}get state(){return this.stateInt}get resolve(){return e=>{this.stateInt=2,this.resolveInt(e)}}get reject(){return e=>{this.stateInt=1,this.rejectInt(e)}}get promise(){return this.promiseInt}get isPending(){return 0===this.stateInt}},Yh=class{constructor(e){this.mcpConfig=e,this.data={sourceRequestsSignaling:{},sourceRequestsMCP:{},fallback:!1,sourceRequestsResponses:{},errors:[]}}setRecord(e,t,i){const n={sequenceNumber:t,timestamp:Date.now(),sourceId:i?.sourceId,fmtp:i?.fmtParams};e.records??(e.records=[]),Tt(e.records,n,this.mcpConfig.storedSRRecordsCount)}recordSignalingOperation(e,t){var i;(i=this.data.sourceRequestsSignaling)[e]??(i[e]={counter:0}),this.data.sourceRequestsSignaling[e].counter++,this.mcpConfig.verboseTelemetry&&this.mcpConfig.sendDuplicates&&"ApplyChannelParametersSourceRequest"===e&&this.setRecord(this.data.sourceRequestsSignaling[e],t)}recordMCPOperation(e,t,i){var n;(n=this.data.sourceRequestsMCP)[e]??(n[e]={counter:0}),this.data.sourceRequestsMCP[e].counter++,this.mcpConfig.verboseTelemetry&&this.setRecord(this.data.sourceRequestsMCP[e],t,i)}recordError(e,t){const i=[Date.now(),t,e];Tt(this.data.errors,i,this.mcpConfig.storedSRRecordsCount)}recordFallback(){this.data.fallback=!0}recordSignalingOperationDuration(e,t){const i=this.data.sourceRequestsSignaling[e]?.records?.find((e=>e.sequenceNumber===t));i&&(i.duration=Date.now()-i.timestamp)}recordSrResultReceived(e,t,i){var n;if(this.mcpConfig.verboseTelemetry){const n=this.data.sourceRequestsMCP[i]?.records?.find((e=>e.sequenceNumber===t));n&&(n.duration=Date.now()-n.timestamp,n.result=e)}(n=this.data.sourceRequestsResponses)[e]??(n[e]=0),this.data.sourceRequestsResponses[e]++}getObjectRef(){return this.data}},Qh=class{constructor(e){this.mcpConfig=e,this.storage={createTime:Date.now(),startedCount:0,stoppedCount:0,clientCapabilities:[],events:[]},this.sourceRequestSenderDiagnostics=new Yh(this.mcpConfig)}get getSourceRequestSenderDiagnostics(){return this.sourceRequestSenderDiagnostics}logStarted(){if(this.storage.startedCount++,this.storage.startedCount>5)return;const e={startedTs:Zh(this.storage.createTime),mpCapabilities:{},sentMessages:{},recvMessages:{},sentFailed:0,recvFailed:0,cachedDshReceived:!1};this.storage.events.push(e),this.lastEventConnecting=!0}logStopped(){this.storage.stoppedCount++;const e=this.getCurrentDCSessionEvent();e&&(e.stoppedTs=Zh(this.storage.createTime)),this.lastEventConnecting=!1}logSentMsg(e){var t,i;const n=this.getCurrentDCSessionEvent();n&&((t=n.sentMessages)[i=e.type]??(t[i]=0),n.sentMessages[e.type]++)}logReceivedMsg(e){var t,i;this.lastEventConnecting=!1;const n=this.getCurrentDCSessionEvent();n&&((t=n.recvMessages)[i=e.type]??(t[i]=0),n.recvMessages[e.type]++,"dsh"!==e.type||n.handshakeDuration||(n.cachedDshReceived=!0))}logHandshakeStarted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeStartedTs=Date.now()),this.storage.clientCapabilities=e}logHandshakeCompleted(e){const t=this.getCurrentDCSessionEvent();t&&(t.handshakeDuration||(t.handshakeDuration=Zh(t.handshakeStartedTs)),t.mpCapabilities.send=e.send_capabilities,t.mpCapabilities.recv=e.receive_capabilities)}logSentFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.sentFailed++,t.lastSentFailed={ts:Zh(this.storage.createTime),error:e})}logRecvFailed(e){const t=this.getCurrentDCSessionEvent();t&&(t.recvFailed++,t.lastRecvFailed={ts:Zh(this.storage.createTime),error:e})}logTimeout(){if(this.storage.startedCount>=5&&!this.lastEventConnecting)return;const e={timeoutTs:Date.now()},t=this.getCurrentDCSessionEvent();t&&(e.handshakeStartedTs=t.handshakeStartedTs),this.lastEventConnecting&&this.storage.events.pop(),this.storage.events.push(e),this.lastEventConnecting=!1}getReport(){const e=this.sourceRequestSenderDiagnostics.getObjectRef();return this.storage.sourceRequestsReport=e,this.storage}getCurrentDCSessionEvent(){const e=this.storage.events[this.storage.events.length-1];return this.storage.startedCount<=5&&void 0!==e?.startedTs?e:null}};function Zh(e){return Date.now()-e}var Xh=class extends We{constructor(e,t,i){super(),this.dcAdapter=e,this.logger=t,this.mcpConfig=i,this.dcSend=null,this.handshakePromise=new Jh,this.isStarted=!1,this.isActive=!1,this.handshakeTimeout=null,this.telemetryLogger=new Qh(this.mcpConfig),this.mcpSupportedFeautres={sourceRequestsEnabled:!1,sourceRequestsResponseEnabled:!1,sendDuplicates:this.mcpConfig?.sendDuplicates}}getTelemetryLogger(){return this.telemetryLogger}mcpFeaturesSupported(e){return this.mcpSupportedFeautres[e]}switchMcpFeauture(e,t){this.logger.warn(`Switching ${e} to ${t}`),this.mcpSupportedFeautres[e]=t}getConfig(){return this.mcpConfig}dispose(){super.dispose(),this.isStarted&&this.dcAdapter.removeHandler(18),this.handshakePromise.promise.catch((()=>{})),this.handshakePromise.reject("MediaControlPlane disposed"),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.isActive=!1,this.switchMcpFeauture("sourceRequestsEnabled",!1),this.switchMcpFeauture("sourceRequestsResponseEnabled",!1),this.dcSend=null}getTelemetryReport(){return this.logger.debug(`Telemetry ${JSON.stringify(this.telemetryLogger.getReport())}`),this.telemetryLogger.getReport()}async sendMsg(e){return await this.handshakePromise.promise,this.sendMsgInternal(e)}start(){if(this.isStarted||!this.mcpConfig)return;this.isStarted=!0;const e={onStarted:async(e,t)=>{this.logger.info(`Data channel handler is started ${e}`),this.telemetryLogger.logStarted(),this.dcSend=t,await this.startHandshake()},onStopped:async e=>{this.logger.info(`Data channel handler is stopped ${e}`),this.telemetryLogger.logStopped(),this.dcSend=null,this.isActive=!1,this.switchMcpFeauture("sourceRequestsEnabled",!1),this.switchMcpFeauture("sourceRequestsResponseEnabled",!1)},onDataReceived:async(e,t)=>{this.processIncomingData(t)}};this.dcAdapter.addHandler(18,e)}onTransportConnected(){this.isStarted&&this.mcpConfig.handshakeTimeout&&!this.isActive&&(this.handshakeTimeout&&clearTimeout(this.handshakeTimeout),this.handshakeTimeout=window.setTimeout((()=>{this.handshakeTimeout=null,this.telemetryLogger.logTimeout(),this.logger.warn(`Timeout after ${this.mcpConfig.handshakeTimeout}ms, raising onHandshakeTimeout`),this.event("onHandshakeTimeout").raise()}),this.mcpConfig.handshakeTimeout))}async startHandshake(){this.handshakePromise.isPending||(this.handshakePromise=new Jh),this.isActive=!1;try{const e=[];this.mcpConfig.enableDominantSpeakerHistory&&e.push("dsh"),this.mcpConfig.enableBweNotifications&&e.push("bwe"),this.mcpConfig.enableSourceRequests&&e.push("sr"),this.telemetryLogger.logHandshakeStarted(e),this.logger.info(`Send syn, client capabilities: ${JSON.stringify(e)}`),await this.sendMsgInternal({type:"syn",client_capabilities:e})}catch(e){this.handshakePromise.reject(e)}}async sendMsgInternal(e){const t=Array.isArray(e)?e:[e],i=(new TextEncoder).encode(JSON.stringify(t)),n=new Uint8Array(1+i.length);n[0]=1,n.set(i,1);try{await this.dcSend(n,[4294967292]);for(const e of t)this.telemetryLogger.logSentMsg(e)}catch(e){throw this.logger.error(`Send failed: ${Be(e)}`),this.telemetryLogger.logSentFailed(Be(e)),e}}processIncomingData(e){if(1!==e[0]){const t=`Unsupported header version ${e[0]}`;return this.logger.info(t),void this.telemetryLogger.logRecvFailed(t)}const t=new DataView(e.buffer,1);let i;try{const e=(new TextDecoder).decode(t);i=JSON.parse(e)}catch(e){return this.logger.error(`Failed to parse received data, error ${Be(e)}`),void this.telemetryLogger.logRecvFailed(Be(e))}for(const e of i)switch(this.telemetryLogger.logReceivedMsg(e),e.type){case"syn":break;case"ack":this.processAckMsg(e);break;case"bwe":this.processBweMsg(e);break;case"dsh":this.processDshMsg(e);break;case"sr_res":this.processSrResMsg(e);break;default:{const t=`Unsupported msg type ${e.type}`;this.logger.error(t),this.telemetryLogger.logRecvFailed(t)}}}processDshMsg(e){this.mcpConfig.enableDominantSpeakerHistory&&(this.logger.debug(`DSH received: ${JSON.stringify(e)}`),this.event("mpDshChanged").raise(e.history))}processSrResMsg(e){this.mcpConfig.enableSourceRequests&&(this.logger.debug(`SR_RES received: ${JSON.stringify(e)}`),this.event("mpSrResReceived").raise(e.sequenceNumber,e.result))}processBweMsg(e){this.mcpConfig.enableBweNotifications&&this.event("mpSendBandwidthChanged").raise(e.bw)}processAckMsg(e){this.telemetryLogger.logHandshakeCompleted(e),this.logger.info(`Ack received: ${JSON.stringify(e)}`);const t=!(!this.mcpConfig.enableDominantSpeakerHistory||!e.send_capabilities?.includes("dsh"));this.switchMcpFeauture("sourceRequestsEnabled",!(!this.mcpConfig.enableSourceRequests||!e.receive_capabilities?.includes("sr"))),this.switchMcpFeauture("sourceRequestsResponseEnabled",!(!this.mcpConfig.enableSourceRequests||!e.send_capabilities?.includes("sr_res"))),this.logger.info(`raising mpDshStatusChanged ${t}`),this.event("mpDshStatusChanged").raise(t),this.handshakePromise.resolve(),clearTimeout(this.handshakeTimeout),this.handshakeTimeout=null,this.isActive=!0}},ep="NegotiationCompleted",tp={OFFER_GENERATION_STARTED:"InitialOfferGenerationStarted",OFFER_GENERATION_ENDED:"InitialOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"InitialAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"InitialAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"InitialOfferProcessingStarted",OFFER_PROCESSING_ENDED:"InitialOfferProcessingEnded",ANSWER_GENERATION_STARTED:"InitialAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"InitialAnswerGenerationEnded"},ip={OFFER_GENERATION_STARTED:"RenegotiationOfferGenerationStarted",OFFER_GENERATION_ENDED:"RenegotiationOfferGenerationEnded",ANSWER_PROCESSING_STARTED:"RenegotiationAnswerProcessingStarted",ANSWER_PROCESSING_ENDED:"RenegotiationAnswerProcessingEnded",OFFER_PROCESSING_STARTED:"RenegotiationOfferProcessingStarted",OFFER_PROCESSING_ENDED:"RenegotiationOfferProcessingEnded",ANSWER_GENERATION_STARTED:"RenegotiationAnswerGenerationStarted",ANSWER_GENERATION_ENDED:"RenegotiationAnswerGenerationEnded"},np=class{constructor(e,t,i){this.mediaSession=e,this.signalingSession=t,this.sourceRequestSender=i,this.operationNames=tp,this.configureModalitiesAsync=this.mediaSession.configureModalitiesAsync.bind(this.mediaSession),this.getAllowedModalities=this.mediaSession.getAllowedModalities.bind(this.mediaSession),this.rejectNegotiationAsync=this.mediaSession.rejectNegotiationAsync.bind(this.mediaSession),this.createRemoteRenderer=this.mediaSession.createRemoteRenderer.bind(this.mediaSession),this.getStatsAsync=this.mediaSession.getStatsAsync.bind(this.mediaSession),this.getLastKnownStats=this.mediaSession.getLastKnownStats.bind(this.mediaSession),this.getCallTechnicalInfo=this.mediaSession.getCallTechnicalInfo.bind(this.mediaSession),this.muteHold=this.mediaSession.muteHold.bind(this.mediaSession),this.muteInputAsync=this.mediaSession.muteInputAsync.bind(this.mediaSession),this.unmuteInputAsync=this.mediaSession.unmuteInputAsync.bind(this.mediaSession),this.muteOutputAsync=this.mediaSession.muteOutputAsync.bind(this.mediaSession),this.unmuteOutputAsync=this.mediaSession.unmuteOutputAsync.bind(this.mediaSession),this.terminate=this.mediaSession.terminate.bind(this.mediaSession),this.createAudioElement=this.mediaSession.createAudioElement.bind(this.mediaSession),this.getSessionConfig=this.mediaSession.getSessionConfig.bind(this.mediaSession),this.getDiagnostics=this.mediaSession.getDiagnostics.bind(this.mediaSession),this.getIncomingRawAudioStream=this.mediaSession.getIncomingRawAudioStream.bind(this.mediaSession),this.getUnmixedAudioProvider=this.mediaSession.getUnmixedAudioProvider.bind(this.mediaSession),this.useNullAudioStreamClient=this.mediaSession.useNullAudioStreamClient.bind(this.mediaSession),this.getSubscriptionManager=this.mediaSession.getSubscriptionManager.bind(this.mediaSession),this.configureSpatialAudio=this.mediaSession.configureSpatialAudio.bind(this.mediaSession),this.setParticipantSpatialAudioPositions=this.mediaSession.setParticipantSpatialAudioPositions.bind(this.mediaSession),this.setCallConstraints=this.mediaSession.setCallConstraints.bind(this.mediaSession),this.startMediaDescriptionsUpdateAsync=this.mediaSession.startMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.completeMediaDescriptionsUpdateAsync=this.mediaSession.completeMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.rejectMediaDescriptionsUpdateAsync=this.mediaSession.rejectMediaDescriptionsUpdateAsync.bind(this.mediaSession),this.getExtensionsManager()?.configureExtension("videoStreamControl",{sender:this.sourceRequestSender})}enableTeamsRealTimeTelemetry(){this.mediaSession.enableTeamsRealTimeTelemetry()}getMediaStatsReport(){return this.mediaSession.getMediaStatsReport()}processOfferAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_STARTED),this.mediaSession.processOfferAsync(e,t).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_PROCESSING_ENDED),e)))}createAnswerAsync(e,t){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_STARTED),this.mediaSession.createAnswerAsync(e,t).then((t=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_GENERATION_ENDED),e||(this.operationNames=ip),t)))}createOfferAsync(e){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_STARTED),this.mediaSession.createOfferAsync(e).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.OFFER_GENERATION_ENDED),e)))}processAnswerAsync(e,t,i,n=!1){return this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_STARTED),this.mediaSession.processAnswerAsync(e,t,i,n).then((()=>{this.signalingSession.setOfferAnswerGenerationTimestamps(this.operationNames.ANSWER_PROCESSING_ENDED),this.operationNames=ip}))}completeNegotiationAsync(e){return this.mediaSession.completeNegotiationAsync(e).then((e=>(this.signalingSession.setOfferAnswerGenerationTimestamps(ep),e)))}sendDtmf(e){return this.mediaSession.sendDtmf?this.mediaSession.sendDtmf(e):Promise.reject("Not Implemented")}getExtensionsManager(){return this.mediaSession.getExtensionsManager?this.mediaSession.getExtensionsManager():null}reconnectAsync(e,t=!1){return this.mediaSession.reconnectAsync(e,t)}completeEscalationAsync(e){return this.mediaSession.completeEscalationAsync(e)}rejectEscalationAsync(e,t){return this.mediaSession.rejectEscalationAsync(e,t)}getAcceptedTypes(){return this.mediaSession.getAcceptedTypes()}getLocalMediaTrackId(e){return this.mediaSession.getLocalMediaTrackId?this.mediaSession.getLocalMediaTrackId(e):null}processNotification(e,t){this.mediaSession.processNotification(e,t)}};function rp(e,t,i){if(void 0===t?.serverMuteVersion||void 0===i?.serverMuteVersion||i.serverMuteVersion>=t.serverMuteVersion)return;const n=i&&i.mediaStreams,r=n&&n.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),a=t&&t.mediaStreams,s=a&&a.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));r&&r.length&&(i.serverMuteVersion=t.serverMuteVersion,r[0].serverMuted=s[0].serverMuted,e.info(`handleServerMutedVersion: patching server muted state in audio streams updated:${JSON.stringify(r[0])} as we encountered stale muteServerVersion. Updated to ${t.serverMuteVersion}`))}function ap(e,t,i,n){if("success"!==i.reason||void 0===t||i.serverMuteVersion<=t.serverMuteVersion)return e.info(`handleMuteUnmuteParticipantInfo: ignoring updating since we encountered invalid state: ${i.reason} serverMuteVersion: ${i.serverMuteVersion}`),!1;const r=t&&t.mediaStreams,a=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type));return!!a&&(a[0].serverMuted=n,t.serverMuteVersion=i.serverMuteVersion,e.info(`handleMuteUnmuteParticipantInfo: updating since we encountered valid state serverMuteVersion: ${i.serverMuteVersion} to: ${n} streams: ${a[0].sourceId}`),!0)}var sp=p;function op(e,t,i,n){i?.forEach((i=>{e[i]&&(t[i]=n(e[i]))}))}function lp(e){return`id=${sp.pii.Mri(e.id)}, participantId=${e.participantId}`}function cp(e){return function(e,t,i,n){const r=JSON.stringify(e),a=JSON.parse(r);return a&&(op(e,a,t,sp.pii.Omit),op(e,a,i,sp.pii.Mri),op(e,a,n,sp.pii.UserName)),JSON.stringify(a)}(e,[],["transferorMri","targetMri"])}var dp=g,up=i.setImmediate?e=>{i.setImmediate(e)}:e=>{(0,dp.defer)(e)},hp=class e{constructor(){this.deferredOperations=new Map,this.deferredOperationsNames=[],this.isRunning=!1}setLogger(e){this._logger=e.createChild("[DeferHandler]")}setDeferToQueueMicrotask(t){t&&i.queueMicrotask?e.defer=e=>i.queueMicrotask(e):e.defer=up}createDeferRunner(e){const t={};return i=>this.runDeferred(t,i,e)}runDeferredWithoutDedup(e,t){this.runDeferred({},e,t)}runDeferred(t,i,n){this.deferredOperations.has(t)||(this.deferredOperations.set(t,i),n&&this.deferredOperationsNames.push(" "+n),this.isRunning||(this.isRunning=!0,this._startDeferalTime=Date.now(),this.causeId=Te(),this._logger?.info(`[${this.causeId}]Deferring operations`),e.defer((()=>{this._timeToRun=Date.now()-this._startDeferalTime,this.deferredOperations.forEach((t=>{e.runWithTryCatch(t)})),this.deferredOperations.clear(),this.isRunning=!1,this._logger?.info(`[${this.causeId}]Deferred operations ran after ${this._timeToRun}ms | Completed after ${Date.now()-this._startDeferalTime}ms | Operations:${this.deferredOperationsNames}`),this.deferredOperationsNames=[]}))))}static runWithTryCatch(e){try{e&&e()}catch(e){}}};hp.defer=up;var pp=hp,gp=class{};gp.instance=new pp;var mp=g,fp="sendonly",vp="recvonly",Sp="sendrecv",yp="audio",Cp="video",_p="applicationsharing-video",Ep="audio-teleconferencing",Tp=class extends We{constructor(e,t,i){super(t),this.mediaSession=e,this.isAvailable=!1,this.mediaSessionInitPromise=new Jh,this.currentIsStreaming=!1,e&&this.mediaSessionInitPromise.resolve(),this.id=i,this.logger=t.createChild(`Stream[${this.id}]`)}set isStreaming(e){this.currentIsStreaming=e,this.logger.info(`isStreaming has changed to ${this.currentIsStreaming}`),this.raiseChanged()}get isStreaming(){return this.currentIsStreaming}update({sourceId:e=null,direction:t=vp,participantId:i=null,endpointId:n=null}={},r){this.logger.info(`[${r}][update before]  sourceId=${e}, direction=${t}, participantId=${i}, endpointId=${xe(n)}`),this.id=e,this.isAvailable=t===Sp||t===fp,this.mediaSession?.getSessionConfig().config.streamAvailabilityConsiderModalities&&this.getIsModalityDisabled()&&(this.logger.info(`Disabling current modality, disabled: ${JSON.stringify(this.mediaSession?.getDisabledModalities?.()||"")}`),this.isAvailable=!1),this.participantId=i,this.endpointId=n,this.logger.info(`[${r}][update after]  sourceId=${e}, direction=${t}, participantId=${i}, endpointId=${xe(n)}`),this.raiseChanged()}setMediaSession(e,t){const i=e?.getAllowedModalities?.()||{};this.logger.info(`[${t}][setMediaSession] ${JSON.stringify(i)}`),this.mediaSession=e,e?this.mediaSessionInitPromise.resolve():this.mediaSessionInitPromise.reject(new Error("MediaSession is null"))}isActive(){return this.isAvailable&&this.isStreaming}getIsModalityDisabled(){return!1}},bp=class extends Tp{},Ip=g,wp=class extends Tp{constructor(e,t,i,n,r,a){super(void 0,e,t),this.configProvider=i,this.streamOptions=n,this.telemetryLogger=r,this.callInfo=a,this.type=2,this.finalTelemetrySent=!1,this.player=new Ki(e.createChild("UmsHydraLiveStreamPlayer"),this.configProvider,this.telemetryLogger),this.isAvailable=!0}getStreamOptions(){return this.streamOptions}getDiagnosticData(){return JSON.stringify({id:this.id,type:this.type,rank:this.rank,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const e=this.player.getSnapshotTelemetryReport(),t={isAvailable:this.isAvailable,isStreaming:this.isStreaming,...e};return(0,Ip.isEqual)(this.lastStreamStats,t)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=t),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,rank:this.rank,...this.lastStreamStats}}stop(){return Promise.resolve(void 0)}async start(e){if(this.logger.info("[start]: Starting UMS stream"),!this.renderer){if(await this.player.configure(this.streamOptions),!(await this.player.loadPlayer(e)).setupSucceeded)return this.player.stop(),this.logger.error("[start]: Failed to load UMS player"),Promise.reject("Failed to load UMS player");this.renderer=this.player.getRenderer()}return this.isStreaming=!0,this.renderer}sendSnapshotTelemetry(){const e=this.player.getSnapshotTelemetryReport();this.logger.debug(`[sendSnapshotTelemetry] sending snapshot telemetry report: ${JSON.stringify(e)}`);const t={...this.callInfo,...e};this.telemetryLogger.sendEvent({eventName:"live_events",props:t})}sendTelemetry(e){if(this.finalTelemetrySent)return;e&&(this.finalTelemetrySent=!0);const t=this.player.getTelemetryReport();this.logger.debug(`[sendTelemetry] sending telemetry report: ${JSON.stringify(t)}`);const i={...this.callInfo,...t};this.telemetryLogger.sendEvent({eventName:"live_events",props:i})}};var Rp=class extends We{constructor(){super(...arguments),this.isRendering=!1,this.frameType=-1}get rendererType(){return 0}captureFrame(){if(this.renderer.captureFrame)return this.renderer.captureFrame();throw new Error("Not implemented yet")}async getStats(){if(this.renderer.getStats)return this.renderer.getStats();throw new Error("Renderer does not support stats")}async setScalingMode(e){this.renderer.setScalingMode(function(e){switch(e){case 1:return"crop";case 0:return"stretch";default:return"fit"}}(e))}async cameraAutoControl(e){throw new Error("Not implemented")}async getCameraManualControlStates(e){throw new Error("Not implemented")}async setCameraManualControlStates(e){throw new Error("Not implemented")}async enumerateCameraManualControls(){throw new Error("Not implemented")}onVideoSizeChanged(e,t){this.streamSize={width:e,height:t},this.event("videoSizeChanged").raise(e,t),this.raiseChanged()}},Ap=class extends Rp{constructor(e,t){super(),this.renderer=t.createPreviewRenderer(e),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t)))}onVideoSizeChanged(e,t){this.isRendering=e>0&&t>0,super.onVideoSizeChanged(e,t)}setVideoMirroring(e){this.renderer.setVideoMirroring(e)}startVideoAsync(){return this.renderer.startVideoAsync()}dispose(){this.renderer&&(this.renderer.dispose(),this.renderer=null)}},Pp=class extends Rp{constructor(e,t,i,n,r){super(),this.logger=e,this.target=t,this.rendererStats=n,this.configProvider=r,this.subscriptionActive=!1,this.firstFrameRendered=!1,this.rendererId=n.newRendererId(),this.renderer=i.createRemoteRenderer(t),this.renderer.on("onVideoSizeChanged",((e,t)=>this.onVideoSizeChanged(e,t))),this.renderer.on("onVideoStateChanged",(e=>this.onVideoStateChanged(e))),this.renderer.on("onIsRenderingChanged",(e=>this.onIsRenderingChanged(e)))}toString(){return`rvr:${this.rendererId}`}onVideoStateChanged(e){this.rendererStats.streamStateChanged(e.stream)}onVideoSizeChanged(e,t){this.configProvider.config.videoIsRenderingCheck&&this.setIsRendering(e>0&&t>0),super.onVideoSizeChanged(e,t)}setIsRendering(e){this.isRendering!==e&&(this.isRendering=e,this.logger.info(`isRendering has changed to ${this.isRendering}`),this.rendererStats.event(this.isRendering?5:6,this.rendererId),this.isRendering&&!this.firstFrameRendered&&(this.firstFrameRendered=!0,this.event("firstFrameRendered").raise()))}onIsRenderingChanged(e){this.setIsRendering(e),this.raiseChanged()}subscribeVideoAsync(e){this.currentVideoStream=e,this.rendererStats.event(1,this.rendererId,e.id);const t=this.renderer.subscribeVideoAsync(e.id,1===e.type);return this.subscriptionActive=!0,t.then((()=>{this.rendererStats.event(2,this.rendererId,e.id),this.watchStream(e)})),t}watchStream(e){this.changeSub&&this.changeSub.dispose(),this.changeSub=e.changed((()=>{e.isAvailable?this.subscriptionActive||this.subscribeVideoAsync(e):(this.subscriptionActive=!1,this.rendererStats.event(3,this.rendererId),this.renderer.unsubscribeNow(),this.rendererStats.event(4,this.rendererId))}))}dispose(){this.renderer&&(this.subscriptionActive&&(this.rendererStats.event(3,this.rendererId),this.currentVideoStream&&!this.currentVideoStream.isAvailable&&this.renderer.unsubscribeNow()),this.renderer.dispose(),this.subscriptionActive&&this.rendererStats.event(4,this.rendererId),this.renderer=null,this.currentVideoStream=null),this.changeSub&&(this.changeSub.dispose(),this.changeSub=null)}},Mp=class extends We{constructor(e,t,i,n=Te()){super(i),this.getRawStream=e,this.disposeStream=t,this.logger=i,this.causeId=n,this.isClientDisposed=!1,this.clientId=dt()}get isDisposed(){return this.isClientDisposed}notifyStreamChange(){this.logger.info(`Raw stream changed, causeId=${this.causeId}`),this.raiseChanged(),this.event("notifiedOnStreamChanged").raise(this.clientId)}async getMediaStream(){return this.checkDisposed(),this.logger.info(`Raw stream requested, causeId=${this.causeId}`),this.event("rawStreamRequested").raise(this.clientId),this.getRawStream()}dispose(){this.checkDisposed(),this.disposeStream?.(),this.isClientDisposed=!0,this.event("clientDisposed").raise(this.clientId),super.dispose(),this.logger.info(`Raw stream client disposed, causeId=${this.causeId}`)}checkDisposed(){if(this.isClientDisposed)throw new Error("Raw stream client is already disposed")}},kp=class{constructor(e,t,i){this.stream=e,this.rawBaseClient=new Mp((async()=>this.stream),(()=>this.dispose()),t,i)}client(){return this.rawBaseClient}updateAndNotifyClient(e){this.rawBaseClient&&(this.stream=e,this.rawBaseClient.notifyStreamChange())}dispose(){this.rawBaseClient=null,this.stream=null}},Dp=class{constructor(e,t,i,n){this.videoStream=e,this.subscriptionManager=t,this.logger=i,this.causeId=n,this.modality=0===e.type?Qe.MODALITY.video:Qe.MODALITY.sharing,this.subscriptionClient=t.subscribeVideo(this.modality,e.mediaSourceId),this.rawBaseClient=new Mp((async()=>this.subscriptionClient?.subscribedStream),(()=>this.unsubscribeVideo()),i,n),this.setClientSubscription(),this.videoStream.changed((()=>{this.rawBaseClient?.isDisposed||(e.isAvailable?this.updateSubscription():this.unsubscribeVideo())}))}client(){return this.rawBaseClient}updateSubscription(){this.rawBaseClient?.isDisposed?this.logger.error(`updateSubscription skipped, raw stream client disposed: stream already exists, causeId=${this.causeId}`):(this.logger.info(`update subcription: Created new subscription, causeId=${this.causeId}`),this.subscriptionClient=this.subscriptionManager.subscribeVideo(this.modality,this.videoStream.mediaSourceId),this.setClientSubscription())}unsubscribeVideo(){this.logger.info(`Disposing subcription, causeId=${this.causeId}`),this.subscriptionClient?.unsubscribe(),this.subscriptionClient?.dispose(),this.subscriptionClient=null}setClientSubscription(){this.logger.info(`setting onMediaStreamChanged callback, causeId=${this.causeId}`),this.subscriptionClient.setOnMediaStreamChangedHandler((()=>this.rawBaseClient?.notifyStreamChange()))}},Op=class{constructor(){this.handlerMap=new Map}dispose(){this.handlerMap.forEach((e=>e.client().dispose())),this.handlerMap.clear()}handlerAdded(e){const t=e.client();t.on("clientDisposed",(()=>this.deleteRawStreamManagerById(t.clientId))),this.handlerMap.set(t.clientId,e)}deleteRawStreamManagerById(e){this.handlerMap.delete(e)}},Np=class extends Op{constructor(e){super(),this.logger=e}streamChanged(e){this.handlerMap.forEach((t=>t.updateAndNotifyClient(e)))}createIRawStreamClient(e){const t=new kp(e,this.logger);return super.handlerAdded(t),t.client()}updateHandlers(e){e.forEach(((e,t)=>{this.handlerMap.has(t)||this.handlerMap.set(t,e)}))}},Lp=class extends Op{constructor(e){super(),this.logger=e}createIRawStreamClient(e,t){const i=new Dp(e,t,this.logger);return super.handlerAdded(i),i.client()}},xp=g,Fp=class extends Tp{constructor(e,t,i,n){super(e,i,n),this.rendererStats=t,this.rawIncomingVideoStreamManager=new Lp(this.logger.createChild("rawVideoStream")),this.type=0}get mediaSourceId(){return this.id}getDiagnosticData(){return JSON.stringify({id:this.id,msi:this.mediaSourceId,rank:this.rank,type:this.type,isAvailable:this.isAvailable,isStreaming:this.isStreaming})}getStats(){const e={isAvailable:this.isAvailable,isStreaming:this.isStreaming};return(0,xp.isEqual)(this.lastStreamStats,e)||(this.streamStatsUpdatedTimestamp=Date.now(),this.lastStreamStats=e),{id:this.id,type:this.type,timestampUpdated:this.streamStatsUpdatedTimestamp,msi:this.mediaSourceId,rank:this.rank,...this.lastStreamStats}}stop(){return this.mediaSessionInitPromise.reject(new Error("Video stream stopped")),Promise.resolve(void 0)}getRawStream(e){return this.logger.info(`[${e}] - IRawStream for incoming video stream requested`),this.rawIncomingVideoStreamManager.createIRawStreamClient(this,this.mediaSession.getSubscriptionManager())}start(e,t){return this.logger.info(`video start: target=${e}, options=${JSON.stringify(t)}`),this.mediaSessionInitPromise.promise.then((()=>new Pp(this.logger.createChild("RemoteVideoRenderer"),e,this.mediaSession,this.rendererStats,this.mediaSession?.getSessionConfig()))).then((e=>(t&&e.setScalingMode(t.scalingMode),this.logger.info(`subscribeVideoAsync: videoRenderer=${e}, id=${this.id}`),e.subscribeVideoAsync(this).catch((t=>{throw e.dispose(),t})).then((()=>(this.isStreaming=!0,e))))))}update(e,t){this.logger.info(`[${t}][update] stream=${JSON.stringify(e)}`);const i=this.isAvailable;super.update(e,t),this.isAvailable&&this.isAvailable!==i&&this.rendererStats.event(0)}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().video}},Up=class extends Fp{constructor(e,t,i,n){super(e,t,i,n),this.type=1}getIsModalityDisabled(){return!!this.mediaSession?.getDisabledModalities?.().sharing}},Bp=class e extends We{constructor(e,t,i,n){super(),this.participantId=e,this.mediaSession=t,this.localStats=i,this.audioSourceIds=[],this.streams={},this.lastUmsStreamId=1;const r=i.receive(1,e),a=i.receive(2,e);this.audio=new bp(t,n,1);const s=new Fp(t,r,n,2),o=new Up(t,a,n,3),l=this.mediaSession?.getSessionConfig()?.config.participantStreamInitialSubscriptions;l&&(s.changed((()=>this.event("streamChanged").raise())),o.changed((()=>this.event("streamChanged").raise()))),this.streams[0]=[s],this.streams[1]=[o],this.streams[2]=[],this.logger=n.createChild("PluginlessCallStreamManager")}setMediaSession(e,t){this.logger.info(`[${t}][setMediaSession]`),this.mediaSession=e,[[this.audio],this.streams[0],this.streams[1]].forEach((i=>i.forEach((i=>i.setMediaSession(e,t)))))}updateStreams(t,i){this.logger.info(`[${i}][updateStreams]`);const n=i=>t.filter((e=>e.type===i)).sort(e.compareStreams);let r=n(yp);0===r.length&&(r=n(Ep)),r.length>0&&(this.audioSourceIds=r.map((e=>e.sourceId)));const a=r[0];a&&this.audio.update(a,i),this.updateMediaStreams(n(Cp),0,i),this.updateMediaStreams(n(_p),1,i)}hasAudioSource(e){return this.audioSourceIds.some((t=>t===e))||this.audio.id===e}useUmsStream(t,i,n,r,a,s){this.logger.info(`[${s}][useUmsStream] Updating ums streams`);const o=this.getUmsInformation(t,r),l=this.streams[2],c=l.filter((t=>!o.some((i=>e.compareUmsStreams(t,i)))));c.forEach((e=>(0,mp.remove)(l,e))),c.length&&this.logger.info(`[${s}][useUmsStream] Removing ${c.length} ums streams`),o.forEach((t=>{let r=l.find((i=>e.compareUmsStreams(i,t)));r||(r=new wp(this.logger.createChild("UmsStream"),this.lastUmsStreamId++,i,t,a,n),this.logger.info(`[${s}][useUmsStream] Adding ums stream with metadata: ${JSON.stringify(t)}`),l.push(r))}))}getUmsStreamMetadata(e,t){let i=null,n=null;if(i=e.find((function(e){return"MiddleLaneUltraLowLatency"===e.deliveryPipelineType&&t===e.isPrimary})),i){const e=i.urls;if(e&&e.length>0){i.identifier||this.logger.warn(`[getUmsStreamMetadata]: no ums stream identifier found, isPrimary: ${t}`);const r=i.decryptionKey?.id,a=i.decryptionKey?.value;r&&a||this.logger.warn(`[getUmsStreamMetadata]: no valid ums stream decryption key found, isPrimary: ${t}`);const s=i.deliveryPipelineType||void 0;n={url:e[0],streamDeliveryPipeline:s,decryptionKey:r&&a?{id:r,value:a}:null}}else this.logger.info(`[getUmsStreamMetadata]: no ums URLs found, isPrimary: ${t}`)}else this.logger.info(`[getUmsStreamMetadata]: no ums stream information found, isPrimary: ${t}`);return n}getUmsInformation(e,t){const i=[];let n=null,r=null;for(const t in e){const i=e[t].streams;if(i){if(n)this.logger.info(`[getUmsInformation]: primary ums stream already found, skipping finding primary stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!0);e?n=e:this.logger.info(`[getUmsInformation]: no primary ums stream found for participant: ${t}`)}if(r)this.logger.info(`[getUmsInformation]: alternate ums stream already found, skipping finding alternate stream for participant: ${t}`);else{const e=this.getUmsStreamMetadata(i,!1);e?r=e:this.logger.info(`[getUmsInformation]: no alternate ums stream found for participant: ${t}`)}}else this.logger.warn(`[getUmsInformation]: no stream information found for participant: ${t}`)}return(n||r)&&i.push({stream:n,altStream:r,threadId:t}),i}static compareStreams(e,t){const i="sendonly"===e.direction||"sendrecv"===e.direction,n="sendonly"===t.direction||"sendrecv"===t.direction;return i&&!n?-1:n&&!i?1:t.sourceId-e.sourceId}static compareUmsStreams(t,i){const n=t.getStreamOptions();return e.compareUmsStreamMetadata(n.stream,i.stream)&&e.compareUmsStreamMetadata(n.altStream,i.altStream)}static compareUmsStreamMetadata(e,t){return!e&&!t||!(!e&&t||e&&!t)&&e.decryptionKey.id===t.decryptionKey.id&&e.decryptionKey.value===t.decryptionKey.value&&e.url===t.url}updateMediaStreams(e,t,i){const n=this.streams[t],r=n.filter((t=>!e.some((e=>e.sourceId===t.id))));r.forEach((e=>(0,mp.remove)(n,e))),r.length&&this.logger.info(`[${i}][updateMediaStreams] Removing ${r.length} streams of type ${t}`),e.forEach(((r,a)=>{let s=n.find((e=>e.id===r.sourceId));s||(0===t?s=new Fp(this.mediaSession,this.localStats.receive(1,this.participantId),this.logger,r.sourceId):1===t&&(s=new Up(this.mediaSession,this.localStats.receive(2,this.participantId),this.logger,r.sourceId)),this.logger.info(`[${i}][updateMediaStreams] Adding stream ${r.sourceId} of type ${t}`),n.push(s),s.changed((()=>this.event("streamChanged").raise()))),s.update(r,i),s.rank=e.length-a}))}},Vp={0:[1],1:[2,6,3,4,5,7,8],2:[6,3,4,8],3:[1,4,5,8],7:[3,4,8],4:[],5:[3,4,8],6:[3,4],8:[3,5,4]},Hp={0:"Disconnected",1:"Connecting",2:"Ringing",3:"Connected",5:"Connected",4:"Disconnected",7:"Connecting"},$p=class extends We{constructor(e,t,i,n,r,a=Te(),s=[]){super(i),this.mri=e,this.callTelemetry=r,this.cachedMediaStreams=s,this.state=0,this.voiceLevel=0,this.isServerMuted=!1,this.endpointType="default",this.balanceUpdates={},this._raiseChangeDeferRunner=gp.instance.createDeferRunner("CallParticipant.RaiseChange"),this.filteredParticipantEndpointDetails={},this.recordTelemetryForStateChange=(e,t,i,n)=>{if(n){const n="_SetParticipantStateInvalid",r={state:t,reason:i,endpoints:[]};this.endpoints?.endpointDetails?.length&&(r.endpoints=gn(this.endpoints.endpointDetails)),this.callTelemetry.recordEvent(n,r,e)}},this.checkIfIncomingServerMutedIsUpdated=e=>{e.endpointDetails.forEach((e=>{const t=this.filteredParticipantEndpointDetails[e.participantId];void 0!==t&&rp(this.logger,t,e)}))},this.handleServerMutedInfoUpdate=e=>{let t=!1;for(const i of e){const e=this.filteredParticipantEndpointDetails[i.participantId];ap(this.logger,e,i,!0)&&(t=!0)}t&&this.updateIsServerMuted()},this.id=this.mri,this.logger=i.createChild((()=>`ICallParticipant[${Ae(this.id)}][${this.state}]`)),this.logger.info(`[${a}]created`),this.streamManager=new Bp(this.id,t,n,this.logger),this.streamManager.on("streamChanged",(()=>this.raiseChanged()))}get audio(){return this.streamManager.audio}get streams(){return this.streamManager.streams}getDiagnosticData(){return JSON.stringify({id:Ae(this.id),state:this.state,isServerMuted:this.isServerMuted})}isSameParticipantsMri(e){return this.id===e}setMediaSession(e,t=Te()){this.streamManager.setMediaSession(e,t)}applyCachedMediaStreams(e=Te()){const t=this.logger.createFnLogger("applyCachedMediaStreams",e);this.cachedMediaStreams?.length?(t.info("applying cachedMediaStreams"),this.updateStreams(this.cachedMediaStreams,e,!1)):t.info("cachedMediaStreams is empty")}updateStreams(e,t=Te(),i=!1){this.logger.createFnLogger("updateStreams",t).info(`isStreamingMode=${i} mediaStreams=${Le(e)}`),e?.length&&(this.cachedMediaStreams=e),i||(this.streamManager.updateStreams(e,t),this.raiseChangedDeferred())}hasAudioSource(e){return this.streamManager.hasAudioSource(e)}raiseChangedDeferred(){this._raiseChangeDeferRunner((()=>this.raiseChanged()))}updateIsServerMuted(){if(!Object.values(this.filteredParticipantEndpointDetails).length)return void this._updateIsServerMuted(!1);let e=!1;Object.values(this.filteredParticipantEndpointDetails).forEach((t=>{const i=e=>t.mediaStreams?.filter((t=>t.type===e)).sort(Bp.compareStreams);let n=i(yp)?.[0];n||(n=i(Ep)?.[0]);const r=!!n?.serverMuted,a=t.endpointState?.state;!1!==r||0!=!!a?.isMuted||(e=!0)}));const t=!e;this._updateIsServerMuted(t)}_updateIsServerMuted(e){e!==this.isServerMuted&&(this.isServerMuted=e,this.logger.info(`_updateIsServerMuted updating to: ${this.isServerMuted}`),this.raiseChanged())}updateVoiceLevel(e){this.voiceLevel!==e&&(this.voiceLevel=e,this.raiseChanged())}setState(e,t,i){if(this.state===e)return;const n=this.logger.createFnLogger("setState",i);if(3===this.state&&6===e)return void n.info("Ignore Connected->EarlyMedia transition, it is a race between media and signaling");const r=Vp[this.state].indexOf(e)>=0;this.recordTelemetryForStateChange(i,e,t,!r),r?(n.info(`state=${this.state}->${e} reason=${this.stateReason}->${t}`),this.state=e,this.stateReason=t,this.raiseChangedDeferred()):n.logFailure(`Invalid state transition ${this.state}->${e} attempted`)}processParticipantDetails(e,t,i){const n=this.logger.createFnLogger("processParticipantDetails","");this.role=e.role,this.meetingRole=e.meetingRole,this.advancedMeetingRole=e.advancedMeetingRole,this.participantType=e.participantType,this.tenantId=e.tenantId,this.propertyBag=e.propertyBag,this.version=e.version,this.isIdentityMasked=!!e.isIdentityMasked,this.nonMaskedId=e.nonMaskedId,this.nonMaskedDisplayName=e.nonMaskedDisplayName,this.nonMaskedObjectId=e.nonMaskedObjectId,this.maskedIdSeqNumber=e.maskedIdSeqNumber,this.maskedId=e.maskedId,this.joinAsStreamingUser=e.joinAsStreamingUser,e.endpointDetails?.length&&(this.endpoints={endpointDetails:[]},this.participantCapabilities={canConference:!1,canShareScreen:!1,canMerge:!0},this.checkIfIncomingServerMutedIsUpdated(e),this.filteredParticipantEndpointDetails={},e.endpointDetails.forEach((e=>{const n=Vh(e,t);if(this.endpoints.endpointDetails.push(n),!n.mappedTo){if(this.filteredParticipantEndpointDetails[e.participantId]={endpointId:e.endpointId,serverMuteVersion:e.serverMuteVersion,endpointState:e.endpointState,mediaStreams:e.mediaStreams},e.capabilities&&(this.participantCapabilities.canConference||"enabled"!==e.capabilities.cloudAudioVideoConference||(this.participantCapabilities.canConference=!0),this.participantCapabilities.canShareScreen||"enabled"!==e.capabilities.cloudScreenSharing||(this.participantCapabilities.canShareScreen=!0),this.participantCapabilities.canMerge||"enabled"!==e.capabilities.cloudMerge||(this.participantCapabilities.canMerge=!0)),this.contentSharingRole=0,e.contentSharing&&e.contentSharing.sessionInformation){const t=e.contentSharing.sessionInformation;"attendee"===t.role?this.contentSharingRole=1:"presenter"===t.role&&(this.contentSharingRole=2)}n.streamInformation&&i&&i()}})),this.updateIsServerMuted(),n.info(`endpointDetails=${JSON.stringify(this.endpoints)}`),this.raiseChangedDeferred())}toCafeParticipant(){return{audioState:Hp[this.state],mri:this.mri}}getSourceIdForMediaType(e){const t=Ld(this,e);return-1===t&&this.logger.warn("getSourceIdForMediaType failed"),t}useUmsStream(e,t,i,n,r,a){this.streamManager.useUmsStream(e,t,i,n,r,a),this.raiseChangedDeferred()}hasSourceId(e,t){return void 0!==xd(this,e,t)}},Gp=class extends We{constructor(e,t,i,n,r,a="",s,o){super(),this.callTelemetry=e,this.signalingSession=i,this.contentSharingGuid=n,this.contentSharingIdentity=r,this.state=a,this.subject=s,this.handleOperationFailure=(e,t,i)=>{i.logFailure(e);const n=this.getTerminatedReasonFromError(e);return t.updateStatusTo&&(this.contentSharingStatus=t.updateStatusTo,this.rejectContentSharing(n)),Promise.reject(n)},this._logger=t.createChild((()=>`[ContentSharingSession][${this.contentSharingGuid}]`)),this.contentSharingStatus=0,this.contentSharingTerminationReason=null,this.contentSharingState=a,this._callOperationHandler=new Hn(this._logger,this.callTelemetry),o&&(this.sessionId=o)}get contentSharingStatus(){return this.status}set contentSharingStatus(e){if(this._logger.info(`[set contentSharingStatus][currentStatus=${this.status}][newStatus=${e}]`),this.callTelemetry.recordEvent("_SetContentSharingStatus",{newStatus:e,oldStatus:this.status}),this.status!==e&&7!==this.status&&8!==this.status){if(this._logger.info(`[set contentSharingStatus] Changing content sharing status to: ${e}`),this.status=e,7===this.status){const e={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[set contentSharingStatus] Content sharing is disconnected"};this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(e)}if(2===this.status||5===this.status){const e={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Content sharing cannot be ended when not presenting"};this._callOperationHandler.maybeRejectOperation("StopContentSharing",e)}3===this.status&&(this._callOperationHandler.maybeResolveOperation("StartContentSharing"),this._callOperationHandler.maybeResolveOperation("TakeContentSharingControl")),this.raiseChanged()}}get contentSharingState(){return this.state}set contentSharingState(e){this.state!==e&&(this.state=e,this.raiseChanged())}startContentSharing(e=Te()){const t=this._logger.createFnLogger("StartContentSharing",e);if(0!==this.contentSharingStatus){const i=`[${e}][startContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.startContentSharingAsync(this.contentSharingIdentity,this.contentSharingState,this.subject,this.contentSharingGuid,e).then((e=>{this.sessionId=e.sessionId,this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StartContentSharing",updateStatusTo:8},t))),this._callOperationHandler.waitForOperation("StartContentSharing")}joinContentSharing(e=Te()){const t=this._logger.createFnLogger("JoinContentSharing",e);if(2!==this.contentSharingStatus){const i=`[${e}][joinContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.joinContentSharingAsync(this.contentSharingGuid,e).then((e=>(this.contentSharingStatus=4,this.contentSharingState=e.sessionState,this.presenterId=e.presenter,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"JoinContentSharing",updateStatusTo:8},t)))}updateContentSharingSessionState(e,t,i=Te()){const n=this._logger.createFnLogger("UpdateContentSharingSessionState",i);if(3!==this.contentSharingStatus){const e=`[${i}][updateContentSharingSessionState][failed][reason=InvalidState]`,t={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:e};return n.logFailure(`state=${this.contentSharingStatus}, reason=${e}`),Promise.reject(t)}return this.signalingSession.updateContentSharingSessionStateAsync(this.contentSharingGuid,t,i).then((()=>Promise.resolve())).catch((t=>this.handleOperationFailure(t,{causeId:i,operation:"UpdateContentSharingSessionState",operationId:e},n)))}takeContentSharingControl(e=Te()){const t=this._logger.createFnLogger("TakeContentSharingControl",e);if(5!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.takeContentSharingControlAsync(this.contentSharingGuid,e).then((()=>{this.contentSharingStatus=3,this.presenterId=this.signalingSession.participantManager.localParticipant.id})).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"TakeContentSharingControl"},t))),this._callOperationHandler.waitForOperation("TakeContentSharingControl")}updateContentSharingParticipantStateToViewer(e=Te()){const t=this._logger.createFnLogger("UpdateParticipantState",e);if(4!==this.contentSharingStatus){const i=`[${e}][updateContentSharingSessionState][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.updateContentSharingParticipantStateAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=this.presenterId===this.signalingSession.participantManager.localParticipant.id?3:5,Promise.resolve()))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"UpdateParticipantState"},t)))}stopContentSharing(e=Te()){const t=this._logger.createFnLogger("StopContentSharing",e);if(2===this.contentSharingStatus||4===this.contentSharingStatus||5===this.contentSharingStatus){const i=`[${e}][stopContentSharing][failed][reason=InvalidState]`,n={terminatedReason:60,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:i};return t.logFailure(`state=${this.contentSharingStatus}, reason=${i}`),Promise.reject(n)}return this.signalingSession.deleteContentSharingAsync(this.contentSharingGuid,e).then((()=>(this.contentSharingStatus=7,this._callOperationHandler.waitForOperation("StopContentSharing")))).catch((i=>this.handleOperationFailure(i,{causeId:e,operation:"StopContentSharing"},t)))}dispose(e=Te()){this._callOperationHandler.rejectPendingOperations({terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"Call ended"},e),this.contentSharingStatus=7,this.contentSharingState="",super.dispose()}rejectContentSharing(e={terminatedReason:12,terminatedReasonCode:0,terminatedReasonSubCode:0,errorMessage:"[rejectContentSharing] Content sharing is disconnected"}){if(7!==this.status&&8!==this.status)throw new Error(`Tried to reject content sharing with status=${this.status}`);this._callOperationHandler.maybeResolveOperation("StopContentSharing"),this._callOperationHandler.rejectPendingOperations(e)}getTerminatedReasonFromError(e){const t=e?.endCode?.code||0,i={terminatedReason:32,terminatedReasonCode:t,terminatedReasonSubCode:e?.endCode?.subCode||0,errorMessage:e};switch(t){case $n.NotFound:i.terminatedReason=34,i.errorMessage="Active session not found on server";break;case $n.Forbidden:i.terminatedReason=8,i.errorMessage="Failed due to insufficient permissions"}return i}};v([wn("StartContentSharing"),S(0,Pn)],Gp.prototype,"startContentSharing",1),v([wn("JoinContentSharing"),S(0,Pn)],Gp.prototype,"joinContentSharing",1),v([wn("UpdateContentSharingSessionState"),S(0,An),S(2,Pn)],Gp.prototype,"updateContentSharingSessionState",1),v([wn("TakeContentSharingControl"),S(0,Pn)],Gp.prototype,"takeContentSharingControl",1),v([wn("UpdateParticipantState"),S(0,Pn)],Gp.prototype,"updateContentSharingParticipantStateToViewer",1),v([wn("StopContentSharing",{waitFor:"StartContentSharing"}),S(0,Pn)],Gp.prototype,"stopContentSharing",1);var jp,zp=class{constructor(){this.messageCounters=new Map}recordDataChannelProtocolEvent(e){this.messageCounters.has(e.dataId)||this.messageCounters.set(e.dataId,{});const t=this.messageCounters.get(e.dataId);switch(t[e.direction]||(t[e.direction]={successful:0,failed:0,fragmented:0,dismissed:0}),e.state){case 0:t[e.direction].successful++;break;case 1:t[e.direction].failed++;break;case 2:t[e.direction].fragmented++;break;case 3:t[e.direction].dismissed++}}setSessionDataChannelState(e){this.sessionState=e.toString()}recordDataChannelError(e){this.dataChannelError=e}get protocolCounters(){if(!this.messageCounters.size)return;const e={};for(const t of this.messageCounters.keys())e[t]=this.messageCounters.get(t);return e}getReport(e){const t={};return t[e+"ProtocolCounters"]=JSON.stringify(this.protocolCounters),t[e+"SessionState"]=this.sessionState,t[e+"Error"]=this.dataChannelError,t}},Wp=class{constructor(e){this.value=e,this.next=void 0}},qp=class{constructor(){this.length=0}enqueue(e){const t=new Wp(e);this.front?(this.rear.next=t,this.rear=t):(this.front=t,this.rear=t),this.length++}dequeue(){if(!this.front)return;const e=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,e.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}},Kp=g,Jp=class{constructor(e){this.comparator=e,this.heap=[]}enqueue(e){this.heap.push(e),this.bubbleUp()}dequeue(){const e=this.peek();if(void 0!==e){const e=this.heap.pop();this.size()>0&&(this.heap[0]=e,this.bubbleDown())}return e}peek(){return this.heap[0]}size(){return this.heap.length}bubbleUp(){let e=this.size()-1,t=this.getParentIndex(e);for(;!this.isRoot(e)&&this.comparator(this.heap[e],this.heap[t]);)[this.heap[t],this.heap[e]]=[this.heap[e],this.heap[t]],e=t,t=this.getParentIndex(e)}bubbleDown(){if(this.size()<=1)return;let e=this.getRootIndex(),t=this.getLeftIndex(e),i=this.getRightIndex(e);for(;this.heap[t]&&this.comparator(this.heap[t],this.heap[e])||this.heap[i]&&this.comparator(this.heap[i],this.heap[e]);)!this.heap[i]||this.comparator(this.heap[t],this.heap[i])?([this.heap[e],this.heap[t]]=[this.heap[t],this.heap[e]],e=t):([this.heap[e],this.heap[i]]=[this.heap[i],this.heap[e]],e=i),t=this.getLeftIndex(e),i=this.getRightIndex(e)}getRootIndex(){return 0}isRoot(e){return 0===e}getLeftIndex(e){return 2*e+1}getRightIndex(e){return 2*e+2}getParentIndex(e){return Math.floor((e-1)/2)}},Yp=class{constructor(e,t,i){this.maxPacketRate=t,this.rateLimiterCheckInterval=i,this.maxDataRate=0,this.packetsEndTimeForPacketRate=0,this.packetsEndTimeForBitrate=0,this.maxDataRate=e/8}canSend(e){if(0===this.maxDataRate&&0===this.maxPacketRate)return!0;const t=Pt();if(this.maxPacketRate&&this.packetsEndTimeForPacketRate>t+this.rateLimiterCheckInterval)return!1;if(this.maxDataRate&&this.packetsEndTimeForBitrate>t+this.rateLimiterCheckInterval)return!1;const i=this.maxPacketRate?1e3/this.maxPacketRate:0,n=this.maxDataRate?e.length/this.maxDataRate*1e3:0;return this.packetsEndTimeForPacketRate=Math.max(this.packetsEndTimeForPacketRate,t)+i,this.packetsEndTimeForBitrate=Math.max(this.packetsEndTimeForBitrate,t)+n,!0}},Qp=class{constructor(e){this.dataIds=new Map,this.maxBitrate=e.config.webrtcDataChannel.maxBitrate,this.maxPacketRate=e.config.webrtcDataChannel.maxPacketRate,this.maxQueueSize=e.config.webrtcDataChannel.maxQueueSize,e.config.webrtcDataChannel.dataIds.forEach((e=>{this.dataIds.set(e.dataId,e)}))}getMaxBitrate(e){return this.dataIds.get(e)?.maxBitrate??this.maxBitrate}getMaxPacketRate(e){return this.dataIds.get(e)?.maxPacketRate??this.maxPacketRate}getMaxQueueSize(e){return this.dataIds.get(e)?.maxQueueSize??this.maxQueueSize}getConfig(e){const t=this.dataIds.get(e)||{dataId:e};return t.maxBitrate=t.maxBitrate??this.maxBitrate,t.maxPacketRate=t.maxPacketRate??this.maxPacketRate,t.maxQueueSize=t.maxQueueSize??this.maxQueueSize,t.priorityWeight=t.priorityWeight??1,t}},Zp=class{constructor(e,t,i){this.dataIdConfig=t,this.rateLimiterCheckInterval=i,this.timeOffset=0,this.packets=new qp,this.startTime=e(),this.finishTime=this.startTime,this.rateLimiter=new Yp(t.maxBitrate,t.maxPacketRate,this.rateLimiterCheckInterval),this.getCurrentTime=e,this.stats={bufferSize:t.maxQueueSize,remainingBytes:0,remainingPackets:0}}enqueue(e){if(0===e.length)return 0;const t=(0,Kp.sumBy)(e,(e=>e.length)),i=this.dataIdConfig.maxQueueSize;if(i&&this.stats.remainingBytes+t>i)throw new Error(`dataId ${this.dataIdConfig.dataId} send queue is full`);const n=this.getCurrentTime();let r=0;return 0===this.packets.size()?(this.startTime=n,this.finishTime=n,this.timeOffset=0,r=n):r=this.finishTime,e.forEach((e=>{r+=e.length*this.dataIdConfig.priorityWeight,this.packets.enqueue({finishTime:r,packet:e}),this.stats.remainingBytes+=e.length,this.stats.remainingPackets++})),this.finishTime=r,t}dequeue(){const e=this.peek();if(void 0!==e){if(!this.rateLimiter.canSend(e.packet))return;this.packets.dequeue(),this.stats.remainingBytes-=e.packet.length,this.stats.remainingPackets--}return e}updateTimeOffset(){this.packets.size()?this.timeOffset=this.getCurrentTime()-this.startTime:(this.startTime=this.getCurrentTime(),this.finishTime=this.startTime,this.timeOffset=0)}peek(){if(0===this.packets.size())return;const e=this.packets.peek();return{finishTime:e.finishTime+this.timeOffset,packet:e.packet}}getConfig(){return this.dataIdConfig}getStats(){return(0,Kp.clone)(this.stats)}},Xp=class{constructor(e){this.senders=new Map,this.currentVirtualClock=0,this.dataIdConfigManager=new Qp(e),this.virtualTimeQueue=new Jp(((e,t)=>e.minTime<t.minTime)),this.sendStats={bufferSize:0,remainingBytes:0,remainingPackets:0},this.rateLimiterCheckInterval=e.config.webrtcDataChannel.rateLimiterCheckInterval}getPacketsToSend(e){if(0===this.virtualTimeQueue.size())return[];const t=[],i=[];for(;e>=0&&this.virtualTimeQueue.size();){const n=this.virtualTimeQueue.peek();if(n.size>e)break;this.virtualTimeQueue.dequeue();const r=n.dataId,a=this.senders.get(r);if(void 0!==a.peek()){const n=a.dequeue();if(void 0!==n){t.push(n.packet),this.sendStats.remainingBytes-=n.packet.length,e-=n.packet.length,this.sendStats.remainingPackets--,this.currentVirtualClock=Math.max(this.currentVirtualClock,n.finishTime);const i=a.peek();i&&this.virtualTimeQueue.enqueue({dataId:r,minTime:i.finishTime,size:i.packet.length})}else i.push(r)}}return i.forEach((e=>{const t=this.senders.get(e);t.updateTimeOffset();const i=t.peek();i&&this.virtualTimeQueue.enqueue({dataId:e,minTime:i.finishTime,size:i.packet.length})})),t}appendPackets(e,t){let i=this.senders.get(e);void 0===i&&(i=new Zp((()=>this.currentVirtualClock),this.dataIdConfigManager.getConfig(e),this.rateLimiterCheckInterval),this.senders.set(e,i));const n=i.getStats(),r=i.enqueue(t);if(this.sendStats.remainingBytes+=r,this.sendStats.remainingPackets+=t.length,0===n.remainingPackets){const t=i.peek();void 0!==t&&this.virtualTimeQueue.enqueue({dataId:e,minTime:t.finishTime,size:t.packet.length})}}getStats(e){if(void 0===e)return(0,Kp.clone)(this.sendStats);const t=this.senders.get(e);return void 0===t?{bufferSize:this.dataIdConfigManager.getMaxQueueSize(e),remainingBytes:0,remainingPackets:0}:t.getStats()}},eg=class{constructor(e,t,i){this.dataId=e,this.statsGatherer=t,this.logger=i,this.pendingFragments=[]}depacketize(e){const t=new DataView(e.buffer),i=63&t.getUint8(2);if(i!==this.dataId)throw new Error(`Invalid packet dataId: ${this.dataId} !== ${i}`);const n=((15&t.getUint8(0))<<8)+t.getUint8(1),r=128&t.getUint8(2),a=t.getUint16(3),s=t.getUint8(5),o=t.getUint32(6),l=t.getUint8(10);if(r){this.pendingFragments.length&&this.logger.warn(`Unfinished message: dataId: ${this.dataId} seqNum: ${a}`),this.remainingPackets=s,0!==s&&this.statsGatherer.recordDataChannelProtocolEvent({direction:"recv",state:2,dataId:i}),this.pendingFragments=[],this.sourceId=o,this.recipients=[];for(let e=0;e<l;e++){const i=t.getUint32(11+4*e);this.recipients.push(i)}}else{if(0===this.pendingFragments.length)return this.logger.safe.error(`No start flag dataId: ${this.dataId} seqNum: ${a}`),this.statsGatherer.recordDataChannelProtocolEvent({direction:"recv",state:3,dataId:i}),null;if(this.nextSeqNum!==a)return this.logger.safe.error(`Invalid sequence number: dataId: ${this.dataId} seqNum: ${a}`),this.statsGatherer.recordDataChannelProtocolEvent({direction:"recv",state:3,dataId:i}),null;this.remainingPackets-=1}if(this.nextSeqNum=a+1&65535,this.pendingFragments.push(e.slice(n)),0===this.remainingPackets){const e=this.pendingFragments.reduce(((e,t)=>e+t.length),0),t=new Uint8Array(e);let i=0;for(const e of this.pendingFragments)t.set(e,i),i+=e.length;return this.pendingFragments=[],{dataId:this.dataId,sourceId:this.sourceId,data:t,recipients:this.recipients}}return null}},tg=class{constructor(e){this.seqNum=0,this.dataId=e}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=new Uint8Array(e.data.length+t),n=new DataView(i.buffer);n.setUint8(0,16+(t>>8)),n.setUint8(1,255&t),n.setUint8(2,128|63&e.dataId),n.setUint16(3,this.seqNum),n.setUint8(5,0),n.setUint32(6,e.sourceId),n.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)n.setUint32(11+4*t,e.recipients[t]);return i.set(e.data,t),this.seqNum+=1,[i]}},ig=class{constructor(e,t,i){this.statsGatherer=i,this.seqNum=0,this.dataId=e,this.fragmentationSize=t}packetize(e){if(e.dataId!==this.dataId)throw new Error(`Invalid dataId: ${this.dataId} !== ${e.dataId}`);const t=11+4*e.recipients.length,i=[],n=this.fragmentationSize-t;if(n<0)throw new Error(`message dataId: ${this.dataId} payload size: ${t} exceeds limit`);let r=e.data.length?Math.ceil(e.data.length/n):1;const a=r-1;a>0&&this.statsGatherer.recordDataChannelProtocolEvent({direction:"send",state:2,dataId:this.dataId});let s=e.data.length,o=!0,l=0;for(;r>0;){const c=Math.min(s,n),d=new Uint8Array(c+t),u=new DataView(d.buffer);u.setUint8(0,16+(t>>8)),u.setUint8(1,255&t),o?(o=!1,u.setUint8(2,128|63&e.dataId)):u.setUint8(2,63&e.dataId),u.setUint16(3,this.seqNum),u.setUint8(5,a),u.setUint32(6,e.sourceId),u.setUint8(10,e.recipients.length);for(let t=0;t<e.recipients.length;t++)u.setUint32(11+4*t,e.recipients[t]);d.set(e.data.slice(l,l+c),t),l+=c,i.push(d),this.seqNum+=1,r-=1,s-=c}return i}},ng=class extends qe{constructor(e,t,i,n){super(),this.dataChannel=e,this.statsGatherer=t,this.stateInternal="Created",this.packetizers=new Map,this.depacketizers=new Map,this.sendScheduleTimer=0,this.pendingPackets=new qp,this.label=e.label,this.logger=i.createChild(`[WebRtcDataChannel ${this.label}]`),this.bufferedAmountLowThreshold=n.config.webrtcDataChannel.bufferedAmountLowThreshold,this.bufferedAmountHighThreshold=n.config.webrtcDataChannel.bufferedAmountHighThreshold,this.fragmentationSize=n.config.webrtcDataChannel.enableFragmentation?n.config.webrtcDataChannel.fragmentationSize:0,n.config.webrtcDataChannel.enableSendScheduler&&(this.sendScheduler=new Xp(n)),this.rateLimiterCheckInterval=n.config.webrtcDataChannel.rateLimiterCheckInterval,this.discardOnSendFailure=n.config.webrtcDataChannel.discardOnSendFailure,this.subscribeOnDataChannelEvents()}getDataIdStats(e){return this.sendScheduler?.getStats(e)}get state(){return this.stateInternal}setDataChannel(e){this.dataChannel&&(this.logger.info(`Replacing internal data channel ${this.label}:${this.dataChannel.id} with ${e.label}:${e.id}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close()),this.dataChannel=e,this.subscribeOnDataChannelEvents()}dispose(){this.logger.info("dispose"),this.dataChannel&&(this.logger.info(`dataChannel.close ${this.dataChannel.id}`),this.unsubscribeOnDataChannelEvents(),this.dataChannel.close(),this.dataChannel=null,this.setState("Destroyed"),super.dispose())}sendMessage(e,t,i,n=[]){try{this.packetizers.has(e)||(this.fragmentationSize?this.packetizers.set(e,new ig(e,this.fragmentationSize,this.statsGatherer)):this.packetizers.set(e,new tg(e)));const r=this.packetizers.get(e).packetize({dataId:e,sourceId:t,data:i,recipients:n});void 0!==this.sendScheduler?(this.sendScheduler.appendPackets(e,r),this.scheduleSend()):r.forEach((e=>{this.dataChannel.send(e)})),this.statsGatherer.recordDataChannelProtocolEvent({direction:"send",state:0,dataId:e})}catch(t){throw this.logger.unsafe.warn(`Failed to construct protocol message: ${Be(t)}`),this.statsGatherer.recordDataChannelProtocolEvent({direction:"send",state:1,dataId:e}),t}}scheduleSend(){if("Connected"!==this.state)return;const e=e=>{try{this.dataChannel.send(e)}catch(e){return this.logger.unsafe.warn(`Failed to send message: ${Be(e)}`),!1}return!0};if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){const t=Date.now();let i=this.bufferedAmountHighThreshold-this.dataChannel.bufferedAmount;for(;this.pendingPackets.size();){const t=this.pendingPackets.peek();if(t.length>i)break;if(!e(t))break;this.pendingPackets.dequeue(),i-=t.length}if(0===this.pendingPackets.size()&&i>0){const t=this.sendScheduler.getPacketsToSend(i);for(const i of t)if(!1===e(i)&&!1===this.discardOnSendFailure){this.pendingPackets.enqueue(i);break}}if(this.dataChannel.bufferedAmount<=this.dataChannel.bufferedAmountLowThreshold){if(this.sendScheduleTimer)return;if(this.sendScheduler.getStats().remainingPackets>0){const e=Math.max(t+this.rateLimiterCheckInterval-Date.now(),20);this.sendScheduleTimer=window.setTimeout((()=>{this.sendScheduleTimer=0,this.scheduleSend()}),e)}}}}subscribeOnDataChannelEvents(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onmessage=e=>{const t=new Uint8Array(e.data),i=63&t[2];try{this.depacketizers.has(i)||this.depacketizers.set(i,new eg(i,this.statsGatherer,this.logger));const e=this.depacketizers.get(i).depacketize(t);e&&(this.statsGatherer.recordDataChannelProtocolEvent({direction:"recv",state:0,dataId:i}),this.event("onmessage").raise(i,e.sourceId,e.data))}catch(e){this.logger.unsafe.warn(`Failed to parse incoming message: ${Be(e)}`),this.statsGatherer.recordDataChannelProtocolEvent({direction:"recv",state:1,dataId:i})}},this.dataChannel.onerror=e=>{const t=e?.target,i=Be(e?.error??e);this.logger.safe.warn(`onerror: label:${t.label} id:${t.id} ${i} `),this.statsGatherer.recordDataChannelError(i)},"open"===this.dataChannel.readyState&&this.dataChannel.id%2==0&&(this.logger.safe.info(`readyState is already 'open' label:${this.dataChannel.label} id:${this.dataChannel.id}`),this.setState("Connected")),this.dataChannel.onopen=e=>{const t=e.target;this.logger.safe.info(`onopen label:${t.label} id:${t.id}`),t.id%2==0&&this.setState("Connected")},this.dataChannel.onclose=e=>{const t=e.target;this.logger.safe.info(`onclose label:${t.label} id:${t.id}`),this.setState("Closed")},this.dataChannel.onclosing=e=>{const t=e.target;this.logger.safe.debug(`onclosing label:${t.label} id:${t.id}`),this.setState("Closed")},void 0!==this.sendScheduler&&(this.dataChannel.bufferedAmountLowThreshold=this.bufferedAmountLowThreshold,this.dataChannel.onbufferedamountlow=()=>{this.scheduleSend()})}unsubscribeOnDataChannelEvents(){this.dataChannel.onmessage=null,this.dataChannel.onerror=null,this.dataChannel.onopen=null,this.dataChannel.onclose=null,this.dataChannel.onclosing=null,this.dataChannel.onbufferedamountlow=null}setState(e){this.stateInternal=e,this.event("onStateChanged").raise(),"Connected"===e&&void 0!==this.sendScheduler&&this.scheduleSend()}},rg=class extends qe{constructor(e,t,i,n){const r=i.createChild("PluginlessDataChannel");super(r),this.pc=e,this.statsGatherer=t,this.configProvider=n,this._state="Inactive",this.logger=r,this.subscribeOnDatachannel()}get state(){return this._state}getDataChannel(e){if(!this.dataChannel){this.logger.safe.info(`[${e}] creating new dataChannel`);try{const e={};this.dataChannel=new ng(this.pc.createDataChannel("main-channel",e),this.statsGatherer,this.logger,this.configProvider),this.subscribeForDataChannelEvents()}catch(t){return this.logger.safe.error(`[${e}] createDataChannel failed: ${Be(t)}`),this.statsGatherer.sessionInfo.setCreateChannelFailReason(t),this.setState("Failed"),null}}return this.dataChannel}updateDataModalityState(e){"Failed"!==this._state&&"Disabled"!==this._state&&(e===Qe.MEDIA_STATE.sendReceive?this.setState("Active"):e===Qe.MEDIA_STATE.inactive&&this.setState("Inactive"))}disable(){this.setState("Disabled")}dispose(){this.stopDataChannel(),this.pc=null,super.dispose()}subscribeOnDatachannel(){this.pc.ondatachannel=e=>{this.onDataChannel(e.channel)}}onDataChannel(e){this.logger.safe.info(`onDataChannel id=${e.id} label=${e.label}`),e.id%2==0?this.dataChannel?(this.logger.safe.info("Found existing data channel, replacing"),this.dataChannel.setDataChannel(e)):(this.dataChannel=new ng(e,this.statsGatherer,this.logger,this.configProvider),this.subscribeForDataChannelEvents()):this.logger.safe.info(`onDataChannel ignoring id ${e.id}`)}subscribeForDataChannelEvents(){this.dataChannel.on("onStateChanged",(()=>{"Closed"===this.dataChannel.state&&(this.stopDataChannel(),this.setState("Inactive"))}))}setState(e){if(this._state!==e){this.statsGatherer.setSessionDataChannelState(e);const t=Te();this._state=e,this.logger.safe.info(`[${t}] SessionDataChannelState changed, state=${this._state}`),"Inactive"===this._state||"Disabled"===this._state?this.stopDataChannel():"Active"===this._state&&this.getDataChannel(t),this.event("onStateChanged").raise(this._state)}}stopDataChannel(){this.dataChannel&&(this.logger.safe.info("stopDataChannel"),this.dataChannel.dispose(),this.dataChannel=null)}},ag=class extends We{constructor(e){super(),this.mainChannel=null,this.sourceId=_n,this._state="Inactive",this.dataHandlers=new Map,this.dataHandlerTelemetry=new Map,this.startTime=Date.now(),this.sendMessage=async(e,t,i)=>{if(this.logger.debug(`Sending message for ${e}, from: ${this.sourceId} to: ${i} state: ${!!this.mainChannel&&this.mainChannel.state} len: ${t.length}`),!this.mainChannel||"Connected"!==this.mainChannel.state||"Active"!==this.state)throw new Error("No active data channel to send data from");this.mainChannel.sendMessage(e,this.sourceId,t,i)},this.logger=e.createChild("PluginlessDataChannel")}get state(){return this._state}registerSessionDataChannel(e,t){this.sessionDataChannel&&this.stop(t),this.sessionDataChannel=e,this.subscribeForSessionDataChannelEvents()}setDataChannelSourceId(e){this.logger.debug(`setDataChannelSourceId ${e}`),this.sourceId=e}requestDataChannelHandler(e){return this.sessionDataChannel.getDataChannel(e)}async sendUserEvents(e,t){if(!this.mainChannel)throw this.logger.info("sendUserEvents() no data channel available"),new Error("Main DataChannel is not active");{const i=t?t.map((e=>parseInt(e,10))):[];this.mainChannel.sendMessage(0,this.sourceId,(new TextEncoder).encode(e),i)}}async addHandler(e,t){if(this.logger.info(`Adding handler with dataId ${e}`),this.dataHandlers.get(e))throw new Error(`Data Id ${e} is already registered`);const i={isStarted:!1,handler:t};this.dataHandlers.set(e,i),this.recordDataHandlerEvent(e,"added"),"Connected"===this.mainChannel?.state&&this.startHandler(e,i)}async removeHandler(e){if(this.logger.info(`Removing handler with dataId ${e}`),!this.dataHandlers.has(e))throw new Error(`Handler associated with Data Id ${e} is not attached`);const t=this.dataHandlers.get(e);t.isStarted&&this.stopHandler(e,t),this.dataHandlers.delete(e)}async updateNegotiationTag(e){}getTelemetry(){if(!this.dataHandlerTelemetry.size)return"";const e={};for(const[t,i]of this.dataHandlerTelemetry)e[t]=i;return JSON.stringify(e)}start(e){this.mainChannel?this.logger.info(`[${e}] already started`):(this.logger.info(`[${e}] starting`),this.mainChannel=this.sessionDataChannel.getDataChannel(e),this.subscribeForMainDataChannelEvents())}stop(e){this.mainChannel&&(this.logger.info(`[${e}] stopping`),this.mainChannel.dispose(),this.mainChannel=null)}dispose(){this.stop(void 0),this.sessionDataChannel=null,super.dispose()}setConfigProviderView(e){this.configProviderView=e}subscribeForMainDataChannelEvents(){this.mainChannel.on("onmessage",((e,t,i)=>{this.logger.debug(`Got message for ${e}, from: ${t} state: ${!!this.mainChannel&&this.mainChannel.state}, len: ${i.length}`),this.dataHandlers.has(e)&&(this.recordDataHandlerEvent(e,"recvd"),this.dataHandlers.get(e).handler.onDataReceived(e,i,t)),this.event("remoteUserEventsReceived").raise(e.toString(),(new TextDecoder).decode(i))})),this.onMainChannelStateChanged(),this.mainChannel.on("onStateChanged",(()=>this.onMainChannelStateChanged()))}onMainChannelStateChanged(){if(this.mainChannel)switch(this.mainChannel.state){case"Connected":this.startHandlers();break;case"Closed":case"Destroyed":this.stopHandlers()}}startHandlers(){for(const[e,t]of this.dataHandlers.entries())t.isStarted||this.startHandler(e,t)}stopHandlers(){for(const[e,t]of this.dataHandlers.entries())t.isStarted&&this.stopHandler(e,t)}startHandler(e,t){this.logger.info(`Starting dataHandler id: ${e}`),t.handler.onStarted(e,((t,i)=>(this.recordDataHandlerEvent(e,"sent"),this.sendMessage(e,t,i))),(()=>{const t=this.mainChannel?.getDataIdStats(e);if(void 0!==t){const e={bufferSize:t.bufferSize,remainingBytes:t.remainingBytes,remainingPackets:t.remainingPackets};return Promise.resolve(e)}return Promise.reject(new Error(`Stats of dataId ${e} is not available`))})),t.isStarted=!0,this.recordDataHandlerEvent(e,"started")}stopHandler(e,t){this.logger.info(`Stopping dataHandler id: ${e}`),t.handler.onStopped(e),t.isStarted=!1,this.recordDataHandlerEvent(e,"removed")}subscribeForSessionDataChannelEvents(){this.sessionDataChannel.on("onStateChanged",(e=>{const t=Te();switch(e){case"Active":this.start(t),this.setState("Active");break;case"Inactive":this.stop(t),this.setState("Inactive");break;case"Failed":this.stop(t),this.setState("Failed");break;case"Disabled":this.stop(t),this.setState("Disabled");break;default:this.logger.warn(`[${t}] unhandled SessionDataChannelState ${e}`)}}))}recordDataHandlerEvent(e,t){this.dataHandlerTelemetry.has(e)||this.dataHandlerTelemetry.set(e,[{}]);const i=this.dataHandlerTelemetry.get(e);let n=i[i.length-1];if("added"===t&&void 0!==n.added){n={},i.push(n);const e=this.configProviderView?.config.maxStoredDataChannelValues??15;i.length>e&&i.shift()}switch(t){case"added":case"started":case"removed":n[t]=Date.now()-this.startTime;break;case"recvd":case"sent":n[t]=isNaN(n[t])?1:n[t]+1}}setState(e){this._state!==e&&(this._state=e,this.logger.info(`PluginlessDataChannelState changed, state=${this._state}`),this.event("onDataChannelStateUpdated").raise(this._state))}},sg=f(ge());(e=>{e.encodeMouseEvent=function(e){if(!e)return new Uint8Array(0);e.buttonType||(e.buttonType=0),e.xPos||(e.xPos=0),e.yPos||(e.yPos=0),e.wheelRotation||(e.wheelRotation=0);const t=new ArrayBuffer(7),i=new DataView(t),n=3&e.type,r=(7&e.buttonType)<<2,a=(e.buttonDown?1:0)<<5,s=(e.wheelButtonDown?1:0)<<6;return i.setUint8(0,1),i.setUint8(1,n|r|a|s),i.setUint16(2,e.xPos,!0),i.setUint16(4,e.yPos,!0),i.setUint8(6,e.wheelRotation),new Uint8Array(t)},e.encodeKeyboardEvent=function(e){const t=new ArrayBuffer(3),i=new DataView(t),n=3&e.codeType,r=(e.keyUp?1:0)<<4,a=(e.repeat?1:0)<<5;return i.setUint8(0,0),i.setUint8(1,n|r|a),i.setUint8(2,e.code),new Uint8Array(t)},e.decodeEventType=function(e){return e[0]},e.decodeMouseEvent=function(e){if(1!==e[0]||7!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{type:3&i,buttonType:i>>2&7,buttonDown:!!(i>>5&1),wheelButtonDown:!!(i>>6&1),xPos:t.getUint16(2,!0),yPos:t.getUint16(4,!0),wheelRotation:t.getUint8(6)}},e.decodeKeyboardEvent=function(e){if(0!==e[0]||3!==e.length)return null;const t=new DataView(e.buffer),i=t.getUint8(1);return{codeType:3&i,code:t.getUint8(2),repeat:!!(i>>5&1),keyUp:!!(i>>4&1)}}})(jp||(jp={}));var og=g,lg=p,cg=1e4,dg="",ug=class extends un{constructor(e,t,i,n,r,a){super(e,t,(()=>this.recordedEvents.length>100)),this.negotiationTag=i,this.callId=n,this.participantId=r,this.endpointId=a,this.messagesFromUnknownSender={},this.tsCallingVersion="2024.14.01.23"}recordProtocolMessage(e,t){e||(t in this.messagesFromUnknownSender||(this.messagesFromUnknownSender[t]=0),this.messagesFromUnknownSender[t]++)}setCallId(e){this.callId=e}setEndpointId(e){this.endpointId=e}setParticipantId(e){this.participantId=e}setTenantId(e){this.tenantId=e}setUserHexCID(e){this.userHexCID=e}},hg=class extends ug{constructor(e,t,i,n,r,a,s){super(e,t,i,n,r,a);const o=Ud(s);if(o){this.sharerParticipantId=o;const e=(0,og.find)(s.endpoints.endpointDetails,(e=>e.participantId===o));e&&(this.sharerClientVersion=e.clientVersion)}}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),SharerParticipantId:i(this.sharerParticipantId),SharerClientVersion:i(this.sharerClientVersion),EventTimestampBag:super.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},pg=class extends ug{constructor(e,t,i,n,r,a){super(e,t,i,n,r,a)}getEvent(e,t){const i=e=>void 0===e?"":e;return{CorrelationId:i(this.callId),ParticipantId:i(this.participantId),EndpointId:i(this.endpointId),NegotiationTag:i(this.negotiationTag),TsCallingVersion:i(this.tsCallingVersion),TenantId:i(this.tenantId),EventTimestampBag:super.getEventTimestampBag(e,t),ProtocolMessages:JSON.stringify({UnknownSender:this.messagesFromUnknownSender})}}},gg=class extends We{constructor(e,t,i,n){super(e),this._logger=e,this._call=t,this._telemetryLoggers=i,this._config=n,this.controlState=0,this.role=0,this._enabled=!1,this._availableAckEnabled=!0,this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._controlRequest=null,this._controlRequestSubscription=null,this._controllerParticipant=null,this._controllerParticipantSubscription=null,this._controllerSourceId=null,this._screenSharingVideoRenderer=null,this._screenSharingVideoRendererSubscriptions=[],this._sharerParticipant=null,this._pendingSharer=null,this._controlCapturer=null,this._captureEventSubscription=null,this._mouseControlEventSubscription=null,this._keyboardControlEventSubscription=null,this._requestControlTimer=null,this._grantControlTimer=null,this._acceptControlTimer=null,this._terminateControlTimer=null,this._delayedSendHandshakeTimer=null,this._availableAckTimer=null,this._retryAttempt=0,this._raiseRenderedAtViewer=null,this._participantSubscriptions={},this._viewerSessionLastTerminatedReason=0,this._completedViewerSessions=[],this.giveControlEnabled=!0,this.isEscalationInProgress=!1,this._logger.info("constructor"),this._callId=this._call.callId,this._call.on("callIdChanged",(e=>{this._callId=e,this._currentViewerSessionTelemetry&&this._currentViewerSessionTelemetry.setCallId(e),this._currentSharerSessionTelemetry&&this._currentSharerSessionTelemetry.setCallId(e)})),this._participantId=this._call.participantId,this._call.on("callLegIdChanged",(e=>{this._participantId=e,this._currentViewerSessionTelemetry&&this._currentViewerSessionTelemetry.setParticipantId(e),this._currentSharerSessionTelemetry&&this._currentSharerSessionTelemetry.setParticipantId(e)})),this._endpointId=this._call.endpointId}setAdapters(e,t,i){this._controlInjector=e,this._rendererAdapter=t,this._dataChannelAdapter=i,this._dataChannelAdapter.on("stateChange",(e=>{this._onDataChannelStatusChanged(e)})),this._dataChannelAdapter.on("protocolMessage",((e,t,i,n)=>this.processProtocolMessage(e,t,i,n))),this._dataChannelAdapter.on("controlMessage",((e,t)=>this.processControlMessage(e,t)))}testSetControlInjector(e){}enableScreenSharingControl(e,t,i,n){if(this._logger.info(`enableScreenSharingControl() enabled=${e} disabledReason=${t}`),this._availableAckEnabled!==e||this._allowControlForUser!==n){if(this._allowControlForUser=n,e)this._raiseScreenSharingControlCapableEvent(!0,dg);else{if(0===t){const e={reason:2,detail:i};this.event("sharingControlError").raise(e)}this._raiseScreenSharingControlCapableEvent(!1,dg)}if(this._availableAckEnabled!==e){const t=e?"AvailableAckEnabled":"AvailableAckDisabled";this._recordSharerSessionTelemetry((e=>e.recordEvent(t)),!1)}this._availableAckEnabled=e}}setGiveControlEnabled(e){this.giveControlEnabled=e}_canEnableGiveControl(){return this._controlInjector.canBeEnabled()&&this.giveControlEnabled}setRaiseRenderedAtViewer(e){this._raiseRenderedAtViewer=e}setScreenSharingControlFeatureFlag(e){this._logger.info(`setScreenSharingControlFeatureFlag() enabled=${e}`),this._enabled=e,this._availableAckEnabled=e,this._enabled&&this._handleCallState(this._callState)}isScreenSharingControlEnabled(){return this._enabled}_disposeRenderer(e){this._disposeControlCapturer(e);for(const e of this._screenSharingVideoRendererSubscriptions)e.dispose();this._screenSharingVideoRendererSubscriptions=[],this._screenSharingVideoRenderer=null}setRenderer(e,t){this._logger.info("setRenderer");const i=Te();if(this._disposeRenderer(i),!e)return Promise.resolve();const n=t||this._rendererAdapter.getTarget(e);return vi((()=>{this._setViewingRenderer(e,n)}))}_isDataChannelActive(){return this._dataChannelAdapter.isActive()&&this._dataChannelAvailable}_raiseScreenSharingControlCapableEvent(e,t,i){if(this._enabled&&this._isDataChannelActive()){this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=true, capable=${e}, role=${this.role}`);const n={capable:e,id:t,disabledBySharer:i};this.event("sharingControlCapable").raise(n)}else{this._logger.info(`_raiseScreenSharingControlCapableEvent() enabled=false, capable=${e}, role=${this.role}`);const i={capable:!1,id:t};this.event("sharingControlCapable").raise(i)}}initControlForSharer(e){this._logger.info("initControlForSharer()"),this._isSharing()&&this._logger.warn("initControlForSharer() when already sharing"),this._resetControlState(),this._screenSharingVideoRenderer=null,this._disposeControlCapturer(),this._logger.info(`role is changing from=${this.role} to=1`),this.role=1,this._availableHandshakeSent=!1,this._raiseScreenSharingControlCapableEvent(this._canEnableGiveControl(),dg),this._initiateSharerSessionTelemetry(e)}enableControlInjector(e){this._logger.info(`enableControlInjector() trackId: ${e}`),this._canEnableGiveControl()?this._controlInjector.enableInjector(e).catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})):this._logger.info("enableControlInjector() give control cannot be enabled")}shutdownControlForSharer(){if(this._logger.info("shutdownControlForSharer()"),this._isSharing()||this._logger.warn("shutdownControlForSharer() when not sharing"),this._controlRequest){this._logger.warn("Rejecting pending control requests");const e=this._getDataSourceIdForParticipantLeg(this._controlRequest),t=this._controlRequest;this._clearControlRequest(),this._raiseControlRequestCanceled(t),this._sendControlRejectRequest(5,e)}if(this._controllerParticipant){const e={inControl:!1,id:this._controllerParticipant.participant.id,terminatedReason:5};this.event("sharingControlChanged").raise(e)}this._finalizeSharerSessionTelemetry("Shutdown"),this._teardownSharerRemoteControl(),this._controlInjector.disableInjector().catch((e=>{const t={reason:0,detail:JSON.stringify({errorMsg:e})};this.event("sharingControlError").raise(t)})),this._resetControlState(),this._resetParticipantSubscriptions(),this._availableAckEnabled=this._enabled,this._logger.info(`role is changing from=${this.role} to=0`),this.role=0}_resetParticipantSubscriptions(){this._logger.info("resetParticipantSubscriptions() Stopping tracking all participant state changes"),(0,og.each)(this._participantSubscriptions,(e=>{e.dispose()})),this._participantSubscriptions={}}_initiateViewerSessionTelemetry(e,t,i){if(!i&&!t)return null;if(!i&&(0,og.find)(this._completedViewerSessions,(e=>t===e)))return null;if(this._currentViewerSessionTelemetry){if(this._currentViewerSessionTelemetry.negotiationTag===t)return null;this._finalizeViewerSessionTelemetry("ShutdownByOtherSession")}return this._logger.info(`Initiating new viewer session telemetry for ${t}`),this._currentViewerSessionTelemetry=new hg(this._logger,(new Date).getTime(),t,this._callId,this._participantId,this._endpointId,e),this._currentViewerSessionTelemetry.recordEvent("CallState",{state:this._callState}),this._isDataChannelActive()&&this._currentViewerSessionTelemetry.recordEvent("DataChannelAvailable"),this._currentViewerSessionTelemetry}_recordViewerSessionTelemetry(e,t=!0){this._currentViewerSessionTelemetry?e&&e(this._currentViewerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeViewerSessionTelemetry(e){if(!this._currentViewerSessionTelemetry)return;this._currentViewerSessionTelemetry.recordEvent(e);const t=this._currentViewerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_viewer_session",t),this._currentViewerSessionTelemetry.negotiationTag&&this._completedViewerSessions.push(this._currentViewerSessionTelemetry.negotiationTag),this._currentViewerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentViewerSessionTelemetry.messagesFromUnknownSender).length&&lg.RootToolsManager.logExternalForDDL("ScreenSharingControl_viewer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentViewerSessionTelemetry=null}_initiateSharerSessionTelemetry(e){if(this._currentSharerSessionTelemetry){if(this._currentSharerSessionTelemetry.negotiationTag===e)return null;this._finalizeSharerSessionTelemetry("ShutdownByOtherSession")}this._logger.info(`Initiating new sharer session telemetry for ${e}`),this._currentSharerSessionTelemetry=new pg(this._logger,(new Date).getTime(),e,this._callId,this._participantId,this._endpointId),this._isDataChannelActive()&&this._currentSharerSessionTelemetry.recordEvent("DataChannelAvailable")}_recordSharerSessionTelemetry(e,t=!0){this._currentSharerSessionTelemetry?e&&e(this._currentSharerSessionTelemetry):t&&this._logger.error("Cannot record telemetry without current session")}_finalizeSharerSessionTelemetry(e){if(!this._currentSharerSessionTelemetry)return;this._currentSharerSessionTelemetry.recordEvent(e);const t=this._currentSharerSessionTelemetry.getEvent();this._sendTelemetryEvent("mdsc_gtc_sharer_session",t),this._currentSharerSessionTelemetry.messagesFromUnknownSender&&Object.keys(this._currentSharerSessionTelemetry.messagesFromUnknownSender).length&&lg.RootToolsManager.logExternalForDDL("ScreenSharingControl_sharer: messages received from unkonwn sender",JSON.stringify(t.ProtocolMessages)),this._currentSharerSessionTelemetry=null}_sendTelemetryEvent(e,t){this._logger.info(`Sending event ${e}: `),Object.keys(t).forEach((e=>{this._logger.info(`     ${e} => ${t[e]}`)})),this._telemetryLoggers?.media?.sendEvent({eventName:e,props:t})}_recordProtocolMessage(e,t){this._currentViewerSessionTelemetry&&this._currentViewerSessionTelemetry.recordProtocolMessage(e,t),this._currentSharerSessionTelemetry&&this._currentSharerSessionTelemetry.recordProtocolMessage(e,t)}reportSharingSessionChangeForViewer(e,t){t&&this._initiateViewerSessionTelemetry(e,t,!1)}initControlForViewer(e,t){if(this._logger.info(`initControlForViewer(${Ae(e?.id)}, ${t})`),!e)return void this._logger.warn("initControlForViewer: Sharer undefined, ignoring");if(this._isViewing()&&this._logger.warn("initControlForViewer: called when already viewing"),3!==this._callState)return this._logger.info(`initControlForViewer: postponed until call is connected, callState=${this._callState}`),this._pendingNegotiationTag=t,void(this._pendingSharer=e);const i=!this._sharerParticipant||this._sharerParticipant&&this._sharerParticipant.id!==e.id||t!==this._currentNegotiationTag;this._currentNegotiationTag=t,this._logger.info(`role is changing from=${this.role} to=2`),this.role=2,this._sharerParticipant?this._sharerParticipant.id!==e.id&&(this._recordViewerSessionTelemetry((e=>e.recordEvent("ShutdownByOtherSession",null,t))),this._logger.info(`initControlForViewer: sharer switched, new sharer id=${Ae(e.id)}`),this._availableHandshakeSent=!1,4===this.controlState&&this._terminateControl(!1)):(this._logger.info(`initControlForViewer: setting sharer to id=${Ae(e.id)}`),this._sharerParticipant=e,this._availableHandshakeSent=!1),this._initiateViewerSessionTelemetry(e,t,!0),i&&this._recordViewerSessionTelemetry((e=>e.recordEvent("SharingStarted"))),this._enabled&&this._isDataChannelActive()&&!this._availableHandshakeSent&&(this._resetControlState(),this._sharerParticipant=e,this._logger.info("initControlForViewer: sending Available message to sharer"),this._startAvailableHandshake())}shutdownControlForViewer(e){this._logger.info("shutdownControlForViewer()"),this._pendingSharer=null;let t=!1;if(e&&e.id!==this._sharerParticipant?.id||(this._logger.info(`shutdownControlForViewer: setting shouldShutdownControlForViewer to true, isViewing: ${this._isViewing()}`),t=!0),t&&this._isViewing()){if(1===this.controlState){if(this._sharerParticipant){const e=this._getSharerDataSourceId();this._sendRequest({action:2,terminatedReason:6},e)}else this._logger.warn("shutdownControlForViewer: sharer participant is null");const e={inControl:!1,id:dg,terminatedReason:6};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:e,details:""}))):this._logger.error("shutdownControlForViewer: Unexpected, no promise could be resolved, controlState=RequestSent")}else if(4===this.controlState){const e={inControl:!1,id:dg,terminatedReason:6};this.event("sharingControlChanged").raise(e)}this._teardownViewerRemoteControl(),this._resetControlState(),this._screenSharingVideoRenderer=null,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._availableHandshakeSent=!1,this._finalizeViewerSessionTelemetry("Shutdown"),2===this.role?(this._logger.info(`_raiseScreenSharingControlCapableEvent  with user role=${this.role}, MRI=, isCapable=false`),this._raiseScreenSharingControlCapableEvent(!1,dg)):this._logger.warn(`can't call _raiseScreenSharingControlCapableEvent, role=${this.role}`),this._logger.info(`role is changing from=${this.role} to=0`),this.role=0}}_resetControlRequest(e){this._clearControlRequest(),this._controlRequest=e,this._registerParticipantListener(e),3===e.participantState&&(this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${e.participant.id}`),this.event("sharingIncomingControlRequest").raise(e.participant.id))}_clearControlRequest(){this._logger.info("_clearControlRequest()"),this._stopListeningToParticipantChanges(this._controlRequest),this._controlRequest=null}_stopListeningToParticipantChanges(e){this._controlRequestSubscription&&(this._logger.info(`_stopListeningToParticipantChanges: stopping tracking changes for ${e.participant.id}`),this._controlRequestSubscription.dispose(),this._controlRequestSubscription=null)}_registerParticipantListener(e){this._logger.info(`_registerParticipantListener: tracking changes for ${e.participant.id}`),this._logger.info(`request.participantState: ${e.participantState} | request.participant.state: ${e.participant.state}`),this._controlRequestSubscription=e.participant.changed((()=>{if(e.participant.state!==e.participantState)switch(this._logger.info(`request.participantState about to changed from: ${e.participantState} to: ${e.participant.state}`),e.participantState=e.participant.state,e.participantState){case 3:this.event("sharingIncomingControlRequest").raise(e.participant.id),this._logger.info(`participantState: Connected, raising: sharingIncomingControlRequest for participantId: ${e.participant.id}`);break;case 0:case 5:case 4:this.denyControlRequest().catch((e=>{this._logger.info(`It is ok if denyControlRequest rejects here as screensharing may have just been stopped. Err: ${e}`)})),this._logger.info(`_registerParticipantListener: participant ${e.participant.id} is no longer connected. resetting`),this._clearControlRequest(),this._raiseControlRequestCanceled(e);break;case 1:case 2:case 6:case 7:this._logger.info(`participantState: ${e.participantState}, participantId: ${e.participant.id}`);break;default:this._logger.error(`_registerParticipantListener: Unexpected participantState ${e.participantState} unhandled`)}}))}_resetControllerParticipant(e){this._controllerParticipantSubscription&&(this._logger.info(`_resetControllerParticipant: stopping tracking changes for ${this._controllerParticipant.participant.id}`),this._controllerParticipantSubscription.dispose(),this._controllerParticipantSubscription=null),e&&(this._logger.info(`_resetControllerParticipant: tracking changes for ${e.participant.id}`),this._controllerParticipantSubscription=e.participant.changed((()=>{3!==e.participant.state&&this.handleParticipantRemoved(e.participant.id)}))),this._controllerParticipant=e}handleParticipantRemoved(e){if(this._participantSubscriptions[e]&&(this._logger.info(`handleParticipantRemoved(): Stopping tracking state changes for ${e}`),this._participantSubscriptions[e].dispose(),delete this._participantSubscriptions[e]),this._isSharing()){if(this._controllerParticipant&&this._controllerParticipant.participant.id===e){this._logger.info("handleParticipantRemoved: controller left call, tearing down control session"),this._teardownSharerRemoteControl(),this.controlState=0,this._resetControllerParticipant();const t={inControl:!1,id:e,terminatedReason:5};this.event("sharingControlChanged").raise(t)}this._raiseScreenSharingControlCapableEvent(!1,e)}else if(this._sharerParticipant&&this._sharerParticipant.id===e&&4===this.controlState){this._logger.info("handleParticipantRemoved: sharer left call, tearing down control session"),this._teardownViewerRemoteControl(),this.controlState=0;const e={inControl:!1,id:dg,terminatedReason:6};this.event("sharingControlChanged").raise(e)}}callStateChanged(e){this._callState=e,this._recordViewerSessionTelemetry((t=>t.recordEvent("CallState",{state:e})),!1),this._recordSharerSessionTelemetry((t=>t.recordEvent("CallState",{state:e})),!1),this.isScreenSharingControlEnabled()&&this._handleCallState(e)}setIsEscalationInProgress(e){this.isEscalationInProgress=e}_getHandshakeDelay(){if(!this._config.handshakeSendDelay?.minParticipantThreshold)return 0;let e=0;if(this._call.participants.length>=this._config.handshakeSendDelay.minParticipantThreshold)for(const t of this._call.participants)t.endpoints?.endpointDetails.some((e=>"interactive"===e.appliedInteractivityLevel))&&e++;if(e<=this._config.handshakeSendDelay.minParticipantThreshold)return 0;const t=Math.ceil((e-this._config.handshakeSendDelay.minParticipantThreshold)/this._config.handshakeSendDelay.increaseEveryN);return Math.min(this._config.handshakeSendDelay.maxDelay,t*this._config.handshakeSendDelay.delayPerN)}_handleCallState(e){switch(e){case 3:this._handleCallConnected();break;case 7:this._handleCallDisconnected();break;case 4:case 5:this.shutdownControlForViewer()}}_handleCallConnected(){this._logger.info("_handleCallConnected()"),this._pendingSharer&&(this.initControlForViewer(this._pendingSharer,this._pendingNegotiationTag),this._pendingSharer=null)}_handleCallDisconnected(){this._logger.info("_handleCallDisconnected()"),this._isSharing()?this.shutdownControlForSharer():this.shutdownControlForViewer()}_videoSizeChanged(e,t){null!==this._controlCapturer&&this._controlCapturer.updateVideoSize(e,t)}_onRenderStarted(){const e={action:11,terminatedReason:0};if(this._sharerParticipant){const t=this._getSharerDataSourceId();this._sendRequest(e,t)}else this._logger.error("Attempted to send sharing rendered message to null sharerParticipant")}_setViewingRenderer(e,t){try{this._screenSharingVideoRenderer=e,this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeVideoSizeChangedEvent(this._screenSharingVideoRenderer,((e,t)=>{this._videoSizeChanged(e,t)}))),this._screenSharingVideoRendererSubscriptions.push(this._rendererAdapter.subscribeRenderStartedEvent(this._screenSharingVideoRenderer,(()=>{this._onRenderStarted()})));let i=1;e.streamSize&&e.streamSize.width>0&&e.streamSize.height>0&&(i=e.streamSize.width/e.streamSize.height),this._controlCapturer=new sg.SlimCoreElectronControlCapturer(this._logger,t,!0,i),4===this.controlState?(this._logger.info("_setViewingRenderer: detected local state is controlling"),this._setupViewerRemoteControl()):this._teardownViewerRemoteControl()}catch(e){this._logger.error(`_setViewingRenderer: unable to set _screenSharingVideoRenderer error=${e}`)}}_onDataChannelStatusChanged(e){this._logger.info(`_onDataChannelStatusChanged(): Data channel status=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e?this._dataChannelAvailable||(this._dataChannelAvailable=!0,this._recordViewerSessionTelemetry((e=>e.recordEvent("DataChannelAvailable")),!1),this._recordSharerSessionTelemetry((e=>e.recordEvent("DataChannelAvailable")),!1),this._enabled&&(this._isViewing()?this._availableHandshakeSent||(this._sharerParticipant?(this._logger.info("_onDataChannelStatusChanged: sending Available message to sharer"),this._startAvailableHandshake()):this._logger.error("Unexpected null _sharerParticipant trying to send Available to sharer")):this._isSharing()&&(this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!0,dg)))):this._dataChannelAvailable&&(this._recordViewerSessionTelemetry((e=>e.recordEvent("DataChannelUnavailable")),!1),this._recordSharerSessionTelemetry((e=>e.recordEvent("DataChannelUnavailable")),!1),this._dataChannelAvailable=!1,this._availableHandshakeSent=!1,this._terminateAvailableHandshake&&this._terminateAvailableHandshake(3),this.isEscalationInProgress||this._raiseScreenSharingControlCapableEvent(!1,dg))}_isSharing(){return 1===this.role}_isViewing(){return 2===this.role}_handleAvailableRequest(e,t,i){let n=!1,r=0;if(this._enabled)if(this._availableAckEnabled)if(this._canEnableGiveControl())if(t?.id){if(this._allowControlForUser&&typeof this._allowControlForUser==typeof Function)return void this._allowControlForUser(t).then((a=>{a||(n=!0,r=1),this._sendResponseToAvailableRequest(e,t,i,n,r)}))}else n=!0,r=10;else this._logger.info("GiveControl is not enabled. no need to answer the available ack"),n=!0,r=9;else this._logger.info("Available ack is off. no need to answer the available ack"),n=!0,r=9;else this._logger.info("Feature flag is off. no need to answer the available ack"),n=!0,r=9;this._sendResponseToAvailableRequest(e,t,i,n,r)}_sendResponseToAvailableRequest(e,t,i,n,r){n?(this._logger.info(`Rejecting Available for handShake:${i}:${e.handshakeId}`),this.event("controlAvailableHandshake").raise(e.handshakeId,i,7,this._getAvailableHandshakeTerminatedFromControlTerminated(r)),this._sendRequest({action:10,terminatedReason:r,handshakeId:e.handshakeId},i)):(this._raiseScreenSharingControlCapableEvent(!0,t.id),this._participantSubscriptions[t.id]||(this._logger.info(`Tracking participant status for ${t.id}`),this._participantSubscriptions[t.id]=t.changed((()=>{3!==t.state&&(this._logger.info(`Participant ${t.id} is not connected. removing`),this.handleParticipantRemoved(t.id))}))),this._logger.info(`Acking Available for handShake:${i}:${e.handshakeId}`),this.event("controlAvailableHandshake").raise(e.handshakeId,i,3),this._sendRequest({action:9,terminatedReason:0,handshakeId:e.handshakeId},i))}processProtocolMessage(e,t,i,n){return vi((()=>{this._processProtocolMessage(e,t,i,n)}))}_raiseControlRequestCanceled(e){this.event("sharingIncomingControlRequestCancelled").raise(e.participant.id)}_handleControlRequest(e,t,i){this._recordSharerSessionTelemetry((e=>{e.recordOperation("ControlRequest",null,String(t))})),this._enabled?this._controlRequest?(this._logger.warn("Sharer is already processing a control request...rejecting new requests"),this._sendControlRejectRequest(3,t)):this._controllerParticipant&&this._controllerParticipant.participant===e?this._controllerParticipant.participantId&&this._controllerParticipant.participantId!==i?(this._logger.warn(`rejecting control request from second endpoint. participantId: ${i}`),this._sendControlRejectRequest(3,t)):(this._logger.warn("Got control request for someone already in control"),this._resetControllerParticipant(),this._resetControlRequest({participant:e,participantState:e.state,participantId:i})):e?(this._logger.info(`resetControlRequest for participantId: ${i}`),this._resetControlRequest({participant:e,participantState:e.state,participantId:i})):this._logger.error("Got ControlRequest message but could not find a sender participant, ignoring"):(this._logger.warn("Sharer control is disabled - rejecting request"),this._sendControlRejectRequest(9,t))}_handleAcceptRequest(e,t){if(1===this.controlState){const i=this._sendRequest({action:5,terminatedReason:0},t);this._logger.info(`_handleAcceptRequest controlMessage.action: ${mg(e.action)} _sendRequest isSent: ${i}`),i?(this._setupViewerRemoteControl(),this.controlState=4,this._requestControlPromise?this._requestControlPromise.resolve():this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${mg(e.action)}`),this._recordViewerSessionTelemetry((e=>{e.recordOperationSuccess("ControlRequest",null)}))):this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control is accepted, but failed to send ack"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${fg(this.controlState)} action=${mg(e.action)}`),this._cancelRequestControlTimer()}else this._logger.warn(`AcceptRequest message received in controlState=${fg(this.controlState)}`)}_handleRejectRequest(e){if(1===this.controlState){this._logger.info(`_handleRejectRequest: controlState: ${fg(this.controlState)}, about to be changed to: ${fg(0)}`),this.controlState=0;const t={inControl:!1,id:dg,terminatedReason:e.terminatedReason};this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:t,details:""}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=RequestSent action=${mg(e.action)}`),this._recordViewerSessionTelemetry((t=>{t.recordOperationFailure("ControlRequest",{reason:vg(e.terminatedReason)})})),this._cancelRequestControlTimer()}else this._logger.warn(`RejectRequest message received in controlState=${fg(this.controlState)} reason=${e.terminatedReason}`)}_handleCancelControlRequest(e,t){if(this._logger.info(`_handleCancelControlRequest action=${mg(e.action)} sender=${t}, controlRequest participantId: ${this._controlRequest.participantId}, controlRequest participantState: ${this._controlRequest.participantState}:`),this._controlRequest){const i=this._controlRequest;this._logger.info(`_handleCancelControlRequest action=${mg(e.action)} sender=${t}, about to raise: _raiseControlRequestCanceled state: ${this._controlRequest.participantState} `),this._recordSharerSessionTelemetry((e=>{e.recordOperationTimeout("ControlRequest",{participantId:t},String(t))})),this._clearControlRequest(),this._raiseControlRequestCanceled(i)}}_handleGiveControl(e,t,i){const n=this._sendRequest({action:5,terminatedReason:0},t);if(this._logger.info(`_handleGiveControl: controlMessage.action: ${mg(e.action)} _sendRequest isSent: ${n}`),n){this._setupViewerRemoteControl(),this._logger.info(`controlState: ${fg(this.controlState)}, about to be changed to: ${fg(4)}`),this.controlState=4,this._recordViewerSessionTelemetry((e=>{e.recordEvent("ControlGiven",{sender:t})}));const i={inControl:!0,id:dg,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(i)}}_handleAck(e,t,i){if(2===this.controlState)if(this._controllerParticipant&&this._controllerParticipant.participant===t){const t=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);i!==t&&this._logger.warn(`acknowledging source id: ${i} does not match requesting source id: ${t}`),this._logger.info(`Setting up remote control for controller source id=${t}`),this._setupSharerRemoteControl(t),this._logger.info(`controlState: ${fg(this.controlState)}, about to be changed to: ${fg(3)}`),this.controlState=3;const n={inControl:!0,id:this._controllerParticipant.participant.id,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(n),this._grantControlPromise?(this._grantControlPromise.resolve(),this._cancelGrantControlTimer(),this._recordSharerSessionTelemetry((e=>{e.recordOperationSuccess("GiveControl",{participantId:t})}))):this._acceptControlPromise?(this._acceptControlPromise.resolve(),this._cancelAcceptControlTimer(),this._recordSharerSessionTelemetry((e=>{e.recordOperationSuccess("ControlRequest",{participantId:t},String(t))}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForControlAck action=${mg(e.action)}`)}else t?this._logger.warn(`Ignoring ack from participant that does not match controller id=${Ae(t.id)}`):this._logger.warn(`Ignoring ack from null participant source id=${i}`);else 5===this.controlState?(this._logger.info(`controlState: ${fg(this.controlState)}, about to be changed to: ${fg(0)}`),this.controlState=0,this._resetControllerParticipant(),this._terminateControlPromise?(this._terminateControlPromise.resolve(),this._cancelTerminateControlTimer()):this._logger.error(`Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck action=${mg(e.action)}`)):this._logger.warn(`Unexpected ack in control controlState=${fg(this.controlState)}`)}_handleTerminate(e,t,i){let n;this._isViewing()?(this._teardownViewerRemoteControl(),n=dg):(this._teardownSharerRemoteControl(),t?n=t.id:this._logger.error("Got terminate message but could not find a sender participant!")),this._logger.info(`controlMessage action: ${mg(e.action)}, controllerId: ${n}`),this._logger.info(`controlState: ${fg(this.controlState)}, about to be changed to: ${fg(0)}`),this.controlState=0,this._resetControllerParticipant();const r={inControl:!1,id:n,terminatedReason:e.terminatedReason};this.event("sharingControlChanged").raise(r),8===e.action&&this._sendRequest({action:5,terminatedReason:0},i)}_handleAvailableAck(e){this._terminateAvailableHandshake&&(this._logger.info(`_handleAvailableAck: terminate available handshake reason: 1,handshakeId: ${e.handshakeId}`),this._terminateAvailableHandshake(1,e.handshakeId)),2===this.role?this._raiseScreenSharingControlCapableEvent(!0,dg):this._logger.info(`Ignoring AvailableAck as viewer session is not initialized, role: ${this.role}`)}_handleAvailableNack(e){this._logger.info(`_handleAvailableNack: action=${mg(e.action)} terminate reason: ${vg(e.terminatedReason)}`),this._viewerSessionLastTerminatedReason=e.terminatedReason,this._recordViewerSessionTelemetry((t=>{t.updateOperationData("AvailableHandshake",{nackReason:e.terminatedReason},e.handshakeId)})),10!==e.terminatedReason?(this._terminateAvailableHandshake&&(this._terminateAvailableHandshake(this._getAvailableHandshakeTerminatedFromControlTerminated(e.terminatedReason),e.handshakeId),this._logger.info(`_handleAvailableNack: terminateAvailableHandshake reason=${vg(e.terminatedReason)}`)),1===e.terminatedReason?(this._logger.warn("_handleAvailableNack: control terminate reason: SharerDenied"),this._raiseScreenSharingControlCapableEvent(!0,dg,!0)):this._raiseScreenSharingControlCapableEvent(!1,dg)):this._logger.warn("_handleAvailableNack: control terminate reason: UnknownSender")}_handleRenderedAtViewer(e,t){this._raiseRenderedAtViewer&&(t?(this._logger.info(`raiseRenderedAtViewer senderId=${t.id}, action=${mg(e.action)}`),this._raiseRenderedAtViewer(t.id)):this._logger.error("Got RenderedAtViewer message but could not find a sender participant!"))}_processProtocolMessage(e,t,i,n){let r;this._recordProtocolMessage(t,n);try{r=JSON.parse(e)}catch(e){return void this._logger.error("Error parsing controlMessage")}switch(t||this._logger.warn(`protocol message from unknown sender with sourceId=${n}`),this._logger.info(`_processProtocolMessage action=${mg(r.action)}, sourceId=${n}`),r.action){case 0:this._handleAvailableRequest(r,t,n);break;case 1:this._handleControlRequest(t,n,i);break;case 3:this._handleAcceptRequest(r,n);break;case 4:this._handleRejectRequest(r);break;case 2:this._handleCancelControlRequest(r,n);break;case 6:this._handleGiveControl(r,n,t);break;case 5:this._handleAck(r,t,n);break;case 8:case 7:this._handleTerminate(r,t,n);break;case 9:this._handleAvailableAck(r);break;case 10:this._handleAvailableNack(r);break;case 11:this._handleRenderedAtViewer(r,t);break;default:this._logger.error(`Unknown request action received on control protocol data sink, action=${mg(r.action)}`)}}_getAvailableHandshakeTerminatedFromControlTerminated(e){switch(e){case 10:return 6;case 1:return 7;default:return 0}}_sendRequest(e,t){if(t<0)return this._logger.warn(`Unexpected: invalid sourceID=${t}`),!1;this._logger.info(`_sendRequest() action=${mg(e.action)} recipient sourceid=${t}`);const i={type:0,message:JSON.stringify(e)},n=[t];return this._dataChannelAdapter.sendProtocolMessage(function(e){const t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=0;t<e.length;t++)i[t]=e.charCodeAt(t);return i}(JSON.stringify(i)),n),!0}async processControlMessage(e,t){if(t===this._controllerSourceId){if(3===this.controlState)return this._processControlMessage(e,t);this._logger.debug(`Ignoring control message, wrong controlState. Expected: RemoteControlling, got: ${fg(this.controlState)}`)}else this._logger.debug(`Ignoring control message, wrong sourceId. Expected: ${t}, got: ${this._controllerSourceId}`)}_processControlMessage(e,t){return this._controlInjector.injectRawInput(e,t)}_resetControlState(){this._logger.info("_resetControlState()"),this.controlState=0,this._resetControllerParticipant(),this._sharerParticipant=null,this._clearControlRequest(),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer()}_setupSharerRemoteControl(e){this._logger.info(`_setupSharerRemoteControl() sourceId=${e}`),this._controllerSourceId=e,this._controlInjector.showVirtualCursor(e).catch((t=>{const i={reason:3,detail:JSON.stringify({sourceId:e,errorMsg:t})};this.event("sharingControlError").raise(i)}))}_teardownSharerRemoteControl(){this._logger.info("_teardownSharerRemoteControl()"),this._controllerSourceId=null,this._controlInjector.showVirtualCursor(0).catch((e=>{const t={reason:3,detail:JSON.stringify({sourceId:0,errorMsg:e})};this.event("sharingControlError").raise(t)}))}_setupViewerRemoteControl(){this._logger.info("_setupViewerRemoteControl()"),this._setCapturerMode(3)}_teardownViewerRemoteControl(){this._logger.info("_teardownViewerRemoteControl()"),this._setCapturerMode(0)}_clearCapturerEventSubscriptions(){this._logger.info("_clearCapturerEventSubscriptions()"),this._captureEventSubscription&&(this._captureEventSubscription.dispose(),this._captureEventSubscription=null),this._mouseControlEventSubscription&&(this._mouseControlEventSubscription.dispose(),this._mouseControlEventSubscription=null),this._keyboardControlEventSubscription&&(this._keyboardControlEventSubscription.dispose(),this._keyboardControlEventSubscription=null)}sendRemoteControlEvent(e,t){if(t)switch(e){case"mouseControlEvent":this._sendControlEvent(jp.encodeMouseEvent(t));break;case"keyboardControlEvent":this._sendControlEvent(jp.encodeKeyboardEvent(t));break;default:return void this._logger.error("sendRemoteControlEvent: Invalid type=",e)}else this._logger.error("sendRemoteControlEvent: Invalid argument.")}_sendControlEvent(e){if(!this._isDataChannelActive()||!this._sharerParticipant||4!==this.controlState)return void this._logger.error(`_sendControlEvent: Dropping message - No data channel or wrong controlState. dataConnected: ${this._isDataChannelActive()} controlState: ${fg(this.controlState)})`);const t=[this._getSharerDataSourceId()];this._dataChannelAdapter.sendControlMessage(e,t)}_setCapturerMode(e){this._logger.info(`_setCapturerMode() capturerMode=${e}`),this._controlCapturer?(this._controlCapturer.setCaptureMode(e),this._clearCapturerEventSubscriptions(),1===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{0===e&&this.event("sharingRendererClicked").raise()})):2===e?this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})):3===e&&(this._mouseControlEventSubscription=this._controlCapturer.on("mouseControlEvent",(e=>{this._sendControlEvent(jp.encodeMouseEvent(e))})),this._keyboardControlEventSubscription=this._controlCapturer.on("keyboardControlEvent",(e=>{this._sendControlEvent(jp.encodeKeyboardEvent(e))})),this._captureEventSubscription=this._controlCapturer.on("ctrlCaptureEvent",(e=>{1===e?this.event("sharingRendererMouseEntering").raise():2===e&&this.event("sharingRendererMouseLeaving").raise()})))):this._logger.info("_controlCapturer not set, relying on external controlCapturer")}setPointerImage(e,t){return this._logger.warn("setPointerImage is deprecated. Use setLocalPointerImage or setRemotePointerImage"),e?this.setRemotePointerImage(e,t):this.setLocalPointerImage(t)}setLocalPointerImage(e){return 0===e.length?Promise.reject(new Error("setLocalPointerImage invalid image length")):this._setPointerImage(0,e)}async setRemotePointerImage(e,t){if(!e)throw new Error("setRemotePointerImage participant is null");if(0===t.length)throw new Error("setRemotePointerImage invalid image length");const i=this._getParticipantsDataSourceIds(e);if(0===i.length)throw new Error("setRemotePointerImage unable to map participant to sourceIds");this._logger.info(`set pointer image for ${i.length} sources`);for(const e of i)await this._setPointerImage(e,t)}_setPointerImage(e,t){return this._isSharing()||this._logger.warn("_setPointerImage called when not sharing"),this._controlInjector.setPointerImage(e,t)}startPointerMode(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`startPointerMode called in bad control controlState=${fg(this.controlState)}`)):this._isViewing()?vi((()=>{this._setCapturerMode(2)})):Promise.reject(new Error("startPointerMode when not viewing")):Promise.reject(new Error("startPointerMode when data channel not active")):Promise.reject(new Error("startPointerMode when feature not enabled"))}stopPointerMode(){return 0!==this.controlState?Promise.reject(new Error(`stopPointerMode called in bad control controlState=${fg(this.controlState)}`)):this._isViewing()?vi((()=>{this._setCapturerMode(1)})):Promise.reject(new Error("stopPointerMode when not viewing"))}_startAvailableHandshake(){const e=this._getSharerDataSourceId(),t=xi(),i=this._getHandshakeDelay(),n=Math.floor(Math.random()*i);if(this._logger.info(`_startAvailableHandshake() - handshakeId: ${e}:${t} ${n>0?`delay: ${n}ms maxDelay: ${i}ms`:""}}`),this._terminateAvailableHandshake&&(this._logger.warn("Replacing existing availble handshake"),this._terminateAvailableHandshake(4)),this._recordViewerSessionTelemetry((e=>e.recordOperation("AvailableHandshake",t))),e<0)this._logger.warn(`_startAvailableHandshake() - sharer: ${Ae(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(t);else{const r=()=>{this.event("controlAvailableHandshake").raise(t,e,1),this._sendRequest({action:0,terminatedReason:0,handshakeId:t},e)||this._logger.error("Failed to send Available message to sharer, will retry after backoff"),this._waitForAvailableAck(t)};n>0?(this._delayedSendHandshakeTimer=window.setTimeout(r,n),this._recordViewerSessionTelemetry((e=>{e.updateOperationData("AvailableHandshake",{delay:n,maxDelay:i},t)}))):r()}this._availableHandshakeSent=!0,this._terminateAvailableHandshake=(i=0,n)=>{this._logger.info(`_terminateAvailableHandshake() - handshakeId: ${e}:${t}, status: ${i}`),this._recordViewerSessionTelemetry((e=>{e.updateOperationData("AvailableHandshake",{tries:this._retryAttempt},n)})),1===i?this._recordViewerSessionTelemetry((e=>{e.recordOperationSuccess("AvailableHandshake",null,"",n)})):(this._logger.error(`GTC handshake terminated with code ${i}, last terminated reason: ${vg(this._viewerSessionLastTerminatedReason)}`),lg.RootToolsManager.logExternalForDDL(`GTC handshake terminated with code ${i},`,this._viewerSessionLastTerminatedReason.toString()),this._recordViewerSessionTelemetry((e=>{e.recordOperationFailure("AvailableHandshake",{reason:i},"",n)}))),this._terminateAvailableHandshake=null,this.event("controlAvailableHandshake").raise(t,e,1===i?5:6,i),n&&n!==t&&this._logger.warn(`AvailableSeries: Got handshake from another series - expected: ${t}, received: ${n}`),this._availableAckTimer&&(clearTimeout(this._availableAckTimer),this._availableAckTimer=null),this._delayedSendHandshakeTimer&&(clearTimeout(this._delayedSendHandshakeTimer),this._delayedSendHandshakeTimer=null),this._retryAttempt=0}}_waitForAvailableAck(e){this._logger.info("_waitForAvailableAck()"),this._availableAckTimer=window.setTimeout((()=>{this._logger.warn(`No Ack received for Available message from attempt=${this._retryAttempt}`),this._availableAckTimer=null;const t=this._getSharerDataSourceId();if(this._retryAttempt<=6)t>=0?(this._logger.info(`Re-sending Available message handshakeId: ${t}:${e}`),this.event("controlAvailableHandshake").raise(e,t,2),this._sendRequest({action:0,terminatedReason:0,handshakeId:e},t)):this._logger.warn(`_waitForAvailableAck() - sharer: ${Ae(this._sharerParticipant?.id)} has no data channel, retrying later`),this._waitForAvailableAck(e);else if(this._logger.error("Reached Available retry limit! Control capability will be false"),this._terminateAvailableHandshake)this._terminateAvailableHandshake(5);else{const e={reason:4,detail:JSON.stringify({sourceId:t,errorMsg:`Timed out after ${this._retryAttempt} tries`})};this.event("sharingControlError").raise(e)}}),2e3*++this._retryAttempt)}requestControl(){return this._enabled?this._isDataChannelActive()?0!==this.controlState?Promise.reject(new Error(`requestControl called in bad controlState=${fg(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?Promise.reject(new Error("request control promise has not been resolved yet while requesting control")):this._terminateControlPromise?Promise.reject(new Error("terminate control promise has not been resolved yet while requesting control")):this._requestControl():Promise.reject(new Error("requestControl unexpected null sharer")):Promise.reject(new Error("requestControl when not viewing")):Promise.reject(new Error("requestControl when data channel not active")):Promise.reject(new Error("requestControl when feature not enabled"))}_requestControl(){this._logger.info(`_requestControl(), controlState: ${this.controlState}`),this._requestControlPromise=Si();const e=()=>{this._requestControlPromise=null};this._requestControlPromise.promise.then(e,e);const t=this._getSharerDataSourceId();if(!this._sendRequest({action:1,terminatedReason:0},t)){const e={inControl:!1,id:dg,terminatedReason:7};return this._requestControlPromise.reject(new Error),this._logger.error("_requestControl(): failed to send the request."),Promise.reject(new Error(JSON.stringify({controlInfo:e,details:""})))}return this._recordViewerSessionTelemetry((e=>e.recordOperation("ControlRequest",""))),this.controlState=1,this._requestControlTimer=window.setTimeout((()=>{if(1===this.controlState){this.controlState=0,this._logger.warn("No response to control request - canceling"),this._sendRequest({action:2,terminatedReason:2},t)||this._logger.error("Failed to send the cancel control request");const e={inControl:!1,id:dg,terminatedReason:2};this._recordViewerSessionTelemetry((e=>{e.recordOperationTimeout("ControlRequest",null)})),this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:e,details:"we did not get any response to the control - terminating control"}))):this._logger.error("Unexpected, no promise could be resolved - controlState=RequestSent")}else this._requestControlPromise?this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:void 0,details:"request control - times out in bad state - do nothing"}))):this._logger.error(`Unexpected, no promise could be resolved - controlState=${fg(this.controlState)}`);this._requestControlTimer=null}),3e4),this._requestControlPromise.promise}_cancelRequestControlTimer(){this._requestControlTimer&&(this._requestControlPromise&&this._requestControlPromise.reject(new Error("cancelled by _cancelRequestControlTimer")),clearTimeout(this._requestControlTimer),this._requestControlTimer=null)}cancelControl(){return this._enabled?this._isDataChannelActive()?1!==this.controlState?Promise.reject(new Error(`cancelControl called in bad state=${fg(this.controlState)}`)):this._isViewing()?this._sharerParticipant?this._requestControlPromise?this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while cancelling control")):this._cancelControl():Promise.reject(new Error("Request control promise has been resolved while cancelling control")):Promise.reject(new Error("cancelControl unexpected null sharer")):Promise.reject(new Error("cancelControl when not viewing")):Promise.reject(new Error("cancelControl when data channel not active")):Promise.reject(new Error("cancelControl when feature not enabled"))}_cancelControl(){this._logger.info("_cancelControl()");const e=this._getSharerDataSourceId();if(1!==this.controlState)return Promise.reject(new Error("Cancel control - in bad state - do nothing"));if(this._cancelRequestControlTimer(),this.controlState=0,this._logger.info("Viewer cancels the control"),!this._sendRequest({action:2,terminatedReason:8},e))return Promise.reject(new Error("Failed to send cancel control request"));{const e={inControl:!1,id:dg,terminatedReason:8};this._recordViewerSessionTelemetry((t=>{t.recordOperationFailure("ControlRequest",{reason:vg(e.terminatedReason)})})),this._requestControlPromise.reject(new Error(JSON.stringify({controlInfo:e,details:""})))}return new Promise(((e,t)=>{e()}))}acceptControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while accepting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while accepting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while accepting control")):this._acceptControlRequest():Promise.reject(new Error("acceptControlRequest when not sharing")):Promise.reject(new Error("acceptControlRequest while no control request pending")):Promise.reject(new Error("acceptControlRequest when data channel not active")):Promise.reject(new Error("acceptControlRequest when feature not enabled"))}_acceptControlRequest(){this._logger.info("_acceptControlRequest()"),this._acceptControlPromise=Si();const e=()=>{this._acceptControlPromise=null};if(this._acceptControlPromise.promise.then(e,e),this._controllerParticipant){this._logger.warn("_acceptControlRequest called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const e=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},e)||this._logger.error("Failed to send the terminateNoAck request"),this._resetControllerParticipant()}const t=this._getDataSourceIdForParticipantLeg(this._controlRequest),i=this._controlRequest.participant.id;return this._sendControlAcceptRequest(t)?(this._resetControllerParticipant(this._controlRequest),this._clearControlRequest(),this.controlState=2,this._acceptControlTimer=window.setTimeout((()=>{if(2===this.controlState){this.controlState=0,this._resetControllerParticipant(),this._recordSharerSessionTelemetry((e=>{e.recordOperationTimeout("ControlRequest",{participantId:t},String(t))})),this._logger.error("No ack received when accepting control request - terminating control"),this._sendRequest({action:7,terminatedReason:4},t)||this._logger.error("Failed to send the TerminateNoAck request");const e={inControl:!1,id:i,terminatedReason:4};this.event("sharingControlChanged").raise(e),this._acceptControlPromise?this._acceptControlPromise.reject(new Error("No ack received when accept control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")}else this._acceptControlPromise?this._acceptControlPromise.reject(new Error("accept control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${fg(this.controlState)}`);this._acceptControlTimer=null}),cg),this._acceptControlPromise.promise):(this._logger.error("Failed to send the accept control request"),this._acceptControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the accept control request!")))}_sendControlAcceptRequest(e){const t=this._sendRequest({action:3,terminatedReason:0},e);return this._recordSharerSessionTelemetry((t=>{t.updateOperationData("ControlRequest",{status:"accepting",participantId:e},null,String(e))})),t}_sendControlRejectRequest(e,t){const i=this._sendRequest({action:4,terminatedReason:e},t);return this._recordSharerSessionTelemetry((i=>{i.recordOperationFailure("ControlRequest",{participantId:t,reason:vg(e)},String(t))})),i}_cancelAcceptControlTimer(){this._acceptControlTimer&&(this._acceptControlPromise&&this._acceptControlPromise.reject(new Error("cancelled by _cancelAcceptControlTimer")),clearTimeout(this._acceptControlTimer),this._acceptControlTimer=null)}denyControlRequest(){return this._enabled?this._isDataChannelActive()?this._controlRequest?this._isSharing()?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while denying control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while denying control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while denying control")):this._denyControlRequest():Promise.reject(new Error("denyControlRequest when not sharing")):Promise.reject(new Error("denyControlRequest while no control request pending")):Promise.reject(new Error("denyControlRequest when data channel not active")):Promise.reject(new Error("denyControlRequest when feature not enabled"))}_denyControlRequest(){this._logger.info("_denyControlRequest()");const e=this._getDataSourceIdForParticipantLeg(this._controlRequest);return this._clearControlRequest(),this._sendControlRejectRequest(1,e)?Promise.resolve():Promise.reject(new Error("Failed to send the deny control requst"))}grantControl(e){return this._enabled?this._isDataChannelActive()?this._controlRequest?Promise.reject(new Error("grantControl called while control request pending")):this._isSharing()?e?this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while granting control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while granting control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while granting control")):this._grantControl(e):Promise.reject(new Error("grantControl null participant")):Promise.reject(new Error("grantControl when not sharing")):Promise.reject(new Error("grantControl when data channel not active")):Promise.reject(new Error("grantControl when feature not enabled"))}_grantControl(e){this._logger.info("_grantControl()"),this._grantControlPromise=Si();const t=()=>{this._grantControlPromise=null};if(this._grantControlPromise.promise.then(t,t),3===this.controlState){if(this._controllerParticipant.participant===e)return this._logger.warn("_grantControl called for participant who already has control"),this._grantControlPromise.resolve(),new Promise(((e,t)=>{e()}));{this._logger.warn("_grantControl called while another participant already has control - terminating control"),this._teardownSharerRemoteControl();const e=this._getDataSourceIdForParticipantLeg(this._controllerParticipant);this._sendRequest({action:7,terminatedReason:5},e)||this._logger.error("Failed to send the terminateNoAck request")}}const i=this._mapParticipantToSourceId(e),n=this._sendRequest({action:6,terminatedReason:0},i);if(this._recordSharerSessionTelemetry((e=>{e.recordOperation("GiveControl",null)})),!n)return this._logger.error("Failed to send the grant control request"),this._grantControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));const r=this._getParticipantIdForDataSourceId(e,i);return this._resetControllerParticipant({participant:e,participantState:e.state,participantId:r}),this.controlState=2,this._grantControlTimer=window.setTimeout((()=>{2===this.controlState?(this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when granting control - terminating control"),this._sendRequest({action:7,terminatedReason:4},i)||this._logger.error("Failed to send the terminateNoAck request"),this._recordSharerSessionTelemetry((e=>{e.recordOperationTimeout("GiveControl",null)})),this._grantControlPromise?this._grantControlPromise.reject(new Error("No ack received when granting control - terminating control")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForControlAck")):this._grantControlPromise?this._grantControlPromise.reject(new Error("Grant control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${fg(this.controlState)}`),this._grantControlTimer=null}),cg),this._grantControlPromise.promise}_cancelGrantControlTimer(){this._grantControlTimer&&(this._grantControlPromise&&this._grantControlPromise.reject(new Error("cancelled by _cancelGrantControlTimer")),clearTimeout(this._grantControlTimer),this._grantControlTimer=null)}_mapParticipantToSourceId(e){return this._dataChannelAdapter.isActive()?Ld(e,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getParticipantsDataSourceIds(e){const t=[];try{if(e?.endpoints?.endpointDetails){if(1===e.endpoints.endpointDetails.length){const i=e.endpoints.endpointDetails[0];if(!i?.mediaStreams)return t.push(_n),t}for(const i of e.endpoints.endpointDetails)if(i?.mediaStreams)for(const e of i.mediaStreams)if(3===kd(e.type)){if(t.push(e.sourceId),t.length>=8)return this._logger.error("Excessive amount of data streams"),t;break}}}catch(e){this._logger.error(`_getParticipantsDataSourceIds caught exception error=${e}`)}return t}_getParticipantIdForDataSourceId(e,t){return xd(e,3,t)}_getDataSourceIdForParticipantId(e,t){return this._dataChannelAdapter.isActive()?function(e,t,i){if(!e||!e.endpoints)return-1;const n=e.endpoints.endpointDetails.find((e=>e?.participantId===t));if(!n)return Ld(e,i);if(!n.mediaStreams)return Ld(e,i);const r=n.mediaStreams.find((({type:e})=>kd(e)===i));return r?r.sourceId:-1}(e,t,3):(this._logger.error("Null data channel cannot map participant to source id"),-1)}_getDataSourceIdForParticipantLeg(e){return this._getDataSourceIdForParticipantId(e.participant,e.participantId)}_getSharerDataSourceId(){const e=Ud(this._sharerParticipant);return e?this._getDataSourceIdForParticipantId(this._sharerParticipant,e):(this._logger.warn("Unable to identify the sharer participantId, falling back to first data channel"),this._mapParticipantToSourceId(this._sharerParticipant))}terminateControl(){if(this._isViewing()){if(4!==this.controlState)return Promise.reject(new Error("terminateControl called while not in control"));if(!this._sharerParticipant)return Promise.reject(new Error("terminateControl called but _sharerParticipant is null"))}else{if(!this._isSharing())return Promise.reject(new Error("terminateControl called but not sharing nor viewing"));if(!this._controllerParticipant)return Promise.reject(new Error("terminateControl called but controllerParticipant is null"))}return this._requestControlPromise?Promise.reject(new Error("Request control promise has not been resolved yet while terminating control")):this._acceptControlPromise?Promise.reject(new Error("Accept control promise has not been resolved yet while terminating control")):this._grantControlPromise?Promise.reject(new Error("Grant control promise has not been resolved yet while terminating control")):this._terminateControlPromise?Promise.reject(new Error("Terminate control promise has not been resolved yet while terminating control")):this._terminateControl()}_terminateControl(e=!0){this._logger.info("_terminateControl()"),this._terminateControlPromise=Si();const t=()=>{this._terminateControlPromise=null};this._terminateControlPromise.promise.then(t,t);let i=0;const n=e?8:7;let r,a;if(this._isViewing()){if(4!==this.controlState)return this._logger.error("Local viewer called terminateControl when not controlling"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local viewer called terminateControl when not controlling"));this._teardownViewerRemoteControl(),i=6,r=this._getSharerDataSourceId(),a=dg,this._logger.info(`Terminating remote control reason: ${i},  recipient: ${r}, controllerId: ${a}`)}else{if(3!==this.controlState||!this._controllerParticipant)return this._logger.error("Local sharer called terminateControl when no one is in control"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Local sharer called terminateControl when no one is in control"));this._teardownSharerRemoteControl(),i=5,r=this._getDataSourceIdForParticipantLeg(this._controllerParticipant),a=this._controllerParticipant.participant.id,this._logger.info(`Terminating control on the sharer side, reason: ${i}, recipient: ${r}, controllerId: ${a}`)}if(!this._sendRequest({action:n,terminatedReason:i},r)){if(e)return this._logger.error("Failed to send the terminate control request"),this._terminateControlPromise.reject(new Error),Promise.reject(new Error("Failed to send the grant control request!"));this._logger.error("Failed to send the terminateNoAck request")}this.controlState=e?5:0;const s={inControl:!1,id:a,terminatedReason:i};return this._logger.info(`raising event sharingControlChanged reason=${s.terminatedReason} controlState=${this.controlState}`),this.event("sharingControlChanged").raise(s),e?(this._terminateControlTimer=window.setTimeout((()=>{5===this.controlState?(this.controlState=0,this._resetControllerParticipant(),this._logger.error("No ack received when terminating control - resending terminate request"),this._sendRequest({action:7,terminatedReason:4},r)||this._logger.error("Failed to send the terminateNoAck request"),this._terminateControlPromise?this._terminateControlPromise.reject(new Error("No ack received when terminating control - resending terminate request")):this._logger.error("Unexpected, no promise could be resolved - controlState=WaitingForTerminateAck")):this._terminateControlPromise?this._terminateControlPromise.reject(new Error("terminate control - times out in bad state - do nothing")):this._logger.error(`Unexpected, no promise could be resolved - controlState=${fg(this.controlState)}`),this._terminateControlTimer=null}),cg),this._terminateControlPromise.promise):(this._terminateControlPromise.resolve(),new Promise(((e,t)=>{e()})))}_cancelTerminateControlTimer(){this._terminateControlTimer&&(this._terminateControlPromise&&this._terminateControlPromise.reject(new Error("cancelled by _cancelTerminateControlTimer")),clearTimeout(this._terminateControlTimer),this._terminateControlTimer=null,this._logger.info("_cancelTerminateControlTimer()"))}_disposeControlCapturer(e=Te()){this._logger.info(`_disposeControlCapturer causeId: ${e}`),this._clearCapturerEventSubscriptions(),this._controlCapturer&&(this._controlCapturer.dispose(e),this._controlCapturer=null)}dispose(e){this._logger.info(`dispose causeId: ${e}`),this._dataChannelAdapter.dispose(e),this._resetControlState(),this._disposeRenderer(e),this._cancelRequestControlTimer(),this._cancelAcceptControlTimer(),this._cancelGrantControlTimer(),this._cancelTerminateControlTimer(),this._terminateAvailableHandshake&&this._terminateAvailableHandshake(2),this._call=null,this._resetParticipantSubscriptions(),this._finalizeViewerSessionTelemetry("Shutdown"),this._finalizeSharerSessionTelemetry("Shutdown"),super.dispose(e)}};function mg(e){switch(e){case 0:return"Available";case 1:return"ControlRequest";case 2:return"CancelControlRequest";case 3:return"AcceptRequest";case 4:return"RejectRequest";case 5:return"Ack";case 6:return"GiveControl";case 7:return"TerminateNoAck";case 8:return"Terminate";case 9:return"AvailableAck";case 10:return"AvailableNack";case 11:return"RenderedAtViewer";default:return"Unknown"}}function fg(e){switch(e){case 0:return"None";case 1:return"RequestSent";case 2:return"WaitingForControlAck";case 3:return"RemoteControlling";case 4:return"LocalControlling";case 5:return"WaitingForTerminateAck";default:return"Unknown"}}function vg(e){switch(e){case 0:return"None";case 1:return"SharerDenied";case 2:return"SharerNoResponse";case 3:return"SharerBusy";case 4:return"AckTimeout";case 5:return"SharerTerminated";case 6:return"ViewerTerminated";case 7:return"DataChannelError";case 8:return"ViewerCancelled";case 9:return"SharerControlDisabled";case 10:return"UnknownSender";default:return"Unknown"}}var Sg=(e=>(e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT",e[e.MIDDLE=2]="MIDDLE",e[e.BACK=3]="BACK",e[e.FORWARD=4]="FORWARD",e))(Sg||{}),yg=(e=>(e[e.SCAN_CODE=0]="SCAN_CODE",e[e.VIRTUAL_KEY=1]="VIRTUAL_KEY",e[e.RECOGNITION_INPUT=2]="RECOGNITION_INPUT",e))(yg||{}),Cg=class{constructor(e){this.logger=e}toEdgeControlMouseEvent(e){let t;switch(e.type){case 0:return{event:this.toMouseMoveEvent(e),apiName:"injectMouseMoveEvent"};case 1:return{event:this.toMouseWheelEvent(e),apiName:"injectMouseWheelEvent"};case 2:return{event:this.toMouseButtonPressedEvent(e),apiName:"injectMouseButtonEvent"};default:throw t=`Uncovered mouse control event type. Event: ${e}`,this.logger.error(t),Error(t)}}toEdgeControlKeyboardEvent(e){return{event:{repeat:e.repeat,keyUp:e.keyUp,codeType:yg[e.codeType],keyCode:e.code},apiName:"injectKeyEvent"}}toMouseMoveEvent(e){return{xPos:e.xPos,yPos:e.yPos}}toMouseWheelEvent(e){return{wheelButtonDown:e.wheelButtonDown,wheelRotation:e.wheelRotation}}toMouseButtonPressedEvent(e){return{xPos:e.xPos,yPos:e.yPos,button:Sg[e.buttonType],buttonDown:e.buttonDown}}};async function _g(e,t,i){return new Promise(((n,r)=>{const a=Buffer.from(e,"base64"),s=document.createElement("canvas").getContext("2d"),o=new Blob([a],{type:"image/png"});let l=new Image;l.onload=()=>{s.drawImage(l,0,0,l.width,l.height,0,0,t,i);const e=s.getImageData(0,0,t,i);window.URL.revokeObjectURL(l.src),l=null,n(Array.from(e.data))},l.onerror=e=>{r(e)},l.src=window.URL.createObjectURL(o)}))}var Eg="ncbjelpjchkpbikbpkcchkhkblodoama",Tg=class{constructor(e){this.logger=e}async sendInjectInputEventMessage(e,t){return this.logger.info("EdgeControlInjectorApi - sendInjectInputEventMessage"),new Promise(((i,n)=>{window.top.chrome.runtime.sendMessage(Eg,{api:e,deviceId:this.virtualInputDeviceId,event:t},(e=>{e.error?n(e.error.message):i(0)}))}))}async createInputDeviceId(e,t,i){this.virtualInputDeviceId&&this.logger.warn("EdgeControlInjectorApi - createInputDeviceId virtual input already exists.");try{this.virtualInputDeviceId=await this.sendCreateInputDeviceMessage(e,i)}catch(e){this.logger.error(`EdgeControlInjectorApi - createInputDevice failed, error: ${JSON.stringify(e)}`),t()}}async sendSetLocalUserAvatarMessage(e){const t=await this.generateAvatarBitmap(e);return new Promise(((e,i)=>{const n=window.top;t&&n.chrome.runtime.sendMessage(Eg,{api:"setLocalUserAvatar",avatarBitmap:t},(t=>{t.error?i(t.error.message):e()}))}))}async sendCloseVirtualInputDeviceMessage(){const e=this.virtualInputDeviceId;return e?(this.logger.info("EdgeControlInjectorApi - sendCloseVirtualInputDeviceMessage called"),new Promise(((t,i)=>{const n=window.top;n.chrome.runtime.sendMessage(Eg,{api:"closeInputDevice",deviceId:e},(e=>{e?e.error?i(e.error.message):(this.virtualInputDeviceId=null,t(e.deviceId)):i(n.chrome.runtime.lastError.message)}))}))):(this.logger.info("EdgeControlInjectorApi - VirtualInputDevice does not exists, nothing to close."),Promise.resolve())}async sendCreateInputDeviceMessage(e,t){this.logger.info("EdgeControlInjectorApi - sendCreateInputDeviceMessage called");const i=await this.generateAvatarBitmap(t);return new Promise(((t,n)=>{const r=window.top,a=e=>{e?e.deviceId?t(e.deviceId):e.error?n(e.error.message):n("Error: Unexpected response from API"):n(r.chrome.runtime.lastError.message)};i?r.chrome.runtime.sendMessage(Eg,{api:"createInputDevice",mediaStreamTrackId:e,avatarBitmap:i},a):r.chrome.runtime.sendMessage(Eg,{api:"createInputDevice",mediaStreamTrackId:e},a)}))}async generateAvatarBitmap(e){if(!e)return null;try{const t=32;return{width:t,height:t,data:await _g(e,t,t)}}catch(e){return this.logger.error(`EdgeControlInjectorApi - generateAvatarBitmap error: ${JSON.stringify(e)}, continue without avatar.`),null}}};var bg=class{constructor(e,t,i){this.logger=e,this.sharingTrackId=t,this.onInitErrorCallback=i,this.images=new Map,this.controlEventConverter=new Cg(e),this.edgeApi=new Tg(this.logger)}showVirtualCursor(e,t){if(this.logger.info(`EdgeControlInjector - showVirtualCursor, id: ${e} sharingTrackId: ${this.sharingTrackId}`),t){this.edgeApi.createInputDeviceId(this.sharingTrackId,this.onInitErrorCallback,this.images[e]);const t=this.images[0];t?this.edgeApi.sendSetLocalUserAvatarMessage(t):this.logger.error("EdgeControllerInjector - local avatar is missing, continue without local avatar")}else this.edgeApi.sendCloseVirtualInputDeviceMessage()}setAvatar(e,t){this.logger.info(`${e} EdgeControlInjector - setAvatar, id: ${e}, data: ${JSON.stringify(t)}`),this.images[e]=t}async injectMouseEvent(e,t){this.logger.info(`${e} EdgeControlInjector - injectMouseEvent ${JSON.stringify(t)}`);const i=this.controlEventConverter.toEdgeControlMouseEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}async injectKeyboardEvent(e,t){const i=this.controlEventConverter.toEdgeControlKeyboardEvent(t);return this.edgeApi.sendInjectInputEventMessage(i.apiName,i.event)}injectClipboardText(e,t){return this.logger.info(`${e} EdgeControlInjector - injectClipboardText is unimplemented`),Promise.resolve(0)}dispose(e){this.logger.info("EdgeControlInjector - dispose"),this.edgeApi.sendCloseVirtualInputDeviceMessage()}},Ig=class{constructor(e){this.logger=e,this.activeSourceId=0,this.edgeVirtualInputSupported=!1,this.pendingPointerImages=new Map,this.logger.info("ControlInjectorAdapter"),"EdgeAnaheim"===ri().name&&async function(e){return new Promise(((t,i)=>{e.info("EdgeControlInjectorApi - sendIsVirtualInputSupportedMessage");const n=window.top;n.chrome.runtime.sendMessage(Eg,{api:"isVirtualInputSupported"},(e=>{e?e.error?t(e.error.message):t(e):i(n.chrome.runtime.lastError?.message)}))}))}(e).then((t=>{this.edgeVirtualInputSupported=t,e.info(`ControlInjectorAdapter - Edge supports virtual input device: ${JSON.stringify(this.edgeVirtualInputSupported)}`)})).catch((t=>{e.info(`ControlInjectorAdapter - Edge IsVirtualInputSupported: ${JSON.stringify(t)}`)}))}enableInjector(e){if(this.injector)return this.logger.error("Control injector already present"),Promise.reject();if("EdgeAnaheim"===ri().name){if(!this.edgeVirtualInputSupported)return this.logger.info("ControlInjectorAdapter - Edge doesn't support give control"),Promise.reject();const t=()=>(this.disableInjector(),this.logger.error("ControlInjectorAdapter - An error occured, control injector is disabled."),Promise.reject());this.injector=new bg(this.logger,e,t),this.logger.info("ControlInjectorAdapter - Edge ControlInjector created")}else window.ControlInjector&&(this.injector=window.ControlInjector(e),this.logger.info("ControlInjectorAdapter - Window ControlInjector created"));return this.pendingPointerImages.forEach(((e,t)=>{this.injector.setAvatar(t,e)})),this.pendingPointerImages.clear(),Promise.resolve()}disableInjector(){return this.injector?(this.logger.info("ControlInjectorAdapter - ControlInjector disposed"),this.injector.dispose(),this.injector=null,Promise.resolve()):(this.logger.error("Control injector not present"),Promise.reject())}setPointerImage(e,t){return this.injector?new Promise((i=>{this.injector.setAvatar(e,t),i()})):(this.pendingPointerImages.set(e,t),Promise.resolve())}showVirtualCursor(e){return this.logger.info(`ControlInjectorAdapter - showVirtualCursor ${e} ${this.activeSourceId}`),this.injector?new Promise((t=>{e?(this.activeSourceId&&this.injector.showVirtualCursor(this.activeSourceId,!1),this.injector.showVirtualCursor(e,!0),this.activeSourceId=e):this.activeSourceId&&(this.injector.showVirtualCursor(this.activeSourceId,!1),this.activeSourceId=0),t()})):(this.logger.error("Control injector not present"),Promise.reject())}injectRawInput(e,t){if(!this.injector)return this.logger.error("Control injector not present"),Promise.reject();const i=this.injector;return new Promise(((n,r)=>{let a,s;const o=jp.decodeEventType(e);switch(o){case 1:a=jp.decodeMouseEvent(e),i.injectMouseEvent(t,a).then((e=>0===e?n():r()));break;case 0:s=jp.decodeKeyboardEvent(e),i.injectKeyboardEvent(t,s).then((e=>0===e?n():r()));break;default:this.logger.error(`Invalid event type in raw input: ${o}`),r()}}))}canBeEnabled(){return"EdgeAnaheim"===ri().name?this.edgeVirtualInputSupported:!!window.ControlInjector}},wg=class{constructor(e){this.logger=e,this.logger.info("RendererAdapter")}getTarget(e){return e.target}subscribeVideoSizeChangedEvent(e,t){const i=e;return i.streamSize&&t(i.streamSize.width,i.streamSize.height),i.renderer.on("onVideoSizeChanged",t)}subscribeRenderStartedEvent(e,t){return e.renderer.on("onVideoStarted",((e,i)=>t()))}};var Rg=class extends We{constructor(e,t){super(e),this.logger=e,this._call=t}isActive(){return!(!this.protocolSendFunc||!this.controlSendFunc)}sendProtocolMessage(e,t){return this.protocolSendFunc?this.protocolSendFunc(e,t):(this.logger.error("Cannot send protocol message, ProtocolHandler hasn't started"),Promise.resolve())}sendControlMessage(e,t){return this.controlSendFunc?this.controlSendFunc(e,t):(this.logger.error("Cannot send control message, ControlHandler hasn't started"),Promise.resolve())}getProtocolHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ProtocolHandler started for ${e}`),this.protocolSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ProtocolHandler stopped for ${e}`);const t=this.isActive();this.protocolSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(1===e){const e=JSON.parse(function(e){return String.fromCharCode.apply(null,e)}(t)),n=this._call.mapDataChannelSourceIdToParticipant(i);let r;return n&&(r=xd(n,3,i)),this.event("protocolMessage").raise(e.message,n,r,i)}}}}getControlHandler(){return{onStarted:async(e,t)=>{this.logger.info(`ControlHandler started for ${e}`),this.controlSendFunc=t,this.isActive()&&this.event("stateChange").raise(!0)},onStopped:async e=>{this.logger.info(`ControlHandler stopped for ${e}`);const t=this.isActive();this.controlSendFunc=null,t&&this.event("stateChange").raise(!1)},onDataReceived:async(e,t,i)=>{if(2===e)return this.event("controlMessage").raise(t,i)}}}},Ag=class extends gg{constructor(e,t,i,n,r){const a={};try{const e=r.getEcsConfig("SkypeCalling","gtcHandshakeSendDelay");e&&(a.handshakeSendDelay=JSON.parse(e))}catch(t){e.error(`Failed to parse ecs config gtcAvailableAckDelay: ${Be(t)}`)}super(e.createChild("ScreenSharingControl"),i,n,a),this.dataChannel=t;const s=new Ig(this._logger),o=new wg(this._logger),l=new Rg(this._logger,i);this.setAdapters(s,o,l)}setupDataHandlers(){this.dataChannel.addHandler(1,this.getProtocolHandler()),this.dataChannel.addHandler(2,this.getControlHandler())}startOrStopControlForViewer(e,t,i){e&&"nonInteractive"!==i?.appliedInteractivityLevel?t&&0===this.role&&this.initControlForViewer(t):2===this.role&&this.shutdownControlForViewer()}getProtocolHandler(){return this._dataChannelAdapter.getProtocolHandler()}getControlHandler(){return this._dataChannelAdapter.getControlHandler()}};function Pg(e){switch(e){case 1:return"specified";case 0:return"all";case 3:return"attendees";case 2:return"presenters";case 4:return"self";default:return"none"}}var Mg={};h(Mg,{addReceiveDirectionality:()=>Kg,allowDataChannel:()=>vm,allowProvisionalAnswer:()=>Em,areNegotiatedDirectionsAcceptable:()=>Zg,areNegotiatedDirectionsFulfilled:()=>Xg,areSendDirectionsFulfilled:()=>em,canUseWebrtc1_0:()=>fm,convertToCodecInfo:()=>_m,getAllowedCodecs:()=>Sm,getSendMediaModalities:()=>am,getSimulcastConfigForMediaType:()=>Cm,getSrtpInfo:()=>tm,hasReceiveDirectionality:()=>qg,hasSendDirectionality:()=>Wg,invertModalities:()=>jg,ipAddressConverter:()=>bm,ipV4RegExp:()=>Vg,ipV6RegExp:()=>Hg,ipv4AddressConverter:()=>wm,ipv6AddressConverter:()=>Im,isOnHold:()=>Jg,isSendModalityAdded:()=>rm,isVersionGreaterOrEqual:()=>ym,makeReinvitelessContext:()=>Rm,mediaTypeToModality:()=>lm,mergeSendModalities:()=>sm,modalityToMediaType:()=>om,negotiateDirectionality:()=>Gg,negotiateModalities:()=>Yg,parseCandidateString:()=>nm,preferSdesSrtp:()=>mm,printMediaStream:()=>Tm,removeChangedSendDirection:()=>im,removeSendDirectionality:()=>zg,scrubConstraints:()=>gm,scrubDevices:()=>pm,scrubObjectExcludingFields:()=>um,scrubObjectFields:()=>dm,scrubSelectedDevices:()=>hm,sendStreamsToModalities:()=>cm});var kg,Dg,Og="undefined"!=typeof navigator&&void 0!==navigator.mediaDevices?.getUserMedia,Ng=(e=>(e.AVD="43",e.Citrix="44",e.VMware="45",e))(Ng||{});function Lg(e=""){const t=e.match(new RegExp("^SkypeSpaces/(\\d+)/"));t?.length&&Object.values(Ng).includes(t[1])&&(Dg=t[1]),"undefined"!=typeof window&&"undefined"!=typeof navigator&&(void 0!==navigator.webkitGetUserMedia&&"undefined"!=typeof webkitRTCPeerConnection&&xg()?(window.RTCPeerConnection=webkitRTCPeerConnection,navigator.getUserMedia=(e,t,i)=>{const n=e=>{e?.deviceId?.exact&&(e.mandatory||(e.mandatory={}),e.mandatory.sourceId=e.deviceId.exact,delete e.deviceId)};return e&&(n(e.audio),n(e.video)),navigator.webkitGetUserMedia(e,t,i)}):Og&&Fg())}function xg(){return!!Dg}function Fg(){navigator.getUserMedia=function(e,t,i){return navigator.mediaDevices.getUserMedia(e).then(t).catch(i)}}"undefined"!=typeof window&&"undefined"!=typeof navigator&&(kg=window,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,window.MediaStream=window.MediaStream||window.webkitMediaStream||window.mozMediaStream||window.msMediaStream,window.AudioContext=window.AudioContext||window.webkitAudioContext);var Ug={window:kg},Bg=class e extends qe{constructor(e){super(),this.isAudioOutputSelectionSupportedValue=!1,e.on("configUpdated",(()=>this.updateConfig())),this.updateConfig(),this.isRollbackSupported()}get isAudioOutputSelectionSupported(){return this.isAudioOutputSelectionSupportedValue}get isBrowserRollbackSupported(){return this.isRollbackSupportedValue}static hasApplyConstraints(){return void 0!==MediaStreamTrack.prototype.applyConstraints}static hasPermissionsApi(){return void 0!==navigator.permissions&&"Firefox"!==ri().name}static get hardwareConcurrency(){return window.navigator.hardwareConcurrency}static get unmaskedGlRenderer(){if(this.renderer)return this.renderer===Qe.MEDIA_ERROR.webGlRendererError?void 0:this.renderer;try{const e=document.createElement("canvas").getContext("webgl"),t=e?.getExtension("WEBGL_debug_renderer_info"),i=t&&e.getParameter(t.UNMASKED_RENDERER_WEBGL);return this.renderer=i,i}catch{return void(this.renderer=Qe.MEDIA_ERROR.webGlRendererError)}}async isRollbackSupported(){let e;try{if(e=Ug.window.RTCPeerConnection&&new Ug.window.RTCPeerConnection({sdpSemantics:"unified-plan"}),e){const t=await e.createOffer();await e.setLocalDescription(t),await e.setLocalDescription({type:"rollback"}),this.isRollbackSupportedValue=!0}}catch(e){this.isRollbackSupportedValue=!1}finally{e?.close()}}static async isCodecsSupported(e){const t={format:"annexb"},i=["no-preference","prefer-software","prefer-hardware"],n=[];for(const r of e)for(const e of i){const i=await(window.VideoEncoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t,width:1280,height:720})),a=await(window.VideoDecoder?.isConfigSupported({codec:r,hardwareAcceleration:e,hevc:t}));if(i||a){const e={name:r,mode:i?.config.hardwareAcceleration,encode:i?.supported,decode:a?.supported};n.push(e)}}return n}static async hasH264CodecSupport(e){const t="v=0\no=- 596983 0 IN IP4 127.0.0.1\ns=session\nc=IN IP4 0.0.0.0\nt=0 0\na=msid-semantic: WMS *\nm=video 3480 RTP/SAVPF 107 99\na=rtpmap:107 H264/90000\na=rtpmap:99 rtx/90000\na=fmtp:107 max-fs=240;max-mbps=3600;max-br=208;max-fps=1500;profile-level-id=42C02A;packetization-mode=1\na=fmtp:99 apt=107\na=setup:actpass\na=mid:video\na=recvonly\na=rtcp-mux\na=ice-ufrag:CvYq\na=ice-pwd:axsjsa0GOz3kz6TuGvNgJZWO\na=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:82:21:FD:BC:D2:90:41:06:FA:03:FD:12:A2\n",i=Ug.window.RTCPeerConnection&&new Ug.window.RTCPeerConnection;if(!i)return!1;try{return await i.setRemoteDescription({sdp:"v=0\no=- 596983 0 IN IP4 127.0.0.1\ns=session\nc=IN IP4 0.0.0.0\nt=0 0\na=msid-semantic: WMS *\nm=video 3480 RTP/SAVPF 107 99\na=rtpmap:107 H264/90000\na=rtpmap:99 rtx/90000\na=fmtp:107 max-fs=240;max-mbps=3600;max-br=208;max-fps=1500;profile-level-id=42C02A;packetization-mode=1\na=fmtp:99 apt=107\na=setup:actpass\na=mid:video\na=recvonly\na=rtcp-mux\na=ice-ufrag:CvYq\na=ice-pwd:axsjsa0GOz3kz6TuGvNgJZWO\na=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:82:21:FD:BC:D2:90:41:06:FA:03:FD:12:A2\n",type:"offer"}),!0}catch(t){return e.error("H264 not supported",t),!1}finally{try{i.close()}catch(e){}}}static hasMediaApi(){return navigator.getUserMedia&&"undefined"!=typeof RTCPeerConnection}static hasCapabilitiesApi(){return!!Ug.window.RTCRtpReceiver?.getCapabilities}static isAudioOutputSelectionSupportedByBrowser(){return!!Ug.window?.HTMLAudioElement?.prototype.setSinkId}updateConfig(){const t=e.isAudioOutputSelectionSupportedByBrowser();t!==this.isAudioOutputSelectionSupportedValue&&(this.isAudioOutputSelectionSupportedValue=t,this.event("isAudioOutputSelectionSupportedChanged").raise())}static hasUnifiedPlanSupport(){let e;try{e=Ug.window.RTCPeerConnection&&new Ug.window.RTCPeerConnection({sdpSemantics:"unified-plan"})}catch(e){return!1}let t=!1;return e&&(t=!!e.addTransceiver,e.close()),t}static hasEncodedStreamApi(){return!!RTCRtpReceiver.prototype.createEncodedStreams||e.hasScriptTransformApi()}static hasScriptTransformApi(){return!!window.RTCRtpScriptTransform}static isWakeLockSupported(){return!!window.navigator.wakeLock}},Vg=RegExp(/^((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]?)(:[0-9]{1,5})?$/),Hg=RegExp(/^\[?(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|:((:[0-9a-fA-F]{1,4}){1,5}|:)((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,5}([0-9a-fA-F]{1,4})?:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\]?(?::\d{1,5})?$/);function $g(e){switch(e){case Qe.MEDIA_STATE.send:return Qe.MEDIA_STATE.receive;case Qe.MEDIA_STATE.receive:return Qe.MEDIA_STATE.send;default:return e}}function Gg(e,t){const i=Wg(e)&&Wg(t),n=qg(e)&&qg(t);return i&&n?Qe.MEDIA_STATE.sendReceive:i?Qe.MEDIA_STATE.send:n?Qe.MEDIA_STATE.receive:e===Qe.MEDIA_STATE.inactive&&t||e&&t===Qe.MEDIA_STATE.inactive?Qe.MEDIA_STATE.inactive:void 0}function jg(e){const t={},i=$g(e.audio);i&&(t.audio=i);const n=$g(e.video);n&&(t.video=n);const r=$g(e.sharing);r&&(t.sharing=r);const a=$g(e.data);return a&&(t.data=a),t}function zg(e){return e===Qe.MEDIA_STATE.sendReceive?Qe.MEDIA_STATE.receive:void 0}function Wg(e){return e===Qe.MEDIA_STATE.send||e===Qe.MEDIA_STATE.sendReceive}function qg(e){return e===Qe.MEDIA_STATE.receive||e===Qe.MEDIA_STATE.sendReceive}function Kg(e){return qg(e)?e:e===Qe.MEDIA_STATE.send?Qe.MEDIA_STATE.sendReceive:Qe.MEDIA_STATE.receive}function Jg(e){return!(e.audio!==Qe.MEDIA_STATE.inactive||e.video&&e.video!==Qe.MEDIA_STATE.inactive||e.sharing&&e.sharing!==Qe.MEDIA_STATE.inactive)}function Yg(e,t){const i={},n=Gg(e.audio,t.audio);n&&(i.audio=n);const r=Gg(e.video,t.video);r&&(i.video=r);const a=Gg(e.sharing,t.sharing);a&&(i.sharing=a);const s=Gg(e.data,t.data);return s&&(i.data=s),i}function Qg(e,t,i){const n=Wg(e)&&Wg(t)||!Wg(e)&&!Wg(i),r=!i||qg(e)&&qg(t)||!qg(e)&&!qg(i);return n&&r}function Zg(e,t,i){return Qg(e.audio,t.audio,i.audio)&&Qg(e.video,t.video,i.video)&&Qg(e.sharing,t.sharing,i.sharing)&&Qg(e.data,t.data,i.data)}function Xg(e,t){function i(e,t){const i=Wg(e)===Wg(t),n=qg(e)===qg(t)||qg(e)&&!t;return i&&n}return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function em(e,t){const i=(e,t)=>Wg(e)===Wg(t);return i(e.audio,t.audio)&&i(e.video,t.video)&&i(e.sharing,t.sharing)&&i(e.data,t.data)}function tm(e){const t={dtls:!1,sdes:!1};return t.dtls=!!e.fingerprint,e.media.forEach((e=>{t.dtls=t.dtls||!!e.fingerprint,t.sdes=t.sdes||!!e.crypto})),t}function im(e,t){if(!t||at(t))return e;const i={};return Ze(e,((e,n)=>{n===Qe.MODALITY.data?i[n]=function(e,t){return Wg(e)&&!Wg(t)?t:e}(e,t[n]):i[n]=function(e,t){return Wg(e)&&!Wg(t)?zg(e)||t:e}(e,t[n])})),i}function nm(e){const t=(e||"").split(" ");return{component:t[1],protocol:t[2],priority:t[3],ip:t[4],port:t[5],type:t[7]}}function rm(e,t){return!Wg(e)&&Wg(t)}function am(e){return{Audio:Wg(e.audio),Video:Wg(e.video),ScreenShare:Wg(e.sharing),Data:Wg(e.data)}}function sm(e,t){const i=ot(e);return Ze(e,((e,n)=>{const r=om(n);Wg(e)&&!t[r]&&(i[n]=zg(e))})),i}function om(e){switch(e){case"audio":return"Audio";case"video":return"Video";case"sharing":return"ScreenShare";default:return null}}function lm(e){switch(e){case"Audio":return"audio";case"Video":return"video";case"ScreenShare":return"sharing";default:return null}}function cm(e){const t={};return st(e).forEach((i=>t[i]=!!e[i])),t}function dm(e,t,i){if(!e)return e;const n={...e};for(const[r,a]of Object.entries(e))"object"==typeof a?n[r]=dm(a,t):a&&t.includes(r)&&(n[r]=i?i(a):Ae(a));return n}function um(e,t,i){if(!e)return e;const n={...e};for(const[r,a]of Object.entries(e))"object"==typeof a?n[r]=um(a,t):a&&!t.includes(r)&&(n[r]=i?i(a):Ae(a));return n}function hm(e){return e?um(e,[]):e}function pm(e,t){if(!e)return e;const i=dm(e,["deviceId","groupId","guid"]);return dm(i,["label"],(e=>_t(e,t)))}function gm(e){return dm(e,["sourceId","deviceId"])}function mm(e){return!(!e.configProvider.config.webrtcForceSdesForS1||!e.configProvider.config.checkSupportForWebrtc_1_0||e.configProvider.mediaConfig.simulcastSessionEnabled)||(e.config.isPstnCall?e.configProvider.config.preferSdesSrtpPstn:e.configProvider.config.preferSdesSrtp)}function fm(e){return!e||Bg.hasUnifiedPlanSupport()}function vm(e){return!!e.configProvider.mediaConfig.simulcastSessionEnabled&&(e.config.isPstnCall?e.configProvider.config.enableDataChannelPstn:e.configProvider.config.enableDataChannel)}function Sm(e,t){switch(t){case Qe.MEDIA_TYPE.audio:return e.config.allowedAudioCodecs;case Qe.MEDIA_TYPE.video:return e.config.allowedVideoCodecs;default:return[]}}function ym(e,t){const i=t.split(".").map((e=>parseInt(e,10))),n=e.split(".").map((e=>parseInt(e,10)));return n[0]>i[0]||n[0]===i[0]&&n[1]>=i[1]}function Cm(e,t){return"Video"===e?t.config.specCompliantSimulcast?.video:"ScreenShare"===e?t.config.specCompliantSimulcast?.sharing:null}function _m(e){return e.map((e=>{const t=e.mimeType.split("/"),i={codec:t[1]||t[0],rate:e.clockRate};return e.channels&&(i.encoding=e.channels),e.sdpFmtpLine&&(i.fmtpLine=e.sdpFmtpLine),i}))}function Em(e,t=!1){const i=!e.configProvider.config.acceptProvisionalAnswerFromPstnOnly||t;return e.config.isPstnCall?e.configProvider.config.allowProvisionalAnswerPstn&&i:e.configProvider.config.allowProvisionalAnswer}function Tm(e){return`${e?.id}:${JSON.stringify(e?.getTracks().map((e=>e.id)))}}`}function bm(e){try{if(Vg.test(e))return wm(e);if(Hg.test(e))return Im(e)}catch(t){return e}return e}function Im(e){let t,i=e.lastIndexOf("]")+1,n="",r="";i>0?(t=e.substring(0,i),r=e.substring(i)):(t=e,i=t.length);const a=t.lastIndexOf(":");if(t.includes(".")){const e=wm(t.substring(a+1,i-1-a));n=t.substring(0,a+1)+e}else a<t.length-1||":"===t[a-1]&&t.match(/:/g).length<7?n=t.substring(0,a+1)+"x":7===t.match(/:/g).length&&(n=t.substring(0,a)+"0:x");return n?r?n+"]"+r:"["===e.substring(0,1)?(n=n.substring(1),n):n:e}function wm(e){const t=e.substring(0,e.lastIndexOf(".")+1)+"x",i=e.lastIndexOf(":");return i>0?t+e.substring(i):t}function Rm(e,t){const i=(t?e?.maxReinvitelessMediaForVideoMultiparty:e?.maxReinvitelessMediaForVideo1on1)||0,n=(t?e?.maxReinvitelessMediaForVBSSMultiparty:e?.maxReinvitelessMediaForVBSS1on1)||0;return{enabled:i>0||n>0,maxStreamsForModality:{video:i,sharing:n}}}var Am=class extends We{constructor(){super(),this.subs=[]}get streams(){return this.sessionAudioProvider?.streams??[]}get comfortNoiseStream(){return this.sessionAudioProvider?.comfortNoiseStream??null}get active(){return this.sessionAudioProvider?.active??!1}setSessionStreamsProvider(e){this.unsubscribeFromStreamEvents(),this.sessionAudioProvider=e,this.subscribeForStreamEvents(),this.event("onStreamsChanged").raise(),this.event("onActiveStateChanged").raise()}dispose(){super.dispose(),this.unsubscribeFromStreamEvents()}subscribeForStreamEvents(){this.sessionAudioProvider&&this.subs.push(this.sessionAudioProvider.on("onStreamsChanged",(()=>this.event("onStreamsChanged").raise())),this.sessionAudioProvider.on("onStreamSourcesUpdated",(e=>this.event("onStreamSourcesUpdated").raise(e))),this.sessionAudioProvider.on("onActiveStateChanged",(()=>this.event("onActiveStateChanged").raise())))}unsubscribeFromStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},Pm=class extends We{constructor(e,t,i,n,r){super(),this.allowVirtualDeviceInCall=e,this.defaultDeviceManager=t,this.logger=i,this.callStats=n,this.isMediaSending=r,this.stats=[],this.selectedVirtualDevice={camera:void 0,screenshare:void 0},this.subs=[this.defaultDeviceManager.on("onVirtualDevicesChanged",(()=>this.handleRegisteredDeviceChange()))]}get isVirtualDeviceEnabled(){return this.allowVirtualDeviceInCall}selectDevices(e){const t=this.defaultDeviceManager.getRegisteredDevices(),i=t.find((t=>t.id===e.camera)),n=t.find((t=>t.id===e.screenshare));this.logger.info(`Selecting virtual devices, camera: ${i?.id}, screenshare: ${n?.id}`);const r={camera:this.selectedVirtualDevice.camera?.id,screenshare:this.selectedVirtualDevice.screenshare?.id};e.camera!==r.camera||e.screenshare!==r.screenshare?(this.selectedVirtualDevice={camera:i,screenshare:n},this.addToCallStat({type:"VirtualDeviceSelected",payload:this.selectedVirtualDevice}),this.event("onSelectedVirtualDevicesChanged").raise(e,r)):this.logger.info("Virtual Device did not change.")}getSelectedDevices(){return Object.entries(this.selectedVirtualDevice).reduce(((e,[t,i])=>(e[t]=i?.id,e)),{})}getDeviceManager(e){return this.allowVirtualDeviceInCall?this.getDeviceManagersForVirtualDevice(e)[0]:(this.logger.info(`VirtualDevice not enabled, using default DM, type: ${e}`),this.defaultDeviceManager)}getDeviceManagersForVirtualDevice(e){return"Video"===e&&this.selectedVirtualDevice.camera?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.camera.getDeviceManagers()):"ScreenShare"===e&&this.selectedVirtualDevice.screenshare?(this.logger.info(`Using Virtual Device (DM), type: ${e}`),this.selectedVirtualDevice.screenshare.getDeviceManagers()):(this.logger.info(`Using default DM, type: ${e}`),[this.defaultDeviceManager])}getDefaultDeviceManager(){return this.defaultDeviceManager}dispose(){this.stats=[],this.subs.forEach((e=>e.dispose())),super.dispose()}hasDevice(e){return this.defaultDeviceManager.id===e||[...this.selectedVirtualDevice.camera?.getDeviceManagers()??[],...this.selectedVirtualDevice.screenshare?.getDeviceManagers()??[]].some((t=>t?.id===e))}addToCallStat(e){const t=this.stats.push(e);this.callStats.appendCallDeviceManagerInfo({events:JSON.stringify(t)})}handleRegisteredDeviceChange(){const e=this.defaultDeviceManager.getRegisteredDevices(),{camera:t,screenshare:i}=this.selectedVirtualDevice;let n=!1,r=!1;t&&(n=e.some((e=>e.id===t.id)),this.logger.info(`Selected camera(${t.id}) in call, isCameraValid:${n}`)),i&&(r=e.some((e=>e.id===i.id)),this.logger.info(`Selected SS(${i.id}) in call, isScreenShareValid:${r}`)),this.selectDevices({camera:n?t.id:void 0,screenshare:r?i.id:void 0})}isModalityEnabled(e){return this.isMediaSending(function(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2}throw new Error("MediaType required")}(e))}},Mm=class{constructor(e){this.ontimeout=e,this.active=!1}get isActive(){return this.active}start(e){void 0!==this.timeoutId&&this.stop(),this.timeoutId=setTimeout((()=>{this.ontimeout(),this.active=!1}),e),this.active=!0}stop(){clearTimeout(this.timeoutId),this.timeoutId=void 0,this.active=!1}};function km(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)}}}function Dm(e){return new Promise((t=>setTimeout(t,e)))}var Om=class{constructor(e,t,i,n){this.mediaControlPlane=e,this.signalingSession=t,this.logger=i,this.diagnostics=n,this.pendingSourceRequests=new Map,this.mediaControlPlane.on("mpSrResReceived",((e,t)=>this.onMsgReceived(e,t)))}mapToSignalingOperation(e){switch(e){case"ApplyChannelParametersSourceRequest":case"ApplyChannelParametersVideoCapabilities":case"ApplyChannelParametersBandwidth":return 0;case"ControlVideoStreaming":return 1;default:return this.logger.error("Unknown send operation"),null}}send(e,t,i,n){switch(e){case"ApplyChannelParametersSourceRequest":return this.sendMessages(e,t,i,n);case"ApplyChannelParametersVideoCapabilities":case"ApplyChannelParametersBandwidth":case"ControlVideoStreaming":return this.signalingSession?(this.diagnostics.recordSignalingOperation(e),this.signalingSession.sendWebRtcMediaNotificationAsync(this.mapToSignalingOperation(e),t)):Promise.reject(new Error("no signaling session"));default:return this.logger.warn(`Unable to send message reason: Operation unknown ${e}`),Promise.reject(new Error("Unable to send message"))}}async sendMessages(e,t,i,n){return this.mediaControlPlane.mcpFeaturesSupported("sendDuplicates")?Promise.all([this.sendMcpMessage(e,t,i,n),this.sendSignalingDupeOperation(e,t,n)]).then():this.sendMcpMessage(e,t,i,n)}setResendingMechanism(e,t,i,n){const r=window.setTimeout((()=>{this.logger.warn(`Fallback for SR: ${e}, switching to signaling`),this.mediaControlPlane.switchMcpFeauture("sourceRequestsEnabled",!1),this.resendPendingMessagesThroughSignaling()}),this.mediaControlPlane.getConfig()?.sourceRequestsMessagesTimeout);this.pendingSourceRequests.set(e,{sequenceNumber:e,timeoutId:r,deferred:t,message:i,operation:n})}async sendMcpMessage(e,t,i,n){if(this.mediaControlPlane?.mcpFeaturesSupported("sourceRequestsEnabled")&&t.applyChannelParameters?.multiChannelParameter?.mediaParameter?.includes("controlVideoStreaming")){const r=km();this.setResendingMechanism(n,r,t,e);try{return this.diagnostics.recordMCPOperation(e,n,i.controlVideoStreaming?.controlInfo),await this.mediaControlPlane.sendMsg({type:"sr",controlVideoStreaming:i.controlVideoStreaming}),this.logger.info(`Sending to MCP sequenceNumber:${n}`),this.mediaControlPlane?.mcpFeaturesSupported("sourceRequestsResponseEnabled")?r.promise:Promise.resolve()}catch(e){const t=Be(e);this.diagnostics.recordError(t,n),this.logger.error(`sendMsgInternal failed with error: ${t}`)}}return this.signalingSession?this.mediaControlPlane?.mcpFeaturesSupported("sendDuplicates")?void 0:(this.diagnostics.recordSignalingOperation(e),this.signalingSession.sendWebRtcMediaNotificationAsync(this.mapToSignalingOperation(e),t)):Promise.reject(new Error("no signaling session"))}async sendSignalingDupeOperation(e,t,i){if(this.signalingSession){const n=this.mapToSignalingOperation(e);return this.diagnostics.recordSignalingOperation(e,i),await this.signalingSession.sendWebRtcMediaNotificationAsync(n,t),this.diagnostics.recordSignalingOperationDuration(e,i),Promise.resolve()}return Promise.reject(new Error("no signaling session"))}resendPendingMessagesThroughSignaling(){this.diagnostics.recordFallback(),this.pendingSourceRequests.forEach((async(e,t)=>{try{this.mediaControlPlane.mcpFeaturesSupported("sendDuplicates")||(this.diagnostics.recordSignalingOperation(e.operation),await this.signalingSession.sendWebRtcMediaNotificationAsync(this.mapToSignalingOperation(e.operation),e.message)),e.deferred.resolve()}catch{e.deferred.reject()}finally{this.logger.warn(`Deleting message from pending: ${t}`),this.pendingSourceRequests.delete(t),clearTimeout(e.timeoutId)}}))}onMsgReceived(e,t){const i=this.pendingSourceRequests.get(e);switch(this.diagnostics.recordSrResultReceived(t,e,i.operation),t){case"ok":case"duplicate":case"out_of_order":i.deferred.resolve();break;default:i.deferred.reject(`Sequence number: ${e} failed with ${t}!`)}clearTimeout(i.timeoutId),this.pendingSourceRequests.delete(e)}},Nm=[1,2,9,10,11,12,30,27,28],Lm="remote",xm=class extends We{constructor(e,t){super(),this.isStreaming=e,this.mediaType=t}},Fm=class e extends We{constructor(t,i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v){super(n),this.signalingAgent=t,this.mediaAgent=i,this.logger=n,this.telemetryLoggers=r,this.currentUserSkypeIdentity=a,this.groupId=s,this.threadId=o,this.ecsProvider=d,this.trouterService=u,this.accountConfiguration=h,this.participants=[],this.isServerMuted=!1,this.isSpeakerMuted=!1,this.isVideoOn=!1,this.isScreenSharingOn=!1,this.callStartedAt=null,this.callHeldAt=null,this.callType=-1,this.failureType=2,this.isEmergency=!1,this.contentSharingSessions=[],this.endpoints={endpointDetails:[]},this.isPreheatEnabled=!1,this.localMediaStreams=[],this.enableRealtimeTelemetry=!1,this.isSharedLineAppearanceV2Activated=!1,this.enableCaptcha=!1,this.requestedHoldState=!1,this.mediaStateConfigurationHelper=new Wh({mediaStates:[Gh(0,4)]}),this.canToggleAudio=!0,this.canToggleVideo=!0,this.connectCallPromise=Promise.resolve(),this.canToggleScreenSharing=!0,this.callUsesMixer=!1,this.isEscalationInProgress=!1,this.retryOutgoingRenegotiation={retry:!1,causeId:""},this.isHoldInProgress=!1,this.isMuteOnHold=!1,this.callSetupFailed=!1,this.isSomeoneSharing=!1,this.isSomeoneStreamingVideo=!1,this.activeTalkersHistory=[],this.callGotConnected=!1,this.mediaRelayWhiteListingIssue=!1,this.signalingSessionCallOptions=null,this.tsCallingTelemetryReported=!1,this.isCallSetupTelemetrySent=!1,this._isAudioStreamConnected=!1,this._wasAudioStreamConnected=!1,this._callInLobby=!1,this._callIsSetupComplete=!1,this._transferState=0,this._parkState=0,this._muteState=0,this._callCreationTime=(new Date).getTime(),this._commandUrlPresence=0,this._capabilities={canMuteOthers:!1,canUnmuteSelf:!1},this._spamRiskLevel=null,this._spamStirAttestation=null,this._callMode=0,this._isUpdatePropertiesSpecifiedAllowedByEcs=!1,this._deferUsingMicrotask=!1,this._staleRosterCheckFixForPluginless=!1,this._transfereeAcceptanceWithoutWaitingForConv=!1,this._enableResolveScreenSharingWhenNegotiationComplete=!1,this._publishedStatesModified=0,this._participantPublishedStatesMap={},this._endpointPublishedStatesMap={},this._participantChangedEventSkipConfig={skipParticipantsUpdatesOnCall:!0},this._dominantSpeakerChangedEventSkipConfig={skipDominantSpeakerUpdatesOnCall:!0},this.receiveOnlyAudioOnCallStart=!1,this.lastContibutingSourceReport=Date.now(),this.instanceNumber=e.instanceCount++%1e3,this._hasDelayedReconnect=!1,this._enableMuteAsync=!1,this._enableUnmuteAsync=!1,this.startVM=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,{voicemailResourcePath:t.callVoicemailStartOptions.voicemailResourcePath,voicemailItemId:t.callVoicemailStartOptions.voicemailItemId,callToVoicemail:!0},Date.now()-r,e),this.getSignalingSessionCallOptions=e=>{const t={suppressDialout:!e.callStartOptions.ringOthers,isPreheatOnly:!(1&~e.callStartOptions.preheatFlags),onBehalfOf:this.onBehalfOfMri,onBehalfOfUserDisplayName:this.onBehalfOfUserDisplayName,callQueueContext:e.callStartOptions?.callQueueContext,muted:!(1&~e.callStartOptions.muteFlags),invitationType:e.invitationType,participantsToNudge:e.participantsToNudge,routingFlags:e.callStartOptions&&e.callStartOptions.routingFlags,parkContext:e.parkContext,pickupCode:e.pickupCode,scenario:e.callStartOptions&&e.callStartOptions.scenario,callUsesMixer:this.callUsesMixer,clientEndpointCapabilities:e.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:e.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:e.meetingPreferences,alternateId:e.callStartOptions?e.callStartOptions.alternateId:null,meetingRegistrationId:e.callStartOptions?e.callStartOptions.meetingRegistrationId:"",participantPin:e.callStartOptions?e.callStartOptions.participantPin:"",additionalEndpointProperties:e.callStartOptions?.additionalEndpointProperties||null,publishedStates:e.callStartOptions?.publishedStates||null,targetApplicationType:e.callStartOptions?.targetApplicationType,isHuddleGroupCall:e.callStartOptions?.isHuddleGroupCall,captchaContentJson:e.callStartOptions?.captchaContentJson},i=e.callStartOptions?.invitationDataJson;if(i)try{t.invitationData=JSON.parse(i)}catch(e){throw new Error(`Invalid JSON in invitationData: ${i}`)}return t},this.startOutgoingCall=(e,t,i,n,r)=>this.signalingSession.startOutgoingCall(i,n,this.getSignalingSessionCallOptions(t),Date.now()-r,e),this.joinGivenConversation=(e,t,i,n,r,a)=>{const s=!(1&~t.callStartOptions.muteFlags),o=!(1&~t.callStartOptions.preheatFlags),l=t.callStartOptions?.invitationDataJson,c=t.callStartOptions?.sharedLineCallInvitationContentJson;this.logger.info(`[${e}][joinGivenConversation] muted=${s}, isPreheatOnly=${o},\n            sharedLineCallInvitationContentJson=${c}, invitationDataJson=${l}`);const d={muted:s,isPreheatOnly:o,clientEndpointCapabilities:t.callStartOptions.clientEndpointCapabilities,clientEndpointDebugContent:t.callStartOptions.clientEndpointDebugContent,isEmergency:this.isEmergency,meetingData:this.meetingData,meetingPreferences:t.meetingPreferences,meetingRegistrationId:t.callStartOptions?t.callStartOptions.meetingRegistrationId:"",participantPin:t.callStartOptions?t.callStartOptions.participantPin:"",additionalEndpointProperties:t?.callStartOptions?.additionalEndpointProperties,applyServerMute:t?.applyServerMute,publishedStates:t?.callStartOptions.publishedStates,invitationData:t?.callStartOptions.invitationDataJson,captchaContentJson:t?.callStartOptions.captchaContentJson,callQueueContext:t?.callStartOptions.callQueueContext};if(c)try{d.sharedLineCallInvitationContent=JSON.parse(c)}catch(e){throw new Error(`Invalid JSON in sharedLineCallInvitationContent: ${c}`)}if(l)try{d.invitationData=JSON.parse(l)}catch(e){throw new Error(`Invalid JSON in invitationDataJson: ${l}`)}return this.signalingSession.joinGivenConversation(a,this.callId,i,n,Date.now()-r,d,e)},this.executeCallTransfer=(e,t,i,n)=>{this._setTransferState(1);const r=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return 0===i?this.signalingSession.transferCallAsync(e,"TransferTypeStandard",void 0,n,t):2===i&&this.signalingSession.transferCallAsync(e,"TransferTypeVoicemail",void 0,n,t),r},this.executeConsultCallTransfer=(e,t,i,n,r)=>{this._setTransferState(1);const a=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,n,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});return this.signalingSession.consultTransferCallAsync(e,t,i,n,r),a},this.createUpdateParticipantPromise=(e,t)=>this._callOperationHandler.createPendingOperation("UpdateParticipantsProperties",e,t),this._getCallEndOperation=()=>this._callOperationHandler.hasPendingOperation("StopCall")?this._callOperationHandler.waitForOperation("StopCall"):this._callOperationHandler.hasPendingOperation("Reject")?this._callOperationHandler.waitForOperation("Reject"):this._callOperationHandler.hasPendingOperation("CallRedirect")?this._callOperationHandler.waitForOperation("CallRedirect"):Promise.resolve(),this._onAcknowledgeError=(e,t,i,n)=>{i.logFailure(e);let r,a={code:2,success:!1,fatal:!0},s=7;throw hh("SendAttach",e)&&(r={code:$n.InternalServerError,subCode:Gn.AttachFailed,phrase:ar}),hh("ProcessIncomingCallRequest",e)&&(r={code:$n.NotAcceptable,subCode:Gn.AttachActionFailed,phrase:sr},a={code:0,success:!1,fatal:!0}),uh(mr,e)&&(s=47),e?.error&&e.error.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer&&(r={code:$n.MediaError,subCode:Gn.MediaOfferProcessingError,phrase:nr}),this.callTelemetry.updateOperationData("Acknowledge",{phases:n,error:De(e)},t),this._callOperationHandler.maybeRejectOperation("Acknowledge",a,void 0,t),this.stopInternal({rejectReason:r,causeId:t,terminatedReason:s}),a},this._onAcknowledgeSuccess=(e,t,i)=>(e.logSuccess("success"),this.callTelemetry.updateOperationData("Acknowledge",{phases:t},i),{code:1,success:!0}),this._processOfferedModalities=(e,t)=>{this.handleOfferedModalities(e,t);const i=this.callUsesMixer?void 0:{modalityOverride:e};return this.updateMediaModalities(i,t)},this._handleOfferProcessingError=(e,t,i)=>(i.logFailure(`handleOfferProcessingError=${e}`),e?.error?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer?(this.callTelemetry.recordEvent("IncompatibleOffer",void 0,t),this.signalingSession.supportsNewOfferRequest()?(this.newOfferRequestDeferred=Si(),this.attachToCallAndGetOffer.promise.then((()=>this.mediaSession.rejectNegotiationAsync(e.error,t))).then((()=>this.signalingSession.requestNewOffer(this.mediaSession.getAcceptedTypes(),t))).then((()=>this.newOfferRequestDeferred.promise)).then((e=>this.mediaSession.processOfferAsync(e,t))).catch((e=>(this.callTelemetry.recordEvent("NewOfferFailed",Ne(e),t),Promise.reject(e))))):Promise.reject(e)):Promise.reject(e)),this._trySendProvisionalMediaAnswer=e=>Promise.resolve(void 0).then((()=>this.mediaSession.createAnswerAsync(!0,e))).then((e=>e.blob?(this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",void 0,Te(),{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.signalingSession.setProvisionalAnswerAsync(e).then((()=>this.mediaAcknowledgmentOperation))):Promise.resolve(void 0))),this.checkForCallIdUpdate=(e,t)=>{if(this.callId!==e){this.logger.info(`[${t}][checkForCallIdUpdate] old=${this.callId}, new=${e}`),this.setCallId(e);try{this.event("callIdChanged").raise(this.callId)}catch(e){this.logger.error(`Error raising call ID change: ${e}`)}this.raiseChanged()}},this.handleRemoteParticipantStateInOneToOneCall=e=>{if(!this.callUsesMixer&&3===this.state){const t=this.participants[0];t&&t.setState(3,void 0,e)}},this.handleRemoteParticipantJoinedInOneToOneCall=(e,t)=>{if(!this.callUsesMixer&&3===this.state){const i=this.participants.filter((t=>t.id===e.id))[0];i?i.setState(3,void 0,t):this.logger.logFailure(`[${t}][handleRemoteParticipantJoinedInOneToOneCall]unable to find particpant ${Ae(e.id)}`)}},this.handleRemoteParticipantStateInObservingCall=(e,t,i)=>{const n=t.isLobby;if(8===this.state){const t=n?7:3;e.setState(t,void 0,i)}},this.getTelemetryFromPhaseExecution=e=>{const t={phase:e.phase,phases:e.phases,code:e.error&&e.error.code,subCode:e.error&&e.error.subCode,message:e.error&&e.error.message,error:e.error};return(t.code||t.message)&&delete t.error,t},this._setTransferState=e=>{this.transferState!==e&&(this.logger.info(`Transfer: state set: ${e}`),this._transferState=e,this.callTelemetry.recordEvent("_SetTransferState",{state:e}),this.raiseChanged())},this._setParkState=e=>{this.parkState!==e&&(this.logger.info(`Parking: state set: ${e}`),this._parkState=e,this.callTelemetry.recordEvent("_SetParkState",{state:e}),this.raiseChanged())},this.prepareNegotiationResultForTelemtry=e=>({isComplete:e.isComplete,activeModalities:e.activeModalities,configuredModalities:e.configuredModalities,initiator:Ae(e.initiator),attemptedModalities:e.attemptedModalities,offeredModalities:e.offeredModalities}),this.prepareTelemetryForOfferAnswer=e=>e&&e.mediaContent&&{isRenegotiation:!!e.renegotiation,isEscalation:!!e.mediaContent.isTwoPartyToMultiPartyEscalation,mediaTypes:e.mediaTypes,newOffer:e.mediaContent.newOffer},this.updateLocalParticipantEndpoints=e=>{const t=this.logger.createFnLogger("updateLocalParticipantEndpoints",""),i=[];(0,fr.forEach)(e,(e=>{const t=Vh(e,this.getSelfClientEndpointCapabilities());i.push(t)})),this.endpoints.endpointDetails=i;const n=this.getDataChannelSourceId();-1!==n&&this.dataChannel&&this.dataChannel.setDataChannelSourceId(n),t.info(`selfEndpointDetails=${JSON.stringify(this.endpoints)}`)},this.handleParticipantsMutedUpdated=(e,t)=>{const i=this.logger.createFnLogger("handleParticipantsMutedUpdated",t);if(void 0!==e?.info){this.logger.info(`handleParticipantsMutedUpdated: number of infos: ${Object.keys(e.info).length}`);for(const t of Object.keys(e.info)){const n=this.getParticipant(t);n?n.handleServerMutedInfoUpdate(e.info[t]):i.info(`Cannot find local participant ${Ae(t)}`)}}else i.info("Ignored, no mute participant info.")},this.handleSelfUnmuteUpdatedInfo=(e,t)=>{const i=this.logger.createFnLogger("handleSelfUnmuteUpdatedInfo",t);if(void 0!==e?.info)for(const n of Object.keys(e.info)){const r=e.info[n];if(n===this.localSignalingParticipant.id){const e=(0,fr.find)(r,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===e){i.info(`Cannot find local participant ${Ae(n)}`);continue}const a=(0,fr.find)(this.localSignalingParticipant.endpointDetails,(t=>t.participantId===e.participantId));ap(this.logger,a,e,!1)&&this.handleSelfServerMutedState(t)}}else i.info("Ignored, no unmute participant info.")},this.state=0,this.terminatedReason=0,this.callStats=new Fh(this.mediaAgent?.getConfigProvider()),this.callDeviceManager=this.createCallDeviceManager(),this.callTelemetry=new pn(this.logger,this._callCreationTime),this.collectMediaStatsDeferred=Si(),this.setCallId(l),this.setGroupId(s),this.setThreadId(o),this.setMessageId(p),this.setSkypeId(this.currentUserSkypeIdentity.id),this.setParticipantId(c),this.setCallOrigin(0),this.logger=this.logger.createChild((()=>{const e=(this.endpointId||"").substr(0,8),t=(this.participantId||"").substr(0,8);return`Web/${this.instanceNumber}[${this.callId}][${e}][${t}][${this.state}]`})),this._staleRosterCheckFixForPluginless=this.ecsProvider.getEcsConfig("SkypeCalling","staleRosterCheckFixForPluginless"),this._transfereeAcceptanceWithoutWaitingForConv=this.ecsProvider.getEcsConfig("SkypeCalling","transfereeAcceptanceWithoutWaitingForConv"),this._enableMuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncMute"),this._enableUnmuteAsync=this.ecsProvider.getEcsConfig("SkypeCalling","enableAsyncUnmute"),this.initializeSignalingSession(c),this.signalingSession.setLocationInfo(g,m,v),this.streamManager=new Bp(this.participantId,null,this.callStats.localStats,this.logger),this.mediaAgent&&(this.dataChannel=new ag(this.logger),this.dataChannel.on("remoteUserEventsReceived",((e,t)=>this.event("remoteUserEventsReceived").raise(e,t))),this.dataChannel.on("onDataChannelStateUpdated",(e=>{"Failed"===e&&(this.logger.error("onDataChannelStateUpdated: datachannel creation failed, will remove data modality"),this.mediaStateConfigurationHelper.removeModality(3),this.updateSignalingDSHMessageSubscription(!0),this.updateMediaModalities())})),this.screenSharingControl=new Ag(this.logger,this.dataChannel,this,this.telemetryLoggers,this.ecsProvider),this.initializeMediaControlPlane(),this.mediaAgent.handleSendMidCallTelemetry(this.sendMidCallTelemetry.bind(this)));const S={enableErrorConversion:this.ecsProvider.getEcsConfig("SkypeCalling","enableErrorConversion")};this._deferUsingMicrotask=this.ecsProvider.getEcsConfig("SkypeCalling","deferUsingMicrotask"),gp.instance.setDeferToQueueMicrotask(this._deferUsingMicrotask),gp.instance.setLogger(n),this.logger.info(`operationHandlerEcsConfig: ${JSON.stringify(S)}`),this._preferredMpLocation=this.ecsProvider.getEcsConfig("SkypeCalling","preferredMpLocation"),this._isUpdatePropertiesSpecifiedAllowedByEcs=this.ecsProvider.getEcsConfig("SkypeCalling","enableUpdateParticipantsSpecified"),this._enableResolveScreenSharingWhenNegotiationComplete=this.ecsProvider.getEcsConfig("SkypeCalling","enableResolveScreenSharingWhenNegotiationComplete"),this._callOperationHandler=new Hn(this.logger,this.callTelemetry,S,void 0,((e,t)=>{this.preconditions(e,t)})),this._participantOperationHandler=new Hn(this.logger,this.callTelemetry,S),this.setMeetingData(f),this.initializeLiveStreamConfigProvider()}get callMode(){return this._callMode}get callId(){return this._callId}get endpointId(){return this._endpointId}get isHostless(){return this.signalingSession.isHostLessCall}get transferState(){return this._transferState}get parkState(){return this._parkState}get capabilities(){return this._capabilities}get publishedStates(){return this._publishedStates}get dataChannelAdapter(){return this.dataChannel}get participantId(){try{const e=this.signalingSession?.participantManager?.localParticipant?.participantId;this._participantId=e||this._participantId}catch(e){this.logger.error("Error updating participantId")}return this._participantId}get role(){return this.localSignalingParticipant.role}get meetingRole(){return this.localSignalingParticipant.meetingRole}get advancedMeetingRole(){return this.localSignalingParticipant.advancedMeetingRole}get maskedIdentityDetails(){return{isIdentityMasked:this.localSignalingParticipant.isIdentityMasked,maskedIdSeqNumber:this.localSignalingParticipant.maskedIdSeqNumber,maskedId:this.localSignalingParticipant.maskedId}}get participantType(){return this.localSignalingParticipant.participantType}get isMuted(){return 2===this._muteState||3===this._muteState}get tenantId(){return this.localSignalingParticipant.tenantId}get mediaLegId(){return this._mediaLegId}get isIncomingOneOnOneVideoCall(){return this.isOneToOneCall()&&this.isSomeoneStreamingVideo}get mediaStreams(){return this.streamManager.streams}get origin(){return this._origin}get propertyBag(){return this.localSignalingParticipant.propertyBag}get version(){return this.localSignalingParticipant.version}get isAudioStreamConnected(){return this._isAudioStreamConnected}set isAudioStreamConnected(e){this._isAudioStreamConnected!==e&&(this._isAudioStreamConnected=e,this._wasAudioStreamConnected=this._wasAudioStreamConnected||e,this.raiseChanged())}setMeetingRole(e){e!==this.localSignalingParticipant.meetingRole&&(this.logger.info(`changing self role to [${e}]`),this.localSignalingParticipant.meetingRole=e,this.event("meetingRoleUpdated").raise(e))}setAdvancedMeetingRole(e){e!==this.localSignalingParticipant.advancedMeetingRole&&(this.logger.info(`changing self advanced meeting role to [${e}]`),this.localSignalingParticipant.advancedMeetingRole=e,this.event("advancedMeetingRoleUpdated").raise(e))}setParticipantType(e){e!==this.localSignalingParticipant.participantType&&(this.logger.info(`changing self participant user type to [${e}]`),this.localSignalingParticipant.participantType=e,this.event("participantTypeUpdated").raise(e))}setPropertyBag(e){e&&!(0,fr.isEqual)(e,this.localSignalingParticipant.propertyBag)&&(this.logger.info(`changing self participant property bag to [${e}]`),this.localSignalingParticipant.propertyBag=e,this.event("propertyBagUpdated").raise(e))}setPropertyRosterVersion(e){e!==this.localSignalingParticipant.version&&(this.logger.info(`changing self participant property version to [${e}]`),this.localSignalingParticipant.version=e,this.event("propertyRosterVersionUpdated").raise(e))}setMaskedIdentityDetails(e=!1,t,i){this.localSignalingParticipant.isIdentityMasked===e&&this.localSignalingParticipant.maskedIdSeqNumber===t&&this.localSignalingParticipant.maskedId===i||(this.localSignalingParticipant.isIdentityMasked=e,this.localSignalingParticipant.maskedIdSeqNumber=t,this.localSignalingParticipant.maskedId=i,this.logger.info(`self participant masked identity details updated to [${JSON.stringify(this.maskedIdentityDetails)}]`),this.event("maskedIdentityDetailsUpdated").raise(this.maskedIdentityDetails))}setJoinAsStreamingUser(e){e!==this.joinAsStreamingUser&&(this.logger.info(`setting self join as streaming user to [${e}]`),this.joinAsStreamingUser=e)}get spamRiskLevel(){return this._spamRiskLevel}set spamRiskLevel(e){e&&(this._spamRiskLevel=e)}get spamStirAttestation(){return this._spamStirAttestation}set spamStirAttestation(e){e&&(this._spamStirAttestation=e)}getScreenHandle(e){if(!this.sharedScreenHandle){const t=!!this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled,i=!!this.mediaSession&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&!this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing,n=this.mediaStateConfigurationHelper.isSending(0)&&i&&t,r=3===e?.getType()?e?.getDeviceId():void 0,a=this.callDeviceManager.getDeviceManager(Kh(2));a.setAudioSharingRequested(n),this.sharedScreenHandle=a.createDevicesHandle({audio:n,sharing:!0},"pluginlessCall:getScreenHandle()",r),this.sharedScreenHandle.on("onStreamStateChanged",((e,t)=>this.onSharingStreamStateChanged(e)))}return this.sharedScreenHandle}setCallOrigin(e){this.logger.info(`Set call origin to ${e}`),this._origin=e,this.callTelemetry.setCallOrigin(e),this.callTelemetry.recordEvent("_SetCallOrigin",{origin:e})}setMediaLegId(e){this._mediaLegId=e,this.callStats.setMediaLegId(e)}setCallId(e){this.callTelemetry.setCallId(e),this.callStats.setCallId(e),this._callId=e}setEndpointId(e){this._endpointId=e,this.logger.info(`[endpointId=${xe(this._endpointId)}]`),this.callTelemetry.setEndpointId(e),this.callStats.setEndpointId(e)}setFailureType(e){this.callTelemetry.setFailureType(e),this.failureType=e}setParticipantId(e){this._participantId=e,this.logger.info(`[participantId=${this._participantId}]`),this.callTelemetry.setParticipantId(this.participantId)}setCallerMri(e){this.callerMri=e,this.logger.info(`[callerMri=${Ae(this.callerMri)}]`)}setTransferorMri(e){const t=ch(e);t!==this.transferorMri&&(this.transferorMri=t,this.logger.info(`transferorMri: ${Ae(this.transferorMri)}`),this.raiseChanged())}setGroupId(e,t=Te()){this.logger.info(`[${t}][setGroupId] groupId=${Ae(e)}`),this.groupId!==e&&(this.groupId=e,this.callTelemetry.setGroupId(e),this.event("groupIdChanged").raise(e))}setMeetingData(e){if(e){if(e.meetingCode&&(!this.meetingData||this.meetingData&&e.meetingCode!==this.meetingData.meetingCode)){const t=e.meetingCode;this.logger.info(`[setMeetingData] meetingCode=${t}`),this.callTelemetry.setMeetingCode(t),this.signalingSession.setMeetingCode(t)}if(e.meetingUrl&&(!this.meetingData||this.meetingData&&e.meetingUrl!==this.meetingData.meetingUrl)){const t=e.meetingUrl.split("?")[0];this.logger.info(`[setMeetingData] meetingUrl=${e.meetingUrl}`),this.callTelemetry.setMeetingUrl(t),this.signalingSession.setMeetingUrl(t)}}this.meetingData=e}setHuddleGroupCall(e){this.isHuddleGroupCall!==!!e&&(this.logger.info(`[setHuddleGroupCall] new isHuddleGroupCall=${e}`),this.isHuddleGroupCall=e,this.callTelemetry.setIsHuddleGroupCall(!0))}setComplianceRecordingContent(e,t){try{if(!(0,fr.isEqual)(this.complianceRecordingContent,t)){this.complianceRecordingContent=t;const i=t?JSON.stringify(t):"";this.callTelemetry.setComplianceRecordingContentLength(i.length),this.logger.info(`[${e}][setComplianceRecordingContent] complianceRecordingContentLength=${i.length}`)}}catch(t){this.logger.error(`[${e}][setComplianceRecordingContent] ${t}`)}}setThreadId(e,t=Te()){this.threadId!==e&&(this.logger.info(`[${t}][setThreadId] threadId=${Me(e)}`),this.threadId=e,this.callTelemetry.setThreadId(e))}setBackroomThreadId(e,t=Te()){this.backroomThreadId!==e&&(this.logger.info(`[${t}][setBackroomThreadId] backroomThreadId=${Me(e)}`),this.backroomThreadId=e,this.callTelemetry.setBackroomThreadId(e))}setMessageId(e,t=Te()){this.messageId!==e&&(this.logger.info(`[${t}][setMessageId] messageId=${Ae(e)}`),this.messageId=e,this.callTelemetry.setMesageId(e))}setSkypeId(e,t=Te()){this.skypeId!==e&&(this.logger.info(`[${t}][setSkypeId]`),this.skypeId=e,this.callTelemetry.setSkypeId(e))}setCallType(e,t){const i=this.logger.createFnLogger("setCallType",t);i.info(`current=${this.callType}, newValue: ${e}`),2!==this.callType||1!==e?e!==this.callType&&(this.callType=e,this.callTelemetry.setCallType(e),2===e&&this.callStats.localStats.call.event(2),this.raiseChanged()):i.logFailure("De-escalating to P2P should not happen!")}setConversationType(e,t){this.logger.createFnLogger("setConversationType",t).info(`current=${this.conversationType}, newValue=${e}`),e!==this.conversationType&&(this.conversationType=e,this.callTelemetry.setConversationType(e),this.raiseChanged())}setCallUsesMixer(e,t){this.callUsesMixer!==!!e&&(this.logger.info(`[${t}][setCallUsesMixer] new value=${e}`),this.callUsesMixer=e,this.callTelemetry.recordEvent("_CallUsesMixer",{newValue:e},t),this.dataChannel.setConfigProviderView(this.mediaSession?.getSessionConfig())),e&&this.mediaControlPlane.start()}setIsEscalationInProgress(e,t){this.logger.info(`[${t}][setIsEscalationInProgress] currentValue=${this.isEscalationInProgress}, newValue=${e}`),this.isEscalationInProgress=e,this.allowScreenSharingControl()&&this.screenSharingControl.setIsEscalationInProgress(e),this.callTelemetry.recordEvent("_EscalationInProgress",void 0,t)}setFromApplicationType(e,t){e&&(this.fromApplicationType=e,this.callTelemetry.recordEvent("_SetFromApplicationType",{fromApplicationType:e},t))}setEnableCaptcha(e){e!==this.localSignalingParticipant.enableCaptcha&&(this.logger.info(`setting self participant to enable captcha to [${e}]`),this.localSignalingParticipant.enableCaptcha=e,this.enableCaptcha=e)}processCallStartOptions(e,t){const i=this.logger.createFnLogger("_ProcessCallStartOptions",t);try{1&e.preheatFlags&&(this.isPreheatEnabled=!0)}catch(e){i.logFailure(e)}}getlocalScreenShareStream(){return(0,fr.find)(this.localMediaStreams,(e=>2===e.mediaType))}setMeetingLayout(e,t){throw new Error("Method not implemented.")}async selectDevices(e){this.callDeviceManager.isVirtualDeviceEnabled?this.callDeviceManager.selectDevices(e):this.logger.error("allowVirtualDeviceInCall not enabled.")}async getSelectDevices(){return this.callDeviceManager.getSelectedDevices()}createStage(e){throw new Error("Method not implemented.")}updateDisplayName(e){this.logger.info("updating displayName"),this.localSignalingParticipant.displayName=e,this.signalingSession.participantManager.localParticipant.displayName=e}init(e){if(this.logger.info(`init callInitOptions:${Le(function(e){const t={mediaPeerType:e.mediaPeerType,threadId:Me(e.threadId)};return Fe(e.messageId)&&(t.messageId=e.messageId),Fe(e.enableGroupCallMeetupGeneration)&&(t.enableGroupCallMeetupGeneration=e.enableGroupCallMeetupGeneration),Fe(e.endpointMetadata)&&(t.endpointMetadata=e.endpointMetadata),Fe(e.onBehalfOf)&&(t.onBehalfOf=Ae(e.onBehalfOf)),Fe(e.onBehalfOfUserDisplayName)&&(t.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName),Fe(e.emergencyContent)&&(t.emergencyContent=e.emergencyContent),Fe(e.isEmergency)&&(t.isEmergency=e.isEmergency),Fe(e.broadcastContext)&&(t.broadcastContext=e.broadcastContext),e.meetingInfo&&(t.meetingInfo={tenantId:e.meetingInfo.tenantId,organizerId:Ae(e.meetingInfo.organizerId)},Fe(e.meetingInfo.meetingType)&&(t.meetingInfo.meetingType=e.meetingInfo.meetingType),Fe(e.meetingInfo.replyChainMessageId)&&(t.meetingInfo.replyChainMessageId=e.meetingInfo.replyChainMessageId)),e.transferContext&&(t.transferContext={transferorMri:Ae(e.transferContext.transferorMri),targetMri:Ae(e.transferContext.targetMri),context:e.transferContext.context},Fe(e.transferContext.transferType)&&(t.transferContext.transferType=e.transferContext.transferType)),t}(e))}`),this.signalingSessionCallOptions={teamsMessageId:e.messageId,enableGroupCallMeetupGeneration:e.enableGroupCallMeetupGeneration,meetingInfo:e.meetingInfo,emergencyContent:e.emergencyContent?JSON.parse(e.emergencyContent):void 0,broadcastContext:e.broadcastContext,endpointMetadata:e.endpointMetadata},this.setMessageId(e.messageId),this.onBehalfOfMri=e.onBehalfOf,this.onBehalfOfUserDisplayName=e.onBehalfOfUserDisplayName,e.threadId&&(this.setThreadId(e.threadId),this.signalingSession.setThreadId(e.threadId)),this.groupId&&this.signalingSession.setGroupId(this.groupId),this.signalingSession.setCallOptions(this.signalingSessionCallOptions),e.transferContext){switch(this.logger.info("Transfer: Call.init, set transferContext",cp(e.transferContext)),this.signalingSession.setTransferContext(e.transferContext.context),e.transferContext.transferType){case 1:this.setCallOrigin(2);break;case 0:this.setCallOrigin(1);break;case 2:this.setCallOrigin(3);break;default:throw new Error(`TransferType: ${e.transferContext.transferType} doesn't have a switch option`)}e.transferContext.context.callAcceptanceCallback?this._transferredCallAcceptanceCallback=e.transferContext.context.callAcceptanceCallback:this.logger.info("[failed]Transfer: Missing transferred call acceptance callback"),e.transferContext.transferorMri&&this.setTransferorMri(e.transferContext.transferorMri)}this.setIsEmergency(!!e.isEmergency),this.raiseChanged()}getIncomingRawAudioStream(){if(!this.mediaSession)throw this.logger.error("can not execute getIncomingRawAudioStream as there is no mediaSession"),new Error("NoMediaSession");return this.mediaSession.getIncomingRawAudioStream()}getUnmixedAudioProvider(){return this.unmixedAudioProvider?Promise.resolve(this.unmixedAudioProvider):Promise.reject("No audio provider available")}setDeviceManager(e){}async startVideo(e,t=Te()){return this.startStopVideo(!0,t)}async stopVideo(e,t=Te()){return this.startStopVideo(!1,t)}async dumpVideoSourceImages(){return Promise.reject(60)}async hold(e,t=Te(),i,n){const r=this.logger.createFnLogger("Hold",t);return r.info(`[Hold][${t}] negotiationTag ${e} hold options: ${Le(i)}`),4===this.state?(r.logFailure("Trying to put a call on hold which is already held state, early resolving the promise"),Promise.resolve(void 0)):i?.isLocal?this.localHold(t,i,n):this.holdWithRenegotiate(t,i)}async holdWithRenegotiate(e,t){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t):(this.logger.logFailure(`[Hold][${e}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async localHold(e,t,i){return this.isValidHoldResumeCallState(this.state)?this.setHold(!0,e,t,i):(this.logger.logFailure(`[LocalHold][${e}] Trying to hold a call in an invalid state: ${this.state}`),Promise.reject(`Trying to hold a call in an invalid state: ${this.state}`))}async unhold(e,t=Te()){const i=this.logger.createFnLogger("Unhold",t);return 3===this.state?(i.logFailure("Trying to resume a call which is already in connected state, early resolving the promise"),Promise.resolve(void 0)):4===this.state?(i.info(`current hold state ${this.requestedHoldState}`),this.setHold(!1,t)):(i.logFailure(`Trying to resume a call in an invalid state: ${this.state}`),Promise.reject(`Trying to resume a call in an invalid state: ${this.state}`))}canMerge(e,t){const i=e.isOneToOneCall(),n=3===this.state,r=4===e.state,a=i&&n&&r;return this.logger.info(`[${t}][canMerge] Call ${e.callId} isOneToOne ${i} isCallConnected ${n} call.state ${this.state} isMergeOnHold ${r} mergeCall.state ${e.state} CanMerge result: ${a}`),a}async updateEndpointMetadata(e,t=Te()){return this.signalingSession.updateEndpointMetadata(e,t)}async sendDtmfTone(e){if(this.mediaSession){const t=this.toneToString(e);return t?(this.logger.info(`[${Pn}][sendDtmfTone]DtmfTone: <omitted>`),Promise.resolve(this.mediaSession.sendDtmf(t))):Promise.reject(new Error("Unsupported DtmfTone"))}return Promise.reject(new Error("no mediaSession"))}async setAudioUsageMode(e){return Promise.reject(60)}async setAudioMidcallConfig(e,t){return Promise.reject(60)}async setAudioMidcallConfigJson(e,t=Te()){if(!e)return Promise.reject(60);et(e.enableSpatialAudio)&&this.mediaSession?.configureSpatialAudio(e.enableSpatialAudio,t),e.noiseSuppressionMode&&await this.setNoiseSuppressionMode(e.noiseSuppressionMode,e.enableAEC)}async setParticipantSpatialAudioPositions(e,t=Te()){const i=e.map((e=>({sourceId:this.participants.find((t=>t.id===e.participantId))?.audio.id,x:e.x,y:e.y})));return this.mediaSession?.setParticipantSpatialAudioPositions(i,t)}async setNoiseSuppressionMode(e,t){return this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe||this.mediaSession.getSessionConfig().config.wasmdns.enableNoiseSuppression?"Auto"===e?this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaSession.getSessionConfig().config.wasmvqe.defaultVqeMode)):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(this.mediaSession.getSessionConfig().config.wasmdns.noiseSuppressionMode,t))):this.mediaSession.getSessionConfig().config.wasmvqe.enableVqe?this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,this.mediaSession.getSessionConfig().config.wasmvqe.enableAec))):this.mediaAgent.getDeviceManager().setAudioEffects(this.mediaAgent.getDeviceManager().effectsManager.vqeModeToAudioEffectType(this.mediaAgent.getDeviceManager().effectsManager.nsModeToVqeMode(e,t))):Promise.resolve()}setInitialTelemetry(e,t,i,n){let r,a,s,o,l;switch(e){case"Subscribe":case"SubscribeWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("SUBSCRIBE"),i||this.callTelemetry.setOperationVariant(e,"CCWM"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i});break;case"Acknowledge":0!==this.state&&8!==this.state&&this.callTelemetry.maybeRecordOperationSuccess(e,{code:4}),this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("callee"),this.signalingSession.setInitialTelemetry(e,{causeId:n});break;case"JoinCall":case"JoinWithMeetingData":this.callTelemetry.setDirection("Incoming"),this.callTelemetry.setSelfParticipantRole("join"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),a=!(1&~t.callStartOptions.muteFlags),s=!(1&~t.callStartOptions.preheatFlags),o={muted:a,isPreheatOnly:s},this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,joinCallOptions:o,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCall":case"StartWithMeetingData":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),1&t.callStartOptions.preheatFlags&&this.callTelemetry.setOperationVariant(e,"Preheat"),r=this.telemetryDataFromCallStartOptions(t.callStartOptions),r&&this.callTelemetry.updateOperationData(e,r,n),l=t.callStartOptions,this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,callStartOptions:l,offerGenerationTime:Date.now()-t.callStartTime});break;case"StartCallToVoiceMail":case"StartCallWithNudge":case"StartCallAndUnpark":this.callTelemetry.setDirection("Outgoing"),this.callTelemetry.setSelfParticipantRole("caller"),this.signalingSession.setInitialTelemetry(e,{correlationId:this.callId,causeId:n,conversationServiceUrl:i,startCallOptions:t.callStartOptions,offerGenerationTime:Date.now()-t.callStartTime})}}async setHold(e,t,i,n){const r=this.logger.createFnLogger("setHold",t,`hold=${e}`);if(!this.canToggleAudio||this.callHoldResumeDeferred)return Promise.reject(new Error("can not set hold as it is already in progress"));this.callHoldResumeDeferred=Si(),this.isHoldInProgress=e,this.canToggleAudio=!1,this.canToggleVideo=!1,this.canToggleScreenSharing=!1,this.requestedHoldState=e;const a=()=>{this.canToggleAudio=!0,this.canToggleScreenSharing=!0,this.canToggleVideo=!0};r.info(`start, holdOptions: ${JSON.stringify(i)}`);const s=this.callHoldResumeDeferred.promise,o=e?"Hold":"Unhold",l={debugContent:{clientScenario:this.convertClientScenario(n)}};try{if(e?this.isMuteOnHold=i&&i.isLocal&&5!==this.state:this.prepareModalitiesForResume(t),!this.isMuteOnHold){const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t),this.updateScreenSharingState(e,t)}e&&(this.prepareModalitiesForHold(t),5===this.state&&this.finishCallHoldResume(),this.setCallState(4,t)),this.isMuteOnHold&&this.setMuteOnHold(e,t),a();const n={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(o,n,null,t,l)}catch(i){this.callTelemetry.recordOperationFailure(o,{error:De(i)},null,t,l),r.logFailure(i),a(),this.callHoldResumeDeferred?.reject(new Error(`Failed setting hold state to ${e}`)),this.callHoldResumeDeferred=null}return s}transferCall(e){return this.logger.warn("transferCall is deprecated, please use callBlindTransfer instead"),this.callBlindTransfer(e)}callBlindTransfer(e,t=Te(),i){return this.executeCallTransfer(e,t,0,i)}callSafeTransfer(e,t=Te(),i){return this.executeCallTransfer(e,t,0,i)}transferCallToVoicemail(e,t=Te()){return this.executeCallTransfer(e.transferTargetMri,t,2,void 0)}callConsultativeTransfer(e,t=Te(),i,n){const r=this.logger.createFnLogger("ConsultativeTransfer",t),a=e.participants[0],s=a&&a.acceptedBy||a&&a.id;return r.info(`transferTargetParticipantLegId: ${i} targetMri: ${Ae(s)}`),this.executeConsultCallTransfer(e.callId,s,i,t,n)}async consultativeTransferWithPickupCode(e,t){const i=this.logger.createFnLogger("ConsultativeTransferWithPickupCode",t);if(i.info(`pickup code: ${e}`),!e||isNaN(Number(e)))return i.info("pickup code cannot be empty"),Promise.reject(Un("TransactionDisallowed"));const n=this._callOperationHandler.createPendingOperation("_CallTransferInProgress",void 0,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),r=`4:${sn}`,a={unparkContent:{pickupCode:Number(e)}};return this.signalingSession.transferCallAsync(r,"TransferTypeStandard",a,{disableForwardingAndUnanswered:!1},t),n}callRedirect(e,t=Te()){return this.logger.createFnLogger("CallRedirect",t).info(`redirectOptions: ${JSON.stringify(e)}`),this.stopInternal({terminatedReason:75,redirectOptions:e,causeId:t}).then((()=>({code:$n.CallRedirected,subCode:Gn.CallRedirectedSuccess,phrase:dr,resultCategories:["Success"]})))}convertParkContext(e){switch(e){case 1:return"sharedLinePark";case 4:return"sharedLineParkV2";case 0:return"teamPark";case 3:return"serverHoldV2";case 5:return"callPark";default:return"serverHold"}}convertClientScenario(e){switch(e){case 0:return"breakoutRoom";case 1:return"musicOnHoldV2";case 2:return"sharedLineAppearanceV2";default:return}}park(e,t=Te()){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [ParkCall] start -  context ${e} parkType ${i}`),5===e?(this.callTelemetry.recordOperation(`${ka(i)}`,t),this._pendingParkPromise=this._callOperationHandler.createPendingOperation("CallParkV2",void 0,t)):this._pendingParkPromise=this._callOperationHandler.waitForOperation("ParkCall"),"serverHoldV2"!==i&&"callPark"!==i&&this._setParkState(1),this.signalingSession.parkCallAsync(i,t).catch((e=>{this.logger.info(`[${t}] [ParkCall] error in parkCallAsync (synchronous error) : ${De(e)}. Hold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("ParkCall",{error:De(e)},t)})),this._pendingParkPromise}async unpark(e,t){const i=this.convertParkContext(e);return this.logger.info(`[${t}] [UnparkCall] start -  context ${e} parkType ${i}`),this._pendingUnparkPromise=this._callOperationHandler.waitForOperation("UnparkCall"),this.signalingSession.unparkAsync(i,t).catch((e=>{this.logger.info(`[${t}] [UnparkCall] error in unparkAsync (synchronous error) : ${De(e)}. Unhold promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UnparkCall",{error:De(e)},t)})),this._pendingUnparkPromise}getServerHoldLocation(){return this._pendingParkPromise.then((()=>(this.logger.info(`getServerHoldLocation ${this.serverHoldLocation}`),this.serverHoldLocation)))}getParkAdditionalContextJson(){return this._pendingParkPromise.then((()=>(this.logger.info(`getParkAdditionalContextJson ${this.parkAdditionalContextJson}`),this.parkAdditionalContextJson)))}getJoinBlob(){return Promise.resolve(JSON.stringify({conversationUrl:this.signalingSession.getConversationUrl(),conversationId:this.callId}))}getTechnicalInformationJson(){return Promise.resolve(JSON.stringify(this.mediaSession.getCallTechnicalInfo()))}isOneToOneCall(){return 1===this.callType&&1===this.participants.length}setMuteOnHold(e,t){this.mediaSession.muteHold(e,t),e||(this.computeCallState(t),this.isMuteOnHold=!1),this.finishCallHoldResume()}finishCallHoldResume(e){e?this.callHoldResumeDeferred?.reject(e):this.callHoldResumeDeferred?.resolve(),this.isHoldInProgress=!1,this.callHoldResumeDeferred=null}computeCallState(e){let t=3;this._callInLobby?t=10:this.signalingSession.participantManager.localParticipant.isStaging&&(t=13),this.logger.info(`[${e}][computeCallState] the call state will be set to ${t}`),this.setCallState(t,e)}async prepareModalitiesForResume(e){this.mediaStateConfigurationHelper.isSending(1)&&await this.turnOnLocalVideoPreview(e)}async prepareModalitiesForHold(e){await this.turnOffLocalVideoPreview(e)}updateMediaState(e,t){this.setVideoOn(e.video===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.video===this.mediaAgent.constants.MEDIA_STATE.send,t),this.setAudioOn(e.audio===this.mediaAgent.constants.MEDIA_STATE.sendReceive||e.audio===this.mediaAgent.constants.MEDIA_STATE.send,t)}updateScreenSharingState(e,t){this.setScreenSharingOn(e.sharing===this.mediaAgent.constants.MEDIA_STATE.send,t)}onSharingStreamStateChanged(t){const i=Te();this.logger.info(`[${i}] Sharing stream state moved to ${t}`);const n={mediaType:2,mediaDirection:1,mediaStreamState:e.streamingStatetoMediaStreamState(t)};this.event("mediaStreamStateChanged").raise(n),this.callStats.localStats.screenShare.streamStateChanged(t),"stopped"===t&&(this.canToggleScreenSharing=!0,this.stopScreenSharing(),"screenSharingCall"!==this.conversationType||this.participants.some((e=>3===e.state))||this.stop(!0,i))}async startScreenSharing(e,t,i,n=Te()){this.allowScreenSharingControl()&&(this.screenSharingControl.shutdownControlForViewer(),this.screenSharingControl.initControlForSharer(i));const r=this.logger.createFnLogger("StartScreenSharing",n);return r.info("started"),this.canToggleScreenSharing?this.isScreenSharingOn?(r.logSuccess("Resolving early because screen sharing is already on"),Promise.resolve()):(this.screenSharingRenegotiationDeferred&&(r.logFailure("called before the renegotiation deferred for the previous one has been closed"),this.screenSharingRenegotiationDeferred.resolve()),this.screenSharingRenegotiationDeferred=Si(),this.callStats.localStats.newSession(2),this.callStats.localStats.screenShare.start(),this.mediaStateConfigurationHelper.isDisabled(2)&&r.info("sharing modality was skipped till now. Adding it now"),this.canToggleScreenSharing=!1,this.callStats.localStats.screenShare.event(0),this.getScreenHandle(e).acquire().then((()=>(r.logSuccess("sharing stream acquired"),this.mediaStateConfigurationHelper.enableModality(2),this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.updateMediaModalities(void 0,n)))).then((()=>(r.logSuccess("updateMediaModalities done"),this.callStats.localStats.screenShare.negotiationStateChanged("started"),this.setScreenSharingOn(!0,n),this.canToggleScreenSharing=!0,this.screenSharingRenegotiationDeferred.promise))).then((()=>{this.enableControlInjector(),this.callStats.localStats.screenShare.negotiationStateChanged("completed")})).catch((e=>{this.callTelemetry.updateOperationData("StartScreenSharing",{error:De(e)},n),this.setScreenSharingOn(!1,n),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!0,this.disposeSharingScreenHandle();const t=e.error;throw t&&t.code===$n.GlareError?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),r.logFailure("starting screen sharing failure with reason glare")):"ScreenSharingStopped"===e.reason?(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","sharingStopped"),r.logFailure("expectedstarting screen sharing failure with reason stopped")):(this.callStats.localStats.screenShare.negotiationStateChanged("rejected","other"),r.logFailure(e)),e}))):Promise.reject(new Error("cannot start screen sharing"))}async stopScreenSharing(e,t,i=Te()){const n=this.logger.createFnLogger("StopScreenSharing",i);if(n.info("started"),!this.canToggleScreenSharing)return n.logFailure("cannot stop screen sharing"),Promise.reject(new Error("cannot stop screen sharing"));if(!this.isScreenSharingOn&&!this._callOperationHandler.hasPendingOperation("StartScreenSharing"))return n.logFailure("screensharing is not on, ignore this operation"),Promise.resolve();this.screenSharingRenegotiationDeferred&&(this.screenSharingRenegotiationDeferred.reject({reason:"ScreenSharingStopped"}),this.screenSharingRenegotiationDeferred=null),this.mediaStateConfigurationHelper.removeModality(2),this.canToggleScreenSharing=!1;const r=()=>{this.canToggleScreenSharing=!0,this.callStats.localStats.screenShare.stop(),this.disposeSharingScreenHandle(),this.mediaAgent.getDeviceManager().shareSystemSound(!1),this.mediaAgent.getDeviceManager().setAudioSharingRequested(!1)};return this.allowScreenSharingControl()&&this.screenSharingControl.shutdownControlForSharer(),this.updateMediaModalities(void 0,i).then((()=>this.setScreenSharingOn(!1,i))).then(r,(e=>{throw n.logFailure(e),this.callTelemetry.updateOperationData("StopScreenSharing",{error:De(e)},i),r(),e}))}async startDataChannel(e,t=Te()){if(!this.allowDataChannel())throw new Error("startDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.enableModality(3),await this.updateMediaModalities({},t)}async stopDataChannel(e,t=Te()){if(!this.allowDataChannel())throw new Error("stopDataChannel is disabled since ECS flag prohibits it");this.mediaStateConfigurationHelper.removeModality(3),await this.updateMediaModalities({},t)}allowDataChannel(){return this.mediaSession?!!this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&(this.isOneToOnePSTNCall()?this.mediaSession.getSessionConfig().config.enableDataChannelPstn:this.mediaSession.getSessionConfig().config.enableDataChannel):(this.logger.warn("datachannel not allowed as there is no mediaSession"),!1)}isGiveControlEnabled(){const e=this.mediaSession?.getSessionConfig()?.config;return e?e.enableGiveControl:(this.logger.warn("Give take control is not enabled as there is no mediaSession, sessionConfig or sessionConfig.config"),!1)}isInitialSignalingDSHSubscriptionEnabled(){const e=this.mediaSession?.getSessionConfig()?.config;return e?!this.allowDataChannel()||e.enableInitialSignalingDSHSubscription:(this.logger.warn("Initial signaling dsh subscription is enabled as there is no mediaSession, sessionConfig or sessionConfig.config"),!0)}isSignalingDSHFallbackEnabled(){const e=this.mediaSession?.getSessionConfig()?.config;return e?e.enableSignalingDSHFallback:(this.logger.warn("Falling back to Signaling DSH is disabled as there is no mediaSession, sessionConfig or sessionConfig.config"),!0)}allowScreenSharingControl(){return this.screenSharingControl?.isScreenSharingControlEnabled()&&this.allowDataChannel()}updateSignalingDSHMessageSubscription(e){this.signalingSession.updateDominantSpeakerHistoryMessageSubscription(e),e&&this.mediaSession?.getDiagnostics?.().dshDiagnostics.setCurrentActiveStrategy("signaling")}async sendUserEvents(e,t){return this.dataChannel.sendUserEvents(e,t)}async shareSystemSound(e,t=Te()){const i=this.logger.createFnLogger("ShareSystemSounds",t,`shareSystemSound=${e}`);if(!(this.mediaSession&&this.mediaSession.getSessionConfig().mediaConfig.simulcastSessionEnabled&&this.mediaSession.getSessionConfig().config.enableAudioSharing&&this.mediaSession.getSessionConfig().config.requireUserActionForAudioSharing))return i.error("shareSystemSound not allowed"),Promise.reject(60);try{return void this.mediaAgent.getDeviceManager().shareSystemSound(e)}catch{return i.error("shareSystemSound failed with device error"),Promise.reject(58)}}async mute(e=xi()){return this.isMuted?Promise.reject(Un("TransactionDisallowed")):this.muteUnmute(!0,e)}async unmute(e=xi()){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")&&await this._callOperationHandler.waitForOperation("_PromotionToRealtime"),this.muteUnmute(!1,e)}async muteSpeaker(e=Te()){return this.muteUnmuteSpeaker(!0,e)}async unmuteSpeaker(e=Te()){return this.muteUnmuteSpeaker(!1,e)}async muteParticipants(t,i,n=xi()){const r=this.logger.createFnLogger("MuteParticipants",n,`muteScope=${t}`);r.info(`callParticipants count=${i.length}`);const a=e.convertMuteScope(t);if(void 0===a)return r.logFailure(`Unrecognized ${t}`),Promise.reject(new Error("Unrecognized muteScope"));if(gh(this.state,[11,12]))return r.logFailure("Can not mute/unmute during preheat call"),Promise.reject(60);const s=[];return i.forEach((e=>{s.push(e.id)})),this.signalingSession.muteAsync(a,s,n).then((e=>this.handleParticipantsMutedUpdated(e,n))).catch((e=>(this.callTelemetry.updateOperationData("MuteParticipants",{error:De(e)},n),r.logFailure(e),e?.endCode?Promise.reject(e.endCode):Promise.reject(e))))}async startAudio(e,t=Te()){const i=this.logger.createFnLogger("StartAudio",t);if(this.receiveOnlyAudioOnCallStart=!1,3!==this.state)return i.logFailure("Cannot startAudio when call is not connected"),Promise.reject(60);if(this.mediaStateConfigurationHelper.enableModality(0),this.callUsesMixer&&this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.isSending(1))try{await this.turnOnLocalVideoPreview(t)}catch(e){return i.logFailure(e),Promise.reject(25)}const n=await this.startStopAudio(!0,t);return await this.signalingSession.recordTelemetryForStartAudio(n),{code:n}}async stopAudio(e,t=Te()){const i=this.logger.createFnLogger("StopAudio",t);if(3!==this.state)return i.logFailure("Cannot stopAudio when call is not connected"),Promise.reject(60);this.mediaStateConfigurationHelper.removeModality(0);const n=await this.startStopAudio(!1,t);return await this.turnOffLocalVideoPreview(t),await this.signalingSession.recordTelemetryForStopAudio(n),{code:n}}assimilate(e,t,i,n=Te()){return Promise.reject(new Error("Not implemented"))}async merge(e,t,i=Te()){const n=this.logger.createFnLogger("MergeCall",i);n.error(`merge callId ${e.callId} callMergeOptions ${JSON.stringify(t)}`);const r=this.canMerge(e,i);if(!r)return n.info(`Error. ${Ne(r)}`),Promise.reject(Un("TransactionDisallowed"));const a=[];return e.participants.forEach((e=>{a.push(this._callOperationHandler.createPendingOperation("MergeCall",e.id,i))})),(await this.mergeCallByAddParticipantWithReplaces(t,e.participants,e,1,"MergeCall",i,a,void 0))[0]}async mergeParticipants(e,t,i,n,r){const a=this.logger.createFnLogger("MergeParticipants",n),s=[];if(!e)return Promise.reject(Un("Invalid callToMerge"));if(0===t.length)return Promise.reject(Un("Invalid participantIds"));const o=[];for(const i of t){let t=Od(e,i);if(!t&&Dd(e,i)&&(a.info("found self endpoint, use localSignalingParticipant"),t=this.localSignalingParticipant),t){const e=xi(),r={id:t.id,participantId:e,replacementParticipantId:i,nonMaskedId:t.nonMaskedId};s.push(r),o.push(this._callOperationHandler.createPendingOperation("MergeParticipant",e,n))}else{const e={code:406,subCode:5201,phrase:`participantLegId ${i} is invalid!`};o.push(Promise.reject(Un(e)))}}return this.mergeCallByAddParticipantWithReplaces(i,s,e,3,"MergeParticipant",n,o,r)}async mergeWithPickupCode(e,t,i=Te()){const n=this.logger.createFnLogger("MergeWithPickupCode",i);if(n.info(`mergeWithPickupCode: pickup code: ${e}, groupId: ${Ae(t.groupId)}, threadId: ${Me(t.threadId)} messageId: ${t.messageId}`),!e||isNaN(Number(e)))return n.info("mergeWithPickupCode: pickup code cannot be empty"),Promise.reject(Un("mergeWithPickupCode: pickup code cannot be empty"));const r={additionalData:t.additionalData,groupId:t.groupId,threadId:t.threadId,messageId:t.messageId,replacementType:2,pickupCode:Number(e)},a={id:`4:${sn}`};return Promise.resolve().then((()=>Promise.all(this.signalingSession.addParticipantsAsync([a],r,i)))).then((e=>(e.length>0&&this.signalingNotifications.onParticipantJoined(e[0],i),Promise.resolve({code:0,subCode:0,phrase:"TransactionComplete"})))).catch((e=>{n.logFailure(`Participant was not added to call, error=${Ne(e)}`);const t=this._handleParticipantOperationFailure("MergeWithPickupCode",e,i,null,!0).reason;return Promise.reject(e?e.endCode:t||0)}))}async setMaxVideoChannels(e){return Promise.reject(60)}async setMaxVbssChannels(e){return Promise.reject(60)}async stop(e=!1,t=Te(),i,n){const r=this.logger.createFnLogger("StopAudio",t);if(6===this.state)return r.logFailure("Trying to stop a call which is already Disconnecting"),Promise.reject(new Error("cannot stop call in Disconnecting state"));if(7===this.state)return r.logFailure("Trying to stop a call which is already Disconnected"),Promise.reject(new Error("cannot stop call in Disconnected state"));if(this.disposedPromise)return Promise.reject("Call already ended");let a=0;1===this.state&&(a=10);const s=n?{clientReasonSubCode:n.clientSubCode,clientReasonPhrase:n.clientPhrase}:{};n?.clientSubCode===Cn.VDI_DISCONNECTED&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.enabled&&this.mediaSession?.getSessionConfig()?.config.vdiDisconnectedTracking.clientPhrases.includes(n?.clientPhrase)&&(s.code=yn.MEDIA_ERROR,s.subCode=Cn.VDI_DISCONNECTED,s.phrase=ur,s.resultCategories=["UnexpectedClientError"],a=4);const o={terminatedReason:a,forEveryone:e,causeId:t,...i,rejectReason:s};return this.stopInternal(o)}publishState(e,t){const i=Oa(e.type),n=this.getPluginlessPublishLevel(e.level),r=e.participantIds&&e.participantIds.length>0?"specified":void 0;return this.callTelemetry.setOperationVariant("PublishState","specified"===r?`${i}Specified`:`${i}None`,t),this.signalingSession.publishStateAsync(i,n,t,e.content,r,e.participantIds)}publishStatesForEveryone(e,t){const i=Oa(e.type),n=this.getPluginlessPublishLevel(e.level);return this.callTelemetry.setOperationVariant("PublishState",`${i}All`),this.signalingSession.publishStateAsync(i,n,t,e.content,"all")}removeState(e,t){return this.signalingSession.removeStateAsync(t,"specified",void 0,e.stateIds).then((e=>Promise.resolve()))}removeStatesForEveryone(e,t){const i=Oa(e.type);return this.signalingSession.removeStateAsync(t,"all",i,void 0).then((e=>Promise.resolve()))}updateMeetingSettings(e,t){return this.signalingSession.updateMeetingSettingsAsync({allowRaiseHands:e.allowRaiseHands,attendeeRestrictions:e.attendeeRestrictions,lockMeeting:e.lockMeeting,breakoutRoomsEnabled:e.breakoutRoomsEnabled,allowPresentersToManageBreakoutRooms:e.allowPresentersToManageBreakoutRooms,disableMdpClientAudioRecording:e.disableMdpClientAudioRecording,refreshSettings:e.refreshSettings},t)}updateMeetingGroups(e,t){this.logger.info(`[UpdateMeetingGroups][${e}] options ${Le(t)}`);const i=this._callOperationHandler.waitForOperation("UpdateMeetingGroups",e),n={fromGroup:t.fromGroup,toGroup:t.toGroup,scope:Pg(t.scope)};return t.participants&&(n.participants=function(e){const t=[];for(const i in e)if(e[i].participantLegIdMap)for(const n in e[i].participantLegIdMap){const r=e[i].participantLegIdMap[n].endpointId;t.push({id:i,mri:i,participantId:n,...r&&{endpointId:r}})}else t.push({id:i,mri:i});return t}(t.participants)),this.signalingSession.updateMeetingsGroupsAsync(e,n).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingGroups] error in updateMeetingGroups (synchronous error) : ${De(t)}. updateMeetingGroupsPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingGroups",{error:De(t)},e)})),i}updateMeetingLiveState(e,t){return this.logger.info(`[UpdateMeetingLiveState][${e}] options ${Le(t)}`),this.signalingSession.updateMeetingLiveStateAsync(e,t).catch((t=>{this.logger.info(`[${e}] [UpdateMeetingLiveState] error in updateMeetingLiveState (synchronous error) : ${De(t)}. promise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateMeetingLiveState",{error:De(t)},e)})),this._callOperationHandler.waitForOperation("UpdateMeetingLiveState",e)}updateMeetingStates(e,t=Te()){var i;this.logger.info(`[UpdateMeetingStates][${t}]`);const n={},r=[];e.operationId=e.operationId||t;for(const a of Object.keys(e.meetingStates)){const s=e.operationId+"_"+a;r.push(s);const o=this._callOperationHandler.createPendingOperation("UpdateMeetingStates",s,t);n[i=e.operationId]??(n[i]={}),n[e.operationId][a]=o,this.callTelemetry.recordOperation("UpdateMeetingStates",t,s)}return Promise.resolve().then((()=>this.signalingSession.updateMeetingStatesAsync(t,e))).then((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{data:De(e)},t,i)})).catch((e=>{for(const i of r)this.callTelemetry.updateOperationData("UpdateMeetingStates",{error:De(e)},t,i);this.logger.logFailure(e)})).then((()=>n))}async updateParticipantInterpretationState(e,t){if(this.logger.info(`[UpdateParticipantInterpretationState][${e}] options ${Le(t)}`),0===t.length)return Promise.reject(Un("Invalid UpdateParticipantInterpretationState options"));const i=this.signalingSession.updateParticipantInterpretationStateAsync(e,t),n=[];t.forEach((t=>{n.push(this._callOperationHandler.createPendingOperation("UpdateParticipantInterpretationState",t.id,e))}));for(let n=0;n<i.length;n++){const r=i[n],a=t[n];r.then((()=>{this.logger.logSuccess(`updateParticipantInterpretationState succeeded for [id=${Ae(a.id)}]`);const t={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess("UpdateParticipantInterpretationState",t,a.id,e),this._callOperationHandler.maybeResolveOperation("UpdateParticipantInterpretationState",t,a.id,e)})).catch((t=>{this.logger.error(`[${e}] [UpdateParticipantInterpretationState] error in updateParticipantInterpretationState (synchronous error) : ${De(t)}. updateParticipantInterpretationStatePromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("UpdateParticipantInterpretationState",{error:De(t)},e);const i=this._handleParticipantOperationFailure("UpdateParticipantInterpretationState",t,e,a.id).reason,n=t?.endCode||i||0;this._callOperationHandler.maybeRejectOperation("UpdateParticipantInterpretationState",n,a.id,e)}))}return Promise.resolve(n)}async updateParticipantsProperties(e,t){const i=this.logger.createFnLogger("UpdateParticipantsProperties",t);if(i.info(`options ${Ae(Le(e))}`),!e)return Promise.reject(Un("Invalid input: UpdateParticipantsPropertiesContext"));const n={},r=e.scope,a=e.operationId,s=new Set;if("self"===r){const i=this.signalingSession.participantManager.localParticipant.id;for(const r in e.propertyBag){const e=Ru(i,a,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},s.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,Ae(e))}}else{if("specified"!==r||!this._isUpdatePropertiesSpecifiedAllowedByEcs)return Promise.reject("This scope is not supported.");{const i=e.participants;for(const e of i){const i=e.id;for(const r in e.propertyBag){const e=Ru(i,a,r),o=this.createUpdateParticipantPromise(e,t);n[e]={[i]:o},s.add(e),this.callTelemetry.recordOperation("UpdateParticipantsProperties",t,Ae(e))}}}}return i.info(`promises created: ${Ae(Le(n))}`),this.signalingSession.updateParticipantsPropertiesAsync(e,s,a,t).catch((e=>{const r=Ne(e);i.info(`[failed][reason=${r}]`);const a={...e};this.callTelemetry.updateOperationData("UpdateParticipantsProperties",{error:De(r)},t);for(const e of Object.keys(n))this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",a,e,t)})),Promise.resolve().then((()=>n))}joinMeetingGroup(e,t){this.logger.info(`[JoinMeetingGroup][${e}] options ${Le(t)}`);const i=this._callOperationHandler.waitForOperation("JoinMeetingGroup",e),n={meetingGroupId:t.meetingGroupId,...t.groupPreferences&&{groupPreferences:t.groupPreferences}};return this.signalingSession.joinMeetingGroupAsync(e,n).catch((t=>{const i=De(t);this.logger.info(`[${e}] [JoinMeetingGroup] error in joinMeetingGroup (synchronous error) : ${i}. joinMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("JoinMeetingGroup",{error:i},e)})),i}leaveMeetingGroup(e,t){this.logger.info(`[LeaveMeetingGroup][${e}] options ${Le(t)}`);const i=this._callOperationHandler.waitForOperation("LeaveMeetingGroup",e),n={meetingGroupId:t.meetingGroupId};return this.signalingSession.leaveMeetingGroupAsync(e,n).catch((t=>{const i=De(t);this.logger.info(`[${e}] [LeaveMeetingGroup] error in leaveMeetingGroup (synchronous error) : ${i}. leaveMeetingGroupPromise will be rejected by signaling callback`),this.callTelemetry.updateOperationData("LeaveMeetingGroup",{error:i},e)})),i}sendMessages(e,t){var i,n;this.logger.info(`[SendMessages][${e}]`);const r={};for(const a of t)if(0===a.scope){const t=this._callOperationHandler.createPendingOperation("SendMessages",a.operationId,e);r[a.operationId]={all:t},this.callTelemetry.recordOperation("SendMessages",e,a.operationId)}else if(1===a.scope)for(const t in a.to)if("participant"===a.to[t].level){const n=Iu(t,a.operationId),s=this._callOperationHandler.createPendingOperation("SendMessages",n,e);r[i=a.operationId]??(r[i]={}),r[a.operationId][t]=s,this.callTelemetry.recordOperation("SendMessages",e,n)}else if("endpoint"===a.to[t].level)for(const i in a.to[t].participantLegIdMap){const t=wu(i,a.operationId),s=this._callOperationHandler.createPendingOperation("SendMessages",t,e);r[n=a.operationId]??(r[n]={}),r[a.operationId][i]=s,this.callTelemetry.recordOperation("SendMessages",e,t)}return this.signalingSession.sendProxiedMessageAsync(e,t).then((e=>{for(const t of e)t.then((e=>{this._callOperationHandler.maybeResolveOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)})).catch((e=>{this._callOperationHandler.maybeRejectOperation("SendMessages",e.transactionEnd,e.resolveString,e.causeId)}));return r}))}updateMonitorSession(e,t=Te()){return Promise.reject(new Error("Not implemented"))}async updateMeetingRoles(e,t,i=Te()){return 3===this.state&&this.signalingSession.hasOwnProperty("updateMeetingRolesAsync")?this.signalingSession.updateMeetingRolesAsync(e,t,i):Promise.reject({code:yn.CLIENT_ERROR_CODE,subCode:Cn.ACTION_NOT_ALLOWED,phrase:"ActionNotAllowed"})}stopInternal(e){const t=this.logger.createFnLogger("stopInternal",e.causeId),i=e.terminatedReason||0;let n=e.rejectReason&&(e.rejectReason.code||e.rejectReason.subCode)?e.rejectReason:this.getRejectionInfoFromTerminatedReason(i);if(e.rejectReason&&(n||(n={}),n.clientReasonSubCode=e.rejectReason.clientReasonSubCode,n.clientReasonPhrase=e.rejectReason.clientReasonPhrase),t.info(`started, terminatedReason=${i}, rejectReason=${Le(n)}`),6===this.state)return t.logFailure("Trying to stop a call which is already Disconnecting"),this.disconnectingPromise;if(7===this.state)return t.logFailure("Trying to stop a call which is already Disconnected"),this.disconnectingPromise;this.setCallState(6,e.causeId,i);const r={causeId:e.causeId,forEveryone:e.forEveryone,scope:this.mapEndpointScope(e.scope),redirectOptions:e.redirectOptions&&zh(e.redirectOptions)};return 1===e.scope&&(n.code=yn.SUCCESS,n.subCode=Cn.ENDED_BY_REMOTE_ENDPOINT,n.phrase=cr),this.disconnectingPromise=Promise.all([this.cleanUpMedia(e.causeId,n).catch((e=>{throw t.logFailure(`cleanUpMedia failed with reason=${Ne(e)}`),e})),this.signalingSession.endAsync(n,r).catch((e=>{throw t.logFailure(`endAsync failed with reason=${Ne(e)}`),e}))]).catch((i=>{throw t.logFailure(i),this.cleanUp(e.causeId,n),i})).then((()=>this.cleanUp(e.causeId,n))).catch((t=>{throw this.callTelemetry.updateOperationData("StopCall",{error:De(t)},e.causeId),this.setCallState(7,e.causeId,i),t})),this.disconnectingPromise}async cleanUp(e,t){return this.logger.info(`[${e}][cleanup]start`),this.disposedPromise||(this.disposedPromise=this.cleanUpFinalize(e,t),this._getCallEndOperation().catch(Sn).then((()=>{const t={code:yn.CLIENT_ERROR_CODE,subCode:Cn.ABANDONED};this._callOperationHandler.rejectPendingOperations(61,e,t),this._participantOperationHandler.rejectPendingOperations(47,e,t)}))),this.disposedPromise}async cleanUpMedia(e,t){return this.mediaDisposedPromise||(this.mediaDisposedPromise=(async()=>{this.callDeviceManager?.dispose(),this.callDeviceManager=null,this.turnOffLocalVideoPreview(e),this.localVideoContainer=null,this.disposeContentSharingSessions(),this.disposeSharingScreenHandle();const i=this.mediaSession;if(this.reportMediaStats=!!i,!i)return;this.unmixedAudioProvider.dispose(),this.mediaControlPlane.dispose(),this.dataChannel.dispose(),this.screenSharingControl.dispose(e),this.mediaSession=null,this.streamManager.setMediaSession(null,e),this.participants?.forEach((t=>{t.setMediaSession(null,e)}));const n=i.terminate(e,t);this.isVideoOn=!1,this.setMediaStream(this.isVideoOn,!1,1),this.setMediaStream(!1,!1,2),this.setMediaStream(!1,!1,0),this.isScreenSharingOn=!1,this.screenSharingRenegotiationDeferred?.reject(t),this.screenSharingRenegotiationDeferred=null,this.mediaStateConfigurationHelper.removeModality(1),this.mediaStateConfigurationHelper.removeModality(0),this.mediaStateConfigurationHelper.removeModality(3),this.mediaStateConfigurationHelper.removeModality(2),i?.getSessionConfig()?.config?.useOneDsLogger&&i.getSessionConfig().config.addTelemetryReportingCallback&&window.removeEventListener("beforeunload",this.beforeUnloadTelemetrySender);try{await n}finally{await this.collectCallStats(i)}})()),this.mediaDisposedPromise}async cleanUpFinalize(e,t){try{await this.cleanUpMedia(e,t)}catch(t){this.logger.info(`[${e}][cleanUpMedia] failure: ${Ne(t)}`)}const i=this.reportCallEndStats(this.reportMediaStats);this.mediaSession?.getSessionConfig().config.waitReportStatsAtCallStop&&await i}async createContentSharingSession(e,t,i,n,r=Te()){if("attendee"===(this.advancedMeetingRole||this.meetingRole)){const e={terminatedReason:8,terminatedReasonCode:403,terminatedReasonSubCode:0,errorMessage:"Failed due to insufficient permissions"};return Promise.reject(e)}const a=new Gp(this.callTelemetry,this.logger,this.signalingSession,e,t,n,i);return this.contentSharingSessions.push(a),a.changed((()=>this.removeContentSessionIfEnded(a))),this.event("contentSharingChanged").raise(),Promise.resolve(a)}stopWithBeacon(e=Te()){return 6===this.state||7===this.state||this.signalingSession.endWithBeacon(e)}disposeContentSharingSessions(){this.contentSharingSessions.forEach((e=>{e.dispose(),this.removeContentSessionIfEnded(e)})),this.event("contentSharingChanged").raise()}isPreheatedOnly(){return!!(12===this.state||2===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall")||9===this.state&&this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))}removeContentSessionIfEnded(e){7!==e.contentSharingStatus&&8!==e.contentSharingStatus||(this.logger.info("stopping the content sharing session."),(0,fr.remove)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.contentSharingGuid)).length&&this.event("contentSharingChanged").raise())}getRejectionInfoFromTerminatedReason(e){switch(e){case 53:return{code:$n.MediaError,subCode:Gn.MediaWhiteListingIssue,phrase:rr};case 4:return{code:$n.MediaError,subCode:this._wasAudioStreamConnected?Gn.MediaDropAfterConnect:Gn.MediaDropDuringConnect,phrase:this._wasAudioStreamConnected?er:Xn};case 47:return{code:$n.MediaError,subCode:Gn.MediaOfferProcessingError,phrase:tr};case 38:return{code:$n.MediaError,subCode:Gn.MediaRenegotiationError,phrase:or};case 10:return{code:$n.Reject,subCode:Gn.Success,phrase:lr};case 25:return{code:$n.UnknownError,subCode:Gn.MediaUnknownError,phrase:Qn};case 58:return{code:$n.MediaError,subCode:Gn.MediaPermissionError,phrase:Zn};case 7:return{code:$n.UnknownError,subCode:Gn.Success,phrase:Yn};case 0:case 1:return{code:$n.Success,subCode:Gn.Success,phrase:lr};case 75:return{code:$n.CallRedirected,subCode:Gn.CallRedirectedSuccess,phrase:dr,resultCategories:["Success"]};case 77:return{code:$n.Success,subCode:Gn.Suspended,phrase:hr}}return null}async acknowledge(e,t,i=Te()){const n=this.logger.createFnLogger("Acknowledge",i),r=Date.now();if(this.setInitialTelemetry("Acknowledge",{callStartTime:r},"",i),0!==this.state&&8!==this.state)throw new Error(`Trying to acknowledge a call that has already been acted on ${this.state}`);n.info(`isMultiParty=${e.isMultiParty}`),n.info(`fromMixer=${e.fromMixer}`),n.info(`participantId=${e.participantId}`),n.info(`callType=${e.callType}`),this.attachToCallAndGetOffer=Si(),this.setCallType(e.isMultiParty?2:1,i),this.setCallUsesMixer(!!e.fromMixer,i),this.setCallerMri(ch(e.callerId)),this.setTransferorMri(e.transferorId),this.transferorType=e.transferorType,this.transferorDisplayName=e.transferorDisplayName,this.incomingCallType=e.callType,this.consultativeCallId=e.consultativeCallId,this.callQueueInfo=e.callQueueInfo,this.setFromApplicationType(e.fromApplicationType,i),this.callStats.localStats.startCall();const a=ph(n);try{if(a.executeSync("ProcessIncomingCallRequest",(()=>this.signalingSession.processIncomingCallRequest(e,t,i))),this.setParticipantId(this.participantId),a.executeSync("ResolvePotentialConflict",(()=>this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)))===this.signalingSession)return Promise.reject({code:7,success:!1});const r=async()=>{a.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(i))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled());const e=this.signalingSession.getInitialMediaOfferFromIncomingCallPayload();this.callStats.setParticipantId(this.participantId),this.onBehalfOfMri=this.signalingSession.onBehalfOf,this.onBehalfOfUserDisplayName=this.signalingSession.onBehalfOfUserDisplayName,this.callQueueContext=this.signalingSession.callQueueContext,this.callPhoneLineType=this.signalingSession.callPhoneLineType;const t=await a.execute("WaitForMediaOffer",(()=>e?Promise.resolve(e):this.attachToCallAndGetOffer.promise));let r;try{r=await a.execute("ProcessOffer",(()=>this.mediaSession.processOfferAsync(t,i)))}catch(e){r=await this._handleOfferProcessingError(e,i,n)}await a.execute("ProcessOfferedModalities",(()=>this._processOfferedModalities(r,i))),await a.execute("TrySendingProvisionalAnswer",(()=>this._trySendProvisionalMediaAnswer(i)))},s=(()=>a.execute("SendAttach",(()=>this.signalingSession.sendAttachToCall(i))).then((()=>this.setCallState(1,i))))();return await Promise.all([s,r()]).catch((async e=>{throw await s,e})),a.executeSync("OnAcknowledgeSuccess",(()=>this._onAcknowledgeSuccess(n,a.getTelemetryData(),i)))}catch(e){return this._onAcknowledgeError(e,i,n,a.getTelemetryData())}}async accept(e,t=Te()){const i=this.logger.createFnLogger("Accept",t);if(i.info(`accept, answerMediaType: ${e.answerMediaType},\n                            withVideo: ${e.withVideo},\n                            muted: ${e.muted},\n                            getSendMediaModalities: ${JSON.stringify(e.sendMediaModalities)},\n                            clientEndpointCapabilities: ${e.clientEndpointCapabilities},\n                            muteFlags: ${e.muteFlags}`),1!==this.state)throw new Error("Only calls in Notified state can be accepted");this.setCallOptions({callStartOptions:e,callStartTime:Date.now()}),this.setSessionIceTransportPolicy(e?.mediaConfiguration);const n=this._callOperationHandler.createPendingOperation("_ConnectCall",void 0,t);this.callStats.localStats.audio.start();const r=ph(i);this.mediaSession.createAudioElement(t);const a=e.muted||!(1&~e.muteFlags);this.setMuted(a?2:this.isServerMuted?1:0,t),this.setCallState(2,t),this.connectCallPromise=this._callOperationHandler.waitForOperation("Accept");try{e.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient(),this.mediaStateConfigurationHelper.setCallAcceptOptions(e),this.mediaStateConfigurationHelper.isSending(1)&&await r.execute("StartVideoSafe",(()=>this.startVideoSafe(t))),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,t);const a=await r.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,t))),s=r.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(a))),o=await r.execute("evaluateEndpointStatesForAccept",(()=>this.evaluateEndpointStatesForAccept(2===this._muteState,e?.additionalEndpointProperties,t))),l=r.execute("handleEndpointStatesForAccept",(()=>this.handleEndpointStatesForAccept(o,t)));i.info("Queued the handleEndpointStatesForAccept");const c=await r.execute("CreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t)));await r.execute("Accept",(()=>this.signalingSession.acceptAsync(c,s,e.clientEndpointCapabilities,t))),await r.execute("WaitForConnect",(()=>n)),this.handleRemoteParticipantStateInOneToOneCall(t),await r.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t))),await l,this.callTelemetry.updateOperationData("Accept",{phases:r.getTelemetryData()},t)}catch(e){let n=7,r={};throw this.callTelemetry.updateOperationData("Accept",this.getTelemetryFromPhaseExecution(e),t),e?.error&&(r={...e.error}),uh(gr,e)&&(n=47),this.mediaSession?.getSessionConfig().config.stopCallOnAcceptFailure&&this.stopInternal({terminatedReason:n,causeId:t,rejectReason:r}),e.terminatedReason=n,i.logFailure(e),e}}async reject(e=Te(),t){const i=t?{clientReasonSubCode:t.clientSubCode,clientReasonPhrase:t.clientPhrase}:{};return 1!==this.state?Promise.reject(60):this.stopInternal({terminatedReason:10,causeId:e,rejectReason:i})}async join(e,t={},i=Te()){const n=Date.now();return this.setInitialTelemetry("JoinCall",{callStartOptions:t,callStartTime:n},e.conversationUrl,i),this.setCallerMri(ch(e.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinCall"),this.joinOrStartCall({callStartOptions:jh(t),callStartTime:n},this.joinGivenConversation,i,e.conversationUrl)}async joinPreheatedCall(e,t){const i=this.logger.createFnLogger("JoinPreheatedCall",t),n=this.isServerMuted||!(1&~e.muteFlags),r=!(2&~e.muteFlags),a=ph(i);this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinPreheatedCall");try{const i={endpointProperties:{preheatProperties:0}};this.setCallState(2,t),this.isCallModeStreaming()||(n?i.state={isMuted:!0}:(await a.execute("UnmuteInput",(()=>this.mediaSession.unmuteInputAsync(t))),this.setMuted(0,t)),r||(await a.execute("UnmuteOutput",(()=>this.mediaSession.unmuteOutputAsync(t))),this.setSpeakerMuted(!1,t))),await this.signalingSession.updateEndpointState(i,t,e.publishedStates),this.computeCallState(t)}catch(e){const n=7;let r;return i.logFailure(` error: ${n} ${Ne(e)}`),Fn(e)?r=e:hh("UnmuteInput",e)?r={code:$n.LocalError,subCode:Gn.MediaUnmuteMicrophoneError,phrase:Ne(e),causeId:t}:hh("UnmuteOutput",e)&&(r={code:$n.LocalError,subCode:Gn.MediaUnmuteSpeakerError,phrase:Ne(e),causeId:t}),this.callTelemetry.updateOperationData("JoinPreheatedCall",{phases:a.getTelemetryData(),error:De(e)},t),this.stopInternal({causeId:t,terminatedReason:n,rejectReason:r}),Promise.reject(r)}}async start(e={},t=Te()){const i=Date.now();return this.setCallerMri(lh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCall",{callStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCall"),this.joinOrStartCall({callStartOptions:jh(e),callStartTime:i},this.startOutgoingCall,t)}async startCallToVoicemail(e,t=Te()){const i=Date.now();return this.setCallerMri(lh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartCallToVoiceMail",{callVoicemailStartOptions:e,callStartTime:i},"",t),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallToVoiceMail"),this.joinOrStartCall({callVoicemailStartOptions:e,callStartTime:i},this.startVM,t)}async joinCallWithoutCallModality(e,t={},i=Te()){const n=Date.now();this.setCallerMri(e.groupCallInitiator),this.setCallType(2,i);const r={callStartOptions:jh(t),callStartTime:n};return this.setInitialTelemetry("Subscribe",r,e.conversationUrl,i),0!==this.state?(this.logger.info(`[${i}][joinCallWithoutCallModality]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,i),this.signalingSession.subscribeToCall(e.conversationUrl,this.callId,t.clientEndpointCapabilities,{meetingRegistrationId:t.meetingRegistrationId,participantPin:t.participantPin,clientEndpointDebugContent:t.clientEndpointDebugContent,additionalEndpointProperties:t.additionalEndpointProperties},i).catch((e=>Fn(e)?(this.logger.info(`[${i}][joinCallWithoutCallModality] ${Ne(e)}`),Promise.reject(e)):Promise.reject(Bh(e)))),this._callOperationHandler.waitForOperation("Subscribe",void 0,i))}startWithMeetingData(e,t){const i=Date.now();return this.setCallerMri(lh+this.currentUserSkypeIdentity.id),this.setInitialTelemetry("StartWithMeetingData",{callStartOptions:t,callStartTime:i},"",e),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartWithMeetingData"),this.joinOrStartCall({callStartOptions:jh(t),callStartTime:i,meetingPreferences:{shouldResurrect:t.shouldResurrect}},this.startOutgoingCall,e)}joinWithMeetingData(e,t,i){const n=Date.now();return this.setInitialTelemetry("JoinWithMeetingData",{callStartOptions:i,callStartTime:n},t.conversationUrl,e),this.setCallerMri(ch(t.groupCallInitiator)),this.connectCallPromise=this._callOperationHandler.waitForOperation("JoinWithMeetingData"),this.joinOrStartCall({callStartOptions:jh(i),callStartTime:n,meetingPreferences:{shouldResurrect:i.shouldResurrect}},this.joinGivenConversation,e,t.conversationUrl)}subscribeWithMeetingData(e,t,i){const n=Date.now();this.setCallerMri(t.groupCallInitiator),this.setCallType(2,e);const r={callStartOptions:jh(i),callStartTime:n};return this.setInitialTelemetry("SubscribeWithMeetingData",r,t.conversationUrl,e),0!==this.state?(this.logger.info(`[${e}][subscribeWithMeetingData]Trying to subscribe to a call that has already been acted on`),Promise.reject(60)):(this.setCallOptions(r),this.setCallState(8,e),this.signalingSession.subscribeToCall(t.conversationUrl,this.callId,i.clientEndpointCapabilities,{meetingPreferences:{shouldResurrect:i.shouldResurrect},meetingData:this.meetingData,meetingRegistrationId:i.meetingRegistrationId,participantPin:i.participantPin,additionalEndpointProperties:i.additionalEndpointProperties},e).catch((t=>Fn(t)?(this.logger.info(`[${e}][subscribeWithMeetingData] ${Ne(t)}`),Promise.reject(t)):Promise.reject(Bh(t)))),this._callOperationHandler.waitForOperation("SubscribeWithMeetingData",void 0,e))}async startCallWithNudge(e,t={},i=Te()){this.setCallerMri(lh+this.currentUserSkypeIdentity.id),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallWithNudge");const n=Date.now();if(this.logger.info(`[${i}][startCallWithNudge]startCallWithNudge for participants: ${function(e){return e.forEach(Ae)}(e)}`),this.participants.length)return Promise.reject(48);if(t.isCast&&t.isHuddleGroupCall)return this.logger.logFailure(`isCast: ${t.isCast} isHuddleGroupCall: ${t.isHuddleGroupCall}`),Promise.reject(new Error("isCast or isHuddleGroupCall can only be set exclusively."));const r={};return r.callStartOptions=jh(t),r.invitationType=Jr.INVITATION_TYPE.NUDGE,r.participantsToNudge=e,r.callStartTime=n,this.setInitialTelemetry("StartCallWithNudge",r,"",i),this.joinOrStartCall(r,this.startOutgoingCall,i)}async startAndUnpark(e,t,i={},n=Te()){this.setCallerMri(lh+this.currentUserSkypeIdentity.id);const r=this.logger.createFnLogger("StartCallAndUnpark",n),a=Date.now();this.setInitialTelemetry("StartCallAndUnpark",{callStartTime:a},"",n),r.info(`startAndUnpark for context: ${e}, pickupCode :${t}`),this.connectCallPromise=this._callOperationHandler.waitForOperation("StartCallAndUnpark");const s={};switch(s.callStartOptions=jh(i),s.pickupCode=t,s.parkContext=sn,e){case 0:s.parkContext=rn;break;case 1:s.parkContext=an;break;case 5:s.parkContext=on;break;case 2:s.parkContext=sn;break;default:throw new Error(`[startAndUnpark] unsupported ParkContext name: ${e}`)}return this.addParticipant(`4:${s.parkContext}`).catch((e=>r.logFailure("Failed to add participant to unparked call"))),this.joinOrStartCall(s,this.startOutgoingCall,n)}async admitParticipant(e,t=Te()){const i=dh(e),n=this.getParticipant(i),r=this._getParticipantLegId(n),a=r?{participantLegId:r}:{};if(n&&7!==n.state){const i={code:0,subCode:3552,phrase:"Participant is not in lobby state"};return this.callTelemetry.maybeRecordOperationSuccess("AdmitParticipant",i,e,t,a),Promise.reject(i)}return this.admitParticipantToCall(i,t,r)}admit(e,t){return this.signalingSession.admitAsync(t)}async callMeBack(e,t,i=Te()){const n=dh(`${lh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri);return this.addCallMeBackParticipant(e,t||n,i)}async addParticipant(e,t={},i=Te()){return(await this.addParticipantsImpl([e],t,i,"addParticipant"))[0]}async addParticipants(e,t={},i=Te()){return this.addParticipantsImpl(e,t,i,"addParticipants")}async addParticipantsImpl(e,t={},i=Te(),n){if(this.logger.info(`[${i}][${n}] start`),this.isEmergency&&0===this.state&&(0!==this.participants.length||1!==e.length))return Promise.reject(new Error("Only 1 participant (the emergency operator) may be added to unstarted emergency calls"));if(t.participantInvitationData)try{JSON.stringify(t.participantInvitationData)}catch(e){throw this.logger.info(`[${i}][${n}] ${e}`),e}const r=[],a=[];if(e.forEach((e=>{const t=this.getOrCreateParticipant(e,i,!0);0===t.state||4===t.state?(a.push(t),r.push(this._participantOperationHandler.createPendingOperation("AddParticipant",t.id,i))):3===t.state?r.push(Promise.resolve(t)):this._participantOperationHandler.hasPendingOperationWithOperationId("AddParticipant",t.id)&&r.push(this._participantOperationHandler.waitForOperation("AddParticipant",t.id))})),0===a.length)return Promise.resolve(r);const s=!!t.disableUnmute,o=this.addParticipantsToCall(a,i,t.participantInvitationData,t.groupId,t.threadId,t.messageId,s,t.alternateId);return(0,fr.zip)(o,a).forEach((async([e,t])=>{try{await e;const n=this._getParticipantLegId(this.getParticipant(t.id)),r=n?{participantLegId:n}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},t.id,i,r),this._participantOperationHandler.maybeResolveOperation("AddParticipant",t,t.id,i)}catch(e){this._participantOperationHandler.maybeRejectOperation("AddParticipant",e,t.id,i)}})),this.raiseChanged(this._participantChangedEventSkipConfig),Promise.resolve(r)}async nudgeParticipants(e,t,i={},n=Te()){return 2!==this.state&&3!==this.state?Promise.reject(48):this.signalingSession.nudgeParticipantsAsync({participantsIds:t,causeId:n,invitationData:i.participantInvitationData,newGroupId:i.groupId,newThreadId:i.threadId,newMessageId:i.messageId})}mapEndpointScope(e){let t="none";switch(e){case 0:t="specified";break;case 1:case 1:t="all";break;default:t="none"}return t}async removeParticipant(e,t=Te(),i,n){const r=this.logger.createFnLogger("removeParticipant",t);r.info("start");const a=this.mapEndpointScope(n);return this.signalingSession.removeParticipantAsync({id:e,endpointId:i},t,a).catch((i=>{r.logFailure(`Participant was not removed from call, error=${i}`);const n=this._handleParticipantOperationFailure("RemoveParticipant",i,t,e).reason;return Promise.reject(n||38)}))}async searchParticipants(e,t){return this.signalingSession.searchParticipantsAsync(e.searchQueryOptions,t)}async getAllParticipants(e,t){return this.signalingSession.getAllParticipantsAsync(e.scope,t)}set dominantSpeakerInfo(e){this.internalDominantSpeakerInfo=e}get dominantSpeakerInfo(){return this.internalDominantSpeakerInfo?this.internalDominantSpeakerInfo:this.mediaSession?.getSessionConfig().config.emptyInitialDSH?{speakerList:[],timestamp:null,noCurrentDominantSpeaker:!1}:{speakerList:this.participants.filter((e=>3===e.state)).map((e=>e.id)),timestamp:null,noCurrentDominantSpeaker:!1}}set slowedDownActiveTalkerInfo(e){(0,fr.isEqual)(this.internalSlowedDownActiveTalkerInfo?.speakerList,e.speakerList)||(this.internalSlowedDownActiveTalkerInfo=e,this.raiseChanged())}get slowedDownActiveTalkerInfo(){return this.internalSlowedDownActiveTalkerInfo}startVideoSafe(e){return this.startVideo(e).catch((t=>{this.logger.info(JSON.stringify(t),"startVideoSafe",e)}))}async joinOrStartCall(e,t,i,n){const r=this.logger.createFnLogger("joinOrStartCall",i);if(0!==this.state&&8!==this.state&&!e.isPromotingToRealtime){const e="Trying to start a call that has already been acted on";return r.logFailure(e),Promise.reject(60)}if(this.signalingAgent.resolvePotentialCallConflict(this.signalingSession)===this.signalingSession)return Promise.reject(57);this.callStats.localStats.startCall();const a=8===this.state||1!==this.participants.length;r.info(`isMultiparty=${a}, reason: participants.length=${this.participants.length}`),this.setCallType(a?2:1,i),this.setCallUsesMixer(a,i),this.setCallOptions(e);const s=e.callStartOptions||{};if(1&~s.preheatFlags){const e=!!s&&(s.muted||!(1&~s.muteFlags));this.setMuted(e?2:this.isServerMuted?1:0,i),this.setCallState(2,i)}else this.setMuted(2,i),this.setSpeakerMuted(!0,i),this.setCallState(11,i);const o=((e,t,i,n,r)=>{if(e){if(e.meetingUrl)return"MeetingUrl";if(e.meetingCode)return"MeetingCode"}return t||i?"ThreadContext":n?"GroupId":r?"Awareness":""})(this.meetingData,this.threadId,this.messageId,this.groupId,!!n);this.callTelemetry.setJoinedFrom(o),this.signalingSession.setJoinedFrom(o),this.setHuddleGroupCall(!!e.callStartOptions?.isHuddleGroupCall);const l=this._callOperationHandler.createPendingOperation("_ConnectCall","",i);return l.catch(Sn),await this.joinOrStartWithMedia(e,t,e.callStartTime,l,i,n),e.callStartOptions?.meetingRegistrationId&&this.callTelemetry.setHasMeetingRegistrationId(!0),e.callStartOptions?.participantPin&&this.callTelemetry.setHasParticipantPin(!0),l}setSessionIceTransportPolicy(e){const t=e?.connectionType;let i=Qe.ICE_TRANSPORT_POLICY.all;switch(t){case"AllSupported":i=Qe.ICE_TRANSPORT_POLICY.all;break;case"NoDirectConnection":i=Qe.ICE_TRANSPORT_POLICY.relay}this.mediaSession?.getSessionConfig().setIceTransportPolicy?.(i)}async joinOrStartWithMedia(e,t,i,n,r,a){const s=this.logger.createFnLogger("joinOrStartWithMedia",r);this.callStats.localStats.audio.start();const o=e.callStartOptions,l=o&&1&o.preheatFlags,c=ph(s);if(e.callStartOptions?.sendMediaModalities&&(this.mediaStateConfigurationHelper=new Wh(e.callStartOptions.sendMediaModalities)),this._preferredMpLocation){e.callStartOptions=e.callStartOptions||{};const t=e.callStartOptions.clientEndpointDebugContent?JSON.parse(e.callStartOptions.clientEndpointDebugContent):{};e.callStartOptions.clientEndpointDebugContent=JSON.stringify({preferredMpLocation:this._preferredMpLocation,...t})}try{o&&!l&&this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)&&this.mediaStateConfigurationHelper.isSending(2)&&(this.setCallUsesMixer(!0,r),await this.getScreenHandle().acquire()),this.mediaStateConfigurationHelper.isSending(0)&&this.setAudioOn(!0,r),this.callUsesMixer||this.mediaStateConfigurationHelper.disableModality(2),s.info(`skipSharingModality=${!this.callUsesMixer}`),c.executeSync("InitializeMediaSession",(()=>this.initializeMediaSession(r))),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.getSessionConfig().config.alwaysNegotiateDataChannel&&this.mediaStateConfigurationHelper.enableModality(3),this.setSessionIceTransportPolicy(e?.callStartOptions?.mediaConfiguration),this.mediaSession.createAudioElement(r),this.callUsesMixer||a||this.isOneToOnePSTNCall()||e.callVoicemailStartOptions||(this.isSomeoneStreamingVideo=!0);const d=this._callOperationHandler.createPendingOperation("_WaitForAnswer","",r,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]});d.catch(Sn);let u=!1;e.isPromotingToRealtime?(this.isSpeakerMuted=!0,u=!0,await c.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await c.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r)))):o&&(l?(u=!0,await c.execute("MuteInput",(()=>this.mediaSession.muteInputAsync(r))),await c.execute("MuteOutput",(()=>this.mediaSession.muteOutputAsync(r))),this.setMuted(2,r),this.setCallUsesMixer(!0,r)):this.mediaStateConfigurationHelper.isSending(1)&&await c.execute("StartVideoSafe",(()=>this.startVideoSafe(r)))),o?.forceAudioSendModalityWithNullStream&&this.mediaSession.useNullAudioStreamClient();const h=await c.execute("UpdateMediaModalities",(()=>this.updateMediaModalities(void 0,r))),p=await c.execute("CreateOffer",(()=>this.mediaSession.createOfferAsync(r))),g=c.executeSync("GetSignalingMediaTypes",(()=>this.getSignalingMediaTypes(this.calculateModalityDirections({},r))));if(this.mediaStateConfigurationHelper.isSending(2)&&this.updateScreenSharingState(h,r),u||(await c.execute("MuteUnmute",(()=>this.muteUnmute(2===this._muteState,r))),await c.execute("MuteUnmuteSpeakers",(()=>this.muteUnmuteSpeaker(this.isSpeakerMuted,r)))),c.executeSync("CallStart",(()=>t(r,e,p,g,i,a))),await c.execute("WaitForConnect",(()=>n)),!this.isCallModeStreaming()||e.isPromotingToRealtime){const e=await c.execute("WaitForAnswer",(()=>d));if(!this.mediaSession?.processAnswerAsync)throw{error:"NoMediaSession",phase:"ProcessAnswer"};await c.execute("ProcessAnswer",(()=>this.mediaSession.processAnswerAsync(e,r,!1))),await c.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(r)))}this.callTelemetry.updateOperationData("_ConnectCall",{phases:c.getTelemetryData()},r),2!==o?.screenshareDirection&&4!==o?.screenshareDirection||(this.screenSharingControl.initControlForSharer(""),this.enableControlInjector())}catch(e){this.catchJoinOrStartCallError(e,r,s,c.getTelemetryData())}}catchJoinOrStartCallError(e,t,i,n){let r,a=0;throw i.logFailure(Ne(e)),e?.error&&(r={...e.error}),hh("MuteInput",e)?(a=7,r={code:$n.LocalError,subCode:Gn.MediaMuteMicrophoneError,phrase:Ne(e),causeId:t}):hh("MuteOutput",e)?(a=7,r={code:$n.LocalError,subCode:Gn.MediaMuteSpeakerError,phrase:Ne(e),causeId:t}):e?.type===this.mediaAgent.constants.MEDIA_ERROR.incompatibleOffer||uh(gr,e)?a=47:e?.type===this.mediaAgent.constants.MEDIA_ERROR.permissionDeniedError?(a=58,r={code:$n.MediaError,subCode:Gn.MediaPermissionError,phrase:Ne(e),causeId:t}):hh("WaitForAnswer",e)||hh("WaitForConnect",e)?a=e.error:uh(pr,e)&&(a=7),this.callTelemetry.updateOperationData("_ConnectCall",this.getTelemetryFromPhaseExecution(e),t),this.callSetupFailed=!0,Promise.all([this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",a,"",t),this._callOperationHandler.maybeRejectOperation("_ConnectCall",a,"",t)]).then((()=>{this.isPromotingToRealtime()||this.stopInternal({causeId:t,terminatedReason:a,rejectReason:r})})).catch(Sn),a}addCallMeBackParticipant(e,t,i){const n=this._participantOperationHandler.waitForOperation("CallMeBack",e),r=this.logger.createFnLogger("CallMeBack",i),a={id:e,assertedId:t};return this.signalingSession.callMeBackAsync(a).then((()=>{r.logSuccess(`successfully executed call me back, participantId = ${Ae(e)}`),this._participantOperationHandler.resolveOperation("CallMeBack",0,e)})).catch((n=>{r.logFailure(`Call me back failed, participantId = ${Ae(e)}, error = ${n}`),this._handleParticipantOperationFailure("CallMeBack",n,i,t,!1);const a=this._processError(n);let s={};a&&(s={...a}),s.failureReason=a.reason?a.reason:11,this._participantOperationHandler.rejectOperation("CallMeBack",s,e)})),n}addParticipantsToCall(e,t,i,n,r,a,s,o){const l=this.logger.createFnLogger("addParticipantsToCall",t);e.forEach((e=>{e.setState(1,void 0,t)}));const c=e.map((e=>({id:e.mri})));l.info(`participantIds=${e.map((e=>Ae(e.id)))}, disableUnmute=${s}`);const d={additionalData:i,groupId:n,threadId:r,messageId:a,disableUnmute:s,alternateId:o};try{const e=this.signalingSession.addParticipantsAsync(c,d,t);return(0,fr.zip)(e,c).map((async([e,i])=>{try{const n=await e;this.signalingNotifications.onParticipantJoined(n,t);const r=this._getParticipantLegId(this.getParticipant(i.id)),a=r?{participantLegId:r}:{};this.callTelemetry.recordOperationSuccess("AddParticipant",{code:0,subCode:0,phrase:""},n.id,t,a)}catch(e){const n=this._handleParticipantOperationFailure("AddParticipant",e,t,i.id).reason;throw this._removeParticipant(i,t,n),n}}))}catch(e){return l.logFailure(`Participants was not added to call, error=${e}`),(0,fr.range)(c.length).map((()=>Promise.reject(1)))}}async mergeCallByAddParticipantWithReplaces(e,t,i,n,r,a,s,o){const l=this.logger.createFnLogger("mergeCallByAddParticipantWithReplaces",a),c=this.convertClientScenario(o),d={additionalData:e.additionalData,groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,callIdToReplace:i.callId,replacementType:n,clientScenario:c},u=await this.signalingSession.addParticipantsAsync(t,d,a);for(let e=0;e<u.length;e++){const i=3===n?t[e].participantId:t[e].id;try{await u[e],l.logSuccess(` [participantInfos id =${Ae(t[e].id)}]`);const n={debugContent:{replacementParticipantLegId:t[e].replacementParticipantId||void 0,clientScenario:c},participantLegId:t[e].participantId},s={code:0,subCode:0,phrase:""};this.callTelemetry.recordOperationSuccess(r,s,i,a,n),this._callOperationHandler.maybeResolveOperation(r,s,i,a)}catch(n){l.logFailure(`Participant was not added to call, error=${Le(n)}`);const s=this._handleParticipantOperationFailure(r,n,a,i,!0,c).reason;this._removeParticipant(t[e],a,s);const o=n?n.endCode:s||0;this._callOperationHandler.maybeRejectOperation(r,o,i,a)}}return Promise.resolve(s)}admitParticipantToCall(e,t,i){const n=this.logger.createFnLogger("admitParticipantToCall",t),r={id:e};return n.info("start"),this.signalingSession.admitParticipantAsync(r,t).then((r=>{n.info(`successfully admitted participant to call, participantId = ${Ae(e)}`);const a=i?{participantLegId:i}:{};this.callTelemetry.recordOperationSuccess("AdmitParticipant",{code:0,subCode:0,phrase:""},e,t,a)})).catch((i=>{n.logFailure(`Participant was not admitted to call, error=${i}`);const r=this._handleParticipantOperationFailure("AdmitParticipant",i,t,e);return Promise.reject(r)}))}_processError(t){let i;const n={reason:i};if(t?.endCode){const r=Hh(t.endCode.code,t.endCode.subCode);i=e.getParticipantReasonFromTerminatedReason(r),n.reason=i,n.code=t.endCode.code,n.subCode=t.endCode.subCode,n.resultCategories=t.endCode.resultCategories,n.phrase=t.endCode.phrase}else n.phrase=`${t}`;return this.logger.info(`_processError error=${t} telemetryData=${JSON.stringify(n)}`),n}_handleParticipantOperationFailure(e,t,i,n,r=!0,a){this.callTelemetry.updateOperationData(e,{error:De(t)},i,n);const s=this._processError(t),o=this.getParticipant(n);s.code&&o&&(o.callEndDiagnosticsInfo={callControllerCode:s.code,callControllerSubCode:s.subCode,phrase:s.phrase,resultCategories:s.resultCategories});try{if(r){const t={debugContent:{clientScenario:a},participantLegId:this._getParticipantLegId(o)||void 0};this.callTelemetry.recordOperationFailure(e,s,n,i,t)}}catch(e){this.logger.info(`_handleParticipantOperationFailure errow during recordOperationFailure ${e}`)}return s}_getParticipantLegId(e){return(0,fr.has)(e,"endpoints.endpointDetails")&&e.endpoints.endpointDetails.length&&e.endpoints.endpointDetails[0].participantId?e.endpoints.endpointDetails[0].participantId:null}isOneToOnePSTNCall(){const e=this.signalingSession.isIncomingCall?this.callerMri:this.participants.length>0?this.participants[0].id:"";return this.isOneToOneCall()&&(0,fr.startsWith)(e,"4:")&&(!this.incomingCallType||!this.callUsesMixer)}isParkedCall(){return this.isOneToOnePSTNCall()&&!!this.callOptions?.parkContext}async updateMediaModalities(e={},t=Te()){let i;const n=this.logger.createFnLogger("updateMediaModalities",t);return n.info(`callUsesMixer=${this.callUsesMixer},isSomeoneSharing=${this.isSomeoneSharing},isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),n.info(`options=${Le(e)},requestHoldState=${this.requestedHoldState},requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}`),i=e.modalityOverride?e.modalityOverride:this.requestedHoldState&&!this.isMuteOnHold?this.getMediaModalitiesForHold(t):this.calculateModalityDirections(e?.offered,t),n.info(`modalities=${Le(i)}`),await this.mediaSession.configureModalitiesAsync(i,t),i}calculateModalityDirections(e={},t){const i=this.logger.createFnLogger("calculateModalityDirections",t);i.info(`callUsesMixer=${this.callUsesMixer}, isEscalationInProgress=${this.isEscalationInProgress}`);const n={audio:this.calculateAudioDirection(e.audio,i),video:this.calculateVideoDirection(e.video,i),sharing:this.calculateSharingDirection(e.sharing,i),data:this.calculateDataDirection(e.data,i)};return i.info(`done, modalities=${Le(n)}`),this.deleteExtraneousModalities(n,t),n}calculateAudioDirection(e,t){return t.info(`calculateAudioDirection, offer=${e}, requestedAudioState=${this.mediaStateConfigurationHelper.isSending(0)}`),this.receiveOnlyAudioOnCallStart?(t.info("calculateAudioDirection, direction=recvonly, receiveOnlyAudioOnCallStart=true"),"recvonly"):this.mediaStateConfigurationHelper.isInactiveOrDisabled(0)||"inactive"===e?"inactive":this.mediaSession.getAllowedModalities().audio.some((e=>e===fp||e===Sp))?"sendrecv":"sendonly"===e?"inactive":"recvonly"}calculateVideoDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(1);if(t.info(`calculateVideoDirection, offer=${e}, requestedVideoState=${i}, isSomeoneStreamingVideo=${this.isSomeoneStreamingVideo}`),this.mediaStateConfigurationHelper.isInactiveOrDisabled(0))return"inactive";let n=i,r=this.isSomeoneStreamingVideo||this.callUsesMixer||this.isEscalationInProgress;return e&&(n=n&&("sendrecv"===e||"sendonly"===e),r=r&&("sendrecv"===e||"recvonly"===e)),n?"sendrecv":r?"recvonly":"inactive"}calculateSharingDirection(e,t){return t.info(`calculateSharingDirection, offer=${e}, requestedScreenSharingState=${this.mediaStateConfigurationHelper.isSending(2)}, isSomeoneSharing=${this.isSomeoneSharing}`),"inactive"===e?"inactive":this.mediaStateConfigurationHelper.isSending(2)?"sendonly":this.isSomeoneSharing||this.callUsesMixer||this.isEscalationInProgress?"recvonly":void 0}calculateDataDirection(e,t){const i=this.mediaStateConfigurationHelper.isSending(3);if(t.info(`calculateDataDirection, offer=${e}, dataEnabled=${i}`),this.allowDataChannel())return i?"inactive"===e?"inactive":"sendrecv":void 0;t.info("calculateDataDirection, disabling data since ECS flag prohibits it")}getMediaModalitiesForHold(e){this.logger.info(`[${e}][getMediaModalitiesForHold]`);const t="inactive",i={audio:t,video:t,data:this.allowDataChannel()?t:void 0,sharing:t};return this.deleteExtraneousModalities(i,e),i}deleteExtraneousModalities(e,t){!Wg(e.video)&&this.mediaStateConfigurationHelper.isDisabled(1)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping videoModality`),delete e.video),!Wg(e.sharing)&&this.mediaStateConfigurationHelper.isDisabled(2)&&(this.logger.info(`[${t}][deleteExtraneousModalities] skipping sharingModality`),delete e.sharing)}getSignalingMediaTypes(e){const t=[];return e.audio&&e.audio!==this.mediaAgent.constants.MEDIA_STATE.inactive&&t.push("Audio"),(e=>e===this.mediaAgent.constants.MEDIA_STATE.send||e===this.mediaAgent.constants.MEDIA_STATE.sendReceive)(e.video)&&t.push("Video"),e.sharing===this.mediaAgent.constants.MEDIA_STATE.send?t.push("ScreenSharer"):e.sharing===this.mediaAgent.constants.MEDIA_STATE.receive&&t.push("ScreenViewer"),t}enableControlInjector(){if(this.allowScreenSharingControl())if(this.getlocalScreenShareStream()){const e=this.mediaSession?.getLocalMediaTrackId("ScreenShare")??"";this.screenSharingControl.enableControlInjector(e)}else this.logger.warn("enableControlInjector: no local screenshare stream found")}createCallDeviceManager(){return new Pm(this.mediaAgent.getConfigProvider().config.allowVirtualDeviceInCall,this.mediaAgent.getDeviceManager(),this.logger.createChild("CallDeviceManager"),this.callStats,(e=>this.isMediaSending(e)))}initializeSignalingSession(t){if(this.signalingSession)return void this.logger.info("Session already exists!");const i=Jr.CALL_STATUS;if(this.localSignalingParticipant={id:dh(`${lh}${this.currentUserSkypeIdentity.id}`,this.currentUserSkypeIdentity.sipUri),displayName:this.currentUserSkypeIdentity.displayName,endpointDetails:[],languageId:null,participantId:t,endpointId:null},this.accountConfiguration){if(this.localSignalingParticipant.applicationType=this.accountConfiguration.applicationType,this.callTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.localSignalingParticipant.ring=this.accountConfiguration.ring,this.callTelemetry.setRing(this.accountConfiguration.ring),this.localSignalingParticipant.region=this.accountConfiguration.region,this.callTelemetry.setRegion(this.accountConfiguration.region),this.localSignalingParticipant.userHexCID=this.accountConfiguration.userHexCID,this.callTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.localSignalingParticipant.partition=this.accountConfiguration.partition,this.callTelemetry.setPartition(this.accountConfiguration.partition),this.localSignalingParticipant.acsResourceId=this.accountConfiguration.acsResourceId,this.callTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.callStats.setAcsResourceId(this.accountConfiguration.acsResourceId),this.accountConfiguration.serviceUrls){const e=this.accountConfiguration.serviceUrls.calling_conversationServiceUrl,t=this.accountConfiguration.serviceUrls.calling_uploadLogRequestUrl;this.signalingAgent.updateUrls(e,t,this.accountConfiguration.enforceUrls)}this.localSignalingParticipant.clientType=this.accountConfiguration.clientType,this.callTelemetry.setClientType(this.accountConfiguration.clientType)}this.callStats.localStats.setLocalUserId(this.localSignalingParticipant.id),this._callOperationHandler&&this._callOperationHandler.resetOperationChain(),this.signalingNotifications={onPromotionCompleted:(e,t,i)=>{this.logger.info(`[${i}][onPromotionCompleted] isFailed=${e} reason=${Le(t)} callMode=${this.callMode}`);const n=e?t:{code:0,subCode:0};if(this.callTelemetry.recordEvent("PromotionCompleted",{reason:n},i),e){const e=Bh(t);this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",e,"",i),this._callOperationHandler.maybeRejectOperation("_CallStartOrJoinInitiated",e,"",i),this._callOperationHandler.maybeRejectOperation("_ConnectCall",e,"",i),this.promotionCompletedDeferred?.reject(e)}else this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,i),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,i);this.participants.forEach((e=>{e.applyCachedMediaStreams(i)}))},onCallStatusChanged:(e,t,n=Te())=>{const r=this.logger.createFnLogger("onCallStatusChanged",n);let a=`[status=${e}]`;if(t&&(a+=`[reason=${Le(t)}]`,void 0!==t.code&&(this.callEndDiagnosticsInfo={callControllerCode:t.code,callControllerSubCode:t.subCode,phrase:t.phrase,resultCategories:t.resultCategories},(t.overflowJoinInformation||t.registrationInformation)&&(this.callEndDiagnosticsInfo.additionalDiagnostics={overflowInformation:t.overflowJoinInformation,registrationInformation:t.registrationInformation}))),r.info(a),this.callTelemetry.recordEvent("_SignalingStateChanged",{status:e,reason:t},n),e===i.CONNECTING)!this._transfereeAcceptanceWithoutWaitingForConv&&this._transferredCallAcceptanceCallback&&(r.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback()),this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n);else if(e===i.RINGING)2===this.audioStreamState?(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n)))):this.participants.forEach((e=>e.setState(2,void 0,n))),this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n);else if(e===i.CONNECTED_FOR_ROSTER_ONLY)this._callOperationHandler.maybeResolveOperation("Subscribe",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("SubscribeWithMeetingData",void 0,void 0,n);else if(e===i.CONNECTED){this._callIsSetupComplete=!0;const e=this.getLocalSignalingEndpointDetails();(e?.isLobby||e?.streamLobby)&&(this._callInLobby=!0,this.updateCapabilities(n,!0));const t=this.signalingSession.participantManager.localParticipant.isStaging;if(11===this.state)this.setCallState(12,n);else if(this._callOperationHandler.hasPendingOperation("JoinPreheatedCall"))r.info("wait for joinPreheatedCall to resolved");else if(this._callInLobby)r.info("[inLobby] Override Connected state from signaling agent"),this.setCallState(10,n);else if(t)this.setCallState(13,n);else{if(3===this.state&&!this._callOperationHandler.hasPendingOperation("_CallStartOrJoinInitiated")&&!this._callOperationHandler.hasPendingOperation("_ConnectCall"))return void r.info("Return: Don't re-send setup telemetry if call was already connected and operations are completed");this.setCallState(3,n),this.handleRemoteParticipantStateInOneToOneCall(n)}this._callOperationHandler.maybeResolveOperation("_CallStartOrJoinInitiated",void 0,void 0,n),this._callOperationHandler.maybeResolveOperation("_ConnectCall",void 0,void 0,n),this.reportTsCallingTelemetry(!0)}else if(e===i.LOCAL_TERMINATED||e===i.REMOTE_TERMINATED){let a=this.callSetupFailed?7:Bh(t);if(8===this.state&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData"]))return this.signalingSession.resetState(),this._callOperationHandler.maybeRejectOperation("Subscribe",a,void 0,n),this._callOperationHandler.maybeRejectOperation("SubscribeWithMeetingData",a,void 0,n),void r.info("Subscribe failed, there is pending start/join operation, ignore call end message");if(1!==a&&t?.code===$n.MediaError&&t?.subCode===Gn.MediaPermissionError&&(a=58,r.info(`[terminated][reason=${Le(t)}]`)),(2===this.state||6===this.state||8===this.state)&&this._callOperationHandler.hasAtleastOneOfPendingOperation(["StartCall","JoinCall","StartWithMeetingData","JoinWithMeetingData","Subscribe","SubscribeWithMeetingData"])){const e={code:this.callEndDiagnosticsInfo.callControllerCode,subCode:this.callEndDiagnosticsInfo.callControllerSubCode,phrase:this.callEndDiagnosticsInfo.phrase,reason:a};this._callOperationHandler.maybeRejectOperations(["Accept","JoinCall","JoinWithMeetingData","JoinPreheatedCall","StartCall","StartCallAndUnpark","StartCallToVoiceMail","StartCallWithNudge","StartWithMeetingData","Subscribe","SubscribeWithMeetingData"],a,void 0,n,e)}this.signalingSession.acceptedElsewhereBy&&(this.acceptedElsewhereBy={id:this.signalingSession.acceptedElsewhereBy.id,displayName:this.signalingSession.acceptedElsewhereBy.displayName}),this.signalingSession.parkAdditionalContextJson&&(this.parkAdditionalContextJson=this.signalingSession.parkAdditionalContextJson),this.signalingSession.serverHoldLocation&&(this.serverHoldLocation=this.signalingSession.serverHoldLocation),this._callOperationHandler.hasPendingOperation("CallParkV2")&&t.pickupCode&&0===t.code&&this._callOperationHandler.resolveOperation("CallParkV2",""+t.pickupCode,void 0,n),1!==a&&this.mediaRelayWhiteListingIssue&&(a=53,r.info(`[terminated][reason=${Le(t)}]`)),this._callOperationHandler.maybeRejectOperation("CallParkV2",a,"",n),this._callOperationHandler.maybeRejectOperation("_WaitForAnswer",a,"",n),this._callOperationHandler.maybeRejectOperation("_ConnectCall",a,"",n);const s=this.mediaSession?.getSessionConfig().config.setDisconnectAfterCleanUp;if(s?this.setTerminatedReason(a):this.setCallState(7,n,a),this.participants.forEach((e=>e.setState(4,void 0,n))),!this.disconnectingPromise){const a={...t,remoteTerminated:e===i.REMOTE_TERMINATED};this.disconnectingPromise=this.cleanUp(n,a).catch((e=>{r.logFailure(`Error when cleaning up the call, callId = ${this.callId}, error = ${e}`)}))}s&&this.disconnectingPromise.finally((()=>{7!==this.state&&this.setCallState(7,n,a)}))}},onOffer:(e,t=Te())=>{const i=this.logger.createFnLogger("onOffer",t);i.info(`${Le((0,fr.omit)(e,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnOffer",this.prepareTelemetryForOfferAnswer(e),t),e.transferor?.details?.id&&this.setTransferorMri(e.transferor.details.id),e.transferor?.transferorType&&(this.transferorType=e.transferor.transferorType),e.transferor?.details?.displayName&&(this.transferorDisplayName=e.transferor.details.displayName),this.clientTransferContext=e.clientTransferContext,this.invitationData=e.invitationData,this.spamRiskLevel=e.riskLevel,this.spamStirAttestation=e.stirAttestation,e.mediaContent.isTwoPartyToMultiPartyEscalation&&this.setIsEscalationInProgress(!0,t),e.renegotiation?this.requestedHoldState&&this._pendingParkPromise?this.renegotiateIncoming(e.mediaContent,t):this._callOperationHandler.executeChained((()=>this.renegotiateIncoming(e.mediaContent,t)),"_RenegotiateIncoming",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}):(i.info("resolving attach / offer promise"),this.attachToCallAndGetOffer.resolve(e.mediaContent))},onNewOffer:(e,t=Te())=>{const i=this.logger.createFnLogger("onNewOffer",t);this.newOfferRequestDeferred?(i.info("onNewOffer"),this.newOfferRequestDeferred.resolve(e.mediaContent)):i.info("callback received but new offer was not requested")},onAnswer:(e,t=Te())=>{const i=this.logger.createFnLogger("onAnswer",t);if(i.info(`${Le((0,fr.omit)(e,"mediaContent","remoteParticipantId"))}`),this.setMediaLegId(e.mediaContent.mediaLegId),this.callTelemetry.recordEvent("_WebOnAnswer",this.prepareTelemetryForOfferAnswer(e),t),e.renegotiation)i.info("resolving previous renegotiation promise"),this.renegotiationAnswerDeferred.resolve(e.mediaContent);else if(i.info("resolving final answer promise"),e.provisional){const i=this.isOneToOnePSTNCall()&&(0,fr.startsWith)(e.remoteParticipantId,"4:");this.mediaSession.processAnswerAsync(e.mediaContent,t,!0,i)}else this._callOperationHandler.maybeResolveOperation("_WaitForAnswer",e.mediaContent,void 0,t),this.handleRemoteParticipantStateInOneToOneCall(t);e.provisional||!e.mediaContent.fromMixer||this.callUsesMixer||this._callOperationHandler.executeChained((async()=>{this.setCallUsesMixer(!0,t),this.mediaStateConfigurationHelper.isDisabled(2)&&this.mediaStateConfigurationHelper.removeModality(2),await this.updateMediaModalities(void 0,t);const e=!(this.isSomeoneSharing||this.isScreenSharingOn||this.isVideoOn);return this.mediaSession.getSessionConfig().config.disableImmidiateEscalationReconnect&&e?(i.info("Delaying reconnect"),this._hasDelayedReconnect=!0,Promise.resolve()):this.mediaSession.reconnectAsync(t,!0)}),"_CallEscalatedToConference",t,t,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})},onMediaAcknowledgementSuccess:(e,t=Te())=>{this.logger.info(`isRenegotiation: ${e}`,"onMediaAcknowledgementSuccess",t),this._callOperationHandler.resolveOperation("_MediaAcknowledgment",void 0,void 0,t)},onMediaAcknowledgementFailure:(e,t,i=Te())=>{this.logger.createFnLogger("onMediaAcknowledgementFailure",i).logFailure(Le(t)),this._callOperationHandler.rejectOperation("_MediaAcknowledgment",t,i)},onMediaRenegotiationRejection:(e,t=Te())=>{this.logger.createFnLogger("onMediaRenegotiationRejection",t).logFailure(Le(e)),this.renegotiationAnswerDeferred.reject(e)},onRosterHandlingComplete:()=>{this.logger.info(`[onRosterHandlingComplete] ${this._publishedStatesModified}`),0!==this._publishedStatesModified&&(this.processPublishedStates(),this._publishedStatesModified=0)},onMeetingGroupDetailsUpdated:(e,t=Te())=>{this.meetingGroupDetails!==e&&(this.callTelemetry.recordEvent("_UpdateMeetingGroupDetails",e,t),this.logger.info(`[${t}][onMeetingGroupDetailsUpdated] update meetingGroupDetails from ${JSON.stringify(this.meetingGroupDetails)} to ${JSON.stringify(e)}`),this.meetingGroupDetails=e,this.raiseChanged())},onSelfParticipantUpdated:(e,t=Te())=>{this.logger.info(`[${t}][onSelfParticipantUpdated]`),this.updateLocalParticipant(e,t),this.raiseChanged()},onParticipantMriUpdated:(e,t,i=Te())=>{this.logger.info(`[${i}][onParticipantMriUpdated]`);const n=this.getParticipant(e);n&&(n.id=t,this.raiseChangedDeferred())},onParticipantUpdated:(t,i=Te())=>{this.logger.info(`[${i}][onParticipantUpdated]: ${lp(t)}`);const n=this.getOrCreateParticipant(t.id,i,!0);n.displayName=t.displayName;const r=e.getStreamsFromEndpoints(t.endpointDetails),a=(0,fr.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||r.length>0||a?(this.updateParticipantStreams(n,t,r,i),this.updateCallParticipantFromSignalingParticipant(n,t,i)):n.setState(3,void 0,i),n.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),this.calculateIsSomeoneStreaming(i),this.raiseChangedDeferred()},onParticipantRemoved:(e,t=Te(),i=!1)=>{if(this.logger.info(`[${t}][onParticipantRemoved]`),i){const i=this.getParticipant(e.id);this.callTelemetry.recordOperationSuccess("_ParticipantJoined",null,i?.id,t,{participantJoinedButReplaced:"Participant joined with original MRI and replaced with participant of RNL MRI"})}else this.callTelemetry.recordOperationSuccess("RemoveParticipant",null,e.id,t),this._participantOperationHandler.maybeRejectOperation("AddParticipant",1,e.id,t);this._removeParticipant(e,t),this.removePublishedStatesByParticipant(e.id),this.calculateIsSomeoneStreaming(t)},onParticipantJoined:(t,i=Te())=>{this.logger.info(`[${i}][onParticipantJoined]`);const n=!this.getParticipant(t.id),r=this.getOrCreateParticipant(t.id,i,!1);r.displayName=t.displayName,0===r.state&&r.setState(1,void 0,i);const a=e.filterVirtualEndpoints(t.endpointDetails),s=e.getStreamsFromEndpoints(a),o=(0,fr.some)(t.endpointDetails,(e=>e?.streamInformation));this.callUsesMixer||s.length>0||o?(this.updateParticipantStreams(r,t,s,i),this.updateCallParticipantFromSignalingParticipant(r,t,i),this.calculateIsSomeoneStreaming(i)):(this.handleRemoteParticipantJoinedInOneToOneCall(t,i),this.handleRemoteParticipantStateInObservingCall(r,t,i),t.acceptedBy&&t.acceptedBy!==t.id&&(r.acceptedBy=t.acceptedBy)),this.callTelemetry.recordOperationSuccess("_ParticipantJoined",gn(t.endpointDetails),r.id,i),r.processParticipantDetails(t,this.getSelfClientEndpointCapabilities(),(()=>{this.signalingSession?.setStreamInformationReceived()})),this.updatePublishedStates(t),n&&this.event("participantAdded").raise(r),this.raiseChangedDeferred()},onCallModeChanged:(e,t)=>{this.callTelemetry.recordEvent("_CallModeChanged",{newCallMode:e,oldCallMode:this._callMode},t),this.logger.info(`onCallModeChanged[${t}]: new=${e} old=${this._callMode} `),e&&this._callMode!==e&&(this._callMode=e,this.isCallModeStreaming()&&this.cleanUpDueToStreaming(t),1===this._callMode&&(this.participants.forEach((e=>{e.applyCachedMediaStreams(t)})),this.promotionCompletedDeferred?.resolve()),this.monitorCallStart(),this.updateCapabilities(t),this.raiseChanged())},getRemoteParticipantCollection:()=>this.participants.map((e=>e.toCafeParticipant())),onReTargetCompletedSuccess:e=>{const t=this.logger.createFnLogger("onReTargetCompletedSuccess",e);t.info(`started, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetSuccess",void 0,e),this.callStats.localStats.call.event(3);const i=this.isEscalationInProgress;this.screenSharingControl&&this.screenSharingControl.shutdownControlForViewer(),this.updateSignalingDSHMessageSubscription(this.isInitialSignalingDSHSubscriptionEnabled()),this.mediaSession.completeEscalationAsync(e).then((()=>(t.logSuccess("completeEscalationAsync"),this.callTelemetry.recordEvent("_WebOnEscalationSuccess",void 0,e),this.handleCallEscalation(i,e),this.updateMediaStatus(e)))).catch((i=>{t.logFailure(`completeEscalationAsync, error=${Ne(i)}`),this.setIsEscalationInProgress(!1,e),this.callTelemetry.recordEvent("_WebOnEscalationFailure",De(i),e),this.stopInternal({causeId:e,terminatedReason:47})}))},onReTargetCompletedFailure:(e,t)=>{this.logger.createFnLogger("onReTargetCompletedFailure",t).logFailure(`reason=${Ne(e)}, isEscalationInProgress=${this.isEscalationInProgress}`),this.callTelemetry.recordEvent("_WebRetargetFailure",De(e),t),this.isEscalationInProgress&&(this.setIsEscalationInProgress(!1,t),this.setCallUsesMixer(!1,t),this.updateMediaStatus(t)),this.callStats.localStats.call.event(4),this.mediaSession.rejectEscalationAsync(e,t)},onChatModalitySetupFailed:e=>{this.logger.debug(`onChatModalitySetupFailed: ${e}`)},onConversationUpdated:(e,t)=>{this.logger.info(`onConversationUpdated[${t}]: ${Le(e)}`),this.setConversationType(e.conversationType,t),this.setMessageId(e.teamsMessageId,t),this.setGroupId(e.groupId,t),this.setThreadId(e.threadId,t),this.setBackroomThreadId(e.backroomThreadId,t),this.setCallType(e.isMultiParty?2:1,t),this._commandUrlPresence=e.commandUrlPresence,this.updateCapabilities(t),this.region=e.region,this.setMeetingData(e.meetingData),this.meetingInfo=e.meetingInfo,this.callLimits=e.callLimits,this.setComplianceRecordingContent(t,e.complianceRecordingContent),this.setHuddleGroupCall(e.isHuddleGroupCall),this.raiseChanged()},onMeetingDetailsUpdated:e=>{this.meetingDetails=e,this.mediaSession&&!this.enableRealtimeTelemetry&&this.meetingDetails.meetingCapability?.enableRealtimeTelemetry&&(this.mediaSession.enableTeamsRealTimeTelemetry(),this.enableRealtimeTelemetry=!0),this.raiseChanged()},onMeetingStatesUpdated:e=>{(0,fr.isEqual)(e,this.meetingStates)||(this.meetingStates=e,this.logger.info(`[onMeetingStatesUpdated] meetingStates updated to ${JSON.stringify(this.meetingStates)}`),this.raiseChanged())},onParticipantCountsUpdated:e=>{(0,fr.isEqual)(e,this.participantCounts)||(this.participantCounts={...ln,...e},this.event("participantCountsUpdated").raise(this.participantCounts),this.mediaSession?.processNotification("ParticipantCountChanged",{count:e.totalParticipants}))},updateIsSharedLineAppearanceV2Activated:e=>{this.isSharedLineAppearanceV2Activated!==e&&(this.logger.info(`_updateIsSharedLineAppearanceV2Activated: new value is ${e}`),this.isSharedLineAppearanceV2Activated=e,this.event("sharedLineAppearanceV2ActivatedChanged").raise(this.isSharedLineAppearanceV2Activated))},onBroadcastMeetingUpdated:e=>{e&&(this.broadcastMeeting&&this.broadcastMeeting.metadataChanged(JSON.stringify(e)),this.broadcastMetadata=e,this.raiseChanged())},onBroadcastMeetingConnected:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingConnected]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&(0===e.code?this._callOperationHandler.resolveOperation("AddBroadcastModality",e,t):this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t))},onBroadcastMeetingEnded:(e,t)=>{this.logger.info(`[${t}][onBroadcastMeetingEnded]`),this._callOperationHandler.hasPendingOperation("AddBroadcastModality")&&this._callOperationHandler.rejectOperation("AddBroadcastModality",e,t),this.signalingSession.endBroadcastMeeting(t)},onTransferRequested:(e,t)=>{const i=this.logger.createFnLogger("onTransferRequested",t);i.info("Transfer: onTransferRequested, target participant",lp(e.target));let n="",r="",a=0;"voicemail"===e.target.endpointType&&(a=2);try{n=e.target.id,r=e.transferor.details.id,e&&e.parkType&&"none"!==e.parkType&&(a=1)}catch(e){return i.logFailure(e),this.callTelemetry.recordEvent("_OnTransferRequestedInvalid"),void this.signalingSession.signalTransferCompletedAsync({code:$h(7)})}const s=this.convertToTransferType(a,e.parkType),o={transferContext:{transferorMri:r,targetMri:n,transferType:a,context:{target:e.target,transferor:e.transferor,transferContext:e.transferContext,newCallModalities:e.newCallModalities,links:e.links,replacementDetails:e.replacementDetails,isConsultative:e.isConsultative,callAcceptanceCallback:()=>{i.logSuccess("Transfer: callAcceptanceCallback called"),this.signalingSession.signalTransferAcceptedAsync(s)}}},onCompleted:e=>{i.logSuccess("Transfer: onCompleted called"),this.signalingSession.signalTransferCompletedAsync({code:$h(e)})}};this.callTelemetry.recordEvent("_OnTransferRequested",{transferType:a}),this.event("transferRequested").raise(o)},onTransferredCallAcceptance:e=>{const t=this.logger.createFnLogger("onTransferredCallAcceptance",e);this._transfereeAcceptanceWithoutWaitingForConv&&this._transferredCallAcceptanceCallback&&(t.info("[Transfer] Invoke call acceptance callback for original call"),this._transferredCallAcceptanceCallback())},onTransferAccepted:e=>{this.logger.info("Transfer: onTransferAccepted"),this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&this._setTransferState(2),this._callOperationHandler.hasPendingOperation("BlindTransfer")&&this._callOperationHandler.maybeResolveOperation("_CallTransferInProgress",void 0,void 0,e),this._callOperationHandler.hasPendingOperation("ParkCall")&&this._setParkState(2)},onTransferCompleted:(e,t)=>{const i=this.logger.createFnLogger("onTransferCompleted",t);i.info("Transfer: onTransferCompleted");const n=e.transferCompletion,r=Bh(n);if(n&&(i.info(`Transfer: Call Transfer Code: ${n.code}`),0===n.code)){if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.resolveOperation("_CallTransferInProgress",void 0,void 0,t),this._setTransferState(3)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:0,subCode:0,phrase:"TransactionComplete"};this._callOperationHandler.resolveOperation("ConsultativeTransferWithPickupCode",e,void 0,t),this._setTransferState(3)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation&&(this.serverHoldLocation=e.unparkContent.CallParkAdditionalContext.ConversationControllerLocation),void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("ParkCall",e.unparkContent.pickupCode,void 0,t),i.logSuccess(`pickupCode=${e.unparkContent.pickupCode}`),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",32,t),i.logFailure(`terminatedReason=${r}`),this._setParkState(4)))}else{if(this._callOperationHandler.hasPendingOperation("_CallTransferInProgress")&&(this._callOperationHandler.rejectOperation("_CallTransferInProgress",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setTransferState(4)),this._callOperationHandler.hasPendingOperation("ConsultativeTransferWithPickupCode")){const e={code:n.code,subCode:n.subCode,resultCategories:n.resultCategories};this._callOperationHandler.rejectOperation("ConsultativeTransferWithPickupCode",e,void 0,t)}this._callOperationHandler.hasPendingOperation("ParkCall")&&(this._callOperationHandler.rejectOperation("ParkCall",r,void 0,t),i.logFailure(`terminatedReason=${r}`),this.transferDiagnosticsInfo={callControllerCode:n.code,callControllerSubCode:n.subCode,phrase:n.phrase,resultCategories:n.resultCategories},this._setParkState(4))}},onParkCompleted:(e,t)=>{this.logger.createFnLogger("onParkCompleted",t).info(`transactionEnd ${Ne(e)}`),this._callOperationHandler.hasPendingOperation("CallParkV2")?0===e.code&&void 0!==e.unparkContent?.pickupCode?(this._callOperationHandler.resolveOperation("CallParkV2",""+e.unparkContent?.pickupCode,void 0,t),this.callTelemetry.maybeRecordOperationSuccess("CallParkV2"),this.serverHoldLocation=e.unparkContent?.CallParkAdditionalContext?.ConversationControllerLocation,this.parkAdditionalContextJson=JSON.stringify(e.unparkContent.CallParkAdditionalContext)):this._callOperationHandler.rejectOperation("CallParkV2",e,t):this._callOperationHandler.hasPendingOperation("ParkCall")&&(0===e.code?(this._callOperationHandler.resolveOperation("ParkCall","",void 0,t),this._setParkState(3)):(this._callOperationHandler.rejectOperation("ParkCall",e,t),this._setParkState(4)))},onUnparkCompleted:(e,t)=>{this.logger.createFnLogger("onUnparkCompleted",t).info(`transactionEnd ${Ne(e)}`),this._callOperationHandler.hasPendingOperation("UnparkCall")&&(0===e.code?this._callOperationHandler.resolveOperation("UnparkCall",e,void 0,t):this._callOperationHandler.rejectOperation("UnparkCall",e,t))},onIncomingCallReplacement:(e,t)=>{const i=this.logger.createFnLogger("onIncomingCallReplacement",t);this.callTelemetry.recordEvent("_onIncomingCallReplacement",{},t),e.callNotification.callType="replaces",e.callNotification.consultativeCallId=this.callId,i.info(`consultativeCallId=${this.callId}`),e.body={gp:e,evt:qn.INCOMING_SKYPE_NGC_CALL,nsp:void 0},this.event("replacementRequested").raise(e)},onContentSharingStopped:e=>{this.logger.debug("ScreenSharing: onContentSharingStopped");for(const t of this.contentSharingSessions)t.contentSharingGuid===e.correlationId&&(t.contentSharingStatus=7)},onContentSharingStarted:e=>{this.logger.debug("ScreenSharing: onContentSharingStarted");const t=new Gp(this.callTelemetry,this.logger.createChild("ContentSharingSession"),this.signalingSession,e.correlationId||xi(),e.contentIdentifier,e.sessionState,e.subject,e.sessionId);t.contentSharingStatus=2,this.contentSharingSessions.push(t),t.changed((()=>this.removeContentSessionIfEnded(t))),this.event("contentSharingChanged").raise()},onContentSharingUpdated:e=>{this.logger.debug("ScreenSharing: onContentSharingUpdated");const t=(0,fr.find)(this.contentSharingSessions,(t=>t.contentSharingGuid===e.correlationId));t?(e.presenter&&(t.presenterId=e.presenter),e.subject&&t.subject!==e.subject&&(t.subject=e.subject),e.sessionState&&t.contentSharingState!==e.sessionState&&(t.contentSharingState=e.sessionState),3===t.contentSharingStatus&&this.localSignalingParticipant.id!==e.presenter?t.contentSharingStatus=5:5===t.contentSharingStatus&&this.localSignalingParticipant.id===e.presenter&&(t.contentSharingStatus=3)):this.logger.warn("onContentSharingUpdated: session not found")},onWebRtcMediaNotification:(e,t)=>{this.mediaSession?.processNotification(e,t);const i=this.mediaSession&&this.mediaSession.getExtensionsManager?this.mediaSession.getExtensionsManager():null;i&&i.processNotification(e,t)},onCorrelationIdUpdated:(e,t)=>this.checkForCallIdUpdate(e,t),onUnmuteRequested:e=>{},onCallForwarded:e=>{e&&e.destinationType!==this.forwardingDestinationType&&(this.forwardingDestinationType=e.destinationType,this.raiseChanged())},onPSTNBalanceUpdate:e=>{},isOneToOnePstnCall:()=>this.isOneToOnePSTNCall(),onUpdateMeetingLiveStateCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingLiveStateCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingLiveState",i)},onUpdateMeetingStatesCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingStatesCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingStates",i)},onUpdateMeetingGroupsCompleted:(e,t,i)=>{this.logger.info(`[onUpdateMeetingGroupsCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"UpdateMeetingGroups",i)},onSetMeetingLayoutCompleted:(e,t,i)=>{this.logger.info(`[onSetMeetingLayoutCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"SetMeetingLayout",i)},onJoinMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"JoinMeetingGroup",i)},onLeaveMeetingGroupCompleted:(e,t,i)=>{this.logger.info(`[onJoinMeetingGroupCompleted] [${t}] transactionEnd ${Ne(e)}`),this.onOperationCompleteCommonHandler(e,t,"LeaveMeetingGroup",i)},onBreakoutDetailsUpdated:(e,t)=>{this.logger.info(`[onBreakoutDetailsUpdated] [${t}]`),this.breakoutDetails=e,this.raiseChanged()},onIncomingProxiedMessages:(e,t)=>{this.logger.info(`[onIncomingProxiedMessages] [${t}] payload ${Ne(e,!0)}`),this.event("incomingProxiedMessages").raise(e)},onUpdateParticipantsPropertiesCompleted:(e,t,i)=>{this.logger.createFnLogger("onUpdateParticipantsPropertiesCompleted",i).info(`promisesToResolve ${Ae(Le(e))}`);for(const t of Object.keys(e))e[t].code===yn.SUCCESS?this._callOperationHandler.maybeResolveOperation("UpdateParticipantsProperties",e[t],t,i):this._callOperationHandler.maybeRejectOperation("UpdateParticipantsProperties",e[t],t,i)},onNudgeToJoinRealtime:e=>{this.logger.info("[onNudgeToJoinRealtime]",e),this.callTelemetry.recordEvent("NudgeToJoinRealTime",e),this.canPromoteToRealTime(1)&&this.promoteToRealtime(1,e).then((()=>this.logger.info(`[onNudgeToJoinRealtime][${e}] completed`))).catch((t=>this.logger.info(`[onNudgeToJoinRealtime][${e}] failed to auto promote: ${Ne(t)}`)))}};const n=Object.create(this.localSignalingParticipant);this.signalingSession=this.signalingAgent.getNewSignalingSession(n,this.signalingNotifications,this.callId,this._callCreationTime),this.signalingSession.participantManager.setStaleCheckForFullRoster(this._staleRosterCheckFixForPluginless),this.signalingSession.participantManager.setEnableMuteAsync(this._enableMuteAsync),this.signalingSession.participantManager.setEnableUnmuteAsync(this._enableUnmuteAsync),this.accountConfiguration&&this.accountConfiguration.deviceType&&this.signalingSession.setDeviceType(this.accountConfiguration.deviceType),this.setCallId(this.callId||this.signalingSession.correlationId),this.signalingSession.participantManager&&this.signalingSession.participantManager.localParticipant&&(this.setEndpointId(this.signalingSession.participantManager.localParticipant.endpointId),this.setParticipantId(this.signalingSession.participantManager.localParticipant.participantId),this.callStats.setParticipantId(this.participantId))}updateParticipantStreams(e,t,i,n){e.updateStreams(i,n,this.isCallModeStreaming());const r=this.getStreamInformationMap(t);this.logger.info(`[updateParticipantStreams]: streaming mode with new streamInfoMap: ${Le(r)}`);const a={callId:this.callId,participantId:this.participantId,endpointId:this.endpointId};this.meetingData&&(a.meetingId=this.meetingData.meetingCode);const s=this.telemetryLoggers?this.telemetryLoggers.tlePlayer:null;e.useUmsStream(r,this._liveStreamConfigProvider,a,this.threadId,s,n)}cleanUpDueToStreaming(e){this.logger.info(`cleanUpDueToStreaming[${e}]: cleaning streams and media and canceling cc operations`),this.cancelAllCallingOperationsDueToStreaming(e);const t={code:$n.Success,subCode:Gn.DowngradeToStreamingClient,phrase:ir};this.participants.forEach((t=>t.updateStreams([],e))),this.cleanUpMedia(e,t).finally((()=>{this.mediaDisposedPromise=null})),this.finishCallHoldResume(t),this.renegotiationAnswerDeferred?.reject(t),this.newOfferRequestDeferred?.reject(t),this._parkState=0,this._transferState=0,this.isServerMuted||(this._muteState=0),this.isSpeakerMuted=!1,this.requestedHoldState=!1,this.isMuteOnHold=!1}cancelAllCallingOperationsDueToStreaming(e){this._callOperationHandler.maybeRejectPendingOperationsWithPredicate(74,e,((e,t)=>(0,fr.some)(t?.preconditionTags,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))))}onOperationCompleteCommonHandler(e,t,i,n){0===e.code?this._callOperationHandler.maybeResolveOperation(i,e,n,t):this._callOperationHandler.maybeRejectOperation(i,e,n,t)}convertToTransferType(e,t){let i="none";return 1===e&&t&&"none"!==t?"teamPark"===t?i="TransferTypeTeamPark":"sharedLinePark"===t?i="TransferTypeSharedLinePark":"serverHold"===t&&(i="TransferTypeServerHold"):0===e?i="TransferTypeStandard":2===e?i="TransferTypeVoicemail":this.logger.info(`Irrelevant combination of transferTye: ${e} and parkType: ${t}`),i}raiseChangedDeferred(e){(!this.raiseChangedDefer||this.raiseChangedDefer.isSkippable&&!e)&&(gp.instance.runDeferredWithoutDedup((()=>{delete this.raiseChangedDefer,this.raiseChanged(e)}),"Call.raiseChanged"),this.raiseChangedDefer={isSkippable:!!e})}static getStreamsFromEndpoints(t){if(!t)return[];const i=e.filterVirtualEndpoints(t);return i.forEach((e=>(0,fr.forEach)(e.mediaStreams,(t=>{t.participantId=e.participantId,t.endpointId=e.endpointId})))),(0,fr.flatMap)(i,(e=>e&&e.mediaStreams||[]))}preconditions(e,t){this.logger.info(`check call mode currentMode is ${this.callMode} operationName is ${e}`),(0,fr.some)(t,(e=>"NOT_SUPPORTED_IN_STREAMING_MODE"===e))&&this.isCallModeStreaming(!0)}mapCallSetupIntent(e){switch(e){case 0:return"None";case 1:return"AutoPromotion";case 2:return"PromotionWithAudio";case 3:return"PromotionWithVideo";default:return"Unknown"}}async promoteToRealtime(e,t){this.logger.info(`[${t}][promoteToRealtime] started with intent=${e}`);const i=this.getPromoteToRealtimeCallOptions(e,this.callOptions);this.callTelemetry.updateOperationData("_PromotionToRealtime",{intent:e},t),this.callTelemetry.recordEvent("StartPromotion",{intent:this.mapCallSetupIntent(e)},t);try{this.promotionCompletedDeferred=Si(),await Promise.all([this.joinOrStartCall(i,this.joinGivenConversation,t,void 0),this.promotionCompletedDeferred.promise])}catch(e){throw this.logger.logFailure(`[${t}][promoteToRealtime] failed with reason=${Ne(e)}`),this.cleanUpDueToStreaming(t),this.signalingSession.cleanUpDueToStreaming(t),e}}async promoteToRealtimeAndUnmute(e){return this.logger.info(`[${e}][promoteToRealtimeAndUnmute]`),this.isPromotingToRealtime()?(this.logger.info(`[${e}][promoteToRealtimeAndUnmute] already promoting to realtime.`),this._callOperationHandler.waitForOperation("_PromotionToRealtime").then((()=>this.muteUnmute(!1,e)))):this.canPromoteToRealTime(2)?(this.unmutePendingPromise=Si(),setTimeout((()=>{this.unmutePendingPromise?.reject("promoteToRealtime unmute timed out")}),1e3*this.signalingSession.signalingAgentConfig.csaTimeoutConfiguration.promotionUnmuteTimeoutSec),Promise.all([this.promoteToRealtime(2,e),this.unmutePendingPromise.promise]).then((()=>{})).finally((()=>this.unmutePendingPromise=null))):Promise.reject("manual promotion with audio is not allowed")}isPromotingToRealtime(){return this._callOperationHandler.hasPendingOperation("_PromotionToRealtime")}getPromoteToRealtimeCallOptions(e,t){let i,n=1;1===e?i={value:!0,mediaTypes:["audio"]}:3===e?(i={value:!0,mediaTypes:["audio"]},n=4):2===e&&(i={value:!1});const r={...t.callStartOptions,sendMediaModalities:{mediaStates:[Gh(0,4),Gh(1,n)].filter((e=>null!=e))},preheatFlags:0};return{...t,callStartOptions:r,applyServerMute:i,isPromotingToRealtime:!0,callStartTime:Date.now()}}canPromoteToRealTime(e){const t=this.logger.createChild("[canPromoteToRealTime]");return t.info(`[promoteType:${e}]`),this.isCallModeStreaming()?this.isPromotingToRealtime()?(t.info("already promoting to realtime"),!1):1===e||2===e:(t.info("cant promote since call mode is not streaming"),!1)}isCallModeStreaming(e=!1){if(2===this.callMode){if(!e)return!0;throw this.logger.info("reject check callmode"),{code:499,subCode:3551,phrase:"TransactionNotAllowedForStreamMode"}}return!1}setCallOptions(e){this.receiveOnlyAudioOnCallStart=!!e.callStartOptions?.receiveOnlyAudioOnCallStart,this.callOptions=e,this.logger.info(`callOptions: ${Le(function(e){const t={};qh(e.callStartTime)&&(t.callStartTime=e.callStartTime),qh(e.callVoicemailStartOptions)&&(t.callVoicemailStartOptions=e.callVoicemailStartOptions),qh(e.invitationType)&&(t.invitationType=e.invitationType),qh(e.meetingPreferences)&&(t.meetingPreferences=e.meetingPreferences),qh(e.parkContext)&&(t.parkContext=e.parkContext),qh(e.pickupCode)&&(t.pickupCode=e.pickupCode),qh(e.participantsToNudge)&&(t.participantsToNudgeSize=e.participantsToNudge.length);const i=e.callStartOptions;if(i){const e={};qh(i.additionalEndpointProperties)&&(e.additionalEndpointProperties=i.additionalEndpointProperties),qh(i.clientEndpointCapabilities)&&(e.clientEndpointCapabilities=i.clientEndpointCapabilities),qh(i.connectionType)&&(e.connectionType=i.connectionType),qh(i.invitationDataJson)&&(e.invitationDataJson=i.invitationDataJson),qh(i.isCast)&&(e.isCast=i.isCast),qh(i.isHuddleGroupCall)&&(e.isHuddleGroupCall=i.isHuddleGroupCall),qh(i.label)&&(e.label=i.label),qh(i.maxVideoChannels)&&(e.maxVideoChannels=i.maxVideoChannels),qh(i.maxVbssChannels)&&(e.maxVbssChannels=i.maxVbssChannels),qh(i.mediaConfiguration)&&(e.mediaConfiguration=i.mediaConfiguration),qh(i.muteFlags)&&(e.muteFlags=i.muteFlags),qh(i.muted)&&(e.muted=i.muted),qh(i.negotiationTag)&&(e.negotiationTag=i.negotiationTag),qh(i.preheatFlags)&&(e.preheatFlags=i.preheatFlags),qh(i.ringOthers)&&(e.ringOthers=i.ringOthers),qh(i.routingFlags)&&(e.routingFlags=i.routingFlags),qh(i.scenario)&&(e.scenario=i.scenario),qh(i.screenshareDirection)&&(e.screenshareDirection=i.screenshareDirection),qh(i.sendMediaModalities)&&(e.sendMediaModalities=i.sendMediaModalities),qh(i.sharedLineCallInvitationContentJson)&&(e.sharedLineCallInvitationContentJson=i.sharedLineCallInvitationContentJson),qh(i.targetApplicationType)&&(e.targetApplicationType=i.targetApplicationType),qh(i.captchaContentJson)&&(e.captchaContentJson=i.captchaContentJson),qh(i.callQueueContext)&&(e.callQueueContext=i.callQueueContext),qh(i.clientEndpointDebugContent)&&(e.clientEndpointDebugContentSize=i.clientEndpointDebugContent.length),qh(i.alternateId)&&(e.alternateId=Ae(i.alternateId)),qh(i.callKey)&&(e.callKeySize=i.callKey.length),qh(i.encryptedKey)&&(e.encryptedKeySize=i.encryptedKey.length),t.callStartOptions=e}return t}(e))}`)}getSelfClientEndpointCapabilities(){return this.callOptions?.callStartOptions?.clientEndpointCapabilities}getLocalSignalingEndpointDetails(){return(0,fr.find)(this.localSignalingParticipant.endpointDetails,(e=>e?.endpointId===this._endpointId))}getStreamInformationMap(e){const t={};return e&&this.accountConfiguration?.clientSupportsUms&&(0,fr.forEach)(e.endpointDetails,(e=>{e?.streamInformation&&e.participantId&&e.participantId!==this._participantId&&(t[e.participantId]=e.streamInformation)})),t}updateSATInfo(e=[]){const t=this.mediaSession?.getSessionConfig().config.slowedDownTalkerInfoAggregationTime;if(!t||t<0)return;const i=Date.now(),n=i-1e3*t;this.activeTalkersHistory=this.activeTalkersHistory.filter((({timestamp:e})=>e>n)).concat({speakers:e.map((e=>e.id)),timestamp:i});const r=Object.entries(this.activeTalkersHistory.reduce(((e,{speakers:t})=>{for(const i of t)e[i]??(e[i]=0),e[i]++;return e}),{})).sort((([,e],[,t])=>t-e)).map((([e])=>e));this.slowedDownActiveTalkerInfo={speakerList:r,timestamp:new Date(i)}}setPlatformCallConstraints(e){this.setCallConstraints(e).catch((e=>{this.logger.error(e)}))}setCallConstraints(e){return this.mediaSession?(this.logger.info(`Applying platform constraints to current call ${JSON.stringify(e)}`),this.mediaSession.setCallConstraints(e,Te())):(this.logger.info("Saving platform constraints until media session is created"),this.temporaryCallConstraints=e,new Promise(((e,t)=>{this.resolveTemporaryCallConstraints=e,this.rejectTemporaryCallConstraints=t})))}initializeMediaSession(t){if(this.mediaSession)return;const i=this.logger.createFnLogger("initializeMediaSession",t),n=((e,t)=>{const i={};return Object.keys(t).forEach((n=>{i[n]=(...i)=>t[n]&&e()&&t[n](...i)})),i})((()=>!this.isCallModeStreaming()||this.isPromotingToRealtime()),{onSessionErrorOccurred:(e,t=Te())=>{i.error(`[${t}][onSessionErrorOccurred]: ${Le(e)}`);const n=[this.mediaAgent.constants.MEDIA_ERROR.iceConnectionError,this.mediaAgent.constants.MEDIA_ERROR.internalError];(0,fr.includes)(n,e.type)&&this.event("mediaConnectionFailed").raise(),this.callTelemetry.recordEvent("SessionError",{type:e.type},t)},onNegotiationRequired:(e=Te())=>{this.executeNegotiation(e,"onNegotiationRequired",!0)},onContributingSourcesChanged:e=>{const t=this.mediaSession?.getSessionConfig().config.contributingSourcesLogInterval,n=t&&Date.now()>=this.lastContibutingSourceReport+t,r=n?new Map(e.map((e=>[e,"<unknown>"]))):new Map,a=[];for(const t of this.participants){const i=e.some((e=>t.hasAudioSource(e))),s=i?1:0;t.updateVoiceLevel(s),i&&(a.push(t),n&&r.set(t.audio.id,Ae(t.id)))}this.updateSATInfo(a),n&&(i.info(`[onContributingSourcesChanged], ${e.length?Array.from(r).join(";"):"none"}`),this.lastContibutingSourceReport=Date.now())},onDominantSpeakerChanged:(e,t)=>{const n=Te(),r=[],a=[];e.forEach((e=>{const t=(0,fr.find)(this.participants,(t=>t.hasAudioSource(e)));t?(r.push(t.id),a.push(Ae(t.id))):a.push(this.streamManager.audio.id===e?"<self>":"<unknown>")})),i.info(`[${n}][onDominantSpeakerChanged], msidList = ${e} => speakerList = ${a}, timestamp = ${t}`),this.dominantSpeakerInfo={speakerList:r,timestamp:t,noCurrentDominantSpeaker:!1},this.event("dominantSpeakerChanged").raise(),this.raiseChanged(this._dominantSpeakerChangedEventSkipConfig)},onAudioStateChanged:(t,i)=>{const n=Te(),r=this.logger.createFnLogger("onAudioStateChanged",n);r.info(Le(t)),this.callStats.localStats.audio.streamStateChanged(t.stream,t.direction);const a=e.streamingStatetoMediaStreamState(t.stream);if(this.audioStreamState=a,!a)return;this.callTelemetry.recordEvent("AudioStateChanged",{state:t,reason:i},n),2===a&&2===this.state&&(this.setCallState(9,n),this.participants.forEach((e=>e.setState(6,void 0,n))));const s={mediaType:0,mediaDirection:e.streamingDirectionToMediaDirectionMapping(t.direction),mediaStreamState:a};if(this.event("mediaStreamStateChanged").raise(s),!this.isCallSetupTelemetrySent&&this.mediaSession?.getSessionConfig().config.sendCallStartupTelemetry&&this.sendCallSetupTelemetry(),0===s.mediaDirection&&(this.isAudioStreamConnected=(0,fr.includes)([2,1],s.mediaStreamState)),(0,fr.includes)([3,4],s.mediaStreamState)&&(r.logFailure(`audio stream state changed to ${t.stream} with reason ${i}`),!i||["timeout","connection-dropped","connectivity-check-failure","suspended"].indexOf(i)>=0)){this.event("mediaConnectionFailed").raise();const e="suspended"===i?77:this.mediaRelayWhiteListingIssue?53:4;this.mediaRelayWhiteListingIssue&&this.callTelemetry.recordEvent("_MediaWhiteListingIssueDetected"),this.stopInternal({causeId:n,terminatedReason:e})}},onQualityChanged:t=>{const i={type:e.convertQualityEventType(t.type),value:e.convertQualityLevel(t.value),isLocalSource:t.isLocalSource,mediaType:e.convertMediaType(t.mediaType)};this.muteUnmuteWorkaround(i),32===i.type&&(this.mediaRelayWhiteListingIssue=3===i.value,this.mediaRelayWhiteListingIssue&&this.event("mediaConnectionWhitelistingWarning").raise()),5===i.type&&3===i.value&&this.trouterService.checkConnection(!0),this.callTelemetry.recordEvent("AudioQualityChanged",i),this.event("callQualityChanged").raise(i)},onOptimalVideoReceiversCountChanged:e=>{i.debug(`onOptimalVideoReceiversCountChanged: ${e}`),this.optimalVideoCount!==e&&(this.optimalVideoCount=e,this.raiseChanged())},onDataChannelUpdated:e=>{const t=Te();i.debug(`[${t}] onDataChannelUpdated`),this.dataChannel.registerSessionDataChannel(e,t)},onUpdateMediaDescriptionsRequired:e=>{this.executeNegotiation(e,"onUpdateMediaDescriptionsRequired",!1)},onRealtimeTelemetryReport:()=>{this.reportTelemetryEvents([{eventName:"realtimetelemetry",props:{user_object_id:{value:lh+this.currentUserSkypeIdentity.id,piiKind:10},call_context_id:{value:this.signalingSession.correlationId,piiKind:0},participant_id:{value:this.participantId,piiKind:0},media_leg_id:{value:this.mediaLegId,piiKind:0},DiagnosticLevel:{value:255,piiKind:0},eventpdclevel:{value:2,piiKind:0},eventpriority:{value:5,piiKind:0},call_technical_info:{value:JSON.stringify(this.mediaSession.getCallTechnicalInfo()),piiKind:0}}}],"realtimeMedia","mdsc")},onTransportConnected:()=>{this.mediaStateConfigurationHelper.isSending(3)&&this.allowDataChannel()?this.mediaControlPlane.onTransportConnected():!this.isInitialSignalingDSHSubscriptionEnabled()&&this.callUsesMixer&&this.updateSignalingDSHMessageSubscription(!0),this.unmixedAudioProvider.setSessionStreamsProvider(this.mediaSession.getUnmixedAudioProvider())}});this.callTelemetry.recordEvent("CreatingConference","",t),this.callDeviceManager||(i.info(`[${t}][initializeMediaSession] Creating new callDeviceManager`),this.callDeviceManager=this.createCallDeviceManager());const r=new Om(this.mediaControlPlane,this.signalingSession,i.createChild("SourceRequestSender"),this.mediaControlPlane.getTelemetryLogger().getSourceRequestSenderDiagnostics),a={maxReinvitelessMediaForVBSSMultiparty:this.signalingSession.getMaxReinvitelessMediaForVBSSForWeb(),maxReinvitelessMediaForVideoMultiparty:this.signalingSession.getMaxReinvitelessMediaForVideoForWeb()};this.callTelemetry.recordEvent("_ReinvitelessConfig",{reinvitelessConfig:a},t),this.mediaSession=new np(this.mediaAgent.createSession(n,this.signalingSession.correlationId,{isConference:this.callUsesMixer,isPstnCall:this.isOneToOnePSTNCall(),isParkedCall:this.isParkedCall(),reinvitelessConfig:a},this.callDeviceManager),this.signalingSession,r),this.temporaryCallConstraints&&(i.info(`Applying saved call constraints to current call ${JSON.stringify(this.temporaryCallConstraints)}`),this.mediaSession.setCallConstraints(this.temporaryCallConstraints,Te()).then(this.resolveTemporaryCallConstraints).catch(this.rejectTemporaryCallConstraints).finally((()=>{this.temporaryCallConstraints=void 0,this.rejectTemporaryCallConstraints=void 0,this.resolveTemporaryCallConstraints=void 0}))),this.dataChannel.setConfigProviderView(this.mediaSession.getSessionConfig()),this.callTelemetry.recordEvent("CreatedConference","",t),this.streamManager.setMediaSession(this.mediaSession,t),this.participants.forEach((e=>{e.setMediaSession(this.mediaSession,t)}));const s=this.mediaSession.getSessionConfig()?.config;s?.useOneDsLogger&&s?.addTelemetryReportingCallback&&(this.beforeUnloadTelemetrySender=()=>{this.sendLastKnownStats()},window.addEventListener("beforeunload",this.beforeUnloadTelemetrySender)),this.screenSharingControl&&this.allowDataChannel()&&(this.screenSharingControl.setGiveControlEnabled(this.isGiveControlEnabled()),this.screenSharingControl.setupDataHandlers()),this.unmixedAudioProvider=new Am}executeNegotiation(e,t,i){const n=this.logger.createFnLogger(t,e);if(this.isCallModeStreaming()||this.isEscalationInProgress)return void n.info(`ignored due to being in streaming=${this.isCallModeStreaming()},\n                isEscalationInProgress=${this.isEscalationInProgress}`);const r=Te();3===this.state||4===this.state||5===this.state||10===this.state||this.isPreheatedOnly()?(n.info(`started, state: ${this.state}, runNegotiation: ${i}`),i?(this.callTelemetry.recordEvent("NegotiationRequired","",e),this._callOperationHandler.executeChained((()=>this.renegotiateOutgoing(e)),"_RenegotiateOutgoing",r,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})):(this.callTelemetry.recordEvent("UpdateMediaDescriptions","",e),this._callOperationHandler.executeChained((()=>this.updateMediaDescriptions(e)),"_UpdateMediaDescriptions",void 0,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}))):n.info(`not started, state: ${this.state}`)}async muteUnmuteWorkaround(e){if(this.mediaSession?.getSessionConfig().config.enableMuteSpeakerUnmuteSpeakerWorkaround&&!this.isSpeakerMuted&&25===e.type&&3===e.value&&0===e.mediaType){this.logger.log("Performing muteSpeaker->unmuteSpeaker workaround");const e=Te();await this.muteSpeaker(e),await this.unmuteSpeaker(e)}}sendLastKnownStats(){if(!this.tsCallingTelemetryReported){const e=this.mediaSession.getLastKnownStats(!0);this.callStats.setMediaStats(e),this.reportTelemetryEvents(this.callStats.buildShortBeaconEvent(),"media","mdsc"),this.reportTelemetryEvents(this.callStats.buildShortCallModalityStats(),"signaling"),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo);const t="in_call_session";this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(!0)}],"signaling","skypecosi_concore_web_ts_calling")}}invertDirectionality(e){switch(e){case this.mediaAgent.constants.MEDIA_STATE.sendReceive:return Sp;case this.mediaAgent.constants.MEDIA_STATE.send:return vp;case this.mediaAgent.constants.MEDIA_STATE.receive:return fp;default:return null}}completeNegotiationAsync(e){const t=this.logger.createFnLogger("completeNegotiationAsync",e),i=this.mediaSession.completeNegotiationAsync(e).then((i=>{t.info(`activeModalities=${i&&Object.keys(i.activeModalities)}`);const n=this.participants[0],r=n?.endpoints?.endpointDetails.length&&n.endpoints.endpointDetails[0].mediaStreams?.length,a=this.mediaSession.getSessionConfig().config.avoidFakeStreamsDuringEscalation&&this.isEscalationInProgress;if(n&&!this.callUsesMixer&&!a&&!r){const t=(e,t,i)=>({participantId:Lm,endpointId:"remote",type:e,direction:this.invertDirectionality(t),sourceId:i,serverMuted:!1}),r=[];r.push(t(yp,i.activeModalities.audio,1)),i.activeModalities.video&&r.push(t(Cp,i.activeModalities.video,2)),i.activeModalities.sharing&&r.push(t(_p,i.activeModalities.sharing,3)),n.updateStreams(r,e)}return t.logSuccess(Le(i)),i}));return i.catch((i=>{t.logFailure(i),this.callTelemetry.recordEvent("_CompleteNegotiationFailed",{e:i},e)})),i}async renegotiateOutgoing(e){let t;this.renegotiationAnswerDeferred=Si();const i=this.logger.createFnLogger("renegotiateOutgoing",e);if(this._hasDelayedReconnect)return i.info("Reconnecting with delay"),this._hasDelayedReconnect=!1,void await this.mediaSession.reconnectAsync(e,!0);i.info("start");const n=ph(i);try{try{t=this.inLocalHold()?this.getMediaModalitiesForHold(e):this.calculateModalityDirections({},e);const i=await n.execute("MediaCreateOffer",(()=>this.mediaSession.createOfferAsync(e))),r=this.getSignalingMediaTypes(t);await n.execute("SignalingStartNegotiation",(()=>this.signalingSession.startRenegotiationAsync(i,r,e)));const a=await n.execute("SignalingRenegotiationAnswer",(()=>this.renegotiationAnswerDeferred.promise));await n.execute("MediaProcessAnswer",(()=>this.mediaSession.processAnswerAsync(a,e,!1)));const s=await n.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(e)));this.onNegotiationCompletion(s,!0,t,e,n.getTelemetryData())}catch(n){if(i.logFailure(n),!n.phase)throw this.callTelemetry.recordEvent("OutgoingNegotiationFailure",n,e),n;let r="unknown";const a=this.mediaAgent.constants.RENEGOTIATION_ERROR;if(r=a.local,"SignalingRenegotiationAnswer"===n.phase||"SignalingStartNegotiation"===n.phase){const e=415;r=n.error.code===$n.GlareError?a.glare:n.error.code===e?a.media:a.signaling}else"MediaCreateOffer"===n.phase&&n.error.type===this.mediaAgent.constants.MEDIA_ERROR.noNetworkError&&(r=a.media);if(this.callTelemetry.recordEvent("OutgoingNegotiationFailure",this.getTelemetryFromPhaseExecution(n),e),n.error.message?.includes("The requested call does not exist"))throw new Error("Call drop due to remote replying with call not found");i.logFailure(r);const s={type:r,detail:n.error};await this.mediaSession.rejectNegotiationAsync(s,e),this.onNegotiationFailure(n,r,e,t)}}catch(t){i.logFailure(t),this.callTelemetry.recordEvent("NegotiationFatalError",De(t),e),this.stopInternal({causeId:e,terminatedReason:47})}}async renegotiateIncoming(e,t){this.mediaAcknowledgmentOperation=this._callOperationHandler.createPendingOperation("_MediaAcknowledgment",null,t,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.mediaAcknowledgmentOperation.catch(Sn);const i=this.logger.createFnLogger("renegotiateIncoming",t);if(i.info("start"),e.newOffer&&!this.mediaAgent.getCapabilities().retargeting)return i.logFailure("Retarget offer received, but pluginless has no support for retarget"),void this.stopInternal({causeId:t,terminatedReason:38});const n=ph(i);try{const i=await n.execute("MediaProcessOffer",(()=>this.mediaSession.processOfferAsync(e,t)));this.handleOfferedModalities(i,t),2===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForResume(t);const r=await this.updateMediaModalities({offered:i},t);1===this.getRenegotiationOfferType(i)&&await this.prepareModalitiesForHold(t),this.updateMediaState(r,t),this.isRenegotiationHoldOrResume(r)&&this.updateScreenSharingState(r,t);const a=await n.execute("MediaCreateAnswer",(()=>this.mediaSession.createAnswerAsync(!1,t))),s=this.getSignalingMediaTypes(r);await n.execute("SignalingAcceptRenegotiation",(()=>this.signalingSession.acceptRenegotiationAsync(a,s,t))),await n.execute("SignalingMediaAcknowledgement",(()=>this.mediaAcknowledgmentOperation));const o=await n.execute("CompleteNegotiation",(()=>this.completeNegotiationAsync(t)));this.onNegotiationCompletion(o,!1,i,t,n.getTelemetryData())}catch(e){try{if(!e.phase||"CompleteNegotiation"===e.phase)throw this.callTelemetry.recordEvent("IncomingNegotiationFailure",e,t),e;const n=e;this.callTelemetry.recordEvent("IncomingNegotiationFailure",this.getTelemetryFromPhaseExecution(e),t);const r={type:this.mediaAgent.constants.RENEGOTIATION_ERROR.local,detail:e.error};if("SignalingAcceptRenegotiation"===n.phase||"SignalingMediaAcknowledgement"===n.phase)return i.logFailure("Error in renegotiateIncoming() -> rejecting media negotiation"),r.type=this.mediaAgent.constants.RENEGOTIATION_ERROR.signaling,this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),void await this.mediaSession.rejectNegotiationAsync(r,t);this._callOperationHandler.maybeRejectOperation("_MediaAcknowledgment",r,void 0,t),await this.mediaSession.rejectNegotiationAsync(r,t),await this.signalingSession.rejectRenegotiationAsync(void 0,t)}catch(e){i.logFailure(e),this.callTelemetry.recordEvent("NegotiationFatalError",De(e),t),this.stopInternal({causeId:t,terminatedReason:47})}}}async updateMediaDescriptions(e){const t=this.logger.createFnLogger("updateMediaDescriptions",e);t.info("start");try{const i=await this.mediaSession.startMediaDescriptionsUpdateAsync(e);t.info(`send updateMediaDesriptions, descriptions=${Le(i)}`),await this.signalingSession.updateMediaDescriptionsAsync(e,i);const n=await this.mediaSession.completeMediaDescriptionsUpdateAsync(e);this.onUpdateMediaDescriptionsCompletion(n,e)}catch(i){t.logFailure(i),this.callTelemetry.recordEvent("UpdateMediaDescriptionsFailure",i,e);const n=await this.mediaSession.rejectMediaDescriptionsUpdateAsync(e,!0);this.onUpdateMediaDescriptionsFailure(i,n,e)}}handleCallEscalation(e,t){const i=this.logger.createFnLogger("handleCallEscalation",t);if(i.info(`current callType=${this.callType}, escalationInProgress=${e}, isEscalationInProgress=${this.isEscalationInProgress}`),e){const e=this.participants[0];e&&e.audio.participantId===Lm?e.updateStreams([{type:yp,direction:"inactive",sourceId:null,serverMuted:!1},{type:Cp,direction:"inactive",sourceId:null,serverMuted:!1},{type:_p,direction:"inactive",sourceId:null,serverMuted:!1}],t):i.info("no 1-1 participant found, stream update ignored"),this.setCallType(2,t),this.setCallUsesMixer(!0,t),this.setIsEscalationInProgress(!1,t),this.callTelemetry.recordEvent("_EscalationCompleted",void 0,t),this.raiseChanged()}}async reportTsCallingTelemetry(e){if(this.tsCallingTelemetryReported)return;await this.connectCallPromise.catch(Sn);const t=e?"call_setup_session":"in_call_session";this.callTelemetry.setCallEndDiagnosticInfo(this.callEndDiagnosticsInfo),this.reportTelemetryEvents([{eventName:t,props:this.callTelemetry.getEvent(e)}],"signaling","skypecosi_concore_web_ts_calling"),e?this.callTelemetry.switchToInCallTelemetry():this.tsCallingTelemetryReported=!0}async sendMidCallTelemetry(e){this.mediaSession&&e?.length&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(!0)),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildMidCallTelemetry(e),"media","mdsc_mid_call_telemetry"))}sendCallSetupTelemetry(){this.mediaSession&&(this.collectCallStats(this.mediaSession),this.reportCallSetupStats(),this.isCallSetupTelemetrySent=!0)}collectCallStats(e){const t=()=>this.collectMediaStatsDeferred.resolve();return e.getStatsAsync(!1).then((e=>this.callStats.setMediaStats(e))).then(t,t)}reportCallSetupStats(){this.collectMediaStatsDeferred.promise.then((()=>{this.reportTelemetryEvents(this.callStats.buildFromCallSetupStats(),"media","mdsc"),this.event("statsReported").raise(),this.collectMediaStatsDeferred=Si()}))}async reportCallEndStats(e){this.callTelemetry.setTerminationState(this.state),this.callTelemetry.setTerminationReason(this.terminatedReason),this.callStats.localStats.endCall(this.terminatedReason),this.reportTelemetryEvents(this.callStats.buildFromLocalStats(),"signaling","skypecosi_concore_web"),this.reportTsCallingTelemetry(!this._callIsSetupComplete),e&&(await this.collectMediaStatsDeferred.promise,this.callStats.appendTerminationInfo(this.terminatedReason,this.state),this.appendInfoToCallStats(),this.reportTelemetryEvents(this.callStats.buildFromMediaStats(),"media","mdsc")),this.event("statsReported").raise(),this.collectMediaStatsDeferred=Si()}reportTelemetryEvents(e,t,i){const n=this.telemetryLoggers?this.telemetryLoggers[t]:null;n?e.forEach((e=>n.sendEvent({eventName:`${i?`${i}_`:""}${e.eventName}`,props:e.props}))):this.logger.debug(`reportTelemetryEvents no logger for tenant ${t}`)}onLocalPreviewSizeChanged(e,t){this.logger.debug(`onLocalPreviewSizeChanged: ${e}x${t}`)}onLocalPreviewStateChanged(e){this.logger.debug(`onLocalPreviewStateChanged: ${e}`),this.callStats.localStats.video.streamStateChanged(e.stream)}async configureVideoModalitiesAsync(e,t){if(!this.mediaSession)return this.logger.warn("Tried to configure modalities after call end"),Promise.resolve();await this.updateMediaModalities(void 0,t),e||this.turnOffLocalVideoPreview(t),this.setVideoOn(e,t)}turnOffLocalVideoPreview(e){return this.localVideoRenderer&&(this.localVideoRenderer.dispose(),this.localVideoRenderer=null),this.disposeLocalVideoHandle(),Promise.resolve(void 0)}turnOnLocalVideoPreview(e){return this.mediaSession?.getSessionConfig().config.useDeviceHandleForLocalVideo?this.acquireLocalVideo(e):(this.localVideoContainer||(this.localVideoContainer=document.createElement("div")),this.turnOnLocalVideoPreviewUsingRenderer(e))}acquireLocalVideo(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e);if(!this.mediaStateConfigurationHelper.isSending(1))return Promise.reject("could not start video preview, not configured to send");try{this.disposeLocalVideoHandle();const e=this.callDeviceManager.getDeviceManager(Kh(1));return this.localVideoHandle=e.createDevicesHandle({video:!0},"pluginlessCall:acquireLocalVideo()"),this.localVideoHandle.on("onStreamStateChanged",(e=>this.onLocalPreviewStateChanged({stream:e}))),this.localVideoHandle.acquire()}catch(e){return t.logFailure(e),void this.disposeLocalVideoHandle()}}turnOnLocalVideoPreviewUsingRenderer(e){const t=this.logger.createFnLogger("_StartPreviewVideo",e),i=this.mediaStateConfigurationHelper.isSending(1);if(!i||!this.localVideoContainer)return Promise.reject(`could not start video preview: requestedVideoState=${i}, localVideoContainer=${this.localVideoContainer}`);this.turnOffLocalVideoPreview(e);const n=vi((()=>{this.localVideoRenderer=this.callDeviceManager.getDeviceManager(Kh(1)).createPreviewRenderer(this.localVideoContainer),this.localVideoRenderer.on("onVideoSizeChanged",((e,t)=>this.onLocalPreviewSizeChanged(e,t))),this.localVideoRenderer.on("onVideoStateChanged",(e=>this.onLocalPreviewStateChanged(e)))})).then((()=>this.localVideoRenderer.startVideoAsync(e)));return n.catch((e=>t.logFailure(e))),n}async startStopVideo(e,t){const i=this.logger.createFnLogger(e?"startVideo":"stopVideo",t);return i.info("start"),this.canToggleVideo?(e?(this.callStats.localStats.newSession(1),this.callStats.localStats.video.start()):this.callStats.localStats.video.stop(),e&&this.mediaStateConfigurationHelper.isDisabled(1)&&i.info("Video modality was skipped till now. Adding it now."),e?this.mediaStateConfigurationHelper.enableModality(1):this.mediaStateConfigurationHelper.removeModality(1),this.canToggleVideo=!1,this.videoTogglePromise=(async()=>{try{let i=!1;e&&(await this.turnOnLocalVideoPreview(t),i=!0),await this.configureVideoModalitiesAsync(i,t)}catch(e){throw i.logFailure(e),this.mediaStateConfigurationHelper.removeModality(1),await this.configureVideoModalitiesAsync(!1,t),e}finally{this.canToggleVideo=!0}})(),this.videoTogglePromise):e===this.mediaStateConfigurationHelper.isSending(1)?(await this.videoTogglePromise,void this.turnOnLocalVideoPreview(t)):(i.logFailure(`video switching is in progress ${e}]`),Promise.reject({reason:1}))}async startStopAudio(e,t){const i=this.logger.createFnLogger(e?"startAudio":"stopAudio",t);try{const e=await this.updateMediaModalities(void 0,t);this.updateMediaState(e,t)}catch(e){return i.logFailure(e),9}return 0}updateEndpointStateForMute(e,t){try{this.signalingSession.updateEndpointState({state:{isMuted:e}},t).catch((e=>{this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}))}catch(e){this.logger.logFailure(`updateEndpointStateForMute failure: ${e}`)}}async handleServerMutedState(e){const t=this.logger.createFnLogger(`handleServerMutedState, isServerMuted=${!!this.isServerMuted}`,e);if(!this.isServerMuted){const i=3===this._muteState;if(1===this._muteState||i)try{t.info("is unmuting, as we are no longer server muted"),await this.handleMuteUnmuteOnMediaSession(!1,e),this.setMuted(0,e),this.unmutePendingPromise?.resolve(),i&&this.updateEndpointStateForMute(!1,e)}catch(e){throw t.logFailure(e),e}}if(this.isServerMuted&&0===this._muteState){t.info("is muting, as we are unmuted");try{await this.handleMuteUnmuteOnMediaSession(!0,e),this.setMuted(1,e)}catch(e){throw t.logFailure(e),e}}}async handleMuteUnmuteOnMediaSession(e,t){const i=this.logger.createFnLogger(`handleMuteUnmuteOnMediaSession, value=${!!e}`,t);if(this.mediaSession&&this.mediaSession.getAllowedModalities&&!this.isServerMuted){const n=this.isMuted||this.isServerMuted,r=this.mediaSession.getAllowedModalities().audio.some((e=>e===fp||e===Sp));(n&&r||!n&&!r)&&(i.info(`updating audio modalities: Muted ${n} -> ${e}; audioAllowed = ${r}`),await this.updateMediaModalities(void 0,t))}return e?(i.info("mediaSession.muteInputAsync"),await this.mediaSession.muteInputAsync(t)):e||(i.info("mediaSession.unmuteInputAsync"),await this.mediaSession.unmuteInputAsync(t)),Promise.resolve()}updateCapabilities(e,t=!1){let i=!1,n=!1;if(!gh(this.state,[11,12])){const e="attendee"===(this.advancedMeetingRole||this.meetingRole);this.isServerMuted&&!this._callInLobby?2&this._commandUrlPresence&&(i=!0):this.isMuted&&(i=!0),n=!!(1&this._commandUrlPresence)&&!e}this._capabilities.canUnmuteSelf===i&&this._capabilities.canMuteOthers===n||(this._capabilities.canUnmuteSelf=i,this._capabilities.canMuteOthers=n,this.logger.info(`[${e}][updateCapabilities] Computed self capabilities: ${JSON.stringify(this._capabilities)}`),t&&this.raiseChanged())}async evaluateEndpointStatesForAccept(e,t,i){const n=this.logger.createFnLogger(`evaluateEndpointStatesForAccept, isMuted=${!!e}`,i),r={};try{await this.handleMuteUnmuteOnMediaSession(e,i),Object.assign(r,{state:{isMuted:e}}),n.info("is updating endpointState for mute"),t&&(Object.assign(r,{endpointProperties:{additionalEndpointProperties:t}}),n.info("is updating endpointState for additionalEndpointProperties"))}catch(e){throw n.logFailure(e),Un(e)}return r}async handleEndpointStatesForAccept(e,t){const i=this.logger.createFnLogger("handleEndpointStatesForAccept",t);try{await this.signalingSession.updateEndpointState(e,t)}catch(e){throw i.logFailure(e),Un(e)}}async muteUnmute(e,t){const i=this.logger.createFnLogger(`muteUnmute, value=${!!e} isServerMuted=${this.isServerMuted} inLobby=${this._callInLobby}`,t);if(gh(this.state,[11,12]))return i.logFailure("Can not mute/unmute during preheat call"),Promise.reject(Un("TransactionDisallowed"));const n=!e&&(!this.isServerMuted||this._callInLobby);try{if((e||n)&&await this.handleMuteUnmuteOnMediaSession(e,t),e)this.setMuted(2,t),i.info("is updating endpointState for mute"),this.updateEndpointStateForMute(!0,t);else{if(!n)return i.info("is unmuting on server"),2===this._muteState&&this.setMuted(3,t),this.isCallModeStreaming()?this.promoteToRealtimeAndUnmute(t):this.signalingSession.unmuteAsync(t).then((e=>{this.handleSelfUnmuteUpdatedInfo(e,t)}));i.info("is updating endpointState for unmute"),this.setMuted(0,t),this.updateEndpointStateForMute(!1,t)}}catch(e){throw i.logFailure(e),Un(e)}}async muteUnmuteSpeaker(e,t){this.setSpeakerMuted(e,t),this.mediaSession&&(e?await this.mediaSession.muteOutputAsync(t):await this.mediaSession.unmuteOutputAsync(t))}getParticipant(e){return this.participants.filter((t=>t.isSameParticipantsMri(e)))[0]}getOrCreateParticipant(e,t,i){let n=this.getParticipant(e);return n||(n=new $p(e,this.mediaSession,this.logger,this.callStats.localStats,this.callTelemetry,t),n.changed((()=>this.onParticipantChanged(n))),this.participants.push(n),i&&this.event("participantAdded").raise(n),this.monitorCallStart(),n)}onParticipantChanged(e){this.event("participantUpdated").raise(e),this.raiseChangedDeferred(this._participantChangedEventSkipConfig)}setCallState(e,t,i=0){if(this.state===e)return;const n=this.logger.createFnLogger("setCallState",t);n.info(`currentState=${this.state}, newState=${e}, terminatedReason=${this.terminatedReason}`),(Sh[this.state].indexOf(e)>=0||(n.logFailure("invalid state transition"),7===e))&&(this.callTelemetry.recordEvent("_SetCallState",{state:e,reason:i},t),this.state=e,this.callStats.localStats.call.callStateChanged(e),7===e&&this.setTerminatedReason(i),3===e&&(this.callGotConnected=!0,this.callHeldAt=null),this.callIsHeld()&&!this.callHeldAt&&(this.callHeldAt=new Date),n.logSuccess(`changed to ${e}, terminatedReason: ${this.terminatedReason}, failureType=${this.failureType}`),this.screenSharingControl.callStateChanged(this.state),this.monitorCallStart(),this.event("callStateChanged").raise(),this.updateCapabilities(t),this.raiseChanged(),this.callTelemetry.recordEvent("_RaiseCallStateChangeEvent",{state:e,reason:i},t))}setTerminatedReason(e){if(this.terminatedReason=e,!(0,fr.includes)(Nm,e)){const e=44===this.terminatedReason,t=55===this.terminatedReason,i=56===this.terminatedReason;this.setFailureType(!this.callGotConnected||!this._wasAudioStreamConnected||e||t||i?0:1)}}setMediaStream(e,t,i){if(e){if(!(0,fr.find)(this.localMediaStreams,(e=>e.mediaType===i))){const e=new xm(t,i);this.logger.info(`setMediaStream ${JSON.stringify(e)}`),this.localMediaStreams.push(e)}}else this.logger.info(`setMediaStream removing ${i}`),(0,fr.remove)(this.localMediaStreams,(e=>e.mediaType===i))}setVideoOn(e,t){this.logger.info(`[${t}]videoOn=${e}`),this.isVideoOn=e,this.setMediaStream(this.isVideoOn,!0,1),this.callTelemetry.recordEvent("_SetLocalVideo",{value:e},t),this.raiseChanged()}setAudioOn(e,t){this.logger.info(`[${t}]audioOn=${e}`),this.setMediaStream(e,!0,0),this.callTelemetry.recordEvent("_SetLocalAudio",{value:e},t)}setScreenSharingOn(e,t){this.logger.info(`[${t}]screenSharingOn=${e}`),this.isScreenSharingOn=e,this.setMediaStream(this.isScreenSharingOn,this.isScreenSharingOn,2),this.callTelemetry.recordEvent("_SetScreenSharing",{screenSharingOn:e},t),this.event("userActivityChanged").raise(),this.raiseChanged()}disposeSharingScreenHandle(){this.sharedScreenHandle&&(this.sharedScreenHandle.dispose(),this.sharedScreenHandle=null)}disposeLocalVideoHandle(){this.localVideoHandle?.dispose(),this.localVideoHandle=null}setMuted(e,t){this._muteState!==e&&(this._muteState=e,this.callTelemetry.recordEvent("_SetMuted",{isMuted:e},t),this.logger.info(`[${t}]participantMuteState:${e}, isMuted: ${this.isMuted}`),this.updateCapabilities(t),this.raiseChanged(),this.event("muteStateChanged").raise(this.isMuted,t))}setSpeakerMuted(e,t){this.logger.info(`[${t}]speakerMute=${e}]`),this.isSpeakerMuted=e,this.raiseChanged()}monitorCallStart(){3!==this.state||!this.participants.length&&2!==this.callMode||this.callStartedAt||(this.callStartedAt=new Date)}_removeParticipant(e,t,i=0){const n=this.logger.createFnLogger("removeParticipant",t);n.info(`mri=${lp(e)}`);const r=(0,fr.remove)(this.participants,(t=>t.isSameParticipantsMri(e.id)))[0];r?(r.setState(4,i,t),this.event("participantRemoved").raise(r)):n.logFailure(`unable to remove participant ${Ae(e.id)}`),this.raiseChanged(this._participantChangedEventSkipConfig)}setIsSomeoneSharing(e,t){const i=this.isSomeoneSharing!==e&&!(e&&this.screenSharingRenegotiationDeferred&&this.callUsesMixer);i&&(this.isSomeoneSharing=e);let n=i;if(this.callUsesMixer&&this.mediaSession?.getSessionConfig().config.enableStopSharingWithIncomingOffer&&(n||(n=t)),n&&this.isSomeoneSharing&&this.isScreenSharingOn&&(this.stopScreenSharing(),this.logger.info("sharingStolen: Cleaning up local screenshare because remote screenshare is running"),this.event("sharingStolen").raise()),this.allowScreenSharingControl()){const e=this.localSignalingParticipant.endpointDetails.find((e=>this._endpointId===e.endpointId)),t=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,t,e)}}handleOfferedModalities(e,t){const i=this.mediaAgent.constants.MEDIA_STATE,n=this.logger.createFnLogger("handleOfferedModalities",t);try{n.info(`offeredModalities=${Le(e)}`)}catch(e){n.logFailure(e)}e.hasOwnProperty("video")||this.mediaStateConfigurationHelper.isSending(1)?e.hasOwnProperty("video")&&!this.mediaStateConfigurationHelper.isSending(1)&&this.mediaStateConfigurationHelper.removeModality(1):this.mediaStateConfigurationHelper.disableModality(1),e.hasOwnProperty("sharing")||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.disableModality(2),e.sharing!==i.receive||this.mediaStateConfigurationHelper.isSending(2)||this.mediaStateConfigurationHelper.removeModality(2),e.data===i.sendReceive&&this.allowDataChannel()&&this.mediaStateConfigurationHelper.enableModality(3),this.setIsSomeoneSharing(e.sharing===i.receive,!0),this.isSomeoneStreamingVideo=e.video===i.receive||e.video===i.sendReceive}getRenegotiationOfferType(e){if(e)if(5===this.state){if("sendrecv"===e.audio)return 2}else if(this.modalitiesAreHold(e))return 1;return 0}isRenegotiationHoldOrResume(e){return 1===this.getRenegotiationOfferType(e)||2===this.getRenegotiationOfferType(e)}isValidHoldResumeCallState(e){return[3,5,10,13].includes(e)}onNegotiationCompletion(e,t,i={},n,r){const a=this.logger.createFnLogger("onNegotiationCompletion",n);a.info(`byLocal=${t}, result=${Le(e)}`),this.callTelemetry.recordEvent("NegotiationCompletion",{phaseTelemetryBag:r,...this.prepareNegotiationResultForTelemtry(e)},n);const s=this.isOneToOneCall();if(s){const t=this.modalitiesAreHold(e.activeModalities)?5:3;this.participants[0].setState(t,void 0,n),a.info(`isOneToOneCall: participant[0] state set to ${t}`)}const o=this.modalitiesAreHold(e.configuredModalities),l=this.modalitiesAreHold(e.activeModalities);let c;const d=this.signalingSession.participantManager.localParticipant.isStaging;a.info(`isStaging= ${d}`),this.requestedHoldState?(o&&l||a.info(`Not expected modalities when processing local hold: ${o} ${l}`),4!==this.state&&a.info(`Not expected state when processing local hold: ${this.state}, switching back to LocalHold`)):t||this.callHoldResumeDeferred?!o&&l?c=5:o||l||this._callInLobby||this.isPreheatedOnly()||(c=d?13:3):4===this.state||this._callInLobby||this.isPreheatedOnly()||(c=s&&5===this.participants[0].state?5:d?13:3),c&&this.setCallState(c,n),this.callHoldResumeDeferred&&(a.info(`isHoldInProgress=${this.isHoldInProgress}, state=${this.state}, completed=${l}`),this.isHoldInProgress?l&&this.finishCallHoldResume():this.inLocalHold()||this.finishCallHoldResume(this.isValidHoldResumeCallState(c)?void 0:new Error(`Call state changed to ${c} instead of Connected, Lobby, Staging or RemoteHold`))),this.requestedHoldState||(this.setIsSomeoneSharing((0,fr.some)(this.participants,(e=>(0,fr.some)(e.streams[1],(e=>e.isAvailable))))),this.isSomeoneStreamingVideo=(0,fr.some)(this.participants,(e=>(0,fr.some)(e.streams[0],(e=>e.isAvailable)))));const u=i&&i.sharing===this.mediaAgent.constants.MEDIA_STATE.send,h=e?.activeModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(this.resolveScreenSharingRenegotiation(n,u,h,e.isComplete),this.retryOutgoingRenegotiation.retry){const e=this.retryOutgoingRenegotiation.causeId;this._callOperationHandler.executeChained((()=>this.updateMediaModalities(void 0,e)),"_Renegotiate",e,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),this.retryOutgoingRenegotiation.retry=!1}}onUpdateMediaDescriptionsFailure(e,t,i){const n=t?.requestedModalities.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.screenSharingRenegotiationDeferred&&n&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}onUpdateMediaDescriptionsCompletion(e,t){this.logger.createFnLogger("onUpdateMediaDescriptionsCompletion",t).info(`result=${Le(e)}`),this.callTelemetry.recordEvent("UpdateMediaDescriptionsCompletion",e,t);const i=e?.requestedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send,n=e?.appliedModalities?.sharing===this.mediaAgent.constants.MEDIA_STATE.send;this.resolveScreenSharingRenegotiation(t,i,n,!0)}resolveScreenSharingRenegotiation(e,t,i,n){const r=this.logger.createFnLogger("resolveScreenShareRenegotiation",e);if(r.info(`invoked with wasSharingOfferred: ${t}, isSharingActive: ${i}, isComplete: ${n}`),this.screenSharingRenegotiationDeferred)if(t&&i)r.info("resolving screenSharingRenegotiationDeferred"),this.screenSharingRenegotiationDeferred.resolve(),this.screenSharingRenegotiationDeferred=null;else if(this._enableResolveScreenSharingWhenNegotiationComplete&&n&&!this.retryOutgoingRenegotiation.retry&&this.canToggleScreenSharing){const e=new Error(`screenSharing error: wasSharingOfferred: ${t}, isSharingActive: ${i}`);r.info(`reject screenSharingRenegotiationDeferred ${e}`),this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null}}async updateMediaStatus(e){if(this.calculateIsSomeoneStreaming(e),this.mediaSession){const t=await this.updateMediaModalities(void 0,e);this.callTelemetry.updateOperationData("_UpdateLocalMediaStatus",t,e)}}calculateIsSomeoneStreaming(e){let t=!1,i=!1;for(const e of this.participants)if(t||(t=(0,fr.some)(e.streams[1],(e=>e.isAvailable))),i||(i=(0,fr.some)(e.streams[0],(e=>e.isAvailable))),t&&i)break;this._hasDelayedReconnect&&(t||i)&&(this.logger.info("Reconnecting with delay"),this._hasDelayedReconnect=!1,this._callOperationHandler.executeChained((()=>this.mediaSession.reconnectAsync(e,!0)),"_RenegotiateOutgoing",e,e,void 0,void 0,{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})),this.setIsSomeoneSharing(t),this.isSomeoneStreamingVideo=i}onNegotiationFailure(e,t,i,n){const r=n&&n.sharing===this.mediaAgent.constants.MEDIA_STATE.send;if(t===this.mediaAgent.constants.RENEGOTIATION_ERROR.glare)return this.screenSharingRenegotiationDeferred&&r&&this.callStats.localStats.screenShare.negotiationStateChanged("rejected","glare"),void(this.retryOutgoingRenegotiation={retry:!0,causeId:i});const a=new Error(`Error in renegotiateOutgoing() -> rejecting hold for callId = ${this.callId}, reason=${t}`);a.innerError=e,this.finishCallHoldResume(a),this.screenSharingRenegotiationDeferred&&r&&(this.screenSharingRenegotiationDeferred.reject(e),this.screenSharingRenegotiationDeferred=null)}static getParticipantReasonFromTerminatedReason(e){switch(e){case 1:return 0;case 9:return 2;case 10:return 3;case 2:return 4;case 24:return 8;case 3:return 9;case 4:return 10;case 14:return 12;case 0:default:return 11;case 15:return 13;case 16:return 14;case 17:return 15;case 18:return 16;case 19:return 17;case 20:return 18;case 11:return 19;case 21:return 20;case 22:return 21;case 23:return 22;case 33:return 25;case 36:return 26;case 37:return 27;case 41:return 30;case 39:return 28;case 42:return 31;case 40:return 29;case 43:return 32;case 44:return 33;case 45:return 34;case 46:return 35;case 47:return 36;case 48:return 37;case 49:return 38;case 50:return 39;case 51:return 40;case 52:return 41;case 54:return 42;case 55:return 44;case 56:return 45;case 12:return 23;case 59:return 46;case 73:return 59;case 61:return 47;case 60:return 48;case 62:return 49;case 63:return 50;case 64:return 5;case 65:return 51;case 8:return 52}}isRemoteParticipantInStaging(e){if(!e.endpointDetails)return!1;for(const t of e.endpointDetails)if(!Nd(t))return!1;return!0}updateCallParticipantFromSignalingParticipant(t,i,n){if((0,fr.every)(i.endpointDetails,(e=>e?.isLobby||e?.streamLobby)))return void t.setState(7,void 0,n);const r=(0,fr.some)(i.endpointDetails,(e=>e?.streamInformation)),a=i.endpointDetails&&(0,fr.some)(i.endpointDetails,(e=>e.mappedTo)),s=e.filterVirtualEndpoints(i.endpointDetails),o=s&&s[0].mediaStreams,l=this.isRemoteParticipantInStaging(i);if(o&&o.length>0){const e=o.every((e=>"inactive"===e.direction));let i=e?5:l?8:3;1!==this.state||e||this.callUsesMixer||(i=2),this.logger.info(`[updateCallParticipantFromSignalingParticipant]: with mediaStreams is not empty, ParticipantState is set to ${i}`),t.setState(i,void 0,n)}else if(o||a||r){const e=l?8:3;this.logger.info(`[updateCallParticipantFromSignalingParticipant]: ParticipantState is set to ${e}, mediaStreams=${!!o}, hasMappedEndpoints=${a}, hasPlayerStreams=${r}`),t.setState(e,void 0,n)}}handleSelfServerMutedState(t){const i=e.filterVirtualEndpoints(this.localSignalingParticipant.endpointDetails),n=(0,fr.find)(i,(e=>this._endpointId===e.endpointId)),r=n&&n.mediaStreams,a=r&&r.filter((e=>"audio"===e.type||"audio-teleconferencing"===e.type)),s=n&&(n.stream||n.streamLobby);if(s){const e=s.serverMuted??!1;n.serverMuteVersion=0,e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.isServerMuted&&this.setMuted(1,t))}else if(a&&a.length>0){const e=a.some((e=>e.serverMuted));e!==this.isServerMuted&&(this.isServerMuted=e,this.callTelemetry.recordEvent("_SelfParticipantUpdated",{isServerMuted:this.isServerMuted}),this.logger.info(`updateLocalParticipant: server muted set to ${e}`),this.event("serverMutedChanged").raise(e,t),this.updateCapabilities(t,!0),this.handleServerMutedState(t))}}checkIfIncomingServerMutedIsUpdated(e){const t=(0,fr.find)(this.localSignalingParticipant.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));if(void 0===t)return;const i=(0,fr.find)(e.endpointDetails,(e=>e.participantId===this.localSignalingParticipant.participantId));rp(this.logger,t,i)}convertWiredPublishedState(e){if(!e)return;const t=Da(e.stateType);return{content:e.content,stateType:t,typeRank:e.typeRank,stateId:e.stateId}}updatePublishedStateModified(e,t){e!==this.currentUserSkypeIdentity.id||t&&t!==this.participantId?this._publishedStatesModified=2|this._publishedStatesModified:this._publishedStatesModified=1|this._publishedStatesModified}updatePublishedStates(e){try{let t=[];(0,fr.forEach)(e.publishedStates,(e=>{t.push(this.convertWiredPublishedState(e))})),(0,fr.isEqual)(this._participantPublishedStatesMap[e.id],t)||(0!==t.length||void 0!==this._participantPublishedStatesMap[e.id]&&null!==this._participantPublishedStatesMap[e.id])&&(this._participantPublishedStatesMap[e.id]=t,this.updatePublishedStateModified(e.id));const i=[];(0,fr.forEach)(e.endpointDetails,(n=>{i.push(n.participantId),t=[],(0,fr.forEach)(n.publishedStates,(i=>{const r=this.convertWiredPublishedState(i);this._endpointPublishedStatesMap[e.id]||(this._endpointPublishedStatesMap[e.id]={},this._endpointPublishedStatesMap[e.id][n.participantId]=[]),t.push(r)})),this._endpointPublishedStatesMap[e.id]&&!(0,fr.isEqual)(this._endpointPublishedStatesMap[e.id][n.participantId],t)&&(0!==t.length||null!==this._endpointPublishedStatesMap[e.id][n.participantId]&&void 0!==this._endpointPublishedStatesMap[e.id][n.participantId])&&(this._endpointPublishedStatesMap[e.id][n.participantId]=t,this.updatePublishedStateModified(e.id,n.participantId))})),this._endpointPublishedStatesMap[e.id]&&Object.keys(this._endpointPublishedStatesMap[e.id]).forEach((t=>{i.some((e=>e===t))||(delete this._endpointPublishedStatesMap[e.id][t],this.updatePublishedStateModified(e.id,t))}))}catch(e){this.logger.error(`updatePublishedStates ${JSON.stringify(e)}`)}this.logger.info(`updatePublishedStates ${JSON.stringify(this._participantPublishedStatesMap)}`),this.logger.info(`updatePublishedStates ${JSON.stringify(this._endpointPublishedStatesMap)}`)}removePublishedStatesByParticipant(e){this._endpointPublishedStatesMap[e]&&delete this._endpointPublishedStatesMap[e],this._participantPublishedStatesMap[e]&&delete this._participantPublishedStatesMap[e],this.updatePublishedStateModified(e)}findOrCreateTypeState(e){let t=this._publishedStates.typeStates.findIndex((t=>t.type===e));if(-1===t){const i={participantStates:[],type:e};this._publishedStates.typeStates.push(i),t=this._publishedStates.typeStates.length-1}return t}processPublishedStates(){this.logger.info(`processPublishedStates ${JSON.stringify(this._participantPublishedStatesMap)}`),this.logger.info(`processPublishedStates ${JSON.stringify(this._endpointPublishedStatesMap)}`);try{this._publishedStates||(this._publishedStates={typeStates:[]}),this._publishedStates.typeStates=[];for(const e of Object.keys(this._participantPublishedStatesMap)){const t=this._participantPublishedStatesMap[e];(0,fr.forEach)(t,(t=>{const i=this.findOrCreateTypeState(t.stateType),n={id:e,publishedState:{content:t.content,stateId:t.stateId,typeRank:t.typeRank}};this._publishedStates.typeStates[i].participantStates.push(n)}))}for(const e of Object.keys(this._endpointPublishedStatesMap))for(const t of Object.keys(this._endpointPublishedStatesMap[e]))this._endpointPublishedStatesMap[e][t].forEach((i=>{const n=this.findOrCreateTypeState(i.stateType),r={id:t,publishedState:{content:i.content,stateId:i.stateId,typeRank:i.typeRank}},a={id:e,endpoints:[r]},s=this._publishedStates.typeStates[n].participantStates.filter((t=>t.id===e));s&&s.length>0?(s[0].endpoints||(s[0].endpoints=[]),s[0].endpoints.push(r)):this._publishedStates.typeStates[n].participantStates.push(a)}));this.event("publishedStatesChanged").raise(this._publishedStates),this.raiseChanged()}catch(e){this.logger.error(`processPublishedStates ${e}}`)}}updateLocalParticipant(t,i){const n=this.logger.createFnLogger("updateLocalParticipant",i);this.checkIfIncomingServerMutedIsUpdated(t),this.localSignalingParticipant.endpointDetails=t.endpointDetails,this.localSignalingParticipant.role=t.role,this.setMeetingRole(t.meetingRole),this.setAdvancedMeetingRole(t.advancedMeetingRole),this.setParticipantType(t.participantType),this.setPropertyBag(t.propertyBag),this.setPropertyRosterVersion(t.version),this.setMaskedIdentityDetails(t.isIdentityMasked,t.maskedIdSeqNumber,t.maskedId),this.localSignalingParticipant.tenantId=t.tenantId,this.localSignalingParticipant.isLobby=t.isLobby,t.joinAsStreamingUser&&(this.localSignalingParticipant.joinAsStreamingUser=t.joinAsStreamingUser,this.setJoinAsStreamingUser(t.joinAsStreamingUser)),void 0!==t.enableCaptcha&&this.setEnableCaptcha(t.enableCaptcha),this.callTelemetry.setTenantId(t.tenantId),this.callStats.setTenantId(t.tenantId);const r=this.localSignalingParticipant.isLobby;t.endpointDetails&&this.updateLocalParticipantEndpoints(t.endpointDetails),this.updatePublishedStates(t),this.handleSelfServerMutedState(i);const a=this.getLocalSignalingEndpointDetails();this._callInLobby=r||!!a?.streamLobby,this.signalingSession.participantManager.localParticipant.isStaging=t.isStaging;const s=this.signalingSession.participantManager.localParticipant.isStaging;n.info(`callInLobby = ${r}, callSetupComplete = ${this._callIsSetupComplete}, callIsHeld = ${this.callIsHeld()}, isStaging = ${s}`),!this._callIsSetupComplete||this.callIsHeld()||gh(this.state,[11,12])||(r?this.setCallState(10,i):s&&gh(this.state,[3,13,10,9,2])?this.setCallState(13,i):this.setCallState(3,i));const o=e.getStreamsFromEndpoints(t.endpointDetails);if(this.callTelemetry.recordEvent("_UpdateLocalParticipantStream",function(e){let t=[];return e.forEach((e=>{try{let i=t.find((t=>t.participantId===e.participantId&&t.endpointId===e.endpointId));i||(i={participantId:e.participantId,endpointId:e.endpointId},t.push(i)),"audio"!==e.type&&"audioteleconference"!==e.type||(i.serverMuted=e.serverMuted),i[e.type]=e.direction}catch(e){t=[]}})),t}(o),i),this.streamManager.updateStreams(o,i),this.updateCapabilities(i,!0),this.allowScreenSharingControl()){const e=t.endpointDetails.find((e=>this._endpointId===e.endpointId)),i=this.participants.find((e=>e.streams[1].some((e=>e.isAvailable))));this.screenSharingControl.startOrStopControlForViewer(this.isSomeoneSharing,i,e)}}modalitiesAreHold(e){return!(e.audio&&"inactive"!==e.audio||e.video&&"inactive"!==e.video||e.sharing&&"inactive"!==e.sharing)}toneToString(e){switch(e){case 0:return"0";case 1:return"1";case 2:return"2";case 3:return"3";case 4:return"4";case 5:return"5";case 6:return"6";case 7:return"7";case 8:return"8";case 9:return"9";case 10:return"*";case 11:return"#";default:return null}}static streamingStatetoMediaStreamState(e){switch(e){case"started":return 0;case"active":return 2;case"inactive":return 1;case"stopped":return 3;default:return 4}}static streamingDirectionToMediaDirectionMapping(e){switch(e){case"send":return 1;case"receive":return 0;default:return}}static convertMuteScope(e){switch(e){case 0:return"EveryoneElse";case 1:return"SpecifiedParticipants";default:return}}callIsHeld(){return 4===this.state||5===this.state}inLocalHold(){return this.isHoldInProgress||4===this.state}telemetryDataFromCallStartOptions(e){const t={};return e.muteFlags&&(t.muteMicrophone=!!(1&e.muteFlags),t.muteSpeaker=!!(2&e.muteFlags)),Object.keys(t).length?t:void 0}reconnect(){const e=Te();return this.mediaSession.reconnectAsync(e)}async provideCallQualityFeedback(e,t,i,n){}async showCQFInfo(e,t){throw new Error("Not implemented")}async isCqfRendered(e){}async provideCallQualityFeedbackEx(e,t,i,n,r,a){}testTriggerMediaRelayWhiteListingIssue(){this.logger.info("Simulating media relay whitelisting issue for test purposes");const e=this.mediaSession.mediaSession.callback;e.onQualityChanged({type:"NetworkRelaysNotReachable",value:"Bad",isLocalSource:!0,mediaType:"Audio"});e.onAudioStateChanged({direction:"send",stream:"failed",content:"audio"})}async getMediaTelemetry(e=!1){return this.mediaSession&&(this.callStats.setMediaStats(await this.mediaSession.getStatsAsync(e)),this.appendInfoToCallStats()),this.callStats.buildMediaTelemetry()}getMediaSessionStats(){return this.mediaSession?.getMediaStatsReport()}getDiagnosticsForE2E(){return this.mediaSession?.getDiagnostics().e2eDiagnostics}appendInfoToCallStats(){this.callStats.appendDataChannelInfo(this.dataChannel.getTelemetry()),this.callStats.appendSharingControlInfo(this.screenSharingControl?.isScreenSharingControlEnabled()),this.callStats.appendMediaControlPaneInfo(JSON.stringify(this.mediaControlPlane.getTelemetryReport()))}getMediaLogs(){return this.mediaAgent.getMediaLogs()}testSetCallState(e){this.logger.info(`Overwriting call state for test purposes: ${this.state} -> ${e} `),this.state=e}testSetCallType(e){this.logger.info(`Overwriting call state for test purposes: ${this.callType} -> ${e} `),this.callType=e}addGroupModality(e,t=Te()){const i=this.logger.createFnLogger("AddGroupModality",t);if(!e.threadId&&!e.groupId)return Promise.reject(Un("No threadId/groupId was provided."));if(6===this.state||7===this.state)return i.info(`Not adding modality because CallState is ${this.state} groupId=${Ae(e.groupId)}, threadId = ${Me(e.threadId)} messageId = ${e.messageId}`),Promise.reject(Un("TransactionDisallowed"));let n;if(e.additionalData)try{n=JSON.stringify(e.additionalData)}catch(t){i.logFailure(`additionalData: ${e.additionalData} is not valid Json, error: ${t}`);const n={code:$n.BadRequest,subCode:0,phrase:`additionalData is not valid Json, error: ${t}`};return Promise.reject(n)}i.info(`groupId=${Ae(e.groupId)}, threadId = ${Me(e.threadId)} messageId = ${e.messageId} additionalData = ${Ae(n)}`);const r={groupId:e.groupId,threadId:e.threadId,messageId:e.messageId,additionalData:n};return this.signalingSession.addGroupModalityAsync(r,t).catch((e=>(i.logFailure(Ne(e)),Promise.reject(e))))}addBroadcastModality(e,t){const i=this.logger.createFnLogger("AddBroadcastModality",t);return Promise.resolve().then((()=>{this.signalingSession.addBroadcastModalityAsync(e,t)})).catch((e=>(i.logFailure(Ne(e)),Promise.reject(Un(e))))).then((()=>this._callOperationHandler.waitForOperation("AddBroadcastModality"))).catch((e=>{throw this.callTelemetry.updateOperationData("AddBroadcastModality",{error:De(e)},t),i.logFailure(e),e}))}static convertQualityEventType(e){switch(e){case"NetworkSendQuality":return 1;case"NetworkRecvQuality":return 2;case"NetworkDelay":return 3;case"NetworkBandwidthLow":return 4;case"NetworkReconnect":return 5;case"NetworkPacketLoss":return 6;case"NetworkJitter":return 7;case"NetworkRateMatching":return 8;case"DeviceCaptureNotFunctioning":return 9;case"DeviceRenderNotFunctioning":return 10;case"DeviceRenderGlitches":return 11;case"DeviceLowSNR":return 12;case"DeviceLowSpeechLevel":return 13;case"DeviceClipping":return 14;case"DeviceEcho":return 15;case"DeviceNearEndToEchoRatio":return 16;case"DeviceHalfDuplexAec":return 17;case"DeviceMultipleEndpoints":return 18;case"DeviceHowling":return 19;case"DeviceRenderZeroVolume":return 20;case"DeviceRenderMute":return 21;case"NetworkSendCatastrophic":return 22;case"NetworkRecvCatastrophic":return 23;case"CpuInsufficient":return 24;case"DeviceCaptureMute":return 25;case"DeviceCaptureNotMuteButSilent":return 26;case"DeviceSpeakWhileMuted":return 27;case"VideoVbssRendered":return 28;case"NetworkEthernetInterfaceUsed":return 29;case"NetworkWlanInterfaceUsed":return 30;case"NetworkWwanInterfaceUsed":return 31;case"NetworkRelaysNotReachable":return 32;case"VideoCapturerDeviceStartFailed":return 33;case"VideoCapturerDeviceStartTimedOut":return 34;case"VideoCapturerDeviceStartFailureLackSystemRes":return 35;case"VideoCapturerDeviceStartFailureMFResConflict":return 36;case"NoNetwork":return 37;case"NetworkNotWorking":return 38;case"DeviceCaptureNotFunctioningDeviceInUse":return 39;case"DeviceRenderNotFunctioningDeviceInUse":return 40;case"VideoCaptureDeviceFreeze":return 45;case"ZeroCaptureDevicesEnumerated":return 43;case"ZeroRenderDevicesEnumerated":return 44;case"VideoCapturePermissionDenied":return 47;case"ScreenshareRecordingDisabled":return 55;case"AudioCapturePermissionDenied":return 46;case"VideoCaptureFreezeRecovered":return 48;case"DeviceRenderHowling":return 49;case"PresentationAudioLoopbackDeviceState":return 53;case"RemoteNetworkConnectivityIssue":return 52;case"AudioCaptureUltrasoundDetected":return 54;case"MusicModeNotAvailable":return 57;case"CameraLighting":return 61;case"AudioLoopbackDeviceReady":return 63;case"NoRequiredVideoCodecs":return 64;case"SpatialAudioMUCHUnavailable":return 65;default:return}}static convertQualityLevel(e){switch(e){case"Unknown":return 0;case"Good":return 1;case"Poor":return 2;case"Bad":return 3;default:return}}static convertMediaType(e){switch(e){case"Audio":return 0;case"Video":return 1;case"ScreenShare":return 2;case"Data":return 3;default:return}}getPluginlessPublishLevel(e){switch(e){case"user":return"user";case"endpoint":return"endpoint";default:throw"Invalid level type."}}setIsEmergency(e){this.logger.info(`Set isEmergency:${e}`),this.isEmergency=e,this.callTelemetry.setIsEmergency(e)}static filterVirtualEndpoints(e){return e&&(0,fr.filter)(e,(e=>!e.mappedTo))}mapDataChannelSourceIdToParticipant(e){let t=null;return t=1===this.callType?this.participants[0]:(0,fr.find)(this.participants,(t=>t.hasSourceId(3,e))),t?.id?this.logger.info(`ParticipantId: ${Ae(t.id)} to SourceId: ${e}`):this.logger.warn(`No Participant found for SourceId: ${e}`),t}getDataChannelSourceId(){const e=(0,fr.find)(this.endpoints.endpointDetails,(e=>null!==e&&e.participantId===this._participantId));if(!e)return this.logger.warn(`No participantLeg found for participantId: ${this._participantId}`),-1;if(!e.mediaStreams)return this.logger.warn(`ParticipantLeg ${this._participantId} does not have valid mediaStreams`),-1;const t=(0,fr.find)(e.mediaStreams,(e=>3===kd(e.type)));return t?t.sourceId:(this.logger.warn(`participantLeg ${this._participantId} has no data channel`),-1)}initializeMediaControlPlane(){this.mediaControlPlane=new Xh(this.dataChannel,this.logger.createChild("MediaControlPlane"),this.mediaAgent.getConfigProvider().config.mediaControlPlaneConfig),this.mediaControlPlane.on("mpSendBandwidthChanged",(e=>{this.mediaSession?.processNotification("BandwithNotification",{bw:e});const t=this.mediaSession?.getExtensionsManager();t?.processNotification("BandwithNotification",{bw:e})})),this.mediaControlPlane.on("mpDshStatusChanged",(e=>{this.updateSignalingDSHMessageSubscription(!e),e&&this.mediaSession?.getDiagnostics()?.dshDiagnostics.setCurrentActiveStrategy("server")})),this.mediaControlPlane.on("onHandshakeTimeout",(()=>{this.isSignalingDSHFallbackEnabled()&&this.updateSignalingDSHMessageSubscription(!0)})),this.mediaControlPlane.on("mpDshChanged",(e=>{const t=this.mediaSession?.getExtensionsManager();t?.processNotification("McpDominantSpeakerInfo",{history:e})}))}initializeLiveStreamConfigProvider(){const e="MDN_MIDDLELANE_TEAMS",t=this.ecsProvider.getEcsConfig(e,"liveStream"),i=this.ecsProvider.getEcsConfig("ConfigIDs",e);this._liveStreamConfigProvider=new li(t,null,i,this.logger.createChild("LiveStreamConfigProvider"))}isMediaSending(e){return this.mediaStateConfigurationHelper.isSending(e)}};Fm.instanceCount=0,v([wn("Initialize",{type:"Sync",convertError:!0,idempotencyLevel:"NoOp"})],Fm.prototype,"init",1),v([wn("StartVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"startVideo",1),v([wn("StopVideo",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"stopVideo",1),v([wn("DumpVideoSourceImages")],Fm.prototype,"dumpVideoSourceImages",1),v([S(1,Pn)],Fm.prototype,"hold",1),v([wn("Hold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(0,Pn)],Fm.prototype,"holdWithRenegotiate",1),v([wn("LocalHold",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(0,Pn)],Fm.prototype,"localHold",1),v([wn("Unhold",{waitFor:["Hold","LocalHold"],preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"unhold",1),v([wn("UpdateEndpointMetadata"),S(1,Pn)],Fm.prototype,"updateEndpointMetadata",1),v([wn("SendDtmfTone",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Fm.prototype,"sendDtmfTone",1),v([wn("SetAudioUsage")],Fm.prototype,"setAudioUsageMode",1),v([wn("SetAudioMidcallConfig")],Fm.prototype,"setAudioMidcallConfig",1),v([wn("SetAudioMidcallConfigJon",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"setAudioMidcallConfigJson",1),v([wn("SetParticipantSpatialAudioPositions",{waitFor:"_ElectronSlimcoreReady",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"setParticipantSpatialAudioPositions",1),v([wn("BlindTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"callBlindTransfer",1),v([wn("SafeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"callSafeTransfer",1),v([wn("TransferToVoicemail",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"transferCallToVoicemail",1),v([wn("ConsultativeTransfer",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"callConsultativeTransfer",1),v([wn("ConsultativeTransferWithPickupCode",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Fm.prototype,"consultativeTransferWithPickupCode",1),v([wn("CallRedirect",{singular:!0,type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"callRedirect",1),v([wn("ParkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"park",1),v([wn("UnparkCall",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"unpark",1),v([wn("getTechnicalInformationJson",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]})],Fm.prototype,"getTechnicalInformationJson",1),v([wn("StartScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(3,Pn)],Fm.prototype,"startScreenSharing",1),v([wn("StopScreenSharing",{waitFor:"_UpdateMediaDescriptions",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(2,Pn)],Fm.prototype,"stopScreenSharing",1),v([wn("StartDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"startDataChannel",1),v([wn("StopDataChannel",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"stopDataChannel",1),v([wn("ShareSystemSounds",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"shareSystemSound",1),v([wn("Mute",{waitFor:"JoinPreheatedCall",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]},!0),S(0,Pn)],Fm.prototype,"mute",1),v([wn("Unmute",{waitFor:["JoinPreheatedCall"]},!0),S(0,Pn)],Fm.prototype,"unmute",1),v([wn("MuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(0,Pn)],Fm.prototype,"muteSpeaker",1),v([wn("UnmuteSpeaker",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(0,Pn)],Fm.prototype,"unmuteSpeaker",1),v([wn("MuteParticipants",void 0,!0),S(2,Pn)],Fm.prototype,"muteParticipants",1),v([wn("StartAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"startAudio",1),v([wn("StopAudio",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"stopAudio",1),v([wn("Assimilate"),S(3,Pn)],Fm.prototype,"assimilate",1),v([S(2,Pn)],Fm.prototype,"merge",1),v([wn("MergeParticipants"),S(1,An),S(3,Pn)],Fm.prototype,"mergeParticipants",1),v([wn("MergeWithPickupCode"),S(0,An),S(2,Pn)],Fm.prototype,"mergeWithPickupCode",1),v([wn("SetMaxVideoChannels")],Fm.prototype,"setMaxVideoChannels",1),v([wn("SetMaxVbssChannels")],Fm.prototype,"setMaxVbssChannels",1),v([wn("StopCall"),S(1,Pn),S(3,kn)],Fm.prototype,"stop",1),v([wn("PublishState"),S(1,An)],Fm.prototype,"publishState",1),v([wn("PublishState"),S(1,An)],Fm.prototype,"publishStatesForEveryone",1),v([wn("RemoveState"),S(1,An)],Fm.prototype,"removeState",1),v([wn("RemoveState"),S(1,An)],Fm.prototype,"removeStatesForEveryone",1),v([wn("UpdateMeetingSettings"),S(1,An)],Fm.prototype,"updateMeetingSettings",1),v([wn("UpdateMeetingGroups"),S(0,An)],Fm.prototype,"updateMeetingGroups",1),v([wn("UpdateMeetingLiveState"),S(0,An)],Fm.prototype,"updateMeetingLiveState",1),v([wn("UpdateMeetingStates"),S(1,An)],Fm.prototype,"updateMeetingStates",1),v([wn("UpdateParticipantInterpretationState"),S(0,An)],Fm.prototype,"updateParticipantInterpretationState",1),v([wn("UpdateParticipantsProperties")],Fm.prototype,"updateParticipantsProperties",1),v([wn("JoinMeetingGroup"),S(0,An)],Fm.prototype,"joinMeetingGroup",1),v([wn("LeaveMeetingGroup"),S(0,An)],Fm.prototype,"leaveMeetingGroup",1),v([wn("SendMessages"),S(0,An)],Fm.prototype,"sendMessages",1),v([wn("UpdateMonitorSession"),S(1,Pn)],Fm.prototype,"updateMonitorSession",1),v([wn("UpdateMeetingRole")],Fm.prototype,"updateMeetingRoles",1),v([wn("CreateContentSharingSession"),S(4,Pn)],Fm.prototype,"createContentSharingSession",1),v([wn("StopCallWithBeacon",{type:"Sync"}),S(0,Pn)],Fm.prototype,"stopWithBeacon",1),v([wn("Acknowledge",{type:"Chained",convertError:!0,idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(2,Pn)],Fm.prototype,"acknowledge",1),v([wn("Accept",{type:"Chained",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(1,Pn)],Fm.prototype,"accept",1),v([wn("Reject",{preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(0,Pn),S(1,kn)],Fm.prototype,"reject",1),v([wn("JoinCall",{type:"Chained",idempotencyLevel:"Error"}),S(1,Mn),S(2,Pn)],Fm.prototype,"join",1),v([wn("JoinPreheatedCall",{waitFor:"_CallStartOrJoinInitiated"})],Fm.prototype,"joinPreheatedCall",1),v([wn("StartCall",{type:"Chained",idempotencyLevel:"Error"}),S(0,Mn),S(1,Pn)],Fm.prototype,"start",1),v([wn("StartCallToVoiceMail",{type:"Chained",idempotencyLevel:"Error"}),S(1,Pn)],Fm.prototype,"startCallToVoicemail",1),v([wn("Subscribe",{type:"Chained",idempotencyLevel:"Error"}),S(2,Pn)],Fm.prototype,"joinCallWithoutCallModality",1),v([wn("StartWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Fm.prototype,"startWithMeetingData",1),v([wn("JoinWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Fm.prototype,"joinWithMeetingData",1),v([wn("SubscribeWithMeetingData",{type:"Chained",idempotencyLevel:"Error"})],Fm.prototype,"subscribeWithMeetingData",1),v([wn("StartCallWithNudge",{type:"Chained",idempotencyLevel:"Error"}),S(1,Mn),S(2,Pn)],Fm.prototype,"startCallWithNudge",1),v([wn("StartCallAndUnpark",{type:"Chained",idempotencyLevel:"Error",preconditionTags:["NOT_SUPPORTED_IN_STREAMING_MODE"]}),S(2,Mn),S(3,Pn)],Fm.prototype,"startAndUnpark",1),v([Rn("AdmitParticipant"),S(0,An),S(1,Pn)],Fm.prototype,"admitParticipant",1),v([wn("Admit")],Fm.prototype,"admit",1),v([Rn("CallMeBack"),S(0,An),S(2,Pn)],Fm.prototype,"callMeBack",1),v([S(0,An),S(2,Pn)],Fm.prototype,"addParticipant",1),v([Rn("AddParticipants"),S(0,An),S(2,Pn)],Fm.prototype,"addParticipants",1),v([S(0,An),S(2,Pn)],Fm.prototype,"addParticipantsImpl",1),v([Rn("NudgeParticipants"),S(0,An),S(3,Pn)],Fm.prototype,"nudgeParticipants",1),v([Rn("RemoveParticipant"),S(0,An),S(1,Pn)],Fm.prototype,"removeParticipant",1),v([wn("SearchParticipants"),S(1,An),S(1,Pn)],Fm.prototype,"searchParticipants",1),v([wn("GetAllParticipants"),S(1,An),S(1,Pn)],Fm.prototype,"getAllParticipants",1),v([wn("_PromotionToRealtime"),S(1,Pn)],Fm.prototype,"promoteToRealtime",1),v([S(0,Pn)],Fm.prototype,"turnOffLocalVideoPreview",1),v([wn("_StartPreviewVideo"),S(0,Pn)],Fm.prototype,"turnOnLocalVideoPreview",1),v([S(0,Pn)],Fm.prototype,"acquireLocalVideo",1),v([S(0,Pn)],Fm.prototype,"turnOnLocalVideoPreviewUsingRenderer",1),v([wn("_UpdateLocalMediaStatus",{type:"Chained"}),S(0,Pn)],Fm.prototype,"updateMediaStatus",1),v([S(0,Pn)],Fm.prototype,"calculateIsSomeoneStreaming",1),v([wn("_Reconnect")],Fm.prototype,"reconnect",1),v([wn("AddGroupModality"),S(1,Pn)],Fm.prototype,"addGroupModality",1),v([wn("AddBroadcastModality")],Fm.prototype,"addBroadcastModality",1);var Um=Fm;function Bm(e){const t=new TextDecoder("utf-8"),i=atob(e),n=Uint8Array.from(i,(e=>e.charCodeAt(0)));return t.decode(n)}var Vm=f(ce()),Hm=new RegExp("/callAgent/","i"),$m=class{constructor(e,t){this.signalingAgentProvider=e,this.callRegistry=t}handleMessage(e){if(!e.eventId){if(e.url.search(Hm)>-1){const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}if(e.eventId in Jn){this.callRegistry.logUploadNotification(e);const t=this.signalingAgentProvider.getSignalingAgent().handleIncomingNotification(e);return"number"==typeof t?{isHandled:!0,resultCode:t}:{isHandled:!0,resultCode:t.resultCode,responseBody:t.responseBody,responseHeaders:t.responseHeaders}}return{isHandled:!1}}},Gm=class{constructor(e,t,i){this.callRegistry=e,this.recentInvitations=[],this.logger=t.createChild("IncomingCallMessageHandler"),this.ecsProvider=i,this.useExperimentalDecode=this.ecsProvider?.getEcsConfig("SkypeCalling","useExperimentalDecode")}handleMessage(e){const t=this.handleIncomingCall(e);return t?{isHandled:t,resultCode:200}:{isHandled:t}}handleIncomingCall(e){const t=Te(),i=this.logger.createFnLogger("handleIncomingCall",t);if(this.isProxiableNotification(e))return this.callRegistry.proxyPushNotification(e),!0;if(!this.isIncomingCallMessage(e))return!1;let n;try{if(e?.body?.gp&&!Ue(e.body.gp))i.info("unencoded payload, skipping decoding."),n=e.body.gp;else{const t=zm(e,i,this.useExperimentalDecode);n=JSON.parse(t)}n.body=e.body}catch(e){return i.logFailure(`Error parsing notification payload: ${e}`),!1}const r=this.isCallTransferNotification(e)?this.buildTransferCallPayload(n):this.buildNGCCallPayload(n);if(!r)return!1;if(this.callRegistry.calls.some((e=>e.callId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the call registry, callId = ${r.convoCallId}, participantId = ${r.participantId}`),!1;const a=this.isCallReplacementNotification(e);if(i.log(`replacementCall=${a}`),!a&&this.recentInvitations.some((e=>e.convoCallId===r.convoCallId&&e.participantId===r.participantId)))return i.logFailure(`Duplicate call filtered because it was in the recent calls list, callId = ${r.convoCallId}, participantId = ${r.participantId}`),!1;5===this.recentInvitations.length&&this.recentInvitations.shift(),this.recentInvitations.push({convoCallId:r.convoCallId,participantId:r.participantId});let s=this.callRegistry.calls.find((e=>e.callId===r.convoCallId&&8===e.state));return s||(s=r.groupId?this.callRegistry.createCallWithGroupId(r.groupId,r.convoCallId,r.participantId,t):this.callRegistry.createCall(r.conversationId,r.convoCallId,r.participantId,void 0,t)),s.init({threadId:r.conversationId,messageId:r.messageId,mediaPeerType:2}),this.callRegistry.testEndpointMetadata?s.acknowledge(r,this.callRegistry.testEndpointMetadata,t):s.acknowledge(r,void 0,t),!0}isIncomingCallMessage(e){return Object.keys(qn).some((t=>qn[t]===e.eventId))?e.eventId!==qn.INCOMING_TFL_TFW_CALL||this.ecsProvider?.getEcsConfig("SkypeCalling","enableTFWTFLOneToOneCall"):this.isCallTransferNotification(e)}isCallTransferNotification(e){return e.callNotification&&("transfer"===e.callNotification.callType||"replaces"===e.callNotification.callType)}isCallReplacementNotification(e){return e.callNotification&&"replaces"===e.callNotification.callType}isProxiableNotification(e){return Object.keys(Kn).some((t=>Kn[t]===e.eventId))}buildTransferCallPayload(e){const t={body:e.body,callerId:e.callNotification.from.id,groupId:null,conversationId:null,convoCallId:e.debugContent.callId,isMultiParty:e.conversationInvitation?.isMultiParty,fromMixer:e.callNotification.fromMixer,ngcCall:!0,participantId:e.callNotification.to.participantId,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,consultativeCallId:e.callNotification.consultativeCallId,messageId:null,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0};return this.logger.info("Incoming transfer paylod",t),t}buildNGCCallPayload(e){if(!e.callNotification)return this.logger.error("Missing callNotification in parsed incoming NGC call payload"),null;const t={groupId:e.groupContext?.id,conversationId:e.groupChat?.threadId,messageId:e.groupChat?.messageId,callerId:e.callNotification.from.id,isMultiParty:e.conversationInvitation.isMultiParty,fromMixer:e.callNotification.fromMixer,convoCallId:e.debugContent.callId,participantId:e.debugContent.participantId,ngcCall:!0,body:e.body,transferorId:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.id,transferorType:e.callNotification.transferor&&e.callNotification.transferor.transferorType,transferorDisplayName:e.callNotification.transferor&&e.callNotification.transferor.details&&e.callNotification.transferor.details.displayName,callType:e.callNotification.callType,callQueueInfo:e.callNotification.applicationContent,videoCall:void 0,launchTime:void 0,pushReceivedTime:void 0,registrationId:void 0,fromApplicationType:e.callNotification.fromApplicationType};return this.logger.info("Incoming NGC payload",t),t}},jm=class extends We{constructor(e,t,i,n,r,a=null,s,o){super(),this.trouterService=e,this.signalingAgentProvider=t,this.mediaAgent=i,this.callingLogger=n,this.telemetryLoggers=r,this.ecsProvider=a,this.skypeIdentity=s,this.oneDsTelemetryLoggers=o,this.calls=[],this.isDisposing=!1,this._disposedPromise=Si(),this.testEndpointMetadata=null,this._disconnectingPromiseDefers=new Map,this.skypeIdentity&&(this.identity=this.skypeIdentity.id),this.callSubscriptionsMap=new Map,this.logger=new Qt(this.callingLogger).createChild(`CallRegistry/${Te()}`),this.registryTelemetry=new hn(this.logger,(new Date).getTime()),this._callOperationHandler||(this._callOperationHandler=new Hn(this.logger,this.registryTelemetry,{},(e=>{this._publishTelemetry(e)})));const l=this.mediaAgent.getConfig().disconnectOnPageHide;this._windowUninitEvent=l?"pagehide":"beforeunload",this.signalingAgentProvider.getSignalingAgent().setTokenRequiredCallBack(this.onTokenRequired.bind(this)),this._createNewCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","createNewCallInDisconnectedState"),this._invokeDeleteCallInDisconnectedState=this.ecsProvider.getEcsConfig("SkypeCalling","invokeDeleteCallInDisconnectedState"),this._useExperimentalDecode=this.ecsProvider.getEcsConfig("SkypeCalling","useExperimentalDecode")}init(e,t,i=Te()){return this.logger.createFnLogger("init",i).info("init"),this.login(e)}uninit(){return this.logout()}login(e,t=Te()){return this.logger.createFnLogger("login",t).info("login"),this.skypeIdentity=e,this.identity=this.skypeIdentity.id,this.initialize(t)}initialize(e=Te(),t){const i=this.logger.createFnLogger("initialize",e),n=t&&t.applicationType?t.applicationType:"null";i.info(`initialize with applicationType: ${n}`),this.accountConfiguration=t,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(t),this.incomingCallMessageHandler=new Gm(this,this.logger,this.ecsProvider),this.trouterService.registerMessageHandler(new $m(this.signalingAgentProvider,this)),this.trouterService.registerMessageHandler(this.incomingCallMessageHandler),i.info("Call registry init, endpointMetadata",this.testEndpointMetadata);try{this.windowUninitListener=()=>{this._disregardWindowUninitEvents||this.stopCallsWithBeacon()},window.addEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){i.logFailure(`Not adding beforeunload listener: ${e}`)}return Promise.resolve(void 0)}logout(e=Te()){const t=this.logger.createFnLogger("logout",e);t.info("logout");try{this.trouterService.clearMessageHandlers(),window.removeEventListener(this._windowUninitEvent,this.windowUninitListener)}catch(e){t.info(`Not removing beforeunload listener: ${e}`)}return Promise.resolve(void 0)}_publishTelemetry(e){if(!this.telemetryLoggers?.signaling)return;this.registryTelemetry.setSkypeId(this.identity);try{const e=this.signalingAgentProvider.getSignalingAgent();this.registryTelemetry.setEndpointId(e.endpointId)}catch(e){this.logger.warn("Could not get end point ID from signaling agent for call registry telemetry.")}this.accountConfiguration&&(this.registryTelemetry.setAcsResourceId(this.accountConfiguration.acsResourceId),this.registryTelemetry.setApplicationType(this.accountConfiguration.applicationType),this.registryTelemetry.setPartition(this.accountConfiguration.partition),this.registryTelemetry.setRegion(this.accountConfiguration.region),this.registryTelemetry.setRing(this.accountConfiguration.ring),this.registryTelemetry.setTenantId(this.accountConfiguration.tenantId),this.registryTelemetry.setUserHexCID(this.accountConfiguration.userHexCID),this.registryTelemetry.setClientType(this.accountConfiguration.clientType));const t=nn;this.telemetryLoggers.signaling.sendEvent({eventName:t,props:this.registryTelemetry.getEvent(null,e)})}async dispose(e=Te()){const t=this.logger.createFnLogger("dispose",e);if(t.info("dispose"),this.isDisposing)return t.warn("call registry is already in disposing stage!"),this._disposedPromise.promise;this.isDisposing=!0;const i=()=>{this.calls=[],this.event("disposed").raise(),super.dispose(),this._disposedPromise.resolve()},n=this.calls.map((e=>e.stop())),r=()=>this.logout();return this.clearCallSubscription(),this.signalingAgentProvider.getSignalingAgent().resetAuthTokenManager(),Promise.all(n).then(r,r).then(i,i),this._disposedPromise.promise}get disposePromise(){return this._disposedPromise.promise}createCallAsync(e){const t=this.logger.createFnLogger("createCallAsync",e.causeId),i=`callId:${e.callId}, localParticipantId: ${Ae(e.localParticipantId)},\n            causeId:${e.causeId}, type:${e.type}, `;switch(e.type){case"MeetingData":i.concat(`meetingUrl:${!!e.meetingData?.meetingUrl}, meetingCode:${!!e.meetingData?.meetingCode}`);break;case"GroupId":i.concat(`groupId:${Ae(e.groupId)}`);break;case"ThreadId":i.concat(`threadId:${Me(e.threadId)}, messageId:${e.messageId}`);break;default:throw new Error("Invalid type in passing parameter.")}t.info(i);const n=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers,r=this._getCurrentCall(e,t);if(r){if(6===r.state){const e=Si();return this._disconnectingPromiseDefers.set(r.callId,e),e.promise}return Promise.resolve(r)}return Promise.resolve(this._createNewCall(e,n,t))}createCallWithMeetingData(e,t,i,n){const r=this.logger.createFnLogger("createCallWithMeetingData",n);if(r.info(`meetingData:${Le(e)}, callId:${t}, localParticipantId: ${Ae(i)}`),!e)return r.info("meetingData cannot be null"),null;const a=this._generateCreateCallOptions(n,t,i,null,null,null,e),s=this._getCurrentCall(a,r);if(s)return s;const o=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(a,o,r)}createCall(e,t,i,n,r=Te()){return this._createCall(e,t,i,n,r)}createCallWithGroupId(e,t,i,n){return this._createCall("",t,i,void 0,n,e)}_createNewCall(e,t,i){let n=null,r=null,a=null,s=null;switch(e.type){case"MeetingData":s=e.meetingData;break;case"GroupId":n=e.groupId;break;case"ThreadId":r=e.threadId,a=e.messageId}const o=new Um(this.signalingAgentProvider.getSignalingAgent(),this.mediaAgent,new Qt(this.callingLogger),t,this.skypeIdentity,n,r,e.callId,e.localParticipantId,this.ecsProvider,this.trouterService,this.accountConfiguration,a,this.locationInfoContent,this.networkInfoContent,s,this.areaContent);o.on("callStateChanged",(async()=>{if(7===o.state&&this._createNewCallInDisconnectedState){const n=this._disconnectingPromiseDefers.get(o.callId);n&&(this._disconnectingPromiseDefers.delete(o.callId),n.resolve(this._createNewCall(e,t,i))),this._invokeDeleteCallInDisconnectedState&&setTimeout((()=>{this.deleteCall(o)}),0)}})),this.calls.push(o),this.event("callAdded").raise(o),this.raiseChanged(),i.info(`creating new call, ${o.callId}, ${Le(s)}, ${Le(o.meetingData)}`);const l=o.on("replacementRequested",(e=>{this.incomingCallMessageHandler.handleMessage(e)}));return this.addCallSubscriptionToMap(o,l),o}_getCurrentCall(e,t){let i=null;return"MeetingData"===e.type&&(i=this.getCallUsingMeetingData(e.meetingData,e.callId,e.localParticipantId,void 0,void 0,e.causeId),i)?(t.info("Call Registry has an entry for this call's meeting data"),i):(i=this.getCall(e.callId,e.localParticipantId,e.causeId),i?(t.info("Call Registry has an entry for this callId, participantId"),i):"ThreadId"===e.type&&(i=this.getCallUsingThreadIdMessageId(e.threadId,e.callId,e.messageId,e.causeId),i)?(t.info("Call Registry has an entry for this threadId, messageId"),i):"GroupId"===e.type&&(i=this.calls.find((t=>t.groupId===e.groupId)),i)?(t.info("Call Registry has an entry for this groupId"),i):i)}_generateCreateCallOptions(e,t,i,n,r,a,s){let o=null;return o=n?{type:"GroupId",callId:t,localParticipantId:i,causeId:e,groupId:n}:r?{type:"ThreadId",callId:t,localParticipantId:i,causeId:e,threadId:r,messageId:a}:{type:"MeetingData",callId:t,localParticipantId:i,causeId:e,meetingData:s},o}_createCall(e,t,i,n,r=Te(),a){const s=this.logger.createFnLogger("createCall",r);s.info(`threadId:${Me(e)}, callId:${t}, localParticipantId: ${Ae(i)}, messageId:${n}, groupId:${Ae(a)}`);const o=this._generateCreateCallOptions(r,t,i,a,e,n,null),l=this._getCurrentCall(o,s);if(l)return l;const c=this.mediaAgent?.getConfig().useOneDsLogger?this.oneDsTelemetryLoggers:this.telemetryLoggers;return this._createNewCall(o,c,s)}getCall(e,t,i=Te()){const n=this.logger.createFnLogger(`getCall[callId=${e}][participantId=${Ae(t)}]`,i);if(!e)return n.logFailure("callId is undefined"),null;const r=this.calls.find((t=>t.callId===e));return r&&n.info("Call Registry already has an entry for this call"),r}async deleteCallAsync(e){return vi((()=>this.deleteCall(e)))}deleteCall(e){const t=this.calls.indexOf(e);return-1!==t&&(this.callSubscriptionsMap.get(e).forEach((e=>{e.dispose()})),this.callSubscriptionsMap.delete(e),this.calls.splice(t,1),this.event("callRemoved").raise(e),this.raiseChanged(),!0)}async setConfiguration(e){this.accountConfiguration=e,this.accountConfiguration&&this.event("accountConfigurationReceived").raise(this.accountConfiguration),this.signalingAgentProvider.getSignalingAgent().update(e)}updateDisplayName(e){return this.skypeIdentity.displayName=e,this.calls.forEach((t=>{t.updateDisplayName(e)})),Promise.resolve()}fireIntent(e,t){return Promise.resolve()}getCallState(e,t){return Promise.reject("Not implemented")}getSetup(){}getEcsConfig(){return Promise.reject()}updateSkypeToken(e){this.logger.debug("CallRegistry.updateSkypeToken() called but not supported in the current set up.")}updateToken(e,t,i,n,r){this.logger.info(`[updateToken], causeId = ${n} tokenType = ${t.tokenType}, factorsJson = ${e}, tokenExpiredTime = ${r}`);try{return this.signalingAgentProvider.getSignalingAgent().updateToken(e,t,i,n,r),Promise.resolve({code:0})}catch(t){return this.logger.info(`Failed to update token with ${e}, error is ${t}`),Promise.reject(Un(`Failed to update token with ${e}, error is ${t}`))}}onTokenRequired(e){const{requestMetadataJson:t,factorsJson:i,tokenType:n,invalidToken:r}=e;this.logger.info(`[onTokenRequired], tokenType ${n}, factorsJson ${i}, requestMetadataJson ${JSON.stringify(t)}`),this.event("tokenRequired").raise(i,n,t,r)}debugInformation(e){const t=e?`CallInformation\n * CallId=${e.callId}`:void 0;return Promise.resolve(t)}setLocationInfo(e,t,i=Te()){if(this.logger.info(`setLocationInfo, ${i}, infoType:${e}, contentJson ${t?"is set":"is undefined"}`),t)try{JSON.parse(t)}catch(e){return Promise.reject(`invalid contentJson: ${e}`)}return this.locationInfoType=e,1===this.locationInfoType&&(this.locationInfoContent=t,this.logger.info(`locationInfoContent set to ${this.locationInfoContent}`)),2===this.locationInfoType&&(this.networkInfoContent=t,this.logger.info(`networkInfoContent set to ${this.networkInfoContent}`)),3===this.locationInfoType&&(this.areaContent=t,this.logger.info(`areaContent set to ${this.areaContent}`)),this.event("locationInfoSet").raise(e,t),Promise.resolve()}createDownloader(){return null}async getUnassembledLocalRecordingSessions(e=Te()){return Promise.reject("Not implemented")}extendBrbFeedback(e,t){return Promise.reject("Not implemented")}proxyPushNotification(e){this.logger.info(`Proxying push notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:zm(e,this.logger,this._useExperimentalDecode)};this.event("proxiedPushNotification").raise(t)}catch(e){this.logger.error(`Error proxying push notification: ${e}`)}}logUploadNotification(e){this.logger.info(`Log upload notification with event ID ${e.eventId}`);try{const t={eventId:e.eventId,payload:zm(e,this.logger,this._useExperimentalDecode)};this.event("logUploadNotification").raise(t)}catch(e){this.logger.error(`Error raising log upload notification: ${e}`)}}sendPush(e,t,i,n){const r={id:e},a=[];return t.forEach((e=>{a.push({id:e})})),this.signalingAgentProvider.getSignalingAgent().sendPushAsync(r,a,i,n)}enableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!1}disableWindowUninitEventHandler(){this._disregardWindowUninitEvents=!0}getCallUsingThreadIdMessageId(e,t,i,n){this.logger.info(`[getCallUsingThreadIdMessageId][${n}] threadID: ${Me(e)} callId: ${t} messageId: ${i}`);let r=null;return e&&(r=this.calls.find((n=>n.threadId===e&&(t&&n.callId===t||i&&n.messageId===i))),r)?(this.logger.logFailure(`[getCallUsingThreadIdMessageId][${n}]Call Registry already has an entry for threadId: ${Me(r.threadId)}, callId: ${r.callId}, messageId: ${r.messageId}`),r):r}getCallUsingMeetingData(e,t,i,n,r,a=Te()){const s=this.logger.createFnLogger("getCallUsingMeetingData",a);if(s.info(`[callId=${t}][participantId=${Ae(i)}] meetingData: ${Le(e)} threadId: ${Me(n)} messageId: ${r}`),!t)return s.logFailure("callId is undefined"),null;let o;for(const i of this.calls){if(i.callId===t){o=i;break}if(vn(i.meetingData,e,a,this.logger)){o=i;break}}return o}stopCallsWithBeacon(){for(const e of this.calls)e.stopWithBeacon()}addCallSubscriptionToMap(e,t){this.callSubscriptionsMap.set(e,(this.callSubscriptionsMap.get(e)||[]).concat(t))}clearCallSubscription(){this.callSubscriptionsMap.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.callSubscriptionsMap.clear()}};function zm(e,t,i=!1){const n=t.createFnLogger("decodeNotificationPayload");n.info(`useExperimentalDecode:${i}`);const r=i?Bm:atob;let a="{}";if(e?.body?.gp)n.info("using notification.body.gp"),a=r(e.body.gp);else if(e?.body?.cp){n.info("using notification.body.cp");const t=atob(e.body.cp);a=Vm.inflate(t,{to:"string"})}return a}v([wn("Initialize",{enableInstantTelemetry:!0})],jm.prototype,"initialize",1),v([wn("Logout",{enableInstantTelemetry:!0})],jm.prototype,"logout",1);var Wm=g,qm=class{constructor(e){this.deviceManager=e}get childDeviceManagers(){return this.deviceManager.getRegisteredDevices()}createPreview(e,t,i,n){return this.executeOnVirtualDeviceManager((n=>i(e,t,n)),n)}getRawDeviceMediaStream(e,t,i){return this.executeOnVirtualDeviceManager((i=>i.getRawDeviceMediaStream(e,t)),i)}setDeviceEffectsAsync(e,t){return this.executeOnVirtualDeviceManager((e=>e.setVideoEffects(t)),e)}setRawMediaStream(e,t,i){this.executeOnVirtualDeviceManager((i=>i.setRawMediaStream(e,t)),i)}unsetRawMediaStream(e,t){this.executeOnVirtualDeviceManager((t=>t.unsetRawMediaStream(e)),t)}getVirtualDevice(e){return this.childDeviceManagers.find((t=>t.id===e))}executeOnVirtualDeviceManager(e,t){return this.getVirtualDevice(t).getDeviceManagers().map((t=>e(t)))}},Km=class e extends We{constructor(e){super(),this._deviceManager=e,this.virtualDeviceAdapter=new qm(this._deviceManager),e.on("onDevicesChanged",(e=>{const t=this._deviceManager.getDeviceDescriptions(e),i=this._mapDevices(t);this._raiseDevicesChanged(i)})),e.on("onSelectedDevicesChanged",(e=>this._raiseDevicesChanged())),e.on("onPermissionStateChanged",(()=>this.event("onPermissionStateChanged").raise())),e.on("onVideoEffectsEvent",((e,t)=>this.event("videoEffectsEvent").raise(e,t))),e.on("onVideoEffectApplied",(()=>this.event("videoEffectApplied").raise()))}get isAudioOutputSelectionSupported(){return this._deviceManager.isAudioOutputSelectionSupported}getPermissionState(e){return"camera"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("camera")):"microphone"===e?this.getPermissionStateHelper(this._deviceManager.getPermissionState("microphone")):"unknown"}askDevicePermission(e){return this._deviceManager.askDevicePermission?this._deviceManager.askDevicePermission(e):Promise.resolve({audio:!0,video:!0})}enumerateDevicesAsync(){return this._deviceManager.enumerateDevicesAsync().then((e=>this._mapDevices(e)))}getPreferredCamera(){throw new Error("Not implemented")}selectDevices(e){if(Object.keys(e).some((e=>this.isVirtualDevice(e))))throw new Error("Virtual Device selection on DM is not supported");const t=(0,Wm.assign)({},this._deviceManager.getSelectedDevices(),e);this._deviceManager.selectDevices(t)}selectDevicesAsync(e){return vi((()=>this.selectDevices(e)))}getSelectedDevices(){return this._deviceManager.getSelectedDevices()}getSelectedDevicesAsync(){return vi((()=>this.getSelectedDevices()))}getDeviceNameAsync(e){return this._deviceManager.getDeviceNameAsync(e)}getSpeakerDeviceDomIdAsync(e,t){return this._deviceManager.getSpeakerDeviceDomIdAsync(e)}async setDeviceEffectsAsync(e,t){if(!this.isVirtualDevice(e))return this._deviceManager.setVideoEffects(t);Promise.all(this.virtualDeviceAdapter.setDeviceEffectsAsync(e,t))}getDeviceEffectsCapabilityAsync(e,t){return this._deviceManager.effectsManager.getEffectsCapability("Video")}setBackgroundImageAsync(e,t,i){return this._deviceManager.effectsManager.configure("Video",{imagePath:t,headers:i})}getImagePropertyAsync(e){return Promise.reject(new Error("Not implemented"))}getMicrophoneGeometryArrayInfoAsync(e){return Promise.reject(new Error("Not implemented"))}transformImageAsync(e,t,i,n){return Promise.reject(new Error("Not implemented"))}setAudioProcessingFlags(e){return this._deviceManager.setAudioProcessingFlags(e)}sendMessageDeviceVideoEffectsAsync(e,t){return Promise.reject(new Error("Not implemented"))}sendMessageDeviceVideoExtensibilityAsync(e,t){return Promise.reject(new Error("Not implemented"))}setVideoCaptureConfigAsync(e,t){return Promise.reject(new Error("Not implemented"))}captureVideoFrameWithoutEffectsAsync(e,t,i){return Promise.reject(new Error("Not implemented"))}getSpeakerVolume(){return Promise.reject(new Error("Not implemented"))}getSpeakerSystemVolume(){return Promise.reject(new Error("Not implemented"))}setSpeakerVolume(e){return Promise.reject(new Error("Not implemented"))}setSpeakerSystemVolume(e){return Promise.reject(new Error("Not implemented"))}unmuteMicrophone(){return Promise.reject(new Error("Not implemented"))}unmuteSpeaker(){return Promise.reject(new Error("Not implemented"))}getNrgLevelsForDeviceTuner(e){return Promise.reject(new Error("Not implemented"))}setAudioEffectsAsync(e,t){return this._deviceManager.setAudioEffects(t)}getAudioFeatureCapability(e){return this._deviceManager.effectsManager.getEffectsCapability("Audio")}getMicrophoneVolume(){return Promise.reject(new Error("Not implemented"))}setMicrophoneVolume(e){return Promise.reject(new Error("Not implemented"))}setDeviceTelemetryData(e,t,i,n=0){return Promise.reject(new Error("Not implemented"))}getSourceFormats(e){return Promise.reject(new Error("Not implemented"))}enableShellSharing(){return Promise.reject(new Error("Not implemented"))}disableShellSharing(){return Promise.reject(new Error("Not implemeted"))}enableParticipantCameras(){return Promise.reject(new Error("Not implemeted"))}registerDerivedSource(e,t){return Promise.reject(new Error("Not implemeted"))}unregisterDerivedSource(e){return Promise.reject(new Error("Not implemeted"))}async createPreview(e,t,i){return"camera"===t.kind&&this.isVirtualDevice(t.device)?this.virtualDeviceAdapter.createPreview(e,i,this.getRenderer,t.device)[0]:"camera"===t.kind&&(0,Wm.isUndefined)(t.device)?this.createPreviewRenderer(e,i):Promise.reject(new Error("Not yet supported"))}async createPreviewRenderer(e,t){return this.getRenderer(e,t,this._deviceManager)}createScreenSharingPreviewRenderer(e,t){return Promise.reject(new Error("Not yet supported"))}getRawDeviceMediaStream(e,t,i){const n=Kh(e);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.getRawDeviceMediaStream(n,t,i)[0]:this._deviceManager.getRawDeviceMediaStream(n,t)}setRawMediaStream(e,t,i){const n=Kh(t);return this.isVirtualDevice(i)?this.virtualDeviceAdapter.setRawMediaStream(e,n,i):this._deviceManager.setRawMediaStream(e,n)}unsetRawMediaStream(e,t){const i=Kh(e);return this.isVirtualDevice(t)?this.virtualDeviceAdapter.unsetRawMediaStream(i,t):this._deviceManager.unsetRawMediaStream(i)}createAudioRenderer(){return this._deviceManager.createAudioRenderer()}startAudioLoopbackDevice(e){return Promise.reject(new Error("Not implemented"))}async dispose(e){return this._deviceManager.dispose(e)}async registerCompositeVideoDevice(e,t,i){return this._deviceManager.registerVirtualDevice(e,t,i)}async unregisterCompositeVideoDevice(e){return this._deviceManager.unregisterVirtualDevice(e)}async createAudioPlayer(){return Promise.reject(new Error("Not implemented"))}_raiseDevicesChanged(e){(e?Promise.resolve(e):this.enumerateDevicesAsync()).then((e=>{this.raiseChanged(),this.event("devicesChanged").raise(e)}))}getPermissionStateHelper(e){switch(e){case"granted":return"granted";case"denied":return"denied";case"prompt":return"prompt";default:return"unknown"}}_mapDevices(e){return e?.map((e=>this._mapDeviceDesc(e)))}_mapDeviceDesc(t){const i=e._mapDeviceType(t.kind);return 6===i?{id:t.id,label:t.label,kind:i,position:0,defaultVideoId:t.id,devicesIds:[]}:1===i?{id:t.id,browserId:t.browserId,label:t.label,kind:i,position:e._mapCameraPosition(t.position)}:4===i?{id:null,browserId:null,label:t.label,kind:i,formFactor:t.formFactor,isPcInternalDevice:t.isPcInternalDevice,microphoneId:t.microphoneId,speakerId:t.speakerId}:{id:t.id,browserId:"default_output_device"===t.browserId?"default":t.browserId,label:t.label,kind:i,isSystemDefault:!!t.isSystemDefault}}static _mapDeviceType(e){switch(e){case"camera":return 1;case"microphone":return 2;case"speaker":return 3;case"compositeAudio":return 4;case"virtualDevice":return 6;default:throw new Error(`Invalid device type '${e}'`)}}static _mapCameraPosition(e){switch(e){case"front":return 1;case"back":return 2;case"external":return 3;default:return 0}}isVirtualDevice(e){return e&&this._deviceManager.getRegisteredDevices().some((t=>t.id===e))}async getRenderer(e,t,i){const n=new Ap(e,i);try{await n.startVideoAsync(),t&&(n.setScalingMode(t.scalingMode),n.setVideoMirroring(!t.ignoreMirroring))}catch(e){throw n.dispose(),e}return n}},Jm=p,Ym=p,Qm=class extends Ym.AbstractLogAppender{constructor(e){super(new Ym.StandardLogFormatter(Ym.SLF_Flags.Component)),this._logger=e}log(e,t,i,n){if(!this._logger)return;const r=e.level<=Ym.LogLevel.Debug4?this._logger.debug:e.level<=Ym.LogLevel.Debug2?this._logger.log:e.level<=Ym.LogLevel.Debug1?this._logger.info:e.level<=Ym.LogLevel.Warning?this._logger.warn:this._logger.error;r&&r.apply(this._logger,[this.formatter().format(e,t,i,n)])}},Zm=p,Xm=f(me()),ef=["CorrelationId","agent_environment_id","UserInfo_TenantId","participant_id","endpoint_id","mediaLegId","metrics_ConfigIds","ts_calling_version","uiVersion"],tf={video:[...ef,"Extensions_WebRTCStats_ssrc_video_recv_framesDecoded","Extensions_WebRTCStats_ssrc_video_recv_packetsReceived","Extensions_WebRTCStats_ssrc_video_recv_ssrc","Extensions_WebRTCStats_ssrc_video_recv_bytesReceived","Extensions_WebRTCStats_ssrc_video_recv_googFrameRateDecoded","Extensions_Video_SubscriptionEvents","Extensions_Video_recv_ResolutionDurations","Extensions_Video_recv_StreamsMax","Extensions_Video_recv_frameRateAvg","Extensions_Video_recv_DurationSeconds","Extensions_Video_recv_FreezeHistogram","Extensions_Video_recv_FreezeTimestamps","Extensions_WebRTCStats_ssrc_video_recv_keyFramesDecoded","Extensions_Video_recv_TotalFreezeDurationMs","Extensions_Video_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"],sharing:[...ef,"Extensions_WebRTCStats_ssrc_sharing_recv_framesDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_packetsReceived","Extensions_WebRTCStats_ssrc_sharing_recv_ssrc","Extensions_WebRTCStats_ssrc_sharing_recv_bytesReceived","Extensions_WebRTCStats_ssrc_sharing_recv_googFrameRateDecoded","Extensions_WebRTCStats_ssrc_sharing_recv_keyFramesDecoded","Extensions_Sharing_SubscriptionEvents","Extensions_Sharing_recv_ResolutionDurations","Extensions_Sharing_recv_StreamsMax","Extensions_Sharing_recv_frameRateAvg","Extensions_Sharing_recv_DurationSeconds","Extensions_Sharing_recv_FreezeHistogram","Extensions_Sharing_recv_FreezeTimestamps","Extensions_Sharing_recv_TotalFreezeDurationMs","Extensions_Sharing_recv_packetsLostRateMax","metrics_ReconnectAttempts","metrics_ReconnectConnectedCount","metrics_RetargetCompletedCount","metrics_UFDs","Payload"]},nf=class extends We{constructor(){super(...arguments),this.stabilizationTimeInAvg=2e4}send(e){e&&setTimeout((()=>{this.event("sendMidCallTelemetry").raise(tf[e])}),this.stabilizationTimeInAvg)}},rf=class extends We{constructor(e,t){super(),this._telemetryService=e,this._ecsProvider=t,this._ecsProvider.on("OnECSChanged",(()=>Zm.RootToolsManager.OnEcsChange()))}fetchEcsConfig(e,t){return Xm.Resolved().then((()=>this._ecsProvider.getEcsConfig(e,t)))}sendTelemetry(e,t){this._telemetryService.getGenericTelemetryLogger&&e?this._telemetryService.getGenericTelemetryLogger(e).sendEvent({eventName:"rt_log",props:t}):this._telemetryService.sendEvents([{eventName:"rt_log",props:t}])}sendMidCallTelemetry(e){Object.keys(tf).includes(e)&&this.event("onMidCallTelemetry").raise(e)}};var af=g,sf=class e{constructor(t){this._prefix=t,this._children=[],this._useConsoleLogger=!1,this.createChild=(t,i)=>{const n="function"==typeof t?"":t,r=new e((this._prefix||"")+n);return this._children.push(r),this._useConsoleLogger&&r.useConsoleLogger(),r},this.createFnLogger=(t,i,...n)=>{const r=`[${i}][${t}]`,a=new e((this._prefix||"")+r);return this._children.push(a),this._useConsoleLogger&&a.useConsoleLogger(),a}}logInfo(){}logFailure(){}logSuccess(){}log(...e){}debug(...e){}info(...e){}warn(...e){}error(...e){}useConsoleLogger(){this._useConsoleLogger=!0;const e=(...e)=>{console.info(this._prefix||"",...e)};this.log=e,this.debug=e,this.info=e,this.warn=e,this.error=e,(0,af.each)(this._children,(e=>e.useConsoleLogger()))}},of=class{constructor(e){this.configProvider=e,this.window=Ug.window,this.updateCapabilityOverrides(),this.configProviderSub=e.on("configUpdated",(()=>this.updateCapabilityOverrides()))}get audio(){return this.getCapability("audio")}get video(){return this.getCapability("video")}get screensharing(){return this.getCapability("screensharing")}get retargeting(){return this.getCapability("retargeting")}dispose(){this.configProviderSub&&this.configProviderSub.dispose()}updateCapabilityOverrides(){let e;this.configProvider.config.capabilities&&(e=this.configProvider.config.capabilities),this.overrides=e||{}}hasMediaCapture(){return!!this.window.navigator.getUserMedia}getCapability(e){return void 0!==this.overrides[e]?!!this.overrides[e]:this.hasMediaCapture()&&this.hasWebRtc()}hasWebRtc(){return void 0!==this.window.RTCPeerConnection}},lf=class e extends qe{constructor(e,t){super(e),this.logger=e,this.configProvider=t,this.eventStates=new Map,this.swMuted=!1,this.logger.safe.info("Initialized")}signalEvent(e,t,i="Audio",n=!0,r=Te(),a,s){const o={type:e,value:t,isLocalSource:n,mediaType:i,deviceManagerId:a,diagnosticData:s},l=this.getEventKey(o),c=this.eventStates.get(l);(!c||c.value!==t||this.configProvider.config.alwaysRaiseBadDeviceEvents&&"Good"!==t)&&(c||"Good"!==t)&&(this.eventStates.set(l,o),this.shouldRaiseEvent(o,c)&&(this.logger.safe.info(`[${r}] Raising UFD ${e} for ${i}: ${t}`),this.event("onQualityChanged").raise(o)))}signalDeviceEvent(t,i,n,r){const a=e.getQualityEventType(t,n,this.configProvider);a?this.signalEvent(a,i,n,void 0,Te(),r):this.logger.warn(`Unknown device quality event type: ${t}`)}raisePendingWhitelistingUFD(){this.lastWhitelistingUFD&&(this.logger.safe.debug(`Raising whitelisting UFD ${this.lastWhitelistingUFD.type}: ${this.lastWhitelistingUFD.value}`),this.event("onQualityChanged").raise(this.lastWhitelistingUFD),this.cancelPendingWhitelistingUFD())}cancelPendingWhitelistingUFD(){if(this.lastWhitelistingUFD){const e=this.getEventKey(this.lastWhitelistingUFD);this.eventStates.delete(e)}this.lastWhitelistingUFD=void 0}setSwMute(e){if(this.swMuted=e,e){const e=this.eventStates.get(this.getEventKey({type:"DeviceSpeakWhileMuted",mediaType:"Audio"}));e&&"Good"!==e.value&&this.event("onQualityChanged").raise(e)}}applyCurrentState(e){this.cancelPendingWhitelistingUFD();let t=0;for(const i of this.eventStates.values())"Good"!==i.value&&(e(i),t++);t>0&&this.logger.safe.info(`Applied ${t} UFDs`)}reset(){this.logger.safe.info("Resetting UFD states");for(const[t,i]of this.eventStates.entries())e.persistent.has(i.type)||this.eventStates.delete(t);this.lastWhitelistingUFD=void 0,this.swMuted=!1}getEventKey(e){return`${e.type}:${e.mediaType}`}shouldRaiseEvent(t,i){return"NetworkRelaysNotReachable"===t.type?(this.lastWhitelistingUFD=t,!1):!(!("DeviceSpeakWhileMuted"!==t.type||this.swMuted||"Good"===t.value&&"Good"!==i?.value)||"NetworkRecvQuality"===t.type&&!this.configProvider.config.webrtcStatNetworkDetectionEnabled||this.configProvider.config.alwaysRaiseBadDeviceEvents&&!e.deviceQualityEvents.has(t.type)&&t.value===i?.value)}static getQualityEventType(e,t,i){switch(e){case 0:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartFailed";case 1:return"Audio"===t?"DeviceCaptureNotFunctioning":"VideoCapturerDeviceStartTimedOut";case 2:return"DeviceCaptureMute";case 3:switch(t){case"ScreenShare":return"ScreenshareRecordingDisabled";case"Audio":return i.config.enableSignalingAudioPermissionDeniedUFD?"AudioCapturePermissionDenied":"DeviceCaptureNotMuteButSilent";case"Video":return"VideoCapturePermissionDenied";default:return}default:return}}};lf.persistent=new Set(["ZeroCaptureDevicesEnumerated","ZeroRenderDevicesEnumerated"]),lf.deviceQualityEvents=new Set(["DeviceCaptureNotFunctioning","VideoCapturerDeviceStartFailed","DeviceCaptureNotFunctioning","VideoCapturerDeviceStartTimedOut","DeviceCaptureMute","ScreenshareRecordingDisabled","DeviceCaptureNotMuteButSilent","VideoCapturePermissionDenied"]);var cf=lf,df=g,uf=g,hf=g,pf={maxOutgoingResolution:({settings:e})=>vf(e),maxParticipantResolutions:({settings:e})=>ff(e),maxIncomingStreams:({settings:e})=>yf(e),maxSimulcastLayers:({settings:e})=>Cf(e),outgoingVideoLimit:({settings:e,constraints:t})=>Sf(e,t)},gf=(e,t,i)=>(e.info(`Converting settings to constraints and mapping, [requestedConstraints=${JSON.stringify(i)}], [settings=${JSON.stringify(t)}]`),mf((0,hf.cloneDeep)(i),(0,hf.cloneDeep)(t))),mf=(e,t)=>Object.keys(e).reduce(((i,n)=>{const r=pf[n]?pf[n]({constraints:e,settings:t}):void 0;return r&&(i[n]=r),i}),{}),ff=e=>e.multiviewResolutionLimits,vf=e=>e.outgoingVideoLimit?.maxResolution,Sf=(e,t)=>{const i=t?.outgoingVideoLimit;if(!i)return;const{outgoingVideoLimit:n={}}=lt(e);if("number"==typeof i)return n?.maxResolution;const r=Object.keys(i).reduce(((e,t)=>{const i=n?.[t];return i&&(e[t]=i),e}),{});return Object.keys(r).length?r:void 0},yf=e=>e.numVideoChannelsGvc,Cf=e=>{const t=e.specCompliantSimulcast,i=t.video?.layerScaleFactors,n=t.sharing?.layerScaleFactors,r=i?.length?Math.max(...i):1,a=n?.length?Math.max(...i):1;return Math.min(r,a)},_f=g,Ef=e=>!!(0,_f.isNumber)(e)||!!(e=>{const t=["maxResolution","maxBitrate","maxFramerate"],i=e=>t.includes(e),n=Object.entries(e);return 0!==n.length&&n.every((([e,t])=>(0,_f.isNumber)(t)&&i(e)))})(e)&&!at(e),Tf={maxIncomingStreams:_f.isNumber,maxSimulcastLayers:_f.isNumber,maxOutgoingResolution:_f.isNumber,maxParticipantResolutions:e=>!!et(e)&&(!!(0,_f.isNumber)(e)||"more"in e&&Object.values(e).every((e=>(0,_f.isNumber)(e)))),outgoingVideoLimit:e=>!!et(e)&&Ef(e),incomingVideoLimit:e=>!!et(e)&&(!!Ef(e)||"more"in e&&Object.values(e).every((e=>Ef(e))))},bf=(e,t)=>{for(const i in t){const n=e[i],r=t[i];e[i]="object"==typeof r?bf({...n},r):tt(n,r)}return e},If=class{constructor(e,t,i,n,r,a,s){this.logger=e,this.defaultSettings=t,this._mediaConfig=i,this._userAgentConfig=n,this._countryCode=r,this.platformCallConstraintsProvider=a,this.currentCallConstraints=s,this.mergedConstraints={},this.callConstraintsTelemetry=[],this.iceTransportPolicy=Qe.ICE_TRANSPORT_POLICY.all,this.validIceTransportPolicies=[Qe.ICE_TRANSPORT_POLICY.all,Qe.ICE_TRANSPORT_POLICY.relay],this.mergeConstraintsTelemetryWithGlobal(),this.mergedConstraints=this.mergeConstraintsWithGlobal(this.currentCallConstraints),this.settings=this.mergeSettings((0,uf.cloneDeep)(this.defaultSettings))}get config(){return this.settings}get mediaConfig(){return this._mediaConfig}get userAgentConfig(){return this._userAgentConfig}get countryCode(){return this._countryCode}addCallConstraintsTelemetryEvent(e,t){const i={timestamp:(new Date).getTime(),type:t,value:e};Tt(this.callConstraintsTelemetry,i,this.config.numCallConstraintsEvents)}getCallConstraintsTelemetry(){return this.callConstraintsTelemetry}getCallConstraints(){return this.mergedConstraints}setCallConstraints(e={}){this.addCallConstraintsTelemetryEvent(e,"requested"),this.logger.safe.debug("Saving new call constraints",JSON.stringify(e));const t=this.transformConstraints((e=>(e=JSON.parse(JSON.stringify(e)),Object.entries(Tf).reduce(((t,[i,n])=>(n(e[i])&&(t[i]=e[i]),t)),{})))(e));return this.logger.safe.debug("Validated call constraints",JSON.stringify(t)),this.mergedConstraints=this.mergeConstraintsWithGlobal(t),this.settings=this.mergeSettings((0,uf.cloneDeep)(this.defaultSettings)),gf(this.logger,this.settings,t)}getIceTransportPolicy(){return this.settings.iceTransportPolicyForced||this.iceTransportPolicy}setIceTransportPolicy(e){this.validIceTransportPolicies.includes(e)?(this.logger.info(`Setting transport policy to ${this.iceTransportPolicy}`),this.iceTransportPolicy=e):this.logger.debug(`Unknown incoming transport policy, using ${this.iceTransportPolicy}`)}transformConstraints(e){const t=(0,uf.cloneDeep)(e);return"maxOutgoingResolution"in t&&(t.outgoingVideoLimit={maxResolution:t.maxOutgoingResolution},delete t.maxOutgoingResolution),"number"==typeof t.outgoingVideoLimit&&(t.outgoingVideoLimit={maxResolution:t.outgoingVideoLimit}),t}mergeConstraintsTelemetryWithGlobal(){this.platformCallConstraintsProvider.callConstraintsTelemetry.forEach((e=>Tt(this.callConstraintsTelemetry,e,this.defaultSettings.numCallConstraintsEvents)))}mergeConstraintsWithGlobal(e={}){const t=this.transformConstraints(this.platformCallConstraintsProvider.constraints);if(!Object.keys(t).length)return e;const i=(0,uf.cloneDeep)(e);return bf(i,t),this.logger.safe.debug(`Merging call constraints ${JSON.stringify(e)} and global constraints ${JSON.stringify(t)}. Result: ${JSON.stringify(i)}`),i}mergeSettings(e){if(!e.enablePlatformCallConstraints||!e.enablePlatformCallConstraintsPerCall)return e;const t=$t(this.logger,e,this.mergedConstraints);return this.logger.safe.info(`Merging settings with platform call constraints: ${Be(t)}`),(0,uf.assign)({},e,t,xw)}},wf="function",Rf="object",Af="undefined",Pf="prototype",Mf="hasOwnProperty",kf=Object,Df=kf[Pf],Of=kf.assign,Nf=kf.create,Lf=kf.defineProperty,xf=Df[Mf],Ff=null;function Uf(e){void 0===e&&(e=!0);var t=!1===e?null:Ff;return t||(typeof globalThis!==Af&&(t=globalThis),t||typeof self===Af||(t=self),t||typeof window===Af||(t=window),t||typeof i===Af||(t=i),Ff=t),t}function Bf(e){throw new TypeError(e)}function Vf(e){if(Nf)return Nf(e);if(null==e)return{};var t=typeof e;function i(){}return t!==Rf&&t!==wf&&Bf("Object prototype may only be an Object:"+e),i[Pf]=e,new i}(Uf()||{}).Symbol,(Uf()||{}).Reflect;var Hf,$f=Of||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Df[Mf].call(t,r)&&(e[r]=t[r]);return e},Gf=function(e,t){return(Gf=kf.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t[Mf](i)&&(e[i]=t[i])})(e,t)};function jf(e,t){function i(){this.constructor=e}typeof t!==wf&&null!==t&&Bf("Class extends value "+String(t)+" is not a constructor or null"),Gf(e,t),e[Pf]=null===t?Vf(t):(i[Pf]=t[Pf],new i)}function zf(e,t){for(var i=0,n=t.length,r=e.length;i<n;i++,r++)e[r]=t[i];return e}var Wf="undefined",qf="constructor",Kf="prototype",Jf="function",Yf="_dynInstFuncs",Qf="_isDynProxy",Zf="_dynClass",Xf="_dynInstChk",ev=Xf,tv="_dfOpts",iv="_unknown_",nv="__proto__",rv="_dyn"+nv,av="__dynProto$Gbl",sv="_dynInstProto",ov="useBaseInst",lv="setInstFuncs",cv=Object,dv=cv.getPrototypeOf,uv=cv.getOwnPropertyNames;var hv=function(){var e;return typeof globalThis!==Wf&&(e=globalThis),e||typeof self===Wf||(e=self),e||typeof window===Wf||(e=window),e||typeof i===Wf||(e=i),e||{}}(),pv=hv[av]||(hv[av]={o:(Hf={},Hf[lv]=!0,Hf[ov]=!0,Hf),n:1e3});function gv(e,t){return e&&cv[Kf].hasOwnProperty.call(e,t)}function mv(e){return e&&(e===cv[Kf]||e===Array[Kf])}function fv(e){return mv(e)||e===Function[Kf]}function vv(e){var t;if(e){if(dv)return dv(e);var i=e[nv]||e[Kf]||(e[qf]?e[qf][Kf]:null);t=e[rv]||i,gv(e,rv)||(delete e[sv],t=e[rv]=e[sv]||e[rv],e[sv]=i)}return t}function Sv(e,t){var i=[];if(uv)i=uv(e);else for(var n in e)"string"==typeof n&&gv(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function yv(e,t,i){return t!==qf&&typeof e[t]===Jf&&(i||gv(e,t))}function Cv(e){throw new TypeError("DynamicProto: "+e)}function _v(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function Ev(e,t,i,n,r){function a(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&gv(i,Zf)){var a=e[Yf]||{};if((r=(a[i[Zf]]||{})[t])||Cv("Missing ["+t+"] "+Jf),!r[Xf]&&!1!==a[ev]){for(var s=!gv(e,t),o=vv(e),l=[];s&&o&&!fv(o)&&!_v(l,o);){var c=o[t];if(c){s=c===n;break}l.push(o),o=vv(o)}try{s&&(e[t]=r),r[Xf]=1}catch(e){a[ev]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=vv(t)[e]),typeof n!==Jf&&Cv("["+e+"] is not a "+Jf),n}(t,e,i)).apply(this,arguments)};return i[Qf]=1,i}if(!mv(e)){var s=i[Yf]=i[Yf]||{},o=s[t]=s[t]||{};!1!==s[ev]&&(s[ev]=!!r),Sv(i,(function(t){yv(i,t,!1)&&i[t]!==n[t]&&(o[t]=i[t],delete i[t],(!gv(e,t)||e[t]&&!e[t][Qf])&&(e[t]=a(e,t)))}))}}function Tv(e,t){return gv(e,Kf)?e.name||t||iv:((e||{})[qf]||{}).name||t||iv}function bv(e,t,i,n){gv(e,Kf)||Cv("theClass is an invalid class definition.");var r=e[Kf];(function(e,t){if(dv){for(var i=[],n=vv(t);n&&!fv(n)&&!_v(i,n);){if(n===e)return!0;i.push(n),n=vv(n)}return!1}return!0})(r,t)||Cv("["+Tv(e)+"] not in hierarchy of ["+Tv(t)+"]");var a=null;gv(r,Zf)?a=r[Zf]:(a="_dynCls$"+Tv(e,"_")+"$"+pv.n,pv.n++,r[Zf]=a);var s=bv[tv],o=!!s[ov];o&&n&&void 0!==n[ov]&&(o=!!n[ov]);var l=function(e){var t={};return Sv(e,(function(i){!t[i]&&yv(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[Qf]&&n){var a=e[Yf]||{};!1!==a[ev]&&(r=(a[t[Zf]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var a={};Sv(i,(function(e){a[e]=r(t,i,e)}));for(var s=vv(e),o=[];s&&!fv(s)&&!_v(o,s);)Sv(s,(function(e){!a[e]&&yv(s,e,!dv)&&(a[e]=r(t,s,e))})),o.push(s),s=vv(s);return a}(r,t,l,o));var c=!!dv&&!!s[lv];c&&n&&(c=!!n[lv]),Ev(r,a,t,l,!1!==c)}bv[tv]=pv.o;var Iv="initialize",wv="name",Rv="getNotifyMgr",Av="identifier",Pv="push",Mv="isInitialized",kv="config",Dv="instrumentationKey",Ov="logger",Nv="length",Lv="time",xv="processNext",Fv="getProcessTelContext",Uv="addNotificationListener",Bv="removeNotificationListener",Vv="stopPollingInternalLogs",Hv="onComplete",$v="getPlugin",Gv="flush",jv="_extensions",zv="splice",Wv="teardown",qv="messageId",Kv="message",Jv="isAsync",Yv="_doTeardown",Qv="update",Zv="getNext",Xv="diagLog",eS="setNextPlugin",tS="createNew",iS="cookieCfg",nS="indexOf",rS="substring",aS="userAgent",sS="split",oS="setEnabled",lS="substr",cS="nodeType",dS="apply",uS="replace",hS="enableDebugExceptions",pS="toLowerCase",gS="call",mS="type",fS="handler",vS="listeners",SS="isChildEvt",yS="getCtx",CS="setCtx",_S="complete",ES="traceId",TS="spanId",bS="traceFlags",IS="",wS="channels",RS="core",AS="createPerfMgr",PS="disabled",MS="extensionConfig",kS="processTelemetry",DS="priority",OS="eventsSent",NS="eventsDiscarded",LS="eventsSendRequest",xS="perfEvent",FS="errorToConsole",US="warnToConsole",BS="getPerfMgr",VS="toISOString",HS="endsWith",$S="startsWith",GS="indexOf",jS="trim",zS="toString",WS="__proto__",qS="constructor",KS=Lf,JS=kf.freeze,YS=kf.keys,QS=String[Pf],ZS=QS[jS],XS=QS[HS],ey=QS[$S],ty=Date[Pf][VS],iy=Array.isArray,ny=Df[zS],ry=xf[zS],ay=ry[gS](kf),sy=/-([a-z])/g,oy=/([^\w\d_$])/g,ly=/^(\d+[\w\d_$])/,cy=Object.getPrototypeOf;function dy(e){return void 0===e||typeof e===Af}function uy(e){return null===e||dy(e)}function hy(e){return!uy(e)}function py(e,t){return!(!e||!xf[gS](e,t))}function gy(e){return!(!e||typeof e!==Rf)}function my(e){return!(!e||typeof e!==wf)}function fy(e){var t=e;return t&&Ey(t)&&(t=(t=(t=t[uS](sy,(function(e,t){return t.toUpperCase()})))[uS](oy,"_"))[uS](ly,(function(e,t){return"_"+t}))),t}function vy(e,t){if(e)for(var i in e)xf[gS](e,i)&&t[gS](e,i,e[i])}function Sy(e,t){var i=!1;return e&&t&&!(i=e===t)&&(i=XS?e[HS](t):function(e,t){var i=!1,n=t?t[Nv]:0,r=e?e[Nv]:0;if(n&&r&&r>=n&&!(i=e===t)){for(var a=r-1,s=n-1;s>=0;s--){if(e[a]!=t[s])return!1;a--}i=!0}return i}(e,t)),i}function yy(e,t){var i=!1;return e&&t&&!(i=e===t)&&(i=ey?e[$S](t):function(e,t){var i=!1,n=t?t[Nv]:0;if(e&&n&&e[Nv]>=n&&!(i=e===t)){for(var r=0;r<n;r++)if(e[r]!==t[r])return!1;i=!0}return i}(e,t)),i}function Cy(e,t){return!(!e||!t)&&-1!==e[nS](t)}var _y=iy||function(e){return!(!e||"[object Array]"!==ny[gS](e))};function Ey(e){return"string"==typeof e}function Ty(e){return"number"==typeof e}function by(e){return"boolean"==typeof e}function Iy(e){var t=!1;if(e&&"object"==typeof e){var i=cy?cy(e):function(e){if(e){if(cy)return cy(e);var t=e[WS]||e[Pf]||e[qS];if(t)return t}return null}(e);i?(i[qS]&&xf[gS](i,qS)&&(i=i[qS]),t=typeof i===wf&&ry[gS](i)===ay):t=!0}return t}function wy(e){if(e)return ty?e[VS]():function(e){if(e&&e.getUTCFullYear){var t=function(e){var t=String(e);return 1===t[Nv]&&(t="0"+t),t};return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+String((e.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}}(e)}function Ry(e,t,i){var n=e[Nv];try{for(var r=0;r<n&&(!(r in e)||-1!==t[gS](i||e,e[r],r,e));r++);}catch(e){}}function Ay(e,t,i){if(e){if(e[GS])return e[GS](t,i);var n=e[Nv],r=i||0;try{for(var a=Math.max(r>=0?r:n-Math.abs(r),0);a<n;a++)if(a in e&&e[a]===t)return a}catch(e){}}return-1}function Py(e){return e&&(e=ZS&&e[jS]?e[jS]():e[uS]?e[uS](/^\s+|(?=\s)\s+$/g,IS):e),e}var My=!{toString:null}.propertyIsEnumerable("toString"),ky=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];function Dy(e){var t=typeof e;if(t===wf||t===Rf&&null!==e||Bf("objKeys called on non-object"),!My&&YS)return YS(e);var i=[];for(var n in e)e&&xf[gS](e,n)&&i[Pv](n);if(My)for(var r=ky[Nv],a=0;a<r;a++)e&&xf[gS](e,ky[a])&&i[Pv](ky[a]);return i}function Oy(e,t,i,n){if(KS)try{var r={enumerable:!0,configurable:!0};return i&&(r.get=i),n&&(r.set=n),KS(e,t,r),!0}catch(e){}return!1}function Ny(e){return JS&&vy(e,(function(e,t){(_y(t)||gy(t))&&JS(t)})),Ly(e)}var Ly=JS||function(e){return e};function xy(){var e=Date;return e.now?e.now():(new e).getTime()}function Fy(e){return function(e){return!(!e||"[object Error]"!==ny[gS](e))}(e)?e[wv]:IS}function Uy(e,t,i,n,r){var a=i;return e&&((a=e[t])===i||r&&!r(a)||n&&!n(i)||(a=i,e[t]=a)),a}function By(e,t,i){var n;return e?!(n=e[t])&&uy(n)&&(n=dy(i)?{}:i,e[t]=n):n=dy(i)?{}:i,n}function Vy(e,t){return uy(e)?t:e}function Hy(e){return!!e}function $y(e){throw new Error(e)}function Gy(e,t,i,n,r){e&&t&&i&&(!1!==r||dy(e[t]))&&(e[t]=function(e,t){var i=null,n=null;return my(e)?i=e:n=e,function(){var e=arguments;if(i&&(n=i()),n)return n[t][dS](n,e)}}(i,n))}function jy(e,t,i,n){return e&&t&&gy(e)&&_y(i)&&Ry(i,(function(i){Ey(i)&&Gy(e,i,t,i,n)})),e}function zy(e){return e&&Of&&(e=kf(Of({},e))),e}function Wy(e,t,i,n,r,a){var s=arguments,o=s[0]||{},l=s[Nv],c=!1,d=1;for(l>0&&by(o)&&(c=o,o=s[d]||{},d++),gy(o)||(o={});d<l;d++){var u=s[d],h=_y(u),p=gy(u);for(var g in u)if(h&&g in u||p&&xf[gS](u,g)){var m=u[g],f=void 0;if(c&&m&&((f=_y(m))||Iy(m))){var v=o[g];f?_y(v)||(v=[]):Iy(v)||(v={}),m=Wy(c,v,m)}void 0!==m&&(o[g]=m)}}return o}function qy(e){var t={};return vy(e,(function(e,i){t[e]=i,t[i]=e})),Ny(t)}function Ky(e){var t={};return vy(e,(function(e,i){t[e]=i[1],t[i[0]]=i[1]})),Ny(t)}var Jy=qy({Unknown:0,NonRetryableStatus:1,InvalidEvent:2,SizeLimitExceeded:3,KillSwitch:4,QueueFull:5}),Yy="window",Qy="document",Zy="navigator",Xy="location",eC="console",tC="performance",iC="JSON",nC="crypto",rC="msCrypto",aC="msie",sC="trident/",oC="XMLHttpRequest",lC=null,cC=null,dC=!1,uC=null,hC=null;function pC(e,t){var i=!1;if(e){try{if(!(i=t in e)){var n=e[Pf];n&&(i=t in n)}}catch(e){}if(!i)try{i=!dy((new e)[t])}catch(e){}}return i}function gC(e){var t=Uf();return t&&t[e]?t[e]:e===Yy&&mC()?window:null}function mC(){return Boolean(typeof window===Rf&&window)}function fC(){return mC()?window:gC(Yy)}function vC(){return Boolean(typeof document===Rf&&document)}function SC(){return vC()?document:gC(Qy)}function yC(){return Boolean(typeof navigator===Rf&&navigator)}function CC(){return yC()?navigator:gC(Zy)}function _C(e){if(e&&dC){var t=gC("__mockLocation");if(t)return t}return typeof location===Rf&&location?location:gC(Xy)}function EC(){return Boolean(typeof JSON===Rf&&JSON||null!==gC(iC))}function TC(){return EC()?JSON||gC(iC):null}function bC(){var e=CC();return!(!e||!e.product)&&"ReactNative"===e.product}function IC(){var e=CC();if(e&&(e[aS]!==cC||null===lC)){var t=((cC=e[aS])||IS)[pS]();lC=Cy(t,aC)||Cy(t,sC)}return lC}function wC(e){var t=Object[Pf].toString[gS](e),i=IS;return"[object Error]"===t?i="{ stack: '"+e.stack+"', message: '"+e.message+"', name: '"+e[wv]+"'":EC()&&(i=TC().stringify(e)),t+i}function RC(){return null===hC&&(hC=yC()&&Boolean(CC().sendBeacon)),hC}function AC(e){var t=!1;try{t=!!gC("fetch");var i=gC("Request");t&&e&&i&&(t=pC(i,"keepalive"))}catch(e){}return t}function PC(){var e=!1;try{e=!!gC(oC)}catch(e){}return e}var MC,kC=["eventsSent","eventsDiscarded","eventsSendRequest","perfEvent"],DC=null;function OC(e,t){return function(){var i=arguments,n=NC(t);if(n){var r=n.listener;r&&r[e]&&r[e][dS](r,i)}}}function NC(e){var t=DC;return t||!0===e.disableDbgExt||(t=DC||function(){var e=gC("Microsoft");return e&&(DC=e.ApplicationInsights),DC}()),t?t.ChromeDbgExt:null}function LC(e){return e?'"'+e[uS](/\"/g,IS)+'"':IS}function xC(e,t){var i=typeof console!==Af?console:gC(eC);if(i){var n="log";i[e]&&(n=e),my(i[n])&&i[n](t)}}var FC=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r[qv]=e,r[Kv]=(i?"AI: ":"AI (Internal): ")+e;var a=IS;EC()&&(a=TC().stringify(n));var s=(t?" message:"+LC(t):IS)+(n?" props:"+LC(a):IS);r[Kv]+=s}return e.dataType="MessageData",e}();function UC(e,t){return(e||{})[Ov]||new BC(t)}var BC=function(){function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i,n,r,a,s=0,o={};bv(e,this,(function(e){function l(t,i){if(!(s>=r)){var a=!0,l="AITR_"+i[qv];if(o[l]?a=!1:o[l]=!0,a&&(t<=n&&(e.queue[Pv](i),s++,c(1===t?"error":"warn",i)),s===r)){var d="Internal events throttle limit per PageView reached for this app.",u=new FC(23,d,!1);e.queue[Pv](u),1===t?e[FS](d):e[US](d)}}}function c(e,i){var n=NC(t||{});n&&n[Xv]&&n[Xv](e,i)}(function(e){i=Vy(e.loggingLevelConsole,0),n=Vy(e.loggingLevelTelemetry,1),r=Vy(e.maxMessageLimit,25),a=Vy(e[hS],!1)})(t||{}),e.consoleLoggingLevel=function(){return i},e.telemetryLoggingLevel=function(){return n},e.maxInternalMessageLimit=function(){return r},e[hS]=function(){return a},e.throwInternal=function(t,n,r,s,d){void 0===d&&(d=!1);var u=new FC(n,r,d,s);if(a)throw wC(u);var h=1===t?FS:US;if(dy(u[Kv]))c("throw"+(1===t?"Critical":"Warning"),u);else{if(d){var p=+u[qv];!o[p]&&i>=t&&(e[h](u[Kv]),o[p]=!0)}else i>=t&&e[h](u[Kv]);l(t,u)}},e[US]=function(e){xC("warn",e),c("warning",e)},e[FS]=function(e){xC("error",e),c("error",e)},e.resetInternalMessageCount=function(){s=0,o={}},e.logInternalMessage=l}))}return e.__ieDyn=1,e}();function VC(e){return e||new BC}function HC(e,t,i,n,r,a){void 0===a&&(a=!1),VC(e).throwInternal(t,i,n,r,a)}function $C(e,t){VC(e)[US](t)}var GC="ctx",jC="ParentContextKey",zC="ChildrenContextKey",WC=function(){function e(t,i,n){var r,a=this,s=!1;a.start=xy(),a[wv]=t,a[Jv]=n,a[SS]=function(){return!1},my(i)&&(s=Oy(a,"payload",(function(){return!r&&my(i)&&(r=i(),i=null),r}))),a[yS]=function(t){return t?t===e[jC]||t===e[zC]?a[t]:(a[GC]||{})[t]:null},a[CS]=function(t,i){t&&(t===e[jC]?(a[t]||(a[SS]=function(){return!0}),a[t]=i):t===e[zC]?a[t]=i:(a[GC]=a[GC]||{})[t]=i)},a[_S]=function(){var t=0,n=a[yS](e[zC]);if(_y(n))for(var r=0;r<n[Nv];r++){var o=n[r];o&&(t+=o[Lv])}a[Lv]=xy()-a.start,a.exTime=a[Lv]-t,a[_S]=function(){},!s&&my(i)&&(a.payload=i())}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),qC=function(){function e(t){this.ctx={},bv(e,this,(function(e){e.create=function(e,t,i){return new WC(e,t,i)},e.fire=function(e){e&&(e[_S](),t&&my(t[xS])&&t[xS](e))},e[CS]=function(t,i){t&&((e[GC]=e[GC]||{})[t]=i)},e[yS]=function(t){return(e[GC]||{})[t]}}))}return e.__ieDyn=1,e}(),KC="CoreUtils.doPerf";function JC(e,t,i,n,r){if(e){var a=e;if(a[BS]&&(a=a[BS]()),a){var s=void 0,o=a[yS](KC);try{if(s=a.create(t(),n,r)){if(o&&s[CS]&&(s[CS](WC[jC],o),o[yS]&&o[CS])){var l=o[yS](WC[zC]);l||(l=[],o[CS](WC[zC],l)),l[Pv](s)}return a[CS](KC,s),i(s)}}catch(e){s&&s[CS]&&s[CS]("exception",e)}finally{s&&a.fire(s),a[CS](KC,o)}}}return i()}var YC=4294967296,QC=4294967295,ZC=!1,XC=123456789,e_=987654321;function t_(){try{var e=2147483647&xy();!function(e){e<0&&(e>>>=0),XC=123456789+e&QC,e_=987654321-e&QC,ZC=!0}((Math.random()*YC^e)+e)}catch(e){}}function i_(e){var t=0,i=gC(nC)||gC(rC);return i&&i.getRandomValues&&(t=i.getRandomValues(new Uint32Array(1))[0]&QC),0===t&&IC()&&(ZC||t_(),t=function(e){var t=((e_=36969*(65535&e_)+(e_>>16)&QC)<<16)+(65535&(XC=18e3*(65535&XC)+(XC>>16)&QC))>>>0&QC;return e||(t>>>=0),t}()&QC),0===t&&(t=Math.floor(YC*Math.random()|0)),e||(t>>>=0),t}function n_(e){void 0===e&&(e=22);for(var t=i_()>>>0,i=0,n=IS;n[Nv]<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(i_()<<2&4294967295|3&t)>>>0,i=0);return n}var r_=Lf,a_="2.8.10",s_="."+n_(6),o_=0;function l_(e){return 1===e[cS]||9===e[cS]||!+e[cS]}function c_(e,t){var i=t[e.id];if(!i){i={};try{l_(t)&&(function(e,t,i){if(r_)try{return r_(e,t,{value:i,enumerable:!1,configurable:!0}),!0}catch(e){}return!1}(t,e.id,i)||(t[e.id]=i))}catch(e){}}return i}function d_(e,t){return void 0===t&&(t=!1),fy(e+o_+++(t?"."+a_:IS)+s_)}function u_(e){var t={id:d_("_aiData-"+(e||IS)+"."+a_),accept:function(e){return l_(e)},get:function(e,i,n,r){var a=e[t.id];return a?a[fy(i)]:(r&&((a=c_(t,e))[fy(i)]=n),n)},kill:function(e,t){if(e&&e[t])try{delete e[t]}catch(e){}}};return t}var h_="toGMTString",p_="toUTCString",g_="cookie",m_="expires",f_="enabled",v_="isCookieUseDisabled",S_="disableCookiesUsage",y_="_ckMgr",C_=null,__=null,E_=null,T_=SC(),b_={},I_={};function w_(e){return!e||e.isEnabled()}function R_(e,t){return!!(t&&e&&_y(e.ignoreCookies))&&-1!==e.ignoreCookies[nS](t)}function A_(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=t[iS];i=n[y_]?n[y_]:P_(t)}return i||(i=function(e,t){var i=P_[y_]||I_[y_];return i||(i=P_[y_]=P_(e,t),I_[y_]=i),i}(t,(e||{})[Ov])),i}function P_(e,t){var i,n=function(e){var t=e[iS]=e[iS]||{};if(Uy(t,"domain",e.cookieDomain,hy,uy),Uy(t,"path",e.cookiePath||"/",null,uy),uy(t[f_])){var i=void 0;dy(e[v_])||(i=!e[v_]),dy(e[S_])||(i=!e[S_]),t[f_]=i}return t}(e||I_),r=n.path||"/",a=n.domain,s=!1!==n[f_],o=((i={isEnabled:function(){var e=s&&M_(t),i=I_[y_];return e&&i&&o!==i&&(e=w_(i)),e}})[oS]=function(e){s=!1!==e},i.set=function(e,t,i,s,l){var c=!1;if(w_(o)&&!function(e,t){return!!(t&&e&&_y(e.blockedCookies)&&-1!==e.blockedCookies[nS](t))||R_(e,t)}(n,e)){var d={},u=Py(t||IS),h=u[nS](";");if(-1!==h&&(u=Py(t[rS](0,h)),d=k_(t[rS](h+1))),Uy(d,"domain",s||a,Hy,dy),!uy(i)){var p=IC();if(dy(d[m_])){var g=xy()+1e3*i;if(g>0){var m=new Date;m.setTime(g),Uy(d,m_,D_(m,p?h_:p_)||D_(m,p?h_:p_)||IS,Hy)}}p||Uy(d,"max-age",IS+i,null,dy)}var f=_C();f&&"https:"===f.protocol&&(Uy(d,"secure",null,null,dy),null===__&&(__=!function(e){return!(!Ey(e)||!Cy(e,"CPU iPhone OS 12")&&!Cy(e,"iPad; CPU OS 12")&&!(Cy(e,"Macintosh; Intel Mac OS X 10_14")&&Cy(e,"Version/")&&Cy(e,"Safari"))&&(!Cy(e,"Macintosh; Intel Mac OS X 10_14")||!Sy(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!Cy(e,"Chrome/5")&&!Cy(e,"Chrome/6")&&(!Cy(e,"UnrealEngine")||Cy(e,"Chrome"))&&!Cy(e,"UCBrowser/12")&&!Cy(e,"UCBrowser/11"))}((CC()||{})[aS])),__&&Uy(d,"SameSite","None",null,dy)),Uy(d,"path",l||r,null,dy),(n.setCookie||L_)(e,O_(u,d)),c=!0}return c},i.get=function(e){var t=IS;return w_(o)&&!R_(n,e)&&(t=(n.getCookie||N_)(e)),t},i.del=function(e,t){var i=!1;return w_(o)&&(i=o.purge(e,t)),i},i.purge=function(e,i){var r,a=!1;if(M_(t)){var s=((r={}).path=i||"/",r[m_]="Thu, 01 Jan 1970 00:00:01 GMT",r);IC()||(s["max-age"]="0"),(n.delCookie||L_)(e,O_(IS,s)),a=!0}return a},i);return o[y_]=o,o}function M_(e){if(null===C_){C_=!1;try{C_=void 0!==(T_||{})[g_]}catch(t){HC(e,2,68,"Cannot access document.cookie - "+Fy(t),{exception:wC(t)})}}return C_}function k_(e){var t={};return e&&e[Nv]&&Ry(Py(e)[sS](";"),(function(e){if(e=Py(e||IS)){var i=e[nS]("=");-1===i?t[e]=null:t[Py(e[rS](0,i))]=Py(e[rS](i+1))}})),t}function D_(e,t){return my(e[t])?e[t]():null}function O_(e,t){var i=e||IS;return vy(t,(function(e,t){i+="; "+e+(uy(t)?IS:"="+t)})),i}function N_(e){var t=IS;if(T_){var i=T_[g_]||IS;E_!==i&&(b_=k_(i),E_=i),t=Py(b_[e]||IS)}return t}function L_(e,t){T_&&(T_[g_]=e+"="+t)}var x_="on",F_="attachEvent",U_="addEventListener",B_="detachEvent",V_="removeEventListener",H_="events",$_="visibilitychange",G_="pagehide",j_="pageshow",z_="unload",W_="beforeunload",q_=d_("aiEvtPageHide"),K_=d_("aiEvtPageShow"),J_=/\.[\.]+/g,Y_=/[\.]+$/,Q_=1,Z_=u_("events"),X_=/^([^.]*)(?:\.(.+)|)/;function eE(e){return e&&e[uS]?e[uS](/^[\s\.]+|(?=[\s\.])[\.\s]+$/g,IS):e}function tE(e,t){var i;if(t){var n=IS;_y(t)?(n=IS,Ry(t,(function(e){(e=eE(e))&&("."!==e[0]&&(e="."+e),n+=e)}))):n=eE(t),n&&("."!==n[0]&&(n="."+n),e=(e||IS)+n)}var r=X_.exec(e||IS)||[];return(i={})[mS]=r[1],i.ns=(r[2]||IS).replace(J_,".").replace(Y_,IS)[sS](".").sort().join("."),i}function iE(e,t,i){void 0===i&&(i=!0);var n=Z_.get(e,H_,{},i),r=n[t];return r||(r=n[t]=[]),r}function nE(e,t,i,n){e&&t&&t[mS]&&(e[V_]?e[V_](t[mS],i,n):e[B_]&&e[B_](x_+t[mS],i))}function rE(e,t,i,n){for(var r=t[Nv];r--;){var a=t[r];a&&(i.ns&&i.ns!==a.evtName.ns||n&&!n(a)||(nE(e,a.evtName,a[fS],a.capture),t[zv](r,1)))}}function aE(e,t){return t?tE("xx",_y(t)?[e].concat(t):[e,t]).ns[sS]("."):e}function sE(e,t,i,n,r){var a;void 0===r&&(r=!1);var s=!1;if(e)try{var o=tE(t,n);if((s=function(e,t,i,n){var r=!1;return e&&t&&t[mS]&&i&&(e[U_]?(e[U_](t[mS],i,n),r=!0):e[F_]&&(e[F_](x_+t[mS],i),r=!0)),r}(e,o,i,r))&&Z_.accept(e)){var l=((a={guid:Q_++,evtName:o})[fS]=i,a.capture=r,a);iE(e,o.type)[Pv](l)}}catch(e){}return s}function oE(e,t,i,n,r){if(void 0===r&&(r=!1),e)try{var a=tE(t,n),s=!1;(function(e,t,i){if(t[mS])rE(e,iE(e,t[mS]),t,i);else{var n=Z_.get(e,H_,{});vy(n,(function(n,r){rE(e,r,t,i)})),0===Dy(n)[Nv]&&Z_.kill(e,H_)}})(e,a,(function(e){return!((!a.ns||i)&&e[fS]!==i||(s=!0,0))})),s||nE(e,a,i,r)}catch(e){}}function lE(e,t,i,n){var r=!1;return t&&e&&e[Nv]>0&&Ry(e,(function(e){e&&(i&&-1!==Ay(i,e)||(r=function(e,t,i){var n=!1,r=fC();r&&(n=sE(r,e,t,i),n=sE(r.body,e,t,i)||n);var a=SC();return a&&(n=sE(a,e,t,i)||n),n}(e,t,n)||r))})),r}function cE(e,t,i){e&&_y(e)&&Ry(e,(function(e){e&&function(e,t,i){var n=fC();n&&(oE(n,e,t,i),oE(n.body,e,t,i));var r=SC();r&&oE(r,e,t,i)}(e,t,i)}))}function dE(e,t,i){return function(e,t,i,n){var r=!1;return t&&e&&_y(e)&&!(r=lE(e,t,i,n))&&i&&i[Nv]>0&&(r=lE(e,t,null,n)),r}([W_,z_,G_],e,t,i)}function uE(e,t,i){var n=aE(q_,i),r=lE([G_],e,t,n);return t&&-1!==Ay(t,$_)||(r=lE([$_],(function(t){var i=SC();e&&i&&"hidden"===i.visibilityState&&e(t)}),t,n)||r),!r&&t&&(r=uE(e,null,i)),r}function hE(e,t,i){var n=aE(K_,i),r=lE([j_],e,t,n);return!(r=lE([$_],(function(t){var i=SC();e&&i&&"visible"===i.visibilityState&&e(t)}),t,n)||r)&&t&&(r=hE(e,null,i)),r}function pE(){var e=gE();return e[rS](0,8)+"-"+e[rS](8,12)+"-"+e[rS](12,16)+"-"+e[rS](16,20)+"-"+e[rS](20)}function gE(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i=IS,n=0;n<4;n++)i+=t[15&(e=i_())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&i_())|0];return i[lS](0,8)+i[lS](9,4)+"4"+i[lS](13,3)+r+i[lS](16,3)+i[lS](19,12)}var mE="00000000000000000000000000000000",fE="0000000000000000";function vE(e,t,i){return!(!e||e[Nv]!==t||e===i||!e.match(/^[\da-f]*$/))}function SE(e){return vE(e,32,mE)}function yE(e){return vE(e,16,fE)}var CE=u_("plugin");function _E(e){return CE.get(e,"state",{},!0)}function EE(e,t){for(var i,n=[],r=null,a=e[Zv]();a;){var s=a[$v]();s&&(r&&my(r[eS])&&my(s[kS])&&r[eS](s),(my(s[Mv])?s[Mv]():(i=_E(s))[Mv])||n[Pv](s),r=s,a=a[Zv]())}Ry(n,(function(n){var r=e[RS]();n[Iv](e.getCfg(),r,t,e[Zv]()),i=_E(n),n[RS]||i[RS]||(i[RS]=r),i[Mv]=!0,delete i[Wv]}))}function TE(e){return e.sort((function(e,t){var i=0;if(t){var n=my(t[kS]);my(e[kS])?i=n?e[DS]-t[DS]:1:n&&(i=-1)}else i=e?1:-1;return i}))}var bE="TelemetryPluginChain",IE="_hasRun",wE="_getTelCtx",RE=0;function AE(e,t,i,n){var r=null,a=[];null!==n&&(r=n?function(e,t,i){for(;e;){if(e[$v]()===i)return e;e=e[Zv]()}return DE([i],t[kv]||{},t)}(e,i,n):e);var s={_next:function(){var e=r;if(r=e?e[Zv]():null,!e){var t=a;t&&t[Nv]>0&&(Ry(t,(function(e){try{e.func[gS](e.self,e.args)}catch(e){HC(i[Ov],2,73,"Unexpected Exception during onComplete - "+wC(e))}})),a=[])}return e},ctx:{core:function(){return i},diagLog:function(){return UC(i,t)},getCfg:function(){return t},getExtCfg:o,getConfig:function(e,i,n){var r;void 0===n&&(n=!1);var a=o(e,null);return a&&!uy(a[i])?r=a[i]:t&&!uy(t[i])&&(r=t[i]),uy(r)?n:r},hasNext:function(){return!!r},getNext:function(){return r},setNext:function(e){r=e},iterate:function(e){for(var t;t=s._next();){var i=t[$v]();i&&e(i)}},onComplete:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];e&&a[Pv]({func:e,self:dy(t)?s.ctx:t,args:i})}}};function o(e,i,n){var r;if(void 0===i&&(i={}),void 0===n&&(n=0),t){var a=t[MS];a&&e&&(r=a[e])}if(r){if(gy(i)&&0!==n){var s=Wy(!0,i,r);t&&2===n&&vy(i,(function(e){if(uy(s[e])){var i=t[e];uy(i)||(s[e]=i)}})),r=s}}else r=i;return r}return s}function PE(e,t,i,n){var r=AE(e,t,i,n),a=r.ctx;return a[xv]=function(e){var t=r._next();return t&&t[kS](e,a),!t},a[tS]=function(e,n){return void 0===e&&(e=null),_y(e)&&(e=DE(e,t,i,n)),PE(e||a[Zv](),t,i,n)},a}function ME(e,t,i){var n=t[kv]||{},r=AE(e,n,t,i),a=r.ctx;return a[xv]=function(e){var t=r._next();return t&&t.unload(a,e),!t},a[tS]=function(e,i){return void 0===e&&(e=null),_y(e)&&(e=DE(e,n,t,i)),ME(e||a[Zv](),t,i)},a}function kE(e,t,i){var n=t[kv]||{},r=AE(e,n,t,i).ctx;return r[xv]=function(e){return r.iterate((function(t){my(t[Qv])&&t[Qv](r,e)}))},r[tS]=function(e,i){return void 0===e&&(e=null),_y(e)&&(e=DE(e,n,t,i)),kE(e||r[Zv](),t,i)},r}function DE(e,t,i,n){var r=null,a=!n;if(_y(e)&&e[Nv]>0){var s=null;Ry(e,(function(e){if(a||n!==e||(a=!0),a&&e&&my(e[kS])){var o=function(e,t,i){var n,r=null,a=my(e[kS]),s=my(e[eS]),o={getPlugin:function(){return e},getNext:function(){return r},processTelemetry:d,unload:u,update:h,_id:n=e?e[Av]+"-"+e[DS]+"-"+RE++:"Unknown-0-"+RE++,_setNext:function(e){r=e}};function l(){var n;return e&&my(e[wE])&&(n=e[wE]()),n||(n=PE(o,t,i)),n}function c(t,i,a,s,o){var l=!1,c=e?e[Av]:bE,d=t[IE];return d||(d=t[IE]={}),t.setNext(r),e&&JC(t[RS](),(function(){return c+":"+a}),(function(){d[n]=!0;try{var e=r?r._id:IS;e&&(d[e]=!1),l=i(t)}catch(e){var s=!r||d[r._id];s&&(l=!0),r&&s||HC(t[Xv](),1,73,"Plugin ["+c+"] failed during "+a+" - "+wC(e)+", run flags: "+wC(d))}}),s,o),l}function d(t,i){function n(i){if(!e||!a)return!1;var n=_E(e);return!n[Wv]&&!n[PS]&&(s&&e[eS](r),e[kS](t,i),!0)}c(i=i||l(),n,"processTelemetry",(function(){return{item:t}}),!t.sync)||i[xv](t)}function u(t,i){function n(){var n=!1;if(e){var r=_E(e),a=e[RS]||r[RS];!e||a&&a!==t.core()||r[Wv]||(r[RS]=null,r[Wv]=!0,r[Mv]=!1,e[Wv]&&!0===e[Wv](t,i)&&(n=!0))}return n}c(t,n,"unload",(function(){}),i[Jv])||t[xv](i)}function h(t,i){function n(){var n=!1;if(e){var r=_E(e),a=e[RS]||r[RS];!e||a&&a!==t.core()||r[Wv]||e[Qv]&&!0===e[Qv](t,i)&&(n=!0)}return n}c(t,n,"update",(function(){}),!1)||t[xv](i)}return Ly(o)}(e,t,i);r||(r=o),s&&s._setNext(o),s=o}}))}return n&&!r?DE([n],t,i):r}var OE=function(e,t,i,n){var r=PE(e,t,i,n);jy(this,r,Dy(r))},NE=500,LE="Channel has invalid priority - ";function xE(e,t,i){t&&_y(t)&&t[Nv]>0&&(Ry(t=t.sort((function(e,t){return e[DS]-t[DS]})),(function(e){e[DS]<NE&&$y(LE+e[Av])})),e[Pv]({queue:Ly(t),chain:DE(t,i[kv],i)}))}function FE(){var e=[];return{add:function(t){t&&e[Pv](t)},run:function(t,i){Ry(e,(function(e){try{e(t,i)}catch(e){HC(t[Xv](),2,73,"Unexpected error calling unload handler - "+wC(e))}})),e=[]}}}var UE="getPlugin",BE=function(){function e(){var t,i,n,r,a,s=this;function o(e){void 0===e&&(e=null);var t=e;if(!t){var r=i||PE(null,{},s[RS]);t=n&&n[UE]?r[tS](null,n[UE]):r[tS](null,n)}return t}function l(e,t,r){e&&Uy(e,MS,[],null,uy),!r&&t&&(r=t[Fv]()[Zv]());var a=n;n&&n[UE]&&(a=n[UE]()),s[RS]=t,i=PE(r,e,t,a)}function c(){t=!1,s[RS]=null,i=null,n=null,a=[],r=FE()}c(),bv(e,s,(function(e){e[Iv]=function(e,i,n,r){l(e,i,r),t=!0},e[Wv]=function(t,i){var s,o=e[RS];if(o&&(!t||o===t[RS]())){var l,d=!1,u=t||ME(null,o,n&&n[UE]?n[UE]():n),h=i||((s={reason:0})[Jv]=!1,s);return e[Yv]&&!0===e[Yv](u,h,p)?l=!0:p(),l}function p(){if(!d){d=!0,r.run(u,i);var e=a;a=[],Ry(e,(function(e){e.rm()})),!0===l&&u[xv](h),c()}}},e[Qv]=function(t,i){var r=e[RS];if(r&&(!t||r===t[RS]())){var a,s=!1,o=t||kE(null,r,n&&n[UE]?n[UE]():n),c=i||{reason:0};return e._doUpdate&&!0===e._doUpdate(o,c,d)?a=!0:d(),a}function d(){s||(s=!0,l(o.getCfg(),o.core(),o[Zv]()))}},e._addHook=function(e){e&&(_y(e)?a=a.concat(e):a[Pv](e))},Gy(e,"_addUnloadCb",(function(){return r}),"add")})),s[Xv]=function(e){return o(e)[Xv]()},s[Mv]=function(){return t},s.setInitialized=function(e){t=e},s[eS]=function(e){n=e},s[xv]=function(e,t){t?t[xv](e):n&&my(n[kS])&&n[kS](e,null)},s._getTelCtx=o}return e.__ieDyn=1,e}(),VE=function(e){function t(){var i,n,r=e.call(this)||this;function a(){i=0,n=[]}return r.identifier="TelemetryInitializerPlugin",r.priority=199,a(),bv(t,r,(function(e,t){e.addTelemetryInitializer=function(e){var t={id:i++,fn:e};return n[Pv](t),{remove:function(){Ry(n,(function(e,i){if(e.id===t.id)return n[zv](i,1),-1}))}}},e[kS]=function(t,i){for(var r=!1,a=n[Nv],s=0;s<a;++s){var o=n[s];if(o)try{if(!1===o.fn[dS](null,[t])){r=!0;break}}catch(e){HC(i[Xv](),1,64,"One of telemetry initializers failed, telemetry item will not be sent: "+Fy(e),{exception:wC(e)},!0)}}r||e[xv](t,i)},e[Yv]=function(){a()}})),r}return jf(t,e),t.__ieDyn=1,t}(BE),HE="Plugins must provide initialize method",$E="_notificationManager",GE="SDK is still unloading...",jE={loggingLevelConsole:1};function zE(e,t){return new qC(t)}function WE(e,t){var i=!1;return Ry(t,(function(t){if(t===e)return i=!0,-1})),i}var qE=function(){function e(){var t,i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S,y,C,_=0;bv(e,this,(function(e){function E(){i=!1,t=Wy(!0,{},jE),e[kv]=t,e[Ov]=new BC(t),e[jv]=[],m=new VE,n=[],r=null,a=null,s=null,o=null,l=null,d=null,c=[],u=null,h=null,p=null,g=!1,f=null,v=d_("AIBaseCore",!0),S=FE(),C=null}function T(){return PE(w(),t,e)}function b(i){var n=function(e,t,i){var n,r=[],a={};return Ry(i,(function(i){(uy(i)||uy(i[Iv]))&&$y(HE);var n=i[DS],s=i[Av];i&&n&&(uy(a[n])?a[n]=s:$C(e,"Two extensions have same priority #"+n+" - "+a[n]+", "+s)),(!n||n<t)&&r[Pv](i)})),(n={all:i})[RS]=r,n}(e[Ov],NE,c);d=n[RS],l=null;var r=n.all;if(p=Ly(function(e,t,i){var n=[];if(e&&Ry(e,(function(e){return xE(n,e,i)})),t){var r=[];Ry(t,(function(e){e[DS]>NE&&r[Pv](e)})),xE(n,r,i)}return n}(h,r,e)),u){var a=Ay(r,u);-1!==a&&r[zv](a,1),-1!==(a=Ay(d,u))&&d[zv](a,1),u._setQueue(p)}else u=function(e,t){function i(){return PE(null,t[kv],t,null)}function n(e,t,i,n){var r=e?e[Nv]+1:1;function a(){0==--r&&(n&&n(),n=null)}r>0&&Ry(e,(function(e){if(e&&e.queue[Nv]>0){var n=e.chain,s=t[tS](n);s[Hv](a),i(s)}else r--})),a()}var r=!1;return{identifier:"ChannelControllerPlugin",priority:NE,initialize:function(t,i,n,a){r=!0,Ry(e,(function(e){e&&e.queue[Nv]>0&&EE(PE(e.chain,t,i),n)}))},isInitialized:function(){return r},processTelemetry:function(t,r){n(e,r||i(),(function(e){e[xv](t)}),(function(){r[xv](t)}))},update:function(t,i){var r=i||{reason:0};return n(e,t,(function(e){e[xv](r)}),(function(){t[xv](r)})),!0},pause:function(){n(e,i(),(function(e){e.iterate((function(e){e.pause&&e.pause()}))}),null)},resume:function(){n(e,i(),(function(e){e.iterate((function(e){e.resume&&e.resume()}))}),null)},teardown:function(t,i){var a=i||{reason:0,isAsync:!1};return n(e,t,(function(e){e[xv](a)}),(function(){t[xv](a),r=!1})),!0},getChannel:function(t){var i=null;return e&&e[Nv]>0&&Ry(e,(function(e){if(e&&e.queue[Nv]>0&&(Ry(e.queue,(function(e){if(e[Av]===t)return i=e,-1})),i))return-1})),i},flush:function(t,r,a,s){var o=1,l=!1,c=null;function d(){o--,l&&0===o&&(c&&(clearTimeout(c),c=null),r&&r(l),r=null)}return s=s||5e3,n(e,i(),(function(e){e.iterate((function(e){if(e[Gv]){o++;var i=!1;e[Gv](t,(function(){i=!0,d()}),a)||i||(t&&null==c?c=setTimeout((function(){c=null,d()}),s):d())}}))}),(function(){l=!0,d()})),!0},_setQueue:function(t){e=t}}}(p,e);r[Pv](u),d[Pv](u),e[jv]=TE(r),u[Iv](t,e,r),EE(T(),r),e[jv]=Ly(TE(d||[])).slice(),i&&function(t){var i=kE(w(),e);e._updateHook&&!0===e._updateHook(i,t)||i[xv](t)}(i)}function I(t){var i,n=null,r=null;return Ry(e[jv],(function(e){if(e[Av]===t&&e!==u&&e!==m)return r=e,-1})),!r&&u&&(r=u.getChannel(t)),r&&((i={plugin:r})[oS]=function(e){_E(r)[PS]=!e},i.isEnabled=function(){var e=_E(r);return!e[Wv]&&!e[PS]},i.remove=function(e,t){var i;void 0===e&&(e=!0);var n=[r],a=((i={reason:1})[Jv]=e,i);R(n,a,(function(e){e&&b({reason:32,removed:n}),t&&t(e)}))},n=i),n}function w(){if(!l){var i=(d||[]).slice();-1===Ay(i,m)&&i[Pv](m),l=DE(TE(i),t,e)}return l}function R(i,n,r){if(i&&i[Nv]>0){var a=ME(DE(i,t,e),e);a[Hv]((function(){var e=!1,t=[];Ry(c,(function(n,r){WE(n,i)?e=!0:t[Pv](n)})),c=t;var n=[];h&&(Ry(h,(function(t,r){var a=[];Ry(t,(function(t){WE(t,i)?e=!0:a[Pv](t)})),n[Pv](a)})),h=n),r&&r(e)})),a[xv](n)}else r(!1)}function A(){var i=e[Ov]?e[Ov].queue:[];i&&(Ry(i,(function(i){var n,r=((n={})[wv]=f||"InternalMessageId: "+i[qv],n.iKey=Vy(t[Dv]),n.time=wy(new Date),n.baseType=FC.dataType,n.baseData={message:i[Kv]},n);e.track(r)})),i[Nv]=0)}function P(e,t,i,n){return u?u[Gv](e,t,i||6,n):(t&&t(!1),!0)}function M(){var e=Vy(t.disableDbgExt);!0===e&&y&&(r[Bv](y),y=null),r&&!y&&!0!==e&&(y=function(e){if(!MC){MC={};for(var t=0;t<kC[Nv];t++)MC[kC[t]]=OC(kC[t],e)}return MC}(t),r[Uv](y))}function k(){var e=Vy(t.enablePerfMgr);!e&&s&&(s=null),e&&By(t,AS,zE)}function D(t){var i=e[Ov];i?HC(i,2,73,t):$y(t)}E(),e[Mv]=function(){return i},e[Iv]=function(n,a,s,o){g&&$y(GE),e[Mv]()&&$y("Core should not be initialized more than once"),t=n||{},e[kv]=t,uy(n[Dv])&&$y("Please provide instrumentation key"),r=o,e[$E]=o,M(),k(),By(t,MS,{}).NotificationManager=r,s&&(e[Ov]=s);var l=By(t,"extensions",[]);(c=[])[Pv].apply(c,zf(zf([],a),l)),h=By(t,wS,[]),b(null),p&&0!==p[Nv]||$y("No "+wS+" available"),i=!0,e.releaseQueue()},e.getTransmissionControls=function(){var e=[];return p&&Ry(p,(function(t){e[Pv](t.queue)})),Ly(e)},e.track=function(i){i.iKey=i.iKey||t[Dv],i[Lv]=i[Lv]||wy(new Date),i.ver=i.ver||"4.0",!g&&e[Mv]()?T()[xv](i):n[Pv](i)},e[Fv]=T,e[Rv]=function(){return r||(r=function(){var e;return Vf(((e={})[Uv]=function(e){},e[Bv]=function(e){},e[OS]=function(e){},e[NS]=function(e,t){},e[LS]=function(e,t){},e))}(),e[$E]=r),r},e[Uv]=function(e){r&&r[Uv](e)},e[Bv]=function(e){r&&r[Bv](e)},e.getCookieMgr=function(){return o||(o=P_(t,e[Ov])),o},e.setCookieMgr=function(e){o=e},e[BS]=function(){if(!a&&!s&&Vy(t.enablePerfMgr)){var i=Vy(t[AS]);my(i)&&(s=i(e,e[Rv]()))}return a||s||null},e.setPerfMgr=function(e){a=e},e.eventCnt=function(){return n[Nv]},e.releaseQueue=function(){if(i&&n[Nv]>0){var e=n;n=[],Ry(e,(function(e){T()[xv](e)}))}},e.pollInternalLogs=function(e){f=e||null;var i=Vy(t.diagnosticLogInterval);return i&&i>0||(i=1e4),_&&clearInterval(_),_=setInterval((function(){A()}),i)},e[Vv]=function(){_&&(clearInterval(_),_=0,A())},jy(e,(function(){return m}),["addTelemetryInitializer"]),e.unload=function(t,n,r){var a;void 0===t&&(t=!0),i||$y("SDK is not initialized"),g&&$y(GE);var s=((a={reason:50})[Jv]=t,a.flushComplete=!1,a),o=ME(w(),e);function l(t){s.flushComplete=t,g=!0,S.run(o,s),e[Vv](),o[xv](s)}o[Hv]((function(){E(),n&&n(s)}),e),P(t,l,6,r)||l(!1)},e[$v]=I,e.addPlugin=function(e,t,i,n){if(!e)return n&&n(!1),void D(HE);var r=I(e[Av]);if(r&&!t)return n&&n(!1),void D("Plugin ["+e[Av]+"] is already loaded!");var a={reason:16};function s(t){c[Pv](e),a.added=[e],b(a),n&&n(!0)}if(r){var o=[r.plugin];R(o,{reason:2,isAsync:!!i},(function(e){e?(a.removed=o,a.reason|=32,s()):n&&n(!1)}))}else s()},e.evtNamespace=function(){return v},e[Gv]=P,e.getTraceCtx=function(e){return C||(C=function(e){var t={};return{getName:function(){return t[wv]},setName:function(i){e&&e.setName(i),t[wv]=i},getTraceId:function(){return t[ES]},setTraceId:function(i){e&&e.setTraceId(i),SE(i)&&(t[ES]=i)},getSpanId:function(){return t[TS]},setSpanId:function(i){e&&e.setSpanId(i),yE(i)&&(t[TS]=i)},getTraceFlags:function(){return t[bS]},setTraceFlags:function(i){e&&e.setTraceFlags(i),t[bS]=i}}}()),C},e.setTraceCtx=function(e){C=e||null},Gy(e,"addUnloadCb",(function(){return S}),"add")}))}return e.__ieDyn=1,e}();function KE(e,t,i,n){Ry(e,(function(e){if(e&&e[t])if(i)setTimeout((function(){return n(e)}),0);else try{n(e)}catch(e){}}))}var JE,YE,QE=function(){function e(t){this.listeners=[];var i=!!(t||{}).perfEvtsSendAll;bv(e,this,(function(e){e[Uv]=function(t){e.listeners[Pv](t)},e[Bv]=function(t){for(var i=Ay(e[vS],t);i>-1;)e.listeners[zv](i,1),i=Ay(e[vS],t)},e[OS]=function(t){KE(e[vS],OS,!0,(function(e){e[OS](t)}))},e[NS]=function(t,i){KE(e[vS],NS,!0,(function(e){e[NS](t,i)}))},e[LS]=function(t,i){KE(e[vS],LS,i,(function(e){e[LS](t,i)}))},e[xS]=function(t){t&&(!i&&t[SS]()||KE(e[vS],xS,!1,(function(e){t[Jv]?setTimeout((function(){return e[xS](t)}),0):e[xS](t)})))}}))}return e.__ieDyn=1,e}(),ZE=function(e){function t(){var i=e.call(this)||this;return bv(t,i,(function(e,t){function i(t){var i=e[Rv]();i&&i[NS]([t],2)}e[Iv]=function(e,i,n,r){t[Iv](e,i,n||new BC(e),r||new QE(e))},e.track=function(n){JC(e[BS](),(function(){return"AppInsightsCore:track"}),(function(){null===n&&(i(n),$y("Invalid telemetry item")),function(e){uy(e[wv])&&(i(e),$y("telemetry name required"))}(n),t.track(n)}),(function(){return{item:n}}),!n.sync)}})),i}return jf(t,e),t.__ieDyn=1,t}(qE),XE="Failed",eT=XE+"MonitorAjax",tT="Track",iT="Start",nT="Stop",rT="Event",aT="AuthContext",sT="Exception",oT="Local",lT="Session",cT="Storage",dT="Browser",uT="Cannot",hT="Buffer",pT="InstrumentationKey",gT=(qy({CRITICAL:1,WARNING:2}),qy(((JE={})[dT+"DoesNotSupport"+oT+cT]=0,JE[dT+uT+"Read"+oT+cT]=1,JE[dT+uT+"Read"+lT+cT]=2,JE[dT+uT+"Write"+oT+cT]=3,JE[dT+uT+"Write"+lT+cT]=4,JE[dT+XE+"RemovalFrom"+oT+cT]=5,JE[dT+XE+"RemovalFrom"+lT+cT]=6,JE[uT+"SendEmptyTelemetry"]=7,JE.ClientPerformanceMathError=8,JE["ErrorParsingAI"+lT+"Cookie"]=9,JE.ErrorPVCalc=10,JE[sT+"WhileLoggingError"]=11,JE[XE+"AddingTelemetryTo"+hT]=12,JE[eT+"Abort"]=13,JE[eT+"Dur"]=14,JE[eT+"Open"]=15,JE[eT+"RSC"]=16,JE[eT+"Send"]=17,JE[eT+"GetCorrelationHeader"]=18,JE[XE+"ToAddHandlerForOnBeforeUnload"]=19,JE[XE+"ToSendQueuedTelemetry"]=20,JE[XE+"ToReportDataLoss"]=21,JE["Flush"+XE]=22,JE.MessageLimitPerPVExceeded=23,JE.MissingRequiredFieldSpecification=24,JE.NavigationTimingNotSupported=25,JE.OnError=26,JE[lT+"RenewalDateIsZero"]=27,JE.SenderNotInitialized=28,JE[iT+tT+rT+XE]=29,JE[nT+tT+rT+XE]=30,JE[iT+tT+XE]=31,JE[nT+tT+XE]=32,JE.TelemetrySampledAndNotSent=33,JE[tT+rT+XE]=34,JE[tT+sT+XE]=35,JE[tT+"Metric"+XE]=36,JE[tT+"PV"+XE]=37,JE[tT+"PV"+XE+"Calc"]=38,JE[tT+"Trace"+XE]=39,JE["Transmission"+XE]=40,JE[XE+"ToSet"+cT+hT]=41,JE[XE+"ToRestore"+cT+hT]=42,JE.InvalidBackendResponse=43,JE[XE+"ToFixDepricatedValues"]=44,JE.InvalidDurationValue=45,JE.TelemetryEnvelopeInvalid=46,JE.CreateEnvelopeError=47,JE[uT+"SerializeObject"]=48,JE[uT+"SerializeObjectNonSerializable"]=49,JE.CircularReferenceDetected=50,JE["Clear"+aT+XE]=51,JE[sT+"Truncated"]=52,JE.IllegalCharsInName=53,JE.ItemNotInArray=54,JE.MaxAjaxPerPVExceeded=55,JE.MessageTruncated=56,JE.NameTooLong=57,JE.SampleRateOutOfRange=58,JE["Set"+aT+XE]=59,JE["Set"+aT+XE+"AccountName"]=60,JE.StringValueTooLong=61,JE.StartCalledMoreThanOnce=62,JE.StopCalledWithoutStart=63,JE["TelemetryInitializer"+XE]=64,JE.TrackArgumentsNotSpecified=65,JE.UrlTooLong=66,JE[lT+cT+hT+"Full"]=67,JE[uT+"AccessCookie"]=68,JE.IdTooLong=69,JE.InvalidEvent=70,JE[eT+"SetRequestHeader"]=71,JE["Send"+dT+"InfoOnUserInit"]=72,JE["Plugin"+sT]=73,JE["Notification"+sT]=74,JE.SnippetScriptLoadFailure=99,JE["Invalid"+pT]=100,JE[uT+"ParseAiBlobValue"]=101,JE.InvalidContentBlob=102,JE[tT+"PageAction"+rT+XE]=103,JE[XE+"AddingCustomDefinedRequestContext"]=104,JE["InMemory"+cT+hT+"Full"]=105,JE[pT+"Deprecation"]=106,JE))),mT=(qy({NotSet:0,Pii_DistinguishedName:1,Pii_GenericData:2,Pii_IPV4Address:3,Pii_IPv6Address:4,Pii_MailSubject:5,Pii_PhoneNumber:6,Pii_QueryString:7,Pii_SipAddress:8,Pii_SmtpAddress:9,Pii_Identity:10,Pii_Uri:11,Pii_Fqdn:12,Pii_IPV4AddressLegacy:13,CustomerContent_GenericContent:32}),qy({Normal:1,CostDeferred:2,RealTime:3,Immediate:4})),fT=(qy({Unspecified:0,String:1,Int32:2,UInt32:3,Int64:4,UInt64:5,Double:6,Bool:7,Guid:8,DateTime:9}),qy({Normal:1,Critical:2})),vT=(qy({NONE:0,ERROR:1,WARNING:2,INFORMATION:3}),Ly($f($f({},gT),qy({AuthHandShakeError:501,AuthRedirectFail:502,BrowserCannotReadLocalStorage:503,BrowserCannotWriteLocalStorage:504,BrowserDoesNotSupportLocalStorage:505,CannotParseBiBlobValue:506,CannotParseDataAttribute:507,CVPluginNotAvailable:508,DroppedEvent:509,ErrorParsingAISessionCookie:510,ErrorProvidedChannels:511,FailedToGetCookies:512,FailedToInitializeCorrelationVector:513,FailedToInitializeSDK:514,InvalidContentBlob:515,InvalidCorrelationValue:516,SessionRenewalDateIsZero:517,SendPostOnCompleteFailure:518,PostResponseHandler:519,SDKNotInitialized:520}))),""),ST="version",yT="properties",CT="1DS-Web-JS-3.2.9",_T="withCredentials",ET=((YE={})[0]=0,YE[2]=6,YE[1]=1,YE[3]=7,YE[4098]=6,YE[4097]=1,YE[4099]=7,YE);function TT(e){return!(e===vT||uy(e))}function bT(e){if(e){var t=e.indexOf("-");if(t>-1)return e.substring(0,t)}return vT}function IT(e,t,i){var n=-1;if(!dy(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=ET[kT(e)]||-1;-1!==n&&-1!==r?n|=r:6===r&&(n=r)}return n}function wT(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||vT}function RT(e){void 0===e&&(e="D");var t=pE();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,vT)),t}function AT(e,t,i,n,r){var a={},s=!1,o=0,l=arguments.length,c=arguments;for("[object Boolean]"===Object[Pf].toString.call(c[0])&&(s=c[0],o++);o<l;o++)vy(c[o],(function(e,t){s&&t&&gy(t)?_y(t)?(a[e]=a[e]||[],Ry(t,(function(t,i){t&&gy(t)?a[e][i]=AT(!0,a[e][i],t):a[e][i]=t}))):a[e]=AT(!0,a[e],t):a[e]=t}));return a}Boolean(SC()),Boolean(fC());var PT=function(){var e=gC(tC);return e&&e.now?e.now():xy()};function MT(e,t){var i=e;i.timings=i.timings||{},i.timings.processTelemetryStart=i.timings.processTelemetryStart||{},i.timings.processTelemetryStart[t]=PT()}function kT(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===Rf&&(t=4,_y(e)?(t=4096,e.length>0&&(t|=kT(e[0]))):xf.call(e,"value")&&(t=8192|kT(e.value)))}return t}var DT=function(e){function t(){var i=e.call(this)||this;return i.pluginVersionStringArr=[],bv(t,i,(function(e,t){e.logger&&e.logger.queue||(e.logger=new BC({loggingLevelConsole:1})),e.initialize=function(i,n,r,a){JC(e,(function(){return"AppInsightsCore.initialize"}),(function(){var s=e.pluginVersionStringArr;if(i){i.endpointUrl||(i.endpointUrl="https://browser.events.data.microsoft.com/OneCollector/1.0/");var o=i.propertyStorageOverride;!o||o.getProperty&&o.setProperty||$y("Invalid property storage override passed."),i.channels&&Ry(i.channels,(function(e){e&&Ry(e,(function(e){if(e.identifier&&e.version){var t=e.identifier+"="+e.version;s.push(t)}}))}))}e.getWParam=function(){return"undefined"!=typeof document||i.enableWParam?0:-1},n&&Ry(n,(function(e){if(e&&e.identifier&&e.version){var t=e.identifier+"="+e.version;s.push(t)}})),e.pluginVersionString=s.join(";"),e.pluginVersionStringArr=s;try{t.initialize(i,n,r,a),e.pollInternalLogs("InternalLog")}catch(t){var l=e.logger,c=wC(t);-1!==c.indexOf("channels")&&(c+="\n - Channels must be provided through config.channels only!"),HC(l,1,514,"SDK Initialization Failed - no telemetry will be sent: "+c)}}),(function(){return{config:i,extensions:n,logger:r,notificationManager:a}}))},e.track=function(i){JC(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n.timings=n.timings||{},n.timings.trackStart=PT(),function(e){return!!(e&&Ty(e)&&e>=1&&e<=4)}(n.latency)||(n.latency=1);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=CT;var a=n.baseData=n.baseData||{};a[yT]=a[yT]||{};var s=a[yT];s[ST]=s[ST]||e.pluginVersionString||vT}t.track(n)}),(function(){return{item:i}}),!i.sync)}})),i}return jf(t,e),t.__ieDyn=1,t}(ZE),OT=DT,NT=my;function LT(e,t,i){return function(n){e[t]=n,i()}}var xT=function(){function e(t){var i=0,n=null,r=[];function a(t,a,o,l){r.push((function(){var r;try{(r=1===i?NT(t)?t(n):n:NT(a)?a(n):n)instanceof e?r.then(o,l):2!==i||NT(a)?o(r):l(r)}catch(e){return void l(e)}})),0!==i&&s()}function s(){if(r.length>0){var e=r.slice();r=[],setTimeout((function(){for(var t=0,i=e.length;t<i;++t)try{e[t]()}catch(e){}}),0)}}function o(e){0===i&&(n=e,i=1,s())}function l(e){0===i&&(n=e,i=2,s())}bv(e,this,(function(t){t.then=function(t,i){return new e((function(e,n){a(t,i,e,n)}))},t.catch=function(e){return t.then(null,e)}})),function(){if(!NT(t))throw new TypeError("ESPromise: resolvedFunc argument is not a Function");try{t(o,l)}catch(e){l(e)}}()}return e.resolve=function(t){return t instanceof e?t:t&&NT(t.then)?new e((function(e,i){try{t.then(e,i)}catch(e){i(e)}})):new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,i){i(t)}))},e.all=function(t){if(t&&t.length)return new e((function(e,i){try{for(var n=[],r=0,a=0;a<t.length;a++){var s=t[a];s&&NT(s.then)?(r++,s.then(LT(n,a,(function(){0==--r&&e(n)})),i)):n[a]=s}0===r&&setTimeout((function(){e(n)}),0)}catch(e){i(e)}}))},e.race=function(t){return new e((function(e,i){if(t&&t.length)try{for(var n=function(n){var r=t[n];r&&NT(r.then)?r.then(e,i):setTimeout((function(){e(r)}),0)},r=0;r<t.length;r++)n(r)}catch(e){i(e)}}))},e}(),FT=xT,UT=0,BT=[],VT=[],HT=[];function $T(){return(new Date).getTime()}var GT,jT=function(){function e(t,i){var n=0,r=(t||"<unnamed>")+"."+UT;function a(e){var t=Uf();t&&t.QUnit&&console&&console.log("ESPromiseScheduler["+r+"] "+e)}function s(e){$C(i,"ESPromiseScheduler["+r+"] "+e)}UT++,bv(e,this,(function(e){var t=null,i=0;function o(e,t){for(var i=0;i<e.length;i++)if(e[i].id===t)return e.splice(i,1)[0];return null}e.scheduleEvent=function(e,l,c){var d=r+"."+i;i++,l&&(d+="-("+l+")");var u=d+"{"+n+"}";n++;var h={evt:null,tm:$T(),id:u,isRunning:!1,isAborted:!1};return h.evt=t?function(e,t){var i=new FT((function(i,n){var r=$T()-t.tm,s=t.id;a("["+d+"] is waiting for ["+s+":"+r+" ms] to complete before starting -- ["+VT.length+"] waiting and ["+BT.length+"] running"),e.abort=function(t){e.abort=null,o(VT,d),e.isAborted=!0,n(new Error(t))},t.evt.then((function(t){o(VT,d),S(e).then(i,n)}),(function(t){o(VT,d),S(e).then(i,n)}))}));return VT.push(e),i}(h,t):S(h),(t=h).evt._schId=u,h.evt;function p(e){for(var t=$T(),i=t-6e5,n=e.length,r=0;r<n;){var a=e[r];if(a&&a.tm<i){var o=null;a.abort?(o="Aborting ["+a.id+"] due to Excessive runtime ("+(t-a.tm)+" ms)",a.abort(o)):o="Removing ["+a.id+"] due to Excessive runtime ("+(t-a.tm)+" ms)",s(o),e.splice(r,1),n--}else r++}}function g(e,i){var n=!1,r=o(BT,e);if(r||(r=o(HT,e),n=!0),r){r.to&&(clearTimeout(r.to),r.to=null);var l=$T()-r.tm;i?n?s("Timed out event ["+e+"] finally complete -- "+l+" ms"):a("Promise ["+e+"] Complete -- "+l+" ms"):(HT.push(r),s("Event ["+e+"] Timed out and removed -- "+l+" ms"))}else a("Failed to remove ["+e+"] from running queue");t&&t.id===e&&(t=null),p(BT),p(VT),p(HT)}function m(e,t){return function(i){return g(e,!0),t&&t(i),i}}function f(e,t,i,n){t.then((function(t){return t instanceof FT?(a("Event ["+e+"] returned a promise -- waiting"),f(e,t,i,n),t):m(e,i)(t)}),m(e,n))}function v(e,t){var i=e.id;return new FT((function(n,r){a("Event ["+i+"] Starting -- waited for "+(e.wTm||"--")+" ms"),e.isRunning=!0,e.abort=function(t){e.abort=null,e.isAborted=!0,g(i,!1),r(new Error(t))};var s=t(i);s instanceof FT?(c&&(e.to=setTimeout((function(){g(i,!1),r(new Error("Timed out after ["+c+"] ms"))}),c)),f(i,s,(function(t){a("Event ["+i+"] Resolving after "+($T()-e.tm)+" ms"),n(t)}),r)):(a("Promise ["+i+"] Auto completed as the start action did not return a promise"),n())}))}function S(t){var i=$T();return t.wTm=i-t.tm,t.tm=i,t.isAborted?FT.reject(new Error("["+d+"] was aborted")):(BT.push(t),v(t,e))}}}))}return e.incomplete=function(){return BT},e.waitingToStart=function(){return VT},e}(),zT="locale",WT="ver",qT="name",KT=Ky({UserExt:[0,"user"],DeviceExt:[1,"device"],TraceExt:[2,"trace"],WebExt:[3,"web"],AppExt:[4,"app"],OSExt:[5,"os"],SdkExt:[6,"sdk"],IntWebExt:[7,"intweb"],UtcExt:[8,"utc"],LocExt:[9,"loc"],CloudExt:[10,"cloud"],DtExt:[11,"dt"]}),JT=Ky({id:[0,"id"],ver:[1,WT],appName:[2,qT],locale:[3,zT],expId:[4,"expId"],env:[5,"env"]}),YT=Ky({domain:[0,"domain"],browser:[1,"browser"],browserVer:[2,"browserVer"],screenRes:[3,"screenRes"],userConsent:[4,"userConsent"],consentDetails:[5,"consentDetails"]}),QT=Ky({locale:[0,zT],localId:[1,"localId"],id:[2,"id"]}),ZT=Ky({osName:[0,qT],ver:[1,WT]}),XT=Ky({ver:[0,WT],seq:[1,"seq"],installId:[2,"installId"],epoch:[3,"epoch"]}),eb=Ky({msfpc:[0,"msfpc"],anid:[1,"anid"],serviceName:[2,"serviceName"]}),tb=Ky({popSample:[0,"popSample"],eventFlags:[1,"eventFlags"]}),ib=Ky({tz:[0,"tz"]}),nb=Ky({sessionId:[0,"sesId"]}),rb=Ky({localId:[0,"localId"],deviceClass:[1,"deviceClass"],make:[2,"make"],model:[3,"model"]}),ab=Ky({role:[0,"role"],roleInstance:[1,"roleInstance"],roleVer:[2,"roleVer"]}),sb=Ky({traceId:[0,"traceID"],traceName:[1,qT],parentId:[2,"parentID"]}),ob=Ky({traceId:[0,"traceId"],spanId:[1,"spanId"],traceFlags:[2,"traceFlags"]});function lb(){return void 0===GT&&(GT=!!db(0)),GT}function cb(){return lb()?db(0):null}function db(e){var t,i,n=null;try{var r=Uf();if(!r)return null;i=new Date,(n=0===e?r.localStorage:r.sessionStorage)&&my(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}function ub(){return this.getId()}function hb(e){this.setId(e)}var pb=function(){function e(){bv(e,this,(function(e){e.setId=function(t){e.customId=t},e.getId=function(){return Ey(e.customId)?e.customId:e.automaticId}}))}return e._staticInit=void Oy(e.prototype,"id",ub,hb),e}(),gb="ai_session",mb=function(){function e(t,i){var n,r,a=UC(t),s=A_(t);bv(e,this,(function(t){var o=function(e){return{sessionRenewalMs:e.sessionRenewalMs&&function(){return e.sessionRenewalMs},sessionExpirationMs:e.sessionExpirationMs&&function(){return e.sessionExpirationMs},cookieDomain:e.cookieDomain&&function(){return e.cookieDomain},namePrefix:e.namePrefix&&function(){return e.namePrefix},sessionAsGuid:function(){return e.sessionAsGuid},idLength:function(){return e.idLength?e.idLength:22}}}(i);function l(){var e=s.get(r());if(e&&my(e.split))c(e);else{var i=function(e,t){var i=cb();if(null!==i)try{return i.getItem(t)}catch(t){GT=!1,HC(e,1,503,"Browser failed read of local storage. "+t)}return null}(a,r());i&&c(i)}t.automaticSession.getId()||d()}function c(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){HC(a,1,510,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&HC(a,2,517,"AI session renewal date is 0, session will be reset.")}function d(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid();!dy(n)&&n?by(n)?e.setId(RT()):e.setId(RT(n)):e.setId(n_(o&&o.idLength?o.idLength():22)),e.acquisitionDate=i,e.renewalDate=i,u(e.getId(),e.acquisitionDate,e.renewalDate),lb()||HC(a,2,505,"Browser does not support local storage. Session durations will be inaccurate.")}function u(e,i,a){var o=i+t.config.sessionExpirationMs(),l=a+t.config.sessionRenewalMs(),c=new Date,d=[e,i,a];o<l?c.setTime(o):c.setTime(l);var u=t.config.cookieDomain?t.config.cookieDomain():null;s.set(r(),d.join("|")+";expires="+c.toUTCString(),null,u),n=(new Date).getTime()}function h(e,t,i){!function(e,t,i){var n=cb();if(null!==n)try{return n.setItem(t,i),!0}catch(t){GT=!1,HC(e,1,504,"Browser failed write to local storage. "+t)}}(a,r(),[e,t,i].join("|"))}my(i.sessionExpirationMs)||(o.sessionExpirationMs=function(){return e.acquisitionSpan}),my(i.sessionRenewalMs)||(o.sessionRenewalMs=function(){return e.renewalSpan}),t.config=o,r=function(){return t.config.namePrefix&&t.config.namePrefix()?gb+t.config.namePrefix():gb},t.automaticSession=new pb,t.update=function(){t.automaticSession.getId()||l();var i=t.automaticSession,r=t.config,a=(new Date).getTime(),s=a-i.acquisitionDate>r.sessionExpirationMs(),o=a-i.renewalDate>r.sessionRenewalMs();s||o?d():(!n||a-n>e.cookieUpdateInterval)&&(i.renewalDate=a,u(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;h(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.acquisitionSpan=864e5,e.renewalSpan=18e5,e.cookieUpdateInterval=6e4,e}(),fb=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function vb(e,t){void 0===t&&(t=fb);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)Sb(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function Sb(e,t){if(void 0===t&&(t=fb),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}function yb(){return this.getExpId()}var Cb=function(){function e(t,i){var n=null,r=fb.slice(0),a=A_(i),s=t;bv(e,this,(function(e){if(vC()){var i=SC().documentElement;i&&(e.locale=i.lang)}function o(e){e!==n&&(n=vb(e,r))}e.env=t.env?t.env:function(e){var t,i={},n=SC();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var a=t[r];a.name&&0===a.name.toLowerCase().indexOf(e)&&(i[a.name.replace(e,"")]=a.content)}}return i}("awa-").env,e.getExpId=function(){return s.expId?function(e){return o(e),n}(s.expId):(o(wT(a,"Treatments")),n)}}))}return e.validateAppExpId=vb,e._staticInit=void Oy(e.prototype,"expId",yb),e}(),_b=function(){},Eb=function(){};function Tb(){return this.getMsfpc()}function bb(){return this.getAnid()}var Ib=function(){function e(t,i){var n=A_(i);bv(e,this,(function(e){t.serviceName&&(e.serviceName=t.serviceName),e.getMsfpc=function(){return wT(n,"MSFPC")},e.getAnid=function(){return wT(n,"ANON").slice(0,34)}}))}var t;return e._staticInit=(Oy(t=e.prototype,"msfpc",Tb),void Oy(t,"anid",bb)),e}(),wb=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},Rb={WIN:/(windows|win32)/i,WINRT:/ arm;/i,WINPHONE:/windows\sphone\s\d+\.\d+/i,OSX:/(macintosh|mac os x)/i,IOS:/(ipad|iphone|ipod)(?=.*like mac os x)/i,LINUX:/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,ANDROID:/android/i,CROS:/CrOS/i},Ab={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},Pb="([\\d,.]+)",Mb="([\\d,_,.]+)",kb="Unknown",Db=[{r:Rb.WINPHONE,os:"Windows Phone"},{r:Rb.WINRT,os:"Windows RT"},{r:Rb.WIN,os:"Windows"},{r:Rb.IOS,os:"iOS"},{r:Rb.ANDROID,os:"Android"},{r:Rb.LINUX,os:"Linux"},{r:Rb.CROS,os:"Chrome OS"},{s:"x11",os:"Unix"},{s:"blackberry",os:"BlackBerry"},{s:"symbian",os:"Symbian"},{s:"nokia",os:"Nokia"},{r:Rb.OSX,os:"Mac OS X"}];function Ob(e,t){return"Windows"===t?Nb(e,"Windows NT"):"Android"===t?Nb(e,t):"Mac OS X"===t?function(e){var t=e.match(new RegExp("Mac OS X "+Mb));if(t){var i=t[1].replace(/_/g,".");if(i){var n=Lb(i);return n?i.split(n)[0]:i}}return kb}(e):"iOS"===t?function(e){var t=e.match(new RegExp("OS "+Mb));if(t){var i=t[1].replace(/_/g,".");if(i){var n=Lb(i);return n?i.split(n)[0]:i}}return kb}(e):kb}function Nb(e,t){var i=e.match(new RegExp(t+" "+Pb));return i?Ab[i[1]]?Ab[i[1]]:i[1]:kb}function Lb(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null}var xb=function(e){if(e.populateOperatingSystemInfo){var t=this,i=CC()||{},n=e.userAgent||i.userAgent||"",r=e.userAgentData||i.userAgentData||{};if(n){var a=function(e){for(var t=0;t<Db.length;t++){var i=Db[t];if(i.r&&e.match(i.r))return i.os;if(i.s&&-1!==e.indexOf(i.s))return i.os}return kb}(n.toLowerCase());t.name=a,t.ver=Ob(n,a)}t.name&&t.name!==kb||!Ey(r.platform)||(t.name=r.platform)}},Fb="MicrosoftApplicationsTelemetryDeviceId";var Ub=function(){function e(t,i){var n=0;bv(e,this,(function(e){var r=t.propertyStorageOverride;e.seq=n,e.epoch=i_(!1).toString();var a=A_(i,t);if(a.isEnabled()||r){var s=function(e,t,i){return t?t.getProperty(i)||"":wT(e,i)}(a,r,Fb);s||(s=pE()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(a,r,Fb,s),e.installId=s}else a.purge(Fb);e.getSequenceId=function(){return++n}}))}return e.__ieDyn=1,e}(),Bb=function(e,t,i,n){var r=this;if(r.traceId=t||gE(),e.enableDistributedTracing&&!i&&(i=gE().substring(0,16)),r.parentId=i,e.enableApplicationInsightsTrace){r.name=n;var a=_C();a&&a.pathname&&(r.name=a.pathname)}},Vb="setLocalId";function Hb(){return this.getLocalId()}function $b(e){this[Vb](e)}var Gb=function(){function e(t,i,n){var r,a=i,s=A_(n,t);bv(e,this,(function(i){if(s&&s.isEnabled()&&(h(),a.enableApplicationInsightsUser)){var n=wT(s,e.userCookieName);if(n){var o=n.split(e.cookieSeparator);o.length>0&&(i.id=o[0])}if(!i.id){i.id=n_(t&&!dy(t.idLength)?t.idLength:22);var l=wy(new Date);i.accountAcquisitionDate=l;var c=[i.id,l],d=a.cookieDomain?a.cookieDomain:void 0;s.set(e.userCookieName,c.join(e.cookieSeparator),31536e3,d)}}if("undefined"!=typeof navigator){var u=navigator;i.locale=u.userLanguage||u.language}function h(){if(!a.hashIdentifiers&&!a.dropIdentifiers){var e=wT(s,"MUID");e&&(r="t:"+e)}return r}i.getLocalId=function(){return r||h()},i[Vb]=function(e){r=e}}))}return e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void Oy(e.prototype,"localId",Hb,$b),e}(),jb=function(e){var t=this;t.popSample=100,t.eventFlags=0,e.hashIdentifiers&&(t.eventFlags=1048576|t.eventFlags),e.dropIdentifiers&&(t.eventFlags=2097152|t.eventFlags)},zb="([\\d,.]+)",Wb="Unknown",qb="Edg/",Kb=[{ua:"OPR/",b:"Opera"},{ua:"PhantomJS",b:"PhantomJS"},{ua:"Edge",b:"Edge"},{ua:qb,b:"Edge"},{ua:"Electron",b:"Electron"},{ua:"Chrome",b:"Chrome"},{ua:"Trident",b:"MSIE"},{ua:"MSIE ",b:"MSIE"},{ua:"Firefox",b:"Firefox"},{ua:"Safari",b:"Safari"},{ua:"SkypeShell",b:"SkypeShell"}],Jb=[{br:"Microsoft Edge",b:"Edge"},{br:"Google Chrome",b:"Chrome"},{br:"Opera",b:"Opera"}];function Yb(e,t){return t.indexOf(e)>-1}function Qb(e,t){for(var i=0;i<t.length;i++)if(e==t[i].brand)return t[i].version;return null}function Zb(e,t){return"MSIE"===t?function(e){var t=e.match(new RegExp("MSIE "+zb));if(t)return t[1];var i=e.match(new RegExp("rv:"+zb));return i?i[1]:void 0}(e):function(e,t){"Safari"===e?e="Version":"Edge"===e&&Yb(qb,t)&&(e="Edg");var i=t.match(new RegExp(e+"/"+zb));return i||"Opera"===e&&(i=t.match(new RegExp("OPR/"+zb)))?i[1]:Wb}(t,e)}function Xb(){return this.getUserConsent()}var eI=function(){function e(t,i){var n=A_(i),r=t||{};bv(e,this,(function(e){var t=_C();if(t){var i=t.hostname;i&&(e.domain="file:"===t.protocol?"local":i)}if(r.populateBrowserInfo){var a=r.userAgent,s=(r.userAgentData||{}).brands,o=CC();o&&(a=a||o.userAgent||"",s=s||(o.userAgentData||{}).brands),function(t,i){if(_y(i))try{for(var n=0;n<Jb.length;n++){var r=Qb(Jb[n].br,i);if(r)return e.browser=Jb[n].b,void(e.browserVer=r)}}catch(e){}if(t){var a=function(e){if(e)for(var t=0;t<Kb.length;t++)if(Yb(Kb[t].ua,e))return Kb[t].b;return Wb}(t);e.browser=a,e.browserVer=Zb(t,a)}}(a,s);var l=function(){var e={h:0,w:0},t=fC();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e}();e.screenRes=l.w+"X"+l.h}e.getUserConsent=function(){return r.userConsented||!!wT(n,r.userConsentCookieName||"MSCC")},e.getUserConsentDetails=function(){try{var e=r.callback;if(e&&e.userConsentDetails){var t=e.userConsentDetails();if(t)return JSON.stringify({Required:t.Required||!1,Analytics:t.Analytics||!1,SocialMedia:t.SocialMedia||!1,Advertising:t.Advertising||!1})}}catch(e){}return null},Oy(e,"userConsent",e.getUserConsent)}))}return e._staticInit=void Oy(e.prototype,"userConsent",Xb),e}();function tI(e,t,i,n,r){var a=t.ext[KT[e]];return a&&vy(n,(function(e,t){if(Ey(t)||Ty(t)||by(t)){var n=a[i[e]];!r&&(n||Ey(n)||Ty(n)||by(n))&&(t=n),a[i[e]]=t}})),a}var iI=function(){function e(t,i,n){bv(e,this,(function(e){e.app=new Cb(i,n),e.cloud=new _b,e.user=new Gb(t,i,n),e.os=new xb(i),e.web=new eI(i,n);var r=new Ub(t,n),a=new Ib(i,n),s=new jb(i);e.loc=new wb,e.device=new Eb;var o=new mb(n,i);e.session=new pb;var l=function(e,t){var i=e||{};return{getName:function(){return i.name},setName:function(e){t&&t.setName(e),i.name=e},getTraceId:function(){return i.traceId},setTraceId:function(e){t&&t.setTraceId(e),SE(e)&&(i.traceId=e)},getSpanId:function(){return i.parentId},setSpanId:function(e){t&&t.setSpanId(e),yE(e)&&(i.parentId=e)},getTraceFlags:function(){return i.traceFlags},setTraceFlags:function(e){t&&t.setTraceFlags(e),i.traceFlags=e}}}(new Bb(i),u()),c=!(i||{}).eventContainExtFields;function d(){var t=e.session;if(t&&Ey(t.customId))return t.customId;o.update();var i=o.automaticSession;if(i){var n=i.getId();n&&Ey(n)&&(t.automaticId=n)}return t.automaticId}function u(){var e=l;return n&&n.getTraceCtx&&(e=n.getTraceCtx(!1)||l),e}e.getTraceCtx=function(){return l},e.getSessionId=d,e.applyApplicationContext=function(t){var i,n=e.app;tI(4,t,JT,((i={})[0]=n.id,i[1]=n.ver,i[2]=n.name,i[3]=n.locale,i[4]=n.getExpId(),i[5]=n.env,i),c)},e.applyUserContext=function(t){var i,n=e.user;tI(0,t,QT,((i={})[1]=n.getLocalId(),i[0]=n.locale,i[2]=n.id,i),c)},e.applyWebContext=function(t){var i,n=e.web;tI(3,t,YT,((i={})[0]=n.domain,i[1]=n.browser,i[2]=n.browserVer,i[3]=n.screenRes,i[5]=n.getUserConsentDetails(),i[4]=n.getUserConsent(),i),c)},e.applyOsContext=function(t){var i,n=e.os;tI(5,t,ZT,((i={})[0]=n.name,i[1]=n.ver,i),c)},e.applySdkContext=function(e){var t;tI(6,e,XT,((t={})[2]=r.installId,t[1]=r.getSequenceId(),t[3]=r.epoch,t),c)},e.applyIntWebContext=function(e){var t;tI(7,e,eb,((t={})[0]=a.getMsfpc(),t[1]=a.getAnid(),t[2]=a.serviceName,t),c)},e.applyUtcContext=function(e){var t,i=((t={})[0]=s.popSample,t);s.eventFlags>0&&(i[1]=s.eventFlags),tI(8,e,tb,i,c)},e.applyLocContext=function(t){var i;tI(9,t,ib,((i={})[0]=e.loc.tz,i),c)},e.applySessionContext=function(e){var t;tI(4,e,nb,((t={})[0]=d(),t),c)},e.applyDeviceContext=function(t){var i,n=e.device;tI(1,t,rb,((i={})[0]=n.localId,i[2]=n.make,i[3]=n.model,i[1]=n.deviceClass,i),c)},e.applyCloudContext=function(t){var i,n=e.cloud;tI(10,t,ab,((i={})[0]=n.role,i[1]=n.roleInstance,i[2]=n.roleVer,i),c)},e.applyAITraceContext=function(e){var t;if(i.enableApplicationInsightsTrace){var n=u();n&&tI(2,e,sb,((t={})[0]=n.getTraceId(),t[1]=n.getName(),t[2]=n.getSpanId(),t),!1)}},e.applyDistributedTraceContext=function(e){var t,i=u();if(i){var n=((t={})[0]=i.getTraceId(),t[1]=i.getSpanId(),t),r=i.getTraceFlags();uy(r)||(n[2]=r),tI(11,e,ob,n,!1)}}}))}return e.__ieDyn=1,e}();var nI=[KT[4],KT[0],KT[3],KT[5],KT[6],KT[7],KT[8],KT[9],KT[1],KT[2],KT[11],KT[10]],rI=function(e){function t(){var i,n,r,a=e.call(this)||this;return a.identifier="SystemPropertiesCollector",a.priority=3,a.version="3.2.9",bv(t,a,(function(e,t){function a(){i=null,n={}}a(),e.initialize=function(n,a,s){t.initialize(n,a,s),r=e._getTelCtx().getExtCfg(e.identifier),i=new iI(n,r,a),a&&a.setTraceCtx&&a.setTraceCtx(i.getTraceCtx())},e.processTelemetry=function(t,a){MT(t,e.identifier),a=e._getTelCtx(a);var s=t.ext=t.ext?t.ext:{};t.data=t.data?t.data:{},Ry(nI,(function(e){s[e]=s[e]||{}})),i&&(i.applyApplicationContext(t),i.applyUserContext(t),i.applyWebContext(t),i.applyOsContext(t),i.applySdkContext(t),i.applyIntWebContext(t),i.applyUtcContext(t),i.applyLocContext(t),i.applySessionContext(t),i.applyDeviceContext(t),r.enableApplicationInsightsTrace&&i.applyAITraceContext(t),r.enableDistributedTracing&&i.applyDistributedTraceContext(t),i.applyCloudContext(t)),Ry(Dy(s),(function(e){0===Dy(s[e]).length&&delete s[e]})),function(e,t){e&&vy(e,(function(e,i){t[e]||(t[e]=i)}))}(n,t.data),e.processNext(t,a)},e.getPropertiesContext=function(){return i},e.setProperty=function(e,t){n[e]=t},e._doTeardown=function(e,t){var n=(e||{}).core();if(n&&n.getTraceCtx&&i){var r=n.getTraceCtx(!1);r&&r===i.getTraceCtx()&&n.setTraceCtx(null)}a()}})),a}return jf(t,e),t.__ieDyn=1,t}(BE),aI=function(e){this._setOverride=function(t,i){e.setOverride(t,i)},this._getOverride=function(t){return e.getOverride(t)}},sI=function(e){function t(t,i){var n=e.call(this,t)||this,r=n;return r.setId=function(e){r._setOverride(JT.id,e)},r.getId=function(){return r._getOverride(JT.id)},r.setVer=function(e){r._setOverride(JT.ver,e)},r.getVer=function(){return r._getOverride(JT.ver)},r.setName=function(e){r._setOverride(JT.appName,e)},r.getName=function(){return r._getOverride(JT.appName)},r.setLocale=function(e){r._setOverride(JT.locale,e)},r.getLocale=function(){return r._getOverride(JT.locale)},r.setEnv=function(e){r._setOverride(JT.env,e)},r.getEnv=function(){return r._getOverride(JT.env)},r.setExpId=function(e){r._setOverride(JT.expId,Cb.validateAppExpId(e))},r.getExpId=function(){return r._getOverride(JT.expId)},i&&(dy(i.env)||r.setEnv(i.env),uy(i.expId)||r.setExpId(i.expId)),n}return jf(t,e),t}(aI),oI=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setRole=function(e){n._setOverride(ab.role,e)},n.getRole=function(){return n._getOverride(ab.role)},n.setRoleInstance=function(e){n._setOverride(ab.roleInstance,e)},n.getRoleInstance=function(){return n._getOverride(ab.roleInstance)},n.setRoleVer=function(e){n._setOverride(ab.roleVer,e)},n.getRoleVer=function(){return n._getOverride(ab.roleVer)},i}return jf(t,e),t}(aI),lI=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setProperty=function(e,t){n._setOverride(e,t)},n.getProperty=function(e){return n._getOverride(e)},i}return jf(t,e),t}(aI),cI=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(rb.localId,e)},n.getLocalId=function(){return n._getOverride(rb.localId)},n.setDeviceClass=function(e){n._setOverride(rb.deviceClass,e)},n.getDeviceClass=function(){return n._getOverride(rb.deviceClass)},n.setMake=function(e){n._setOverride(rb.make,e)},n.getMake=function(){return n._getOverride(rb.make)},n.setModel=function(e){n._setOverride(rb.model,e)},n.getModel=function(){return n._getOverride(rb.model)},i}return jf(t,e),t}(aI),dI=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setTz=function(e){n._setOverride(ib.tz,e)},n.getTz=function(){return n._getOverride(ib.tz)},i}return jf(t,e),t}(aI),uI=function(e){function t(t,i){var n=e.call(this,t)||this,r=n;if(r.setOsName=function(e){r._setOverride(ZT.osName,e)},r.getOsName=function(){return r._getOverride(ZT.osName)},r.setVer=function(e){r._setOverride(ZT.ver,e)},r.getVer=function(){return r._getOverride(ZT.ver)},i&&i.userAgent&&i.populateOperatingSystemInfo){var a=new xb(i);r.setOsName(a.name),r.setVer(a.ver)}return n}return jf(t,e),t}(aI);function hI(e,t){if(e)for(var i=0;i<t.length;i++){var n=t[i];uy(e[n])&&(e[n]={}),e=e[n]}return e}var pI=function(e){var t=this,i=[];t.setOverride=function(e,t){e&&i.push({key:e,value:t})},t.hasOverride=function(e){var t=!1;return Ry(i,(function(i){i.key===e&&(t=!0)})),t},t.getOverride=function(e){var t;return Ry(i,(function(i){i.key===e&&(t=i.value)})),t},t.applyOverrides=function(t,n){if(i.length>0)try{var r=hI(t,e);Ry(i,(function(e){!function(e,t,i){if(e&&t){var n=t.split("."),r=n[n.length-1];n.length>1&&(e=hI(e,n.slice(0,-1))),uy(i)?dy(e[r])||delete e[r]:e[r]=i}}(r,e.key,e.value)}))}catch(e){}}},gI=function(e){function t(t){var i=e.call(this,t)||this,n=i;return n.setLocalId=function(e){n._setOverride(QT.localId,e)},n.getLocalId=function(){return n._getOverride(QT.localId)},n.setLocale=function(e){n._setOverride(QT.locale,e)},n.getLocale=function(){return n._getOverride(QT.locale)},n.setId=function(e){n._setOverride(QT.id,e)},n.getId=function(){return n._getOverride(QT.id)},i}return jf(t,e),t}(aI),mI=function(e){function t(t,i){var n=e.call(this,t)||this,r=n;return r.setDomain=function(e){r._setOverride(YT.domain,e)},r.getDomain=function(){return r._getOverride(YT.domain)},r.setBrowser=function(e){r._setOverride(YT.browser,e)},r.getBrowser=function(){return r._getOverride(YT.browser)},r.setBrowserVer=function(e){r._setOverride(YT.browserVer,e)},r.getBrowserVer=function(){return r._getOverride(YT.browserVer)},r.setScreenRes=function(e){r._setOverride(YT.screenRes,e)},r.getScreenRes=function(){return r._getOverride(YT.screenRes)},r.setUserConsent=function(e){r._setOverride(YT.userConsent,e)},r.getUserContext=function(){return r._getOverride(YT.userConsent)},i&&(dy(i.userConsented)||r.setUserConsent(i.userConsented)),n}return jf(t,e),t}(aI),fI="ext",vI=function(e,t,i){var n=this,r={};function a(e){for(var t="",i=0;i<e.length;i++)t&&(t+="_"),t+=e[i];return dy(r[t])&&(r[t]=new pI(e)),t?r[t]:null}n.data=new lI(a(["data"])),n.app=new sI(a([fI,KT.AppExt]),t),n.user=new gI(a([fI,KT.UserExt])),n.os=new uI(a([fI,KT.OSExt]),t),n.web=new mI(a([fI,KT.WebExt]),t),n.device=new cI(a([fI,KT.DeviceExt])),n.loc=new dI(a([fI,KT.LocExt])),n.cloud=new oI(a([fI,KT.CloudExt])),n.applyOverrides=function(e,t){var i=Dy(r);i&&i.length>0&&Ry(i,(function(i){r[i].applyOverrides(e,t)}))}},SI=function(e){function t(){var i=e.call(this)||this;i.identifier="OverridePropertiesPlugin",i.priority=4,i.version="3.2.9";var n=null;return bv(t,i,(function(e,t){e.initialize=function(i,n,r){t.initialize(i,n,r),e._baseInit(i,n,r)},e.processTelemetry=function(t,n){MT(t,i.identifier),n=e._getTelCtx(n);var r=e.getOverrideContext();r&&r.applyOverrides(t,n),e.processNext(t,n)},e._baseInit=function(e,t,r){n=new vI(e,i._getTelCtx().getExtCfg(i.identifier),t)},e.setProperty=function(e,t){n&&n.data.setProperty(e,t)},e.getOverrideContext=function(){return n}})),i}return jf(t,e),t.__ieDyn=1,t}(BE),yI="REAL_TIME",CI="",_I="POST",EI="drop",TI="send",bI="requeue",II="rspFail",wI="application/x-json-stream",RI="cache-control",AI="content-type",PI="kill-duration",MI="time-delta-millis",kI="client-version",DI="client-id",OI="time-delta-to-apply-millis",NI="upload-time",LI="apikey",xI="AuthMsaDeviceTicket",FI="AuthXToken",UI="msfpc",BI="trace",VI="user";function HI(e){var t=(e.ext||{}).intweb;return t&&TT(t[UI])?t[UI]:null}function $I(e){for(var t=null,i=0;null===t&&i<e.length;i++)t=HI(e[i]);return t}var GI=function(){function e(t,i){var n=i?[].concat(i):[],r=this,a=$I(n);r.iKey=function(){return t},r.Msfpc=function(){return a||CI},r.count=function(){return n.length},r.events=function(){return n},r.addEvent=function(e){return!!e&&(n.push(e),a||(a=HI(e)),!0)},r.split=function(i,r){var s;if(i<n.length){var o=n.length-i;uy(r)||(o=r<o?r:o),s=n.splice(i,o),a=$I(n)}return new e(t,s)}}return e.create=function(t,i){return new e(t,i)},e}(),jI=function(){function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",a=!1;bv(e,this,(function(e){e.allowRequestSending=function(){return t},e.firstRequestSent=function(){n&&(n=!1,a||(t=!1))},e.shouldAddClockSkewHeaders=function(){return i},e.getClockSkewHeaderValue=function(){return r},e.setClockSkew=function(e){a||(e?(r=e,i=!0,a=!0):i=!1,t=!0)}}))}return e.__ieDyn=1,e}(),zI=function(){function e(){var t={};bv(e,this,(function(e){e.setKillSwitchTenants=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&Ry(e,(function(e){t.push(Py(e))})),t}(e.split(","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),a=0;a<n.length;++a)t[n[a]]=xy()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=Py(e);return void 0!==i[n]&&i[n]>xy()||(delete i[n],!1)}}))}return e.__ieDyn=1,e}(),WI=zI;function qI(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)}var KI,JI=2e6,YI=Math.min(JI,65e3),QI="metadata",ZI="f",XI=/\./,ew=function(){function e(t,i,n,r){var a="data",s="baseData",o=!!r,l=i,c={};bv(e,this,(function(e){function i(e,t){var i=c[e];return void 0===i&&(e.length>=7&&(i=yy(e,"ext.metadata")||yy(e,"ext.web")),c[e]=i),i}function r(e,t,a,s,c,d,u){vy(e,(function(e,h){var p=null;if(h||TT(h)){var g=a,m=e,f=c,v=t;if(o&&!s&&XI.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var _=S[C];v=v[_]=v[_]||{},g+="."+_,f&&f.push(_)}m=S[y-1]}}if(p=s&&i(g)||!l||!l.handleField(g,m)?function(e,t,i){if(!t&&!TT(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||_y(t))t={value:t};else if("object"!==n||xf.call(t,"value")){if(uy(t.value)||t.value===vT||!Ey(t.value)&&!Ty(t.value)&&!by(t.value)&&!_y(t.value))return null}else t={value:i?JSON.stringify(t):t};if(_y(t.value)&&!function(e){return e.length>0}(t.value))return null;if(!uy(t.kind)){if(_y(t.value)||!function(e){return 0===e||e>0&&e<=13||32===e}(t.kind))return null;t.value=t.value.toString()}return t}(m,h,n):l.value(g,m,h,n)){var E=p.value;if(v[m]=E,d&&d(f,m,p),u&&"object"==typeof E&&!_y(E)){var T=f;T&&(T=T.slice()).push(m),r(h,E,g+"."+m,s,T,d,u)}}}}))}e.createPayload=function(e,t,i,n,r,a){return{apiKeys:[],payloadBlob:CI,overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendType:a,sendReason:r}},e.appendPayload=function(i,n,r){var a=i&&n&&!i.overflow;return a&&JC(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),a=i.payloadBlob,s=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?YI:JI,p=0,g=0;p<t.length;){var m=t[p];if(m){if(s>=r){i.overflow=n.split(p);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(a.length+v>u){i.overflow=n.split(p);break}a&&(a+="\n"),a+=f,++g>20&&(a.substr(0,1),g=0),o=!0,s++}else f?l.push(m):c.push(m),t.splice(p,1),p--}p++}if(l&&l.length>0&&i.sizeExceed.push(GI.create(n.iKey(),l)),c&&c.length>0&&i.failedEvts.push(GI.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=a,i.numEvents=s;var S=n.iKey();-1===Ay(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),a},e.getEventBlob=function(e){try{return JC(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+bT(e.iKey);var i={},n=e.ext;n&&(t.ext=i,vy(n,(function(e,t){r(t,i[e]={},"ext."+e,!0,null,null,!0)})));var o=t[a]={};o.baseType=e.baseType;var l=o[s]={};return r(e.baseData,l,s,!1,[s],(function(e,t,n){tw(i,e,t,n)}),true),r(e.data,o,a,!1,[],(function(e,t,n){tw(i,e,t,n)}),true),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))}return e.__ieDyn=1,e}();function tw(e,t,i,n){if(n&&e){var r=IT(n.value,n.kind,n.propertyType);if(r>-1){var a=e[QI];a||(a=e[QI]={f:{}});var s=a[ZI];if(s||(s=a[ZI]={}),t)for(var o=0;o<t.length;o++){var l=t[o];s[l]||(s[l]={f:{}});var c=s[l][ZI];c||(c=s[l][ZI]={}),s=c}s=s[i]={},_y(n.value)?s.a={t:r}:s.t=r}}}var iw="sendAttempt",nw="&NoResponseBody=true",rw=((KI={})[1]=bI,KI[100]=bI,KI[200]="sent",KI[8004]=EI,KI[8003]=EI,KI),aw={},sw={};function ow(e,t,i){aw[e]=t,!1!==i&&(sw[t]=e)}function lw(e){try{return e.responseText}catch(e){}return CI}function cw(e,t){var i=!1;if(e&&t){var n=Dy(e);if(n&&n.length>0)for(var r=t.toLowerCase(),a=0;a<n.length;a++){var s=n[a];if(s&&py(t,s)&&s.toLowerCase()===r){i=!0;break}}}return i}function dw(e,t,i,n){t&&i&&i.length>0&&(n&&aw[t]?(e.hdrs[aw[t]]=i,e.useHdrs=!0):e.url+="&"+t+"="+i)}function uw(e,t){return t&&(Ty(t)?e=[t].concat(e):_y(t)&&(e=t.concat(e))),e}ow(xI,xI,!1),ow(kI,kI),ow(DI,"Client-Id"),ow(LI,LI),ow(OI,OI),ow(NI,NI),ow(FI,FI);var hw=function(){function e(t,i,n,r,a){this._responseHandlers=[];var s,o,l,c,d,u,h,p,g,m,f="?cors=true&"+AI.toLowerCase()+"="+wI,v=new WI,S=!1,y=new jI,C=!1,_=0,E=!0,T=[],b={},I=[],w=null,R=!1,A=!1,P=!1;bv(e,this,(function(e){var M=!0;function k(e,t){for(var i=0,n=null,r=0;null==n&&r<e.length;)1===(i=e[r])?(null===uC&&(uC=typeof XDomainRequest!==Af)&&PC()&&(uC=uC&&!pC(gC(oC),"withCredentials")),uC?n=D:PC()&&(n=N)):2===i&&AC(t)&&(!t||t&&!p)?n=O:C&&3===i&&RC()&&(n=x),r++;return n?{_transport:i,_isSync:t,sendPOST:n}:null}function D(e,t,i){var n=new XDomainRequest;n.open(_I,e.urlString),e.timeout&&(n.timeout=e.timeout),n.onload=function(){var e=lw(n);L(t,200,{},e),Y(e)},n.onerror=function(){L(t,400,{})},n.ontimeout=function(){L(t,500,{})},n.onprogress=function(){},i?n.send(e.data):a.set((function(){n.send(e.data)}),0)}function O(e,t,i){var n,r=e.urlString,s=!1,o=!1,l=((n={body:e.data,method:_I}).Microsoft_ApplicationInsights_BypassAjaxInstrumentation=!0,n);i&&(l.keepalive=!0,2===e._sendReason&&(s=!0,m&&(r+=nw))),M&&(l.credentials="include"),e.headers&&Dy(e.headers).length>0&&(l.headers=e.headers),fetch(r,l).then((function(e){var i={},n=CI,r=e.headers;r&&r.forEach((function(e,t){i[t]=e})),e.body&&e.text().then((function(e){n=e})),o||(o=!0,L(t,e.status,i,n),Y(n))})).catch((function(e){o||(o=!0,L(t,0,{}))})),s&&!o&&(o=!0,L(t,200,{})),!o&&e.timeout>0&&a.set((function(){o||(o=!0,L(t,500,{}))}),e.timeout)}function N(e,t,i){var n=e.urlString;function r(e,t,i){if(!e[i]&&t&&t.getResponseHeader){var n=t.getResponseHeader(i);n&&(e[i]=Py(n))}return e}function a(e){var t={};return e.getAllResponseHeaders?t=function(e){var t={};return Ey(e)&&Ry(Py(e).split(/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=Py(e.substring(0,i)).toLowerCase(),r=Py(e.substring(i+1));t[n]=r}else t[Py(e)]=1}})),t}(e.getAllResponseHeaders()):(t=r(t,e,MI),t=r(t,e,PI),t=r(t,e,"kill-duration-seconds")),t}function s(e,i){L(t,e.status,a(e),i)}i&&e.disableXhrSync&&(i=!1);var o=function(e,t,i,n,r,a){function s(e,t,i){try{e[t]=i}catch(e){}}void 0===n&&(n=!1),void 0===r&&(r=!1);var o=new XMLHttpRequest;return n&&s(o,"Microsoft_ApplicationInsights_BypassAjaxInstrumentation",n),i&&s(o,_T,i),o.open(e,t,!r),i&&s(o,_T,i),!r&&a&&s(o,"timeout",a),o}(_I,n,M,!0,i,e.timeout);vy(e.headers,(function(e,t){o.setRequestHeader(e,t)})),o.onload=function(){var e=lw(o);s(o,e),Y(e)},o.onerror=function(){s(o)},o.ontimeout=function(){s(o)},o.send(e.data)}function L(e,t,i,n){try{e(t,i,n)}catch(e){HC(o,2,518,wC(e))}}function x(e,t,i){var n=200,r=e._thePayload,a=e.urlString+(m?nw:CI);try{var s=CC();if(!s.sendBeacon(a,e.data))if(r){var l=[];Ry(r.batches,(function(e){if(l&&e&&e.count()>0){for(var t=e.events(),i=0;i<t.length;i++)if(!s.sendBeacon(a,w.getEventBlob(t[i]))){l.push(e.split(i));break}}else l.push(e.split(0))})),Q(l,8003,r.sendType,!0)}else n=0}catch(e){$C(o,"Failed to send telemetry using sendBeacon API. Ex:"+wC(e)),n=0}finally{L(t,n,{},CI)}}function F(e){return 2===e||3===e}function U(e){return A&&F(e)&&(e=2),e}function B(){return!S&&_<i}function V(){var e=I;return I=[],e}function H(e,t,i){var n=!1;return e&&e.length>0&&!S&&l[t]&&w&&(n=0!==t||B()&&(i>0||y.allowRequestSending())),n}function $(e){var t={};return e&&Ry(e,(function(e,i){t[i]={iKey:e.iKey(),evts:e.events()}})),t}function G(e,i,n,r,a){if(e&&0!==e.length)if(S)Q(e,1,r);else{r=U(r);try{var s=e,d=0!==r;JC(c,(function(){return"HttpManager:_sendBatches"}),(function(s){s&&(e=e.slice(0));for(var o=[],c=null,u=PT(),h=l[r]||(d?l[1]:l[0]),p=h&&h._transport,m=g&&(A||F(r)||3===p||h._isSync&&2===p);H(e,r,i);){var f=e.shift();f&&f.count()>0&&(v.isTenantKilled(f.iKey())?o.push(f):(c=c||w.createPayload(i,n,d,m,a,r),w.appendPayload(c,f,t)?null!==c.overflow&&(e=[c.overflow].concat(e),c.overflow=null,W(c,u,PT(),a),u=PT(),c=null):(W(c,u,PT(),a),u=PT(),e=[f].concat(e),c=null)))}c&&W(c,u,PT(),a),e.length>0&&(I=e.concat(I)),Q(o,8004,r)}),(function(){return{batches:$(s),retryCount:i,isTeardown:n,isSynchronous:d,sendReason:a,useSendBeacon:F(r),sendType:r}}),!d)}catch(e){HC(o,2,48,"Unexpected Exception sending batch: "+wC(e))}}}function j(e,t){var i={url:f,hdrs:{},useHdrs:!1};t?(i.hdrs=AT(i.hdrs,b),i.useHdrs=Dy(i.hdrs).length>0):vy(b,(function(e,t){sw[e]?dw(i,sw[e],t,!1):(i.hdrs[e]=t,i.useHdrs=!0)})),dw(i,DI,"NO_AUTH",t),dw(i,kI,CT,t);var n=CI;Ry(e.apiKeys,(function(e){n.length>0&&(n+=","),n+=e})),dw(i,LI,n,t),dw(i,NI,xy().toString(),t);var r=function(e){for(var t=0;t<e.batches.length;t++){var i=e.batches[t].Msfpc();if(i)return encodeURIComponent(i)}return CI}(e);if(TT(r)&&(i.url+="&ext.intweb.msfpc="+r),y.shouldAddClockSkewHeaders()&&dw(i,OI,y.getClockSkewHeaderValue(),t),c.getWParam){var a=c.getWParam();a>=0&&(i.url+="&w="+a)}for(var s=0;s<T.length;s++)i.url+="&"+T[s].name+"="+T[s].value;return i}function z(e,t,i){e[t]=e[t]||{},e[t][s.identifier]=i}function W(t,i,n,r){if(t&&t.payloadBlob&&t.payloadBlob.length>0){var a=!!e.sendHook,s=l[t.sendType];!F(t.sendType)&&t.isBeacon&&2===t.sendReason&&(s=l[2]||l[3]||s);var d=P;(t.isBeacon||3===s._transport)&&(d=!1);var g=j(t,d);d=d||g.useHdrs;var m=PT();JC(c,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var l=0;l<t.batches.length;l++)for(var f=t.batches[l].events(),v=0;v<f.length;v++){var S=f[v];if(R){var C=S.timings=S.timings||{};z(C,"sendEventStart",m),z(C,"serializationStart",i),z(C,"serializationCompleted",n)}S[iw]>0?S[iw]++:S[iw]=1}Q(t.batches,1e3+(r||0),t.sendType,!0);var T={data:t.payloadBlob,urlString:g.url,headers:g.hdrs,_thePayload:t,_sendReason:r,timeout:u,disableXhrSync:h,disableFetchKeepAlive:p};d&&(cw(T.headers,RI)||(T.headers[RI]="no-cache, no-store"),cw(T.headers,AI)||(T.headers[AI]=wI));var b=null;s&&(b=function(i){y.firstRequestSent();var n=function(e,i){q(e,i,t,r)},a=t.isTeardown||t.isSync;try{s.sendPOST(i,n,a),e.sendListener&&e.sendListener(T,i,a,t.isBeacon)}catch(e){$C(o,"Unexpected exception sending payload. Ex:"+wC(e)),L(n,0,{})}}),JC(c,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(b)if(0===t.sendType&&_++,a&&!t.isBeacon&&3!==s._transport){var i={data:T.data,urlString:T.urlString,headers:AT({},T.headers),timeout:T.timeout,disableXhrSync:T.disableXhrSync,disableFetchKeepAlive:T.disableFetchKeepAlive},n=!1;JC(c,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{e.sendHook(i,(function(e){n=!0,E||e._thePayload||(e._thePayload=e._thePayload||T._thePayload,e._sendReason=e._sendReason||T._sendReason),b(e)}),t.isSync||t.isTeardown)}catch(e){n||b(T)}}))}else b(T)}))}),(function(){return{thePayload:t,serializationStart:i,serializationCompleted:n,sendReason:r}}),t.isSync)}t.sizeExceed&&t.sizeExceed.length>0&&Q(t.sizeExceed,8003,t.sendType),t.failedEvts&&t.failedEvts.length>0&&Q(t.failedEvts,8002,t.sendType)}function q(e,t,i,r){var a=9e3,s=null,o=!1,l=!1;try{var c=!0;if(typeof e!==Af){if(t){y.setClockSkew(t[MI]);var d=t[PI]||t["kill-duration-seconds"];Ry(v.setKillSwitchTenants(t["kill-tokens"],d),(function(e){Ry(i.batches,(function(t){if(t.iKey()===e){s=s||[];var n=t.split(0);i.numEvents-=n.count(),s.push(n)}}))}))}if(200==e||204==e)return void(a=200);(!function(e){return!(e>=300&&e<500&&408!=e&&429!=e||501==e||505==e)}(e)||i.numEvents<=0)&&(c=!1),a=9e3+e%1e3}if(c){a=100;var u=i.retryCnt;0===i.sendType&&(u<n?(o=!0,J((function(){0===i.sendType&&_--,G(i.batches,u+1,i.isTeardown,A?2:i.sendType,5)}),A,qI(u))):(l=!0,A&&(a=8001)))}}finally{o||(y.setClockSkew(),K(i,a,r,l)),Q(s,8004,i.sendType)}}function K(t,i,n,r){try{r&&s._backOffTransmission(),200===i&&(r||t.isSync||s._clearBackOff(),function(e){if(R){var t=PT();Ry(e,(function(e){e&&e.count()>0&&function(e,t){R&&Ry(e,(function(e){z(e.timings=e.timings||{},"sendEventCompleted",t)}))}(e.events(),t)}))}}(t.batches)),Q(t.batches,i,t.sendType,!0)}finally{0===t.sendType&&(_--,5!==n&&e.sendQueuedRequests(t.sendType,n))}}function J(e,t,i){t?e():a.set(e,i)}function Y(t){var i=e._responseHandlers;try{for(var n=0;n<i.length;n++)try{i[n](t)}catch(t){HC(o,1,519,"Response handler failed: "+t)}if(t){var r=JSON.parse(t);TT(r.webResult)&&TT(r.webResult[UI])&&d.set("MSFPC",r.webResult[UI],31536e3)}}catch(t){}}function Q(e,t,i,n){if(e&&e.length>0&&r){var a=r[function(e){var t=rw[e];return TT(t)||(t="oth",e>=9e3&&e<=9999?t=II:e>=8e3&&e<=8999?t=EI:e>=1e3&&e<=1999&&(t=TI)),t}(t)];if(a){var s=0!==i;JC(c,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){J((function(){try{a.call(r,e,t,s,i)}catch(e){HC(o,1,74,"send request notification failed: "+e)}}),n||s,0)}),(function(){return{batches:$(e),reason:t,isSync:s,sendSync:n,sendType:i}}),!s)}}}e.initialize=function(e,t,i,n,r){var a;r||(r={}),f=e+f,P=!!dy(r.avoidOptions)||!r.avoidOptions,c=t,d=t.getCookieMgr(),R=!c.config.disableEventTimings;var v=!!c.config.enableCompoundKey;o=(s=i).diagLog();var S=r.valueSanitizer,y=r.stringifyObjects;dy(r.enableCompoundKey)||(v=!!r.enableCompoundKey),u=r.xhrTimeout,h=!!r.disableXhrSync,p=!!r.disableFetchKeepAlive,m=!1!==r.addNoResponse,C=!bC(),w=new ew(c,S,y,v),uy(r.useSendBeacon)||(C=!!r.useSendBeacon);var _=n,T=r.alwaysUseXhrOverride?n:null,b=r.alwaysUseXhrOverride?n:null,I=[3,2];if(!n){E=!1;var A=_C();A&&A.protocol&&"file:"===A.protocol.toLowerCase()&&(M=!1);var D=[];bC()?(D=[2,1],I=[2,1,3]):D=[1,2,3],(n=k(D=uw(D,r.transports),!1))||$C(o,"No available transport to send events"),_=k(D,!0)}T||(T=k(I=uw(I,r.unloadTransports),!0)),g=!E&&(C&&RC()||!p&&AC(!0)),(a={})[0]=n,a[1]=_||k([1,2,3],!0),a[2]=T||_||k([1],!0),a[3]=b||k([2,3],!0)||_||k([1],!0),l=a},e._getDbgPlgTargets=function(){return[l[0],v,w,l]},e.addQueryStringParameter=function(e,t){for(var i=0;i<T.length;i++)if(T[i].name===e)return void(T[i].value=t);T.push({name:e,value:t})},e.addHeader=function(e,t){b[e]=t},e.canSendRequest=function(){return B()&&y.allowRequestSending()},e.sendQueuedRequests=function(e,t){dy(e)&&(e=0),A&&(e=U(e),t=2),H(I,e,0)&&G(V(),0,!1,e,t||0)},e.isCompletelyIdle=function(){return!S&&0===_&&0===I.length},e.setUnloading=function(e){A=e},e.addBatch=function(e){if(e&&e.count()>0){if(v.isTenantKilled(e.iKey()))return!1;I.push(e)}return!0},e.teardown=function(){I.length>0&&G(V(),0,!0,2,2)},e.pause=function(){S=!0},e.resume=function(){S=!1,e.sendQueuedRequests(0,4)},e.sendSynchronousBatch=function(e,t,i){e&&e.count()>0&&(uy(t)&&(t=1),A&&(t=U(t),i=2),G([e],0,!1,t,i||0))}}))}return e.__ieDyn=1,e}();function pw(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];return setTimeout(e,t,i)}function gw(e){clearTimeout(e)}function mw(e,t){return{set:e||pw,clear:t||gw}}var fw="eventsDiscarded",vw="overrideInstrumentationKey",Sw="maxEventRetryAttempts",yw="maxUnloadEventRetryAttempts",Cw=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="3.2.9";var r,a,s,o,l,c,d,u=!1,h=[],p=null,g=!1,m=0,f=500,v=0,S=1e4,y={},C=yI,_=null,E=null,T=0,b=0,I={},w=-1,R=!0,A=!1,P=6,M=2;return bv(t,n,(function(e,t){function n(e){"beforeunload"!==(e||fC().event).type&&(A=!0,a.setUnloading(A)),B(2,2)}function k(e){A=!1,a.setUnloading(A)}function D(e,t){if(e.sendAttempt||(e.sendAttempt=0),e.latency||(e.latency=1),e.ext&&e.ext[BI]&&delete e.ext[BI],e.ext&&e.ext[VI]&&e.ext[VI].id&&delete e.ext[VI].id,R&&(e.ext=zy(e.ext),e.baseData&&(e.baseData=zy(e.baseData)),e.data&&(e.data=zy(e.data))),e.sync)if(T||g)e.latency=3,e.sync=!1;else if(a)return R&&(e=zy(e)),void a.sendSynchronousBatch(GI.create(e.iKey,[e]),!0===e.sync?1:e.sync,3);var i=e.latency,n=v,r=S;4===i&&(n=m,r=f);var s=!1;if(n<r)s=!$(e,t);else{var o=1,l=20;4===i&&(o=4,l=1),s=!0,function(e,t,i,n){for(;i<=t;){var r=V(e,t,!0);if(r&&r.count()>0){var a=r.split(0,n),s=a.count();if(s>0)return 4===i?m-=s:v-=s,Q(fw,[a],Jy.QueueFull),!0}i++}return G(),!1}(e.iKey,e.latency,o,l)&&(s=!$(e,t))}s&&Y(fw,[e],Jy.QueueFull)}function O(e,t,i){var n=j(e,t,i);return a.sendQueuedRequests(t,i),n}function N(){return v>0}function L(){if(w>=0&&j(w,0,l)&&a.sendQueuedRequests(0,l),m>0&&!E&&!g){var e=y[C][2];e>=0&&(E=F((function(){E=null,O(4,0,1),L()}),e))}var t=y[C][1];!_&&!p&&t>=0&&!g&&(N()?_=F((function(){_=null,O(0===b?3:1,0,1),b++,b%=2,L()}),t):b=0)}function x(){i=null,u=!1,h=[],p=null,g=!1,m=0,f=500,v=0,S=1e4,y={},C=yI,_=null,E=null,T=0,b=0,r=null,I={},s=void 0,o=0,w=-1,l=null,R=!0,A=!1,P=6,M=2,c=null,d=mw(),a=new hw(500,2,1,{requeue:K,send:Z,sent:X,drop:ee,rspFail:te,oth:ie},d),q(),I[4]={batches:[],iKeyMap:{}},I[3]={batches:[],iKeyMap:{}},I[2]={batches:[],iKeyMap:{}},I[1]={batches:[],iKeyMap:{}},ne()}function F(e,t){0===t&&T&&(t=1);var i=1e3;return T&&(i=qI(T-1)),d.set(e,t*i)}function U(){return null!==_&&(d.clear(_),_=null,b=0,!0)}function B(e,t){U(),p&&(d.clear(p),p=null),g||O(1,e,t)}function V(e,t,i){var n=I[t];n||(n=I[t=1]);var r=n.iKeyMap[e];return!r&&i&&(r=GI.create(e),n.batches.push(r),n.iKeyMap[e]=r),r}function H(t,i){a.canSendRequest()&&!T&&(s>0&&v>s&&(i=!0),i&&null==p&&e.flush(t,null,20))}function $(e,t){R&&(e=zy(e));var i=e.latency,n=V(e.iKey,i,!0);return!!n.addEvent(e)&&(4!==i?(v++,t&&0===e.sendAttempt&&H(!e.sync,o>0&&n.count()>=o)):m++,!0)}function G(){for(var e=0,t=0,i=function(i){var n=I[i];n&&n.batches&&Ry(n.batches,(function(n){4===i?e+=n.count():t+=n.count()}))},n=1;n<=4;n++)i(n);v=t,m=e}function j(t,i,n){var r=!1,s=0===i;return!s||a.canSendRequest()?JC(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=4;i>=t;){var n=I[i];n&&n.batches&&n.batches.length>0&&(Ry(n.batches,(function(t){a.addBatch(t)?r=r||t&&t.count()>0:e=e.concat(t.events()),4===i?m-=t.count():v-=t.count()})),n.batches=[],n.iKeyMap={}),i--}e.length>0&&Y(fw,e,Jy.KillSwitch),r&&w>=t&&(w=-1,l=0)}),(function(){return{latency:t,sendType:i,sendReason:n}}),!s):(w=w>=0?Math.min(w,t):t,l=Math.max(l,n)),r}function z(e,t){O(1,0,t),G(),W((function(){e&&e(),h.length>0?p=F((function(){p=null,z(h.shift(),t)}),0):(p=null,L())}))}function W(e){a.isCompletelyIdle()?e():p=F((function(){p=null,W(e)}),.25)}function q(){(y={})[yI]=[2,1,0],y.NEAR_REAL_TIME=[6,3,0],y.BEST_EFFORT=[18,9,0]}function K(t,i){var n=[],r=P;A&&(r=M),Ry(t,(function(t){t&&t.count()>0&&Ry(t.events(),(function(t){t&&(t.sync&&(t.latency=4,t.sync=!1),t.sendAttempt<r?(MT(t,e.identifier),D(t,!1)):n.push(t))}))})),n.length>0&&Y(fw,n,Jy.NonRetryableStatus),A&&B(2,2)}function J(t,i){var n=e._notificationManager||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){HC(e.diagLog(),1,74,t+" notification failed: "+i)}}function Y(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t.length>0&&J(e,[t].concat(i))}function Q(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t.length>0&&Ry(t,(function(t){t&&t.count()>0&&J(e,[t.events()].concat(i))}))}function Z(e,t,i){e&&e.length>0&&J("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])}function X(e,t){Q("eventsSent",e,t),L()}function ee(e,t){Q(fw,e,t>=8e3&&t<=8999?t-8e3:Jy.Unknown)}function te(e){Q(fw,e,Jy.NonRetryableStatus),L()}function ie(e,t){Q(fw,e,Jy.Unknown),L()}function ne(){o=i&&i.disableAutoBatchFlushLimit?0:Math.max(1500,S/6)}x(),e._getDbgPlgTargets=function(){return[a]},e.initialize=function(o,l,u){JC(l,(function(){return"PostChannel:initialize"}),(function(){var h=l;t.initialize(o,l,u);try{l.addUnloadCb,c=aE(d_(e.identifier),l.evtNamespace&&l.evtNamespace());var p=e._getTelCtx();o.extensionConfig[e.identifier]=o.extensionConfig[e.identifier]||{},i=p.getExtCfg(e.identifier),d=mw(i.setTimeoutOverride,i.clearTimeoutOverride),R=!i.disableOptimizeObj&&!!gC("chrome"),function(e){var t=e.getWParam;e.getWParam=function(){var e=0;return i.ignoreMc1Ms0CookieProcessing&&(e|=2),e|t()}}(h),i.eventsLimitInMem>0&&(S=i.eventsLimitInMem),i.immediateEventLimit>0&&(f=i.immediateEventLimit),i.autoFlushEventsLimit>0&&(s=i.autoFlushEventsLimit),Ty(i[Sw])&&(P=i[Sw]),Ty(i[yw])&&(M=i[yw]),ne(),i.httpXHROverride&&i.httpXHROverride.sendPOST&&(r=i.httpXHROverride),TT(o.anonCookieName)&&a.addQueryStringParameter("anoncknm",o.anonCookieName),a.sendHook=i.payloadPreprocessor,a.sendListener=i.payloadListener;var g=i.overrideEndpointUrl?i.overrideEndpointUrl:o.endpointUrl;e._notificationManager=l.getNotifyMgr(),a.initialize(g,e.core,e,r,i);var m=o.disablePageUnloadEvents||[];dE(n,m,c),uE(n,m,c),hE(k,o.disablePageShowEvents,c)}catch(t){throw e.setInitialized(!1),t}}),(function(){return{coreConfig:o,core:l,extensions:u}}))},e.processTelemetry=function(t,n){MT(t,e.identifier);var r=(n=e._getTelCtx(n)).getExtCfg(e.identifier),a=!!i.disableTelemetry;r&&(a=a||!!r.disableTelemetry);var s=t;a||u||(i[vw]&&(s.iKey=i[vw]),r&&r[vw]&&(s.iKey=r[vw]),D(s,!0),A?B(2,2):L()),e.processNext(s,n)},e._doTeardown=function(e,t){B(2,2),u=!0,a.teardown(),function(e,t){cE([W_,z_,G_],e,t)}(null,c),function(e,t){var i=aE(q_,t);cE([G_],e,i),cE([$_],null,i)}(null,c),function(e,t){var i=aE(K_,t);cE([j_],e,i),cE([$_],null,i)}(null,c),x()},e.setEventQueueLimits=function(e,t){S=e>0?e:1e4,s=t>0?t:0,ne();var i=v>e;if(!i&&o>0)for(var n=1;!i&&n<=3;n++){var r=I[n];r&&r.batches&&Ry(r.batches,(function(e){e&&e.count()>=o&&(i=!0)}))}H(!0,i)},e.pause=function(){U(),g=!0,a.pause()},e.resume=function(){g=!1,a.resume(),L()},e.addResponseHandler=function(e){a._responseHandlers.push(e)},e._loadTransmitProfiles=function(e){U(),q(),C=yI,L(),vy(e,(function(e,t){var i=t.length;if(i>=2){var n=i>2?t[2]:0;if(t.splice(0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t.push(n),y[e]=t}}))},e.flush=function(e,t,i){if(void 0===e&&(e=!0),!g)if(i=i||1,e)null==p?(U(),j(1,0,i),p=F((function(){p=null,z(t,i)}),0)):h.push(t);else{var n=U();O(1,1,i),null!=t&&t(),n&&L()}},e.setMsaAuthTicket=function(e){a.addHeader(xI,e)},e.hasEvents=N,e._setTransmitProfile=function(e){C!==e&&void 0!==y[e]&&(U(),C=e,L())},e._backOffTransmission=function(){T<4&&(T++,U(),L())},e._clearBackOff=function(){T&&(T=0,U(),L())},Oy(e,"_setTimeoutOverride",(function(){return d.set}),(function(e){d=mw(e,d.clear)})),Oy(e,"_clearTimeoutOverride",(function(){return d.clear}),(function(e){d=mw(d.set,e)}))})),n}return jf(t,e),t.__ieDyn=1,t}(BE),_w=Cw,Ew="_dropInst";function Tw(e,t){if(t)for(var i=Dy(t),n=0;n<i.length;n++){var r=i[n];py(e,r)||(e[r]=t[r])}}function bw(e,t){var i=null;if(t){t.endpointUrl&&(i=t.endpointUrl);var n=(t.extensionConfig||{})[e]||{};n.overrideEndpointUrl&&(i=n.overrideEndpointUrl)}return i}var Iw=function(e){function t(i,n){var r=e.call(this)||this;return bv(t,r,(function(e,t){function r(e){var t=[];return e&&Ry(e,(function(e){e.iKey===i&&t.push(e)})),t}function a(t){if(e[t]&&e.listeners)for(var i=0;i<e.listeners.length;i++){var n=e.listeners[i];if(n&&n[t])return!0}return!1}var s={eventsSent:function(t){if(a("eventsSent")){var i=r(t);i.length>0&&e.eventsSent(i)}},eventsDiscarded:function(t,i){if(a("eventsDiscarded")){var n=r(t);n.length>0&&e.eventsDiscarded(n,i)}},eventsSendRequest:function(t,i){a("eventsSendRequest")&&e.eventsSendRequest(t,i)},perfEvent:function(t){a("perfEvent")&&e.perfEvent(t)}};n.addNotificationListener(s)})),r}return jf(t,e),t.__ieDyn=1,t}(QE),ww=function(){function e(){var t,i,n,r,a,s,o,l,c,d,u,h,p,g,m=null,f=null;bv(e,this,(function(e){function v(){t={},i=[],n=null,r=null,a=[],s=[],o={},l=null,c=null,d=null,u=null,h=null,p=null,g=!1}function S(e,i){if(void 0===i&&(i=null),e){(!function(e){return e.pause&&e.teardown&&e.flush}(e)?a:s).push(e);var n=e.identifier;t.extensionConfig[n]=t.extensionConfig[n]||{},Tw(t.extensionConfig[n],i)}return e}function y(e){i=[],l=S(new rI,t.propertyConfiguration),i.push(l),t.extensions&&Ry(t.extensions,(function(e){my(e)||S(e)})),e&&Ry(e,(function(e){e&&!my(e)&&i.push(S(e))}))}function C(a){if(!n){g||HC(e.diagLog(),2,520,"The Shared Manager is not yet created, the returned shared instance will be overwritten");var s=_(a||t.instrumentationKey||"_not_defined_",{});r=new QE,(n=new Rw(e,e.diagLog(),r)).initialize(s,i),n.isInitialized()&&c&&(d=bw(c.identifier,s)),m&&n.setCookieMgr(m)}}function _(e,i){var n={};return n.instrumentationKey=e,n.channels=function(e){var i=[[]];return t.channels&&Ry(t.channels,(function(e,t){my(e)||(i[t]=i[t]||[],i[t]=i[t].concat(e))})),e&&e.channels&&Ry(e.channels,(function(e,t){my(e)||(i[t]=i[t]||[],i[t]=i[t].concat(e))})),i}(i),function(e){var i=[];t.extensions&&t.extensions.length>0&&(i=i.concat(t.extensions)),e&&e.extensions&&e.extensions.length>0&&(i=i.concat(e.extensions)),i.length>0&&(e.extensions=i),e.extensionConfig=e.extensionConfig||{},Tw(e.extensionConfig,t.extensionConfig)}(n),Tw(n,i),Tw(n,t),n}function E(e){var t=[];return i&&i.length>0&&(t=t.concat(i)),e&&e.length>0&&(t=t.concat(e)),t}v(),e.diagLog=function(){return u||(u=new BC(t)),u},e.getCookieMgr=function(){return C(),m||n.getCookieMgr()},e.setCookieMgr=function(e){m=e,n&&n.setCookieMgr(e)},e.getPerfMgr=function(){return p||t&&t.enablePerfMgr&&(p=f||new qC(e.getNotifyMgr())),p},e.setPerfMgr=function(e){f=e,p=e},e.create=function(i,r){g?HC(e.diagLog(),2,514,"Shared Manager has already been initialized."):(t=i||{},n=null,function(){var e=t.channels||[[]],i=new _w,n=i.identifier,r=!1;c=null,d=null,Ry(e,(function(e){Ry(e,(function(e){my(e)||(S(e),e.identifier===n&&(r=!0,c=e))}))})),r||(e[0].push(i),c=S(i,t.channelConfiguration)),t.channels=e}(),y(r))},e.getInst=function(e){return(o[e]||{}).inst},e.newInst=function(t,i,a){var s=e.getInst(t);if(s)return HC(e.diagLog(),2,514,"Instance already exists for ["+t+"]"),s;if(C(t),n.isInitialized()){var l=_(t,i);if(c){var u=bw(c.identifier,l);d&&u&&d!==u&&HC(e.diagLog(),2,511,"The endpointUrl mismatch, shared Url ["+d+"] is different from configured ["+u+"] shared will be used!")}var h=new Iw(t,r);s=new Rw(e,e.diagLog(),h),o[t]={iKey:t,inst:s,notifyMgr:h},s.setPerfMgr(e.getPerfMgr()),s.initialize(l,E(a)),s.isInitialized()||(HC(e.diagLog(),2,520,"Failed to initialize new instance!"),s=null,delete o[t])}return s},e.getSharedPlugin=function(e){C();var t=null,i=n.getPlugin(e);return i&&(t=i.plugin),t},e.getPropertyManager=function(){return C(),l},e.getPostChannel=function(){return C(),c},e.getNotifyMgr=function(){return h||(h=new QE),h},e.unload=function(e,t,i){var r=Dy(o),a=r.length+1,s={reason:50,isAsync:e,flushComplete:!1};function l(e,i){0==--a&&(v(),t&&t(i))}n&&(Ry(r,(function(t){!function(e,t,i,n){var r=o[e];r&&(r.inst&&r.inst.isInitialized()?r.inst.unload(t,(function(t){i&&i(e,t)}),n):i&&i(e,{reason:50,isAsync:t,flushComplete:!1}))}(t,e,(function(e,t){l(0,t)}),i)})),n.isInitialized()&&(n.unload(e,(function(e){l(0,s=e)}),i),n=null)),l(0,s)},e[Ew]=function(e){e&&o.iKey&&delete o[e]}}))}return e.__ieDyn=1,e}(),Rw=function(e){function t(i,n,r){var a,s=e.call(this)||this,o=i;return bv(t,s,(function(e,t){e.getSharedPropertyManager=function(){return o.getPropertyManager()},e.getSharedPostChannel=function(){return o.getPostChannel()},e.getOverridePropertyManager=function(){return a},e.initialize=function(i,s){JC(e,(function(){return"ApplicationInsights:initialize"}),(function(){var o=[a=new SI];s&&(o=o.concat(s)),i.extensionConfig=i.extensionConfig||[];var l=i.propertyConfiguration||{};i.propertyConfiguration&&delete i.propertyConfiguration,i.extensionConfig[a.identifier]=l;try{t.initialize(i,o,n,r)}catch(t){HC(e.logger,1,514,"Failed to initialize SDK."+wC(t))}}),(function(){return{config:i,extensions:s}}))},e.unload=function(i,n,r){o[Ew]&&o[Ew]((e.config||{}).instrumentationKey),t.unload(i,n,r)}})),s}return jf(t,e),t.__ieDyn=1,t}(OT);var Aw=class{getInitialSettings(){return{resizeModeForSharing:"none",enableAudioProcessingFallback:!1,allowVirtualDeviceInCall:!1,activeSpeaker:{timeToPromote:1e4},dtmf:{toneDuration:200,toneGap:100},mediaStreamHoldInterval:5e3,webrtcContributingSourcesPollingInterval:1e3,webrtcIceGatheringTimeoutMs:2e4,webrtcAllowedMediaContentType:Qe.ALLOWED_CONTENT_TYPES.SDP_NGC,webrtcMediaContentType:Qe.CONTENT_TYPE.SDP,webrtcScreensharingCapabilityMaxFS:8160,webrtcScreensharingCapabilityMaxFPS:1500,webrtcStatHwSilentDetectionDuration:5,webrtcStatHwSilentDetectionLevel:14,webrtcStatPollInterval:1e3,webrtcStatStoredRecordsNumber:60,webrtcStatNetworkDetectionDuration:10,webrtcHealedRatioWindowSize:5,webrtcHealedRatioExtendedWindowSize:20,webrtcStatNetworkDetectionHysteresis:.01,webrtcStatNetworkDetectionBadLevel:.17,webrtcStatNetworkDetectionGoodLevel:.15,webrtcMinAudioSamplesRecvForNetworkRecvQuality:48e4,webrtcVideoCapabilityCheckIntervalMin:2e4,webrtcVideoCapabilityCheckIntervalMinMultiparty:5e3,webrtcVideoCapabilityCheckIntervalMax:3e4,webrtcVideoCapabilityCheckIntervalMaxMultiparty:5500,webrtcScreensharingCapabilityCheckIntervalMin:0,webrtcScreensharingCapabilityCheckIntervalMax:0,webrtcVideoCapabilityMaxFS:3600,webrtcVideoCapabilityMaxFPS:3e3,webrtcMultiPartyRecvVideoMaxFS:3600,webrtcRecvVideoMaxFS:8160,webrtcCameraOpenFs:3600,minCameraOpenFps:15,maxCameraOpenFps:30,webrtcMultipartyMaxScalingFs:3600,webrtcMaxScalingFs:8160,webrtcVideoScaling:!1,webrtcVideoScalingMultiparty:!0,enableOptimalVideoCount:!1,ovcBandwidthPerVideoReceiver:2e5,ovcSlidingWindowPercentile:.3,ovcSlidingWindowSamples:20,nonEstimatedDefaultVideoReceiversCount:4,ovcMaxCount:4,ovcMaxCountXL:4,ovcXLParticipantsCount:100,ovcIgnoreFirstSamples:10,ovcAvailableConcurrencyForBiggerGrid:4,ovcMemoryForBiggerGrid:2,ovcRampUpCooldown:15e3,ovcRampDownCooldown:1e4,webrtcStatNetworkDetectionEnabled:!0,webrtcUseNewStatsApi:!0,useAudioAnalyzer:!0,webrtcVideoSubscriptionDisposeTimeout:2e3,webrtcCompareContentTypeInOffer:!0,iceServerTransport:"udp,tcp,tls",iceHostCandidateOnly:!0,iceUdpAddressType:"ip",iceTcpAddressType:"ip",renegotiationAttempts:3,reconnectTimeLimit:9e4,initialReconnectTimeLimit:0,maxReconnectDelayTime:5,waitForRelayOnReconnect:!0,relayWaitSaneTimeoutMs:25e3,reconnectOnDisconnect:!1,reconnectWithNoRelays:!1,reconnectWithProbes:!1,reconnectWaitTimeAfterProbe:1e3,reconnectOnPcClose:!0,reconnectWakeupTimeLimit:18e4,webrtcSpeakingWhileMutedDetectionWindow:3,webrtcSpeakingWhileMutedBadDuration:3,webrtcSpeakingWhileMutedDetectionLevel:4e3,webrtcNegotiateDisabledDataModality:!1,recoverableMediaErrors:[Qe.MEDIA_ERROR.iceConnectionError,Qe.MEDIA_ERROR.noNetworkError,Qe.MEDIA_ERROR.srtpError,Qe.MEDIA_ERROR.incompatibleOffer,Qe.MEDIA_ERROR.internalError].join(","),forceReconnectErrors:[Qe.MEDIA_ERROR.audioPlaybackError].join(","),sendCallStartupTelemetry:!0,webrtcMultiPartyRecvVideoSignaling:!0,webrtcVideoDelayThreshold:10,webrtcEndOfCallFreezeThreshold:3,webrtcSubscriptionEventLimit:300,webrtcHandleRollback:!0,webrtcHandleRemoteRollback:!1,losingConnectivityTimeoutMs:-1,iceCandidateFilterMDns:!0,webrtcInjectTransportCCAudio:!1,webrtcInjectTransportCCAudioMultiparty:!0,webrtcRejectedFeatures:"byPass",webrtcRequiredFeatures:"nonByPass",webrtcSimulcastSessionEnabled:!1,webrtcSimulcastStreamsCountForVideo:1,webrtcSimulcastStreamsCountForSharing:1,webrtcFmtParamListSupported:!0,webrtcNegotiatedSsrcRangeForVideo:0,webrtcNegotiatedSsrcRangeForSharing:0,webrtcNegotiatedSsrcRangeForVideoOneToOne:0,webrtcNegotiatedSsrcRangeForSharingOneToOne:0,webrtcAllowRestoreKeyframe:!1,webrtcEnabledCustomBwEstimationForVideo:!1,webrtcDisabledSenderBitrate:1e3,maxStoredPreferredResolutionCount:4,maxStoredQualityLimitationReasonEvents:30,maxStoredUFDCount:50,simulcastTelemetryLayoutsPerSession:5,simulcastTelemetryNumModalitySessions:3,simulcastTelemetryNumFMTP:10,maxSendVideoCapabilitiesReportingForVideoEnabled:!1,maxSendVideoCapabilitiesReportingForSharingEnabled:!1,maxSendVideoCapabilitiesReportingUseMaximumWidthHeight:!0,maxSendVideoCapabilitiesReportingSendMaxFs:!1,maxSendVideoCapabilitiesReportingSendMaxMbps:!1,maxReportedOvershootingEvents:20,permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!0,adpRequestAVLast:!0,rememberNegative:!1,persistOnDeniedError:!0,disableOnPermissionDeniedOnly:!1},devices:{blacklist:{microphone:"stereo mix \\(",camera:"(ir camera|avstream media device)",speaker:"stereo mix \\("},overrideDefault:!1,compositeLabelMatchingThreshold:.5,piiSafeWords:["airpod","bluetooth","hands-free","stereo","wireless","citrix hdx","remote audio","vmware","built-in","integrated","internal","teams","high definition","facetime","macbook","smartaudio","front","rear","back","iphone","ipad","display","displayport","dp","hdmi","amd","nvidia","intel","analog","digital","dock","line( in| out)?","s/pdif","external","thunderbolt\\d*","usb","panoramic","desktop","capture","cable","cam","virtual","manycam","snap camera","obs","vb-audio","vaio","effect","sink","source","default","test"],pollingIntervalActive:3e3,enumerateDevicesTimeout:25e3,enumerateDevicesAfterADP:!1},useGoogPrefixAudioConstraints:!0,multiviewResolutionLimits:{1:720,2:720,3:540,4:360,more:360},maxSpotlightResolution:720,multiviewResolutionLimitUpdateThrottleDelay:300,useMultiviewLimitsOnInitialRequest:!0,useApplyChannelParametersForSourceRequests:!0,maxVideoFreezeTimestampsInBucket:5,webrtcSendBandwidthNotificationsEnabled:!1,webrtcSendBandwidthIgnoredUpdateLimit:6,webrtcSendBandwidthThreshold:.1,checkSupportForWebrtc_1_0:!1,webrtcLastAppliedVideoCapabilitiesCount:5,webrtcLastAppliedVideoCapabilitiesSequenceCount:5,gumRequestTimeout:2e4,overrideGumFromWebkit:!1,setMinFpsForWebkit:!1,videoCaptureFreezeTimeout:5e3,webrtcCloseAfterIceFailure:!0,audioBandwidthInKbps:90,videoBandwidthAllocation:.3,enableQosSupport:!1,forceUnbundledTransport:!1,allowedAudioCodecs:[],allowedVideoCodecs:[],allowedVideoCodecsMultiparty:[{clockRate:9e4,mimeType:"video/H264"},{clockRate:9e4,mimeType:"video/rtx"}],filterCodecsInSdp:!1,filterCodecsInSdpMultiparty:!0,filterCodecsInSdpV2:!1,reduceRtcpFbInSdp:[],reduceRtcpFbInSdpMultiparty:["goog-remb","transport-cc","ccm/fir","nack","nack/pli"],subscribeToSsrcForVideo:!1,audioRendererUsePauseOnDetach:!0,audioRendererRestartOnPause:!1,audioRendererRestartOnDeviceError:!0,disableAudioOutputSelection:!1,preferSdesSrtp:!1,preferSdesSrtpPstn:!1,useLocalStorageForOneDs:!0,useOneDsLogger:!1,useSendBeaconSync:!1,addTelemetryReportingCallback:!0,eventsLimitInMem:200,eventLatency:mT.Normal,eventLatencyRealTime:mT.RealTime,enableCompoundKey:!1,telemetryTenants:{signaling:"53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",media:"1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",realtimeMedia:"5aea257f81424f5d8574e57a50974ead-d3a768ce-590c-4595-ab85-3dd046114290-6701",tlePlayer:"2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326"},transmitProfileName:"REAL_TIME",transmitProfileTimings:[],waitReportStatsAtCallStop:!1,oneStreamPerDeviceType:!1,enableWebRtcInternalsLogs:!1,enableMultiViewStats:!0,webrtcBWJumpLowerLimit:1e5,webrtcBWJumpUpperLimit:3e5,uplinkBWStabilizationSlidingWindowSize:10,uplinkBWStabilizationMaxDeviation:.1,uplinkBWStabilizationMinBandwidth:1e5,downlinkBWStabilizationSlidingWindowSize:10,downlinkBWStabilizationMaxDeviation:.1,downlinkBWStabilizationMinBandwidth:1e5,maxKeyFrameTimestampsInBucket:5,enableAudioSharing:!1,enableStopSharingWithIncomingOffer:!0,enableDevtoolsAPI:!1,enableDataChannel:!1,enableDataChannelMultiparty:!0,enableDataChannelPstn:!1,alwaysNegotiateDataChannel:!0,webrtcDataChannel:{enableFragmentation:!1,fragmentationSize:0,enableSendScheduler:!1,rateLimiterCheckInterval:250,discardOnSendFailure:!1,bufferedAmountLowThreshold:65535,bufferedAmountHighThreshold:262144,maxBitrate:0,maxPacketRate:0,maxQueueSize:524288,dataIds:[]},acceptDisabledDataModality:!0,rejectUnbundledDataModality:!0,sctpPort:5e3,enableGiveControl:!1,maxStoredDataChannelValues:15,mediaControlPlaneConfig:{enableBweNotifications:!0,enableDominantSpeakerHistory:!0,enableSourceRequests:!1,sourceRequestsMessagesTimeout:1e4,storedSRRecordsCount:60,verboseTelemetry:!1,sendDuplicates:!1},localPreviewMirroringSupported:!1,enableVideoEffects:!0,useRawMediaApiForVideoEffects:!1,forceKeyFrameV2ScaleFactor:1.1,effectsTelemetryBufferSize:20,useGenericWorkerLoader:!1,applyAudioEffectOnDemand:!1,wasmdns:{pTime:10,goodPerfThreshold:8,poorPerfThreshold:10,badPerfThreshold:12,perfWindowLength:10,enableNoiseSuppression:!1,noiseSuppressionMode:"Off",backgroundMode:!1},wasmvqe:{enableAec:!1,enableVqe:!1,backgroundMode:!1,performanceThresholdMs:8,performanceWindowDurationSecs:10,defaultVqeMode:fh.VqeMode.Off,callType:fh.CallType.Conference,audioUsageMode:fh.AudioUsageMode.Default,performanceProfile:fh.AecPerfProfile.Normal},webcv:{qualityConfig:{outputFps:{min:15,max:30},outputResolution:720,preserveResolution:!0,degradationLadder:[{resolution:{width:1920,height:1080},fps:{min:15,max:30}},{resolution:{width:1280,height:720},fps:{min:15,max:30}},{resolution:{width:960,height:540},fps:{min:15,max:30}},{resolution:{width:640,height:360},fps:{min:13,max:30}},{resolution:{width:416,height:234},fps:{min:10,max:20}},{resolution:{width:320,height:180},fps:{min:10,max:20}}],initialLadderResolution:720,improvementFpsThresholdPercent:20,statsIntervalSec:5,enableMaskPropagation:!1,maskPropagationFramesInterval:30},powerPreference:mh.PowerPreference.HighPerformance,useInsertableStreams:!1,webGLUnsupportedRenderers:["Google SwiftShader"],webGLRequiredExtensions:["EXT_color_buffer_float","WEBGL_debug_renderer_info","OES_texture_float_linear"],usePreheat:!1,useSharedArrayBuffer:!0,useWasmEffects:!1,processorType:mh.ProcessorType.Webgl2},insertFakeCandidateIfNeeded:!0,useSdpCapabilitiesLegacySession:!0,useSdpCapabilities:!0,enableH264SpsPpsIdrKeyframe:!0,disableMsSdp:!1,disableSdes:!1,disableIceReinvite:!1,iceDisconnectedTimeoutMs:3e4,enableLocalVideoConstraints:!0,webrtcAudioChannelSignalingFeedback:"app recv:dsh",webrtcVideoChannelSignalingFeedback:"app send:src recv:src,vc",webrtcResolutionManagerCooldownTimeout:15e3,webrtcResolutionManagerRetryDelay:5e3,webrtcNativeCpuOveruseDisabled:!1,webrtcDisplayStreamContentHint:"text",h264SendProfileOverride:"42C02A",addFmtpToInitialSubscription:!0,h264SubscribeProfile:"64001f",notRenderingTimeInterval:{video:3,sharing:10},notRenderingLowBitrateThreshold:6,notRenderingLowFramerateThreshold:3,isBytesRecvUsedInIsRenderingCalculation:!0,useConnectionState:!0,useDtlsTrasportConnectionCheck:!1,enableNetworkRecvQualityUFD:!0,enableNetworkSendQualityUFD:!0,enableSignalingAudioPermissionDeniedUFD:!1,webrtcJitterLowThreshold:.2,webrtcJitterHighThreshold:.35,webrtcJitterSticknessTime:5e3,webrtcLossRateLowThreshold:.2,webrtcLossRateHighThreshold:.3,webrtcLossRateSticknessTime:5e3,webrtcMinPacketsSentForNetworkSendQuality:200,webrtcLossRateWindowSize:3,webrtcJitterWindowSize:3,networkSendQualityDiagnostics:!1,networkRecvQualityDiagnostics:!1,webrtcJitterExtendedWindowSize:6,webrtcLossRateExtendedWindowSize:6,freezeMinDuration:128,freezeIntervalFrequency:1e3,minPacketsReceivedToCalculatePacketLossRate:100,healedRatioPrecision:8,jitterPrecision:3,requestNewStreamOnUnmute:!0,raiseVideoMuteUfd:!1,useMediaQualityController:!1,useMediaQualityControllerForceKeyFrame:!1,layoutControlTimeout:1e4,extmapAllowMixed:!1,enableVla:!1,allowRemoteVla:!1,enableNonAdvVla:!1,specCompliantSimulcast:{},specCompliantSimulcastMultiparty:{video:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1],minFsForSimulcast:920,useApplyConstraints:!1},sharing:{enableLocally:!1,allowEnableRemotely:!1,layerScaleFactors:[1]},allowOverride:!1,constraintsDisableVla:!0,collectResolutionInfo:!0,maxBrControlEnabled:!1,allowedBweOvershootRatio:1,allowResLimit:!1},enforceOpusFmtpMultiparty:{usedtx:1},videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!1,mapSsrcToTrackForStats:!1,enableVideoOrientationExtension:!1,speakerGainLevel:0,ignoreClosedDtlsTransportState:!1,disconnectOnPageHide:!0,renderThroughCanvas:!1,isRenderingBasedOnRawStatistics:!1,enableDevicePixelRatio:!0,useSetParametersToApplyCapabilities:!1,enablePlatformCallConstraints:!1,enablePlatformCallConstraintsPerCall:!1,enableDynamicCallConstraints:!0,numCallConstraintsEvents:6,setParametersMaxBitrateUndefined:!1,onAddTrackRemoveOtherTracks:!0,avoidFakeStreamsDuringEscalation:!0,navConnectionPollingInterval:1e3,navConnectionNumSamplesToCollect:60,allowProvisionalAnswer:!1,allowProvisionalAnswerPstn:!0,acceptProvisionalAnswerFromPstnOnly:!0,disableIncomingDtlsRoleOverride:!1,disableOutgoingDtlsRoleOverride:!1,statsAllowAnyVideoSendTrack:!1,pictureInPicture:{enablePictureInPicture:!1,aspectRatioHorizontal:16,aspectRatioVertical:9,maxActiveStreams:1,minStreamGridCellWidth:160,dominantStreamChangeDebounce:3e3,statisticsBufferSize:20,multiStreamWorkerURL:""},showStatsInCall:!1,useSetStreamsForSender:!0,addPrefixForMsidInSdp:!1,enableMuteSpeakerUnmuteSpeakerWorkaround:!1,alwaysRaiseBadDeviceEvents:!1,removeRecvStreamOnEnded:!0,requiredVideoCodecs:["h264"],primaryVideoCodecs:["h264","vp8","vp9"],removeUnsupportedVideoModality:!1,enableActiveSpeakerBasedDSH:!0,enableInitialSignalingDSHSubscription:!0,enableSignalingDSHFallback:!1,emptyInitialDSH:!0,bwPercentiles:[5,50,95],enableTimerTracker:!1,diagnostics:{sideBySide:!0,useForTelemetry:!1,collectWhileNotConnected:!1,collectionLimits:{numDeviceEvents:200,numVideoEffectsEvents:100,numAudioEffectsEvents:100,numOvershootEvents:100,numIsRenderingEvents:100,numStatsReports:600,numStatsErrors:100,numSubscriptionEvents:100,numUFDs:100,numNativeSessions:3,numSessions:3,numNetworkEvents:50,numReconnects:50,numCapabilitiesRequested:60,numCapabilitiesApplied:60,maxVideoStatsAfterSubscription:30,numResolutionSwitches:10,numSamplesForE2E:4},telemetryLimits:{numDeviceEvents:50,numVideoEffectsEvents:50,numAudioEffectsEvents:50,numOvershootEvents:20,numIsRenderingEvents:4,numPreferredResolutions:3,numSubscriptionEvents:100,numUFDs:50,numAggregatedSamples:60,numStatsErrors:20,numCapabilitiesRequested:5,numCapabilitiesApplied:3,maxVideoStatsAfterSubscription:30,numNetworkEvents:20,numReconnects:10,numRendererStateChangedEvents:10},teamsRealtimeTelemetry:{pollingInterval:15},performanceMonitoring:{useComputePressure:!1,fluctuationSamplesNum:5,enableRemoteVideoCalculator:!1,enableLowerResolution:!1,monitoringStrategy:"decodeTime",decodeThresholds:{1080:{fps:30,maxDecodeTime:20},720:{fps:30,maxDecodeTime:15},540:{fps:30,maxDecodeTime:11},360:{fps:30,maxDecodeTime:9},234:{fps:15,maxDecodeTime:10},180:{fps:15,maxDecodeTime:10}},defaultThrehold:{fps:30,maxDecodeTime:60},fpsDiffThresholds:{1080:{fps:30,fpsDiff:4},720:{fps:30,fpsDiff:4},540:{fps:30,fpsDiff:4},360:{fps:30,fpsDiff:4},234:{fps:15,fpsDiff:2},180:{fps:15,fpsDiff:2}},defaultFpsDiffThreshold:{fps:30,fpsDiff:10},volatilityThresholds:{1080:10,720:10,540:10,360:10,234:5,180:5},defaultVolatilityThreshold:10,remoteVideoTrackInterval:10,telemetryResolutionRequestSpanMs:5e3,cpuMetricCollector:3},features:{takeFreezeTelemetryFromGathererV2:!0,useLastSampleDeltaPerSecondConverter:!1,useNewerStatisticsMetrics:!1,useNewNetworkUFD:!1,useNewSpeakingWhileMutedUFD:!1,useNewSendBandwidthCalculation:!1,useNewStatsForLocalVideoStreamWatcher:!1}},requireUserActionForAudioSharing:!1,postponeAudioMixerForAudioSharing:!1,reassignMediaStreamAudioTrackAfterCreation:!1,deactiveAudioSender:!1,webrtcForceSdesForS1:!1,webrtcPranswerWaitForMediaPollingInterval:1e3,webrctRemoveVideoModalitiesForPstn:!1,removeSendersOnConfigureModalities:!0,streamAvailabilityConsiderModalities:!0,setBWSeed:!1,bwSeedOptions:{mids:["*"],aggregation:"const",aggregateLastN:null,constValue:-1,minValue:-1,cappingValue:-1,useLocalStorage:!1,localStorageKey:"bwSeed"},stopCallOnAcceptFailure:!0,allowMediaBypass:!0,enablePermissionsWorkaround:!1,disposeSendersSync:!1,disposeStreamsSync:!1,maxVideoStatsAfterSubscription:30,ecsConfigTimeout:2e4,contributingSourcesLogInterval:1e4,useNewTokenApi:!1,audioRendererFailedReconnectTimes:0,audioRendererFailedRetryCodes:[3],effectsApplyConstraintsRetryMs:1e3,isSpotlightEnabled:!0,addAudioStreamBeforeConnection:!1,redReceiveEnabled:!1,mediaEventDictionary:Qe.MEDIA_EVENT_FIELDS,useSenderV2:!0,applySenderParamsBeforeStart:!0,reuseLastSetParameters:!1,hevcCodecs:["hev1.1.6.L120.90","hev1.1.4.L93.B0","hev1.1.6.L93.B0"],useInactiveAudioTrack:!1,enableRollbackHandler:!1,disableImmidiateEscalationReconnect:!1,enableCachingFMTP:!0,setDisconnectAfterCleanUp:!1,sendResolutionTableOverride:Qe.RES_TABLE.SEND,recvResolutionTableOverride:Qe.RES_TABLE.RECV,maxSendVideoCapabilitiesReportingForVideoEnabledMultiparty:!0,participantStreamInitialSubscriptions:!0,holdRetryActivationDelay:-1,holdSkipActivation:!0,recoverOnStreamUnmute:!1,isAv1Allowed:!1,audioSharingMemoryLeakFix:!0,h264SdpProfileMultiparty:"64001f",rejectIncompatibleOriginator:!1,coeffOfValidTimeDelayBetweenFramesArrival:2,invalidFPSAboveMax:40,useWakeLockApi:!1,noRequiredCodecsWorkaround:!1,vdiDisconnectedTracking:{enabled:!0,clientPhrases:["failure"]},multiStreamSupported:!1,nonMultiStreamChannels:9,useTokenMigrationHeader:!1,clientSupportsAadToken:!1,clientSupportsCaeToken:!1,clientSupportsSkypeToken:!0,supportMissingTokenTypesInResponse:!0,useSkypeTokenWhenNoAuthenticateHeader:!1,useKeyFrameApi:!1,useDeviceHandleForLocalVideo:!0,enablePlayVideoOnStreamUnmuteWorkaround:!1}}getEnforcedSettings(){return{}}},Pw=class extends Aw{getInitialSettings(){const e=super.getInitialSettings();return e.oneStreamPerDeviceType=!0,e.removeUnsupportedVideoModality=!0,e}},Mw=class extends Aw{constructor(){super()}getEnforcedSettings(){return{useAudioAnalyzer:!1,enableAudioSharing:!1}}},kw=class extends Pw{constructor(e){super(),this.browserInfo=e}getEnforcedSettings(){const e={webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,permissions:{usePositiveInAdp:!1,useNegativeInAdp:!1,adpFallback:!0,adpFallbackAudio:!0,adpFallbackVideo:!1,adpRequestAVLast:!1,rememberNegative:!1},devices:{pollingIntervalIdle:1e4},audioRendererRestartOnPause:!0,subscribeToSsrcForVideo:!0,noRequiredCodecsWorkaround:!0};return ym(this.browserInfo.version,"15.0")||(e.statsAllowAnyVideoSendTrack=!0),ym(this.browserInfo.version,"16.0")&&"Mobile"===this.browserInfo.formFactor&&(e.enablePermissionsWorkaround=!0),ym(this.browserInfo.version,"17.0")&&"Mobile"===this.browserInfo.formFactor&&(e.recoverOnStreamUnmute=!0),e}},Dw=class extends Pw{getEnforcedSettings(){return{webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useDtlsTrasportConnectionCheck:!0,videoIsRenderingCheck:!1,fixSdpForPartialIceRestart:!0,mapSsrcToTrackForStats:!0,ignoreClosedDtlsTransportState1on1:!0,subscribeToSsrcForVideo1on1:!0,devices:{enumerateDevicesTimeout:0,pollingIntervalIdle:1e4,idlePollingOnStart:!0},webrtcInjectTransportCCAudioMultiparty:!1,videoCaptureFreezeTimeout:0,filterCodecsInSdp:!0,useSetParametersToApplyCapabilities:!0,removeRecvStreamOnEnded:!0,webrtcDisabledSenderBitrate:0,disableAudioOutputSelection:!0}}},Ow=class extends Aw{constructor(){super()}getEnforcedSettings(){return{checkSupportForWebrtc_1_0:!0,requireUserActionForAudioSharing:!0,webrtcSimulcastSessionEnabled:!0,webrtcAllowRestoreKeyframe:!0,useAudioAnalyzer:!1,enablePlatformCallConstraints:!0,specCompliantSimulcastMultiparty:{video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!1,minFsForSimulcast:920},maxBrControlEnabled:!0,allowResLimit:!0,allowOverride:!0},extmapAllowMixedMultiparty:!0,enableVlaMultiparty:!0,allowRemoteVlaMultiparty:!0,enableNonAdvVlaMultiparty:!0,useMediaQualityControllerMultiparty:!0,useSdpCapabilities:!1}}},Nw=class extends Pw{constructor(e){super(),this.browserInfo=e}getEnforcedSettings(){const e={};return ym(this.browserInfo.version,"74.0")&&(e.webrtcSimulcastSessionEnabled=!0,e.webrtcAllowRestoreKeyframe=!0,e.enableAudioSharing=!0),"RoomAudioProcessing"===this.browserInfo.formFactor&&(e.defaultAudioProcessingFlags=0,e.wasmvqe={enableAec:!1,enableVqe:!1,backgroundMode:!1},e.wasmdns={enableNoiseSuppression:!1,backgroundMode:!1}),"CiscoOS"===this.browserInfo.name&&(e.waitReportStatsAtCallStop=!0),"Mobile"===this.browserInfo.formFactor&&(e.enableAudioSharing=!1,e.audioRendererFailedReconnectTimes=3,e.devices={pollingIntervalIdle:1e4}),"SamsungTV"===this.browserInfo.name&&(e.useSetParametersToApplyCapabilities=!0),ym(this.browserInfo.version,"98.0")&&"Desktop"===this.browserInfo.formFactor&&(e.specCompliantSimulcastMultiparty={video:{layerScaleFactors:[1,2],enableLocally:!0,allowEnableRemotely:!0,useApplyConstraints:!0,minFsForSimulcast:920},maxBrControlEnabled:!0,allowResLimit:!0},e.extmapAllowMixedMultiparty=!0,e.enableVlaMultiparty=!0,e.allowRemoteVlaMultiparty=!0,e.enableNonAdvVlaMultiparty=!0,e.useMediaQualityControllerMultiparty=!0),ym(this.browserInfo.version,"100.0")&&(e.redReceiveEnabledMultiparty=!0),e.webcv={useWasmEffects:!0,processorType:mh.ProcessorType.Wasm},e}},Lw=class{constructor(e){this.settings=e,this.isTransportUnbundled=!1,this.webrtcRejectedFeatures="",this.webrtcRequiredFeatures="",this.spatialAudioEnabled=!1,this._maxBandwidthInKbps=0,this._noiseSuppressionMode="Auto",this._enableMediaBypass=!1,this.audioContext={enabledLocally:!1,disabledRemotely:!1,enabledForSend:!1,initFailed:!1,initSendFailed:!1,codec:"None",lastUsedCodec:"None"}}setMediaConfiguration(e,t){this.maxBandwidthInKbps=Math.floor((e.maxBandwidthInBps||0)/1e3),this.isTransportUnbundled=this.settings.forceUnbundledTransport||this.settings.enableQosSupport&&(e.enableMediaQoS||!!e.mediaPortRanges),this._mediaPortRanges=e.mediaPortRanges,this.simulcastSessionEnabled=this.settings.webrtcSimulcastSessionEnabled&&fm(this.settings.checkSupportForWebrtc_1_0),this._noiseSuppressionMode=e.noiseSuppressionMode||"Auto",this._enableMediaBypass=this.settings.allowMediaBypass&&e.enableMediaBypass,this.webrtcRejectedFeatures=this._enableMediaBypass?"":this.settings.webrtcRejectedFeatures,this.webrtcRequiredFeatures=this._enableMediaBypass?"":this.settings.webrtcRequiredFeatures,this.spatialAudioEnabled=t?t.spatialAudioEnabled:e.enableSpatialAudio}get mediaBypassEnabled(){return this._enableMediaBypass}get noiseSuppressionMode(){return this._noiseSuppressionMode}get maxBandwidthInKbps(){return this._maxBandwidthInKbps}set maxBandwidthInKbps(e){this._maxBandwidthInKbps=e,this.settings.maxBandwidthInKbps&&(this._maxBandwidthInKbps=Math.min(this.settings.maxBandwidthInKbps,this._maxBandwidthInKbps||Number.MAX_SAFE_INTEGER))}get audioPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.audioMin&&this._mediaPortRanges.audioMax)return{min:this._mediaPortRanges.audioMin,max:this._mediaPortRanges.audioMax}}get videoPortRange(){if(this.isTransportUnbundled&&this._mediaPortRanges&&this._mediaPortRanges.videoMin&&this._mediaPortRanges.videoMax)return{min:this._mediaPortRanges.videoMin,max:this._mediaPortRanges.videoMax}}get audioCodecContext(){return this.settings.useInsertableStreams?.audioWasmCodec?.enable?this.audioContext:void 0}};function xw(e,t){if(Array.isArray(e))return t.slice()}var Fw=class extends qe{constructor(e,t,i={}){super(e),this.logger=e,this.platformCallConstraintsProvider=t,this.platformConfig=function(){const e=ri();return"ChromiumAVD"===e.engine?new Mw:"Safari"===e.engine?new kw(e):"Firefox"===e.name?new Dw:xg()?new Ow:"Chromium"===e.engine?new Nw(e):new Aw}(),this.sessionCount=0,this._consoleOverrides={},this.uaConfig=new Bg(this),this.mediaConfiguration={},this.configReceivedDefer=km(),this.initialSettings=(0,df.mergeWith)({},(0,df.cloneDeep)(this.platformConfig.getInitialSettings()),(0,df.cloneDeep)(i),this.platformConfig.getEnforcedSettings(),xw),this.settings=this.initialSettings,this.settingsWithoutOverrides=this.initialSettings,this.stackSettings=(0,df.cloneDeep)(i),this.mediaSettings=new Lw(this.settings),this.platformCallConstraintsProvider.changed((()=>{this.updateSettings();const e=this.platformCallConstraintsProvider.constraints,t=this.logger.createChild("SettingsToCallConstraintsConverter"),i=gf(t,this.settings,e);this.platformCallConstraintsProvider.addCallConstraintsTelemetryEvent(i,"applied")})),this.configReceivedTimeout=window.setTimeout((()=>{this.configReceivedTimeout=void 0,this.configReceivedDefer.resolve()}),this.settings.ecsConfigTimeout),this.logger.safe.info("Initialized")}getCallConstraints(){return this.platformCallConstraintsProvider.constraints}setCallConstraints(e){return this.platformCallConstraintsProvider.setConstraints(e),e}getCallConstraintsTelemetry(){return this.logger.error("Not supported globally, returning empty array"),[]}addCallConstraintsTelemetryEvent(e,t){this.logger.error("Not supported globally")}getIceTransportPolicy(){return this.logger.warn(`Not supported globally, returning default ${Qe.ICE_TRANSPORT_POLICY.all}`),Qe.ICE_TRANSPORT_POLICY.all}setIceTransportPolicy(e){this.logger.error("Not supported globally")}getConfigReceivedOrTimeout(){return this.configReceivedDefer.promise}getConfigView(e,t){const i=e?"Multiparty":"1on1",n=Object.entries((0,df.cloneDeep)(this.settings)).reduce(((e,[t,n])=>(e[t]=n,t.endsWith(i)&&(e[t.replace(i,"")]=n),e)),{}),r=new Lw(n);return r.setMediaConfiguration(this.mediaConfiguration,t?.mediaConfig),new If(this.logger.createChild("ConfigProviderView"),n,r,this.userAgentConfig,this.countryCode,this.platformCallConstraintsProvider,t?.getCallConstraints())}updateConfig(e,t,i,n){this.etag=t||this.etag,this.configIds=i||this.configIds,this.country=n||this.country,this.event("newConfigReceived").raise(e,t,i),this.settingsWithoutOverrides=(0,df.mergeWith)({},this.settingsWithoutOverrides,e,xw),this.updateSettings(),this.configReceivedTimeout&&(window.clearTimeout(this.configReceivedTimeout),this.configReceivedTimeout=void 0),this.configReceivedDefer.resolve()}updateSessionCount(e){this.sessionCount=e,0===e&&this.pendingSettings&&(this.logSettings("Applying pending configuration",this.pendingSettings),this.updateSettings(this.pendingSettings),this.pendingSettings=null),e>0&&this.configReceivedTimeout&&this.configReceivedDefer.resolve()}get config(){return this.settings}get stackConfig(){return this.stackSettings}get consoleOverrides(){return this._consoleOverrides}get defaultConfig(){return this.initialSettings}get userAgentConfig(){return this.uaConfig}get countryCode(){return this.country}setMediaConfiguration(e){this.mediaConfiguration=e,this.mediaSettings.setMediaConfiguration(e)}get mediaConfig(){return this.mediaSettings}get ETag(){return this.etag}get ecsConfigIds(){return this.configIds}setConsoleOverrides(e){this._consoleOverrides=(0,df.mergeWith)({},this._consoleOverrides,e,xw),this.updateSettings()}setConsoleOverride(e,t){this._consoleOverrides[e]=t,this.updateSettings()}clearConsoleOverride(e){delete this._consoleOverrides[e],this.updateSettings()}clearAllConsoleOverrides(){this._consoleOverrides={},this.updateSettings()}updateSettings(e=this.settingsWithoutOverrides){if(this.sessionCount>0)return this.pendingSettings=e,void this.logSettings("pendingSettings updated",e);this.settings=this.mergeSettings(e),this.event("configUpdated").raise(),this.logSettings("Settings updated",this.settings)}logSettings(e,t){const i=Object.entries(t).reduce(((e,[t,i])=>(i!==this.initialSettings[t]&&(e[t]=i),e)),{});this.logger.safe.info(`${e}: ${JSON.stringify(i)}`)}mergeSettings(e){if(!e.enablePlatformCallConstraints&&!this._consoleOverrides.enablePlatformCallConstraints)return this.mergeSettingsWithConsoleOverrides(e);let t=e;const{setConsoleOverridesBeforeCallConstraints:i}=this._consoleOverrides;return i&&(t=this.mergeSettingsWithConsoleOverrides(t)),t=this.mergeSettingsWithPlatformConstraints(t),i||(t=this.mergeSettingsWithConsoleOverrides(t)),t}mergeSettingsWithConsoleOverrides(e){return this.logger.safe.info(`Merging settings with console overrides: ${Be(this._consoleOverrides)}`),(0,df.mergeWith)({},e,this._consoleOverrides,xw)}mergeSettingsWithPlatformConstraints(e){const t=this.platformCallConstraintsProvider.getSettings(e);return this.logger.safe.info(`Merging settings with platform call constraints: ${Be(t)}`),(0,df.assign)({},e,t,xw)}},Uw=class{constructor(e,t){this.streamClient=e,this.logger=t,this.rawBaseClient=new Mp((()=>this.getStream()),(()=>this.activeRawInputMediaStreamClient?.dispose()),t)}client(){return this.rawBaseClient}disposeActiveMediaStreamClient(){this.logger.info("Disposing active media stream client"),this.activeRawInputMediaStreamClient?.dispose("Disposed by RawDeviceStreamManager"),this.activeRawInputMediaStreamClient=null}async getStream(){return this.activeRawInputMediaStreamClient?.originalMediaStream?.active?(this.logger.info("Returning stream from active mediaStreamClient"),this.activeRawInputMediaStreamClient.originalMediaStream):(this.activeRawInputMediaStreamClient=await this.streamClient(),await this.activeRawInputMediaStreamClient.start(),this.activeRawInputMediaStreamClient.originalMediaStream)}},Bw=class{constructor(e,t){this.logger=e,this.raiseTelemetryEvent=t,this.handlerMap=new Map([["Audio",new Map],["Video",new Map],["ScreenShare",new Map]])}dispose(e){this.logger.info(`disposing IRawStream ${e}`),this.handlerMap.get(e).forEach((e=>e.client().dispose()))}disposeAll(){this.logger.info("Dispose All clients"),this.handlerMap.forEach((e=>e.forEach((e=>e.client().dispose()))))}notifyChange(e){this.handlerMap.get(e).forEach((e=>{e.disposeActiveMediaStreamClient(),e.client().notifyStreamChange()}))}createIRawStreamClient(e,t){this.logger.info(`Create new IRawStream client for ${t}`);const i=new Uw(e,this.logger);return this.handlerAdded(i,t),i.client()}handlerAdded(e,t){const i=e.client();this.setClientSubscription(i,t),this.handlerMap.get(t).set(i.clientId,e)}deleteRawStreamManagerById(e,t){this.logger.info(`Deleting from map: ${t}`),this.handlerMap.get(t).delete(e)}setClientSubscription(e,t){this.logger.info(`Setting subscription on IRawStream client for ${t}`),e.on("clientDisposed",(i=>{this.deleteRawStreamManagerById(e.clientId,t),this.raiseTelemetryEvent("IRawStream_client_disposed",{mediaType:t,clientId:i})})),e.on("rawStreamRequested",(e=>{this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})})),e.on("notifiedOnStreamChanged",(e=>this.raiseTelemetryEvent("IRawStream_media_stream_changed",{mediaType:t,clientId:e})))}},Vw=class extends qe{constructor(e,t){super(e),this.logger=e,this.configProvider=t,this.window=Ug.window,this.isMuted=!1,this.isPlayingAllowed=!1,this.hadPlaybackError=!1,this.audioContext=null,this.sourceNode=null,this.gainNode=null,this.onAudioError=e=>{const t=e&&e.target||this.audio;if(this.hadPlaybackError=!0,t?.error){const e=t.error.code,i=`error with rendering audio code: ${e}, message: ${t.error.message}`;this.event("onAudioPlaybackError").raise(e,Qe.MEDIA_ERROR.audioPlaybackError,i),this.logger.safe.error(i)}else this.logger.safe.error("error with audio rendering")},this.onAudioPaused=async()=>{if(this.configProvider.config.audioRendererRestartOnPause&&this.canPlay&&!this.isMuted){const e=Te();this.logger.safe.info(`[${e}] audio playback is paused by OS, resuming it`),await this.startStream(e)}}}get muted(){return this.isMuted}async setMuted(e,t){return this.isMuted=e,e?this.stopStream(t):this.startStream(t)}get canPlay(){return this.stream&&this.isPlayingAllowed}getStream(){return this.stream}getDeviceId(){return this.deviceId}async play(e){if(this.stream=e,this.isPlayingAllowed=!0,!this.isMuted)return this.startStream()}stop(){this.stopStream(),this.isPlayingAllowed=!1}async setOutputDevice(e,t=Te()){if(this.audio)if(this.configProvider.config.disableAudioOutputSelection)this.logger.safe.warn(`[${t}] audio-output selction is disabled, disableAudioOutputSelection: true`);else if(this.audio.setSinkId){if(e){this.logger.safe.info(`[${t}] setting audio output device ID to ${Ae(e)}`),this.deviceId=e;try{await this.audio.setSinkId(e)}catch(e){this.logger.safe.warn(`[${t}] setSinkId operation was aborted with error ${Be(e)}`)}this.configProvider.config.audioRendererRestartOnDeviceError&&this.hadPlaybackError&&!this.isMuted&&(this.logger.safe.info(`[${t}] audio playback error happened, restarting audio stream on new device`),await this.startStream(t),this.hadPlaybackError=!1)}}else this.logger.safe.warn(`[${t}] setting output device is not supported`);else this.deviceId=e}dispose(){this.logger.safe.info("dispose"),super.dispose(),this.audio&&(this.stop(),this.stream=null,this.audio.removeEventListener("error",this.onAudioError),this.audio.removeEventListener("pause",this.onAudioPaused),this.window.document.body.removeChild(this.audio),this.event("onAudioElementRemoved").raise(this.audio),this.audio=null),this.detachGainNode()}async startStream(e=Te()){if(this.canPlay)try{await this.assureAudioElement(e),this.logger.safe.info(`[${e}] attaching stream to renderer: ${this.stream?.id}`),this.configProvider.config.speakerGainLevel&&this.reattachToGainNode(this.stream,this.configProvider.config.speakerGainLevel),this.audio.srcObject=this.stream,await this.audio.play()}catch(t){this.logger.safe.warn(`[${e}] play operation was aborted with error ${Be(t)}`)}}async assureAudioElement(e=Te()){if(!this.audio)return this.logger.safe.info(`[${e}] creating audio element`),this.audio=this.window.document.createElement("audio"),this.audio.addEventListener("error",this.onAudioError),this.audio.addEventListener("pause",this.onAudioPaused),this.window.document.body.appendChild(this.audio),this.audio.autoplay=!0,this.event("onAudioElementAdded").raise(this.audio),this.setOutputDevice(this.deviceId,e)}stopStream(e=Te()){this.audio&&this.canPlay&&(this.detachGainNode(),this.logger.safe.info(`[${e}] detaching stream from renderer: ${this.stream?.id}`),this.configProvider.config.audioRendererUsePauseOnDetach?this.audio.pause():this.audio.srcObject=null)}attachToGainNode(e,t){this.audioContext=new Ug.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(e),this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=t,this.sourceNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination)}detachGainNode(){this.sourceNode?.disconnect(),this.sourceNode=null,this.gainNode?.disconnect(),this.gainNode=null,this.audioContext?.close(),this.audioContext=null}reattachToGainNode(e,t){this.detachGainNode(),this.attachToGainNode(e,t)}},Hw=class{constructor(e){this.logger=e,this.queue=Promise.resolve()}add(e,t=Te()){let i;i=e instanceof Jh?()=>e.promise:e;const n=this.queue.then(i);return this.queue=n.catch((e=>{if(this.queue){let i="";e instanceof TypeError&&(i=e.stack),this.logger.safe.error(`[${t}] Error from promiseQueue! ${Be(e)} ${i}`)}})),n}dispose(){this.queue=null}},$w=g,Gw=class{constructor(e){this.container=e,this.formatRegexPattern=new RegExp(/{(\d+)}/g),this.elements={},this.previousSamples={},this.overlayToggled=!0,this.createTableCell=(e,t,i)=>{this.elements[e]=document.createElement("td"),this.elements[e].title=e,this.addElementStyle(e,i),this.elements[t].appendChild(this.elements[e])},this.topElement=e.ownerDocument.createElement("div"),this.topElement.classList.add("vdi-occlusion"),this.topElement.style.position="absolute",this.topElement.style.top="0px",this.topElement.style.left="0px",this.topElement.style.zIndex="100",this.topElement.style.transform="inherit",this.topElement.style.backgroundColor="rgba(0, 0, 0, 0.25)",this.topElement.style.pointerEvents="all",this.topElement.style.minWidth="15px",this.topElement.style.minHeight="15px",this.topElement.style.cursor="pointer",this.topElement.onclick=()=>{this.overlayToggled=!this.overlayToggled},this.container.appendChild(this.topElement),this.table=document.createElement("table"),this.table.style.borderCollapse="collapse",this.table.style.fontSize="smaller",this.topElement.appendChild(this.table)}dispose(){this.topElement.removeChild(this.table),this.container.removeChild(this.topElement),this.table=null,this.topElement=null,this.container=null}createTableColumn(e,t){if(this.overlayToggled)for(const i of Object.keys(e)){const n=e[i];n.hideUndefined&&n.values.every((e=>!e))||this.createTableRow(i,n,t)}}createTableRow(e,t,i){this.elements[e]||(this.elements[e]=document.createElement("tr"),this.table.appendChild(this.elements[e]));const n=`${e}-title`,r=`${e}-${i}`,a=this.formatValue(t),s=this.previousSamples[r]!==a;this.previousSamples[r]=a;const o=function(e){const{values:t,lowerThreshold:i,upperThreshold:n,highlightUndefined:r,fixedValueThreshold:a,allowedDeviationThreshold:s}=e;for(const e of t){if(void 0===e&&null===e&&r)return!0;if(a&&a!==e)return!0;if(null==e||!(0,$w.isNumber)(e))return!1;if(i&&Number(e)<=i)return!0;if(n&&Number(e)>=n)return!0;if(s){const i=(0,$w.mean)(t),n=i*s;if(Math.abs(Number(e)-i)>n)return!0}}return!1}(t)||!(!t.highlightChange||!s);this.elements[n]||(this.createTableCell(n,e,!1),this.elements[n].innerText=t.text?t.text:e),this.createTableCell(r,e,o),this.elements[r].innerText=a}clearTable(){for(;this.table.hasChildNodes();)this.table.removeChild(this.table.lastChild);this.elements={}}addElementStyle(e,t){this.elements[e].style.color=t?"#F72F35":"#FBF719",this.elements[e].style.fontSize="smaller",this.elements[e].style.lineHeight="1",this.elements[e].style.padding="0px 1px 0px 1px",this.elements[e].style.maxWidth="60px",this.elements[e].style.overflow="hidden",this.elements[e].style.whiteSpace="nowrap",this.elements[e].style.textOverflow="ellipsis"}formatValue(e){const{values:t,format:i,undefinedFallback:n="N/A"}=e;return i?i.replace(this.formatRegexPattern,((e,i)=>t[i]?t[i].toString():n.toString())):t?.length&&t[0]?t[0].toString():n.toString()}},jw=class{constructor(e,t,i){this.container=t,this.renderer=i,this.subs=[],e&&!this.overlay&&(this.overlay=new Gw(this.container),this.subs.push(this.renderer.on("onVideoSizeChanged",((e,t)=>this.streamSize={width:e,height:t}))),this.subs.push(this.renderer.on("onRendererSizeChanged",((e,t)=>this.rendererSize={width:Math.ceil(t.width),height:Math.ceil(t.height)}))))}setStats(e){if(!this.overlay)return;const{id:t,ssrc:i,keyFramesDecoded:n,nackCount:r,firCount:a,pliCount:s,decoderImplementation:o,packetsLost:l}=e.inboundRTP,{frameRateReceived:c,frameRateDecoded:d,bitrate:u,decodeTime:h}=e.extensions??{},p=this.renderer?.getMsi(),g=this.renderer?.getLocalMsi(),m={streamSize:{format:"{0}x{1}",values:[this.streamSize?.width,this.streamSize?.height],undefinedFallback:0},rendererSize:{format:"{0}x{1}",values:[this.rendererSize?.width,this.rendererSize?.height],undefinedFallback:0},ssrc:{values:[i]},msid:{text:"sourceId/msid",format:"{0}/{1}",values:[p,g]},fps:{text:"FPS(r/d)",format:"{0}/{1}",values:[c,d],highlightUndefined:!0,lowerThreshold:1,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{format:"{0} kbps",values:[Ww(u)],lowerThreshold:24},decodeTime:{format:"{0} ms",values:[h],upperThreshold:15,highlightUndefined:!0},keyFramesDecoded:{text:"KFs",values:[n]},nacksFirsPlisSent:{text:"N/F/P",format:"{0}/{1}/{2}",values:[r,a,s],undefinedFallback:0,highlightChange:!0},packetsLost:{text:"lost",values:[l],undefinedFallback:0,highlightChange:!0},codecImplementationName:{text:"decoder",values:[o],highlightUndefined:!0}};this.overlay.clearTable(),this.overlay.createTableColumn(m,t)}dispose(){this.subs.forEach((e=>e.dispose())),this.subs=[],this.overlay?.dispose(),this.overlay=null,this.container=null,this.renderer=null}},zw=class{constructor(e,t){this.container=t,e&&!this.overlay&&(this.overlay=new Gw(this.container))}setStats(e){if(!this.overlay)return;const t=e=>{const{rid:t,ssrc:i,frameWidth:n,frameHeight:r,framesPerSecond:a,keyFramesEncoded:s,nackCount:o,firCount:l,pliCount:c,encoderImplementation:d,qualityLimitationReason:u}=e.outboundRTP,{cameraOpenResolution:h,bitrate:p,encodeTime:g,frameRateEncoded:m,frameRateSent:f,qp:v}=e.extensions??{};return{rid:{values:[t],hideUndefined:!0},cameraSize:{format:"{0}x{1}",values:[h?.width,h?.height]},inputSize:{format:"{0}x{1}",values:[e.mediaSource?.width,e.mediaSource?.height]},sentSize:{format:"{0}x{1}",values:[n,r]},ssrc:{values:[i]},fps:{text:"FPS(i/e/s)",format:"{0}/{1}/{2}",values:[a,m,f],lowerThreshold:7,upperThreshold:45,allowedDeviationThreshold:.2},bitrate:{format:"{0} kbps",values:[Ww(p)],lowerThreshold:24},encodeTime:{format:"{0} ms",values:[g],upperThreshold:15},keyFramesEncoded:{text:"KFs",values:[s]},qp:{values:[v]},nacksFirsPlisRecv:{text:"N/F/P",format:"{0}/{1}/{2}",values:[o,l,c],undefinedFallback:0,highlightChange:!0},codecImplementationName:{text:"encoder",values:[d],highlightUndefined:!0},qualityLimitationReason:{text:"limited",values:[u],fixedValueThreshold:"none"},bwe:{format:"{0} kbps",values:[Ww(e.transport?.selectedCandidatePair?.availableOutgoingBitrate)],lowerThreshold:100}}};this.overlay.clearTable();const i=[e,...e.altLayouts??[]];for(const e of i)this.overlay.createTableColumn(t(e),e.outboundRTP.id)}dispose(){this.overlay?.dispose(),this.overlay=null,this.container=null}};function Ww(e){return e&&Math.floor((e||0)/1e3)}var qw=class e extends qe{constructor(t,i,n){const r=i.createChild(""+e.rendererId++);super(r),this.container=t,this.configProvider=n,this.video=this.container.ownerDocument.createElement("video"),this.lastNotifiedVideoWidth=0,this.lastNotifiedVideoHeight=0,this.isVideoAttached=!1,this.onVideoDataUpdated=()=>{let e=this.video.videoWidth,t=this.video.videoHeight;(e<32||t<32)&&(e=t=0),this.lastNotifiedVideoWidth===e&&this.lastNotifiedVideoHeight===t||(this.lastNotifiedVideoWidth=e,this.lastNotifiedVideoHeight=t,this.event("onVideoSizeChanged").raise(e,t)),this.playVideo()},this.onVideoError=()=>{this.logger.safe.info(`onVideoError: error with video rendering: ${JSON.stringify(this.video.error)||"no video"}`),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onError",payload:JSON.stringify(this.video.error)||"no video"})},this.onVideoPaused=()=>{this.logger.safe.info("onVideoPaused: video playback is paused"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPaused"}),this.playVideo()},this.onVideoPlayed=()=>{this.logger.safe.info("onVideoPlayed"),this.event("onVideoRendererStateChanged").raise({timestamp:Date.now(),state:"onVideoPlayed"})},this.onContextMenu=e=>{e.preventDefault()},this.logger=r,this.video.style.width="100%",this.video.style.height="100%",this.video.setAttribute("playsinline","true"),this.video.disablePictureInPicture=!0,this.video.autoplay=!0,this.video.muted=!0,this.attachEventListeners(),this.logger.safe.info("created")}getVideoElement(){return this.video}dispose(){super.dispose(),this.isVideoAttached&&(this.container.removeChild(this.video),this.isVideoAttached=!1),this.sizeTracker?.dispose(),this.detachEventListeners(),this.attachMediaStream(null),this.video=null,this.stream=null,this.canvas=null,this.context=null}attachMediaStream(e){this.stream!==e&&(this.stream&&(this.video.srcObject=null),e&&(this.video.hidden=0===e.getVideoTracks().length,this.video.srcObject=e,this.isVideoAttached||(this.container.appendChild(this.video),this.isVideoAttached=!0)),this.stream=e)}setScalingMode(e){this.video.style.objectFit=function(e){switch(e){case"crop":return"cover";case"stretch":return"fill";default:return"contain"}}(e)}getMediaStream(){return this.stream}getTrackId(){return this.stream?.getTracks()[0]?.id??void 0}async captureFrame(){const e=this.stream;if(!e)throw this.logger.safe.error("Mediastream not found"),new Error("Mediastream not found");const t=e.getVideoTracks?.()?.[0]?.getSettings(),i=t?.width,n=t?.height;if(!i||!n)throw this.logger.safe.error("Failed to get video track width/height"),new Error("Failed to get video track width/height");const r=this.getImageData(i,n);return{getSize:()=>({width:i,height:n}),isMirrored:()=>!1,getImageData:()=>r}}playVideo(){this.video?.paused&&this.video.play().catch((e=>{this.logger.safe.error(`Play video error: ${e}`)}))}getImageData(e,t){if(this.canvas??(this.canvas=this.container.ownerDocument.createElement("canvas")),this.context??(this.context=this.canvas.getContext("2d")),!this.context)throw this.logger.safe.error("Failed to get canvas 2d context"),new Error("Failed to get canvas 2d context");return this.canvas.width=e,this.canvas.height=t,this.context.drawImage(this.video,0,0,e,t),this.context.getImageData(0,0,e,t)}attachEventListeners(){this.video.addEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.addEventListener("timeupdate",this.onVideoDataUpdated),this.video.addEventListener("error",this.onVideoError),this.video.addEventListener("pause",this.onVideoPaused),this.video.addEventListener("contextmenu",this.onContextMenu),this.video.addEventListener("play",this.onVideoPlayed)}detachEventListeners(){this.video.removeEventListener("loadedmetadata",this.onVideoDataUpdated),this.video.removeEventListener("timeupdate",this.onVideoDataUpdated),this.video.removeEventListener("error",this.onVideoError),this.video.removeEventListener("pause",this.onVideoPaused),this.video.removeEventListener("contextmenu",this.onContextMenu),this.video.removeEventListener("play",this.onVideoPlayed)}};qw.rendererId=0;var Kw=qw;function Jw(e){return e.map((e=>new Yw(e.w,e.h,e.minBr,e.maxBr)))}var Yw=class{constructor(e,t,i=0,n=0){this.width=e,this.height=t,this.minBitrate=i,this.maxBitrate=n,this.fs=Math.ceil(e/Qe.MACROBLOCK_SIZE)*Math.ceil(t/Qe.MACROBLOCK_SIZE)}toString(){return this.height?`${this.height}p`:`${this.fs}fs`}},Qw=class e{constructor(e){e||(this.resolutions=Jw(Qe.RES_TABLE.SEND)),this.resolutions=Jw(e)}static initialize(t){e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride),t.on("configUpdated",(()=>{e.Send=new e(t.config.sendResolutionTableOverride),e.Recv=new e(t.config.recvResolutionTableOverride)}))}get initialResolution(){return this.resolutions[this.resolutions.length-1]}getResolutionByFs(e){for(let t=this.resolutions.length-1;t>=0;t--)if(this.resolutions[t].fs<=e)return this.resolutions[t];return this.resolutions[0]}getMaxFS(e,t){return this.getResolutionRecord(e,t).fs}getResolutionForBitrate(e){let t=this.resolutions.filter((t=>t.maxBitrate&&t.maxBitrate>=e)).shift(),i=this.resolutions.filter((t=>t.minBitrate&&t.minBitrate<=e)).pop();return t=t??i,i=i??t,{lowRes:t,highRes:i}}getBitrateForResolution(e,t){const i=this.getResolutionRecord(e,t);return{minBitrate:i.minBitrate,maxBitrate:i.maxBitrate}}getResolutionForHeight(e){for(let t=this.resolutions.length-1;t>=0;t--)if(this.resolutions[t].height<=e)return this.resolutions[t];return this.resolutions[0]}getResolutionRecord(e,t){const i=Math.max(e,t),n=Math.min(e,t);for(const e of this.resolutions)if(e.width>=i&&e.height>=n)return e;return this.resolutions[this.resolutions.length-1]}getNextLowerResolution(e,t){const i=Math.min(e,t),n=this.getResolutionForHeight(i),r=this.resolutions.indexOf(n);return this.resolutions[r-1]}getNextHigherResolution(e,t){const i=Math.min(e,t),n=this.getResolutionForHeight(i),r=this.resolutions.indexOf(n);return this.resolutions[r+1]}getResolutions(){return this.resolutions}};Qw.Recv=new Qw(Qe.RES_TABLE.RECV),Qw.Send=new Qw(Qe.RES_TABLE.SEND);var Zw=Qw,Xw=class extends qe{constructor(e,t,i,n){super(),this.videoElement=e,this.minInterval=t,this.maxInterval=i,this.window=Ug.window,this.devicePixelRatio=n&&window.devicePixelRatio||1,this.originalVideoElementSize={width:e.offsetWidth,height:e.offsetHeight},this.initializeSizeTracking()}get width(){return this.originalVideoElementSize.width*this.devicePixelRatio}get height(){return this.originalVideoElementSize.height*this.devicePixelRatio}initializeSizeTracking(){const e=Math.floor(Math.random()*Math.abs(this.maxInterval-this.minInterval))+this.minInterval;this.elementSizeTrackingRef=this.window.setInterval((()=>{this.videoElementSizeChanged()&&(this.saveCurrentVideoElementSize(),this.raiseChanged())}),e)}triggerVideoElementSizeChange(){this.originalVideoElementSize.height&&this.originalVideoElementSize.width&&this.raiseChanged()}dispose(){this.elementSizeTrackingRef&&this.window.clearInterval(this.elementSizeTrackingRef)}videoElementSizeChanged(){return this.originalVideoElementSize.width!==this.videoElement.offsetWidth||this.originalVideoElementSize.height!==this.videoElement.offsetHeight}saveCurrentVideoElementSize(){this.originalVideoElementSize.width=this.videoElement.offsetWidth,this.originalVideoElementSize.height=this.videoElement.offsetHeight}},eR=class extends Kw{constructor(e,t,i,n){super(e,i.createChild("local"),n),this.mediaStreamProvider=t,this.isDisposed=!1,this.serialQueue=new Hw(this.logger.createChild("rendererQueue")),this.lastNotifiedRendererResolution={width:0,height:0},this.logger.safe.info("ctor"),this.overlayStats=new zw(this.configProvider.config.showStatsInCall,e)}getResolution(){return this.lastNotifiedRendererResolution}dispose(){this.logger.safe.info("dispose"),this.isDisposed=!0,this.event("onRendererDisposed").raise(this),super.dispose(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),this.statsSub?.dispose(),this.overlayStats.dispose()}setVideoMirroring(e){this.configProvider.config.localPreviewMirroringSupported&&(this.getVideoElement().style.transform=e?"scaleX(-1)":void 0)}startVideoAsync(e=Te()){return this.logger.safe.info(`[${e}] starting local video`),this.event("onRendererStarted").raise(this),this.sizeTracker=new Xw(this.getVideoElement(),this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax,this.configProvider.config.enableDevicePixelRatio),this.sizeTracker.changed((()=>this.onSizeTrackerChanged())),this.serialQueue.add((()=>this.restartVideo()),e)}updateStreamAsync(e=Te()){return this.logger.safe.info(`[${e}] updating local video`),this.serialQueue.add((()=>this.restartVideo()),e)}setStatsProvider(e){this.statsSub?.dispose(),this.statsSub=e.on("onDiagnosticUpdated",(e=>{e.video?.send?.length&&this.overlayStats.setStats(e.video?.send[0])}))}onSizeTrackerChanged(){const e=this.sizeTracker.width,t=this.sizeTracker.height,i=Zw.Send.getResolutionForHeight(Math.min(t,e));this.lastNotifiedRendererResolution.width===i.width&&this.lastNotifiedRendererResolution.height===i.height||(this.lastNotifiedRendererResolution.width=i.width,this.lastNotifiedRendererResolution.height=i.height,this.event("onRendererSizeChanged").raise(this,{height:i.height,width:i.width}))}async restartVideo(){const e=await this.mediaStreamProvider.getVideoStream(!1,"localVideoRenderer");try{if(await e.start(),this.isDisposed)throw e.dispose(),new Error("local video renderer is disposed");this.attachStream(e)}catch(e){throw this.mediaStreamProvider.raiseTelemetryEvent("video_preview_error",{mediaType:"Video",error:Be(e)}),e}}attachStream(e){if(this.mediaStream!==e)if(this.mediaStream?.parentId!==e?.parentId){this.logger.safe.info(`attach media stream ${e?.id}`);try{this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),e&&super.attachMediaStream(e.rawStream),this.mediaStream=e}catch(t){throw e&&e.dispose(),t}}else e.dispose()}},tR=g;function iR(e,t){const i=e.width/e.height,n=(0,tR.clone)(e);return i>t?n.width=Math.floor(e.height*t):i<t&&(n.height=Math.floor(e.width/t)),n}var nR=class e{constructor(e,t,i=!0,n=!1,r){this.audio=e,this.video=t,this.withTimeout=i,this.withEffect=n,this.withOverridenStream=r}clone(){const t=lt(this.video),i=lt(this.audio);return new e(i,t,this.withTimeout,this.withEffect,this.withOverridenStream)}},rR=class{constructor(e){this.logger=e}dispose(){}updateVideoConstraints(e,t,i){const n=this.calculateConstraints(t,i);this.logger.safe.info(`Calculated constraints: ${JSON.stringify(n)} from capabilities: ${JSON.stringify(t)}`);const r=n.resolution,a=n.fps,s=r&&(!mt(r.width,e.video.minWidth,e.video.maxWidth)||!mt(r.height,e.video.minHeight,e.video.maxHeight)),o=e.video.fps!==a;if(!s&&!o)return e;const l=e.clone();return s&&this.setResolution(l,r),o&&(l.video.fps=a),l}updateResolution(e,t){const i=e.clone();return this.setResolution(i,t),i}setResolution(e,t){e.video.maxWidth=t.width,e.video.minWidth=t.width,e.video.maxHeight=t.height,e.video.minHeight=t.height}getKey(e){return e.video?at(e.video)?"video":e.video.deviceId&&e.video.minWidth&&e.video.minHeight?`${e.video.deviceId}x${e.video.minWidth}x${e.video.minHeight}`:e.video.minWidth&&e.video.minHeight?`${e.video.minWidth}x${e.video.minHeight}`:e.video.deviceId?`${e.video.deviceId}`:(this.logger.safe.error(`Cannot create key for constraints: ${gm(e)}`),""):"audio"}convertConstraints(e,t={}){if(!e)return null;const i=lt(t);return e?.deviceId&&(i.deviceId=e.deviceId),i}},aR=class{constructor(){this.MAX_SHARING_WIDTH=1920,this.MAX_SHARING_HEIGHT=1080}getResolutionTable(e,t){const i=this.constraintToMaxResolution(e,t);return this.generateResolutionTable(i)}constraintToMaxResolution(e,t){const i=this.getPortraitOrLandscapeMaxResolution(e),n=iR({width:e.width,height:e.height},t),r=i.width/n.width,a=i.height/n.height,s=Math.min(r,a);return this.resizeResolution(n,s)}resizeResolution(e,t){return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}getPortraitOrLandscapeMaxResolution(e){return e.width>e.height?{width:this.MAX_SHARING_WIDTH,height:this.MAX_SHARING_HEIGHT}:{width:this.MAX_SHARING_HEIGHT,height:this.MAX_SHARING_WIDTH}}ceilToMackroblockSize(e){const t=e.width,i=e.height;return{width:Math.ceil(t/Qe.MACROBLOCK_SIZE)*Qe.MACROBLOCK_SIZE,height:Math.ceil(i/Qe.MACROBLOCK_SIZE)*Qe.MACROBLOCK_SIZE}}generateResolutionTable(e){return[1,2/3,1/3,1/6].map((t=>this.resizeResolution(e,t))).map((e=>this.ceilToMackroblockSize(e)))}},sR=class{constructor(e){this.logger=e,this.FPS_TABLE=[15,7.5,3.75,1.875],this.resolutionTableCalculator=new aR,this.initialAspectRatio=null}calculateConstraints(e,t){this.initialAspectRatio||(this.initialAspectRatio=t.width/t.height);const i=this.resolutionTableCalculator.getResolutionTable(t,this.initialAspectRatio);let n={resolution:i[i.length-1],fps:this.FPS_TABLE[this.FPS_TABLE.length-1]};return i.some((t=>{const i=this.getFs(t);return this.FPS_TABLE.some((r=>{const a=this.getMbps(i,r);return i<=e.maxFs&&r<=e.maxFps&&a<=e.maxMbps&&(n={resolution:t,fps:r},!0)}))}))?this.logger.safe.info(`Calculated resolution: ${JSON.stringify(n)}`):this.logger.safe.error(`None of available resolutions are suitable: ${JSON.stringify(i)}. Fallback to: ${JSON.stringify(n)}`),n}getMbps(e,t){return e*t}getFs(e){return Math.ceil(e.width/Qe.MACROBLOCK_SIZE)*Math.ceil(e.height/Qe.MACROBLOCK_SIZE)}},oR=class{constructor(e,t){this.logger=e,this.maxCapabilities=t}ensureValidity(e){this.throwIfMissing(e);const t=this.calculateMissing(e);return this.maxCapabilities&&this.applyMaxCapabilities(t),this.logger.safe.info(`Validating capabilities ${JSON.stringify(t)}`),t}throwIfMissing(e){if(!e.maxFs&&!e.maxMbps&&!e.maxFps||e.maxFs&&!e.maxMbps&&!e.maxFps||!e.maxFs&&e.maxMbps&&!e.maxFps||!e.maxFs&&!e.maxMbps&&e.maxFps)throw new Error(`Missing video capabilities ${JSON.stringify(e)}`)}calculateMissing(e){const t=ot(e);return!e.maxFs&&e.maxMbps&&e.maxFps&&(t.maxFs=e.maxMbps/e.maxFps),e.maxFs&&!e.maxMbps&&e.maxFps&&(t.maxMbps=e.maxFs*e.maxFps),e.maxFs&&e.maxMbps&&!e.maxFps&&(t.maxFps=e.maxMbps/e.maxFs),t}applyMaxCapabilities(e){this.maxCapabilities.maxFs&&(e.maxFs=Math.min(e.maxFs,this.maxCapabilities.maxFs)),this.maxCapabilities.maxMbps&&(e.maxMbps=Math.min(e.maxMbps,this.maxCapabilities.maxMbps)),this.maxCapabilities.maxFps&&(e.maxFps=Math.min(e.maxFps,this.maxCapabilities.maxFps))}},lR=class extends rR{constructor(e,t){super(e),this.initialConstraints={maxWidth:1920,minWidth:1920,maxHeight:1080,minHeight:1080,fps:15},this.maxCapabilities={maxFs:8160,maxFps:15},this.validator=new oR(this.logger.createChild("CV"),this.maxCapabilities),this.constraintsCalculator=new sR(this.logger.createChild("CC")),t.config.resizeModeForSharing&&(this.initialConstraints.resizeMode=t.config.resizeModeForSharing)}createConstraintsObject(e){if(!e.sharing)throw new Error(`Sharing constraints are not presented: ${JSON.stringify(e)}`);const t=this.convertConstraints(e.sharing,this.initialConstraints),i=e.audio?e.audio:null;return i?.deviceId===Qe.SYSTEM_AUDIO_SOURCE_ID&&delete i.deviceId,new nR(i,t,!1,!1,e.withOverridenStream)}generatePolicies(e){return[e]}calculateConstraints(e,t){this.logger.safe.info(`Stream resolution is ${JSON.stringify(t)}`);const i=this.validator.ensureValidity(e);return this.constraintsCalculator.calculateConstraints(i,t)}},cR=class extends lR{constructor(e,t,i){super(e,i);const n=t.screen.width/t.screen.height;n<1&&([this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[this.initialConstraints.maxHeight,this.initialConstraints.maxWidth],[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[this.initialConstraints.minHeight,this.initialConstraints.minWidth]);let r=iR({width:this.initialConstraints.maxWidth,height:this.initialConstraints.maxHeight},n);[this.initialConstraints.maxWidth,this.initialConstraints.maxHeight]=[r.width,r.height],r=iR({width:this.initialConstraints.minWidth,height:this.initialConstraints.minHeight},n),[this.initialConstraints.minWidth,this.initialConstraints.minHeight]=[r.width,r.height]}},dR=class extends rR{constructor(e,t){super(t),this.configProvider=e}createConstraintsObject(e){const t={},i=ri().engine;void 0!==e.audioProcessingFlags&&("Chromium"===i||"ChromiumAVD"===i?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags),this.configProvider.config.useGoogPrefixAudioConstraints&&(t.googAutoGainControl=!!(1&e.audioProcessingFlags),t.googAutoGainControl2=!!(1&e.audioProcessingFlags),t.googEchoCancellation=!!(2&e.audioProcessingFlags),t.googHighpassFilter=!!(4&e.audioProcessingFlags),t.googNoiseSuppression=!!(4&e.audioProcessingFlags),t.googTypingNoiseDetection=!!(4&e.audioProcessingFlags))):"Safari"===i||"Firefox"===i?(t.autoGainControl=!!(1&e.audioProcessingFlags),t.echoCancellation=!!(2&e.audioProcessingFlags),t.noiseSuppression=!!(4&e.audioProcessingFlags)):this.logger.warn(`Unsupported browser for audio processing flags ${i}`));const n=this.convertConstraints(e.audio,t),r=this.convertConstraints(e.video,this.initialVideoConstraints);return new nR(n,r,e.withTimeout,e.withEffect,e.withOverridenStream)}calculateConstraints(e){const t=Math.min(e.maxFs,this.configProvider.config.webrtcCameraOpenFs);return{resolution:Zw.Send.getResolutionByFs(t),fps:e.maxFps}}get initialVideoConstraints(){const e=Zw.Send.getResolutionByFs(this.configProvider.config.webrtcCameraOpenFs);return{maxWidth:e.width,minWidth:e.width,maxHeight:e.height,minHeight:e.height,fps:this.configProvider.config.maxCameraOpenFps}}},uR=class{static getProvider(e,t,i){if("ScreenShare"===e){const e=i.createChild("SharingCP");return"Safari"===ri().name?new cR(e,Ug.window,t):new lR(e,t)}return new dR(t,i.createChild("VideoCP"))}},hR=class{constructor(){}getPolicies(e){if(e.audio&&!e.video&&this.hasAudioProcessingConstraints(e))return[e,new nR({deviceId:e.audio.deviceId},null)];if(!e.video)return[e];const t=this.getSuitableResolutions(e).map((t=>this.getConstraintsForResolution(e,t))),i=e.audio,n={deviceId:e.video.deviceId},r=new nR(i,n,e.withTimeout);return t.push(r),t}getSuitableResolutions(e){return Zw.Send.getResolutions().filter((t=>t.width<=e.video.maxWidth&&t.height<=e.video.maxHeight)).reverse()}getConstraintsForResolution(e,t){const i=e.clone();return i.video.minWidth=t.width,i.video.minHeight=t.height,i}hasAudioProcessingConstraints(e){const t=e&&e.audio;return t&&(void 0!==t.echoCancellation||void 0!==t.autoGainControl||void 0!==t.noiseSuppression)}},pR=class{constructor(e,t){this.error=e,this.constraints=t,this.permissionDeniedBySystemErrorMsg=["Permission denied by system","The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission."]}getMediaError(){let e;switch(this.error.name){case"SourceUnavailableError":case"TrackStartError":case"NotReadableError":case"AbortError":e={type:Qe.MEDIA_ERROR.sourceUnavailableError,detail:`media device is already used by another process: ${Be(this.error)}`};break;case"ConstraintNotSatisfiedError":case"OverconstrainedError":e={type:Qe.MEDIA_ERROR.constraintNotSatisfiedError,detail:`could not obtain constrained media stream: ${Be(this.error)}`};break;case"DevicesNotFoundError":case"NotFoundError":e={type:Qe.MEDIA_ERROR.devicesNotFoundError,detail:`specified device not found: ${Be(this.error)}`};break;case"NotAllowedError":e=this.permissionDeniedBySystemErrorMsg.some((e=>e===this.error.message))?{type:Qe.MEDIA_ERROR.permissionDeniedBySystemError,detail:`no system permissions: ${Be(this.error)}`}:{type:Qe.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${Be(this.error)}`};break;case"PermissionDeniedError":case"PermissionDismissedError":e={type:Qe.MEDIA_ERROR.permissionDeniedError,detail:`permission to use media device was denied: ${Be(this.error)}`};break;case Qe.MEDIA_ERROR.extensionNotFoundError:e={type:Qe.MEDIA_ERROR.extensionNotFoundError,detail:`extension is not found: ${Be(this.error)}`};break;case Qe.MEDIA_ERROR.chromeRuntimeNotDefinedError:e={type:Qe.MEDIA_ERROR.chromeRuntimeNotDefinedError,detail:`chrome runtime is not defined: ${Be(this.error)}`};break;case Qe.MEDIA_ERROR.sharingCancelledError:e=this.getSharingCancelledError(this.error);break;case Qe.MEDIA_ERROR.mediaStreamRequestTimedOut:e={type:Qe.MEDIA_ERROR.mediaStreamRequestTimedOut,detail:"Media Stream request timed out."};break;default:e=this.error.message===Qe.MEDIA_ERROR.sharingCancelledError?this.getSharingCancelledError(this.error):{type:Qe.MEDIA_ERROR.mediaStreamRequestError,detail:`media stream request error: ${Be(this.error)}`}}return e.isAudio=!!this.constraints.audio,e.detail+=` constraints: ${Be(gm(this.constraints))}`,e.message=e.detail,e}getSharingCancelledError(e){return{type:Qe.MEDIA_ERROR.sharingCancelledError,detail:`screen sharing cancelled: ${Be(e)}`}}},gR=class{constructor(e){this.logger=e}static isSupported(){return!0}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be applied: ${JSON.stringify(gm(t))}`),new Promise(((e,i)=>{Ug.window.navigator.getUserMedia(t,e,i)})).catch((t=>{throw new pR(t,e).getMediaError()}))}applyConstraints(e,t){if(!e||!e.getVideoTracks()||!e.getVideoTracks()[0])return Promise.reject("No video tracks found");const i=e.getVideoTracks()[0];return this.applyConstraintsForTrack(i,t)}applyConstraintsForTrack(e,t){const i=this.constraintsAdapter.toTrackConstraints(t);return e.applyConstraints?(this.logger.safe.info(`Apply constraints: ${JSON.stringify(i)} on ${JSON.stringify(e.id)}`),e.applyConstraints(i).catch((e=>{throw new pR(e,t).getMediaError()}))):Promise.reject("track.applyConstraints() is not supported")}},mR=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};return e.audio&&(t.audio=lt(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Qe.MEDIA_DEVICE.defaultId&&(t.audio.deviceId=e.audio.deviceId)),e.video&&(t.video={mandatory:{}},e.video.deviceId&&(t.video.mandatory.sourceId=e.video.deviceId),e.video.minWidth&&(t.video.mandatory.minWidth=e.video.minWidth),e.video.maxWidth&&(t.video.mandatory.maxWidth=e.video.maxWidth),e.video.minHeight&&(t.video.mandatory.minHeight=e.video.minHeight),e.video.maxHeight&&(t.video.mandatory.maxHeight=e.video.maxHeight),e.video.fps&&(t.video.mandatory.maxFrameRate=e.video.fps,this.configProvider.config.setMinFpsForWebkit&&(t.video.mandatory.minFrameRate=this.configProvider.config.minCameraOpenFps,t.video.mandatory.idealFrameRate=e.video.fps)),at(t.video.mandatory)&&delete t.video.mandatory),t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},fR=class{constructor(e){this.configProvider=e}toGumConstraints(e){const t={};if(e.audio&&(t.audio=lt(e.audio),t.audio.deviceId&&delete t.audio.deviceId,e.audio.deviceId&&e.audio.deviceId!==Qe.MEDIA_DEVICE.defaultId&&(t.audio.deviceId={exact:e.audio.deviceId})),e.video){t.video={width:{},height:{},frameRate:{}},e.video.deviceId&&(t.video.deviceId={exact:e.video.deviceId}),e.video.minWidth&&(t.video.width.min=e.video.minWidth),e.video.maxWidth&&(t.video.width.max=e.video.maxWidth),e.video.minHeight&&(t.video.height.min=e.video.minHeight),e.video.maxHeight&&(t.video.height.max=e.video.maxHeight),e.video.fps&&(t.video.frameRate.max=e.video.fps,t.video.frameRate.min=this.configProvider.config.minCameraOpenFps,t.video.frameRate.ideal=e.video.fps);for(const e in t.video)at(t.video[e])&&delete t.video[e]}return t}toTrackConstraints(e){const t={};return e.video&&(e.video.minWidth&&(t.width=e.video.minWidth),e.video.minHeight&&(t.height=e.video.minHeight),e.video.fps&&(t.frameRate=e.video.fps)),t}},vR=class{toGumConstraints(e){if(!e||!e.video)throw new Error(`constraints cannot be applied: ${e}`);const t={video:{}},i=e.video.deviceId&&e.video.deviceId!==Qe.DISPLAY_SOURCE_ID;return e.video.resizeMode&&(t.video.resizeMode=e.video.resizeMode),i&&(t.video.deviceId={exact:e.video.deviceId}),e.video.maxWidth&&(t.video.width={max:e.video.maxWidth},i&&(t.video.width.ideal=e.video.maxWidth)),e.video.maxHeight&&(t.video.height={max:e.video.maxHeight},i&&(t.video.height.ideal=e.video.maxHeight)),e.video.fps&&(t.video.frameRate=e.video.fps),e.audio&&(t.audio=!e.audio.deviceId||{deviceId:{exact:e.audio.deviceId}}),t}toTrackConstraints(e){const t=navigator.mediaDevices.getSupportedConstraints();if(!t)throw new Error("Constraints are not supported by browser");const i={};return t.width&&e.video.minWidth&&(i.width=e.video.minWidth),t.height&&e.video.minHeight&&(i.height=e.video.minHeight),t.frameRate&&e.video.fps&&(i.frameRate=e.video.fps),i.resizeMode=e.video.resizeMode,i}},SR=class extends gR{constructor(e,t){if(super(t.createChild("WebRTCProvider")),this.configProvider=e,this.timeoutId=null,void 0!==navigator.webkitGetUserMedia&&void 0!==webkitRTCPeerConnection&&xg()){if(!this.configProvider.config.overrideGumFromWebkit||!Og)return void(this.constraintsAdapter=new mR(e));this.logger.safe.info("Overriding getUserMedia from webkit"),Fg()}this.constraintsAdapter=new fR(e)}getStream(e){if(!e.withTimeout||!this.configProvider.config.gumRequestTimeout)return super.getStream(e);const t=this.startGumRequestTimer(e),i=super.getStream(e).then((t=>{if(!this.timeoutId)throw this.stopStreamAfterTimeout(t,e),this.getMediaStreamTimeoutError(e);return this.stopGumRequestTimer(),t}));return Promise.race([t,i]).catch((e=>{throw this.stopGumRequestTimer(),e}))}getMediaStreamTimeoutError(e){const t={name:Qe.MEDIA_ERROR.mediaStreamRequestTimedOut,message:`Media stream request timed out. Constraints: ${Be(gm(e))}`};return new pR(t,e).getMediaError()}startGumRequestTimer(e){return new Promise(((t,i)=>{this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,i(this.getMediaStreamTimeoutError(e))}),this.configProvider.config.gumRequestTimeout)}))}stopGumRequestTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}stopStreamAfterTimeout(e,t){this.logger.safe.info(`Stopping media stream acquired after timeout: ${JSON.stringify(e.id)} with constraints: ${JSON.stringify(t)}`);try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${Be(e)}`)}}},yR=class extends gR{constructor(e){super(e.createChild("WebRTCDispProvider")),this.constraintsAdapter=new vR}static isSupported(){return!!window.navigator.mediaDevices.getDisplayMedia}getStream(e){const t=this.constraintsAdapter.toGumConstraints(e);return this.logger.safe.info(`Constraints to be used: ${JSON.stringify(t)}`),Promise.resolve().then((()=>e.video?.deviceId&&e.video?.deviceId!==Qe.DISPLAY_SOURCE_ID?Ug.window.navigator.mediaDevices.getUserMedia(t):Ug.window.navigator.mediaDevices.getDisplayMedia(t))).catch((t=>{throw new pR(t,e).getMediaError()}))}},CR=class{constructor(e){this.detail=e}getStream(e){throw this.getError(e)}applyConstraints(e,t){throw this.getError(t)}applyConstraintsForTrack(e,t){throw this.getError(t)}getError(e){return{type:Qe.MEDIA_ERROR.unsupportedStream,detail:this.detail,message:this.detail,isAudio:!!e.audio}}},_R=class{static getStreamProvider(e,t,i){return"ScreenShare"===e?yR.isSupported()?new yR(i):(i.error("GUM stream provider cannot be created for display stream"),new CR("Sharing not supported")):new SR(t,i)}},ER=class extends qe{constructor(e,t,i){super(i),this.mediaStream=e,this.logger=i,this.mediaStreamSubscriptions=[],this.isHold=!1,this.isMuted=this.mediaStream.getMuted(),this._isDisposed=!1,this.originalId=e.id,this.subscribeOnMediaStreamEvents(),this.update(t),this.logger.safe.info("ctor"),this.mediaType=this.mediaStream.mediaType}get id(){return this.originalId}get parentId(){return this.originalId}get rawStream(){return this.gumStream}get rawTrack(){return this.getTrackByMediaType(this.rawStream,this.mediaType)}get deviceId(){return this.mediaStream.deviceId}update(e){e&&(this.gumStream=e,this.enableDisableTracks())}dispose(){this._isDisposed?this.logger.safe.info("already disposed"):(this._isDisposed=!0,this.logger.safe.info("dispose"),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaStream&&(this.mediaStream.disposeClient(this),this.unsubscribeFromMediaStreamEvents(),this.mediaStream=null),this.event("onStreamClientDisposed").raise(this))}clone(){const e=this.mediaStream.getClient();return this.isMuted&&e.setMuted(!0),this.isHold&&e.setHold(!0),e}applyCapabilities(e){return this.mediaStream.applyCapabilities(e)}setMuted(e,t=Te()){this.isMuted=e||this.mediaStream.getMuted(),this.logger.safe.info(`[${t}] setMuted => ${this.isMuted}`),this.enableDisableTracks()}setHold(e){this.isHold=e,this.enableDisableTracks()}start(){return this.mediaStream.start()}hasAudio(){return this.mediaStream.hasAudio()}hasVideo(){return this.mediaStream.hasVideo()}hasDisplay(){return this.mediaStream.hasDisplay()}isSameStream(e){return this.parentId===e.parentId}getResolution(){return this.mediaStream.getResolution()}getFrameRate(){return this.mediaStream.getFrameRate()}isActive(){return!0}isDisposed(){return this._isDisposed}subscribeOnMediaStreamEvents(){this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamStarted",((e,t)=>{this.event("onStreamClientStarted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamError",((e,t)=>{this.event("onStreamClientError").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackMuted",((e,t)=>{this.event("onStreamClientMuted").raise(this,t)}))),this.mediaStreamSubscriptions.push(this.mediaStream.on("onStreamTrackEnded",((e,t)=>{this.event("onStreamClientEnded").raise(this,t)})))}unsubscribeFromMediaStreamEvents(){this.mediaStreamSubscriptions.forEach((e=>e.dispose())),this.mediaStreamSubscriptions=[]}enableDisableTracks(){this.gumStream?this.gumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`Track ${JSON.stringify(e.id)} enabled state set to => ${e.enabled}`))})):this.logger.safe.warn("gumStream stream doesn't exist")}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}},TR=[30,15,7.5,3.75,1.875];function bR(e){return e&&e.getVideoTracks()[0]?IR(e.getVideoTracks()[0]):null}function IR(e){if(e&&e.getSettings){const t=e.getSettings();if(t)return{width:t.width,height:t.height}}return null}function wR(e){return e&&e.getVideoTracks()[0]?RR(e.getVideoTracks()[0]):0}function RR(e){if(e&&e.getSettings){const t=e.getSettings();if(t)return gt(TR,t.frameRate,!0)}return 0}var AR=class e extends qe{constructor(t,i,n,r){super(n),this.streamConstraints=t,this.serialQueue=i,this.configProvider=r,this.clientId=0,this.clients=[],this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.isMuted=!1,this.isHold=!1,this.gumStartTime=0,this.streamId=e.streamGeneration++,this.logger=n.createChild(`MediaStream:${this.streamId}`),this.mediaType=this.getMediaType(this.streamConstraints),this.constraintsProvider=uR.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(t)}get id(){return this.streamId}get rawStream(){return this.currentGumStream}get deviceId(){return this.rawStream?.getTracks()?.[0]?.getSettings?.()?.deviceId??null}applyCapabilities(e){if(this.currentGumStream){const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t)return Promise.resolve(!1);if(this.currentConstraints!==t){this.currentConstraints=t;const e=this.currentConstraints;return this.hasDisplay()?this.applyConstraints(this.currentConstraints).then((()=>ut(this.currentConstraints,e))).catch((e=>(this.logger.safe.error(`Apply constraints error: ${Be(e)}`),!1))):this.applyConstraintsInternal().then((()=>ut(this.currentConstraints,e)))}}return Promise.resolve(!1)}getClient(){let e;this.currentGumStream?(e=this.getClone(),this.clientGumStreams.push({[this.constraintsProvider.getKey(this.currentConstraints)]:e})):this.clientGumStreams.push({});const t=new ER(this,e,this.logger.createChild("Client:"+this.clientId++));return this.clients.push(t),t}getClone(){return this.hasDisplay()?this.currentGumStream:this.currentGumStream.clone()}setMuted(e){this.isMuted=e,this.clients.forEach((t=>{t.setMuted(e)})),this.enableDisableTracks()}getMuted(){return this.isMuted}setHold(e){this.isHold=e,this.clients.forEach((t=>{t.setHold(e)})),this.enableDisableTracks()}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(){for(let e=this.clients.length-1;e>=0;e--)this.clients[e].dispose()}disposeClient(e){const t=this.clients.indexOf(e);t>=0&&(this.clients.splice(t,1),this.streamsDump.push(this.clientGumStreams[t]),this.clientGumStreams.splice(t,1),0===this.clients.length)&&this.disposeStream()}async disposeStream(){this.event("onStreamDisposing").raise(this);try{await this.stopGumStream(),this.event("onStreamDisposed").raise(this)}catch(e){this.event("onStreamError").raise(this,e)}this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),super.dispose()}hasAudio(){return!!this.currentGumStream&&0!==this.currentGumStream.getAudioTracks().length}hasVideo(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId!==Qe.DISPLAY_SOURCE_ID}hasDisplay(){return!!this.currentGumStream&&0!==this.currentGumStream.getVideoTracks().length&&this.currentConstraints.video&&this.currentConstraints.video.deviceId===Qe.DISPLAY_SOURCE_ID}getVideoDeviceId(){return this.currentConstraints.video.deviceId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=bR(this.currentGumStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=wR(this.currentGumStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}async startStream(e){let t;t=e.video?this.applyConstraintsInternal():this.updateGumStreamInternal(e);try{await t,this.event("onStreamStarted").raise(this,e)}catch(e){throw this.event("onStreamError").raise(this,e),e}}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}updateClients(e){const t=this.constraintsProvider.getKey(e);this.clients.forEach(((e,i)=>{this.clientGumStreams[i][t]||(this.clientGumStreams[i][t]=this.getClone()),e.update(this.clientGumStreams[i][t])}))}applyConstraints(e){const t=this.getGumStreamProvider();return Promise.all(this.clients.map((i=>t.applyConstraints(i.rawStream,e)))).then((()=>{}))}applyConstraintsInternal(){return new Promise(((e,t)=>{this.logger.safe.info(`applying stream constraints: ${JSON.stringify(gm(this.currentConstraints))}`);const i=new Jh;this.clients.forEach((e=>{e.onApplyConstraints&&e.onApplyConstraints(i.promise)}));const n=this.serialQueue.add((()=>{const e=(new hR).getPolicies(this.currentConstraints);return this.mediaStreamStartPromise=this.updateGumStreamInternal(e[0]),e.slice(1).forEach((e=>{this.mediaStreamStartPromise=this.mediaStreamStartPromise.catch((t=>{if(Qe.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("could not obtain constrained media stream, will attempt weaker policy"),this.updateGumStreamInternal(e);throw t.constraints=e,t}))})),this.mediaStreamStartPromise})).then((()=>{i.resolve()})).catch((e=>{throw this.logger.safe.error(`failed to apply constraints: ${JSON.stringify(gm(e.constraints))} error: ${Be(e)}`),i.reject(e),e}));e(n)}))}enableDisableTracks(){this.currentGumStream&&this.currentGumStream.getTracks().forEach((e=>{void 0!==e.enabled&&(e.enabled=!("audio"===e.kind&&this.isMuted||this.isHold),this.logger.safe.info(`control media stream track kind: ${e.kind} enabled: ${e.enabled} muted: ${e.muted}`))}))}getGumStreamProvider(){return _R.getStreamProvider(this.mediaType,this.configProvider,this.logger.createChild("MSProvider"))}async updateGumStreamInternal(e){this.logger.safe.info(`querying user media for stream: ${JSON.stringify(e)}`),this.logger.safe.info("Getting GUM stream");const t=await this.getGumStream(e);this.logger.safe.info("Updating gum stream audio tracks"),this.updateGumStreamAudioTracks(t),this.currentGumStream=t,this.logger.safe.info("Updating stream constraints"),this.updateConstraints(e,t),this.logger.safe.info("Caching GUM stream"),this.cacheGumStream(this.currentConstraints,t),this.updateClients(this.currentConstraints),this.updateGumStreamVideoTracks(t),this.enableDisableTracks(),this.logger.safe.info("media stream updated");const i=this.stopRequestCalculation();this.event("onStreamAcquired").raise(this,i,(this.hasVideo()||this.hasDisplay())&&this.getResolution()||void 0)}async getGumStream(e){const t=this.gumStreams[this.constraintsProvider.getKey(e)];if(t)return t;const i=this.getGumStreamProvider();return this.startRequestCalculation(),i.getStream(e)}updateGumStreamAudioTracks(e){e.getAudioTracks().forEach((e=>{e.onended=e=>{this.logger.safe.info(`Audio stream track ended: ${JSON.stringify(e.error?.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},e.onmute=()=>{this.logger.safe.info("Audio stream track muted"),this.event("onStreamTrackMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info("Audio stream track unmuted"),this.event("onStreamTrackMuted").raise(this,!1)},e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`)}))}updateGumStreamVideoTracks(e){const[t]=e.getVideoTracks();t&&(t.onmute=e=>{this.logger.safe.error(`Video stream track muted: ${JSON.stringify(gm(this.currentConstraints))}; ${JSON.stringify(e)}`)},t.onended=e=>{this.logger.safe.info(`Video stream track ended: ${JSON.stringify(gm(this.currentConstraints))}; ${JSON.stringify(e?.error.name||e)}`),this.event("onStreamTrackEnded").raise(this,e)},this.hasDisplay()&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(t,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(t.id)}`))}cacheGumStream(e,t){const i=this.constraintsProvider.getKey(e);this.gumStreams[i]!==t&&(this.gumStreams[i]&&(this.logger.safe.info(`Stream cache hit for ${i}, stopping old stream`),this.stopOneGumStream(this.gumStreams[i])),this.gumStreams[i]=t)}updateConstraints(e,t){this.currentConstraints=e.video?this.constraintsProvider.updateResolution(e,this.getResolution()):e,this.logger.safe.info(`Stream constraints updated: ${JSON.stringify(this.currentConstraints)}`)}applyContentHint(e,t){["","text","detail","motion"].indexOf(t)<0?this.logger.safe.error(`Cannot apply content hint: ${t}`):(this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t)}startRequestCalculation(){this.gumStartTime=Date.now()}stopRequestCalculation(){if(0===this.gumStartTime)return 0;const e=Date.now()-this.gumStartTime;return this.gumStartTime=0,e}stopGumStream(){return this.mediaStreamStartPromise?(this.logger.safe.info("queueing media stream stop"),this.serialQueue.add((()=>{this.stopGumStreamInternal()}))):Promise.resolve()}stopOneGumStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.onended=null,e.onmute=null,e.stop()})),this.logger.safe.info("media stream stopped")}catch(e){this.logger.safe.warn(`failed to stop media stream: ${Be(e)}`)}}stopGumStreamInternal(){this.currentGumStream&&([...this.clientGumStreams,...this.streamsDump,this.gumStreams].forEach((e=>{Ze(e,(e=>{this.stopOneGumStream(e)}))})),this.gumStreams={},this.clientGumStreams=[],this.streamsDump=[],this.currentGumStream=null)}};AR.streamGeneration=0;var PR=AR,MR=class extends qe{constructor(e,t,i,n,r,a,s){super(s),this.id=e,this.masterStream=t,this.currentConstraints=i,this.constraintsProvider=n,this.streamProvider=r,this.configProvider=a,this._isDisposed=!1,this.masterStreamSubscriptions=[],this.mixerSubscriptions=[],this.parentId=t.id,this.logger=s.createChild(`C:${this.parentId}:${this.id}`),this.subscribeOnMasterStreamEvents()}get rawTrack(){return this.mediaTrack}get rawStream(){return this.rawMediaStream||(this.rawMediaStream=new MediaStream([this.mediaTrack]),this.configProvider.config.reassignMediaStreamAudioTrackAfterCreation&&this.rawMediaStream.getAudioTracks().length>0&&(this.rawMediaStream.removeTrack(this.rawMediaStream.getAudioTracks()[0]),this.rawMediaStream.addTrack(this.mediaTrack))),this.rawMediaStream}get deviceId(){return this.masterStream.deviceId}get mediaType(){return this.masterStream.mediaType}get originalMediaStream(){return this.masterStream.getOriginalMediaStream()}getCurrentConstraints(){return this.currentConstraints}dispose(e){this._isDisposed||(this._isDisposed=!0,this.logger.safe.info(`dispose: ${e}`),this.logger=this.logger.createChild("DISPOSED"),this.event("onStreamClientDisposing").raise(this),this.mediaTrack&&(this.unsubscribeFromMediaTrackEvents(),this.mediaTrack=null),this.masterStream&&(this.unsubscribeFromMasterStreamEvents(),this.masterStream.disposeClient(this),this.masterStream=null),this.unsubscribeFromMixerTrackEvents(),super.dispose(),this.event("onStreamClientDisposed").raise(this))}async applyCapabilities(e){if(!this.mediaTrack)return!1;const t=this.constraintsProvider.updateVideoConstraints(this.currentConstraints,e,this.getResolution());if(!t||!this.configProvider.config.recoverOnStreamUnmute&&this.currentConstraints===t)return!1;const i=async e=>{try{return await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t,!0}catch(t){if(e)throw this.logger.safe.error(`Apply constraints error: ${JSON.stringify(t)}`),t;return this.logger.safe.warn(`Apply constraints failed and will be re-tried, error ${JSON.stringify(t)}`),!1}},n=this.currentConstraints.withEffect&&this.configProvider.config.effectsApplyConstraintsRetryMs;return!await i(!n)&&n&&(await Dm(this.configProvider.config.effectsApplyConstraintsRetryMs),await i(!0)),!0}start(){return this.masterStream.start()}clone(e){return this.masterStream||this.logger.safe.error(`clone: master stream is null, reason: ${e}`),this.masterStream.getClient(`streamclient: ${e}`)}setMuted(e,t){this.isMuted=e,this.applyState(t)}setHold(e,t){this.isHold=e,this.applyState(t)}isSameStream(e){return this.parentId===e.parentId}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=IR(this.mediaTrack),i=t?.width?t:e,n=`Track resolution is ${i.width}x${i.height}.`;return t?.width?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=RR(this.mediaTrack);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}update(e){e?this.mediaTrack?this.logger.safe.error(`Media track is already created: ${this.mediaTrack.id}`):(this.mediaTrack=this.getTrackByMediaType(e,this.mediaType),this.updateTrackConstraints(),this.subscribeOnMediaTrackEvents(this.mediaTrack),this.hasMasterAudio=e&&e.getAudioTracks().length>0,this.hasMasterVideo=e&&e.getVideoTracks().length>0,this.hasMasterAudio&&this.hasMasterVideo&&(this.rawMediaStream=e),this.logger.safe.info(`Updated: ${Tm(e)}`)):this.logger.safe.error("No master media stream, skipping update")}resetEffectsOutputConstraints(e){this.masterStream.resetEffectsOutputConstraints(e)}async updateTrackConstraints(){if("ScreenShare"!==this.mediaType)return;const e=this.masterStream.getResolution();if(e){const t=this.currentConstraints.clone();t.video.maxWidth=e.width,t.video.minWidth=e.width,t.video.maxHeight=e.height,t.video.minHeight=e.height;try{await this.streamProvider.applyConstraintsForTrack(this.mediaTrack,t),this.currentConstraints=t}catch(e){this.logger.safe.error(`Apply constraints error: ${JSON.stringify(e)}`)}}}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}applyState(e){void 0!==this.mediaTrack?.enabled&&(this.mediaTrack.enabled=!this.isMuted&&!this.isHold,this.logger.safe.info(`[${e}] Track ${JSON.stringify(this.mediaTrack.id)} enabled state set to => ${this.mediaTrack.enabled}`))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`),this.event("onStreamClientEnded").raise(this,t)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`),this.event("onStreamClientMuted").raise(this,!0)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.id} unmuted`),this.event("onStreamClientMuted").raise(this,!1)}}unsubscribeFromMediaTrackEvents(){this.mediaTrack.onended=null,this.mediaTrack.onmute=null,this.mediaTrack.onunmute=null}unsubscribeFromMixerTrackEvents(){this.mixerSubscriptions.forEach((e=>e.dispose())),this.mixerSubscriptions=[]}subscribeOnMasterStreamEvents(){this.masterStreamSubscriptions.push(this.masterStream.on("onStreamStarted",((e,t)=>this.event("onStreamClientStarted").raise(this,t))),this.masterStream.on("onStreamError",((e,t)=>this.event("onStreamClientError").raise(this,t))),this.masterStream.on("onStreamTrackMuted",((e,t)=>this.event("onStreamClientMuted").raise(this,t))),this.masterStream.on("onStreamDisposing",(e=>this.dispose())),this.masterStream.on("onStreamQualityChanged",((e,t,i,n)=>this.event("onStreamQualityChanged").raise(this,t,i,n))),this.masterStream.on("onStreamTrackEnded",((e,t)=>this.event("onStreamClientEnded").raise(this,t))))}unsubscribeFromMasterStreamEvents(){this.masterStreamSubscriptions.forEach((e=>e.dispose())),this.masterStreamSubscriptions=[]}hasAudio(){return this.hasMasterAudio}hasVideo(){return this.hasMasterVideo}isActive(){return this.mediaTrack?.enabled&&!this.mediaTrack?.muted&&"live"===this.mediaTrack?.readyState}onVideoStreamQualityChanged(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.masterStream.onVideoStreamQualityChanged(e,t,i)}isDisposed(){return this._isDisposed}},kR=class extends qe{constructor(e,t,i,n,r,a){super(a),this.stream=e,this.constraints=t,this.constraintsProvider=i,this.gumStreamProvider=n,this.configProvider=r,this.logger=a,this.clients=[],this.streams=[],this.clientId=0,this.mediaStreamSubscription=this.stream.on("onStreamAcquired",(()=>this.onStreamAcquired()))}getClient(){const e=new MR(this.clientId++,this.stream,this.constraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger);return this.addClient(e),e}disposeClient(e){this.removeClient(e),this.clients.length||this.event("onAllClientsDisposed").raise()}dispose(){this.mediaStreamSubscription.dispose(),this.clients.length&&this.logger.safe.error(`Not all clients are disposed! ${JSON.stringify(this.clients.map((e=>e.id)))}`),this.streams.forEach((e=>this.disposeStream(e))),super.dispose()}getOrCreateStream(){const e=this.streams.length?this.streams[this.streams.length-1]:this.stream.rawStream;if(!e)return null;const t=e.clone();return this.logger.safe.info(`Cloned: ${Tm(e)} -> ${Tm(t)}`),this.resetStream(t),this.streams.push(t),t}addClient(e){this.updateClient(e),this.clients.push(e)}updateClient(e){const t=this.getOrCreateStream();t&&e.update(t)}removeClient(e){const t=this.clients.indexOf(e);this.clients.splice(t,1)}addStream(){this.clients.forEach((e=>this.updateClient(e)))}disposeStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Stopping track: ${JSON.stringify(e.id)}`),e.stop()}))}onStreamAcquired(){this.addStream()}resetStream(e){e.getTracks().forEach((e=>{this.logger.safe.info(`Resetting state for track: ${e.id}`),e.enabled=!0}))}},DR=class{static getStrategy(e,t,i,n,r,a){return a?new xR(i,n):"Video"===e?new LR(t,i,n,r):new NR(t,i,n)}},OR=class{constructor(e,t,i){this.gumStreamProvider=e,this.serialQueue=t,this.logger=i}getStream(e){return this.logger.safe.info(`Requesting stream with constraints: ${JSON.stringify(gm(e))}`),this.serialQueue.add((()=>this.request(e)))}},NR=class extends OR{constructor(e,t,i){super(e,t,i.createChild("SimpleStrat"))}request(e){return this.gumStreamProvider.getStream(e)}},LR=class extends OR{constructor(e,t,i,n){super(e,t,i.createChild("MultStrat")),this.policyGenerator=new hR}request(e){const t=this.policyGenerator.getPolicies(e);return this.makeRequests(t)}makeRequests(e){const t=e[0];return this.logger.safe.info(`Requesting media stream with policy: ${JSON.stringify(t)}`),this.makeRequestWithPolicy(t).catch((t=>{const i=e.slice(1);if(i.length&&Qe.MEDIA_ERROR.constraintNotSatisfiedError===t.type)return this.logger.safe.warn("Could not obtain constrained media stream, will attempt weaker policy"),this.makeRequests(i);throw t}))}makeRequestWithPolicy(e){return this.gumStreamProvider.getStream(e)}},xR=class extends OR{constructor(e,t){super(null,e,t.createChild("WithOveriddenStreamStart"))}request(e){return new Promise(((t,i)=>t(e.withOverridenStream)))}},FR=class e extends qe{constructor(t,i,n,r,a){super(r),this.serialQueue=i,this.configProvider=n,this.effectManager=a,this.gumRequestTime=0,this.id=e.streamId++,this.logger=r.createChild(`MediaStream:${this.id}`),this.mediaType=this.getMediaType(t),this.initialize(t)}get rawStream(){return this.mediaStream}get deviceId(){return this.originalMediaStream?this.originalMediaStream.getTracks()?.[0]?.getSettings?.()?.deviceId:null}start(){return this.mediaStreamStartPromise||(this.mediaStreamStartPromise=this.startStream(this.currentConstraints)),this.mediaStreamStartPromise}dispose(e){this.event("onStreamDisposing").raise(this),this.stopMediaStream(e).catch((e=>{this.event("onStreamError").raise(this,e)})).finally((()=>{this.constraintsProvider=null,this.serialQueue=null,this.configProvider=null,this.logger=this.logger.createChild("DISPOSED"),this.clientGenerationStrategy.dispose(),this.event("onStreamDisposed").raise(this),super.dispose()}))}disposeClient(e){this.clientGenerationStrategy.disposeClient(e)}getClient(e){return this.logger.safe.debug(`getClient: ${e}`),this.clientGenerationStrategy.getClient()}getOriginalMediaStream(){return this.originalMediaStream}getResolution(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e={width:this.currentConstraints.video.minWidth,height:this.currentConstraints.video.minHeight},t=bR(this.mediaStream),i=t??e,n=`Stream resolution is ${i.width}x${i.height}.`;return t?this.logger.safe.info(n):this.logger.safe.error(`${n}. Resolution not found, assuming default resolution.'`),i}getFrameRate(){if(!["Video","ScreenShare","PanoramicVideo"].some((e=>e===this.mediaType)))return null;const e=wR(this.mediaStream);return 0===e?this.logger.safe.error("Stream frame rate is not avalable, returning 0"):this.logger.safe.info(`Stream fps is ${e}`),e}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`Media type is not defined: ${JSON.stringify(e)}`)}resetEffectsOutputConstraints(e){const t=bR(this.originalMediaStream);this.effectManager.resetOutputConstraints("Video",{width:Math.min(e.width,t.width||Number.MAX_SAFE_INTEGER),height:Math.min(e.height,t.height||Number.MAX_SAFE_INTEGER)})}initialize(e){this.constraintsProvider=uR.getProvider(this.mediaType,this.configProvider,this.logger),this.currentConstraints=this.constraintsProvider.createConstraintsObject(e),this.gumStreamProvider=_R.getStreamProvider(this.mediaType,this.configProvider,this.logger),this.mediaStreamRequestStrategy=DR.getStrategy(this.mediaType,this.gumStreamProvider,this.serialQueue,this.logger,this.configProvider,!!this.currentConstraints.withOverridenStream),this.clientGenerationStrategy=new kR(this,this.currentConstraints,this.constraintsProvider,this.gumStreamProvider,this.configProvider,this.logger),this.clientGenerationStrategy.on("onAllClientsDisposed",(()=>this.onAllClientsDisposed()))}onAllClientsDisposed(){this.logger.safe.info("All clients are disposed, disposing master stream"),this.dispose()}async startStream(e){try{await this.getOrCreateMediaStream(e),this.event("onStreamStarted").raise(this,this.currentConstraints)}catch(e){throw this.event("onStreamError").raise(this,e),e}}async getOrCreateMediaStream(e){if(this.mediaStream)return Promise.resolve();const t=this.getRequestStartTimestamp(),i=await this.mediaStreamRequestStrategy.getStream(e);return this.gumRequestTime=this.getRequestDuration(t),this.handleMediaStreamRequestSuccess(i,e)}async handleMediaStreamRequestSuccess(e,t){const i=t.withOverridenStream&&t.withEffect&&this.configProvider.config.useRawMediaApiForVideoEffects;this.logger.safe.info(`Media stream acquired: ${Tm(e)} with constraints: ${JSON.stringify(gm(t))}`),this.originalMediaStream=e,this.subscribeToTrackEvents(this.originalMediaStream),this.currentConstraints=t,t.withEffect&&"Video"===this.mediaType&&!i?this.mediaStream=await this.getVideoEffectStream(e):this.mediaStream=e,await this.startNoiseSuppression(),this.applyState(this.mediaStream),this.event("onStreamAcquired").raise(this,this.gumRequestTime,"Audio"!==this.mediaType&&this.getResolution()||void 0)}async getVideoEffectStream(e){this.sub=this.effectManager.on("onVideoStreamQualityChanged",((e,t,i)=>this.onVideoStreamQualityChanged(e,t,i)));const t=await this.effectManager.startEffect("Video",e);return this.logger.safe.info(`Media stream switched: ${Tm(e)} -> ${Tm(t)}`),t}subscribeToTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=e=>{this.logger.safe.info(`Track ${t.id} ended: ${JSON.stringify(e)}`),this.event("onStreamTrackEnded").raise(this,e)},t.onmute=()=>{this.logger.safe.info(`Track ${t.id} muted`),this.event("onStreamTrackMuted").raise(this,!0)},t.onunmute=()=>{this.logger.safe.info(`Track ${t.id} unmute`),this.event("onStreamTrackMuted").raise(this,!1)})}unsubscribeFromTrackEvents(e){const t=e?this.getTrackByMediaType(e,this.mediaType):null;t&&(t.onended=null,t.onmute=null,t.onunmute=null)}getTrackByMediaType(e,t){return"Audio"===t?e.getAudioTracks()[0]:e.getVideoTracks()[0]}removeVideoEffectStream(){this.sub?.dispose(),this.effectManager.stopEffect("Video",this.mediaStream)}applyState(e){e.getAudioTracks()?.forEach((e=>this.applyAudioState(e)));const t=e.getVideoTracks()[0];this.applyVideoState(t)}applyAudioState(e){e&&(this.hasNonDefaultAudioProcessingConstraints()||"ScreenShare"===this.mediaType?this.applyContentHint(e,"music"):this.configProvider.config.defaultAudioContentHint&&this.applyContentHint(e,this.configProvider.config.defaultAudioContentHint),e.muted&&this.event("onStreamTrackMuted").raise(this,!0),this.logger.safe.info(`Audio track added: ${JSON.stringify(e.id)}`))}applyVideoState(e){e&&("ScreenShare"===this.mediaType&&this.configProvider.config.webrtcDisplayStreamContentHint&&this.applyContentHint(e,this.configProvider.config.webrtcDisplayStreamContentHint),this.logger.safe.info(`Video track added: ${JSON.stringify(e.id)}`))}applyContentHint(e,t){this.logger.safe.info(`Apply content hint: ${t}`),e.contentHint=t}hasNonDefaultAudioProcessingConstraints(){const e=this.currentConstraints.audio;if(e){const t=this.configProvider.config.defaultAudioProcessingFlags;let i;return void 0===e.echoCancellation&&void 0===e.autoGainControl&&void 0===e.noiseSuppression||(i=0,void 0!==e.echoCancellation&&(i+=e.echoCancellation?2:0),void 0!==e.autoGainControl&&(i+=e.autoGainControl?1:0),void 0!==e.noiseSuppression&&(i+=e.noiseSuppression?4:0)),i!==t}return!1}getRequestStartTimestamp(){return Date.now()}getRequestDuration(e){return 0===e?0:Date.now()-e}async startNoiseSuppression(){"Audio"===this.mediaType&&(this.logger.safe.info(`ECS keys for wasmvqe are: ${JSON.stringify(this.configProvider.config.wasmvqe)}`),this.logger.safe.info(`ECS keys for wasmdns are: ${JSON.stringify(this.configProvider.config.wasmdns)}`),this.configProvider.config.applyAudioEffectOnDemand&&!this.currentConstraints.withEffect||(this.mediaStream=await this.effectManager.startEffect("Audio",this.mediaStream)))}stopMediaStream(e){return this.mediaStreamStartPromise?(this.logger.safe.info(`Queueing media stream stop: ${e}`),this.serialQueue.add((()=>this.stopMediaStreamInternal()))):Promise.resolve()}stopOneMediaStream(e){try{e.getTracks().forEach((e=>{this.logger.safe.info(`Track is stopped: ${JSON.stringify(e.id)}`),e.stop()})),this.logger.safe.info(`Media stream stopped: ${e.id}`)}catch(e){this.logger.safe.warn(`Failed to stop media stream: ${Be(e)}`)}}stopMediaStreamInternal(){"Video"===this.mediaType&&this.configProvider.config.enableVideoEffects&&this.removeVideoEffectStream(),this.mediaStream&&(this.stopOneMediaStream(this.mediaStream),this.mediaStream=null),this.originalMediaStream&&(this.stopOneMediaStream(this.originalMediaStream),this.unsubscribeFromTrackEvents(this.originalMediaStream),this.originalMediaStream=null)}onVideoStreamQualityChanged(e,t,i){this.logger.safe.debug(`onStreamQualityChanged: ${JSON.stringify(e)}@${t}, reason=${i}`),this.event("onStreamQualityChanged").raise(this,e,t,i)}};FR.streamId=0;var UR=FR,BR=class e extends qe{constructor(e,t,i){super(e),this.logger=e,this.configProvider=t,this.effectsManager=i,this.cachedStreamsSubs=new Map,this.cachedStreamsMap=new Map,this.mediaStreamSerialQueue=new Hw(this.logger),this.couldUseWebrtc_1_0=!1}getMediaStream(e,t){this.logger.safe.info(`retrieving media stream: ${JSON.stringify(gm(e))}`),this.cachedStreamsMap.size||(this.couldUseWebrtc_1_0=fm(this.configProvider.config.checkSupportForWebrtc_1_0));let i=this.getSuitableStream(e);i||(this.logger.safe.info(`cached stream is not found. Creating a new one with constraints: ${Be(gm(e))}`),i=this.createCachedStream(e)),this.logger.safe.info(`starting cached stream id=${i.id}`,t);const n=i.getClient(t);return n.start().catch((e=>{this.logger.safe.error(`could not start media stream: ${i.id}, total streams: ${this.cachedStreamsMap.size}, error: ${Be(e)}`),this.removeStream(i)})),n}dispose(){this.cachedStreamsSubs&&(this.cachedStreamsSubs.forEach((e=>{e.forEach((e=>{e.dispose()}))})),this.cachedStreamsSubs=null),this.cachedStreamsMap&&(this.cachedStreamsMap.forEach((e=>e.dispose("MSM dispose"))),this.cachedStreamsMap=null),this.mediaStreamSerialQueue&&(this.mediaStreamSerialQueue.dispose(),this.mediaStreamSerialQueue=null),super.dispose()}getCachedStreams(){return this.cachedStreamsMap}getActiveConstraints(){const e={audio:!1,video:!1,sharing:!1};return this.cachedStreamsMap.forEach(((t,i)=>{i.audio&&(e.audio=!0),i.video&&(e.video=!0),i.sharing&&(e.sharing=!0)})),e}onDevicesChanged(t){this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t)?this.logger.safe.info("Device list is empty, permission workaround enabled"):this.cachedStreamsMap.forEach(((e,i)=>{if(!i.sharing){const e=this.isDeviceOutdated(i.audio,t),n=this.isDeviceOutdated(i.video,t);(e||n)&&this.cachedStreamsMap.delete(i)}}))}getSuitableStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{this.isSuitable(this.addDeviceIdIfNecessary(i,n),e)&&(t=n)})),t&&this.cachedStreamsMap.get(t)}addDeviceIdIfNecessary(e,t){if(!e.deviceId)return t;const i=this.cloneStreamConstraints(t);return t.audio&&void 0===t.audio.deviceId&&(i.audio.deviceId=e.deviceId),t.video&&void 0===t.video.deviceId&&(i.video.deviceId=e.deviceId),t.sharing&&(i.sharing.deviceId=Qe.DISPLAY_SOURCE_ID),i}cloneStreamConstraints(e){return{...lt(e),withOverridenStream:e.withOverridenStream}}createCachedStream(e){const t=this.createStream(e);return this.event("onStreamCreated").raise(t.id,t.mediaType),this.subscribeOnStreamEvents(t),this.logger.safe.info(`created media stream, id: ${t.id} total: ${this.cachedStreamsMap.size}`),this.cachedStreamsMap.set(e,t),t}disposeCurrentDeviceStream(t){for(const[i,n]of this.cachedStreamsMap.entries())t.sharing||i.sharing||(e.deviceChanged(t.audio,i.audio)||e.deviceChanged(t.video,i.video))&&n.dispose("MSM dispose oneStreamPerDeviceType")}createStream(e){return this.configProvider.config.oneStreamPerDeviceType&&this.couldUseWebrtc_1_0&&this.disposeCurrentDeviceStream(e),this.configProvider.config.webrtcSimulcastSessionEnabled&&Bg.hasApplyConstraints()&&this.couldUseWebrtc_1_0?new UR(e,this.mediaStreamSerialQueue,this.configProvider,this.logger,this.effectsManager):new PR(e,this.mediaStreamSerialQueue,this.logger,this.configProvider)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamAcquired",((e,t,i)=>this.onStreamAcquired(e,t,i)))),t.push(e.on("onStreamDisposing",(e=>this.onStreamDisposing(e)))),this.cachedStreamsSubs.set(e,t)}unsubscribeFromStreamEvents(e){this.cachedStreamsSubs.get(e).forEach((e=>e.dispose())),this.cachedStreamsSubs.delete(e)}removeStream(e){this.logger.safe.info(`release media stream generation: ${e.id} cached: ${this.cachedStreamsMap.size}`),this.cachedStreamsSubs.has(e)?(this.unsubscribeFromStreamEvents(e),this.cachedStreamsMap.delete(this.getConstraintsForStream(e)),this.getStreamsCountByType("Audio")||this.effectsManager.stopEffect("Audio"),this.cachedStreamsMap.size||this.event("onAllStreamsRemoved").raise()):this.logger.safe.warn(`skipping unknown stream ${e.id}`)}getConstraintsForStream(e){let t;return this.cachedStreamsMap.forEach(((i,n)=>{e===i&&(t=n)})),t}isSuitable(e,t){const i=!(!e.withOverridenStream||!t.withOverridenStream),n=i||t.sharing||this.isAcceptable(e.audio,t.audio)&&e.audioProcessingFlags===t.audioProcessingFlags,r=i||this.isAcceptable(e.video,t.video),a=this.configProvider.config.requireUserActionForAudioSharing&&t.sharing&&!!e.audio!=!!t.audio,s=this.isAcceptable(e.sharing,t.sharing),o=s&&this.isAcceptable(e.audio,t.audio),l=a?o:s,c=e.withEffect===t.withEffect,d=e.withOverridenStream?.id===t.withOverridenStream?.id;return!t.force&&n&&r&&l&&c&&d}isAcceptable(e,t){return!e&&!t||e&&t&&e.deviceId===t.deviceId}isDeviceOutdated(e,t){return e?.deviceId&&!t.some((t=>t.deviceId===e.deviceId))}onStreamDisposing(e){this.logger.safe.info(`onStreamDisposing event ${e.id}`),this.event("onStreamDisposing").raise(e.id,e.mediaType),this.removeStream(e)}onStreamAcquired(e,t,i){const n="Audio"===e.mediaType?void 0:!!e.rawStream.getAudioTracks()[0],r="ScreenShare"===e.mediaType?this.getSharingSource(e):void 0;this.event("onStreamAcquired").raise(e.id,e.mediaType,t,i,n,r)}getSharingSource(e){const t=e.rawStream.getVideoTracks()[0],i=t.getConstraints();if(i?.deviceId)return"camera";const n=t.getSettings();return n?.displaySurface??"unknown"}static deviceChanged(e,t){return!(!e||!t)&&e.deviceId!==t.deviceId}static isDeviceListEmpty(e){return e.every((e=>""===e.label))}getStreamsCountByType(e){let t=0;return this.cachedStreamsMap.forEach((i=>{t+=i.mediaType===e?1:0})),t}},VR=class{constructor(e,t,i,n,r){this.deviceId=e,this.label=t,this.kind=i,this.groupId=n,this.capabilities=r,this.type=this.getType(this.kind),this.guid=`${this.type}:${this.deviceId}`,this.isSystemDefault=this.deviceId===Qe.MEDIA_DEVICE.defaultId}toDeviceDesc(){return{id:this.guid,browserId:this.deviceId,label:this.label,kind:this.type}}getType(e){switch(e){case Qe.MEDIA_DEVICE_KIND.audioInput:return Qe.MEDIA_DEVICE.microphone;case Qe.MEDIA_DEVICE_KIND.audioOutput:return Qe.MEDIA_DEVICE.speaker;case Qe.MEDIA_DEVICE_KIND.videoInput:return Qe.MEDIA_DEVICE.camera;case Qe.MEDIA_DEVICE_KIND.compositeAudio:return Qe.MEDIA_DEVICE.compositeAudio;case Qe.MEDIA_DEVICE_KIND.virtualDevice:return Qe.MEDIA_DEVICE.virtualDevice;default:throw new Error(`Device kind to recognized: ${e}`)}}},HR=class extends VR{constructor(e,t,i,n){super(e,t,i,n)}},$R=class extends VR{constructor(e,t,i,n,r){super(e,t,i,n,r)}toDeviceDesc(){const e=super.toDeviceDesc();return e.isSystemDefault=this.isSystemDefault,e}},GR=class extends VR{constructor(e,t,i,n,r){if(super(e,t,i,n,r),this.position="unknown",r&&r.facingMode&&1===r.facingMode.length)switch(r.facingMode[0]){case"user":this.position="front";break;case"environment":this.position="back"}}toDeviceDesc(){const e=super.toDeviceDesc();return e.position=this.position,e}},jR=class extends VR{constructor(e,t,i,n,r,a){super(null,i,n,""),this.micDevice=e,this.speakerDevice=t,this.formFactor=r,this.isPcInternalDevice=a,this.guid=null,this.isSystemDefault=!1}get micDeviceId(){return this.micDevice.guid}get speakerDeviceId(){return this.speakerDevice.guid}toDeviceDesc(){const e=super.toDeviceDesc();return e.microphoneId=this.micDeviceId,e.speakerId=this.speakerDeviceId,e.formFactor=this.formFactor,e.isPcInternalDevice=this.isPcInternalDevice,e}};function zR(e){const t=e.getCapabilities&&e.getCapabilities();switch(t&&(delete t.groupId,delete t.deviceId),e.kind){case Qe.MEDIA_DEVICE_KIND.audioInput:case Qe.MEDIA_DEVICE_KIND.audioOutput:return new $R(e.deviceId,e.label,e.kind,e.groupId,t);case Qe.MEDIA_DEVICE_KIND.videoInput:return new GR(e.deviceId,e.label,e.kind,e.groupId,t);default:throw new Error(`Device kind is not recognized: ${e.kind}`)}}function WR(e,t,i){return new jR(e,t,i,"compositeAudio",0,!1)}function qR(e){switch(e){case Qe.MEDIA_DEVICE.microphone:return Qe.MEDIA_DEVICE_KIND.audioInput;case Qe.MEDIA_DEVICE.speaker:return Qe.MEDIA_DEVICE_KIND.audioOutput;case Qe.MEDIA_DEVICE.camera:return Qe.MEDIA_DEVICE_KIND.videoInput;default:throw new Error(`Device type to recognized: ${e}`)}}function KR(e,t,i,n,r={str:""}){r.str+=`|input(${t.length})`;let a=[];const s=[n.config.devices.blacklist[e],n.defaultConfig.devices.blacklist[e]];for(const e of s)try{const i=new RegExp(e,"i");a=t.filter((t=>e&&t.label.match(i)?(r.str+=`|-blacklisted(${t.label})`,!1):t.deviceId!==Qe.MEDIA_DEVICE.communicationsId||(r.str+="|-communications",!1)));break}catch(i){r.str+=`|filterError('${e}', ${Be(i)})`,a=t}if(a.length){const t=function(e,t,i){if(1===t.length)return i.str+="|default:only",t[0];const n=t.find((e=>e.isSystemDefault&&e.deviceId===Qe.MEDIA_DEVICE.defaultId));if(!n)return i.str+="|default:noSynthetic",t.find((e=>e.isSystemDefault))||t[0];{const r=t.filter((e=>e!==n));if(1===r.length)return i.str+="|default:firstNonDefault",r[0];if(""!==n.groupId){const e=r.filter((e=>e.groupId===n.groupId));if(1===e.length)return i.str+=`|default:groupId(${Ae(e[0].guid)})`,e[0]}const a=r.map((e=>e.label)),s=function(e,t){return t.reduce(((t,i)=>{const n=e.includes(i)?i.length:0;return t.length<n?i:t}),"")}(n.label,a),o=r.find((e=>e.label===s));if(o)return i.str+=`|default:label(${Ae(o.guid)})`,o;const l=e.find((e=>e.isSystemDefault));if(l){const e=r.find((e=>e.deviceId===l.deviceId));if(e)return i.str+=`|default:previousList(${Ae(e.guid)})`,e}}return i.str+="|default:anyOrNull",t.find((e=>e.isSystemDefault))||null}(i,a,r);if(t&&(t.isSystemDefault=!0,r.str+=`|default(${Ae(t.guid)})`),t&&t.deviceId!==Qe.MEDIA_DEVICE.defaultId&&a.length>1&&(a=a.filter((e=>e.deviceId!==Qe.MEDIA_DEVICE.defaultId||(r.str+="|-defaultId",!1)))),e===Qe.MEDIA_DEVICE.camera||t||(r.str+="|+syntheticDefault",a.unshift(function(e){const t={deviceId:Qe.MEDIA_DEVICE.defaultId,label:Qe.MEDIA_DEVICE.defaultDeviceLabel,kind:qR(e),groupId:"",toJSON:()=>JSON.stringify(t)};return zR(t)}(e))),i.forEach((e=>{const t=a.find((t=>t.guid===e.guid));t&&!t.label&&e.label&&(r.str+=`|migrateLabel(${Ae(t.guid)})`,t.label=e.label)})),e===Qe.MEDIA_DEVICE.speaker){const e=a.filter((e=>""===e.label));e.length>1&&e.length===a.length&&(a=t?[t]:[a[0]],r.str+=`|-filteredEmptyLabels(${e.length})`)}}return a}function JR(e,t,i=.5,n={str:""}){const r=[];if(e.length&&t.length){const a=function(e,t,i={str:""}){const n=new Set;for(const i of[...e,...t])n.add(i.groupId);const r=[];for(const a of n.values()){let n=e.filter((e=>e.groupId===a)),s=t.filter((e=>e.groupId===a));if(n&&s)if(1===n.length&&1===s.length)r.push({microphone:n[0],speaker:s[0]}),i.str+=`|pairSimple(${Ae(n[0].guid)}, ${Ae(s[0].guid)})`;else if(n.length>1||s.length>1){let e=YR(n,s);for(;e;)i.str+=`|pairComplex(${Ae(e.microphone.guid)}, ${Ae(e.speaker.guid)})`,r.push(e),n=n.filter((t=>t!==e.microphone)),s=s.filter((t=>t!==e.speaker)),e=YR(n,s)}}return r}(e.filter((e=>""!==e.groupId)),t.filter((e=>""!==e.groupId)),n);a.length&&(r.push(...a.map((e=>WR(e.microphone,e.speaker,QR(e.microphone.label,e.speaker.label))))),n.str+=`|directMatched(${r.length})`);const s=r.length;r.push(...function(e,t,i,n){const r=[];return e.length&&t.length?(e.forEach((e=>{const a=t.filter((t=>t.groupId===e.groupId));if(!a.length)return void(n.str+=`|lbl_nocand(${Ae(e.guid)})`);let s=St(e.label,a[0].label).length;const o=a.sort(((t,i)=>{const n=St(e.label,t.label),r=St(e.label,i.label);return n.length>s&&(s=n.length),r.length>s&&(s=r.length),r.length-n.length}));if(o.length){const t=s/e.label.length;t>i&&(r.push(WR(e,o[0],QR(e.label,o[0].label))),n.str+=`|lbl_matched(${Ae(e.guid)} & ${Ae(o[0].guid)}, ${Math.round(1e4*t)/100}%)`)}})),r):r}(e.filter((e=>!r.some((t=>t.micDeviceId===e.guid)))),t.filter((e=>!r.some((t=>t.speakerDeviceId===e.guid)))),i,n)),n.str+=`|otherMatched(${r.length-s})`}return r}function YR(e,t){let i=999,n=null;if(e.length>0&&t.length>0)for(const r of e)for(const e of t){const t=yt(r.label,e.label);t<i&&(i=t,n={microphone:r,speaker:e})}return n}function QR(e,t){if(e===t)return e;let i=St(e,t);i=i.trim().replace(/^\((.+)\)$/,"$1");let n="",r="",a=0;const s=[ZR(e),ZR(t)];if(0===s[0]||0===s[1])return i;for(let e=0;e<i.length;e++)if("("===i[e])a++,r+=i[e];else if(")"===i[e]){if(!(a>0))break;a--,r+=i[e],n+=r,r=""}else a>0?r+=i[e]:n+=i[e];const o=ZR(n);return o!==s[0]&&o!==s[1]||(n=n.replace(/\w+\s?\((.+)\)/,"$1"),n=QR(i,n)),n.trim()}function ZR(e){const t=["(",")"];let i=0;for(let n=0;n<e.length;n++)t.some((t=>e[n]===t))&&i++;return i}var XR={microphone:"",camera:"",speaker:"",compositeAudio:"",audioIngestDevice:"",virtualDevice:""},eA=class extends qe{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.debugInfo=XR,this.lists=new Map,this.lists.set(Qe.MEDIA_DEVICE.microphone,[]),this.lists.set(Qe.MEDIA_DEVICE.camera,[]),this.configProvider.userAgentConfig.isAudioOutputSelectionSupported&&(this.lists.set(Qe.MEDIA_DEVICE.speaker,[]),this.lists.set(Qe.MEDIA_DEVICE.compositeAudio,[])),e.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>this.onConfigUpdated())),this.logger.safe.info("Initialized")}get devices(){const e=[];return this.lists.forEach((t=>e.push(...t))),e}getDevicesByType(e){return this.lists.get(e)??[]}updateDevices(e,t=!1){if(ut(this.latestRawList,e))return;this.latestRawList=e;const i=this.devices;this.debugInfo.microphone="microphone",this.debugInfo.camera="camera",this.debugInfo.speaker="speaker",this.debugInfo.compositeAudio="compositeAudio",this.updatePrimitiveDeviceList(Qe.MEDIA_DEVICE.microphone,e.filter((e=>e.type===Qe.MEDIA_DEVICE.microphone))),this.updatePrimitiveDeviceList(Qe.MEDIA_DEVICE.camera,e.filter((e=>e.type===Qe.MEDIA_DEVICE.camera))),this.lists.get(Qe.MEDIA_DEVICE.speaker)&&(this.updatePrimitiveDeviceList(Qe.MEDIA_DEVICE.speaker,e.filter((e=>e.type===Qe.MEDIA_DEVICE.speaker))),this.lists.get(Qe.MEDIA_DEVICE.compositeAudio)&&this.updateCompositeAudioDeviceList(this.lists.get(Qe.MEDIA_DEVICE.microphone),this.lists.get(Qe.MEDIA_DEVICE.speaker)));const n=this.lists.get(Qe.MEDIA_DEVICE.compositeAudio)||[];this.lists.set(Qe.MEDIA_DEVICE.microphone,this.orderDeviceList(this.lists.get(Qe.MEDIA_DEVICE.microphone),n)),this.lists.get(Qe.MEDIA_DEVICE.speaker)&&this.lists.set(Qe.MEDIA_DEVICE.speaker,this.orderDeviceList(this.lists.get(Qe.MEDIA_DEVICE.speaker),n));const r=this.lists.get(Qe.MEDIA_DEVICE.microphone);this.setTopItemToDefault(r);const a=this.lists.get(Qe.MEDIA_DEVICE.speaker);this.setTopItemToDefault(a),ut(i,this.devices)||(this.logger.safe.info("Device lists updated and changed"),this.logger.safe.info(this.debugInfo.microphone),this.logger.safe.info(this.debugInfo.camera),this.logger.safe.info(this.debugInfo.speaker),this.logger.safe.info(this.debugInfo.compositeAudio),this.event("onDevicesChanged").raise(this.devices,t))}updateVirtualDeviceList(e){const t=this.lists.get(Qe.MEDIA_DEVICE.virtualDevice),i=e.map((e=>new HR(e.id,e.label,"virtualDevice","")));ut(t,i)?this.logger.safe.info("Device lists did not change."):(this.lists.set(Qe.MEDIA_DEVICE.virtualDevice,i),this.event("onDevicesChanged").raise(this.devices,!1))}updateActiveMicrophone(e){if(!e||e.deviceId===Qe.MEDIA_DEVICE.defaultId)return;const t=this.lists.get(Qe.MEDIA_DEVICE.microphone),i=t.findIndex((e=>e.isSystemDefault));-1!==i&&t[i]!==e?(this.logger.safe.info("Removing synthetic default microphone"),e.isSystemDefault=!0,t.splice(i,1),this.lists.set(Qe.MEDIA_DEVICE.microphone,t),this.event("onDevicesChanged").raise(this.devices,!1)):e.isSystemDefault=!0}updatePrimitiveDeviceList(e,t){const i={str:this.debugInfo[e]};this.lists.set(e,KR(e,t,this.lists.get(e)||[],this.configProvider,i)),this.debugInfo[e]=i.str}updateCompositeAudioDeviceList(e,t){const i={str:this.debugInfo.compositeAudio};this.lists.set(Qe.MEDIA_DEVICE.compositeAudio,JR(e,t,this.configProvider.config.devices.compositeLabelMatchingThreshold,i)),this.debugInfo.compositeAudio=i.str}orderDeviceList(e,t){return e.sort(((e,i)=>this.getDevicePriority(i,this.getCompositeAudioDeviceCounterpart(i,t))-this.getDevicePriority(e,this.getCompositeAudioDeviceCounterpart(e,t))))}getCompositeAudioDeviceCounterpart(e,t){const i=t.find((t=>t.micDeviceId===e.guid||t.speakerDeviceId===e.guid));return i?i[e.type===Qe.MEDIA_DEVICE.speaker?"micDevice":"speakerDevice"]:null}getDevicePriority(e,t){let i=0;return this.configProvider.config.devices.overrideDefault&&t&&(!e.isSystemDefault&&t.isSystemDefault?(this.debugInfo[e.type]+=`|overrideDefault(${Ae(e.guid)})`,i+=10):e.isSystemDefault&&!t.isSystemDefault&&"microphone"===e.type&&(i+=15)),e.isSystemDefault&&(i+=5),t&&(i+=1,t.isSystemDefault&&(i+=2)),i}setTopItemToDefault(e){e?.length&&(e.forEach((e=>e.isSystemDefault=!1)),e[0].isSystemDefault=!0)}onConfigUpdated(){let e=!1;this.configProvider.userAgentConfig.isAudioOutputSelectionSupported?this.lists.has(Qe.MEDIA_DEVICE.speaker)||(this.lists.set(Qe.MEDIA_DEVICE.speaker,[]),this.lists.set(Qe.MEDIA_DEVICE.compositeAudio,[]),e=!0):(this.lists.has(Qe.MEDIA_DEVICE.speaker)&&(this.lists.delete(Qe.MEDIA_DEVICE.speaker),e=!0),this.lists.has(Qe.MEDIA_DEVICE.compositeAudio)&&(this.lists.delete(Qe.MEDIA_DEVICE.compositeAudio),e=!0)),e&&(this.logger.safe.info("Updating device list due to config update"),this.updateDevices(this.latestRawList||[]))}},tA=class e extends qe{constructor(t,i){super(i),this.pollingInterval=0,e.enumeratorUsers.add(this),e.initialize(this,t,i)}startDevicePolling(t){this.pollingInterval=t?e.configProvider.config.devices.pollingIntervalIdle:e.configProvider.config.devices.pollingIntervalActive,e.updatePollingTask()}stopDevicePolling(t){this.pollingInterval=t?0:e.configProvider.config.devices.pollingIntervalIdle,e.updatePollingTask()}dispose(){super.dispose(),this.stopDevicePolling(!0),e.enumeratorUsers.delete(this),0===e.enumeratorUsers.size&&(e.logger.safe.info("disposing"),e.initializeCalled=!1,e.isInitialized=new Jh,e.list=void 0,e.window.navigator.mediaDevices.ondevicechange=void 0)}static get isPolling(){return 0!==e.currentPollingInterval}static initialize(t,i,n){e.initializeCalled||(e.initializeCalled=!0,e.window=Ug.window,e.configProvider=i,e.logger=n,e.list=new eA(i,n.createChild("DeviceList")),i.userAgentConfig.on("isAudioOutputSelectionSupportedChanged",(()=>e.enumerateDevices())),i.on("configUpdated",(()=>{void 0!==i.config.devices.pollingIntervalIdle&&null!==e.pollingTimer&&t.startDevicePolling(!0)})),i.config.devices.pollingIntervalIdle&&i.config.devices.idlePollingOnStart&&t.startDevicePolling(!0),e.window.navigator.mediaDevices&&(e.window.navigator.mediaDevices.ondevicechange=()=>{n.safe.info("enumerating due to ondevicechange callback"),e.enumerateDevices().catch((e=>{n.safe.error(`unable to enumerate ondevicechange: ${Be(e)}`)}))}),e.enumerateDevices().then((()=>e.isInitialized.resolve())).catch((t=>e.isInitialized.reject(t))))}static async enumerateDevices(t=!1){if(!e.window.navigator?.mediaDevices?.enumerateDevices)throw new Error("device enumeration unsupported");if(e.enumerateDevicesPromise&&!t)return e.logger.safe.info("enumeration request postponed"),void(e.hasPendingUpdate=!0);try{e.enumerateDevicesPromise??(e.enumerateDevicesPromise=e.configProvider.config.devices.enumerateDevicesTimeout?function(e,t,i,n){let r;const a=[e,new Promise(((e,n)=>{r=setTimeout(n.bind(null,new Error(`Promise timed out ${i?`: ${i}`:""} after ${t} ms`)),t)}))];n&&a.push(n);const s=Promise.race(a),o=()=>{r&&clearTimeout(r)};return s.then(o,o),s}(e.window.navigator.mediaDevices.enumerateDevices(),e.configProvider.config.devices.enumerateDevicesTimeout,"enumerateDevices"):e.window.navigator.mediaDevices.enumerateDevices());const i=await e.enumerateDevicesPromise;e.list.updateDevices(i.map((e=>zR(e))),t)}catch(t){const i=Be(t);throw e.logger.safe.warn(`error with enumerating devices: ${i}`),e.raiseFailedEnumeration(i),t}finally{e.enumerateDevicesPromise=void 0,e.hasPendingUpdate&&(e.hasPendingUpdate=!1,e.logger.safe.info("running postponed enumeration"),e.enumerateDevices())}}static updatePollingTask(){let t=Number.MAX_SAFE_INTEGER;for(const i of e.enumeratorUsers.values())i.pollingInterval<t&&(t=i.pollingInterval);if(t===Number.MAX_SAFE_INTEGER&&(t=0),(e.pollingTimer||e.currentPollingInterval!==t)&&e.pollingTimer&&(e.window.clearTimeout(e.pollingTimer),e.pollingTimer=void 0),e.currentPollingInterval=t,0===t)return;const i=async()=>{if(e.currentPollingInterval)try{await e.enumerateDevices(!0),e.pollingTimer=e.window.setTimeout(i,e.currentPollingInterval)}catch(t){throw e.pollingTimer=null,t}};e.logger.safe.info(`starting device polling with interval ${t}ms`),e.pollingTimer=1,i()}static raiseFailedEnumeration(t){for(const i of e.enumeratorUsers.values())i.event("onDeviceEnumerationfailed").raise(t)}};tA.isInitialized=new Jh,tA.initializeCalled=!1,tA.currentPollingInterval=0,tA.hasPendingUpdate=!1,tA.enumeratorUsers=new Set;var iA=tA,nA=class extends qe{constructor(e,t,i){super(i),this.deviceList=e,this.configProvider=t,this.logger=i,this.userSelectedDevices={microphone:null,camera:null,speaker:null},this.currentlySelectedDevices={microphone:null,camera:null,speaker:null,audioIngestDevice:null},this.deviceList.on("onDevicesChanged",(e=>this.onDevicesChanged(e))),e.devices.length>0&&this.onDevicesChanged(e.devices),this.logger.safe.info("Initialized")}get selectedDevices(){return lt(this.currentlySelectedDevices)}selectDevices(e){let t=!1;if(Ze(e,((e,i)=>{const n=this.getDeviceToSelect(i,this.deviceList.getDevicesByType("audioIngestDevice"===i?"microphone":i),e);"camera"===i&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i]),n?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.userSelectedDevices[i]=n?.guid||this.userSelectedDevices[i],t=!0),this.currentlySelectedDevices[i]=n})),t){const e=rt(this.currentlySelectedDevices).map((e=>JSON.stringify(pm(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed from public interface: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!0)}}getDeviceToSelect(e,t,i){let n;const r=this.userSelectedDevices[e];return i?n=t.find((e=>e.guid===i)):r&&(n=t.find((e=>e.guid===r))),"audioIngestDevice"===e?n:n||t[0]}onDevicesChanged(e){let t=!1;if(Object.keys(this.currentlySelectedDevices).forEach((i=>{const n="audioIngestDevice"===i?"microphone":i,r=e.filter((e=>e.type===n));if(r.length>0){const e=this.getDeviceToSelect(i,r);e?.guid!==this.currentlySelectedDevices[i]?.guid&&(this.currentlySelectedDevices[i]=e,t=!0)}else this.currentlySelectedDevices[i]&&(this.currentlySelectedDevices[i]=null,t=!0)})),t){const e=rt(this.currentlySelectedDevices).map((e=>JSON.stringify(pm(e,this.configProvider.config.devices.piiSafeWords))));this.logger.safe.info(`Changed due to device list change: ${e}`),this.event("onSelectedDevicesChanged").raise(this.selectedDevices,!1)}}},rA=class extends qe{constructor(e,t){super(e),this.logger=e,this.mediaStream=t,this.subs=[],this.subscribeOnMediaStreamEvents(t)}acquire(){return this.mediaStream?this.mediaStream.start().then((()=>this.logger.safe.info("Stream acquired"))).catch((e=>{throw this.logger.safe.warn(`Failed to acquire the stream: ${Be(e)}`),e})):Promise.reject("Disposed")}dispose(){this.logger.safe.info("Disposing stream"),this.unsubscribeFromMediaStreamEvents(),this.mediaStream&&(this.mediaStream.dispose(),this.mediaStream=null),super.dispose()}subscribeOnMediaStreamEvents(e){this.subs=[e.on("onStreamClientStarted",(()=>this.event("onStreamStateChanged").raise("active"))),e.on("onStreamClientMuted",((e,t)=>this.event("onStreamStateChanged").raise(t?"inactive":"active"))),e.on("onStreamClientEnded",(()=>this.event("onStreamStateChanged").raise("stopped"))),e.on("onStreamClientError",((e,t)=>{const i=t.type===Qe.MEDIA_ERROR.permissionDeniedError||t.type===Qe.MEDIA_ERROR.sharingCancelledError;this.event("onStreamStateChanged").raise(i?"cancelled":"failed")}))]}unsubscribeFromMediaStreamEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}},aA=[Qe.MEDIA_STATE.inactive,Qe.MEDIA_STATE.receive,Qe.MEDIA_STATE.send,Qe.MEDIA_STATE.sendReceive],sA=[Qe.MEDIA_STATE.inactive,Qe.MEDIA_STATE.receive],oA=class extends qe{constructor(e,t,i){super(i),this.configProvider=e,this.deviceManager=t,this.logger=i,this.currentState={microphone:"unknown",camera:"unknown"},this.lastGum={audio:!1,video:!1},this.registeredTrackers=new Set,this.accessIssuePermissionOther={audio:!1,video:!1},this.window=Ug.window,this.permittedModalities={audio:aA,video:aA,sharing:aA},this.initialize()}async initialize(){!Bg.hasPermissionsApi()||"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera?"unknown"!==this.currentState.microphone&&"unknown"!==this.currentState.camera||this.logger.safe.warn(`Permissions API is not supported in this browser. Microphone: ${this.currentState.microphone}, camera: ${this.currentState.camera}`):(this.logger.safe.info("Initializing"),await this.registerPermissionTracker("microphone"),await this.registerPermissionTracker("camera"))}getPermissionState(e){return this.currentState[e]||"unknown"}isPermissionKnown(e){const t=this.getPermissionState(e);return"unknown"!==t&&"prompt"!==t}get browserPermittedModalities(){return this.permittedModalities}get knownPermissionStates(){return lt(this.currentState)}update(e,t){const i=lt(t);e.audio||delete i.audio,e.video||delete i.video;const n=lt(this.permittedModalities);Ze(i,((e,t)=>{this.permittedModalities[t]=e?aA:sA})),ut(n,this.permittedModalities)||this.event("onDevicesPermissionChanged").raise()}async askDevicePermission(e){const t=e?lt(e):{audio:!0,video:this.deviceManager.hasCamera()};if(this.accessIssuePermissionOther={audio:!1,video:!1},this.configProvider.config.permissions.rememberNegative&&(t.audio=t.audio&&this.permittedModalities.audio===aA,t.video=t.video&&this.permittedModalities.video===aA),t.sharing)throw new Error("askDevicePermission does not support sharing constraints.");const i={audio:!1,video:!1};this.lastGum={audio:!1,video:!1};const n=async(i,n,r)=>{const a={audio:!!i.audio,video:!!i.video,sharing:!0};return!(this.configProvider.config.permissions.adpRequestAVLast&&t.audio&&t.video)||this.lastGum.audio&&this.lastGum.video||(this.logger.safe.info("Prompting for audio and video to ensure omnibar state"),await this.askDevicePermissionPrompt({audio:!0,video:!0},!1)),this.update(t,a),this.deviceManager.raiseTelemetryEvent("ask_device_permission",{constraints:e,resultConstraints:i,error:r,reason:n}),a};await this.initialize();const r=this.getPermissionState("microphone"),a=this.getPermissionState("camera");if(this.logger.safe.info(`Permission state { audio: ${r}, video: ${a} }`),this.configProvider.config.permissions.useNegativeInAdp&&(!t.audio||"denied"===r)&&(!t.video||"denied"===a))return n(i,"navigator_permissions_denied");if(this.configProvider.config.permissions.usePositiveInAdp&&(!t.audio||t.audio&&"granted"===r)&&(!t.video||t.video&&"granted"===a))return n(t,"navigator_permissions_granted");try{return n(this.getConstrainsWithPermissionError(await this.askDevicePermissionPrompt(t,this.configProvider.config.permissions.adpFallback)),"stream_acquisition")}catch(e){return n(i,"stream_acquisition",e)}}async askDevicePermissionPrompt(e,t=!0){const i={audio:!1,video:!1};try{const t=this.deviceManager.getMediaStream(e);return t&&(this.lastGum=lt(e),await t.start(),i.audio=t.hasAudio(),i.video=t.hasVideo(),this.disposeLater(t)),i}catch(n){if(e.audio&&e.video&&t){try{i.video=this.configProvider.config.permissions.adpFallbackVideo&&(await this.askDevicePermissionPrompt({video:!0})).video}catch(e){e.type!==Qe.MEDIA_ERROR.permissionDeniedError&&(this.accessIssuePermissionOther.video=!0)}try{i.audio=this.configProvider.config.permissions.adpFallbackAudio&&(await this.askDevicePermissionPrompt({audio:!0})).audio}catch(e){e.type!==Qe.MEDIA_ERROR.permissionDeniedError&&(this.accessIssuePermissionOther.audio=!0)}}else if(t)throw n;return i}}getConstrainsWithPermissionError(e){return this.configProvider.config.permissions.disableOnPermissionDeniedOnly?{audio:this.accessIssuePermissionOther.audio||e.audio,video:this.accessIssuePermissionOther.video||e.video}:e}disposeLater(e){setTimeout((()=>{e.dispose()}),this.configProvider.config.mediaStreamHoldInterval)}async registerPermissionTracker(e){if(!this.registeredTrackers.has(e))try{const t=await this.window.navigator.permissions.query({name:e});this.handlePermissionStateChanged(e,t.state),t.onchange=()=>this.handlePermissionStateChanged(e,t.state),this.registeredTrackers.add(e)}catch(t){this.logger.safe.error(`Error querying permissions for ${e}: ${Be(t)}`)}}handlePermissionStateChanged(e,t){this.logger.safe.info(`Permission state for ${e} changed ${this.currentState[e]} -> ${t}`),this.currentState[e]=t,this.deviceManager.raiseTelemetryEvent("permissions_state_changed",this.knownPermissionStates),this.deviceManager.handlePermissionStateChange()}},lA=class extends We{constructor(e,t=dt()){super(),this.dms=e,this.label=t,this.id=dt(),this.receivedEvents=new Map,this.subscribeToDeviceManagers(e)}getDeviceManagers(){return this.dms}dispose(){super.dispose(),this.dms?.forEach((e=>e.dispose())),this.dms=null}subscribeToDeviceManagers(e){e.forEach(((e,t)=>{e.on("onVideoEffectsEvent",((...t)=>this.eventHandler("onVideoEffectsEvent",e,(()=>this.event("onVideoEffectsEvent").raise(...t))))),e.on("onVideoEffectApplied",((...t)=>this.eventHandler("onVideoEffectApplied",e,(()=>this.event("onVideoEffectApplied").raise(...t))))),e.on("onDeviceTelemetryEvent",(e=>this.event("onDeviceTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onVideoEffectsTelemetryEvent",(e=>this.event("onVideoEffectsTelemetryEvent").raise({deviceId:`${this.id}/${t}`,...e}))),e.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise(`${this.id}/${t}`))),e.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))}))}eventHandler(e,t,i){let n=this.receivedEvents.get(e);if(n??(n=new Set),n.add(t),this.dms.every((e=>n.has(e))))return i(),void n.clear();this.receivedEvents.set(e,n)}},cA=()=>(e,t,i)=>{const n=i.value;return i.value=function(...e){return this.serialQueue.add(n.bind(this,...e))},i},dA=class{constructor(e){this.size=e,this.items=[]}clear(){this.items=[]}},uA=class extends dA{get isFull(){return this.items.length>=this.size}add(e){return this.isFull&&this.items.shift(),this.items.push(e),!0}},hA=class extends dA{add(e){return!(this.items.length>=this.size||(this.items.push(e),0))}},pA=class{constructor(e){this.error=new hA(e)}startLoadTimer(){this.loadStartTimestamp=Date.now()}stopLoadTimer(){this.loadDuration=Date.now()-this.loadStartTimestamp}clearErrors(){this.error.clear()}setError(e,t){this.error.add({type:e,message:t})}getReport(){return{loadDuration:this.loadDuration,error:this.error.items}}},gA=class{constructor(e,t,i){this.configProvider=e,this.statistics=t,this.logger=i}isWasmEffectSupported(){return this.configProvider.config.webcv.useWasmEffects?!!window.MediaStreamTrackProcessor||(this.logger.info("wasmEffects disabled, insertable streams are not supported"),!1):(this.logger.info("wasmEffects disabled by feature flag"),!1)}isWebgl2EffectSupported(){return this.isCurrentRendererSupported()&&this.isWebGL2Supported()}isCurrentRendererSupported(){const e=this.configProvider.config.webcv.webGLUnsupportedRenderers;let t=!1;const i=Bg.unmaskedGlRenderer;return i&&!e.some((e=>e===i))?t=!0:(this.statistics.setError("RendererIsNotSupported",`Blacklisted from ${JSON.stringify(e)}`),this.logger.info(`Unsupported renderer: ${Be(i)}`)),t}isWebGL2Supported(){try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return this.statistics.setError("WebGL2IsNotSupported"),this.logger.info("WebGL2 context is not supported"),!1;const t=e.getSupportedExtensions(),i=this.configProvider.config.webcv.webGLRequiredExtensions.filter((e=>!t.includes(e)));if(i.length>0)return this.statistics.setError("WebGL2RequiredExtensionsNotSupported","Required WebGL2 extensions not supported."),this.logger.info(`Unsupported WebGL2 extensions: ${Be(i)}`),!1}catch(e){return this.statistics.setError("WebGL2IsNotSupported",`Error: ${Be(e)}`),this.logger.error(`isWebGL2Supported: ${Be(e)}`),!1}return!0}},mA=class extends qe{constructor(e,t,i,n){super(i),this.webcvProvider=e,this.configProvider=t,this.logger=i,this.createWasmCVWorker=n,this.serialQueue=new Hw(this.logger),this.videoEffectToWebCVEffectMapping={0:mh.VideoEffectType.Off,1:mh.VideoEffectType.BackgroundBlur,16:mh.VideoEffectType.BackgroundReplacement},this.effectType=0,this.isPortrait=!1,this.effectProviderSubs=[],this.statistics=new pA(this.configProvider.config.effectsTelemetryBufferSize),this.processorType=mh.ProcessorType.Webgl2,this.lastNotifiedResolutions=new Map}get isEffectEnabled(){return 0!==this.effectType}async init(){if(!this.effectProvider){this.logger.safe.debug("Init");try{this.effectProvider=await this.initializeVideoEffectProvider()}catch(e){throw this.notifyError("FailedToInitialize",`Initialization failed, error:${Be(e)}`),e}}}async dispose(){this.logger.safe.debug("Dispose"),this.effectProvider&&(this.effectProviderSubs.forEach((e=>e.dispose())),this.effectProviderSubs=null,await this.effectProvider.disposeAsync()),this.lastNotifiedResolutions.clear(),super.dispose()}async configure(e){if(this.logger.safe.debug(`Set config: ${JSON.stringify(e)}`),this.effectConfig={backgroundImageUrl:e.imagePath,headers:e.headers},this.effectProvider)return this.effectProvider.configureEffect(this.effectConfig);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setEffectAsync(e){if(!this.shouldApplyEffect(e))return void this.logger.safe.debug(`Effect ${this.effectType} is already set`);this.effectProvider||(this.logger.safe.debug("Initializing effect provider"),await this.init()),this.logger.safe.debug(`Set effect: ${e}`);const t=this.getWebCVEffect(e);if(!t)throw new Error(`Effect with type ${e} is not supported`);if(this.shouldCollectStats(e)&&this.notifyAboutLastSessionStats("EffectChanged"),this.effectType=e,this.effectProvider)try{await this.effectProvider.setEffectAsync(t)}catch(e){throw await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to apply ${t}, error:${Be(e)}`),e}else this.logger.safe.debug("WebCV is not initialized. Do nothing")}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}`),!this.effectProvider)return this.logger.safe.debug("WebCV is not initialized. Do nothing"),e;if(e.getTracks().length>0){const t=e.getVideoTracks()[0].getSettings();this.isPortrait=t.height>t.width}let t=e;try{t=await this.effectProvider.setSourceAsync(e)}catch(e){await this.handleFailedProcessing(),this.notifyError("FailedToInitialize",`Failed to set source, error:${Be(e)}`)}return t}async removeSourceAsync(e){if(this.logger.safe.debug(`Remove source: ${e?e.id:"no stream"}`),this.effectProvider)return this.effectProvider.removeSourceAsync(e);this.logger.safe.debug("WebCV is not initialized. Do nothing")}async getEffectsCapability(){let e=0;const t=await this.getCapability();this.logger.safe.debug(`Get capabilty with return: ${JSON.stringify(t)}`);for(const i of t){const t=this.getVideoEffectType(i);if(!t)throw new Error(`Cannot convert WebCV effect to VideoEffect ${i}`);e|=t}return e}getStats(e){if(!this.effectProvider)return;const t=this.effectProvider.getStats(),i=this.statistics.getReport();return t||i.error.length?{timestamp:Date.now(),statsReason:e,...this.createTelemetryEvent(t,i)}:void 0}getVersion(){return this.effectProvider?.getVersion?.()??"Unknown"}async resetOutputConstraints(e,t=mh.EffectQualityChangeReason.ExternalParam){const i=this.getNewResolution(e,t),n={...this.configProvider.config.webcv.qualityConfig};return this.isPortrait?n.outputResolution=i.width:n.outputResolution=i.height,this.effectProvider?.configureStreamProcessor(n,mh.EffectQualityChangeReason.ExternalParam)}getNewResolution(e,t){let i;switch(t){case mh.EffectQualityChangeReason.ExternalParam:i=this.lastNotifiedResolutions.get(mh.EffectQualityChangeReason.RendererSize),this.lastNotifiedResolutions.set(mh.EffectQualityChangeReason.ExternalParam,e);break;case mh.EffectQualityChangeReason.RendererSize:i=this.lastNotifiedResolutions.get(mh.EffectQualityChangeReason.ExternalParam),this.lastNotifiedResolutions.set(mh.EffectQualityChangeReason.RendererSize,e)}return{width:Math.max(e.width,i?.width||Number.MIN_SAFE_INTEGER),height:Math.max(e.height,i?.height||Number.MIN_SAFE_INTEGER)}}createTelemetryEvent(e,t){return{payload:{version:this.getVersion(),...t,...e,isWasmEnabled:this.processorType===mh.ProcessorType.Wasm}}}notifyError(e,t){this.statistics.setError(e,t),this.notifyAboutLastSessionStats("EffectError")}notifyAboutLastSessionStats(e){const t=this.getStats(e);t&&this.event("onVideoEffectTelementyEvent").raise(t)}async initializeVideoEffectProvider(){if(!this.webcvProvider)return this.logger.safe.debug("WebCV provider is not set"),null;this.statistics.startLoadTimer();const e=await this.webcvProvider.getVideoEffectProvider();if(this.statistics.stopLoadTimer(),!e)return this.statistics.setError("FailedToInitialize"),this.logger.safe.warn("WebCV is not initialized"),null;this.logger.safe.debug(`WebCV v${e.getVersion?.()} is initialized`);const t=await this.webcvProvider.getModelConfig();return await e.configureModel(t),this.configProvider.config.webcv.loadWorkerCallback=this.createWasmCVWorker,await e.configure({...this.configProvider.config.webcv,processorType:this.processorType}),this.effectConfig&&await e.configureEffect(this.effectConfig),this.effectProviderSubs=[e.on("onEffectApplied",(()=>this.event("onMediaStreamUpdateRequested").raise("Video"))),e.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats("EffectStopped"))),e.on("onVideoEffectQualityChanged",(e=>this.event("onVideoEffectQualityChanged").raise(e))),e.on("onVideoStreamQualityChanged",(e=>this.event("onVideoStreamQualityChanged").raise(e.resolution,e.fps,e.reason))),e.on("onCapabilitiesChanged",(()=>this.event("onVideoEffectCapabilitiesChanged").raise())),e.on("onFirstFrameProcessed",(()=>this.onFirstFrameProcessed())),e.on("onErrorNotified",(e=>this.notifyError("WebcvProccessorError",e))),e.on("videoFreezeDetected",(e=>this.event("videoFreezeDetected").raise(e)))],e}async getCapability(){if(!this.configProvider.config.enableVideoEffects)return this.logger.debug("Video effects disabled"),[mh.VideoEffectType.Off];if(!this.webcvProvider)return this.logger.debug("WebCVProvider is not configured"),[mh.VideoEffectType.Off];const e=new gA(this.configProvider,this.statistics,this.logger.createChild("CapabilityChecker"));let t=[mh.VideoEffectType.Off];return e.isWasmEffectSupported()?(t=[mh.VideoEffectType.Off,mh.VideoEffectType.BackgroundBlur,mh.VideoEffectType.BackgroundReplacement],this.processorType=mh.ProcessorType.Wasm):e.isWebgl2EffectSupported()&&(t=[mh.VideoEffectType.Off,mh.VideoEffectType.BackgroundBlur,mh.VideoEffectType.BackgroundReplacement],this.processorType=mh.ProcessorType.Webgl2),this.effectProvider?this.effectProvider.getCapability():t}getWebCVEffect(e){return this.videoEffectToWebCVEffectMapping[e]}getVideoEffectType(e){return st(this.videoEffectToWebCVEffectMapping).find((t=>this.videoEffectToWebCVEffectMapping[t]===e))}onFirstFrameProcessed(){this.event("onVideoEffectApplied").raise(),this.logger.safe.debug("onVideoEffectApplied event raised")}async handleFailedProcessing(){this.effectType=0;try{await this.effectProvider.setEffectAsync(mh.VideoEffectType.Off)}catch(e){this.notifyError("WebcvProccessorError",`Failed to handle error state, error:${Be(e)}`)}}shouldApplyEffect(e){return this.effectType!==e}shouldCollectStats(e){return 0!==this.effectType&&0!==e&&this.effectType!==e}};v([cA()],mA.prototype,"init",1),v([cA()],mA.prototype,"dispose",1),v([cA()],mA.prototype,"configure",1),v([cA()],mA.prototype,"setSourceAsync",1),v([cA()],mA.prototype,"removeSourceAsync",1),v([cA()],mA.prototype,"getEffectsCapability",1);var fA=class extends qe{constructor(e,t,i,n,r,a){super(r),this.wasmdnsProvider=e,this.wasmaecProvider=t,this.wasmVqeProvider=i,this.configProvider=n,this.logger=r,this.createWasmAudioWorkletCbs=a,this.serialQueue=new Hw(this.logger),this.stopped=!0,this.hasError=!1,this.statistics=new pA(this.configProvider.config.effectsTelemetryBufferSize),this.currentEffect=fh.AudioEffectType.Off,this.currentEffectCapability=0,this.audioEffectToWasmAudioEffectType={0:fh.AudioEffectType.Off,1:fh.AudioEffectType.NoiseSuppressionClassic,2:fh.AudioEffectType.NoiseSuppressionDeep,4:fh.AudioEffectType.EchoCancellationClassic,8:fh.AudioEffectType.VoiceQualityEnhancementClassic,16:fh.AudioEffectType.VoiceQualityEnhancementDeep},this.audioEffectTypeToUserNsMode={[fh.AudioEffectType.Off]:"Off",[fh.AudioEffectType.NoiseSuppressionClassic]:"Low",[fh.AudioEffectType.NoiseSuppressionDeep]:"High"},this.noiseSuppressionModeToWasmDnsEffectMapping={Off:fh.AudioEffectType.Off,High:fh.AudioEffectType.NoiseSuppressionDeep,Low:fh.AudioEffectType.NoiseSuppressionClassic}}get isEffectEnabled(){return this.currentEffect!==fh.AudioEffectType.Off}shouldFallbackToNativeProcessing(){return!(!this.configProvider.config.enableAudioProcessingFallback||(this.configProvider.config.wasmvqe.enableVqe||this.configProvider.config.wasmdns.enableNoiseSuppression?this.hasError?(this.logger.safe.info("shouldFallbackToNativeProcessing: error was encountred initializing the package"),0):this.configProvider.config.wasmvqe.enableVqe&&!this.wasmVqeProvider?(this.logger.safe.info("shouldFallbackToNativeProcessing: VQE provider is enabled but not loaded"),0):!this.configProvider.config.wasmdns.enableNoiseSuppression||this.wasmdnsProvider&&this.wasmaecProvider||(this.logger.safe.info("shouldFallbackToNativeProcessing: DNS/AEC provider is enabled but not loaded"),0):(this.logger.safe.info("shouldFallbackToNativeProcessing: custom processing is not enabled"),0)))}nsModeToVqeMode(e,t){switch(e){case"High":return t?fh.VqeMode.DeepVQE:fh.VqeMode.DeepNS;case"Low":return t?fh.VqeMode.SkypeVQE:fh.VqeMode.SkypeNS;default:return t?fh.VqeMode.SkypeAEC:fh.VqeMode.Off}}vqeModeToNsMode(e){switch(e){case fh.VqeMode.DeepVQE:case fh.VqeMode.DeepNS:return"High";case fh.VqeMode.SkypeVQE:case fh.VqeMode.SkypeNS:return"Low";case fh.VqeMode.SkypeAEC:case fh.VqeMode.Off:default:return"Off"}}vqeModeToAudioEffectType(e){switch(e){case fh.VqeMode.DeepVQE:return 16;case fh.VqeMode.DeepNS:return 2;case fh.VqeMode.SkypeVQE:return 8;case fh.VqeMode.SkypeNS:return 1;case fh.VqeMode.SkypeAEC:return 4;case fh.VqeMode.Off:default:return 0}}async initializeProvider(){if(this.configProvider.config.wasmvqe.enableVqe&&!this.vqeProvider)return this.logger.safe.debug("Initializing VQE provider ..."),void(this.vqeProvider=await this.initializeAudioEffectProvider(fh.AudioEffectType.VoiceQualityEnhancementDeep));this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.dnsProvider&&(this.logger.safe.debug("Initializing DNS provider ..."),this.dnsProvider=await this.initializeAudioEffectProvider(fh.AudioEffectType.NoiseSuppressionDeep)),this.configProvider.config.wasmdns.enableNoiseSuppression&&!this.aecProvider&&(this.logger.safe.debug("Initializing AEC provider ..."),this.aecProvider=await this.initializeAudioEffectProvider(fh.AudioEffectType.EchoCancellationClassic))}async configureEffect(e){this.statistics.clearErrors();let t=e;if(!t){let e=this.configProvider.mediaConfig.noiseSuppressionMode;this.logger.safe.info(`Configuring the audio effect manager for Noise Suppression mode: ${e}`),"Auto"===e&&(e=this.configProvider.config.wasmvqe.enableVqe?this.vqeModeToNsMode(this.configProvider.config.wasmvqe.defaultVqeMode):this.configProvider.config.wasmdns.noiseSuppressionMode,this.logger.safe.info(`Overriding 'Auto' with ${e}`)),t={...this.configProvider.config.wasmdns,...this.configProvider.config.wasmvqe},t.noiseSuppressionMode=e}if(await this.getEffectsCapability(),this.configProvider.config.wasmvqe.enableVqe)try{if(!this.vqeProvider)return void this.logger.safe.error("VQE provider is not initialized");this.userNoiseSuppressionMode&&(t.noiseSuppressionMode=this.vqeModeToNsMode(this.userNoiseSuppressionMode)),this.logger.safe.debug("Configuring VQE audio effects ..."),await this.vqeProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${Be(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${Be(t)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate()}else if(this.configProvider.config.wasmdns.enableNoiseSuppression){t.noiseSuppressionMode||(this.logger.safe.debug("configureEffect was called without a noiseSuppressionMode. Using noiseSuppressionMode from config provider ..."),t.noiseSuppressionMode=this.configProvider.mediaConfig.noiseSuppressionMode),this.currentEffect=this.noiseSuppressionModeToWasmDnsEffectMapping[t.noiseSuppressionMode],this.logger.safe.debug(`currentEffect is ${this.currentEffect}`);try{if(!this.dnsProvider||!this.aecProvider)return void this.logger.safe.debug("DNS & AEC providers not initialized");this.logger.safe.debug("Configuring DNS/AEC audio effects ..."),t.loadAudioWorkletCallback=this.createWasmAudioWorkletCbs?.getWasmDnsWorklet,await this.dnsProvider.configureEffect(t),t.loadAudioWorkletCallback=this.createWasmAudioWorkletCbs?.getWasmAecWorklet,await this.aecProvider.configureEffect(t),this.logger.safe.debug(`The audio effects were configured as follows: ${Be(t)}, and current capability is ${this.currentEffectCapability}.`)}catch(e){this.notifyError("FailedToInitialize",`Audio effect provider configuration failed (${e}), while trying to use this configuration: ${Be(t)},\n                    under the following capability: ${this.currentEffectCapability}.`),this.requestStreamUpdate()}}}async setSourceAsync(e){if(this.logger.safe.debug(`Set source: ${e?e.id:"no stream"}, currentEffect = ${this.currentEffect}`),this.stopped||(this.stop(),this.stopped=!1),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const t=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${t}).`),this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${t}).`),e}if(!this.configProvider.config.wasmvqe.enableVqe&&!this.configProvider.config.wasmdns.enableNoiseSuppression)return e;if(this.effectProviderSubs=[this.vqeProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.vqeProvider?.on("onErrorNotified",(e=>this.notifyError("WasmVqeProccessorError",e))),this.dnsProvider?.on("onEffectStopped",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onMetricsUpdated",(()=>this.notifyAboutLastSessionStats())),this.dnsProvider?.on("onErrorNotified",(e=>this.notifyError("WasmDnsProccessorError",e))),this.aecProvider?.on("onErrorNotified",(e=>this.notifyError("WasmAecProccessorError",e)))],this.configProvider.config.wasmvqe.enableVqe)try{const t=await this.vqeProvider.setSourceAsync(e);return this.aecRefStream&&this.vqeProvider.setRefStream(this.aecRefStream),t}catch(t){return this.notifyError("WasmVqeProccessorError",`setSourceAsync: Failed to asynchronously set source for VQE (${t})`),e}let t=e;try{t=await this.aecProvider.setSourceAsync(e),this.aecRefStream&&this.aecProvider.setRefStream?.(this.aecRefStream)}catch(e){this.notifyError("WasmAecProccessorError",`setSourceAsync: Failed to asynchronously set source for AEC (${e})`)}try{return await this.dnsProvider.setSourceAsync(t)}catch(e){this.notifyError("WasmDnsProccessorError",`setSourceAsync: Failed to asynchronously set source for DNS (${e})`)}return t}async setAecRefStream(e){try{if(this.logger.safe.debug(`Setting the reference stream to: ${e?e.id:"Null"}`),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setAecRefStream: audio effect provider not initialized (${e}).`),void this.logger.safe.warn(`Unable to setAecRefStream for audio effects: audio effect provider not initialized (${e}).`)}this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider.setRefStream(e):this.configProvider.config.wasmdns.enableNoiseSuppression&&this.aecProvider.setRefStream(e)}catch(e){this.notifyError("WasmVqeProccessorError",`setRefStream: Failed to set reference stream for echo cancellation (${e})`)}this.aecRefStream=e}async setEffectAsync(e){const t=this.audioEffectToWasmAudioEffectType[e];if(this.currentEffect===t)return;const i=this.currentEffect===fh.AudioEffectType.Off||t===fh.AudioEffectType.Off;if(this.currentEffect=t,this.userNoiseSuppressionMode=this.nsModeToVqeMode(this.audioEffectTypeToUserNsMode[t],!1),await this.initializeProvider(),await this.configureEffect(),!(this.vqeProvider||this.dnsProvider&&this.aecProvider)){const e=this.vqeProvider?this.dnsProvider?"AEC":"DNS":"VQE";return this.statistics.setError("FailedToInitialize",`setSourceAsync: audio effect provider not initialized (${e}).`),void this.logger.safe.warn(`Unable to configure audio effects: audio effect provider not initialized (${e}).`)}try{this.configProvider.config.wasmvqe.enableVqe?await this.vqeProvider.setEffectAsync(t):this.configProvider.config.wasmdns.enableNoiseSuppression&&(await this.dnsProvider.setEffectAsync(t),await this.aecProvider.setEffectAsync(t)),this.configProvider.config.applyAudioEffectOnDemand&&this.configProvider.config.wasmvqe.enableVqe&&i&&this.requestStreamUpdate(!0),this.logger.safe.debug(`The audio effect was set to '${t}'`)}catch(e){throw this.notifyError("WasmVqeProccessorError",`setEffectAsync: Failed to apply '${t}' audio effect, error: ${Be(e)}`),e}}stop(){try{this.dnsProvider?.dispose(),this.dnsProvider=null,this.aecProvider?.dispose(),this.aecProvider=null,this.vqeProvider?.dispose(),this.vqeProvider=null,this.effectProviderSubs?.forEach((e=>e?.dispose())),this.effectProviderSubs=null,this.stopped=!0,this.logger.safe.debug("The audio effects provider was stopped.")}catch(e){this.logger.safe.error(`Failed to stop the audio effects provider (${e})`)}}dispose(){try{this.hasError=!1,this.stop(),super.dispose(),this.logger.safe.debug("The audio effects provider was disposed.")}catch(e){this.logger.safe.error(`dispose: Failed to dispose the audio effects provider (${e})`)}}async getEffectsCapability(){return this.currentEffectCapability=0,this.configProvider.config.wasmvqe.enableVqe?(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.configProvider.config.wasmvqe.enableAec&&(this.currentEffectCapability|=4,this.currentEffectCapability|=8,this.currentEffectCapability|=16)):this.configProvider.config.wasmdns.enableNoiseSuppression&&(this.currentEffectCapability|=1,this.currentEffectCapability|=2,this.currentEffectCapability|=4),this.currentEffectCapability}getVersion(){return`WasmDns ${this.dnsProvider?.getVersion()??"Unknown"} / WasmAec ${this.aecProvider?.getVersion()??"Unknown"} / WasmVqe ${this.vqeProvider?.getVersion()??"Unknown"}`}getStats(){const e=this.configProvider.config.wasmvqe.enableVqe?this.vqeProvider?.getStats():this.dnsProvider?.getStats();return e?(e.userNoiseSuppressionMethod=this.userNoiseSuppressionMode,{timestamp:Date.now(),...this.createTelemetryEvent(e)}):null}async initializeAudioEffectProvider(e){if(!this.wasmVqeProvider&&e===fh.AudioEffectType.VoiceQualityEnhancementDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmVqe package not available."),this.logger.safe.warn("WasmVqe package not available."),null;if(!this.wasmdnsProvider&&e===fh.AudioEffectType.NoiseSuppressionDeep)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmDns package not available."),this.logger.safe.warn("WasmDns package not available."),null;if(!this.wasmaecProvider&&e===fh.AudioEffectType.EchoCancellationClassic)return this.statistics.setError("FailedToInitialize","initializeAudioEffectProvider: WasmAec package not available."),this.logger.safe.warn("WasmAec package not available."),null;let t;this.statistics.startLoadTimer();try{this.configProvider.config.wasmvqe.enableVqe&&e===fh.AudioEffectType.VoiceQualityEnhancementDeep&&(t=await this.wasmVqeProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===fh.AudioEffectType.NoiseSuppressionDeep&&(t=await this.wasmdnsProvider.getAudioEffectProvider()),this.configProvider.config.wasmdns.enableNoiseSuppression&&e===fh.AudioEffectType.EchoCancellationClassic&&(t=await this.wasmaecProvider.getAudioEffectProvider())}catch(e){this.logger.safe.warn(`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`),this.statistics.setError("FailedToInitialize",`initializeAudioEffectProvider: Failed to initialize the audio effect provider (${e})`)}return this.statistics.stopLoadTimer(),t?(e===fh.AudioEffectType.VoiceQualityEnhancementDeep&&this.logger.safe.debug(`WasmVqe v${t.getVersion?.()} initialized!`),e===fh.AudioEffectType.NoiseSuppressionDeep&&this.logger.safe.debug(`WasmDns v${t.getVersion?.()} initialized!`),e===fh.AudioEffectType.EchoCancellationClassic&&this.logger.safe.debug(`WasmAec v${t.getVersion?.()} initialized!`),t):(this.logger.safe.warn("Unitialized Wasm audio effect provider."),null)}createTelemetryEvent(e){return{payload:{audioEffectsCapability:this.currentEffectCapability,version:this.getVersion(),...this.statistics.getReport(),...e}}}notifyError(e,t){this.statistics.setError(e,t),this.notifyAboutLastSessionStats()}notifyAboutLastSessionStats(){const e=this.getStats();e&&this.event("onAudioEffectTelemetryEvent").raise(e)}requestStreamUpdate(e=!1){(e||this.configProvider.config.enableAudioProcessingFallback&&!this.hasError)&&(this.hasError=!0,this.event("onMediaStreamUpdateRequested").raise("Audio"))}};v([cA()],fA.prototype,"setSourceAsync",1),v([cA()],fA.prototype,"setAecRefStream",1),v([cA()],fA.prototype,"setEffectAsync",1),v([cA()],fA.prototype,"stop",1),v([cA()],fA.prototype,"dispose",1);var vA=class extends qe{constructor(e,t){super(),this.configProvider=e,this.logger=t}isEffectEnabled(e){switch(e){case"Video":return this.videoEffectManager?.isEffectEnabled;case"Audio":return this.audioEffectManager?.isEffectEnabled;default:return!1}}shouldFallbackToNativeProcessing(e){return"Audio"===e&&this.audioEffectManager?.shouldFallbackToNativeProcessing()}addEffectManager(e,t){switch(e){case"Audio":this.addAudioEffectManagerAndSubscribe(t);break;case"Video":this.addVideoEffectManagerAndSubscribe(t)}}async startEffect(e,t){switch(e){case"Audio":return this.logger.safe.info("audioEffectManager is "+(this.audioEffectManager?"defined":"undefined")),this.audioEffectManager?.shouldFallbackToNativeProcessing()?(this.logger.safe.info("No custom audio effect is used. Fallback to native audio processing"),t):this.audioEffectManager.setSourceAsync(t);case"Video":return this.videoEffectManager.setSourceAsync(t);default:return t}}async setEffectType(e,t){switch(e){case"Audio":return this.audioEffectManager?.setEffectAsync(t);case"Video":return this.videoEffectManager?.setEffectAsync(t)}}stopEffect(e,t){switch(e){case"Audio":this.logger.safe.info("stopping audio effect"),this.audioEffectManager?.stop();break;case"Video":this.logger.safe.info("stopping video effect"),this.videoEffectManager?.removeSourceAsync(t)}}resetOutputConstraints(e,t,i){"Video"===e&&this.videoEffectManager?.resetOutputConstraints(t,i)}getStats(e,t){switch(e){case"Audio":return this.audioEffectManager?.getStats();case"Video":return this.videoEffectManager?.getStats(t);default:return}}async configure(e,t){if("Video"===e)return this.videoEffectManager?.configure(t)}async getEffectsCapability(e){switch(e){case"Audio":return this.audioEffectManager?.getEffectsCapability();case"Video":return this.videoEffectManager?.getEffectsCapability();default:return 0}}setAecRefStream(e){return this.audioEffectManager.setAecRefStream(e)}vqeModeToAudioEffectType(e){return this.audioEffectManager.vqeModeToAudioEffectType(e)}nsModeToVqeMode(e,t){return this.audioEffectManager.nsModeToVqeMode(e,t)}dispose(){super.dispose(),this.audioEffectManager?.dispose(),this.audioEffectManager=null,this.videoEffectManager?.dispose(),this.videoEffectManager=null}addAudioEffectManagerAndSubscribe(e){this.audioEffectManager||(this.audioEffectManager=new fA(e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.configProvider,this.logger.createChild("AudioEffectManager"),e.createAudioWasmWorkerCbs),this.audioEffectManager.on("onAudioEffectTelemetryEvent",(e=>{this.event("onAudioEffectTelemetryEvent").raise(e)})),this.audioEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})))}addVideoEffectManagerAndSubscribe(e){this.videoEffectManager||(this.videoEffectManager=new mA(e.webcvProvider,this.configProvider,this.logger.createChild("VideoEffectManager"),e.createWasmCVWorker),this.videoEffectManager.on("onMediaStreamUpdateRequested",(e=>{this.event("onMediaStreamUpdateRequested").raise(e)})),this.videoEffectManager.on("onVideoEffectQualityChanged",(e=>{this.event("onVideoEffectQualityChanged").raise(e)})),this.videoEffectManager.on("onVideoStreamQualityChanged",((e,t,i)=>{this.event("onVideoStreamQualityChanged").raise(e,t,i)})),this.videoEffectManager.on("onVideoEffectCapabilitiesChanged",(()=>{this.event("onVideoEffectCapabilitiesChanged").raise()})),this.videoEffectManager.on("onVideoEffectTelementyEvent",(e=>{this.event("onVideoEffectTelementyEvent").raise(e)})),this.videoEffectManager.on("onVideoEffectApplied",(()=>{this.event("onVideoEffectApplied").raise()})),this.videoEffectManager.on("videoFreezeDetected",(e=>{this.event("videoFreezeDetected").raise(e)})))}},SA=class e extends qe{constructor(t,i,n,r,a,s,o,l,c,d){super(t),this.logger=t,this.configProvider=i,this.diagnostics=n,this.domOverrides=r,this.ufdManager=a,this.id=dt(),this.virtualDeviceRecord=new Map,this.deviceEnumerator=new iA(this.configProvider,this.logger.createChild("DeviceEnumerator")),this.deviceSelection=new nA(iA.list,this.configProvider,this.logger.createChild("DeviceSelection")),this.permissionManager=new oA(this.configProvider,{getMediaStream:e=>this.getMediaStream({...e,withEffect:!1,withTimeout:!0,force:!1,audioProcessingFlags:e.audio&&!e.video?this.getAudioProcessingFlags():void 0},"permissionManager"),hasCamera:()=>this.hasDeviceType("camera"),raiseTelemetryEvent:(e,t)=>this.raiseTelemetryEvent(e,t),getActiveConstraints:()=>this.mediaStreamManager.getActiveConstraints(),handlePermissionStateChange:()=>this.handlePermissionStateChange()},this.logger.createChild("PermissionManager")),this.activeRenderers=[],this.selectedDevices={camera:null,microphone:null,speaker:null,audioIngestDevice:null},this.pendingDevices=null,this.deviceManagerSubscriptions=[],this.streamManagerSubscriptions=[],this.streamSubscriptions=new Map,this.rendererSubscriptions=new Map,this.rawDeviceStreamManager=new Bw(this.logger.createChild("RawDeviceStream"),this.raiseTelemetryEvent.bind(this)),this.customDeviceMediaStreamMap=new Map,this.clientAudioRenderers=new Map,this.audioSharingRequested=!1,this.virtualDeviceSubs=new Map,this.effectsManagerInternal=new vA(this.configProvider,this.logger.createChild("EffectsManager")),this.effectsManagerInternal.addEffectManager("Audio",{wasmdnsProvider:o,wasmaecProvider:l,wasmVqeProvider:c,createAudioWasmWorkerCbs:d?.audioWorklet}),this.effectsManagerInternal.addEffectManager("Video",{webcvProvider:s,createWasmCVWorker:d?.createWasmCVWorker}),this.mediaStreamManager=new BR(this.logger.createChild("MediaStreamManager"),this.configProvider,this.effectsManager),this.deviceManagerSubscriptions=[this.permissionManager.on("onDevicesPermissionChanged",(()=>this.event("onDevicesPermissionChanged").raise())),iA.list.on("onDevicesChanged",((e,t)=>this.onDevicesChanged(e,t))),this.deviceSelection.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),this.effectsManager.on("onAudioEffectTelemetryEvent",(e=>{this.diagnostics?.registerAudioEffectsEvent(lt(e)),this.event("onAudioEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onMediaStreamUpdateRequested",(e=>this.onMediaStreamUpdateRequested(e,!0))),this.effectsManager.on("onVideoEffectQualityChanged",(e=>this.onVideoEffectsQualityEventHandler(e))),this.effectsManager.on("onVideoEffectTelementyEvent",(e=>{this.diagnostics?.registerVideoEffectsEvent(lt(e)),this.event("onVideoEffectsTelemetryEvent").raise(e)})),this.effectsManager.on("onVideoEffectApplied",(()=>{this.raiseTelemetryEvent("video_effect_applied",{}),this.event("onVideoEffectApplied").raise()}))],this.subscribeOnStreamManagerEvents(),this.subscribeOnDeviceEnumeratorEvents(),this.deviceList.length&&this.onSelectedDevicesChanged(this.deviceSelection.selectedDevices,!1),this.createChildDeviceManager=t=>new e(t,i,void 0,r,a,s,o,l,c,d)}get deviceList(){return iA.list.devices}get isDeviceEnumeratorInitialized(){return iA.isInitialized}get isAudioOutputSelectionSupported(){return this.configProvider.userAgentConfig.isAudioOutputSelectionSupported}get effectsManager(){return this.effectsManagerInternal}createPreviewRenderer(e){const t=new eR(e,this,this.logger.createChild("videorenderer"),this.configProvider);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(t.getVideoElement()),this.subscribeOnRendererEvents(t),t}async askDevicePermission(e){await this.isDeviceEnumeratorInitialized.promise;const t=await this.permissionManager.askDevicePermission(e);if(this.configProvider.config.devices.enumerateDevicesAfterADP)try{await iA.enumerateDevices()}catch(e){this.logger.safe.warn(`Post-ADP device enumeration failed: ${Be(e)}`)}return t}getPermissionState(e){return this.permissionManager.getPermissionState(e)}handlePermissionStateChange(){this.diagnostics&&(this.diagnostics.permissionStates=this.permissionManager.knownPermissionStates),this.event("onPermissionStateChanged").raise()}onMediaStreamUpdateRequested(e,t=!1){if("Video"===e&&(this.updateRenderersAsync(),this.effectsManager.isEffectEnabled("Video")))return this.logger.safe.info("onStreamUpdateRequested will be called after the first frame is proccessed of the video effect stream"),void this.effectsManager.once("onVideoEffectApplied",(()=>this.event("onStreamUpdateRequested").raise(e)));this.event("onStreamUpdateRequested").raise(e,t)}createAudioRenderer(){const e=new Vw(this.logger.createChild("CustomAudioRenderer"),this.configProvider),t=dt();this.clientAudioRenderers.set(t,e);const i=e.play.bind(e),n=e.stop.bind(e);return this.raiseTelemetryEvent("custom_audio_renderer_created",this.getSelectedDevices()),{play:i,stop:n,dispose:()=>{this.clientAudioRenderers.get(t)?.dispose(),this.clientAudioRenderers.delete(t)},setMuted:(t,i=Te())=>e.setMuted(t,i),isMuted:()=>e.muted}}setAudioSharingRequested(e){this.audioSharingRequested=e}createDevicesHandle(e,t,i){const n=e.sharing?"ScreenShare":e.video?"Video":"Audio";return new rA(this.logger.createChild("DevicesHandle"),this.getMediaStream({...e,...i&&{deviceId:i},withTimeout:!1,withEffect:!1,audioProcessingFlags:this.audioProcessingFlags,force:!1,withOverridenStream:this.customDeviceMediaStreamMap.get(n)?.active&&this.customDeviceMediaStreamMap.get(n)},t))}shareSystemSound(e){this.configProvider.config.postponeAudioMixerForAudioSharing&&(this.audioSharingRequested=e,this.event("onAudioSharingToggled").raise(e))}getAllowedModalities(){const e=ot(this.permissionManager.browserPermittedModalities);return this.hasDeviceType("microphone")||(e.audio=[Qe.MEDIA_STATE.inactive,Qe.MEDIA_STATE.receive]),this.hasDeviceType("camera")||(e.video=[Qe.MEDIA_STATE.inactive,Qe.MEDIA_STATE.receive]),e}getRawDeviceMediaStream(e,t){if("ScreenShare"!==e&&!this.hasDeviceType(this.getDeviceType(e)))throw new Error("NoInputDevice");this.audioSharingRequested=t;const i=this.getStreamHandlerByType(e);if(!i)return this.logger.safe.debug(`method not found for ${e}`),null;const n=this.rawDeviceStreamManager.createIRawStreamClient(i,e);return this.raiseTelemetryEvent("IRawStream_client_created",e),n}setRawMediaStream(e,t){if(!e)throw this.logger.error(`Could not set ${e} as to ${t}`),new Error("InvalidStream");this.customDeviceMediaStreamMap.set(t,e),this.onMediaStreamUpdateRequested(t),this.raiseTelemetryEvent("set_raw_outgoing_media_stream",t)}unsetRawMediaStream(e){this.customDeviceMediaStreamMap.get(e)?(this.customDeviceMediaStreamMap.delete(e),this.onMediaStreamUpdateRequested(e),this.raiseTelemetryEvent("unset_raw_outgoing_media_stream",e)):this.logger.safe.debug("no custom stream")}async setVideoEffects(e){return this.effectsManager.setEffectType("Video",e)}async setAudioEffects(e){return this.effectsManager.setEffectType("Audio",e)}async getAudioStream(e,t,i=!1){const n=this.configProvider.config.devices.enumerateBeforeGettingStream;return n&&("always"!==n&&iA.isPolling||await iA.enumerateDevices()),this.getMediaStream({audio:!0,withTimeout:this.permissionManager.isPermissionKnown("microphone"),withEffect:!i&&this.effectsManager.isEffectEnabled("Audio"),audioProcessingFlags:this.getAudioProcessingFlags(),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Audio")?.active&&this.customDeviceMediaStreamMap.get("Audio")},t)}async getVideoStream(e,t,i=!1){const n=this.configProvider.config.devices.enumerateBeforeGettingStream;return n&&("always"!==n&&iA.isPolling||await iA.enumerateDevices()),this.getMediaStream({video:!0,withTimeout:this.permissionManager.isPermissionKnown("camera"),withEffect:!i&&this.configProvider.config.enableVideoEffects&&this.effectsManager.isEffectEnabled("Video"),force:e,withOverridenStream:!i&&this.customDeviceMediaStreamMap.get("Video")?.active&&this.customDeviceMediaStreamMap.get("Video")},t)}getDisplayStream(e,t=!1){const i=!(!this.configProvider.config.enableAudioSharing||!this.audioSharingRequested);return this.getMediaStream({audio:i,sharing:!0,withTimeout:!1,withEffect:!1,audioProcessingFlags:i?0:void 0,force:!1,withOverridenStream:!t&&this.customDeviceMediaStreamMap.get("ScreenShare")?.active&&this.customDeviceMediaStreamMap.get("ScreenShare")},e)}async enumerateDevicesAsync(){return await this.isDeviceEnumeratorInitialized.promise,this.getDeviceDescriptions(this.deviceList)}async getDeviceNameAsync(e){await this.isDeviceEnumeratorInitialized.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.label??""}async getSpeakerDeviceDomIdAsync(e){await this.isDeviceEnumeratorInitialized.promise;const t=this.deviceList.find((t=>t.guid===e));return t?.deviceId??""}selectDevices(e){return this.pendingDevices?(this.logger.safe.info(`Overriding device selection until enumeration is complete with ${JSON.stringify(hm(this.pendingDevices))}`),void(this.pendingDevices=e)):this.isDeviceEnumeratorInitialized.isPending?(this.logger.safe.info("Postponing device selection until enumeration is complete"),this.pendingDevices=e,void this.isDeviceEnumeratorInitialized.promise.then((()=>{this.logger.safe.info("Performing postponed device selection");const e=this.pendingDevices;this.pendingDevices=null,this.selectDevices(e)}))):void this.deviceSelection.selectDevices(e)}getSelectedDevices(){return this.toSelectedDevices(this.deviceSelection.selectedDevices)}setAudioProcessingFlags(e){e!==this.audioProcessingFlags&&(this.logger.debug(`Setting audio processing flags: ${this.audioProcessingFlags} -> ${e}`),this.audioProcessingFlags=e,this.event("onStreamUpdateRequested").raise("Audio"))}getOutputDeviceId(){return this.selectedDevices.speaker?.deviceId}getDeviceDescriptions(e){return(e||this.deviceList).map((e=>e.toDeviceDesc()))}getDevicesCount(){return this.deviceList.reduce(((e,t)=>(e[t.type]++,e)),{camera:0,speaker:0,microphone:0,compositeAudio:0,virtualDevice:0,audioIngestDevice:0})}async getKnownPermissionStates(){return await this.permissionManager.initialize(),this.permissionManager.knownPermissionStates}getLocalVideoRenderers(){return this.activeRenderers}dispose(){this.deviceManagerSubscriptions?.forEach((e=>e.dispose())),this.deviceManagerSubscriptions=null,this.virtualDeviceSubs?.forEach((e=>e.forEach((e=>e.dispose())))),this.virtualDeviceSubs?.clear(),this.virtualDeviceSubs=null,this.virtualDeviceRecord?.forEach((e=>e.dispose())),this.virtualDeviceRecord=null,this.unsubscribeFromStreamManagerEvents(),this.deviceEnumerator.dispose(),this.mediaStreamManager.dispose(),this.activeVideoEffectSub?.dispose(),this.activeVideoStreamForEffect?.dispose(),this.disposeRawStreamAccess(),this.disposeClientAudioRenderer(),this.effectsManager.dispose(),super.dispose()}async registerVirtualDevice(e,t){const i=e.length?e.map((({id:e},t)=>{const i=this.createChildDeviceManager(this.logger.createChild(`VirtualDevice-${t}`));return i.selectDevices({camera:e}),i})):[this.createChildDeviceManager(this.logger.createChild("VirtualDevice"))],n=new lA(i,t),r=n.id,a=[n.on("onVideoEffectApplied",((...e)=>this.event("onVideoEffectApplied").raise(...e))),n.on("onVideoEffectsEvent",((...e)=>this.event("onVideoEffectsEvent").raise(...e))),n.on("onDeviceTelemetryEvent",((...e)=>this.event("onDeviceTelemetryEvent").raise(...e))),n.on("onVideoEffectsTelemetryEvent",((...e)=>this.event("onVideoEffectsTelemetryEvent").raise(...e))),n.on("onDevicesPermissionChanged",((...e)=>this.event("onDevicesPermissionChanged").raise(...e))),n.on("onStreamUpdateRequested",((...e)=>this.event("onStreamUpdateRequested").raise(...e)))];return this.virtualDeviceSubs.set(r,a),this.virtualDeviceRecord.set(r,n),iA.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.raiseTelemetryEvent("register_virtual_device",{deviceCount:i.length,id:r}),this.event("onVirtualDevicesChanged").raise(),r}async unregisterVirtualDevice(e){this.virtualDeviceRecord.has(e)?(this.virtualDeviceSubs.get(e).forEach((e=>e.dispose())),this.virtualDeviceSubs.delete(e),this.virtualDeviceRecord.get(e).dispose(),this.virtualDeviceRecord.delete(e),iA.list.updateVirtualDeviceList(this.getRegisteredDevices()),this.event("onVirtualDevicesChanged").raise(),this.raiseTelemetryEvent("unregister_virtual_device",{id:e})):this.logger.error(`No virtual device found with id ${e}`)}getRegisteredDevices(){return Array.from(this.virtualDeviceRecord.values())}getAudioProcessingFlags(){if(!this.effectsManager.shouldFallbackToNativeProcessing("Audio"))return this.audioProcessingFlags??this.configProvider.config.defaultAudioProcessingFlags}disposeClientAudioRenderer(){this.clientAudioRenderers.size&&(this.clientAudioRenderers.forEach((e=>{e.dispose()})),this.clientAudioRenderers.clear(),this.raiseTelemetryEvent("custom_audio_renderer_disposed",this.getSelectedDevices()))}disposeRawStreamAccess(){this.rawDeviceStreamManager.disposeAll(),this.rawDeviceStreamManager=null}toSelectedDevices(e){return Object.entries(e).reduce(((e,[t,i])=>(i&&(e[t]=i.guid),e)),{})}getStreamConstraints(e){return{deviceId:e?.deviceId||void 0}}hasDeviceType(e){return rt(this.deviceList).some((t=>t.type===e))}getConstraints(e){if(!e.audio&&!e.video&&!e.sharing)throw new Error("requesting nothing");if(this.logger.safe.info(`retrieving media stream: ${JSON.stringify(e)}`),e.sharing){let t;const i=this.selectedDevices.audioIngestDevice;return t=i&&e.deviceId?{deviceId:i.deviceId}:e.audio&&!e.deviceId?{deviceId:Qe.SYSTEM_AUDIO_SOURCE_ID}:void 0,{audio:t,sharing:{deviceId:e.deviceId||Qe.DISPLAY_SOURCE_ID},withTimeout:e.withTimeout,withEffect:!1,audioProcessingFlags:e.audioProcessingFlags,force:!1,withOverridenStream:e.withOverridenStream}}const t=this.selectedDevices.microphone,i=this.selectedDevices.camera,n=e.audio&&t,r=e.video&&i;if(!n&&!r)throw{type:Qe.MEDIA_ERROR.noDeviceSelected,detail:`audio requested ${e.audio}, video requested: ${e.video} Devices: ${JSON.stringify(this.deviceList.map((e=>JSON.stringify(pm(e,this.configProvider.config.devices.piiSafeWords)))))}`};const a=this.getStreamConstraints(t),s=this.getStreamConstraints(i);let o=e.audioProcessingFlags;return void 0!==o&&e.audio&&!e.video&&t?.capabilities&&(t.capabilities.echoCancellation&&!t.capabilities.echoCancellation.includes(!!(2&o))&&(o^=2),t.capabilities.autoGainControl&&!t.capabilities.autoGainControl.includes(!!(1&o))&&(o^=1),t.capabilities.noiseSuppression&&!t.capabilities.noiseSuppression.includes(!!(4&o))&&(o^=4)),o!==e.audioProcessingFlags&&this.logger.safe.warn(`Unable to fulfill processing flags ${e.audioProcessingFlags}, using ${o} instead`),{audio:e.audio?a:void 0,video:e.video?s:void 0,withTimeout:e.withTimeout,withEffect:e.withEffect,audioProcessingFlags:o,force:e.force,withOverridenStream:e.withOverridenStream}}getMediaStream(e,t){const i=this.getConstraints(e),n=this.mediaStreamManager.getMediaStream(i,t);return this.subscribeOnStreamEvents(n),n.start().then((()=>{const t=n.hasAudio(),i=n.hasVideo();t&&this.signalDeviceGood("Audio",n.rawTrack.muted),i&&this.signalDeviceGood(n.mediaType,n.rawTrack.muted),this.permissionManager.update(e,e)})).catch((t=>this.handleUserMediaError(e,t))),n}signalDeviceGood(e,t){this.ufdManager.signalDeviceEvent(0,"Good",e,this.id),this.ufdManager.signalDeviceEvent(1,"Good",e,this.id),this.ufdManager.signalDeviceEvent(3,"Good",e,this.id),t||"Audio"!==e&&!this.configProvider.config.raiseVideoMuteUfd||this.ufdManager.signalDeviceEvent(2,"Good",e,this.id)}handleUserMediaError(e,t){const i=this.getMediaType(e),n=e.audio&&e.video,r=(e,t)=>{!n&&this.ufdManager.signalDeviceEvent(e,t,i,this.id)};switch(t.type){case Qe.MEDIA_ERROR.permissionDeniedError:"ScreenShare"!==i&&(r(3,"Bad"),this.configProvider.config.permissions.persistOnDeniedError&&this.refreshPermissions(e));break;case Qe.MEDIA_ERROR.permissionDeniedBySystemError:r(3,"Bad");break;case Qe.MEDIA_ERROR.sourceUnavailableError:r(0,"Bad");break;case Qe.MEDIA_ERROR.mediaStreamRequestTimedOut:r(1,"Bad");break;default:this.logger.safe.error(`getMediaStream() error: ${Be(t)}`),r(0,"Bad")}}refreshPermissions(e){const t=e.audio&&!e.video,i=!e.audio&&e.video;t?this.permissionManager.update({audio:!0},{audio:!1}):i&&this.permissionManager.update({video:!0},{video:!1})}getMediaType(e){if(e.sharing)return"ScreenShare";if(e.video)return"Video";if(e.audio)return"Audio";throw new Error(`mediaType is not defined for this constraint ${JSON.stringify(e)}`)}subscribeOnStreamEvents(e){const t=[];t.push(e.on("onStreamClientStarted",((e,t)=>this.onStreamStarted(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),t.push(e.on("onStreamClientEnded",((e,t)=>this.onStreamEnded(e,t)))),t.push(e.on("onStreamClientMuted",((e,t)=>this.onStreamMuted(e,t)))),t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),this.configProvider.config.useRawMediaApiForVideoEffects&&t.push(e.on("onStreamClientDisposed",(e=>this.removeVideoEffectStream(e)))),this.streamSubscriptions.set(e,t)}async removeVideoEffectStream(e){if(e.getCurrentConstraints().withEffect){this.logger.safe.info(`this.activeVideoEffectSub: ${this.activeVideoEffectSub} to be disposed`),this.activeVideoEffectSub?.dispose();const e=await(this.activeVideoStreamForEffect?.getMediaStream());this.effectsManager.stopEffect("Video",e)}}unsubscribeFromStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}subscribeOnRendererEvents(e){const t=[];t.push(e.on("onRendererDisposed",(e=>this.onRendererDisposed(e)))),t.push(e.on("onRendererStarted",(e=>this.onRendererStarted(e)))),t.push(e.on("onRendererSizeChanged",((e,t)=>this.onRendererSizeChanged()))),this.rendererSubscriptions.set(e,t)}unsubscribeFromRendererEvents(e){this.rendererSubscriptions.has(e)&&(this.rendererSubscriptions.get(e).forEach((e=>e.dispose())),this.rendererSubscriptions.delete(e))}subscribeOnStreamManagerEvents(){this.streamManagerSubscriptions=[],this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onAllStreamsRemoved",(()=>this.onAllStreamsRemoved()))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamAcquired",((e,t,i,n,r,a)=>this.onStreamAcquired(e,t,i,n,r,a)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamCreated",((e,t)=>this.onStreamCreated(e,t)))),this.streamManagerSubscriptions.push(this.mediaStreamManager.on("onStreamDisposing",((e,t)=>this.onMasterStreamDisposing(e,t))))}subscribeOnDeviceEnumeratorEvents(){this.deviceEnumerator.on("onDeviceEnumerationfailed",(e=>this.raiseTelemetryEvent("enumeration_failed",{error:e})))}unsubscribeFromStreamManagerEvents(){this.streamManagerSubscriptions.forEach((e=>e.dispose()))}async updateRenderersAsync(){try{await Promise.all(this.activeRenderers.map((e=>e.updateStreamAsync()))),this.logger.safe.info("Renderers updates finished")}catch(e){this.logger.safe.error(`Error updating renderers: ${Be(e)}`)}}onSelectedDevicesChanged(e,t){const i=this.selectedDevices;if(this.selectedDevices=e,this.diagnostics?.setSelectedDevices(e,t),!("camera"in i^"camera"in this.selectedDevices||"microphone"in i^"microphone"in this.selectedDevices)){const e=this.toSelectedDevices(this.selectedDevices),t=this.toSelectedDevices(i);this.event("onSelectedDevicesChanged").raise(e,t),e.microphone!==t.microphone&&this.rawDeviceStreamManager.notifyChange("Audio"),e.camera!==t.camera&&this.rawDeviceStreamManager.notifyChange("Video"),this.clientAudioRenderers.forEach((e=>{e.setOutputDevice(this.getOutputDeviceId())}))}const n=this.configProvider.config.devices.piiSafeWords;this.raiseTelemetryEvent("selected_devices_changed",{microphone:this.selectedDevices.microphone&&_t(this.selectedDevices.microphone.label,n),camera:this.selectedDevices.camera&&_t(this.selectedDevices.camera.label,n),speaker:this.selectedDevices.speaker&&_t(this.selectedDevices.speaker.label,n),fromInterface:t}),this.updateRenderersAsync()}onDevicesChanged(e,t){this.event("onDevicesChanged").raise(e,t),this.mediaStreamManager.onDevicesChanged(e),this.diagnostics?.setDeviceList(e,t,this.getDeviceListDebugInfo());const i=this.getDevicesCount();this.ufdManager.signalEvent("ZeroCaptureDevicesEnumerated",i.microphone>0?"Good":"Bad"),this.isAudioOutputSelectionSupported&&this.ufdManager.signalEvent("ZeroRenderDevicesEnumerated",i.speaker>0?"Good":"Bad");const n=new Map;let r=1;this.raiseTelemetryEvent("devices_changed",{devices:e.map((e=>{const t=n.get(e.groupId)||r++;return n.set(e.groupId,t),{label:_t(e.label,this.configProvider.config.devices.piiSafeWords),isSystemDefault:e.isSystemDefault,kind:e.kind,type:e.type,capabilities:e.capabilities,groupId:`${t}`}})),debug:this.getDeviceListDebugInfo()})}getDeviceListDebugInfo(){return iA.list.debugInfo}raiseTelemetryEvent(e,t){this.logger.safe.info(`Device event: ${e}: ${JSON.stringify(this.scrubPayload(e,t))}`);const i={eventType:e,timestamp:Date.now(),payload:t};this.diagnostics?.registerDeviceTelemetryEvent(lt(i)),this.event("onDeviceTelemetryEvent").raise(i)}scrubPayload(e,t){return"devices_changed"===e?{devices:rt(t.devices).map((e=>pm(e,this.configProvider.config.devices.piiSafeWords))),debug:t.debug}:t}async onStreamStarted(e,t){if(this.permissionManager.browserPermittedModalities.audio.some((e=>e===Qe.MEDIA_STATE.send))||this.permissionManager.browserPermittedModalities.video.some((e=>e===Qe.MEDIA_STATE.send)))try{await iA.enumerateDevices()}catch(e){this.logger.safe.warn(`onStreamStarted device enumeration failed: ${Be(e)}`)}if(e.rawTrack){switch(e.mediaType){case"Audio":this.deviceEnumerator.startDevicePolling(),this.updateActiveMicrophone(e,t);break;case"Video":this.deviceEnumerator.startDevicePolling()}this.configProvider.config.useRawMediaApiForVideoEffects&&e.getCurrentConstraints().withEffect&&(this.activeVideoEffectSub=this.effectsManager.on("onVideoStreamQualityChanged",((t,i,n)=>e.onVideoStreamQualityChanged(t,i,n))))}else this.logger.safe.warn(`stream:${e.id} is already disposed`)}updateActiveMicrophone(e,t){if(e.deviceId){const i=this.deviceList.find((t=>t.deviceId===e.deviceId));if(!i&&"default"!==e.deviceId)return void this.logger.safe.error("Active device not found",`Device id from track: '${Ae(e.deviceId)}', known devices: [${this.deviceList.map((e=>JSON.stringify(pm(e,this.configProvider.config.devices.piiSafeWords))))}]}`,JSON.stringify(gm(t)));i&&"default"!==e.deviceId&&t.audio&&t.audio.deviceId===Qe.MEDIA_DEVICE.defaultId&&iA.list.updateActiveMicrophone(i)}}onStreamDisposing(e){this.unsubscribeFromStreamEvents(e)}onStreamMuted(e,t){("Audio"===e.mediaType||this.configProvider.config.raiseVideoMuteUfd)&&this.ufdManager.signalDeviceEvent(2,t?"Bad":"Good",e.mediaType,this.id),"Audio"===e.mediaType&&this.event("onAudioStreamMuted").raise(t),this.raiseTelemetryEvent(t?"stream_muted":"stream_unmuted",e.mediaType)}onStreamEnded(e,t){t.error?(this.raiseTelemetryEvent("stream_ended_error",{mediaType:e.mediaType,error:{type:t.error.name,detail:t.error.message}}),"SourceUnavailableError"===t.error.name&&this.ufdManager.signalDeviceEvent(0,"Bad","Audio",this.id)):("Audio"!==e.mediaType&&"Video"!==e.mediaType||this.ufdManager.signalDeviceEvent(0,"Bad",e.mediaType,this.id),this.raiseTelemetryEvent("stream_ended",e.mediaType))}onStreamError(e,t){this.raiseTelemetryEvent("stream_error",{mediaType:e.mediaType,error:t})}onAllStreamsRemoved(){this.deviceEnumerator.stopDevicePolling(),this.audioSharingRequested=!1}onStreamAcquired(e,t,i,n,r,a){0!==i&&this.raiseTelemetryEvent("stream_acquired",{id:e,mediaType:t,timestamp:i,resolution:n,withAudio:r,source:a})}onStreamCreated(e,t){this.raiseTelemetryEvent("stream_created",{id:e,mediaType:t})}onMasterStreamDisposing(e,t){this.raiseTelemetryEvent("stream_disposed",{id:e,mediaType:t})}onRendererDisposed(e){nt(this.activeRenderers,(t=>t===e)),this.domOverrides.onMediaElementRemoved?.(e.getVideoElement()),this.unsubscribeFromRendererEvents(e)}onRendererStarted(e){this.activeRenderers.push(e),this.event("onLocalRendererStarted").raise(e)}getLargestRendererResolution(){const e=this.activeRenderers.map((e=>e.getResolution()));return e?.length>0?e.reduce(((e,t)=>t.height>e.height?t:e)):{width:0,height:0}}onVideoEffectsQualityEventHandler(e){const t=this.deviceSelection.selectedDevices.camera;if(t?.deviceId){const i={type:"onVideoEffectQualityChanged",payload:{message:e.message,effectType:e.effectType}};this.event("onVideoEffectsEvent").raise(t.deviceId,i)}}onRendererSizeChanged(){const e=this.getLargestRendererResolution();this.effectsManager.resetOutputConstraints("Video",e,mh.EffectQualityChangeReason.RendererSize)}getDeviceType(e){if("Video"===e)return"camera";if("Audio"===e)return"microphone";throw new Error(`DeviceType for mediaType: ${e} doesn't exist`)}getStreamHandlerByType(e){return"Video"===e?()=>this.getVideoStream(!1,"rawStream",!0):"Audio"===e?()=>this.getAudioStream(!1,"rawStream",!0):"ScreenShare"===e?()=>Promise.resolve(this.getDisplayStream("rawStream",!0)):null}},yA=class{constructor(e){this.configProvider=e,this.data={deviceList:[],deviceSelectionChangeCount:0,deviceSelectionChangeCountFromInterface:0,permissionStates:{microphone:"unknown",camera:"unknown"},devicesCount:{microphone:0,camera:0,speaker:0,compositeAudio:0,audioIngestDevice:0,virtualDevice:0},devicesChangeCount:0,devicesPollChangeCount:0,deviceTelemetryEvents:[],videoEffectsEvents:[],audioEffectsEvents:[]},Object.defineProperty(this.data,"rawUsedDevices",{get:()=>this.rawUsedDevices,configurable:!1,enumerable:!1})}set permissionStates(e){this.data.permissionStates=e}setSelectedDevices(e,t){const i={microphone:_t(e.microphone?.label,this.configProvider.config.devices.piiSafeWords),camera:_t(e.camera?.label,this.configProvider.config.devices.piiSafeWords),speaker:_t(e.speaker?.label,this.configProvider.config.devices.piiSafeWords)};this.rawUsedDevices={microphone:e.microphone?.label,camera:e.camera?.label,speaker:e.speaker?.label},this.data.usedDevices&&(this.data.deviceSelectionChangeCount++,t&&this.data.deviceSelectionChangeCountFromInterface++),this.data.usedDevices=i}setDeviceList(e,t,i){this.data.deviceList=e.map((e=>({label:_t(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.type}))),i&&(this.data.deviceDebugStrings=lt(i)),this.data.devicesCount.microphone=e.filter((e=>"microphone"===e.type)).length,this.data.devicesCount.camera=e.filter((e=>"camera"===e.type)).length,this.data.devicesCount.speaker=e.filter((e=>"speaker"===e.type)).length,this.data.devicesCount.compositeAudio=e.filter((e=>"compositeAudio"===e.type)).length,this.data.devicesChangeCount++,t&&this.data.devicesPollChangeCount++}registerDeviceTelemetryEvent(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.data.latestCameraOpenResolution=t.resolution)}Tt(this.data.deviceTelemetryEvents,e,this.configProvider.config.diagnostics.collectionLimits.numDeviceEvents)}registerVideoEffectsEvent(e){Tt(this.data.videoEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numVideoEffectsEvents)}registerAudioEffectsEvent(e){Tt(this.data.audioEffectsEvents,e,this.configProvider.config.diagnostics.collectionLimits.numAudioEffectsEvents)}getObjectRef(){return this.data}},CA=class{constructor(){this.data={clientDSH:void 0,signalingDSH:void 0,serverDSH:void 0,activeStrategy:void 0,lastMsgOrigin:void 0}}setCurrentActiveStrategy(e){this.data.activeStrategy=e}resetState(){return this.data.lastMsgOrigin=void 0,this}recordHistoryEvent(e,t){var i,n;(i=this.data)[n=t+"DSH"]??(i[n]={count:0,duplicateCount:0}),this.data.lastMsgOrigin=t;const r=this.data[t+"DSH"];r.count++,r.firstMsgTime??(r.firstMsgTime=Date.now()),ut(this.data.lastHistory,e)&&r.duplicateCount++,this.data.lastHistory=e,this.data.lastMsgDate=Date.now()}getObjectRef(){return this.data}},_A=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,this.data={video:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},sharing:{events:[],counters:{attempted:0,subscribed:0,unsubscribed:0,failed:0}},subscribedTrackIds:[]}}set subscribedTrackIds(e){this.data.subscribedTrackIds=e}addSubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:1,msi:t,localMsi:i,ts:Date.now()};Tt(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.attempted++}}addSubscribed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:2,msi:t,localMsi:i,ts:Date.now(),duration:n};Tt(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.subscribed++}}addUnsubscribe(e,t,i){const n=this.getModalityData(e);if(n){const e={evt:3,msi:t,localMsi:i,ts:Date.now()};Tt(n.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),n.counters.unsubscribed++}}addFailed(e,t,i,n){const r=this.getModalityData(e);if(r){const e={evt:-1,msi:t,localMsi:i,ts:Date.now(),error:n};Tt(r.events,e,this.configProvider.config.diagnostics.collectionLimits.numSubscriptionEvents),r.counters.failed++}}getObjectRef(){return this.data}getModalityData(e){switch(e){case Qe.MEDIA_TYPE.video:return this.data.video;case Qe.MEDIA_TYPE.sharing:return this.data.sharing;default:return void this.addStatsError(`Unsupported modality ${e}`)}}},EA=class{constructor(e,t){this.configProvider=e,this.addStatsError=t,this.data={videoMaxCapabilitiesEvents:[],videoMaxCapabilitiesErrors:[],sharingMaxCapabilitiesEvents:[],sharingMaxCapabilitiesErrors:[],currentVideoSsrcRequestedCapabilities:{},currentVideoSsrcAppliedCapabilities:{},currentSharingSsrcRequestedCapabilities:{},currentSharingSsrcAppliedCapabilities:{},numVideoControlMessages:0,numOutOfOrderVideoControlMessages:0,numWebcamFreezeIntervals:0,numProcessedStreamFreezeIntervals:0}}onMaxCapabilitiesRequested(e){const t={causeId:e.causeId,events:[{eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled}]};try{if(e.modality===Qe.MODALITY.video){Tt(this.data.videoMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested);for(const t of e.capabilities)this.data.currentVideoSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}else if(e.modality===Qe.MODALITY.sharing){Tt(this.data.sharingMaxCapabilitiesEvents,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesRequested);for(const t of e.capabilities)this.data.currentSharingSsrcRequestedCapabilities[`${t.ssrc??0}`]=t}}catch(e){this.addStatsError?.("onMaxCapabilitiesRequested",Be(e))}}onMaxCapabilitiesApplied(e){try{const t=this.getEventForCause(e.modality,e.causeId),i={eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:`${e.error}`||"none"};if(t&&(Tt(t.events,i,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1),e.error&&(e.modality===Qe.MODALITY.video?Tt(this.data.videoMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1):e.modality===Qe.MODALITY.sharing&&Tt(this.data.sharingMaxCapabilitiesErrors,t,this.configProvider.config.diagnostics.collectionLimits.numCapabilitiesApplied,1))),e.modality===Qe.MODALITY.video)for(const t of e.capabilities)this.data.currentVideoSsrcAppliedCapabilities[`${t.ssrc??0}`]=t;else if(e.modality===Qe.MODALITY.sharing)for(const t of e.capabilities)this.data.currentSharingSsrcAppliedCapabilities[`${t.ssrc??0}`]=t}catch(e){this.addStatsError?.("onMaxCapabilitiesApplied",Be(e))}}addVideoControlMessage(e=!1){this.data.numVideoControlMessages++,e&&this.data.numOutOfOrderVideoControlMessages++}getObjectRef(){return this.data}registerWebcamFreeze(){this.data.numWebcamFreezeIntervals++}registerProcessedStreamFreeze(){this.data.numProcessedStreamFreezeIntervals++}getEventForCause(e,t){return(e===Qe.MODALITY.video?this.data.videoMaxCapabilitiesEvents:this.data.sharingMaxCapabilitiesEvents).find((e=>e.causeId===t))}},TA=class{constructor(e){this.configProvider=e,this.data={renderers:[],firstTimeToFirstFrameVideo:-1,firstTimeToFirstFrameSharing:-1,timeToFirstFrameSinceSubscriptionStartVideo:-1,timeToFirstFrameSinceSubscriptionStartSharing:-1,isRenderingEvents:{video:[],sharing:[]},preferredResolution:{video:void 0,sharing:void 0}}}setTimeToFirstFrame(e,t){-1!==e&&(t===Qe.MODALITY.video&&-1===this.data.firstTimeToFirstFrameVideo?this.data.firstTimeToFirstFrameVideo=e:t===Qe.MODALITY.sharing&&-1===this.data.firstTimeToFirstFrameSharing&&(this.data.firstTimeToFirstFrameSharing=e))}setTimeToFirstFrameSinceSubscriptionStart(e,t){-1!==e&&(t===Qe.MODALITY.video&&-1===this.data.timeToFirstFrameSinceSubscriptionStartVideo?this.data.timeToFirstFrameSinceSubscriptionStartVideo=e:t===Qe.MODALITY.sharing&&-1===this.data.timeToFirstFrameSinceSubscriptionStartSharing&&(this.data.timeToFirstFrameSinceSubscriptionStartSharing=e))}setIsRendering(e,t){this.data.isRenderingEvents[t]&&Tt(this.data.isRenderingEvents[t],{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents)}setPreferredResolution(e,t){(e.width||e.height)&&(this.data.preferredResolution[t]=e)}newRendererDiagnostics(){const e=new bA(this,this.configProvider),t=e.on("onDisposed",(()=>{this.removeDeadRenderers(),t.dispose()}));return this.data.renderers.push(e.getObjectRef()),e}getObjectRef(){return this.data}removeDeadRenderers(){this.data.renderers=this.data.renderers.filter((e=>e.alive))}},bA=class extends qe{constructor(e,t){super(),this.managerDiagnostics=e,this.configProvider=t,this.isAlive=!0,this.data={alive:!0,totalFreezeDuration:0,isRendering:!1,timeToFirstFrame:-1,timeToFirstFrameSinceSubscriptionStart:-1,rendererStates:[]},delete this.data.alive,Object.defineProperty(this.data,"alive",{get:()=>this.isAlive,enumerable:!1,configurable:!1})}set trackId(e){this.data.trackId=e}set rendererSize(e){this.data.rendererSize=e,e.toString=()=>`${e.width}x${e.height}`,this.managerDiagnostics.setPreferredResolution(e,this.data.modality)}set msi(e){this.data.msi=e}set modality(e){this.data.modality=e}set isRendering(e){this.data.isRendering=e,this.managerDiagnostics.setIsRendering(e,this.data.modality)}set timeToFirstFrame(e){this.data.timeToFirstFrame=e,this.managerDiagnostics.setTimeToFirstFrame(e,this.data.modality)}set timeToFirstFrameSinceSubscriptionStart(e){this.data.timeToFirstFrameSinceSubscriptionStart=e,this.managerDiagnostics.setTimeToFirstFrameSinceSubscriptionStart(e,this.data.modality)}addFreezeDuration(e){this.data.totalFreezeDuration+=e}addStateChange(e){Tt(this.data.rendererStates,e,this.configProvider.config.diagnostics.telemetryLimits.numRendererStateChangedEvents)}dispose(){this.isAlive=!1,this.event("onDisposed").raise()}getObjectRef(){return this.data}},IA=g,wA=f(ye()),RA=g;function AA(e){let t="";return Ze(e,((e,i)=>{t+=(t?";":"")+i,void 0!==e&&(t+=`=${e}`)})),t}var PA=class{constructor(e){this.parameters={},e&&e.split(";").forEach((e=>{const t=e.split("=");this.parameters[t[0]]=t[1]}))}setIfMissing(e,t){this.contains(e)||(this.parameters[e]=t)}removeIfPresent(e){this.contains(e)&&delete this.parameters[e]}get(e){return this.parameters[e]}names(){return Object.keys(this.parameters)}contains(e){return this.parameters.hasOwnProperty(e)}toString(){return AA(this.parameters)}};function MA(e,t,i){if(!e.rtp)return;const n=e.rtp.filter((e=>e.payload===t))[0];n&&DA(e,{codec:n.codec,rate:n.rate,payload:n.payload,encoding:n.encoding},(e=>(e.rtp.payload=i,e)))}function kA(e){const t=new Set;for(const i of e.media)for(const e of i.rtp??[])t.add(e.payload);const i=[96,127];for(let e=i[0];e<=i[1];e++)if(!t.has(e))return e;const n=[35,64];for(let e=n[0];e<=n[1];e++)if(!t.has(e))return e;return-1}function DA(e,t,i){NA(e,t,!0,i)}function OA(e,t,i){NA(e,t,!1,i)}function NA(e,t,i,n){if(e.rtp){for(let r=0;r<e.rtp.length;r++){const a=e.rtp[r],s=a.payload;if(t.codec.toLowerCase()!==a.codec.toLowerCase()||t.rate!==a.rate||t.encoding!==a.encoding||t.payload&&t.payload!==a.payload)continue;const o={rtp:a};e.fmtp||(e.fmtp=[]);const l=e.fmtp.find((e=>a.payload===e.payload));o.fmtp=l,e.rtcpFb||(e.rtcpFb=[]),o.rtcpFb=e.rtcpFb.filter((e=>e.payload===a.payload));const c=o.rtcpFb.length>0;if(null===n(o))e.payloads=e.payloads.toString().split(" ").filter((e=>a.payload!==+e)).join(" "),e.fmtp=e.fmtp.filter((e=>a.payload!==e.payload)),e.rtcpFb=e.rtcpFb.filter((e=>a.payload!==e.payload)),e.rtp[r]=null;else{if(o.rtp.payload!==s){const t=o.rtp.payload;e.payloads=e.payloads.toString().split(" ").map((e=>+e===s?t:+e)).join(" "),o.fmtp&&(o.fmtp.payload=t),o.rtcpFb&&o.rtcpFb.forEach((e=>e.payload=t)),e.fmtp.filter((e=>e.config&&e.config.indexOf(`apt=${s}`)>-1)).forEach((e=>e.config=e.config.replace(`apt=${s}`,`apt=${t}`)))}!l&&o.fmtp&&e.fmtp.push(o.fmtp),!c&&o.rtcpFb&&o.rtcpFb.forEach((t=>e.rtcpFb.push(t)))}if(i)break}e.rtp=e.rtp.filter((e=>!!e))}}function LA(e,t){if(!e.rtp)return;let i=-1;if(e.rtp.forEach((function(e,n){t.codec.toLowerCase()!==e.codec.toLowerCase()||t.rate!==e.rate||t.encoding!==e.encoding||t.payload&&t.payload!==e.payload||(i=n)})),i>=0&&e.rtp.length>1){const t=e.rtp[i].payload;e.rtp.splice(i,1),e.payloads=e.payloads.split(" ").filter((e=>t!==+e)).join(" "),e.fmtp=e.fmtp?.filter((e=>t!==e.payload))}}function xA(e,t){e.rtp.unshift({payload:t.payload,codec:t.codec,rate:t.rate,encoding:t.encoding}),e.payloads=`${t.payload} ${e.payloads}`}function FA(e,t,i){if(!(0,RA.isUndefined)(e.rate)&&e.rate!==t.rate)return!1;if(!(0,RA.isUndefined)(e.codec)&&e.codec.toLowerCase()!==t.codec.toLowerCase())return!1;if(!(0,RA.isUndefined)(e.encoding)){if(!(0,RA.isUndefined)(t.encoding)&&e.encoding!==t.encoding)return!1;if((0,RA.isUndefined)(t.encoding)&&1!==e.encoding)return!1}return!!(0,RA.isUndefined)(e.fmtpLine)||!(!i||!i.find((i=>i.payload===t.payload&&-1!==i.config.toLowerCase().indexOf(e.fmtpLine.toLowerCase()))))}function UA(e,t){return t===e||"*"===t}function BA(e,t,i,n){if(!e.rtp?.length)return;let r=e.rtp.filter((i=>t.some((t=>FA(t,i,e.fmtp)))));e.type===Qe.MEDIA_TYPE.video&&(r=r.filter((t=>{const i=e.fmtp&&e.fmtp.find((e=>e.payload===t.payload&&e.config.startsWith("apt=")));if(i){const e=+i.config.split(";")[0].split("=")[1];return r.some((t=>t.payload===e))}return!0}))),r.length?(e.rtp=r,i&&(e.rtp=(0,RA.flatten)(t.map((t=>e.rtp.filter((i=>FA(t,i,e.fmtp))))))),e.payloads=e.rtp.map((e=>e.payload)).join(" "),e.fmtp=e.fmtp&&e.fmtp.filter((t=>e.rtp.some((e=>UA(e.payload,t.payload))))),e.rtcpFb=e.rtcpFb&&e.rtcpFb.filter((t=>e.rtp.some((e=>UA(e.payload,t.payload)))))):n&&n.warn("Empty rtp list after filtering")}function VA(e){if(e.label)switch(e.label){case Qe.MEDIA_LABEL.audio:return"Audio";case Qe.MEDIA_LABEL.video:return"Video";case Qe.MEDIA_LABEL.sharing:return"ScreenShare";case Qe.MEDIA_LABEL.data:return"Data"}else switch(e.type){case Qe.MEDIA_TYPE.audio:return"Audio";case Qe.MEDIA_TYPE.video:return"Video";case Qe.MEDIA_TYPE.data:case Qe.MEDIA_TYPE.dataChannel:return"Data"}return null}function HA(e){if(e.label)switch(e.label){case Qe.MEDIA_LABEL.audio:return Qe.MODALITY.audio;case Qe.MEDIA_LABEL.video:return Qe.MODALITY.video;case Qe.MEDIA_LABEL.sharing:return Qe.MODALITY.sharing;case Qe.MEDIA_LABEL.data:return Qe.MODALITY.data}else switch(e.type){case Qe.MEDIA_TYPE.audio:return Qe.MODALITY.audio;case Qe.MEDIA_TYPE.video:return Qe.MODALITY.video;case Qe.MEDIA_TYPE.data:case Qe.MEDIA_TYPE.dataChannel:return Qe.MODALITY.data}return null}function $A(e){switch(e){case Qe.MODALITY.audio:return Qe.MEDIA_LABEL.audio;case Qe.MODALITY.video:return Qe.MEDIA_LABEL.video;case Qe.MODALITY.sharing:return Qe.MEDIA_LABEL.sharing;case Qe.MODALITY.data:return Qe.MEDIA_LABEL.data;default:return null}}function GA(e){return e.media.reduce(((e,t)=>{if(0!==t.port){const i=HA(t);if(!(i in e)){const n=t.direction?t.direction.toLowerCase():Qe.MEDIA_STATE.sendReceive;e[i]=n}}return e}),{})}function jA(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));if(t){const i=t.mids?.toString().split(" ")[0];return e.media.find((e=>{const t="number"==typeof e.mid?e.mid.toString():e.mid;return i===t}))||null}return null}function zA(e){return 0===e.port}function WA(e){let t;return e&&DA(e,{codec:"h264",rate:9e4},(e=>{e.fmtp?.config&&(t=function(e){const t=new PA(e);return{maxFs:+t.get(Qe.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Qe.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Qe.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Qe.VIDEO_CAPABILITIES.MAX_BR_PATH)}}(e.fmtp.config))})),t}function qA(e){const t=e.media.map((e=>parseFloat(e.mid||"0")));for(let e=1;e<=Math.max(...t)+1;e++)if(!t.includes(e))return e.toString();return"-1"}var KA=g;function JA(){const e=[{jsep:"active",msSdp:"tcp-act"},{jsep:"passive",msSdp:"tcp-pass"},{jsep:"so",msSdp:"tcp-so"}];function t(e,t){delete e.generation,delete e["network-id"],delete e["network-cost"],e.transport.match(/tcp/i)&&i(e,t)}function i(t,i){e.some((function(e){if(i){if(e.msSdp===t.transport.toLowerCase())return t.transport="tcp",t.tcptype=e.jsep,!0}else if(t.tcptype&&e.jsep===t.tcptype.toLowerCase())return t.transport=e.msSdp,delete t.tcptype,!0;return!1}))}function n(e,t,i){const n=t.connection||i.connection,r=function(e,t,i){return e.port===i&&e.ip===t};return!!n&&(1===e.component?r(e,n.ip,t.port):!!t.rtcp&&r(e,t.rtcp.ip||n.ip,t.rtcp.port))}this.fromMsSdp=function(e){e.candidates=e.candidates||[],e.xCandidatesIpv6&&(e.xCandidatesIpv6.forEach((function(t){e.candidates.push(t)})),delete e.xCandidatesIpv6),e.candidates.forEach((function(e){t(e,!0)}))},this.toMsSdp=function(e,i){e.candidates=e.candidates||[],e.candidates.sort((function(t,r){return t.foundation!==r.foundation?t.foundation-r.foundation:t.component!==r.component?t.component-r.component:+n(r,e,i)-+n(t,e,i)})),e.candidates=e.candidates.filter((function(i,n){t(i,!1);const r=e.candidates[n-1];return!r||r.component!==i.component||r.foundation!==i.foundation})),function(e,t){if(e.port&&!e.candidates.length){const i=jA(t);i&&(e.port=i.port,e.connection=i.connection)}}(e,i)}}var YA=()=>new JA,QA=class{toMsSdp(e,t){"offer"===t?e.rtcp&&(e.rtcp={port:e.port}):delete e.rtcp}},ZA=()=>new QA,XA={STREAM_ID:{audio:"mainAudio",video:"mainVideo",sharing:"applicationsharingVideo"},STREAM_ID_DELIMITER:"-"},eP=[{label:Qe.MEDIA_LABEL.audio,id:XA.STREAM_ID.audio},{label:Qe.MEDIA_LABEL.video,id:XA.STREAM_ID.video},{label:Qe.MEDIA_LABEL.sharing,id:XA.STREAM_ID.sharing}].reduce(((e,t)=>(e[t.label]=t.id,e)),{}),tP=dt(),iP=class{constructor(e){this.configuration=e}fromMsSdp(e){if(0===e.port)return;if(!this.isRecvOnly(e)||this.configuration.unifiedPlanEnabled){if(e.msid){e.ssrcs&&1===e.ssrcs.length&&(this.addStream(e,e.ssrcs[0].id,e.ssrcs[0].value,e.msid),e.ssrcs.shift());const t=e.msid.split(" ");(this.configuration.addPrefixForMsid||"-"===t[0])&&(e.msid=this.getMsidValue(t[0],t[1]||t[0],e.label))}if(e.ssrcs)this.updateMsids(e.ssrcs,((t,i)=>this.configuration.addPrefixForMsid||"-"===t?this.getMsidValue(t,i,e.label):`${t} ${i}`));else{const t=this.getFlowSsrcs(e);t.length>0?t.forEach((i=>{this.addStream(e,i,tP,this.getMsidValue(t[0],t[0],e.label))})):e.xSsrcRange&&this.addStream(e,e.xSsrcRange.ssrcMin,tP,this.getMsidValue(e.xSsrcRange.ssrcMin,e.xSsrcRange.ssrcMin,e.label))}}delete e.xSsrcRange}toMsSdp(e,t){if(0===e.port)return;let i;e.ssrcs?.[0]&&(i=e.ssrcs[0].id),void 0!==i&&(e.xMultiStream||(e.xSsrcRange={ssrcMin:i,ssrcMax:i+t}))}getFlowSsrcs(e){if(e.ssrcGroups&&e.type===Qe.MEDIA_TYPE.video){let t;if(e.ssrcGroups.some((e=>"FID"===e.semantics&&(t=e,!0))),t)return t.ssrcs.split(" ").map((e=>+e))}return[]}addStream(e,t,i,n){e.ssrcs=e.ssrcs||[],e.ssrcs.push({attribute:"cname",id:t,value:i}),e.ssrcs.push({attribute:"msid",id:t,value:n})}updateMsids(e,t){e.filter((e=>"msid"===e.attribute)).forEach((e=>{const i=e.value.split(" ");e.value=t(i[0],i[1]||i[0])}))}getMsidValue(e,t,i){const n=this.getMsidPrefix(i);return n+e+" "+n+t}getMsidPrefix(e){return eP[e]?eP[e]+XA.STREAM_ID_DELIMITER:""}isRecvOnly(e){return"recvonly"===e.direction}},nP={audio:"main-audio",video:"main-video"},rP=class{constructor(e,t){this.context=e,this.mediaManager=t,this.logger=this.context.logger,this.candidateTransform=YA(),this.streamTransform=new iP(this.context.configuration),this.rtcpTransform=ZA()}toMsSdp(e,t){return e.msidSemantic={semantic:"WMS",token:"*"},e.media.forEach(((i,n)=>{if(i.protocol=Qe.PROFILES.rtpSavp,i.label=i.label||this.getLabel(i.type),zA(i)){for(const e in i)i.hasOwnProperty(e)&&["type","port","protocol","payloads"].indexOf(e)<0&&delete i[e];i.payloads="34"}const r=this.getSsrcRangeForIndex(i.direction,n);this.streamTransform.toMsSdp(i,r),i.crypto&&i.crypto.forEach((function(e){e.config+="|2^31"})),0!==i.port&&e.fingerprint&&(i.fingerprint=e.fingerprint),this.candidateTransform.toMsSdp(i,e),this.rtcpTransform.toMsSdp(i,t),i.invalid&&(this.logger.unsafe.error(`Unknown SDP attributes! ${JSON.stringify(i.invalid)}`),delete i.invalid),this.transformExtensions(i,!1),0!==i.port&&(i.type===Qe.MEDIA_TYPE.audio&&this.context.configProvider.config.webrtcAudioChannelSignalingFeedback?i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcAudioChannelSignalingFeedback}:i.type===Qe.MEDIA_TYPE.video&&this.context.configProvider.config.webrtcVideoChannelSignalingFeedback&&(i.signalingFbXMessage={payload:"*",param:this.context.configProvider.config.webrtcVideoChannelSignalingFeedback}))})),delete e.fingerprint,e}fromMsSdp(e,t){for(let i=e.media.length-1;i>=0;--i){const n=e.media[i];if((n.ssrcs&&n.ssrcs[0]||n.xSsrcRange)&&(e.msidSemantic={semantic:"WMS",token:"*"}),zA(n))n.direction||(n.direction="inactive");else{if(this.streamTransform.fromMsSdp(n),delete n.cryptoscale,n.fingerprint&&(!this.isOffer(t)||this.context.configProvider.config.disableIncomingDtlsRoleOverride&&n.setup||(n.setup="actpass")),n.crypto)for(let e=n.crypto.length-1;e>=0;--e){const t=n.crypto[e];t.config.match(/.*\|\d+:\d+/)?n.crypto.splice(e,1):t.config=t.config.replace(/(.*)\|2\^\d+/,"$1")}n.remoteCandidates&&(delete n.candidates,delete n.xCandidatesIpv6,delete n.remoteCandidates),this.candidateTransform.fromMsSdp(n),n.rtcpFbXMessage&&delete n.rtcpFbXMessage,n.invalid&&this.logger.unsafe.info(`Unknown SDP attributes! ${JSON.stringify(n.invalid)}`),this.transformExtensions(n,!0)}}return e}transformExtensions(e,t){const i=[{name:Qe.ABS_SEND_TIME.EXT_URI,encoded:Qe.ABS_SEND_TIME.MSSDP_ENCODED_URI},{name:Qe.TRANSPORT_CC.EXT_URI,encoded:Qe.TRANSPORT_CC.MSSDP_ENCODED_URI}];e.ext&&e.ext.forEach((function(e){i.some((function(i){const n=t?i.encoded:i.name,r=t?i.name:i.encoded;return n===e.uri&&(e.uri=r,!0)}))}))}isOffer(e){return"offer"===e}getLabel(e){return nP.hasOwnProperty(e)&&nP[e]||"undefined"}getSsrcRangeForIndex(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();return Wg(e)&&n?n.getSsrcRange():0}},aP=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new rP(this.context,this.mediaManager)}modify(e){this.msSdpT.toMsSdp(e,this.sessionType)}},sP=class{constructor(e,t,i){this.context=e,this.mediaManager=t,this.sessionType=i,this.msSdpT=new rP(this.context,this.mediaManager)}modify(e){this.msSdpT.fromMsSdp(e,this.sessionType)}},oP=class{constructor(e){this.context=e}modify(e){const t=mm(this.context),i=tm(e),n=e.media.find((e=>!!e.crypto));e.media.forEach((e=>{e.type!==Qe.MEDIA_TYPE.dataChannel&&(!t&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!i.dtls||i.sdes&&t?Qe.PROFILES.rtpSavpf:Qe.PROFILES.udpTlsRtpSavpf,zA(e)&&e.protocol===Qe.PROFILES.rtpSavpf&&n&&(e.crypto=n.crypto))}))}},lP=class{constructor(e,t,i){this.mediaManager=e,this.isOffer=t,this.configProvider=i}modify(e){e.media.forEach(((e,t)=>{const i=e.setup,n=this.mediaManager.getMediaEntities()[t],r=n.getExtension("setup");i&&n.isEnabled()&&("actpass"!==i?n.setExtension("setup",i):this.isOffer&&void 0!==r&&"actpass"!==r&&!this.configProvider.config.disableOutgoingDtlsRoleOverride&&(e.setup=r))}))}},cP=class{constructor(e,t){this.mediaManager=e,this.modalities=t}modify(e){let t=0;e.media.forEach(((e,i)=>{const n=parseInt(e.mid,10);!isNaN(n)&&n>=t&&(t=n+1)})),e.media.forEach(((i,n)=>{const r=this.mediaManager.getMediaEntities()[n];if(zA(i)||r.isDisabled()||!(r.getModality()in this.modalities)){const a=r.getExtension("midApplied")?void 0:i.mid||""+t++;0===n?i.direction=Qe.MEDIA_STATE.inactive:e.media[n]=gM(i.type,void 0,i.protocol,a)}}))}},dP=class{constructor(e,t){this.mediaManager=e,this.remote=t}modify(e){const t=this.mediaManager.getMediaEntities();for(let i=0;i<t.length;i++){const n=t[i],r=e.media[i];if(n.getExtension("rollback"))if(r&&!this.remote)e.media[i]=null;else if(!r&&this.remote){const t=n.getType()===Qe.MEDIA_TYPE.data?Qe.MEDIA_TYPE.dataChannel:n.getType(),i=t===Qe.MEDIA_TYPE.dataChannel?Qe.PROFILES.udpDtlsSctp:Qe.PROFILES.udpTlsRtpSavpf;e.media.push(gM(t,void 0,i,void 0))}}e.media=e.media.filter((e=>e))}},uP=class{constructor(e){this.mediaManager=e}modify(e){this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];t.getModality()!==Qe.MODALITY.data||n&&n.type===Qe.MEDIA_TYPE.dataChannel||e.media.splice(i,0,gM(Qe.MEDIA_TYPE.data,Qe.MEDIA_LABEL.data,Qe.PROFILES.rtpSavp,void 0))}))}},hP=class{constructor(e,t){this.context=e,this.direction=t}modify(e){e.media.forEach((e=>{e.type===Qe.MEDIA_TYPE.dataChannel&&(e.type=Qe.MEDIA_TYPE.data,e.payloads=Qe.PAYLOAD_TYPE.X_DATA)})),vm(this.context)&&mM(e,Qe.MEDIA_TYPE.data).forEach((t=>{t.rtp=t.rtp||[],t.fmtp=t.fmtp||[],t.rtp.push({codec:"x-data",payload:127,rate:9e4}),t.rtp.push({codec:"rtx",payload:126,rate:9e4}),t.fmtp.push({payload:126,config:"apt=127"});const i=this.getNonOverlappingSsrc(e);t.xSsrcRange={ssrcMin:i,ssrcMax:i},t.rtcpMux="rtcp-mux",t.xDataProtocol="sctp",t.direction=this.direction}))}getNonOverlappingSsrc(e){let t,i=!0;do{t=Math.floor(4294967293*Math.random())+2,mM(e).forEach((e=>{e?.ssrcs?.[0]?.id===t&&(i=!1)}))}while(!i);return t}},pP=class{constructor(e){this.configProvider=e,this.uri="urn:3gpp:video-orientation",this.value=13}modify(e){if(this.configProvider.config.enableVideoOrientationExtension)for(const t of mM(e,Qe.MEDIA_TYPE.video))this.modifyMedia(t)}},gP=class extends pP{modifyMedia(e){e.ext??(e.ext=[]),e.ext.some((e=>e.uri===this.uri))||e.ext.push({value:this.getAvailableValue(e.ext),uri:this.uri})}getAvailableValue(e){const t=e.map((e=>e.value));return t.includes(this.value)?Math.max(...t)+1:this.value}},mP=class extends pP{modifyMedia(e){e.ext=e.ext?.filter((e=>e.uri!==this.uri))}},fP=class{constructor(e){this.context=e}modify(e){const t=e.groups?.find((e=>"BUNDLE"===e.type));for(let i=e.media.length-1;i>=0;i--){const n=e.media[i];if(n.type===Qe.MEDIA_TYPE.data){const r=this.context.configProvider.config.rejectUnbundledDataModality&&!this.context.configProvider.mediaConfig.isTransportUnbundled&&!t?.mids?.toString().includes(n.mid),a=vm(this.context);a||this.context.configProvider.config.acceptDisabledDataModality?(n.port=a&&!r?n.port:0,n.payloads=Qe.PAYLOAD_TYPE.DATA_CHANNEL,n.type=Qe.MEDIA_TYPE.dataChannel,n.protocol=Qe.PROFILES.udpDtlsSctp,n.sctpPort??(n.sctpPort=this.context.configProvider.config.sctpPort),delete n.xDataProtocol,delete n.rtp,delete n.fmtp,delete n.rtcp,delete n.rtcpMux,delete n.ext,delete n.ssrcs,delete n.ssrcGroups,delete n.xSsrcRange):e.media.splice(i,1)}}}},vP=class{constructor(e,t){this.modalities=e,this.mediaManager=t}modify(e){mM(e).forEach((e=>{const t=HA(e),i=this.mediaManager.getMediaEntityByMid(e.mid);!(this.modalities[t]!==Qe.MEDIA_STATE.send||i.getExtension("reinviteless")||e.direction&&e.direction.toLowerCase()===Qe.MEDIA_STATE.receive)&&(e.direction=Qe.MEDIA_STATE.receive)}))}},SP=class{constructor(e,t){this.isMultiparty=e,this.cname=t}modify(e){this.isMultiparty&&mM(e).forEach((e=>{const t=e.direction;t!==Qe.MEDIA_STATE.receive&&t!==Qe.MEDIA_STATE.inactive||(e.ssrcs&&e.ssrcs[0]?e.ssrcs=[{id:e.ssrcs[0].id,attribute:"cname",value:this.cname}]:e.type===Qe.MEDIA_TYPE.audio?e.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:e.type===Qe.MEDIA_TYPE.video&&(e.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}))}},yP=class{modify(e){const t=new Set;mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{e.ssrcs&&e.ssrcs.length>1&&t.add(e.ssrcs[0].id)}));const i=mM(e,Qe.MEDIA_TYPE.video).find((e=>e.direction===Qe.MEDIA_STATE.sendReceive||e.direction===Qe.MEDIA_STATE.send));mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{const n=e.direction;if((n===Qe.MEDIA_STATE.receive||n===Qe.MEDIA_STATE.inactive)&&e.ssrcs&&1===e.ssrcs.length){const n=e.ssrcs[0].id;(1===n||i&&i.ssrcs[0].id===n||!i&&t.has(n))&&(delete e.ssrcs,delete e.ssrcGroups)}}))}},CP=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t];e.label=$A(i.getModality())}))}},_P=class{modify(e){e.media.forEach((e=>{delete e.label}))}},EP=class{constructor(e,t,i){this.mediaManager=e,this.modalities=t,this.configProvider=i}modify(e){let t=this.configProvider.mediaConfig.maxBandwidthInKbps;const i=e.bandwidth?.find((e=>"CT"===e.type));i&&(!t||t>i.limit)&&(t=i.limit);const n=this.configProvider.config.audioBandwidthInKbps||0,r=Math.max(t-n,0),a=this.configProvider.config.videoBandwidthAllocation&&Wg(this.modalities.video)&&Wg(this.modalities.sharing);mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{if(delete e.bandwidth,r){let t=r;if(a){const i=this.mediaManager.getMediaEntityByMid(e.mid).getModality()===Qe.MODALITY.video?this.configProvider.config.videoBandwidthAllocation:1-this.configProvider.config.videoBandwidthAllocation;t=Math.round(r*i)}e.bandwidth=[{limit:t,type:"AS"}]}}))}},TP=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.mediaConfig.maxBandwidthInKbps;t&&(e.bandwidth=[{limit:t,type:"CT"}])}},bP=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i.getExtension("iceUfrag");i.setExtension("iceRestart",!!e.iceUfrag&&!!n&&n!==e.iceUfrag),i.setExtension("iceUfrag",e.iceUfrag)}))}},IP=class{modify(e){const t=new Set(["urn:ietf:params:rtp-hdrext:csrc-audio-level","http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]);mM(e).forEach((e=>{e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}))}},wP=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed&&(e.extmapAllowMixed="extmap-allow-mixed")}},RP=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.extmapAllowMixed||delete e.extmapAllowMixed}},AP=class{modify(e){mM(e).forEach((e=>{delete e.signalingFbXMessage}))}},PP=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){if(!this.configProvider.config.isAv1Allowed)return;const t=function(e,t){const i=new Set,n=[];for(const t of e.media)for(const e of t.rtp??[])i.add(e.payload);for(let e=t[0];e<=t[1];e++)i.has(e)||n.push(e);return n}(e,[96,127]);this.mediaManager.getMediaEntities().forEach(((i,n)=>{if(i.getModality()===Qe.MODALITY.audio)return;const r=e.media[n];let a=0;OA(r,{codec:"AV1",rate:9e4},(e=>{e.rtp.payload<96&&(e.rtp.payload=t[a]??e.rtp.payload,a++)}))}))}},MP=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new DP(this.mediaManager,this.configProvider,this.sdpType,!1)}modify(e){this.configProvider.config.filterCodecsInSdpV2||this.baseModifier.modify(e)}},kP=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.baseModifier=new DP(this.mediaManager,this.configProvider,this.sdpType,!0)}modify(e){this.configProvider.config.filterCodecsInSdpV2&&this.baseModifier.modify(e)}},DP=class{constructor(e,t,i,n=!1){this.mediaManager=e,this.configProvider=t,this.sdpType=i,this.alwaysReorder=n}modify(e){this.configProvider.config.filterCodecsInSdp&&"offer"===this.sdpType&&this.mediaManager.getMediaEntities().forEach(((t,i)=>{const n=e.media[i];if(!n)return;const r=Sm(this.configProvider,n.type);r.length&&BA(n,_m(r),!!t.getExtension("unnegotiatedModality")||this.alwaysReorder,null)}))}},OP=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;t&&i&&(i.codec!==i.lastUsedCodec&&"None"!==i.lastUsedCodec&&this.removeSubstitutionCodecIfNeeded(t,i.lastUsedCodec),i.enabledLocally&&!i.disabledRemotely&&this.addSubstitutionCodecIfNeeded(t,i.codec,e))}addSubstitutionCodecIfNeeded(e,t,i){if(this.isSubstitutionCodecAdded(e,t))return;const n=kA(i);if(-1===n)return;const r=vM(t,"SUBSTITUTION");SM(i,r.payload,n),xA(e,r)}removeSubstitutionCodecIfNeeded(e,t){LA(e,vM(t,"SUBSTITUTION"))}isSubstitutionCodecAdded(e,t){let i=!1;return DA(e,vM(t,"SUBSTITUTION"),(()=>{i=!0})),i}},NP=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;if(t&&i&&i.enabledLocally&&!i.disabledRemotely){const e=vM(i.codec,"SUBSTITUTION"),n=vM(i.codec,"CODEC");DA(t,e,(e=>{e.rtp.codec=n.codec,e.rtp.rate=n.rate,e.rtp.encoding=n.encoding}))}}},LP=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;if(!t||!i?.enabledLocally)return;const n=vM(i.codec,"CODEC"),r=vM(i.codec,"SUBSTITUTION");let a=!1;DA(t,n,(e=>{i.enabledForSend&&(e.rtp.codec=r.codec,e.rtp.rate=r.rate,e.rtp.encoding=r.encoding,e.fmtp={payload:n.payload,config:"ptime=20"}),a=!0})),i.disabledRemotely=!a}},xP=class{modify(e){LA(e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),{codec:"CN",rate:16e3})}},FP=class{constructor(e){this.configProvider=e}modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=this.configProvider.mediaConfig.audioCodecContext;if(!t||!i?.enabledLocally||i.disabledRemotely)return;let n=!1;const r={codec:"CN",rate:48e3};if(DA(t,r,(()=>{n=!0})),n)return;const a=kA(e);-1!==a&&(SM(e,Qe.PAYLOAD_TYPE.MSRTC_CNFB,a),r.payload=Qe.PAYLOAD_TYPE.MSRTC_CNFB,xA(t,r))}},UP=class{modify(e){LA(e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),{codec:"g722",rate:8e3,encoding:2})}},BP=class{constructor(e){this.configProvider=e}modify(e){const t=this.configProvider.config.enforceOpusFmtp;t&&DA(e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),{codec:"opus",rate:48e3,encoding:2},(e=>{e.fmtp||(e.fmtp={payload:e.rtp.payload});const i=new PA(e.fmtp.config);Object.keys(t).forEach((e=>{i.removeIfPresent(e),i.setIfMissing(e,`${t[e]}`)})),e.fmtp.config=i.toString()}))}},VP=class{modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio));if(t&&zA(t)){const i=e.media.find((e=>!!e.iceUfrag));i&&(t.port=9,t.direction="inactive",t.iceUfrag=i.iceUfrag,t.icePwd=i.icePwd,t.rtcpMux="rtcp-mux",i.crypto&&(t.crypto=i.crypto),i.fingerprint&&(t.fingerprint=i.fingerprint,t.setup=i.setup),t.rtp=[{payload:0,codec:"PCMU",rate:8e3}],t.payloads="0")}}},HP=class{constructor(e){this.otherPartyCodecs=e}modify(e){const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=["cn","telephone-event"],n=t.rtp.filter((e=>-1!==this.otherPartyCodecs.indexOf(e.codec.toLowerCase())&&-1===i.indexOf(e.codec.toLowerCase())));if(0===n.length)throw new Error("there is no matching primary audio codec");t.rtp.filter((e=>e!==n[0]&&-1===i.indexOf(e.codec.toLowerCase()))).forEach((e=>{LA(t,e)}))}},$P=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){this.configProvider.config.webrtcInjectTransportCCAudio&&mM(e,Qe.MEDIA_TYPE.audio).forEach((e=>{const t=e.ext?.find((e=>e.uri===Qe.TRANSPORT_CC.EXT_URI));if(!t)return void this.logger.safe.info("transport-cc ext not present in sdp, skipping injecting transport-cc attribute for audio");const i=e.rtp?.find((e=>"opus"===e.codec.toLowerCase()));if(!i)return void this.logger.safe.info("opus codec not found, skipping injecting transport-cc attribute for audio");const n=i.payload,r=e.rtcpFb?.find((e=>e.type===Qe.TRANSPORT_CC.ATTRIBUTE&&e.payload===n));r?this.logger.safe.info("opus codec already has transport-cc attribute"):(e.rtcpFb=e.rtcpFb||[],e.rtcpFb.push({payload:n,type:Qe.TRANSPORT_CC.ATTRIBUTE}),this.logger.safe.info("injected transport-cc attribute"))}))}},GP=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){e.media.forEach(((e,t)=>{if(zA(e)||e.type!==Qe.MEDIA_TYPE.video)return;const i=this.mediaManager.getMediaEntities()[t];DA(e,{codec:"h264",rate:9e4},(e=>{const t=i.getLocalRecvCapabilities();if(!t)return;e.fmtp||(e.fmtp={payload:e.rtp.payload});const n=new PA(e.fmtp.config);this.configProvider.config.h264SdpProfile?(n.removeIfPresent("profile-level-id"),n.setIfMissing("profile-level-id",this.configProvider.config.h264SdpProfile)):n.setIfMissing("profile-level-id","42C02A"),n.setIfMissing("max-fs",t.getMaxFS().toString()),n.setIfMissing("max-mbps",t.getMaxMBPS().toString()),n.setIfMissing("max-fps",t.getMaxFPS().toString()),e.fmtp.config=n.toString()}))}))}},jP=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<this.configProvider.config.nonMultiStreamChannels)return;let t=0;for(let i=0;i<e.media.length;i++)if("video"===e.media[i].type){if(e.media[i].xMultiStream)break;t++}const i=e.media.findIndex((e=>e.xMultiStream)),n=e.media[i];if(!n)return;const r=n.xMultiStream.startSsrc,a=n.xMultiStream.ssrcGroupRange,s=n.xMultiStream.ssrcRange;delete n.xMultiStream;const o=this.configProvider.config.numVideoChannelsGvc-t-1,l=[];for(let t=0;t<o;t++){const o=(0,KA.cloneDeep)(n);o.mid=qA(e),o.xSourceStreamId=n.xSourceStreamId,o.subStreamIndex=t,l.push(o.mid);const c=r+t*s;o.ssrcGroups=[{ssrcs:`${c} ${c+a}`,semantics:"FID"}],o.xSsrcRange={ssrcMin:c,ssrcMax:c+s-1},e.media.splice(i+t,0,o)}const c=r+o*s;n.ssrcGroups=[{ssrcs:`${c} ${c+a}`,semantics:"FID"}],n.xSsrcRange={ssrcMin:c,ssrcMax:c+s-1};const d=e.groups.find((e=>e.mids.includes(n.mid)));d.mids=`${d.mids} ${l.join(" ")}`}},zP=class{constructor(e,t,i){this.mediaManager=e,this.configProvider=t,this.type=i}modify(e){if(!this.configProvider.config.multiStreamSupported||this.configProvider.config.numVideoChannelsGvc<=this.configProvider.config.nonMultiStreamChannels+1)return;const t=this.mediaManager.getMediaEntitiesByModality(Qe.MODALITY.video);let i=-1,n=-1;if(t.forEach(((t,r)=>{const a=e.media.findIndex((e=>e.mid===t.getMid()));r===this.configProvider.config.nonMultiStreamChannels-1&&(n=a),i=a})),-1===i||-1===n)return;const r=e.media[i];e.media.splice(n+1,i-n-1);const a=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;r.xMultiStream={numberOfStreams:a,startSsrc:1,ssrcRange:1,ssrcGroupRange:1},"answer"===this.type&&(r.xMultiStream.numberOfStreams=Math.min(a,this.configProvider.mediaConfig.multiStreamChannelsOffered),r.ssrcGroups&&delete r.ssrcGroups,r.xSsrcRange&&delete r.xSsrcRange)}},WP=class{constructor(e){this.configProvider=e}modify(e){mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{DA(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new PA,i=new PA(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((e=>{if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n=this.configProvider.config.h264SendProfileOverride||n),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}))}},qP=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{OA(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new PA(e.fmtp.config);t.setIfMissing("sps-pps-idr-in-keyframe","1"),e.fmtp.config=t.toString()}}))}))}},KP=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.enableH264SpsPpsIdrKeyframe&&mM(e,Qe.MEDIA_TYPE.video).forEach((e=>{OA(e,{codec:"h264",rate:9e4},(e=>{if(e.fmtp){const t=new PA(e.fmtp.config);t.removeIfPresent("sps-pps-idr-in-keyframe"),e.fmtp.config=t.toString()}}))}))}},JP=class{constructor(e){this.configProvider=e}modify(e){const t=(e.groups||[]).findIndex((e=>"BUNDLE"===e.type)),i=e.groups?e.groups[t]:void 0;i&&(this.configProvider.mediaConfig.isTransportUnbundled?(i.mids=this.createBundleFromMedia(mM(e,Qe.MEDIA_TYPE.video)),i.mids||e.groups.splice(t,1)):i.mids=this.createBundleFromMedia(mM(e)))}createBundleFromMedia(e){return e.map((e=>e.mid?.toString())).filter((e=>e)).join(" ")}},YP=class{modify(e){e.media.forEach((e=>{zA(e)&&e.bundleOnly&&(e.port=9,delete e.invalid)}))}},QP=class{constructor(e,t){this.configProvider=e,this.mediaManager=t}modify(e){if(!this.configProvider.mediaConfig.isTransportUnbundled&&!e.groups?.find((e=>"BUNDLE"===e.type))){let t=!1;if(e.media.forEach(((e,i)=>{const n=this.mediaManager.getMediaEntities()[i];!t&&n.isEnabled()?(e.mid=n.getMid(),t=!0):(n.disable(),e.port=0)})),t){e.groups||(e.groups=[]);const t={type:"BUNDLE"};e.groups.push(t)}}}},ZP=class{constructor(e,t){this.configProvider=e,this.logger=t}modify(e){e.media.forEach((e=>{const t=!!e.candidates;if(e.candidates&&(e.candidates=e.candidates.filter((e=>{let t=!0,i=!0,n=!0;return this.configProvider.config.iceCandidateType&&(t=!!e.type.match(new RegExp(this.configProvider.config.iceCandidateType,"i"))),this.configProvider.config.iceCandidateTransport&&(i=!!e.transport.match(new RegExp(this.configProvider.config.iceCandidateTransport,"i"))),this.configProvider.config.iceCandidateFilterMDns&&(n=!this.isMdns(e.ip),n||this.logger.safe.info(`Filtering out mDNS candidate ${Ae(e.ip)}:${Ae(e.port)}`)),t&&i&&n}))),t&&e.connection&&this.configProvider.config.iceCandidateFilterMDns&&(e.candidates&&0!==e.candidates.length||(e.candidates=[fM(e.port)]),this.isMdns(e.connection.ip)||!this.hasMatchingCandidate(e))){const t=this.getDefaultCandidate(e);e.connection.ip=t.ip,e.port=t.port}}))}hasMatchingCandidate(e){const t=e.connection;return t&&!!e.candidates.find(this.createIpAndPortMatcher(t.ip,e.port))}getDefaultCandidate(e){return e.candidates.slice().sort(((e,t)=>e.type===t.type?0:"host"===e.type||"relay"===t.type?1:"relay"===e.type||"host"===t.type?-1:0))[0]}isMdns(e){return e.indexOf(".local")>-1||e.indexOf(".encrypted")>-1}createIpAndPortMatcher(e,t){return i=>i.ip===e&&i.port===t}},XP=class{modify(e){const t=mM(e)[0];t&&(t.candidates=[fM()])}},eM=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{this.fromMsSdp(e,t)}))}fromMsSdp(e,t){if(zA(e)||e.rids&&e.simulcast)return;const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n?.shouldBeEnabledInRemoteDesc()&&(n.enableInRemoteDesc(),e.simulcast={dir1:"recv",list1:n.ridList.map((e=>`${n.activeRids.includes(e)?"":"~"}${e}`)).join(";")},e.rids=n.ridList.map((e=>({id:e,direction:"recv"}))))}},tM=class{constructor(e,t){this.mediaManager=e,this.logger=t}modify(e){e.media.forEach(((e,t)=>{this.toMsSdp(e,t)}))}toMsSdp(e,t){const i=this.mediaManager.getMediaEntities()[t],n=i?.getSimulcastContext();n&&(n.localDescriptionIsApplied(),n.shouldBeEnabledInLocalDesc()&&(n.enableInLocalDesc(),this.removeSimulcastEnvelope(e),this.addStreamSsrc(e,i.getLocalSsrc())))}removeSimulcastEnvelope(e){e.rids&&delete e.rids,e.simulcast&&delete e.simulcast}addStreamSsrc(e,t){if(!t)return;if(e.ssrcs)return void this.logger.safe.debug(`Media mid: ${e.mid} already contains ssrc: ${JSON.stringify(e.ssrcs)}`);const i=t;this.setSsrc(e,i)}setSsrc(e,t){e.ssrcs=[{id:t,attribute:"fake_attribute",value:"fake_value"}]}},iM=class{constructor(e){this.mediaManager=e}modify(e){e.media.forEach(((e,t)=>{const i=this.mediaManager.getMediaEntities()[t],n=i?.getLocalTrackId();(!e.msid&&i?.getSimulcastContext()?.shouldUseSimulcast()&&n||i?.getExtension("reinviteless"))&&(e.msid=`- ${n??"-"}`)}))}},nM=class{constructor(e,t){this.mediaManager=e,this.configProvider=t}modify(e){const t=this.mediaManager.getMediaEntities(),i=(0,KA.flatMap)(t,(e=>e.getRtpHeaderExtensions())),n=i.find((e=>"vla"===e?.headerType))?.value,r=i.find((e=>"non-adv-vla"===e?.headerType))?.value,a=n??r??(0,KA.flatMap)(e.media,(e=>e.ext||[])).find((e=>e.uri===Qe.VLA.EXT_URI))?.value,s=function(e,t,i,n=!1){const r=(0,KA.flatMap)(e.media,(e=>e.ext||[])).map((e=>e.value));if(0===r.length)return i;const a=2,s=14;if(n&&!r.includes(i))return i;let o;for(let e=a;e<=s;e++)if(!r.includes(e)){o=e;break}return!o&&t&&(o=Math.max(...r)+1),o}(e,this.configProvider.config.extmapAllowMixed,Qe.VLA.DEFAULT_VALUE);e.media.forEach(((e,i)=>{const n=VA(e);if(!this.configProvider.config.enableVla||"Video"!==n&&"ScreenShare"!==n)return;if(e.ext?.find((e=>e.uri===Qe.VLA.EXT_URI)))return;const r=t[i]?.getRtpHeaderExtensions(),o=r?r.find((e=>"vla"===e.headerType))?.value??r.find((e=>"non-adv-vla"===e.headerType))?.value:a??s;o&&(e.ext=e.ext||[],e.ext.push({value:o,uri:Qe.VLA.EXT_URI}))}))}},rM=class{constructor(e){this.configProvider=e}modify(e){e.media.forEach((e=>{const t=VA(e);if(this.configProvider.config.allowRemoteVla&&("Video"===t||"ScreenShare"===t))return;const i=e.ext?.findIndex((e=>e.uri===Qe.VLA.EXT_URI));i>-1&&e.ext.splice(i,1)}))}},aM=class{constructor(e){this.configProvider=e}modify(e,t,i){e.media.forEach((e=>{const n=VA(e);if(!this.configProvider.config.enableNonAdvVla||"Video"!==n&&"ScreenShare"!==n||e.ext?.find((e=>e.uri===i)))return;const r=e.ext?.find((e=>e.uri===t));r&&(r.uri=i)}))}},sM=class extends aM{constructor(e,t){super(e),this.mediaManager=t}modify(e){const t=this.mediaManager.getMediaEntities();(0,KA.flatMap)(t,(e=>e.getRtpHeaderExtensions())).some((e=>"vla"===e?.headerType))||super.modify(e,Qe.VLA.EXT_URI,Qe.VLA.EXT_URI_NON_ADV)}},oM=class extends aM{constructor(e){super(e)}modify(e){super.modify(e,Qe.VLA.EXT_URI_NON_ADV,Qe.VLA.EXT_URI)}},lM=class{modify(e){e.media.forEach((e=>{e.ext?.forEach((e=>e.uri=this.normalizeSlashesInUri(e.uri)))}))}normalizeSlashesInUri(e){return e.replace(/\\/g,"/")}},cM=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.fixSdpForPartialIceRestart){const[{iceUfrag:t,icePwd:i}={}]=e.media;void 0!==t&&void 0!==i&&e.media.forEach((e=>{e.iceUfrag=t,e.icePwd=i}))}}},dM=class{constructor(e){this.configProvider=e}modify(e){if(this.configProvider.config.reduceRtcpFbInSdp?.length)for(const t of mM(e,Qe.MEDIA_TYPE.video))t.rtcpFb=t.rtcpFb&&this.getFbList(t.rtcpFb)}getFbList(e){const t=[],i=[];for(const n of e){const e=n.subtype?`${n.type}/${n.subtype}`:`${n.type}`;t.includes(e)||(this.configProvider.config.reduceRtcpFbInSdp.includes(e)?(t.push(e),i.push({...n,payload:"*"})):i.push(n))}return i}},uM=class{constructor(e){this.configProvider=e}modify(e){if(!this.configProvider.config.redReceiveEnabled)return;const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio));let i=0;DA(t,{codec:"opus",rate:48e3,encoding:2},(e=>{i=e.rtp.payload}));const n={codec:"RED",rate:8e3};DA(t,n,(e=>{e.rtp.rate=48e3,e.rtp.encoding=2,i&&(e.fmtp={payload:e.rtp.payload,config:`${i}/${i}`})})),LA(t,n)}},hM=class{constructor(e){this.configProvider=e}modify(e){this.configProvider.config.redReceiveEnabled&&DA(e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),{codec:"red",rate:48e3,encoding:2},(e=>{e.rtp.codec="RED",e.rtp.rate=8e3,delete e.rtp.encoding}))}},pM=class{constructor(e,t){this.configProvider=e,this.sdpType=t}modify(e){if(!this.configProvider.config.redReceiveEnabled||"offer"!==this.sdpType)return;const t=e.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i={codec:"red",rate:48e3,encoding:2};let n=0;if(DA(t,i,(e=>{n=e.rtp.payload})),n===Qe.PAYLOAD_TYPE.MSRTC_RED)return;const r=kA(e);-1!==r&&(SM(e,Qe.PAYLOAD_TYPE.MSRTC_RED,r),DA(t,i,(e=>{e.rtp.payload=Qe.PAYLOAD_TYPE.MSRTC_RED})))}};function gM(e,t,i,n){const r={type:e,port:0,label:t,payloads:e===Qe.MEDIA_TYPE.dataChannel||e===Qe.MEDIA_TYPE.data?Qe.PAYLOAD_TYPE.DATA_CHANNEL:"36",protocol:i,connection:{ip:"10.10.10.10",version:4}};return n&&(r.mid=n),r}function mM(e,t=null){return e.media.filter((e=>!(zA(e)||t&&e.type!==t)))}function fM(e=1234){return{component:1,ip:"10.10.10.10",foundation:1755259772,priority:2122197247,port:9!==e?e:1234,transport:"UDP",type:"host"}}function vM(e,t){if(!Qe.AUDIO_DECODER[e]?.[t])throw`unsupported codec ${e} or type ${t}`;const i=Qe.AUDIO_DECODER[e][t];return{codec:i.NAME,rate:i.RATE,encoding:i.ENCODING,payload:Qe.AUDIO_DECODER[e].PT}}function SM(e,t,i){for(const n of e.media)MA(n,t,i)}var yM=class e{constructor(e,t,i,n){this.context=e,this.sessionType=t,this.sdp=i,this.remote=n,this.mediaManager=this.context.mediaManager,this.sdpTransform=this.context.sdpTransform,this.logger=this.context.logger.createChild("SessionDescr"),this.sdpModel=wA.parse(this.sdp),n&&new jP(this.context.configProvider).modify(this.sdpModel),this.sdpModel.media.forEach((e=>{(0,IA.isUndefined)(e.mid)||(e.mid=e.mid.toString())})),this.remote&&!this.context.configProvider.config.disableMsSdp&&new sP(e,this.mediaManager,t).modify(this.sdpModel)}clone(){return new e(this.context,this.sessionType,this.sdp,this.remote)}getModalities(){return this.modalities||GA(this.sdpModel)}updateModalities(e){this.modalities=e}getSrtpInfo(){return tm(this.sdpModel)}getVideoCodecs(){const e={};return this.sdpModel.media.forEach((t=>{"video"===t.type&&t.rtp.map((e=>e.codec.toLowerCase())).forEach((t=>e[t]=!0))})),Object.keys(e)}usePrimaryAudioCodecOnly(e){new HP(e).modify(this.sdpModel)}isCodecSwitchSupported(){return!this.sdpModel.media.some((e=>e.type===Qe.MEDIA_TYPE.audio&&e.xMediaSettings&&this.containsMediaSetting(e.xMediaSettings,"codecswitchunsupported")))}toLocal(){return this.sdpModel=this.sdpTransform.toLocal(this.sdpModel,this.mediaManager,this.sessionType),wA.write(this.sdpModel)}toOffer(){return this.toOfferAnswer()}toAnswer(){return this.toOfferAnswer()}toOfferAnswer(){const e="offer"===this.sessionType;return new ZP(this.context.configProvider,this.logger).modify(this.sdpModel),(new YP).modify(this.sdpModel),e&&this.mediaManager.isEmpty()&&this.mediaManager.fromOffer(this.sdpModel,this.modalities),this.mediaManager.syncModalities(this.sdpModel,this.modalities,!e),this.sdpModel=e?this.sdpTransform.toOffer(this.sdpModel,this.mediaManager,this.modalities):this.sdpTransform.toAnswer(this.sdpModel,this.mediaManager,this.modalities),this.context.configProvider.config.disableMsSdp||new aP(this.context,this.mediaManager,this.sessionType).modify(this.sdpModel),new GP(this.mediaManager,this.context.configProvider).modify(this.sdpModel),this.modalities=GA(this.sdpModel),wA.write(this.sdpModel)}toRemote(e){return this.modalities=e,this.mediaManager.fromRemote(this.sdpModel,this.modalities),this.sdpModel=this.sdpTransform.toRemote(this.sdpModel,this.mediaManager,this.modalities,this.sessionType),wA.write(this.sdpModel)}getVideoRecvCapabilities(){return WA(this.getMediaByLabel(Qe.MEDIA_LABEL.video))}getSharingRecvCapabilities(){return WA(this.getMediaByLabel(Qe.MEDIA_LABEL.sharing))}getMediaByType(e){return this.sdpModel.media.find((t=>t.type===e))}isUnbundled(){const e=this.sdpModel.groups?.find((e=>"BUNDLE"===e.type)),t=this.sdpModel.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),i=this.sdpModel.media.find((e=>e.type===Qe.MEDIA_TYPE.video));return e?!e.mids.toString().split(" ").find((e=>e===t.mid)):!!i}couldBeUnbundled(){return!this.sdpModel.groups?.find((e=>"BUNDLE"===e.type))||this.hasUnbundledIceCandidates()}containsMediaSetting(e,t){return e.some((e=>-1!==e.settings.indexOf(t)))}getMediaByLabel(e){return this.sdpModel.media.find((t=>t.label===e))}hasIceCandidatesForMediaType(e,t=""){const i=this.sdpModel.media?this.sdpModel.media.filter((t=>t.type===e&&!!t.candidates&&0!==t.candidates.length)):[];return t?i.some((e=>!!e.candidates&&e.candidates.some((e=>e.type===t)))):!!i.length}hasIceCandidates(){return this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.audio)||this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.video)}hasRelayIceCandidates(){return this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.audio,"relay")||this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.video,"relay")}hasUnbundledIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Qe.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.audio)&&(!e.length||this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.video))}hasUnbundledRelayIceCandidates(){const e=this.sdpModel.media.filter((e=>e.type===Qe.MEDIA_TYPE.video&&0!==e.port));return this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.audio,"relay")&&(!e.length||this.hasIceCandidatesForMediaType(Qe.MEDIA_TYPE.video,"relay"))}isIceRestart(){return this.mediaManager.getMediaEntities().some((e=>e.getExtension("iceRestart")))}isMSRTC(){return!!this.sdpModel.xMediaBw}insertFakeCandidateIfNeeded(e,t){this.hasIceCandidates()||(e.setFakeIceCandidate(!0),t&&(t.fakeIceCandidate=!0),(new XP).modify(this.sdpModel))}getBweType(){const e=this.sdpModel.media.find((e=>0!==e.port&&e.type===Qe.MEDIA_TYPE.video));if(!e)return"Unknown";const t=e.ext?.find((e=>e.uri===Qe.TRANSPORT_CC.EXT_URI||e.uri===Qe.TRANSPORT_CC.MSSDP_ENCODED_URI));return t?"SSBWE":"REMB"}fixDataModality(){new uP(this.mediaManager).modify(this.sdpModel)}getPayloadsForMedia(e){const t=this.sdpModel.media.find((t=>t.type===e&&0!==t.port));return t?.rtp??[]}},CM=class{constructor(e){this.context=e}createLocalOffer(e){return new yM(this.context,"offer",e)}createRemoteOffer(e){return new yM(this.context,"offer",e,!0)}createLocalAnswer(e){return new yM(this.context,"answer",e)}createRemoteAnswer(e){return new yM(this.context,"answer",e,!0)}},_M=class{static build(e){return new CM(e=e||{})}};function EM(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var TM=class{constructor(){this.info={OfferedSrtp:"none",NegotiatedSrtp:"none",IceConnectionState:"none",IceConnectionStatePrevious:"none",SignalingState:"none",SignalingStatePrevious:"none",RelayCandidate:"none",IceTransportPolicy:"none",IceServers:"none",FakeIceCandidate:!1,BweType:"none",SdpSemantics:"none",BundlePolicy:"none",IPAddress:"none",ReflexiveLocalIP:"none",NumberOfInterfaces:0,EncodedStreamWorker:!1,AudioCodecEvents:"none"}}setCandidateDetails(e){"host"===e.type&&"udp"===e.protocol?this.setIPAddressInfo(e.ip):"srflx"===e.type&&this.setReflexiveLocalIP(e.ip)}setOfferedModalities(e){this.offeredModalities=e,this.activeModalities=e}setNegotiatedModalities(e){this.negotiatedModalities=e,this.activeModalities=e}setNegotiatedSrtpInfo(e){this.info.NegotiatedSrtp=EM(e)}setOfferedSrtpInfo(e){this.info.OfferedSrtp=EM(e)}setIceConnectionState(e){this.info.IceConnectionStatePrevious=this.info.IceConnectionState,this.info.IceConnectionState=e}setSignalingConnectionState(e){this.info.SignalingStatePrevious=this.info.SignalingState,this.info.SignalingState=e}setRelayCandidateInfo(e){this.info.RelayCandidate=JSON.stringify(e)}fillExtensionInfo(e){!function(e,t){for(const i in t)t.hasOwnProperty(i)&&(e[i]=t[i])}(e,this.info)}setIceTransportPolicy(e){this.info.IceTransportPolicy=e}setIceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.info.IceServers=JSON.stringify(t)}setFakeIceCandidate(e){this.info.FakeIceCandidate=e}setBweType(e){"Unknown"!==e&&(this.info.BweType=e)}setSdpSemantics(e){this.info.SdpSemantics=e}setBundlePolicy(e){this.info.BundlePolicy=e}setEncodedStreamWorkerLoaded(e){this.info.EncodedStreamWorker=e}setAudiocCodecEvents(e){this.info.AudioCodecEvents=JSON.stringify(e)}setCreateChannelFailReason(e){this.info.CreateChannelFailReason=Be(e)}setIPAddressInfo(e){this.info.NumberOfInterfaces+=1,"none"===this.info.IPAddress&&(this.info.IPAddress=e)}setReflexiveLocalIP(e){"none"===this.info.ReflexiveLocalIP&&(this.info.ReflexiveLocalIP=e)}},bM=class{constructor(e){this.audioContext=new Ug.window.AudioContext,this.sourceNode=this.audioContext.createMediaStreamSource(e),this.analyzerNode=this.createAnalyserNode(this.sourceNode)}dispose(){this.sourceNode.disconnect(),this.audioContext.close(),this.audioContext=null,this.sourceNode=null,this.analyzerNode=null}getInputLevel(){if(!this.analyzerNode)return 0;const e=new Uint8Array(this.analyzerNode.frequencyBinCount);return this.analyzerNode.getByteFrequencyData(e),Math.floor(65535*function(e){return 0===e.length?0:e.reduce(((e,t)=>e+t),0)/e.length}(e)/255)}createAnalyserNode(e){const t=this.audioContext.createAnalyser();return t.fftSize=1024,t.smoothingTimeConstant=.1,e.connect(t),t}},IM=class e{constructor(e){this.name=e,this.sharedState={mark:new Map,measure:[]}}mark(e,t){const i=Pt();this.sharedState.mark.set(e,{name:e,ts:i,startTime:Ct(Mt+i),details:t})}measure(e,t){const i=this.sharedState.mark.get(t.start),n=this.sharedState.mark.get(t.end);if(i&&n){const r={...t,parentName:this.name===e?"":this.name};this.sharedState.measure.push({name:e,details:r,duration:Ct(n.ts-i.ts),startTime:i.startTime})}}markAndMeasure(e,t,i,n){!1===this.sharedState.mark.has(t)&&this.mark(t,i);const r=this.sharedState.mark.get(e),a=this.sharedState.mark.get(t);if(r&&a){const e={...n,parentName:this.name===t?"":this.name};this.sharedState.measure.push({name:t,details:e,duration:Ct(a.ts-r.ts),startTime:r.startTime})}}clone(t){const i=new e(`${this.name}|${t}`);return i.setSharedState(this.sharedState),i}setSharedState(e){this.sharedState=e}getReport(){return this.sharedState.measure.map((e=>({name:e.name,duration:e.duration,ts:e.startTime,parentName:e.details.parentName})))}},wM=class e{mark(){}measure(){}markAndMeasure(){}clone(){return new e}getReport(){return[]}},RM=class{constructor(e){this.enableTimerTracker=e,this.timerTrackers={},this.timerTrackerOptions={}}getTimerTracker(e,t){if(!this.enableTimerTracker)return new wM;const i=new IM(e);if(this.timerTrackers[e]){const t=this.timerTrackerOptions[e];if(t?.first)return new wM;t?.last&&(this.timerTrackers[e]=[i]),t?.all&&this.timerTrackers[e].push(i)}else this.timerTrackers[e]=[i],this.timerTrackerOptions[e]=t;return i}getReport(){if(this.enableTimerTracker)return Object.keys(this.timerTrackers).reduce(((e,t)=>{const i=this.timerTrackerOptions[t];return(i.first||i.last)&&(e[t]=[this.timerTrackers[t][0]?.getReport()]),i.all&&(e[t]=Object.values(this.timerTrackers[t]).map((e=>e?.getReport()))),e}),{})}},AM=class{constructor(){this.presentationAPIUserDuration=0,this.presentationAudioDuration=0,this.isActiveScreenSharing=!1}handleInputLevel(e,t){this.isActiveScreenSharing&&("ScreenShare"===e&&t>0&&(this.presentationAPIUserDuration+=Qe.TIME_INTERVAL.SEC_1),"Audio"===e&&t>0&&(this.presentationAudioDuration+=Qe.TIME_INTERVAL.SEC_1))}updateScreenSharingStream(e,t){"ScreenShare"===t&&(this.isActiveScreenSharing=!!e)}getPresentationAudioDuration(){return this.presentationAudioDuration}getPresentationAudioAPIUserDuration(){return this.presentationAPIUserDuration}},PM=/profile-level-id=(.{6})/,MM=class{constructor(e,t,i=(()=>{}),n=(()=>this),r=(()=>{}),a=new CA,s){this.configProvider=e,this.dmDiagnostics=t,this.addSessionStatsError=i,this.newNativeSession=n,this.commitNativeSession=r,this.dshDiagnostics=a,this.getSessionRef=s,this.data={startTime:Date.now(),duration:0,offeredSrtp:"unknown",negotiatedSrtp:"unknown",iceConnectionState:"none",iceConnectionStatePrevious:"none",signalingState:"none",signalingStatePrevious:"none",relayCandidate:"none",iceTransportPolicy:"none",iceServers:"none",fakeIceCandidate:!1,bweType:"Unknown",sdpSemantics:"none",bundlePolicy:"none",iceCandidateErrors:[],H264Profiles:[],numInterfaces:0,statsReports:[],aggregatedModalityStats:{},multiViewStats:[],networkInfo:[],statsErrors:[],statsOnSubscribed:{},recvVideoStreamCount:{min:0,max:0,mode:0},reportedReceiveBandwidth:[],encodedStreamWorker:!1,audioCodecEvents:"none",totalVideoRecvMblocksRates:{macroblockRateReceivedMax:0,macroblockRateReceivedAvg:0,macroblockRateDecodedMax:0,macroblockRateDecodedAvg:0,macroblockRateMaxDecoderLossPercent:0,macroblockRateDecoderLossPercent:0},timerTrackerReport:{},loopIntervalMax:-1,loopIntervalMedian:-1,fetchTimeMax:-1,fetchTimeMedian:-1,videoPerformanceEvent:[],ovcToSubscriptionEvents:[],presentationAPIUserDuration:0,presentationAudioDuration:0,earlyMediaNumStatsPolls:0},this.timerTracker=new RM(this.configProvider.config.enableTimerTracker),this.presentationAudioTelemetry=new AM,bt(this.data,{duration:()=>this.data.endTime?this.data.endTime-this.data.startTime:Date.now()-this.data.startTime,bandwidthReport:()=>this.bandwidthStatsRef?.getBandwidthReport(),timerTrackerReport:()=>this.timerTracker.getReport(),presentationAPIUserDuration:()=>this.presentationAudioTelemetry.getPresentationAudioAPIUserDuration(),presentationAudioDuration:()=>this.presentationAudioTelemetry.getPresentationAudioDuration()}),Object.defineProperty(this.data,"IPAddress",{enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(this.data,"reflexiveLocalIP",{enumerable:!1,writable:!0,configurable:!0})}getTimerTracker(e,t){return this.timerTracker.getTimerTracker(e,t)}get deviceManager(){return this.dmDiagnostics}get audioLevel(){return this.analyzer?.getInputLevel()}get reflexiveLocalIP(){return this.data.reflexiveLocalIP}set bandwidthDiagnostic(e){this.bandwidthStatsRef=e}get callIsMuted(){return this.getSessionRef?.().callIsMuted}get sharingAudioLevel(){return this.analyzerSharing?.getInputLevel()}set offeredModalities(e){this.data.offeredModalities=e,this.data.activeModalities=e}set negotiatedModalities(e){this.data.negotiatedModalities=e,this.data.activeModalities=e}set offeredSrtp(e){this.data.offeredSrtp=kM(e)}set negotiatedSrtp(e){this.data.negotiatedSrtp=kM(e)}set iceConnectionState(e){this.data.iceConnectionStatePrevious=this.data.iceConnectionState,this.data.iceConnectionState=e}set signalingConnectionState(e){this.data.signalingStatePrevious=this.data.signalingState,this.data.signalingState=e}set relayCandidateInfo(e){this.data.relayCandidate=JSON.stringify(e)}set iceTransportPolicy(e){this.data.iceTransportPolicy=e}set iceServers(e){const t=e.map((e=>{const t={...e};return t.username&&(t.username="true"),t.credential&&(t.credential="true"),t}));this.data.iceServers=JSON.stringify(t)}set fakeIceCandidate(e){this.data.fakeIceCandidate=e}set bweType(e){this.data.bweType=e}set sdpSemantics(e){this.data.sdpSemantics=e}set isCodecsSupported(e){this.data.codecSupport=e}set bundlePolicy(e){this.data.bundlePolicy=e}set latestRawReport(e){this.data.latestRawReport=e}set recvVideoStreamsCount(e){this.data.recvVideoStreamCount=e}set aggregatedStatsRef(e){this.data.aggregatedModalityStats=e}set multiViewStats(e){this.data.multiViewStats=e}set videoCapabilities(e){if(!e?.codecs)return;const t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=PM.exec(e.sdpFmtpLine)?.[1];i&&t.push(i)}})),this.data.H264Profiles=[...new Set(this.data.H264Profiles.concat(t))]}set sentBWSeed(e){var t;(t=this.data).initialBWSeed??(t.initialBWSeed=e),this.data.sentBWSeed=e}set reportedSendBandwidth(e){this.data.reportedSendBandwidth=e,(!this.data.reportedSendBandwidthMin||this.data.reportedSendBandwidthMin>e)&&(this.data.reportedSendBandwidthMin=e),(!this.data.reportedSendBandwidthMax||this.data.reportedSendBandwidthMax<e)&&(this.data.reportedSendBandwidthMax=e)}set maxSessionBandwidth(e){this.data.maxSessionBandwidth=e}set bwStabiliationTime(e){this.data.bwStabilizationTime=e}set bwDownlinkStabiliationTime(e){this.data.bwDownlinkStabilizationTime=e}set statsOnSubscribed(e){this.data.statsOnSubscribed=e}set loopIntervalMax(e){this.data.loopIntervalMax=e}set loopIntervalMedian(e){this.data.loopIntervalMedian=e}set fetchTimeMax(e){this.data.fetchTimeMax=e}set fetchTimeMedian(e){this.data.fetchTimeMedian=e}setTotalVideoRecvMblocksRates(e){this.data.totalVideoRecvMblocksRates=e}setCandidateDetails(e){"host"===e.type&&"udp"===e.protocol?(this.data.numInterfaces++,this.data.IPAddress||(this.data.IPAddress=e.ip)):"srflx"!==e.type||this.data.reflexiveLocalIP||(this.data.reflexiveLocalIP=e.ip)}setAudioSendStream(e,t){if(this.configProvider.config.useAudioAnalyzer){const i=new bM(e.rawStream);"ScreenShare"===t&&e.hasAudio()?(this.analyzerSharing?.dispose(),this.analyzerSharing=i):"Audio"===t&&(this.analyzer?.dispose(),this.analyzer=i)}}addNetworkInfo(e){Tt(this.data.networkInfo,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addIceCandidateError(e){this.data.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.data.iceCandidateErrors=[]}registerEarlyMediaPoll(){this.data.earlyMediaNumStatsPolls++}addReportedReceiveBandwidth(e){Tt(this.data.reportedReceiveBandwidth,e,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addOvcSubscriptionReport(e,t,i){const n=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];n?.ovc.count!==e&&Tt(this.data.ovcToSubscriptionEvents,{ovc:{ts:Date.now(),count:e,subsCount:t,...i},subs:[]},this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples)}addSubscriptionToOvcEvent(e){const t=this.data.ovcToSubscriptionEvents[this.data.ovcToSubscriptionEvents.length-1];t&&t.subs.push({ts:Date.now(),count:e})}addStatsReport(e){Tt(this.data.statsReports,e,this.configProvider.config.diagnostics.collectionLimits.numStatsReports)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));i?i.count++:Tt(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors),this.addSessionStatsError(`nativeSession:${e}`,t)}setPresentationAudioOnScreenSharing(e,t){this.presentationAudioTelemetry.updateScreenSharingStream(e,t)}handlePresentationAudioInputLevel(){this.presentationAudioTelemetry.handleInputLevel("Audio",this.audioLevel),this.presentationAudioTelemetry.handleInputLevel("ScreenShare",this.sharingAudioLevel)}terminate(){this.data.endTime=Date.now(),this.analyzer?.dispose(),this.analyzer=null,this.analyzerSharing?.dispose(),this.analyzerSharing=null}newQualityManagerDiagnostics(){const e=new EA(this.configProvider,((e,t)=>this.addStatsError(`qualityManagerDiagnostics:${e}`,t)));return this.data.qualityManager=e.getObjectRef(),e}newRemoteVideoManagerDiagnostics(){const e=new TA(this.configProvider);return this.data.remoteVideoManager=e.getObjectRef(),e}newSubscriptionManagerDiagnostics(){const e=new _A(this.configProvider,(e=>this.addStatsError("subscriptionManagerDiagnostics",e)));return this.data.subscriptionManager=e.getObjectRef(),e}set encodedStreamWorker(e){this.data.encodedStreamWorker=e}set audioCodecEvents(e){this.data.audioCodecEvents=e}getObjectRef(){return this.data}registerVideoPerformanceEvent(e,t){const i={type:t,perfEvent:e,resRequestEvent:null,resChangedEvent:[]};this.data.videoPerformanceEvent=this.data.videoPerformanceEvent.concat(i)}registerResolutionChanageRequest(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];t&&(t.resRequestEvent=e)}registerResolutionChanageEvent(e){const t=this.data.videoPerformanceEvent[this.data.videoPerformanceEvent.length-1];e.ts-t?.resRequestEvent.ts<this.configProvider.config.diagnostics.performanceMonitoring.telemetryResolutionRequestSpanMs&&t.resChangedEvent.push(e)}};function kM(e){let t="";return e.dtls&&(t+="dtls"),e.sdes&&(t+="sdes"),t}var DM=Symbol("sessionDiagnosticsRef"),OM=class{constructor(e,t,i,n,r,a){this.logger=e,this.configProvider=t,this.diagnosticsReport=i,this.dmDiagnostics=n,this.dshDiagnostics=new CA,this.data={creationTime:Date.now(),callNumber:0,sessionId:"unknown",isMultiParty:!1,dtmfSuccessCount:0,dtmfFailureCount:0,iceInitTime:0,iceConnectedStateTime:0,negotiationCount:0,rejectedNegotiationCount:0,initialNegotiationCompleted:!1,finalAnswerTime:0,transportReconnectedCount:0,rollbackNegotiation:[],activeModalities:{},allowedAudioSend:!0,allowedVideoSend:!0,allowedScreensharingSend:!0,noIceCandidatesEventCount:{good:0,bad:0},noRelayIceCandidatesEventCount:{good:0,bad:0},microphoneInUseEventCount:{good:0,bad:0},cameraInUseEventCount:{good:0,bad:0},cameraFreezeEventCount:{start:0,end:0},rawMedia:{audio:{recv:{numAttempts:0,durationRatio:0},send:{numAttempts:0,durationRatio:0}}},ufds:[],statsErrors:[],webrtcSessions:[],isOngoing:!1,duration:0,callMutedRatio:0,callOsMuted:0,callHwSilent:0,callSwMuted:0,callIsMuted:!1,callSpeakerMuted:0,callIsSpeaking:0,networkRecvUFD:void 0,networkSendUFD:void 0,deviceManager:void 0,relayTimers:void 0,authTokenFetcherStats:void 0,dominantSpeaker:this.dshDiagnostics.getObjectRef(),[DM]:this},this.transportDisconnected=!1,this.commonMuteTracker=new LM,this.swMuteTracker=new LM,this.osMuteTracker=new LM,this.speakerMuteTracker=new LM,this.hwSilentTracker=new LM,this.isSpeakingTracker=new LM,this.networkRecv=new xM,this.networkSend=new xM,this.rawMediaTimers={audio:{send:new LM,recv:new LM}},this.dmFragmenter=new NM(this.dmDiagnostics),this.durationTimer=new LM,this.data.callNumber=r,this.data.sessionId=a,this.durationTimer.start(),bt(this.data,{isOngoing:()=>void 0===this.data.terminationTime,duration:()=>this.durationTimer.elapsed,callMutedRatio:()=>FM(this.commonMuteTracker.elapsed,this.data.duration),callOsMuted:()=>this.osMuteTracker.elapsed,callHwSilent:()=>this.hwSilentTracker.elapsed,callSwMuted:()=>this.swMuteTracker.elapsed,callIsMuted:()=>this.swMuteTracker.isRunning,callSpeakerMuted:()=>this.speakerMuteTracker.elapsed,callIsSpeaking:()=>this.isSpeakingTracker.elapsed,networkRecvUFD:()=>({good:this.networkRecv.getCount("Good"),poor:this.networkRecv.getCount("Poor"),bad:this.networkRecv.getCount("Bad"),goodRatio:FM(this.networkRecv.getElapsed("Good"),this.data.duration),poorRatio:FM(this.networkRecv.getElapsed("Poor"),this.data.duration),badRatio:FM(this.networkRecv.getElapsed("Bad"),this.data.duration)}),networkSendUFD:()=>({good:this.networkSend.getCount("Good"),poor:this.networkSend.getCount("Poor"),bad:this.networkSend.getCount("Bad"),goodRatio:FM(this.networkSend.getElapsed("Good"),this.data.duration),poorRatio:FM(this.networkSend.getElapsed("Poor"),this.data.duration),badRatio:FM(this.networkSend.getElapsed("Bad"),this.data.duration)}),deviceManager:()=>this.dmFragmenter.getFragment(this.dmDiagnostics),relayTimers:()=>this._relayManager?.getStats(),authTokenFetcherStats:()=>this._relayManager?.getAuthTokenStats()}),bt(this.data.rawMedia.audio.recv,{durationRatio:()=>FM(this.rawMediaTimers.audio.recv.elapsed,this.data.duration)}),bt(this.data.rawMedia.audio.send,{durationRatio:()=>FM(this.rawMediaTimers.audio.send.elapsed,this.data.duration)})}get telemetryReport(){const e={type:"WebRtcMediaStats",data:this.diagnosticsReport.getSessionTelemetry(this.data.sessionId)},t={};return Xe(e.data,((e,i,n)=>{let r=0;Vg.test(e)?(r=13,t[i]="IPv4"):Hg.test(e)&&(r=4,t[i]="IPv6"),n[i]={type:r,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(t),__VALUE__:!0},e}get mediaStatsReport(){return this.diagnosticsReport.getMediaSessionStats(this.data.sessionId)}get realtimeTelemetryReport(){return this.diagnosticsReport.getTeamsRealtimeTelemetry(this.data.sessionId)}get e2eDiagnostics(){return this.diagnosticsReport.getDiagnosticsForE2eTests(this.data.sessionId)}set relayManager(e){this._relayManager=e}set isMultiParty(e){this.data.isMultiParty=e}set mediaLegId(e){this.data.mediaLegId=e.process()}set ETag(e){this.data.ETag=e}set configIds(e){this.data.configIds=e}set reconnect(e){this.data.reconnect=e}set relay(e){this.data.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}set sessionError(e){this.data.error=e}set dtmfResult(e){e?this.data.dtmfSuccessCount++:this.data.dtmfFailureCount++}set swMute(e){e?this.swMuteTracker.start():this.swMuteTracker.stop(),this.updateCommonMute()}set speakerMute(e){e?this.speakerMuteTracker.start():this.speakerMuteTracker.stop()}set hwSilent(e){e?this.hwSilentTracker.start():this.hwSilentTracker.stop()}set isSpeaking(e){e?this.isSpeakingTracker.start():this.isSpeakingTracker.stop()}set iceInitTime(e){this.data.iceInitTime||(this.data.iceInitTime=e)}set finalAnswerTime(e){var t;(t=this.data).finalAnswerTime??(t.finalAnswerTime=e)}set iceConnectedStateTimestamp(e){this.data.iceConnectedStateTime||(this.data.iceConnectedStateTime=e)}set allowedModalities(e){this.data.allowedAudioSend=e.audio.some((e=>Wg(e))),this.data.allowedVideoSend=e.video.some((e=>Wg(e))),this.data.allowedScreensharingSend=e.sharing.some((e=>Wg(e)))}negotiationStart(e){var t;(t=this.data).initialNegotiationType??(t.initialNegotiationType=e),this.data.negotiationCount++}negotiationCompleted(e){this.data.initialNegotiationCompleted=!0,this.data.activeModalities=e,this.data.error=void 0}negotiationRejected(){this.data.rejectedNegotiationCount++}registerRollbackEvent(e){this.data.rollbackNegotiation.push({type:e.type,attempt:this.data.rollbackNegotiation.length+1,error:e.error})}registerRawMediaAccess(e,t,i){const n=this.data.rawMedia[e]?.[t];if(n){n.numAttempts++;const r=this.rawMediaTimers[e]?.[t];i?r?.start():r?.stop()}}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.data.noIceCandidatesEventCount.good++:this.data.noIceCandidatesEventCount.bad++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.data.noRelayIceCandidatesEventCount.good++:this.data.noRelayIceCandidatesEventCount.bad++;break;case"DeviceCaptureNotFunctioning":"Good"===e.value?this.data.microphoneInUseEventCount.good++:this.data.microphoneInUseEventCount.bad++;break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.data.cameraInUseEventCount.good++:this.data.cameraInUseEventCount.bad++;break;case"DeviceCaptureMute":"Bad"===e.value?this.osMuteTracker.start():this.osMuteTracker.stop(),this.updateCommonMute();break;case"NetworkRecvQuality":this.networkRecv.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.data.cameraFreezeEventCount.end++:this.data.cameraFreezeEventCount.start++}"DeviceSpeakWhileMuted"!==e.type&&Tt(this.data.ufds,{...e,timestamp:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numUFDs)}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.data.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}terminated(e){this.data.terminationReason=lt(e),this.data.terminationTime=Date.now(),this.durationTimer.stop(),this.swMuteTracker.stop(),this.speakerMuteTracker.stop(),this.hwSilentTracker.stop(),this.isSpeakingTracker.stop(),this.dmFragmenter.terminated(this.dmDiagnostics)}addStatsError(e,t){const i=this.data.statsErrors.find((i=>i.error===t&&i.origin===e));this.logger.safe.error(`Stats error from '${e}': ${t} (${i?.count??1})`),i?i.count++:Tt(this.data.statsErrors,{origin:e,error:t,count:1},this.configProvider.config.diagnostics.collectionLimits.numStatsErrors)}newNativeSessionDiag(e=!0){let t;return t=new MM(this.configProvider,this.dmDiagnostics,((e,t)=>this.addStatsError(e,t)),(e=>this.newNativeSessionDiag(e)),(()=>this.pushNativeSessionDiag(t.getObjectRef())),this.dshDiagnostics.resetState(),(()=>this.getObjectRef())),e&&Tt(this.data.webrtcSessions,t.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numNativeSessions),t}pushNativeSessionDiag(e){Tt(this.data.webrtcSessions,e,this.configProvider.config.diagnostics.collectionLimits.numNativeSessions)}getObjectRef(){return this.data}updateCommonMute(){this.swMuteTracker.isRunning||this.osMuteTracker.isRunning?this.commonMuteTracker.start():this.swMuteTracker.isRunning||this.osMuteTracker.isRunning||this.commonMuteTracker.stop()}},NM=class{constructor(e){this.fragmentBase=this.sanitizeDiagnostics(e)}getFragment(e){const t=this.fragmentTerminated??e;return{devicesChangeCount:t.devicesChangeCount-this.fragmentBase.devicesChangeCount,deviceSelectionChangeCount:t.deviceSelectionChangeCount-this.fragmentBase.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:t.deviceSelectionChangeCountFromInterface-this.fragmentBase.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:t.devicesPollChangeCount-this.fragmentBase.devicesPollChangeCount}}terminated(e){this.fragmentTerminated=this.sanitizeDiagnostics(e)}sanitizeDiagnostics(e){return{devicesChangeCount:e.devicesChangeCount,deviceSelectionChangeCount:e.deviceSelectionChangeCount,deviceSelectionChangeCountFromInterface:e.deviceSelectionChangeCountFromInterface,devicesPollChangeCount:e.devicesPollChangeCount}}},LM=class{constructor(){this.startTime=0,this.elapsedInternal=0,this.countInternal=0}get isRunning(){return!!this.startTime}get elapsed(){return Math.round(this.startTime?this.elapsedInternal+Pt()-this.startTime:this.elapsedInternal)}get count(){return this.countInternal}start(){this.startTime||(this.startTime=Pt(),this.countInternal++)}stop(){this.startTime&&(this.elapsedInternal+=Pt()-this.startTime,this.startTime=0)}},xM=class{constructor(){this.currentLevel="Good",this.stopWatches={},this.getStopWatch(this.currentLevel).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getElapsed(e){const t=this.stopWatches[e];return t?t.elapsed:0}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new LM,this.stopWatches[e]=t),t}};function FM(e,t){return e/(0!==t?t:1)}function UM(e,t,i){return ct({recv:ct({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytesReceived:Ot(e.audio?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Ot(e.audio?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Ot(e.audio?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:t?.codec?.mimeType.split("/")[1],googTrackId:t?.track?.trackIdentifier,transport_id:t?.transport?.id,transportId:t?.inboundRTP.transportId,transport_selectedCandidatePairId:t?.transport?.selectedCandidatePairId,transport_dtlsCipher:t?.transport?.dtlsCipher,transport_srtpCipher:t?.transport?.srtpCipher,pair_id:t?.transport?.selectedCandidatePair?.id,pair_responsesSent:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:t?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:t?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:t?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:t?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Ot(e.audio?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:t?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:t?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:t?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:t?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:t?.transport?.selectedCandidatePair?.localCandidate?.ip??t?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:t?.transport?.selectedCandidatePair?.remoteCandidate?.ip??t?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Ot(e.audio?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:t?.transport?.selectedCandidatePair?.nominated}),send:ct({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytesSent:Ot(e.audio?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Ot(e.audio?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Ot(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:i?.codec?.mimeType.split("/")[1],googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.outboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Ot(e.audio?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Ot(e.audio?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated})})}function BM(e,t,i,n){return ct({recv:ct({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytesReceived:Ot(t[e]?.recv,(e=>e.inboundRTP.bytesReceived)),packetsReceived:Ot(t[e]?.recv,(e=>e.inboundRTP.packetsReceived)),packetsLost:Ot(t[e]?.recv,(e=>e.inboundRTP.packetsLost)),googCodecName:i?.codec?.mimeType.split("/")[1],codecImplementationName:i?.inboundRTP.decoderImplementation,googTrackId:i?.track?.trackIdentifier,transport_id:i?.transport?.id,transportId:i?.inboundRTP.transportId,transport_selectedCandidatePairId:i?.transport?.selectedCandidatePairId,transport_dtlsCipher:i?.transport?.dtlsCipher,transport_srtpCipher:i?.transport?.srtpCipher,pair_id:i?.transport?.selectedCandidatePair?.id,pair_responsesSent:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:i?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:i?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:i?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:i?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Ot(t[e]?.recv,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:i?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:i?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:i?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:i?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:i?.transport?.selectedCandidatePair?.localCandidate?.ip??i?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:i?.transport?.selectedCandidatePair?.remoteCandidate?.ip??i?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Ot(t[e]?.recv,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:i?.transport?.selectedCandidatePair?.nominated,framesDecoded:Ot(t[e]?.recv,(e=>e.inboundRTP.framesDecoded)),googFrameHeightReceived:Ot(t[e]?.recv,(e=>e.inboundRTP.frameHeight)),googFrameWidthReceived:Ot(t[e]?.recv,(e=>e.inboundRTP.frameWidth)),googFrameRateReceived:Ot(t[e]?.recv,(e=>e.extensions?.frameRateReceived||0)),googNacksSent:Ot(t[e]?.recv,(e=>e.inboundRTP.nackCount)),googPlisSent:Ot(t[e]?.recv,(e=>e.inboundRTP.pliCount)),keyFramesDecoded:Ot(t[e]?.recv,(e=>e.inboundRTP.keyFramesDecoded)),googFirsSent:Ot(t[e]?.recv,(e=>e.inboundRTP.firCount)),googJitterBufferMs:Ot(t[e]?.recv,(e=>e.extensions?.jitterBufferMs)),googFrameRateDecoded:Ot(t[e]?.recv,(e=>e.extensions?.frameRateDecoded||0)),googFrameRateOutput:i?.extensions?.trackRecvFps,jitter:i?.inboundRTP.jitter}),send:ct({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytesSent:Ot(t[e]?.send,(e=>e.outboundRTP.bytesSent)),packetsSent:Ot(t[e]?.send,(e=>e.outboundRTP.packetsSent)),packetsLost:Ot(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost)),googCodecName:n?.codec?.mimeType.split("/")[1],codecImplementationName:n?.outboundRTP.encoderImplementation,googTrackId:n?.track?.trackIdentifier,transport_id:n?.transport?.id,transportId:n?.outboundRTP.transportId,transport_selectedCandidatePairId:n?.transport?.selectedCandidatePairId,transport_dtlsCipher:n?.transport?.dtlsCipher,transport_srtpCipher:n?.transport?.srtpCipher,pair_id:n?.transport?.selectedCandidatePair?.id,pair_responsesSent:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesSent)),pair_requestsReceived:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsReceived)),pair_googRemoteCandidateType:n?.transport?.selectedCandidatePair?.remoteCandidate?.candidateType,pair_consentRequestsSent:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.consentRequestsSent)),pair_googTransportType:n?.transport?.selectedCandidatePair?.localCandidate?.protocol,pair_googLocalCandidateType:n?.transport?.selectedCandidatePair?.localCandidate?.candidateType,pair_googWritable:n?.transport?.selectedCandidatePair?.writable,pair_requestsSent:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.requestsSent)),pair_googRtt:Ot(t[e]?.send,(e=>1e3*e.transport?.selectedCandidatePair?.currentRoundTripTime),!0),pair_googActiveConnection:n?.transport?.selectedCandidatePair?.nominated,pair_packetsDiscardedOnSend:n?.transport?.selectedCandidatePair?.packetsDiscardedOnSend,pair_bytesReceived:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesReceived)),pair_responsesReceived:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.responsesReceived)),pair_remoteCandidateId:n?.transport?.selectedCandidatePair?.remoteCandidate?.id,pair_localCandidateId:n?.transport?.selectedCandidatePair?.localCandidate?.id,pair_packetsSent:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.packetsSent)),pair_googLocalAddress:n?.transport?.selectedCandidatePair?.localCandidate?.ip??n?.transport?.selectedCandidatePair?.localCandidate?.address,pair_googRemoteAddress:n?.transport?.selectedCandidatePair?.remoteCandidate?.ip??n?.transport?.selectedCandidatePair?.remoteCandidate?.address,pair_bytesSent:Ot(t[e]?.send,(e=>e.transport?.selectedCandidatePair?.bytesSent)),pair_googReadable:n?.transport?.selectedCandidatePair?.nominated,framesEncoded:Ot(t[e]?.send,(e=>e.outboundRTP.framesEncoded)),googNacksReceived:Ot(t[e]?.send,(e=>e.outboundRTP.nackCount)),googPlisReceived:Ot(t[e]?.send,(e=>e.outboundRTP.pliCount)),googFirsReceived:Ot(t[e]?.send,(e=>e.outboundRTP.firCount)),keyFramesEncoded:Ot(t[e]?.send,(e=>e.outboundRTP.keyFramesEncoded)),googFrameHeightInput:n?.mediaSource?.height,googFrameWidthInput:n?.mediaSource?.width,googFrameRateInput:Ot(t[e]?.send,(e=>e.mediaSource?.framesPerSecond)),googFrameHeightSent:Ot(t[e]?.send,(e=>e.outboundRTP.frameHeight)),googFrameWidthSent:Ot(t[e]?.send,(e=>e.outboundRTP.frameWidth)),googFrameRateSent:Ot(t[e]?.send,(e=>e.extensions?.frameRateSent)),googRtt:Ot(t[e]?.send,(e=>1e3*(e.remoteInboundRTP?.roundTripTime??0)),!0),hugeFramesSent:n?.outboundRTP.hugeFramesSent,qpSum:Ot(t[e]?.send,(e=>e.outboundRTP.qpSum)),qualityLimitationDurations:n?JSON.stringify(n?.outboundRTP.qualityLimitationDurations):void 0,qualityLimitationReason:n?.outboundRTP.qualityLimitationReason,qualityLimitationResolutionChanges:n?.outboundRTP.qualityLimitationResolutionChanges,jitter:n?.remoteInboundRTP?.jitter})})}function VM(e){return e?.substring(e.indexOf("/")+1).toUpperCase()}var HM=e=>ct({id:e.outboundRTP.ssrc.toString(),codecName:VM(e.codec?.mimeType),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,rtt:e.remoteInboundRTP?.roundTripTime,frameRateInput:e.mediaSource?.framesPerSecond,frameWidthInput:e.mediaSource?.width,frameHeightInput:e.mediaSource?.height,framesEncoded:e.outboundRTP.framesEncoded,frameRateEncoded:e.extensions?.frameRateEncoded,framesSent:e.outboundRTP.framesSent,frameRateSent:e.extensions?.frameRateSent,frameWidthSent:e.outboundRTP.frameWidth,frameHeightSent:e.outboundRTP.frameHeight,keyFramesEncoded:e.outboundRTP.keyFramesEncoded,nackCount:e.outboundRTP.nackCount,firCount:e.outboundRTP.firCount,pliCount:e.outboundRTP.pliCount,transportId:e.outboundRTP.transportId,altLayouts:e.altLayouts?.map(HM)}),$M=e=>ct({id:e.inboundRTP.ssrc.toString(),codecName:VM(e.codec?.mimeType),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,msi:e.renderer?.msi,jitterBufferMs:e.extensions?.jitterBufferMs,frameRateOutput:e.extensions?.frameRateDecoded,frameRateDecoded:e.extensions?.frameRateDecoded,frameRateReceived:e.extensions?.frameRateReceived,frameWidthReceived:e.inboundRTP.frameWidth,frameHeightReceived:e.inboundRTP.frameHeight,longestFreezeDuration:e.extensions?.longestFreeze,totalFreezeDuration:e.extensions?.totalFreezeDuration,framesReceived:e.inboundRTP.framesReceived,framesDropped:e.inboundRTP.framesDropped,framesDecoded:e.inboundRTP.framesDecoded,keyFramesDecoded:e.inboundRTP.keyFramesDecoded,nackCount:e.inboundRTP.nackCount,firCount:e.inboundRTP.firCount,pliCount:e.inboundRTP.pliCount,transportId:e.inboundRTP.transportId}),GM=e=>ct({id:e.outboundRTP.ssrc.toString(),codecName:VM(e.codec?.mimeType),bitrate:e.extensions?.bitrate,jitter:e.remoteInboundRTP?.jitter,packets:e.outboundRTP.packetsSent,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.remoteInboundRTP?.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.remoteInboundRTP?.packetsDiscarded,rtt:e.remoteInboundRTP?.roundTripTime,audioLevel:e.mediaSource?.audioLevel,transportId:e.outboundRTP.transportId}),jM=e=>ct({id:e.inboundRTP.ssrc.toString(),codecName:VM(e.codec?.mimeType),bitrate:e.extensions?.bitrate,jitter:e.inboundRTP.jitter,packets:e.inboundRTP.packetsReceived,packetsPerSecond:e.extensions?.packetsPerSecond,packetsLost:e.inboundRTP.packetsLost,packetsLostPerSecond:e.extensions?.packetsLostPerSecond,packetsDiscarded:e.inboundRTP.packetsDiscarded,rtt:e.remoteOutboundRTP?.roundTripTime,jitterBufferMs:e.extensions?.jitterBufferMs,audioLevel:e.inboundRTP.audioLevel,healedRatio:e.extensions?.healedRatio,transportId:e.inboundRTP.transportId}),zM=e=>ct({id:e.id,state:e.state,dataChannelIdentifier:e.dataChannelIdentifier,messagesSent:e.messagesSent,bytesSent:e.bytesSent,messagesReceived:e.messagesReceived,bytesReceived:e.bytesReceived,sendBitrate:e.extensions?.sendBitrate,recvBitrate:e.extensions?.recvBitrate,messagesSentPerSecond:e.extensions?.sendMessageRate,messagesReceivedPerSecond:e.extensions?.recvMessageRate}),WM=e=>ct({id:e.id,rtt:e.selectedCandidatePair?.currentRoundTripTime,availableIncomingBitrate:e.selectedCandidatePair?.availableIncomingBitrate,availableOutgoingBitrate:e.selectedCandidatePair?.availableOutgoingBitrate,relayProtocol:e.selectedCandidatePair?.localCandidate?.relayProtocol,candidateType:`${e.selectedCandidatePair?.localCandidate?.candidateType??""}:${e.selectedCandidatePair?.remoteCandidate?.candidateType??""}`});function qM(e){return(e.audio?.send??[]).map(GM)}function KM(e){return(e.audio?.recv??[]).map(jM)}function JM(e){return e.video?.send?.length?e.video.send.map(HM):[]}function YM(e){return(e.video?.recv??[]).map($M)}function QM(e){return e.sharing?.send?.length?e.sharing.send.map(HM):[]}function ZM(e){return(e.sharing?.recv??[]).map($M)}function XM(e){return(e.data??[]).map(zM)}function ek(e){return Object.values(e.transports??{}).map(WM)}function tk(e){return 1e4*e}function ik(e,t=Number(new Date)){if(!e)return;const i=lt(e);return e.lastMsgDate&&(e.timeSinceLastMsg=e.lastMsgDate-t),delete i.lastMsgDate,delete i.lastHistory,ct(i)}function nk(e,t,i=0){const n=t.filter((e=>void 0!==e));let r;switch(e){case"Difference":r=n[n.length-1]-n[0];break;case"Average":r=n.reduce(((e,t)=>e+t),0)/n.length;break;case"LastValue":r=n[n.length-1]}return r||0===r?`${"number"==typeof r?+r.toFixed(i):r}`:void 0}function rk(e,t,i){return(i?e.map((e=>e?.[t]?.[i])):e.map((e=>e?.[t]))).filter((e=>void 0!==e)).reduce(((e,t)=>e.concat(t)),[])}function ak(e){const t=e[e.length-1]?.extensions?.powerEfficient;return void 0===t?"":t?"hw":"sw"}function sk(e,t){return e&t?"Bidirectional":e?"ReceiveFromPeer":t?"SendToPeer":"Inactive"}function ok(e){const t=e[e.length-1]?.extensions?.callIsMuted,i=e[e.length-1]?.extensions?.rawInputVolume;return t?"0":!t&&i>0?"2":t||0!==i?void 0:"1"}function lk(e,t){const i=rk(e,"audio","send"),n=rk(e,"audio","recv"),r=function(e){const t=e.find((e=>e?.transports));return t?t.transports[Object.keys(t.transports)[0]]:void 0}(e);if(i.length||n.length)return ct({mediaType:"Audio",mediaDirection:sk(n.length,i.length),"Received BW estimate":nk("Average",n.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Recv Loss Rate (Avg)":nk("LastValue",n.map((e=>e?.extensions?.lossRate/100)),3),"Rtp Packets Received":nk("Difference",n.map((e=>e?.inboundRTP.packetsReceived))),"Rtp Packet Sent":nk("Difference",i.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":nk("Average",i.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Audio Codec":nk("LastValue",i.map((e=>e?.codec?.mimeType)))?.split("/")[1],"Send RTT (Avg)":nk("LastValue",i.map((e=>e?.extensions?.rttAvg))),"Audio NW jitter avg":nk("LastValue",n.map((e=>e?.extensions?.jitterAvg)),3),"Audio send bps":nk("Average",i.map((e=>e?.extensions?.bitrate))),"JB delay (ms)":nk("LastValue",n.map((e=>e?.extensions?.jitterBufferDelayMs))),"Recv Audio Codec":nk("LastValue",n.map((e=>e?.codec?.mimeType)))?.split("/")[1],"Current Render Device Name":t?.speaker,"Current Capture Device Name":t?.microphone,"Latest Network Type":r?.selectedCandidatePair?.localCandidate?.networkType,"Latest Transport Protocol":r?.selectedCandidatePair?.localCandidate?.protocol,"Latest Reflexive Address":bm(r?.extensions?.reflexiveLocalIP),"Local Address":bm(r?.selectedCandidatePair?.localCandidate?.ip),"Local short-term Healed Data Ratio":nk("LastValue",n.map((e=>e?.extensions?.healedRatio))),"Send activity (0=muted; 1=inactive; 2=active)":ok(i)})}function ck(e,t){const i=nk("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/")[1],n=i?i+` ${ak(e)}`:void 0;return{"Rtp Packet Sent":nk("Difference",e.map((e=>e?.outboundRTP.packetsSent))),"Sent BW estimate":nk("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableOutgoingBitrate))),"Send Current Bitrate":nk("Average",e.map((e=>e?.extensions?.bitrate))),"Allocated Send Bandwidth Average":nk("LastValue",e.map((e=>e?.extensions?.bitrateAvg))),"Send Actual Height":nk("LastValue",e.map((e=>e?.outboundRTP.frameHeight))),"Send Actual Width":nk("LastValue",e.map((e=>e?.outboundRTP.frameWidth))),"Send Current Frame Rate":nk("Average",e.map((e=>e?.extensions?.frameRateSent))),"Send RTT (Avg)":nk("LastValue",e.map((e=>e?.extensions?.rttAvg))),"Sent Codec Name":n,"Webcam Freeze Intervals":nk("LastValue",e.map((e=>e?.extensions?.captureFreezeIntervalsCount))),"Current Capture Device Name":t?.camera,"Number of Sync Frame Request per Minute":nk("LastValue",e.map((e=>e?.extensions?.pliRate)))}}function dk(e){const t=nk("LastValue",e.map((e=>e?.mediaEntity?.xSourceStreamId))),i=nk("LastValue",e.map((e=>e?.codec?.mimeType)))?.split("/")[1],n=i?i+` ${ak(e)}`:void 0;return{"Recv Loss Rate (Avg)":nk("LastValue",e.map((e=>e?.extensions?.lossRate)),3),"Received BW estimate":nk("Average",e.map((e=>e?.transport?.selectedCandidatePair?.availableIncomingBitrate))),"Receive Current Bitrate":nk("Average",e.map((e=>e?.extensions?.bitrate))),"Rtp Packets Received":nk("Difference",e.map((e=>e?.inboundRTP.packetsReceived))),"Receive Actual Height":nk("LastValue",e.map((e=>e?.inboundRTP.frameHeight))),"Receive Actual Width":nk("LastValue",e.map((e=>e?.inboundRTP.frameWidth))),"Receive Current Frame Rate":nk("Average",e.map((e=>e?.extensions?.frameRateReceived))),"Received Codec Name":n,"Received Total Freeze Fraction (ms per min)":nk("LastValue",e.map((e=>e?.extensions?.totalFreezeFraction))),videoSourceId:t?parseInt(t):void 0,"Received Fps Time Weighted Harmonic Average":nk("LastValue",e.map((e=>e?.extensions?.fpsHarmonicAverage)))}}function uk(e,t,i){const n=lk(e,t);n&&i.channels.push(n);const r=function(e,t){const i=[],n=function(e){const t={},i=i=>{e.map((e=>e?.video?.[i])).forEach((e=>{e?.forEach((e=>{var n;const r=e?.mediaEntity?.remoteSsrc;t[r]??(t[r]={}),(n=t[r])[i]??(n[i]=[]),t[r][i].push(e)}))}))};return i("recv"),i("send"),t}(e);for(const{send:e,recv:r}of Object.values(n)){let n={mediaType:"Camera",mediaDirection:sk(r?.length,e?.length)};r&&(n={...n,...dk(r)}),e&&(n={...n,...ck(e,t)}),i.push(ct(n))}return i}(e,t);r.length&&i.channels.push(...r);const a=function(e){const t=rk(e,"sharing","send"),i=rk(e,"sharing","recv");if(!i.length&&!t.length)return;let n={mediaType:"AppSharing",mediaDirection:"Bidirectional","Render Device Name":""};return i.length&&(n={...n,...dk(i)}),t.length&&(n={...n,...ck(t,{microphone:void 0,camera:"Screen sharing",speaker:void 0})}),ct(n)}(e);a&&i.channels.push(a)}function hk(e,t,i,n,r){return ct({recv:ct({id:i?.inboundRTP.id,ssrc:i?.inboundRTP.ssrc,mediaType:i?.inboundRTP.mediaType??i?.inboundRTP.kind,bytes:Nt(t[e]?.recv,(e=>e.inboundRTP.bytesReceived),r),packets:Nt(t[e]?.recv,(e=>e.inboundRTP.packetsReceived),r),packetsLost:Nt(t[e]?.recv,(e=>e.inboundRTP.packetsLost),r),codec:i?.codec?.mimeType.split("/")[1],codecReport:i?.aggregated?.codecReport,framesDecoded:Nt(t[e]?.recv,(e=>e.inboundRTP.framesDecoded),r),height:Nt(t[e]?.recv,(e=>e.inboundRTP.frameHeight),r),width:Nt(t[e]?.recv,(e=>e.inboundRTP.frameWidth),r),frameRate:Nt(t[e]?.recv,(e=>e.extensions?.frameRateReceived),r)}),send:ct({id:n?.outboundRTP.id,ssrc:n?.outboundRTP.ssrc,mediaType:n?.outboundRTP.mediaType??n?.outboundRTP.kind,bytes:Nt(t[e]?.send,(e=>e.outboundRTP.bytesSent),r),packets:Nt(t[e]?.send,(e=>e.outboundRTP.packetsSent),r),packetsLost:Nt(t[e]?.send,(e=>e.remoteInboundRTP?.packetsLost),r),codec:n?.codec?.mimeType.split("/")[1],framesEncoded:Nt(t[e]?.send,(e=>e.outboundRTP.framesEncoded),r),heightInput:n?.mediaSource?.height,widthInput:n?.mediaSource?.width,height:Nt(t[e]?.send,(e=>e.outboundRTP.frameHeight),r),width:Nt(t[e]?.send,(e=>e.outboundRTP.frameWidth),r),frameRate:Nt(t[e]?.send,(e=>e.extensions?.frameRateSent),r)})})}function pk(e,t,i,n){const r=t?.codec?.mimeType.split("/");return ct({recv:ct({id:t?.inboundRTP.id,ssrc:t?.inboundRTP.ssrc,mediaType:t?.inboundRTP.mediaType??t?.inboundRTP.kind,bytes:Nt(e.audio?.recv,(e=>e.inboundRTP.bytesReceived),n),packets:Nt(e.audio?.recv,(e=>e.inboundRTP.packetsReceived),n),packetsLost:Nt(e.audio?.recv,(e=>e.inboundRTP.packetsLost),n),codec:r?.[r?.length-1],audioLevel:Nt(e.audio?.recv,(e=>Math.floor(65535*e.inboundRTP.audioLevel)),n)}),send:ct({id:i?.outboundRTP.id,ssrc:i?.outboundRTP.ssrc,mediaType:i?.outboundRTP.mediaType??i?.outboundRTP.kind,bytes:Nt(e.audio?.send,(e=>e.outboundRTP.bytesSent),n),packets:Nt(e.audio?.send,(e=>e.outboundRTP.packetsSent),n),packetsLost:Nt(e.audio?.send,(e=>e.remoteInboundRTP?.packetsLost),n),codec:i?.codec?.mimeType.split("/")[1],audioLevel:Nt(e.audio?.send,(e=>Math.floor(65535*e.aggregated.audioLevel)),n)})})}var gk=class{constructor(e,t){this.rootRef=e,this.configProvider=t}get rootCopy(){return lt(this.rootRef)}get rawRootRef(){return this.rootRef}getSessionTelemetry(e){const t=this.rootRef.sessions.find((t=>t.sessionId===e)),i={metrics:{},Extensions:{}};if(!t)return;const n=Pt();try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,n=e?.terminationTime??0,r=t.webrtcSessions[t.webrtcSessions.length-1];i.metrics=function(e,t,i,n){const r=e.webrtcSessions[e.webrtcSessions.length-1];return ct({MediaLegId:e.mediaLegId,CreationTime:tk(e.creationTime),CallNumber:e.callNumber,SessionId:e.sessionId,MultiParty:e.isMultiParty,ErrorType:e.error?.type??"none",ErrorDetail:e.error?.detail??"none",IncompatibleOffer:e.error?.type===Qe.MEDIA_ERROR.incompatibleOffer,TerminationTime:tk(e.terminationTime),TerminationReason_code:e.terminationReason?.code,TerminationReason_subCode:e.terminationReason?.subCode,TerminationReason_phrase:e.terminationReason?.phrase,TerminationReason_remoteTerminated:e.terminationReason?.remoteTerminated,TerminationReason_clientReasonPhrase:e.terminationReason?.clientReasonPhrase,TerminationReason_clientReasonSubCode:e.terminationReason?.clientReasonSubCode,CallDuration:tk(e.duration),IceInitTime:tk(e.iceInitTime),IceConnectedStateTime:tk(e.iceConnectedStateTime),NegotiationCount:e.negotiationCount,RejectedNegotiationCount:e.rejectedNegotiationCount,InitialNegotiationCompleted:e.initialNegotiationCompleted,InitialNegotiationType:e.initialNegotiationType,FinalAnswerTime:tk(e.finalAnswerTime),TransportReconnectedCount:e.transportReconnectedCount,RollbackNegotiation:JSON.stringify(e.rollbackNegotiation),Relay:e.relay?JSON.stringify(e.relay):void 0,ActiveModalities:JSON.stringify(e.activeModalities),AllowedAudioSend:e.allowedAudioSend,AllowedVideoSend:e.allowedVideoSend,AllowedScreensharingSend:e.allowedScreensharingSend,RelayManager:JSON.stringify(e.relayTimers),AuthTokenStats:JSON.stringify(e.authTokenFetcherStats),CallMutedRatio:tk(e.callMutedRatio),CallOsMuted:tk(e.callOsMuted),CallHwSilent:tk(e.callHwSilent),CallSwMuted:tk(e.callSwMuted),CallSpeakerMuted:tk(e.callSpeakerMuted),CallIsSpeaking:tk(e.callIsSpeaking),DtmfSuccess:e.dtmfSuccessCount,DtmfFailure:e.dtmfFailureCount,ReconnectInProgress:e.reconnect?.isReconnecting,RetargetIncomingCount:e.reconnect?.retargetCount.incoming,RetargetOutgoingCount:e.reconnect?.retargetCount.outgoing,RetargetCompletedCount:e.reconnect?.retargetCount.completed,RetargetRejectedCount:e.reconnect?.retargetCount.rejected,EscalationAttemptedCount:e.reconnect?.escalationCount.attempted,EscalationCompletedCount:e.reconnect?.escalationCount.completed,EscalationRejectedCount:e.reconnect?.escalationCount.rejected,ReconnectAttemptedCount:e.reconnect?.reconnectCount.attempted,ReconnectConnectedCount:e.reconnect?.reconnectCount.connected,ReconnectAttempts:JSON.stringify(kt(Et(e.reconnect?.records,n.config.diagnostics.telemetryLimits.numReconnects),"startTime",e.creationTime)),NetworkEvents:JSON.stringify(kt(Et(e.reconnect?.tmpRecords,n.config.diagnostics.telemetryLimits.numNetworkEvents),"startTime",e.creationTime)),NoIceCandidatesGoodEventCount:e.noIceCandidatesEventCount.good,NoIceCandidatesBadEventCount:e.noIceCandidatesEventCount.bad,NoRelayIceCandidatesGoodEventCount:e.noRelayIceCandidatesEventCount.good,NoRelayIceCandidatesBadEventCount:e.noRelayIceCandidatesEventCount.bad,MicrophoneInUseGoodEventCount:e.microphoneInUseEventCount.good,MicrophoneInUseBadEventCount:e.microphoneInUseEventCount.bad,CameraInUseGoodEventCount:e.cameraInUseEventCount.good,CameraInUseBadEventCount:e.cameraInUseEventCount.bad,CameraFreezeStartEventCount:e.cameraFreezeEventCount.start,CameraFreezeEndEventCount:e.cameraFreezeEventCount.end,NetworkRecvGood:e.networkRecvUFD.good,NetworkRecvGoodRatio:e.networkRecvUFD.goodRatio,NetworkRecvPoor:e.networkRecvUFD.poor,NetworkRecvPoorRatio:e.networkRecvUFD.poorRatio,NetworkRecvBad:e.networkRecvUFD.bad,NetworkRecvBadRatio:e.networkRecvUFD.badRatio,NetworkSendGood:e.networkSendUFD.good,NetworkSendGoodRatio:e.networkSendUFD.goodRatio,NetworkSendPoor:e.networkSendUFD.poor,NetworkSendPoorRatio:e.networkSendUFD.poorRatio,NetworkSendBad:e.networkSendUFD.bad,NetworkSendBadRatio:e.networkSendUFD.badRatio,Connection_Downlink:Ot(r.networkInfo,(e=>e.downlink)),Connection_EffectiveType:Ot(r.networkInfo,(e=>e.effectiveType)),Connection_Rtt:Ot(r.networkInfo,(e=>e.rtt)),Connection_SaveData:It(r.networkInfo)?.saveData,RawOutputAudioAccessAttempted:e.rawMedia.audio.recv.numAttempts,RawOutputAudioAccessDurationRatio:e.rawMedia.audio.recv.durationRatio,RawInputAudioOverrideAttempted:e.rawMedia.audio.send.numAttempts,RawInputAudioOverrideDurationRatio:e.rawMedia.audio.send.durationRatio,UFDs:JSON.stringify(kt(Et(e.ufds,n.config.diagnostics.telemetryLimits.numUFDs),"timestamp",e.creationTime)),MediaQosEnabled:i.configuration.mediaConfig?.enableMediaQoS??!1,PortRangeConfigured:!!i.configuration.mediaConfig?.mediaPortRanges,hardwareConcurrency:i.configuration.userAgentConfig.hardwareConcurrency,ETag:e.ETag,ConfigIds:e.configIds,GPUName:i.configuration.userAgentConfig.unmaskedGlRenderer,PermissionStates:JSON.stringify(i.deviceManager.permissionStates),DeviceList:JSON.stringify(i.deviceManager.deviceList),DeviceListDebug:JSON.stringify(i.deviceManager.deviceDebugStrings),DevicesChangeCount:e.deviceManager.devicesChangeCount,DevicesPollChangeCount:e.deviceManager.devicesPollChangeCount,DeviceSelectionChangeCount:e.deviceManager.deviceSelectionChangeCount,DeviceSelectionChangeFromInterfaceCount:e.deviceManager.deviceSelectionChangeCountFromInterface,DevicesCount:JSON.stringify(i.deviceManager.devicesCount),UsedMicrophone:i.deviceManager.usedDevices?.microphone,UsedSpeaker:i.deviceManager.usedDevices?.speaker,UsedCamera:i.deviceManager.usedDevices?.camera,DeviceEvents:JSON.stringify(kt(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),VideoEffects:JSON.stringify(kt(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),AudioEffects:JSON.stringify(kt(i.deviceManager.audioEffectsEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),MediaByPassEnabled:!!i.configuration.mediaConfig.enableMediaBypass,CallConstraints:JSON.stringify(n.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(ik(e.dominantSpeaker,e.terminationTime))})}(t,n,this.rootRef,this.configProvider),i.Extensions=function(e,t,i){const n=e.aggregatedModalityStats,r=It(n.audio?.recv),a=It(n.audio?.send),s=It(n.video?.recv),o=It(n.video?.send),l=It(n.sharing?.recv),c=It(n.sharing?.send),d=i=>i&&Et(lt(i).map((i=>kt(Et(i.events,t.config.diagnostics.telemetryLimits.numCapabilitiesApplied,1),"timestamp",e.startTime))),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),u=d(e.qualityManager?.videoMaxCapabilitiesEvents),h=d(e.qualityManager?.videoMaxCapabilitiesErrors),p=d(e.qualityManager?.sharingMaxCapabilitiesEvents),g=d(e.qualityManager?.sharingMaxCapabilitiesErrors),m="REMB"!==e.bweType?e.bandwidthReport:void 0,f="REMB"===e.bweType?e.bandwidthReport:void 0,v=[],S=[];return e.statsOnSubscribed.video?.forEach((e=>v.push(e))),e.statsOnSubscribed.sharing?.forEach((e=>S.push(e))),ct({BundlePolicy:e.bundlePolicy,FakeIceCandidate:e.fakeIceCandidate,H264_available_profiles:JSON.stringify(e.H264Profiles),IceConnectionState:e.iceConnectionState,IceConnectionStatePrevious:e.iceConnectionStatePrevious,IceServers:e.iceServers,IceTransportPolicy:e.iceTransportPolicy,NegotiatedSrtp:JSON.stringify(e.negotiatedSrtp),OfferedSrtp:JSON.stringify(e.offeredSrtp),RelayCandidate:e.relayCandidate,SdpSemantics:e.sdpSemantics,iceCandidateErrors:JSON.stringify(e.iceCandidateErrors),SignalingState:e.signalingState,SignalingStatePrevious:e.signalingStatePrevious,WebRTCStats_statsErrors:JSON.stringify(i),MaxSessionBandwidth:e.maxSessionBandwidth,Bandwidth_uplinkStabilizationTime:JSON.stringify(e.bwStabilizationTime),Bandwidth_downlinkStabilizationTime:JSON.stringify(e.bwDownlinkStabilizationTime),totalVideoControlMessages:e.qualityManager?.numVideoControlMessages,outOfOrderVideoControlMessages:e.qualityManager?.numOutOfOrderVideoControlMessages,webcamFreezeIntervals:e.qualityManager?.numWebcamFreezeIntervals,processedStreamFreezeIntervals:e.qualityManager?.numProcessedStreamFreezeIntervals,IPAddress:e.IPAddress??"none",ReflexiveLocalIP:e.reflexiveLocalIP??"none",NumberOfInterfaces:e.numInterfaces,StartTime:e.startTime,EndTime:e.endTime,AudioTransportRecvBitrate:r?.transport?.extensions?.recvBWAvg,AudioTransportSendBitrate:r?.transport?.extensions?.sendBWAvg,AudioPayloadRecvBitrate:r?.aggregated?.bitrateAvg,AudioPayloadSendBitrate:a?.aggregated?.bitrateAvg,VideoPayloadRecvBitrate:s?.aggregated?.bitrateAvg,VideoPayloadSendBitrate:o?.aggregated?.bitrateAvg,WebRTCStats_bweStat_googAvailableReceiveBandwidth:Ot(n.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate))??Ot(n.video?.send,(e=>e.transport?.selectedCandidatePair?.availableIncomingBitrate)),WebRTCStats_bweStat_googAvailableSendBandwidth:Ot(n.video?.send,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate))??Ot(n.video?.recv,(e=>e.transport?.selectedCandidatePair?.availableOutgoingBitrate)),ReportedSendBWMax:e.reportedSendBandwidthMax,ReportedSendBWMin:e.reportedSendBandwidthMin,Bandwidth_jumpsHistogram:JSON.stringify(o?.transport?.extensions?.bwJumpsHistogram),StartCallBWESendSide:JSON.stringify(m?.startOfTheCall),EndCallBWESendSide:JSON.stringify(m?.endOfTheCall),BWEStdSendSide:JSON.stringify(m?.std),BwPercentilesSendSide:JSON.stringify(m?.bwPercentiles),AvgBwSendSide:JSON.stringify(m?.avgBwe),StartCallBWE:JSON.stringify(f?.startOfTheCall),EndCallBWE:JSON.stringify(f?.endOfTheCall),BWEStd:JSON.stringify(f?.std),BwPercentiles:JSON.stringify(f?.bwPercentiles),AvgBw:JSON.stringify(f?.avgBwe),WebRTCStats_ssrc:ct({audio:UM(n,r,a),video:BM("video",n,s,o),sharing:BM("sharing",n,l,c)}),Audio_recv_jitterBufferAvgSize:r?.aggregated?.avgJitterBufferSize,Audio_recv_packetsLostRateMax:r?.aggregated?.lossRateMax,Audio_recv_jitterAvg:r?.aggregated?.jitterAvg,Audio_recv_networkAvgLossRate:r?.aggregated?.networkAvgLossRate,Audio_send_rttAvg:a?.aggregated?.rttAvg&&Ct(1e3*a.aggregated.rttAvg),Audio_send_rttMax:a?.aggregated?.rttMax&&Ct(1e3*a.aggregated.rttMax),Audio_send_RawInputVolume:Ot(n.audio?.send,(e=>e.aggregated?.rawInputVolume)),Audio_send_packetsLostRateMax:a?.aggregated?.lossRateMax,Audio_send_presentationAPIUserDuration:e.presentationAPIUserDuration,Audio_send_presentationDuration:e.presentationAudioDuration,Video_recv_DurationSeconds:s?.aggregated?.duration,Video_recv_FreezeHistogram:JSON.stringify(s?.aggregated?.freezeCountHistogram),Video_recv_FreezeTimestamps:JSON.stringify(Dt(s?.aggregated?.freezeTimestampsHistogram,e.startTime)),Video_recv_LongestFreezeDuration:s?.aggregated?.longestFreeze,Video_recv_OngoingFreeze:s?.extensions?.isFrozen,Video_recv_OngoingFreezeDuration:s?.aggregated?.ongoingFreezeDuration,Video_recv_TotalFreezeDuration:s?.aggregated?.totalFreezeDuration,Video_recv_RecvAvgFreezeDuration:s?.aggregated?.avgFreezeDuration,Video_recv_NumResolutionSwitches:s?.aggregated?.numResolutionSwitches,Video_recv_ResolutionDurations:JSON.stringify(s?.aggregated?.resolutionDurations),Video_recv_StreamsMax:e.recvVideoStreamCount.max,Video_recv_StreamsMin:e.recvVideoStreamCount.min,Video_recv_StreamsMode:e.recvVideoStreamCount.mode,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Video_recv_bitrateAvg:s?.aggregated?.bitrateAvg,Video_recv_bitrateMax:s?.aggregated?.bitrateMax,Video_recv_frameRateAvg:s?.aggregated?.avgFrameRate,Video_recv_jitterBufferAvgSize:s?.aggregated?.avgJitterBufferSize,Video_recv_packetsLostRateMax:s?.aggregated?.lossRateMax,Video_recv_isRenderingEvents:JSON.stringify(Et(e.remoteVideoManager?.isRenderingEvents.video,t.config.diagnostics.telemetryLimits.numIsRenderingEvents)),Video_recv_FpsHarmonicAverage:s?.aggregated?.fpsHarmonicAverage,Video_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.video?.toString(),Video_recv_statsOnSubscribed:JSON.stringify(v),Video_SubscriptionEvents:JSON.stringify(kt(e.subscriptionManager?.video.events,"ts",e.startTime)),Video_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.video.counters),Video_send_CaptureFramerateAvg:o?.aggregated?.captureFramerateAvg,Video_send_DurationSeconds:o?.aggregated?.duration,Video_send_FreezeIntervals:o?.extensions?.captureFreezeIntervalsCount,Video_send_MaxCapabilities:JSON.stringify(u),Video_send_MaxCapabilitiesErrors:JSON.stringify(h),Video_send_OvershootDurations:JSON.stringify({fs:o?.aggregated?.totalFsOvershootDuration,fps:o?.aggregated?.totalFpsOvershootDuration,br:o?.aggregated?.totalBrOvershootDuration}),Video_send_OvershootEvents:JSON.stringify(kt(o?.aggregated.overshootEvents,"timestamp",e.startTime)),Video_send_QpAvg:o?.aggregated?.qpAvg,Video_send_bitrateAvg:o?.aggregated?.bitrateAvg,Video_send_bitrateMax:o?.aggregated?.bitrateMax,Video_send_frameRateAvg:o?.aggregated?.frameRateAvg,Video_send_AllocateBWAvg:o?.aggregated?.bweAvg,Video_send_CameraOpenWidth:o?.extensions?.cameraOpenResolution?.width,Video_send_CameraOpenHeight:o?.extensions?.cameraOpenResolution?.height,Video_send_packetsLostRateMax:o?.aggregated?.lossRateMax,Video_send_resolutionSwitches:JSON.stringify(o?.aggregated?.resolutionSwitches),Sharing_recv_DurationSeconds:l?.aggregated?.duration,Sharing_recv_FreezeHistogram:JSON.stringify(l?.aggregated?.freezeCountHistogram),Sharing_recv_FreezeTimestamps:JSON.stringify(Dt(l?.aggregated?.freezeTimestampsHistogram,e.startTime)),Sharing_recv_LongestFreezeDuration:l?.aggregated?.longestFreeze,Sharing_recv_OngoingFreeze:l?.extensions?.isFrozen,Sharing_recv_TotalFreezeDuration:l?.aggregated?.totalFreezeDuration,Sharing_recv_RecvAvgFreezeDuration:l?.aggregated?.avgFreezeDuration,Sharing_recv_NumResolutionSwitches:l?.aggregated?.numResolutionSwitches,Sharing_recv_ResolutionDurations:JSON.stringify(l?.aggregated?.resolutionDurations),Sharing_recv_StreamsMax:e.recvVideoStreamCount.max,Sharing_recv_StreamsMin:e.recvVideoStreamCount.min,Sharing_recv_StreamsMode:e.recvVideoStreamCount.mode,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_bitrateAvg:l?.aggregated?.bitrateAvg,Sharing_recv_bitrateMax:l?.aggregated?.bitrateMax,Sharing_recv_frameRateAvg:l?.aggregated?.avgFrameRate,Sharing_recv_jitterBufferAvgSize:l?.aggregated?.avgJitterBufferSize,Sharing_recv_packetsLostRateMax:l?.aggregated?.lossRateMax,Sharing_recv_FpsHarmonicAverage:l?.aggregated?.fpsHarmonicAverage,Sharing_recv_isRenderingEvents:JSON.stringify(Et(e.remoteVideoManager?.isRenderingEvents.sharing,t.config.diagnostics.telemetryLimits.numIsRenderingEvents)),Sharing_recv_PreferredResolution:e.remoteVideoManager?.preferredResolution.sharing?.toString(),Sharing_recv_statsOnSubscribed:JSON.stringify(S),Sharing_SubscriptionEvents:JSON.stringify(kt(e.subscriptionManager?.sharing.events,"ts",e.startTime)),Sharing_SubscriptionCounters:JSON.stringify(e.subscriptionManager?.sharing.counters),Sharing_send_CaptureFramerateAvg:c?.aggregated?.captureFramerateAvg,Sharing_send_DurationSeconds:c?.aggregated?.duration,Sharing_send_MaxCapabilities:JSON.stringify(p),Sharing_send_MaxCapabilitiesErrors:JSON.stringify(g),Sharing_send_OvershootDurations:JSON.stringify({fs:c?.aggregated?.totalFsOvershootDuration,fps:c?.aggregated?.totalFpsOvershootDuration,br:c?.aggregated?.totalBrOvershootDuration}),Sharing_send_resolutionSwitches:c?.aggregated?.resolutionSwitches,Sharing_send_OvershootEvents:JSON.stringify(kt(c?.aggregated.overshootEvents,"timestamp",e.startTime)),Sharing_send_QpAvg:c?.aggregated?.qpAvg,Sharing_send_bitrateAvg:c?.aggregated?.bitrateAvg,Sharing_send_bitrateMax:c?.aggregated?.bitrateMax,Sharing_send_frameRateAvg:c?.aggregated?.frameRateAvg,Sharing_send_AllocateBWAvg:c?.aggregated?.bweAvg,Sharing_send_packetsLostRateMax:c?.aggregated?.lossRateMax,multipleVideoStreams:JSON.stringify(kt(e.multiViewStats,"startTime",e.startTime)),ReportedReceiveBandwidth:e.reportedReceiveBandwidth,OvcToSubscriptions:JSON.stringify(e.ovcToSubscriptionEvents),EncodedStreamWorker:e.encodedStreamWorker,AudioCodecEvents:JSON.stringify(e.audioCodecEvents),HevcCodecSupport:JSON.stringify(e?.codecSupport),CallSetupTimeTracker:JSON.stringify(e.timerTrackerReport),InitialBWSeed:e.initialBWSeed,SentBWSeed:e.sentBWSeed,videoPerformanceEvent:JSON.stringify(e.videoPerformanceEvent),EarlyMedia_NumStatsPolls:e.earlyMediaNumStatsPolls})}(r,this.configProvider,t.statsErrors)}catch(e){t[DM].addStatsError("DiagnosticsReport:getSessionTelemetry",Be(e)),i.Extensions.WebRTCStats_statsErrors=JSON.stringify(t.statsErrors)}return i.metrics.ReportGenerationTimeMs=Ct(Pt()-n),i}getTeamsRealtimeTelemetry(e){const t=this.rootRef.sessions.find((t=>t.sessionId===e));if(t)try{const e=t.webrtcSessions[t.webrtcSessions.length-1],i=this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval;return function(e,t){const i=rk(e,"inactiveTracks"),n={channels:[]};return uk(e,t,n),i.length&&uk(i,void 0,n),n}(e.statsReports.slice(e.statsReports.length-i),this.rootRef.deviceManager.rawUsedDevices)}catch(e){throw t[DM].addStatsError("DiagnosticsReport:getRealTimeTelemetry",Be(e)),e}}getMediaSessionStats(e){const t=this.rootRef.sessions.find((t=>t.sessionId===e));if(t)try{const e=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,i=e?.terminationTime??0,n=t.webrtcSessions[t.webrtcSessions.length-1],r=n?.statsReports.length?n.statsReports[n.statsReports.length-1]:void 0,a=r?function(e){return{audio:{send:qM(e),recv:KM(e)},video:{send:JM(e),recv:YM(e)},screenShare:{send:QM(e),recv:ZM(e)},data:XM(e),transports:ek(e)}}(r):void 0;return a&&(a.extensions=function(e,t){const i=e.qualityManager&&Et(lt(e.qualityManager.videoMaxCapabilitiesEvents).map((i=>kt(Et(i.events,t.config.diagnostics.telemetryLimits.numCapabilitiesApplied,1),"timestamp",e.startTime))),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested),n=e.qualityManager&&Et(lt(e.qualityManager.sharingMaxCapabilitiesEvents).map((i=>kt(Et(i.events,t.config.diagnostics.telemetryLimits.numCapabilitiesApplied,1),"timestamp",e.startTime))),t.config.diagnostics.telemetryLimits.numCapabilitiesRequested);return ct({Video_SubscriptionEvents:JSON.stringify(kt(e.subscriptionManager?.video.events,"ts",e.startTime)),Sharing_SubscriptionEvents:JSON.stringify(kt(e.subscriptionManager?.sharing.events,"ts",e.startTime)),Video_send_MaxCapabilities:JSON.stringify(i),Sharing_send_MaxCapabilities:JSON.stringify(n),RelayCandidate:e.relayCandidate,Video_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameVideo,Sharing_recv_TimeToFirstFrame:e.remoteVideoManager?.firstTimeToFirstFrameSharing,Video_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartVideo,Sharing_recv_TimeToFirstFrameSinceSubscriptionStart:e.remoteVideoManager?.timeToFirstFrameSinceSubscriptionStartSharing})}(n,this.configProvider),a.metrics=function(e,t,i){return ct({DeviceEvents:JSON.stringify(kt(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>t)),"timestamp",e.creationTime)),IceConnectedStateTime:1e4*e.iceConnectedStateTime})}(t,i,this.rootRef)),a}catch(e){throw t[DM].addStatsError("DiagnosticsReport:getMediaSessionStats",Be(e)),e}}getDiagnosticsForE2eTests(e){const t=this.rootRef.sessions.find((t=>t.sessionId===e));let i={};if(t){try{const e=t.webrtcSessions[t.webrtcSessions.length-1],n=t.callNumber>1?this.rootRef.sessions.find((e=>t.callNumber-1===e.callNumber)):void 0,r=n?.terminationTime??0;i=function(e,t,i,n,r){const a=e.aggregatedModalityStats,s=It(a.audio?.recv),o=It(a.audio?.send),l=It(a.video?.recv),c=It(a.video?.send),d=It(a.sharing?.recv),u=It(a.sharing?.send),h=[],p=[];return e.statsOnSubscribed.video?.forEach((e=>h.push(e))),e.statsOnSubscribed.sharing?.forEach((e=>p.push(e))),ct({multipleVideoStreams:e.multiViewStats,WebRTCStats_ssrc:ct({audio:pk(a,s,o,r),video:hk("video",a,l,c,r),sharing:hk("sharing",a,d,u,r)}),CallSwMuted:1e3*t.callSwMuted,DeviceEvents:kt(i.deviceManager.deviceTelemetryEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime),VideoEffects:kt(i.deviceManager.videoEffectsEvents.filter((e=>e.timestamp>n)),"timestamp",t.creationTime)})}(e,t,this.rootRef,r,this.configProvider.config.diagnostics.collectionLimits.numSamplesForE2E)}catch(e){t[DM].addStatsError("DiagnosticsReport:getSessionTelemetry",Be(e))}return i}}},mk=class{constructor(e,t){this.configProvider=e,this.deviceManagerDiagnostics=t,this.root={creationTime:Date.now(),numTotalSessions:0,deviceManager:this.deviceManagerDiagnostics.getObjectRef(),configuration:{stackConfig:this.configProvider.stackConfig,defaultConfig:this.configProvider.defaultConfig,mediaConfig:{},userAgentConfig:{isAudioOutputSelectionSupported:this.configProvider.userAgentConfig.isAudioOutputSelectionSupported,isBrowserRollbackSupported:this.configProvider.userAgentConfig.isBrowserRollbackSupported,hardwareConcurrency:Bg.hardwareConcurrency,unmaskedGlRenderer:Bg.unmaskedGlRenderer,hasMediaApi:Bg.hasMediaApi(),hasCapabilitiesApi:Bg.hasCapabilitiesApi(),hasUnifiedPlanSupport:void 0},consoleOverrides:this.configProvider.consoleOverrides,fullConfig:lt(this.configProvider.config),ecsConfigUpdates:[]},browserInfo:ri(),sessions:[]},this.diagnosticsReport=new gk(this.root,this.configProvider),this.configProvider.on("newConfigReceived",((e,t,i)=>{this.root.configuration.ecsConfigUpdates.push({timestamp:Date.now(),etag:t,configIds:i,config:e})})),this.configProvider.on("configUpdated",(()=>{this.root.configuration.consoleOverrides=this.configProvider.consoleOverrides,this.root.configuration.fullConfig=lt(this.configProvider.config)}))}get reportGenerator(){return this.diagnosticsReport}get rootRef(){return this.root}set mediaConfig(e){this.root.configuration.mediaConfig=e}newSession(e,t,i){this.root.configuration.userAgentConfig.hasUnifiedPlanSupport=this.configProvider.mediaConfig.simulcastSessionEnabled;const n=new OM(i,e,this.diagnosticsReport,this.root.deviceManager,++this.root.numTotalSessions,t);return Tt(this.root.sessions,n.getObjectRef(),this.configProvider.config.diagnostics.collectionLimits.numSessions),n}},fk=class e{constructor(e,t){this.safe=e,this.unsafe=t,this.safe||(this.safe=this.unsafe)}warn(...e){this.unsafe.warn(...e)}error(...e){this.unsafe.error(...e)}debug(...e){this.unsafe.debug(...e)}info(...e){this.unsafe.info(...e)}createChild(t){return new e(this.safe.createChild(t),this.unsafe.createChild(t))}},vk=g,Sk=class{constructor(e){this.logger=e,this.extensionId="nkeimhogjdpnpccoofpliimaahmaaome",this.editorExtensionId="ncbjelpjchkpbikbpkcchkhkblodoama",this.logId="TeamsWebRTCLogs",this.loggingState="unknown",this.connectionCount=0,window.webRtcInternalsCollector=this}get isExtensionAvailable(){return"unavailable"!==this.loggingState}async updateSessionCount(e){this.isExtensionAvailable&&(0===this.connectionCount&&1===e?("stopped"===this.loggingState&&await this.discardLogs(),await this.initialStartLogging()):0===e&&await this.stopLogging(),this.connectionCount=e)}async collect(){return this.isExtensionAvailable?this.collectPromise?this.collectPromise:this.collectPromise=new Promise((async e=>{try{this.connectionCount>0&&(this.logger.safe.info(`Stopping logger for gathering, open connections: ${this.connectionCount}`),await this.stopLogging()),await this.storeLogs();const t=await this.gatherFromStorage();this.connectionCount>0&&await this.continueLogging(),e(t.length>0?t.join("\r\n"):"")}catch(t){this.logger.safe.error("Error while collecting logs",t),e(JSON.stringify(t))}this.collectPromise=void 0})):""}async initialStartLogging(){try{await this.startLogging()}catch(e){if(e?.includes("A log is already open"))try{const t=e.match(/State=(\w+)/);await this.cleanState(t?.[1]),await this.startLogging()}catch(e){this.logger.safe.error("Error while starting logging at cleanup phase",e),this.loggingState="unknown"}else this.logger.safe.error("Error while starting logging",e),this.loggingState="unavailable"}}async continueLogging(){try{await this.startLogging()}catch(e){this.logger.safe.error("Error while continuing logging",e),this.loggingState="stopped"}}async startLogging(){await this.sendMessage(this.extensionId,{method:"logging.start"}),this.logger.safe.info("Logging started"),this.loggingState="started"}async cleanState(e){try{if("started"===e)await this.stopLogging(),await this.discardLogs();else{if("stopped"!==e)throw new Error(`Unexpected logging state: ${e}`);await this.discardLogs()}}catch(e){this.logger.safe.error("Error while cleaning state",e)}}async stopLogging(){try{await this.sendMessage(this.extensionId,{method:"logging.stop"}),this.logger.safe.info("Logging stopped"),this.loggingState="stopped"}catch(e){this.logger.safe.error("Error while stopping logging",e)}}async discardLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.discard"}),this.logger.safe.info("Logs discarded"),this.loggingState="closed"}catch(e){this.logger.safe.error("Error while discarding logs",e)}}async storeLogs(){try{await this.sendMessage(this.extensionId,{method:"logging.store",logId:this.logId}),this.logger.safe.info(`Logs stored to ${this.logId}`),this.loggingState="closed"}catch(e){this.logger.safe.error("Error while storing logs",e)}}async gatherFromStorage(){const e=[];let t={offset:0};do{t=await this.sendMessage(this.editorExtensionId,{api:"getWebRtcLog",logId:this.logId,offset:t.offset}),e.push(t.data),this.logger.safe.info(`Batch gathered with offset: ${t.offset}, moreData: ${t.moreData}`)}while(t.moreData);return this.logger.safe.info("Finished gathering"),e}sendMessage(e,t){return new Promise(((i,n)=>{const r=chrome.runtime;r.sendMessage(e,t,(e=>{if(!e||e?.error){const i=e?JSON.stringify(e.error):r.lastError;n(`sendMessage ${JSON.stringify(t)} failed with error: ${i}`)}i(e)}))}))}},yk=(()=>{let e;return{getInstance:function(t,i){return i?.config.enableWebRtcInternalsLogs&&"EdgeAnaheim"===ri().name&&chrome?.runtime?(e||(e=new Sk(t)),e):(t.safe.info("WebRTC internal logging is disabled"),{collect:()=>Promise.resolve(""),updateSessionCount:()=>Promise.resolve()})}}})(),Ck=yk,_k=class{getId(){return 0}getDeviceId(){return Qe.EMPTY_DEVICE_ID}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return"display"}getType(){return 1}getIcon(e,t){return Promise.resolve(null)}},Ek=class{constructor(e){this.descr=e}getId(){return 0}getDeviceId(){return this.descr.browserId}getPreviewAsync(e,t){return Promise.resolve(null)}getDescription(){return this.descr.label}getType(){return 3}getIcon(e,t){return Promise.resolve(null)}},Tk=class{constructor(e){this.deviceManager=e,this.sharingSource=new _k}onScreensChanged(e){return{dispose:()=>{}}}enumerateScreensAsync(){return Promise.resolve([this.sharingSource])}enumerateWindowsAsync(){return Promise.resolve([])}async enumerateCamerasAsync(){return(await this.deviceManager.enumerateDevicesAsync()).filter((e=>"camera"===e.kind)).map((e=>new Ek(e)))}},bk=class{constructor(){this.data={records:[],tmpRecords:[],isReconnecting:!1,networkRecoveredCount:0,disconnectedRecoveredCount:0,reconnectCount:{attempted:0,connected:0},retargetCount:{incoming:0,outgoing:0,completed:0,rejected:0},escalationCount:{attempted:0,completed:0,rejected:0}}}registerState(e){const t="connected"===e?this.activeTmpRecord:this.getTmpRecord();t&&t.events[t.events.length-1]?.type!==e&&(t.events.push({type:e,time:Date.now()-t.startTime}),"networkOnline"===e?this.data.networkRecoveredCount++:"connected"===e&&this.data.disconnectedRecoveredCount++,"reconnect"!==e&&"connected"!==e||(t.endTime=Date.now()-t.startTime,this.activeTmpRecord=null))}registerReconnectAttempt(e){this.activeRecord&&(this.activeAttempt={direction:e,startTime:Date.now()-this.activeRecord.startTime,status:!1},this.data.isReconnecting=!0,this.activeRecord.attempts.push(this.activeAttempt))}registerReconnectAttemptStatus(e){"completed"===e&&(this.data.isReconnecting=!1),this.activeAttempt&&this.activeRecord&&(this.activeAttempt.endTime=Date.now()-this.activeRecord.startTime,this.activeAttempt.status="completed"===e)}registerReconnect(e){if(this.data.reconnectCount[e]++,this.data.isReconnecting="attempted"===e,"attempted"===e){if(this.activeRecord)return;this.activeRecord={startTime:Date.now(),attempts:[]},this.data.records.push(this.activeRecord)}else if("connected"===e){if(!this.activeRecord)return;this.activeTmpRecord&&this.registerState("connected"),this.activeRecord.endTime=Date.now()-this.activeRecord.startTime,this.activeRecord=void 0,this.activeAttempt=void 0}}registerRetarget(e){this.data.retargetCount[e]++}registerEscalation(e){this.data.escalationCount[e]++}getObject(){return this.data}getTmpRecord(){return(!this.activeTmpRecord||this.activeTmpRecord.endTime>0)&&(this.activeTmpRecord={startTime:Date.now(),events:[]},this.data.tmpRecords.push(this.activeTmpRecord)),this.activeTmpRecord}},Ik=class{constructor(){}process(e){return this.mediaLegId=e||this.mediaLegId||dt().toUpperCase(),this.mediaLegId}},wk=class{constructor(e,t){this.relayManager=e,this.diagnostics=t}initialize(){}setRelayOverride(){}async queryRelaysAsync(e){const t=await this.relayManager.queryRelaysAsync(e);return t.length>0&&(this.diagnostics.relay=t[0]),t}getStats(){return this.relayManager.getStats?.()??{unavailable:"1"}}getAuthTokenStats(){return this.relayManager.getAuthTokenStats()}},Rk=class{constructor(e,t,i){this.stats=e,this.diag=t,i&&t&&(i.reconnect=t.getObject())}registerState(e){this.diag?.registerState(e)}registerReconnectAttempt(e){this.stats.registerReconnectAttempt(e),this.diag?.registerReconnectAttempt(e)}registerReconnectAttemptStatus(e){switch(e){case"completed":this.stats.registerReconnectAttemptCompleted();break;case"rejected":this.stats.registerReconnectAttemptRejected()}this.diag?.registerReconnectAttemptStatus(e)}registerReconnect(e){switch(e){case"attempted":this.stats.registerReconnectAttempted();break;case"connected":this.stats.registerReconnectConnected()}this.diag?.registerReconnect(e)}registerRetarget(e){switch(e){case"completed":this.stats.registerRetargetCompleted();break;case"rejected":this.stats.registerRetargetRejected();break;case"incoming":this.stats.registerRetargetIncoming();break;case"outgoing":this.stats.registerRetargetOutgoing()}this.diag?.registerRetarget(e)}registerEscalation(e){switch(e){case"attempted":this.stats.registerEscalationStart();break;case"completed":this.stats.registerEscalationCompleted();break;case"rejected":this.stats.registerEscalationRejected()}this.diag?.registerEscalation(e)}},Ak=class{constructor(e){this.initialCallbacks=e,this.queueCallbacks={onTerminated:this.genCallback(this.initialCallbacks.onTerminated),onSessionErrorOccurred:this.genCallback(this.initialCallbacks.onSessionErrorOccurred),onNegotiationRequired:this.genCallback(this.initialCallbacks.onNegotiationRequired),onAudioStateChanged:this.genCallback(this.initialCallbacks.onAudioStateChanged),onAudioHwSilentChanged:this.genCallback(this.initialCallbacks.onAudioHwSilentChanged),onTransportDisconnected:this.genCallback(this.initialCallbacks.onTransportDisconnected),onTransportConnected:this.genCallback(this.initialCallbacks.onTransportConnected),onTransportInitialized:this.genCallback(this.initialCallbacks.onTransportInitialized),onTransportFailed:this.genCallback(this.initialCallbacks.onTransportFailed),onUpdateMediaDescriptionsRequired:this.genCallback(this.initialCallbacks.onUpdateMediaDescriptionsRequired),onTeamsRealtimeTelemetryReport:this.genCallback(this.initialCallbacks.onTeamsRealtimeTelemetryReport)},this.queue=[]}flush(){this.queue.forEach((e=>{e.method.apply(null,e.args)})),this.clear()}clear(){this.queue=[]}genCallback(e){return(...t)=>this.queue.push({method:e,args:t})}},Pk=class{constructor(e,t){this.relayConfig=e,this.logger=t}async ensureOnline(){if(0===this.relayConfig.length)return this.logger.safe.warn("No TURN servers defined"),0;if(this.probeDeferred)return this.probeDeferred.promise;this.logger.safe.info(`Starting TURN probes with ${JSON.stringify(this.relayConfig[0].urls)}`),this.checkStart=Date.now();let e=0;this.probeDeferred=Si();const t=async()=>{await this.performCheck()&&this.finalize()},i=()=>{t(),e<3e3&&(e+=1e3),this.probeTimer=setTimeout(i,e)};return i(),this.probeDeferred.promise}finalize(){this.probeTimer&&(clearTimeout(this.probeTimer),this.probeTimer=0),this.probeDeferred&&(this.probeDeferred.resolve(Date.now()-this.checkStart),this.probeDeferred=null)}dispose(){this.finalize()}async performCheck(){this.logger.safe.info("Probing...");const e=this.tryCreatePc();if(!e)return!1;e.createDataChannel("probe");const t=Si();function i(i){e.onicecandidate=void 0,e.close(),t.resolve(i)}let n=!1;return e.onicecandidate=e=>{const t=e.candidate;if(!t)return n||this.logger.safe.info("still offline"),void i(n);const r=t.type??nm(t.candidate).type;"srflx"!==r&&"relay"!==r||(this.logger.safe.info(`Back online through ${r} candidate`),n=!0,"srflx"===r&&(this.ipFromRelay=t.address,i(!0)))},await e.setLocalDescription(await e.createOffer()),t.promise}tryCreatePc(){try{return new Ug.window.RTCPeerConnection({iceServers:this.relayConfig})}catch(e){return this.logger.safe.info(`Failed to create PC, errCode=${e.code}`),null}}},Mk=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],a=i.fqdns&&i.fqdns.length>0,s=t.iceUdpAddressType,o=t.iceTcpAddressType,l=t.iceServerTransport;if(!r&&!a)return e;if(l.includes("udp")&&i.udpPort){const e=!a||"fqdn"!==s&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.udpPort}?transport=udp`)}if(l.includes("tcp")&&i.tcpPort){const e=!a||"fqdn"!==o&&r?r:i.fqdns[0];n.push(`turn:${e}:${i.tcpPort}?transport=tcp`)}return l.includes("tls")&&i.tlsPort&&a&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),kk=(e,t)=>e.reduce(((e,i)=>{const n=[],r=i.addresses&&i.addresses[0],a=i.fqdns&&i.fqdns.length>0,s=t.iceUdpAddressType,o=t.iceServerTransport;if(!r&&!a)return e;if(o.includes("udp")&&i.udpPort){const e=!a||"fqdn"!==s&&r?r:i.fqdns[0];n.push(`stun:${e}:${i.udpPort}`)}return o.includes("tls")&&i.tlsPort&&a&&n.push(`turns:${i.fqdns[0]}:${i.tlsPort}`),e.concat({urls:n,credential:i.password,username:i.username})}),[]),Dk=class{constructor(e,t,i,n,r,a,s,o){this.session=e,this.context=t,this.diagnostics=i,this.sessionOperationQueue=n,this.callback=r,this.sessionCallbacks=a,this.configProvider=s,this.relayManager=o,this.wasConnected=!1,this.isDisconnected=!1,this.isReconnectConference=!1,this.escalationType=0,this._isSignalingStable=!0,this.reconnectDelayTime=0,this._isReconnectScheduled=!1,this.isDisposing=!1,this.isWaitingForNetwork=!1,this.onOnline=async()=>{this.logger.safe.info("onOnline: Network is up"),this.diagnostics.registerState("networkOnline"),this.isOnlineDeferred?.resolve(),this.isOnlineDeferred=null},this.onOffline=()=>{this.logger.safe.info("onOffline: Network is down"),this.diagnostics.registerState("networkOffline"),this.isOnlineDeferred=km()},this.logger=t.getLogger().createChild("ReconnectManagerV2"),this.ufdManager=t.getUfdManager(),this.session.callbacks=a,this.reconnectManagerMessageQueue=new Ak(a),window.addEventListener("online",this.onOnline),window.addEventListener("offline",this.onOffline)}get isOnline(){return!this.isOnlineDeferred}async createRelayProber(){if(!this._relayProber){const e=Date.now(),t=kk(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config),i=Date.now()-e;this.logger.safe.info(`RelayProber configuration fetched in ${i} ms`),i>5e3&&this.diagnostics.registerState("relayConfigFetched"),this._relayProber=new Pk(t,this.logger.createChild("RelayProber"))}return this._relayProber}dispose(){this.isDisposing=!0,window.removeEventListener("online",this.onOnline),window.removeEventListener("offline",this.onOffline),this._relayProber?.dispose(),this.isOnlineDeferred?.reject(new Error("dispose")),this.reconnectTimer&&this.resetReconnectTimer()}get settings(){return(this.reconnectSession||this.session).getSessionConfig().config}getCurrentSession(){return this.reconnectSession||this.session}getMainSession(){return this.session||this.reconnectSession}getReconnectSession(){return this.reconnectSession}async onIceDisconnect(e){if(this.wasConnected)this.raiseReconnectEvent("Bad",e);else if(!this.settings.reconnectWithNoRelays&&!this.session.hasRelayCandidates())return void this.onReconnectFailed("no relays",e);if(this.isDisconnected=!0,!this.isReconnecting()&&!this.isWaitingForNetwork)return this.logger.safe.info(`[${e}] reconnect attempt after iceDisconnect error`),this.session.isFailed()&&this.diagnostics.registerState("failed"),this.diagnostics.registerReconnect("attempted"),this.reconnectAsync(e)}onTransportDisconnect(e){this.isDisconnected=!0,this.wasConnected&&(this.diagnostics.registerState("disconnected"),this.handleTmpConnectivityLoss(e))}onConnected(e){this.isDisconnected=!1,this.logger.safe.info(`[${e}] set allow UFD`),this.diagnostics.registerState("connected"),this.raiseReconnectEvent("Good",e),this.wasConnected=!0,this._relayProber?.finalize()}onNegotiationCompletedAsync(e){return this.logger.safe.info(`[${e}] handle negotiation completed`),this.setSignalingState(!0),this.isReconnecting()&&(this.diagnostics.registerRetarget("completed"),2===this.escalationType&&this.blockCurrentSession(e)),Promise.resolve()}async onSessionErrorOccurred(e,t){this.logger.safe.info(`[${t}] handle session error`,Be(e)),await this.rejectReconnect(t),this.isReconnectAllowed()?await this.scheduleReconnectRetry(t,!1,!1):this.callback.onSessionErrorOccurred(e,t,this.wasConnected)}onNegotiationRejection(e,t){this.logger.safe.info(`[${t}] handle negotiation rejection`),this.diagnostics.registerRetarget("rejected");const i=1===this.escalationType;return this.rejectReconnect(t).then((()=>{const n=e.type===Qe.RENEGOTIATION_ERROR.glare&&i;(e.type!==Qe.RENEGOTIATION_ERROR.glare||i)&&(this.isRecoverableError(e.type)||n?this.scheduleReconnectRetry(t,n,i):this.onReconnectFailed(Be(e),t))}))}async ensureNetwork(e){const t=this.isOnline;if(!this.isOnline){this.logger.safe.info(`[${e}] waiting for network...`);try{await this.isOnlineDeferred.promise}catch(t){return void this.logger.safe.info(`${e} call disposed while waiting for network`)}this.logger.safe.info(`[${e}] network seems up`)}if(this.isDisconnected){const i=await this.createRelayProber(),n=await i.ensureOnline();this.logger.safe.info(`[${e}] probing complete in ${n} ms`),this.diagnostics.registerState("relaysUp"),t&&n<1e3&&this.logger.safe.info(`[${e}] looks like network failed on remote side, recovery was quick`)}}oldSessionIsOnline(e){return!!this.session?.isConnected()&&(this.logger.safe.info(`[${e}] old session recovered`),this.isReconnecting()||this.diagnostics.registerReconnect("connected"),!0)}async waitForNetworkAndTryLightweightRecovery(e){const t=this.oldSessionIsOnline(e);if(t||!this.settings.reconnectWithProbes)return t;this.setReconnectTimer(),this.isWaitingForNetwork=!0;const i=this.getMaxNetworkWaitTime();return this.logger.safe.info(`[${e}] can wait up to ${i} ms`),await Promise.race([this.ensureNetwork(e),yi(i)]),this.isWaitingForNetwork=!1,this.session&&(this.session.isConnected()||this.session.isFailed()||(this.logger.safe.info(`[${e}] giving session a moment to recover`),await yi(this.settings.reconnectWaitTimeAfterProbe)),this.oldSessionIsOnline(e))?(this.resetReconnectTimer(),!0):this.checkIfTimerFailed(e)?(this.logger.safe.info(`[${e}] session reconnect timer reached during network checks`),!0):!!this.isDisposing&&(this.logger.safe.info(`[${e}] session is disposed`),!0)}reconnectAsync(e,t=!1,i=!1){return this.logger.safe.info(`[${e}] queueing reconnect, force=${t}, escalation=${i}`),this.diagnostics.registerReconnectAttempt(i?"local escalation":"out"),this._isReconnectScheduled=!0,i&&(this.escalationType=1),this.sessionOperationQueue.queueOperation((async()=>{if(this._isReconnectScheduled=!1,t||!await this.waitForNetworkAndTryLightweightRecovery(e))return this.isReconnecting()?(this.logger.safe.info(`[${e}] ongoing reconnect is in progress`),void this.sessionOperationQueue.completeCurrentOperation()):(this.diagnostics.registerState("reconnect"),await this.initReconnect(e),await this.reconnectSession.configureModalitiesAsync(this.getConfiguredModalities(),e),void this.sessionOperationQueue.completeCurrentOperation());this.sessionOperationQueue.completeCurrentOperation()}),e)}async acceptReconnectStartAsync(e,t){return this.logger.safe.info(`[${t}] accepting reconnect`),this.diagnostics.registerRetarget("incoming"),e?(this.escalationType=2,this.diagnostics.registerEscalation("attempted")):(!this.isReconnecting()&&this.isDisconnected?this.diagnostics.registerReconnect("attempted"):this.isReconnecting()&&await this.rejectReconnect(t),this.diagnostics.registerState("reconnect"),this.diagnostics.registerReconnectAttempt("in")),this.initReconnect(t)}acceptReconnectFinish(e){const t=this.getConfiguredModalities();return this.reconnectSession.configureModalitiesAsync(t,e).then((()=>t))}isReconnecting(){return!!this.reconnectSession}isReconnectScheduled(){return this._isReconnectScheduled}cleanUp(){this.sessionCallbacks=null,this.reconnectSession=null}async terminateAsync(e){try{await(this.session?.terminate(e,{}))}catch{}try{await this.terminateReconnectSessionAsync(e,!0)}catch{}this.cleanUp()}completeReconnect(e){return this.logger.safe.info(`[${e}] completing reconnect`),2===this.escalationType&&(this.unblockCurrentSession(),this.diagnostics.registerEscalation("completed")),this.escalationType=0,this.reconnectSession&&(this.context.config.isConference=this.isReconnectConference,this.disposeActiveSession(e),this.session=this.reconnectSession,this.reconnectManagerMessageQueue.clear(),this.diagnostics.registerReconnectAttemptStatus("completed"),this._isSignalingStable||this.diagnostics.registerRetarget("completed"),this.isDisconnected&&this.diagnostics.registerReconnect("connected"),this.resetReconnectTimer(),this.reconnectDelayTime=0,this.reconnectSession=null,this.negotiationPausePromise=null,this.session.callbacks=this.sessionCallbacks||{}),Promise.resolve()}async rejectReconnect(e){this.logger.safe.info(`[${e}] rejecting reconnect`),this.setSignalingState(!1),2===this.escalationType&&this.diagnostics.registerEscalation("rejected"),this.escalationType=0,this.reconnectSession&&(await this.terminateReconnectSessionAsync(e,!1),this.diagnostics.registerReconnectAttemptStatus("rejected")),this.session&&(this.reconnectManagerMessageQueue.flush(),this.session.callbacks=this.sessionCallbacks,this.unblockCurrentSession())}configureModalitiesAsync(e,t){this.lastKnownConfiguredModalities=e;const i=[];return this.session&&i.push(this.session.configureModalitiesAsync(e,t)),this.reconnectSession&&i.push(this.reconnectSession.configureModalitiesAsync(e,t)),Promise.all(i).then((()=>Promise.resolve()))}canSendDtmf(){return this.getMainSession().canSendDtmf()}getExtensionsManager(){return this.getMainSession().getExtensionsManager()}muteHold(e,t){this.getMainSession().muteHold(e,t)}muteInputAsync(e){return this.getMainSession().muteInputAsync(e)}unmuteInputAsync(e){return this.getMainSession().unmuteInputAsync(e)}muteOutputAsync(e){return this.getMainSession().muteOutputAsync(e)}unmuteOutputAsync(e){return this.getMainSession().unmuteOutputAsync(e)}_deviceSelectionChanged(){this.session&&this.session.deviceSelectionChanged(),this.reconnectSession&&this.reconnectSession.deviceSelectionChanged()}disposeActiveSession(e){if(this.session&&this.isReconnecting()){this.logger.safe.info(`[${e}] About to dispose current session...`);const t=this.session;return this.lastKnownConfiguredModalities=this.session.getConfiguredModalities(),t.callbacks=this.reconnectManagerMessageQueue.queueCallbacks,t.move(this.reconnectSession,e),this.session=null,t.terminate(e,{},!1)}return Promise.resolve()}registerRetargetOutgoing(){this.diagnostics.registerRetarget("outgoing")}isSignalingStable(){return this._isSignalingStable}getConfiguredModalities(){return this.getMainSession().getConfiguredModalities()||this.lastKnownConfiguredModalities}checkIfTimerFailed(e){return!(this.isReconnectAllowed()||this.session&&!this.session.isFailed()||(this.onReconnectFailed("the time limit was reached",e),0))}async scheduleReconnectRetry(e,t,i){const n=this.getReconnectDelayTime();if(this.logger.safe.info(`[${e}}] scheduling reconnect retry attempt in ${n}`),await yi(n),t||!this.checkIfTimerFailed(e))return this.reconnectAsync(e,i,i)}isRecoverableError(e){return Qe.RENEGOTIATION_ERROR.media===e||Qe.RENEGOTIATION_ERROR.signaling===e}async resetReconnectSession(e){this.logger.safe.info(`[${e}] Resetting reconnect session. Session exists: old: ${!!this.session}, new: ${!!this.reconnectSession}`),this.isReconnectConference=0!==this.escalationType||this.context.config.isConference;const t=0!==this.escalationType||this.context.config.isConference&&this.wasConnected&&!this.isDisconnected,i=this.getMainSession(),n=this.configProvider.getConfigView(this.isReconnectConference,i.getSessionConfig()),r=i.clone(t,n);r.callbacks={...this.sessionCallbacks,onTransportConnected:e=>{2!==this.escalationType&&this.completeReconnect(e),this.raiseReconnectEvent("Good",e),this.sessionCallbacks.onTransportConnected(e)}},this.session&&(this.session.callbacks={...this.reconnectManagerMessageQueue.queueCallbacks,onSessionErrorOccurred:(e,t)=>(e.type!==Qe.MEDIA_ERROR.iceConnectionError&&this.reconnectManagerMessageQueue.queueCallbacks.onSessionErrorOccurred(e,t),Promise.resolve())}),this.reconnectSession&&(this.reconnectSession.move(r,e),this.logger.safe.info(`[${e}] reconnect session still exists during reconnect clone operation`),await this.terminateReconnectSessionAsync(e,!1)),this.logger.safe.info(`[${e}] New session reset.`),this.reconnectSession=r}async initReconnect(e){this.logger.safe.info(`[${e}] initiate reconnect`),this.setReconnectTimer(),await this.resetReconnectSession(e),this.setSignalingState(!1),this.session&&(this.blockCurrentSession(e),await Promise.all([this.reconnectSession.muteInputAsync(e),this.reconnectSession.muteOutputAsync(e)]))}blockCurrentSession(e){this.negotiationPausePromise=this.session.pauseNegotiations(e)}unblockCurrentSession(){this.negotiationPausePromise&&(this.negotiationPausePromise.resolve(),this.negotiationPausePromise=null)}raiseReconnectEvent(e,t){this.ufdManager.signalEvent("NetworkReconnect",e,"Audio",!0,t)}async terminateReconnectSessionAsync(e,t){if(this.reconnectSession){const i=new Ak(this.sessionCallbacks);this.reconnectSession.callbacks={...i.queueCallbacks,onTerminated:t?this.sessionCallbacks.onTerminated:i.queueCallbacks.onTerminated},await this.reconnectSession.terminate(e,{},!1),i.clear(),this.reconnectSession=null}}setReconnectTimer(){const e=this.wasConnected?this.settings.reconnectTimeLimit:this.settings.initialReconnectTimeLimit;e>0&&!this.reconnectTimer&&(this.reconnectTimerStart=Date.now(),this.reconnectTimer=window.setTimeout((()=>this.resetReconnectTimer()),e))}resetReconnectTimer(){clearTimeout(this.reconnectTimer),this.reconnectTimer=null}isReconnectAllowed(){return!!this.reconnectTimer&&!this.isDisposing}getReconnectDelayTime(){return 1e3*Math.min(++this.reconnectDelayTime,this.settings.maxReconnectDelayTime)}getMaxNetworkWaitTime(){const e=this.reconnectTimerStart>0?Date.now()-this.reconnectTimerStart:0;return Math.max(this.settings.reconnectTimeLimit-e,0)}onReconnectFailed(e,t){this.callback.onSessionErrorOccurred({type:Qe.MEDIA_ERROR.iceConnectionError,detail:`Reconnect failed, error - ${Be(e)}`},t,this.wasConnected)}setSignalingState(e){this._isSignalingStable=e}async handleTmpConnectivityLoss(e){this.logger.safe.info(`[${e}] Session went into disconnected state, giving it ${this.settings.losingConnectivityTimeoutMs}ms to recover`),-1!==this.settings.losingConnectivityTimeoutMs&&(await yi(this.settings.losingConnectivityTimeoutMs),this.isDisconnected&&this.raiseReconnectEvent("Poor",e)),this.isDisconnected&&this.settings.reconnectOnDisconnect&&(this.logger.safe.info(`[${e}] Session is still down, triggering reconnect`),this.onIceDisconnect(e))}},Ok=class{constructor(e,t){this.stats=e,this.diagnostics=t}set mediaLegId(e){this.stats.setMediaLegId(e.process()),this.diagnostics&&(this.diagnostics.mediaLegId=e)}set isMultiParty(e){e&&this.stats.setMultiParty(),this.diagnostics&&(this.diagnostics.isMultiParty=e)}set allowedModalities(e){this.stats.setSendModalities(e),this.diagnostics&&(this.diagnostics.allowedModalities=e)}set sessionError(e){this.stats.setError(e),this.diagnostics&&(this.diagnostics.sessionError=e)}set finalAnswerTime(e){this.stats.setFinalAnswerTimestamp(e),this.diagnostics&&(this.diagnostics.finalAnswerTime=e)}set dtmfResult(e){this.stats.dtmfResult(e),this.diagnostics&&(this.diagnostics.dtmfResult=e)}set swMute(e){this.stats.setSwMute(e),this.diagnostics&&(this.diagnostics.swMute=e)}set speakerMute(e){this.stats.setSpeakerMute(e),this.diagnostics&&(this.diagnostics.speakerMute=e)}set hwSilent(e){this.stats.setHwSilent(e),this.diagnostics&&(this.diagnostics.hwSilent=e)}set isSpeaking(e){this.stats.setSpeakingState(e),this.diagnostics&&(this.diagnostics.isSpeaking=e)}set iceConnectedStateTimestamp(e){this.stats.setIceConnectedStateTimestamp(e),this.diagnostics&&(this.diagnostics.iceConnectedStateTimestamp=e)}set iceInitTime(e){this.stats.setIceInitTimestamp(e),this.diagnostics&&(this.diagnostics.iceInitTime=e)}set ETag(e){this.stats.setETag(e),this.diagnostics&&(this.diagnostics.ETag=e)}set configIds(e){this.stats.setConfigIds(e),this.diagnostics&&(this.diagnostics.configIds=e)}set relay(e){this.stats.setRelay(e),this.diagnostics&&(this.diagnostics.relay=e)}negotiationStart(e){switch(this.diagnostics?.negotiationStart(e),e){case"Offering":this.stats.negotiation.offering.started();break;case"Answering":this.stats.negotiation.answering.started()}}negotiationCompleted(e){this.stats.negotiation.current.completed(e),this.diagnostics?.negotiationCompleted(e)}negotiationRejected(){this.stats.negotiation.current.rejected(),this.diagnostics?.negotiationRejected()}registerTransportConnected(){this.stats.registerTransportConnected(),this.diagnostics?.registerTransportConnected()}registerTransportDisconnected(){this.stats.registerTransportDisconnected(),this.diagnostics?.registerTransportDisconnected()}registerTransportFailed(){this.stats.registerTransportFailed(),this.diagnostics?.registerTransportFailed()}registerRollbackEvent(e){this.stats.registerRollbackEvent(e),this.diagnostics?.registerRollbackEvent(e)}registerRawMediaAccess(e,t,i){"send"===t?this.stats.registerSetInputRawMedia(i):this.stats.registerOutputRawMediaAccess(),this.diagnostics?.registerRawMediaAccess(e,t,i)}registerQualityStateChangedEvent(e){this.stats.registerQualityStateChangedEvent(e),this.diagnostics?.registerQualityStateChangedEvent(e)}terminated(e){this.stats.terminated(e),this.diagnostics?.terminated(e)}},Nk=class{constructor(e){this.logger=e,this.operationQueue=null,this.currentOperationDeferred=null,this.operationQueue=new Hw(this.logger)}queueOperation(e,t=Te()){this.logger.safe.info(`[${t}] queueing operation`);const i=new Jh,n=this.operationQueue.add((()=>(this.currentOperationDeferred=i,e())),t);return this.operationQueue.add(i,t),n}completeCurrentOperation(){this.currentOperationDeferred&&(this.logger.safe.info("completing operation"),this.currentOperationDeferred.resolve())}},Lk=class extends qe{constructor(e,t,i,n,r,a,s,o=i.getLogger().createChild("SessionV2",t)){super(o),this.session=e,this.context=i,this.callback=n,this.statistics=r,this.configProvider=a,this.diagnostics=s,this.logger=o,this.audioStreamStates={[Qe.STREAMING_STATE.inactive]:[Qe.STREAMING_STATE.started,Qe.STREAMING_STATE.active,Qe.STREAMING_STATE.failed],[Qe.STREAMING_STATE.started]:[Qe.STREAMING_STATE.active,Qe.STREAMING_STATE.removed,Qe.STREAMING_STATE.stopped,Qe.STREAMING_STATE.failed],[Qe.STREAMING_STATE.active]:[Qe.STREAMING_STATE.removed,Qe.STREAMING_STATE.stopped,Qe.STREAMING_STATE.failed]},this.mediaLegId=new Ik,this.rejectedNegotiations=0,this.negotiationState=null,this.audioStreamState=Qe.STREAMING_STATE.inactive,this.deviceManagerDisposables=[],this.visibilityChangedHandler=()=>{if(this.logger.safe.debug(`document.visibilityState changed: ${document.visibilityState}`),"visible"===document.visibilityState&&this.pcClosedInfo){const e=this.pcClosedInfo;this.pcClosedInfo=null,Date.now()<e.timestamp+this.configProvider.config.reconnectWakeupTimeLimit?(this.logger.safe.info(`[${e.causeId}] start reconnect after wakeup`),this.startReconnect(e.causeId)):(this.logger.safe.info(`[${e.causeId}] terminate a call after wakeup because allowed time limit for reconnect exceeded`),this.endCallOnFailure(e.mediaError,e.causeId))}},this.ufdManager=i.getUfdManager(),this.ufdManagerDisposable=this.ufdManager.on("onQualityChanged",(e=>this.qualityChanged(e))),this.sessionOperationQueue=new Nk(this.logger),this.mediaLegId=new Ik,this.diagnosticsWrapper=new Ok(this.statistics,this.diagnostics),this.statistics.setId(t),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.diagnosticsWrapper.ETag=this.configProvider.ETag,this.diagnosticsWrapper.configIds=this.configProvider.ecsConfigIds,this.diagnosticsWrapper.isMultiParty=!!i.config.isConference,this.recoverableErrors=this.configProvider.config.recoverableMediaErrors.split(","),this.forceReconnectErrors=this.configProvider.config.forceReconnectErrors.split(",");const l=this.getSessionCallbacks();e.callbacks=l,e.relayManagerProvider=this,this.reconnectManager=new Dk(e,i,new Rk(this.statistics,this.diagnostics?new bk:void 0,this.diagnostics),this.sessionOperationQueue,this.getReconnectManagerCallbacks(),l,this.configProvider,this.getRelayManager()),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesPermissionChanged",(()=>this.diagnosticsWrapper.allowedModalities=this.getAllowedModalities()))),this.deviceManagerDisposables.push(this.deviceManager.on("onSelectedDevicesChanged",(()=>this.deviceSelectionChanged()))),this.deviceManagerDisposables.push(this.deviceManager.on("onDevicesChanged",((e,t)=>this.deviceListChanged(t)))),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount()),this.diagnostics&&(this.diagnostics.relayManager=this.getRelayManager()),this.ufdManager.applyCurrentState((e=>this.qualityChanged(e))),document.addEventListener("visibilitychange",this.visibilityChangedHandler),this.requestWakeLock()}async requestWakeLock(){if(Bg.isWakeLockSupported()&&this.configProvider.config.useWakeLockApi)try{this.wakeLock=await window.navigator.wakeLock.request("screen")}catch(e){this.logger.safe.info(`Wakelock request failed - ${e.message}`)}}enableTeamsRealTimeTelemetry(){this.realtimeTelemetryInterval||(this.logger.safe.info("teams realtime telemetry is enabled"),this.getSessionCallbacks().onTeamsRealtimeTelemetryReport(),this.realtimeTelemetryInterval=window.setInterval((()=>{this.getSessionCallbacks().onTeamsRealtimeTelemetryReport()}),1e3*this.configProvider.config.diagnostics.teamsRealtimeTelemetry.pollingInterval))}getMediaStatsReport(){return this.diagnostics?.mediaStatsReport}createOfferAsync(e){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Offering");try{const t=await this.getCurrentSession().createOfferAsync(e);return this.updateSelectedDevices(),t.mediaLegId=this.mediaLegId.process(t.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,this.reconnectManager.isReconnecting()&&!this.reconnectManager.isSignalingStable()&&(this.reconnectManager.registerRetargetOutgoing(),t.newOffer=!0),t}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),e)}setCallConstraints(e,t){return this.getCurrentSession().setCallConstraints(e,t)}processOfferAsync(e,t){return this.sessionOperationQueue.queueOperation((async()=>{this.diagnosticsWrapper.negotiationStart("Answering"),e.mediaLegId=this.mediaLegId.process(e.mediaLegId);try{e.newOffer&&await this.reconnectManager.acceptReconnectStartAsync(e.escalationOccurring,t);const i=await this.getCurrentSession().processOfferAsync(e,t);if(e.newOffer){const e=await this.reconnectManager.acceptReconnectFinish(t);return i.sharing===Qe.MEDIA_STATE.sendReceive&&(i.sharing=e.sharing===Qe.MEDIA_STATE.send?Qe.MEDIA_STATE.send:Qe.MEDIA_STATE.receive),i}return i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}),t)}async processAnswerAsync(e,t,i,n){try{return await this.getCurrentSession().processAnswerAsync(e,t,i,n)}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}async completeNegotiationAsync(e){this.rejectedNegotiations=0;try{const t=await this.getCurrentSession().completeNegotiationAsync(e);return this.negotiationState=t,this.diagnosticsWrapper.finalAnswerTime=Date.now(),this.diagnosticsWrapper.negotiationCompleted?.(t.activeModalities),await this.reconnectManager.onNegotiationCompletedAsync(e),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}ignoreNotReconnectError(e){return e.detail?.type!==Qe.MEDIA_ERROR.incompatibleOriginator}async rejectNegotiationAsync(e,t){this.logger.safe.info(`[${t}] rejectNegotiationAsync`,e);try{if(this.reconnectManager.isReconnecting()&&this.ignoreNotReconnectError(e))return await this.reconnectManager.onNegotiationRejection(e,t),this.registerNegotiationRejection(this.negotiationState),this.sessionOperationQueue.completeCurrentOperation(),this.negotiationState;{const i=await this.getCurrentSession().rejectNegotiationAsync(e,t,this.isRenegotiationAllowed(e.type));return this.sessionOperationQueue.completeCurrentOperation(),this.registerNegotiationRejection(i),i}}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}completeEscalationAsync(e){return this.reconnectManager.completeReconnect(e)}rejectEscalationAsync(e){return this.reconnectManager.rejectReconnect(e)}async terminate(e,t){this.logger.safe.info(`terminate reject reason: ${JSON.stringify(t||"")}`),this.registerVideoEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Video","StatsQuery")),this.registerAudioEffectsTelemetryEvent(this.deviceManager.effectsManager.getStats("Audio")),this.statistics.setPermissionStates(await this.deviceManager.getKnownPermissionStates()),this.diagnosticsWrapper.terminated(t);const i=()=>this.cleanUp();return this.reconnectManager.terminateAsync(e).then(i,i)}async getStatsAsync(e){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.getMainSession().getStatsAsync(e).then((e=>this.prepareStats(e)))}getLastKnownStats(e=!1){return this.configProvider.config.diagnostics.useForTelemetry?this.diagnostics?.telemetryReport:this.prepareStats(this.getMainSession().getLastKnownStats(e),e)}getCallTechnicalInfo(){return this.diagnostics?.realtimeTelemetryReport}async createAnswerAsync(e,t){try{const i=await this.getCurrentSession().createAnswerAsync(e,t);return this.updateSelectedDevices(),i.mediaLegId=this.mediaLegId.process(i.mediaLegId),this.diagnosticsWrapper.mediaLegId=this.mediaLegId,i}catch(e){throw this.diagnosticsWrapper.sessionError=e,e}}configureModalitiesAsync(e,t){return Ze(e,((t,i)=>{t||delete e[i]})),this.reconnectManager.configureModalitiesAsync(e,t)}getAllowedModalities(){return this.deviceManager.getAllowedModalities()}createRemoteRenderer(e){return this.getMainSession().createRemoteRenderer(e)}async sendDtmf(e){try{const t=await this.getMainSession().sendDtmf(e);return this.diagnosticsWrapper.dtmfResult=!0,t}catch(e){throw this.diagnosticsWrapper.dtmfResult=!1,e}}canSendDtmf(){return this.reconnectManager.canSendDtmf()}getExtensionsManager(){return this.reconnectManager.getExtensionsManager()}muteHold(e,t){this.reconnectManager.muteHold(e,t)}muteInputAsync(e){return this.diagnosticsWrapper.swMute=!0,this.ufdManager.setSwMute(!0),this.reconnectManager.muteInputAsync(e)}unmuteInputAsync(e){return this.diagnosticsWrapper.swMute=!1,this.ufdManager.setSwMute(!1),this.reconnectManager.unmuteInputAsync(e)}muteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!0,this.reconnectManager.muteOutputAsync(e)}unmuteOutputAsync(e){return this.diagnosticsWrapper.speakerMute=!1,this.reconnectManager.unmuteOutputAsync(e)}getAcceptedTypes(){return this.reconnectManager.getCurrentSession().getAcceptedTypes()}useNullAudioStreamClient(){this.getCurrentSession().useNullAudioStreamClient()}createAudioElement(e){this.getCurrentSession().createAudioElement(e)}getIncomingRawAudioStream(){return this.diagnosticsWrapper.registerRawMediaAccess("audio","recv",!0),this.getCurrentSession().getIncomingRawAudioStream()}getUnmixedAudioProvider(){return this.getCurrentSession().getUnmixedAudioProvider()}deviceSelectionChanged(){this.updateSelectedDevices(),this.reconnectManager._deviceSelectionChanged()}registerDeviceTelemetryEvent(e){this.getCurrentSession().onDeviceEvent(e),this.statistics.registerDeviceTelemetryEvent(e)}registerVideoEffectsTelemetryEvent(e){this.statistics.registerVideoEffectsTelemetryEvent(e)}registerAudioEffectsTelemetryEvent(e){this.statistics.registerAudioEffectsTelemetryEvent(e)}reconnectAsync(e,t=!1){return this.reconnectManager.reconnectAsync(e,!0,t)}isReconnecting(){return this.reconnectManager.isReconnecting()}getRelayManager(){return this.relayManager??(this.relayManager=new wk(this.context.maContext.getRelayManager(),this.diagnosticsWrapper))}getSessionConfig(){return this.reconnectManager.getCurrentSession().getSessionConfig()}getDiagnostics(){return this.diagnostics}getLocalMediaTrackId(e){return this.reconnectManager.getMainSession().getLocalMediaTrackId(e)}getSubscriptionManager(){return this.getCurrentSession().getSubscriptionManager()}getDisabledModalities(){return this.getCurrentSession().getDisabledModalities()}configureSpatialAudio(e,t){this.getCurrentSession().configureSpatialAudio(e,t)}setParticipantSpatialAudioPositions(e,t){this.getCurrentSession().setParticipantSpatialAudioPositions(e,t)}startMediaDescriptionsUpdateAsync(e){return this.getCurrentSession().startMediaDescriptionsUpdateAsync(e)}completeMediaDescriptionsUpdateAsync(e){return this.getCurrentSession().completeMediaDescriptionsUpdateAsync(e)}rejectMediaDescriptionsUpdateAsync(e,t){return this.getCurrentSession().rejectMediaDescriptionsUpdateAsync(e,t)}processNotification(e,t){this.session.processNotification(e,t)}async cleanUp(){this.callback=null,this.deviceManagerDisposables.forEach((e=>e.dispose())),this.ufdManagerDisposable.dispose(),this.reconnectManager.dispose(),this.pcClosedInfo=null,document.removeEventListener("visibilitychange",this.visibilityChangedHandler),window.clearInterval(this.realtimeTelemetryInterval),this.wakeLock&&(await this.wakeLock.release(),this.wakeLock=null)}updateSelectedDevices(){const e=this.deviceManager.getSelectedDevices(),t=e=>e?this.deviceManager.getDeviceNameAsync(e).then((e=>_t(e,this.configProvider.config.devices.piiSafeWords))):Promise.resolve("none");Promise.all([t(e.microphone),t(e.speaker),t(e.camera)]).then((([e,t,i])=>{this.statistics.setUsedDevices({microphone:e,speaker:t,camera:i})}))}getCurrentSession(){return this.reconnectManager.getCurrentSession()}getMainSession(){return this.reconnectManager.getMainSession()}setAudioStreamState(e,t,i){this.isAudioStateValid(e)?this.raiseAudioStateChanged(e,t,i):this.logger.safe.error(`[${t}] audio state transition is invalid: ${this.audioStreamState} -> ${e}`)}isAudioStateValid(e){return this.audioStreamStates[this.audioStreamState].indexOf(e)>=-1}raiseAudioStateChanged(e,t,i){if(this.logger.safe.info(`[${t}] audio state changed to ${e}`),this.callback.onAudioStateChanged){const t={content:"audio",direction:"receive",stream:e};this.callback.onAudioStateChanged(t,i)}}getReconnectManagerCallbacks(){return{onSessionErrorOccurred:(e,t,i)=>{this.isNetworkMediaError(e)&&!i&&this.ufdManager.raisePendingWhitelistingUFD(),this.endCallOnFailure(e,t)}}}isNetworkMediaError(e){return e.type===Qe.MEDIA_ERROR.iceConnectionError||e.type===Qe.MEDIA_ERROR.noNetworkError}isRecoverableMediaError(e){return this.recoverableErrors.includes(e.type)}startReconnect(e=Te()){return this.reconnectManager.onIceDisconnect(e)}shouldForceReconnect(e){return this.forceReconnectErrors.includes(e.type)}isUnexpectedPcClose(e){return e.type===Qe.MEDIA_ERROR.unexpectedClose}getSessionCallbacks(){return this.sessionCallbacks||(this.sessionCallbacks={onTerminated:()=>{this.logger.safe.warn("call onTerminated"),this.event("onTerminated").raise(this)},onSessionErrorOccurred:(e,t=Te())=>this.isUnexpectedPcClose(e)?this.handlePcClosed(e,t):this.shouldForceReconnect(e)?this.reconnectManager.reconnectAsync(t,!0):this.isRecoverableMediaError(e)?this.reconnectManager.isReconnecting()?this.reconnectManager.onSessionErrorOccurred(e,t):this.startReconnect(t):(this.endCallOnFailure(e,t),Promise.resolve()),onNegotiationRequired:e=>this.callback.onNegotiationRequired(e),onAudioHwSilentChanged:e=>{this.diagnosticsWrapper.hwSilent=e},onAudioStateChanged:(e,t)=>{this.setAudioStreamState(e,t)},onTransportConnected:(e=Te())=>{this.logger.safe.info(`[${e}] Transport connectivity established`),this.ufdManager.cancelPendingWhitelistingUFD(),this.reconnectManager.onConnected(e),this.diagnosticsWrapper.registerTransportConnected(),this.diagnosticsWrapper.iceConnectedStateTimestamp=Date.now(),this.callback?.onTransportConnected(e)},onTransportDisconnected:(e=Te())=>{this.logger.safe.warn(`[${e}] Transport connectivity lost`),this.reconnectManager.onTransportDisconnect(e),this.diagnosticsWrapper.registerTransportDisconnected()},onTransportFailed:()=>{this.diagnosticsWrapper.registerTransportFailed()},onTransportInitialized:()=>{this.diagnosticsWrapper.iceInitTime=Date.now()},onUpdateMediaDescriptionsRequired:e=>this.callback.onUpdateMediaDescriptionsRequired(e),onTeamsRealtimeTelemetryReport:()=>this.callback.onRealtimeTelemetryReport()}),this.sessionCallbacks}registerNegotiationRejection(e){this.rejectedNegotiations++,this.diagnosticsWrapper.negotiationRejected?.(),e.rollback&&this.diagnosticsWrapper.registerRollbackEvent(e.rollback)}isRenegotiationAllowed(e){return this.rejectedNegotiations<this.context.configProvider.config.renegotiationAttempts&&!this.reconnectManager.isReconnectScheduled&&(Qe.RENEGOTIATION_ERROR.signaling===e||Qe.RENEGOTIATION_ERROR.media===e)}prepareStats(e,t=!1){this.statistics.setDeviceList(this.deviceManager.getDeviceDescriptions(),this.deviceManager.getDeviceListDebugInfo()),this.statistics.setRelayManagerTimers(this.getRelayManager().getStats()),this.statistics.setVideoEffectStats(this.context.callDeviceManager.getDeviceManager("Video").effectsManager.getStats("Video","StatsQuery")),this.statistics.setAudioEffectStats(this.deviceManager.effectsManager.getStats("Audio"));const i=this.statistics.generateStatistics(e,this.mediaLegId,t);return this.configProvider.config.diagnostics.features.useNewerStatisticsMetrics&&(i.data.metrics=this.diagnostics?.telemetryReport?.data.metrics),i}deviceListChanged(e){e&&this.statistics.deviceChangedByPoll(),this.statistics.devicesChanged(),this.statistics.setDevicesCount(this.deviceManager.getDevicesCount())}qualityChanged(e){const t=e.deviceManagerId;!t||this.context.callDeviceManager.hasDevice(t)?this.callback?.onQualityChanged&&(this.diagnosticsWrapper.registerQualityStateChangedEvent(e),"DeviceSpeakWhileMuted"===e.type&&(this.diagnosticsWrapper.isSpeaking="Good"!==e.value),this.callback.onQualityChanged(e)):this.logger.info(`${t} - is not added to Call, skipping UFD.`)}endCallOnFailure(e,t,i){this.callback&&(this.callback.onSessionErrorOccurred&&this.callback.onSessionErrorOccurred(e,t),this.diagnosticsWrapper.sessionError=e,this.setAudioStreamState(Qe.STREAMING_STATE.failed,t,i))}async handlePcClosed(e,t){const i=this.configProvider.config.reconnectWakeupTimeLimit;return this.logger.safe.info(`[${t}] handle unexpected PC closed event`,`visibilityState=${document.visibilityState}, wakeupLimit=${this.configProvider.config.reconnectWakeupTimeLimit}`),"visible"===document.visibilityState?this.startReconnect(t):i?void(this.pcClosedInfo={timestamp:Date.now(),causeId:t,mediaError:e}):this.endCallOnFailure(e,t,"suspended")}},xk=class{constructor(e){this.creationTime=e,this.records=[],this.activeRecord=null,this.activeAttempt=null,this.reconnectState=!1}getReport(){return this.records.length?JSON.stringify(this.records):""}isReconnecting(){return this.reconnectState}onReconnectStart(){this.reconnectState=!0,this.activeRecord||(this.activeRecord={attempts:[],endTime:null,startTime:Date.now()-this.creationTime},this.records.push(this.activeRecord))}onReconnectAttempt(e){if(!this.activeRecord)return null;this.activeAttempt={direction:e,status:!1,endTime:null,startTime:this.getTimestamp()},this.reconnectState=!0,this.activeRecord.attempts.push(this.activeAttempt)}onReconnectConnected(){if(!this.activeRecord)return null;this.reconnectState=!1,this.activeRecord.endTime=this.getTimestamp(),this.activeRecord=this.activeAttempt=null}onReconnectCompleted(){this.reconnectState=!1,this.resolveReconnectAttempt(!0)}onReconnectRejected(){this.resolveReconnectAttempt(!1)}resolveReconnectAttempt(e){this.activeAttempt&&this.activeRecord&&(this.activeAttempt.status=e,this.activeAttempt.endTime=this.getTimestamp())}getTimestamp(){return Date.now()-this.creationTime-this.activeRecord.startTime}},Fk=window.navigator,Uk=class{constructor(e="Good"){this.stopWatches=[],this.currentLevel=e,this.getStopWatch(e).start()}updateLevel(e){this.currentLevel!==e&&(this.getStopWatch(this.currentLevel).stop(),this.currentLevel=e,this.getStopWatch(this.currentLevel).start())}getCount(e){const t=this.stopWatches[e];return t?t.count:0}getElapsed(e){const t=this.stopWatches[e];return t?t.elapsed:0}getStopWatch(e){let t=this.stopWatches[e];return t||(t=new LM,this.stopWatches[e]=t),t}},Bk=RegExp(/^((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]?)(\:[0-9]{2,5})?$/),Vk=RegExp(/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(:[0-9]{2,5})?$/),Hk=class{constructor(e,t,i){this.configProvider=e,this.callNumber=t,this.sessionDiagnostics=i,this.negotiation={offering:this.offering(),answering:this.answering(),current:this.current()},this.creationTime=Date.now(),this.negotiationCount=0,this.initialNegotiationCompleted=!1,this.activeModalities={},this.multiParty=!1,this.noIceCandidatesGoodEventCount=0,this.noIceCandidatesBadEventCount=0,this.noRelayIceCandidatesGoodEventCount=0,this.noRelayIceCandidatesBadEventCount=0,this.cameraInUseBadEventCount=0,this.cameraInUseGoodEventCount=0,this.microphoneInUseBadEventCount=0,this.microphoneInUseGoodEventCount=0,this.cameraFreezeStartEventCount=0,this.cameraFreezeEndEventCount=0,this.networkRecv=new Uk,this.networkSend=new Uk,this.retargetIncomingCount=0,this.retargetOutgoingCount=0,this.retargetCompletedCount=0,this.retargetRejectedCount=0,this.reconnectAttemptedCount=0,this.reconnectConnectedCount=0,this.escalationAttemptedCount=0,this.escalationCompletedCount=0,this.escalationRejectedCount=0,this.durationTimer=new LM,this.terminationReason={},this.terminationTime=0,this.sessionId="0",this.rejectedNegotiationCount=0,this.mediaError={type:"none",detail:"none"},this.incompatibleOffer=!1,this.dtmfSuccess=0,this.dtmfFailure=0,this.relay=null,this.relayManagerTimers=null,this.allowedAudioSend=!0,this.allowedVideoSend=!0,this.allowedScreensharingSend=!0,this.iceInitTime=0,this.finalAnswerTime=0,this.iceConnectedStateTime=0,this.usedDevices=null,this.deviceSelectionChangeCount=0,this.devicesChangeCount=0,this.devicesPollChangeCount=0,this.mute=new LM,this.osMute=new LM,this.hwSilent=new LM,this.isSpeaking=new LM,this.swMute=new LM,this.speakerMute=new LM,this.deviceTelemetryEvents=[],this.videoEffectsTelemetryEvents=new uA(this.configProvider.config.effectsTelemetryBufferSize),this.audioEffectsTelemetryEvents=new uA(this.configProvider.config.effectsTelemetryBufferSize),this.devicesCount=null,this.reconnectStats=new xk(this.creationTime),this.transportDisconnected=!1,this.transportReconnectedCount=0,this.ufds=[],this.mediaQosEnabled=!1,this.portRangeConfigured=!1,this.rollbackNegotiation=[],this.rawOutputAudioAccess={attempt:0,timer:new LM},this.rawInputAudioOverride={attempt:0,timer:new LM},this.connectionEffectiveTypeSeries=new uA(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionRttSeries=new uA(this.configProvider.config.navConnectionNumSamplesToCollect),this.connectionDownlinkSeries=new uA(this.configProvider.config.navConnectionNumSamplesToCollect),this.navigatorConnectionInterval=setInterval((()=>{const e=Fk?.connection;e&&("number"==typeof e.downlink&&this.connectionDownlinkSeries.add(e.downlink),"number"==typeof e.rtt&&this.connectionRttSeries.add(e.rtt),"number"==typeof e.effectiveType&&this.connectionEffectiveTypeSeries.add(e.effectiveType))}),this.configProvider.config.navConnectionPollingInterval),this.durationTimer.start()}terminated(e){this.terminationReason=lt(e),this.terminationTime=Date.now(),this.durationTimer.stop(),this.osMute.stop(),this.swMute.stop(),this.hwSilent.stop(),this.isSpeaking.stop(),this.mute.stop(),this.speakerMute.stop(),this.rawInputAudioOverride.timer.stop(),this.rawOutputAudioAccess.timer.stop(),clearInterval(this.navigatorConnectionInterval)}setMultiParty(){this.multiParty=!0}updateCommonMute(){this.swMute.isRunning||this.osMute.isRunning?this.mute.start():this.mute.stop()}setDeviceList(e,t){this.deviceList=e.map((e=>({label:_t(e.label,this.configProvider.config.devices.piiSafeWords),kind:e.kind}))),t&&(this.deviceDebugStrings=lt(t))}setPermissionStates(e){this.permissionStates=e}setSwMute(e){e?this.swMute.start():this.swMute.stop(),this.updateCommonMute()}setSpeakerMute(e){e?this.speakerMute.start():this.speakerMute.stop()}setHwSilent(e){e?this.hwSilent.start():this.hwSilent.stop()}setSpeakingState(e){e?this.isSpeaking.start():this.isSpeaking.stop()}setETag(e){this.ETag=e}setConfigIds(e){this.configIds=e}setVideoEffectStats(e){e&&this.videoEffectsTelemetryEvents.add(e)}setAudioEffectStats(e){e&&this.audioEffectsTelemetryEvents.add(e)}registerQualityStateChangedEvent(e){switch(e.type){case"NoNetwork":"Good"===e.value?this.noIceCandidatesGoodEventCount++:this.noIceCandidatesBadEventCount++;break;case"NetworkRelaysNotReachable":"Good"===e.value?this.noRelayIceCandidatesGoodEventCount++:this.noRelayIceCandidatesBadEventCount++;break;case"DeviceCaptureNotFunctioning":"Good"===e.value?this.microphoneInUseGoodEventCount++:this.microphoneInUseBadEventCount++;break;case"VideoCapturerDeviceStartFailed":"Good"===e.value?this.cameraInUseGoodEventCount++:this.cameraInUseBadEventCount++;break;case"DeviceCaptureMute":"Audio"===e.mediaType&&("Bad"===e.value?this.osMute.start():this.osMute.stop(),this.updateCommonMute());break;case"NetworkRecvQuality":this.networkRecv.updateLevel(e.value);break;case"NetworkSendQuality":this.networkSend.updateLevel(e.value);break;case"VideoCaptureDeviceFreeze":"Good"===e.value?this.cameraFreezeEndEventCount++:this.cameraFreezeStartEventCount++}"DeviceSpeakWhileMuted"!==e.type&&this.ufds.push({...e,timestamp:Date.now()-this.creationTime}),this.ufds.length>this.configProvider.config.maxStoredUFDCount&&this.ufds.shift()}registerRetargetIncoming(){this.retargetIncomingCount++}registerRetargetOutgoing(){this.retargetOutgoingCount++}registerRetargetCompleted(){this.retargetCompletedCount++}registerRetargetRejected(){this.retargetRejectedCount++}registerEscalationStart(){this.escalationAttemptedCount++}registerEscalationCompleted(){this.escalationCompletedCount++}registerEscalationRejected(){this.escalationRejectedCount++}registerRollbackEvent(e){e&&this.rollbackNegotiation.push({type:e.type,attempt:this.rollbackNegotiation.length+1,error:e.error?e.error:""})}registerReconnectAttempted(){this.reconnectAttemptedCount++,this.reconnectStats.onReconnectStart()}registerReconnectConnected(){this.reconnectConnectedCount++,this.reconnectStats.onReconnectConnected()}registerDeviceTelemetryEvent(e){e.timestamp=e.timestamp-this.creationTime,this.deviceTelemetryEvents.push(e)}registerVideoEffectsTelemetryEvent(e){e&&(e.timestamp=e.timestamp-this.creationTime,this.videoEffectsTelemetryEvents.add(e))}registerAudioEffectsTelemetryEvent(e){if(e){e.timestamp=e.timestamp-this.creationTime;const t=this.audioEffectsTelemetryEvents.items.pop();t&&this.audioEffectsChanged(t,e)&&this.audioEffectsTelemetryEvents.add(t),this.audioEffectsTelemetryEvents.add(e)}}audioEffectsChanged(e,t){return e.payload.fallback!==t.payload.fallback||void 0!==t.payload.userNoiseSuppressionMethod&&e.payload.userNoiseSuppressionMethod!==t.payload.userNoiseSuppressionMethod||void 0!==t.payload.userAudioEffect&&e.payload.userAudioEffect!==t.payload.userAudioEffect}registerReconnectAttempt(e){this.reconnectStats.onReconnectAttempt(e)}registerReconnectAttemptCompleted(){this.reconnectStats.onReconnectCompleted()}registerReconnectAttemptRejected(){this.reconnectStats.onReconnectRejected()}setMediaLegId(e){this.mediaLegId=e}setId(e){this.sessionId=e}setError(e){e.type===Qe.MEDIA_ERROR.incompatibleOffer&&(this.incompatibleOffer=!0),this.mediaError.type=e.type||Qe.MEDIA_ERROR.internalError,this.mediaError.detail=e.detail||e.toString()}setRelay(e){this.relay={address:e.addresses.join(),expires:e.expires,realm:e.realm,credentials:!(!e.username||!e.password),ports:[e.udpPort?`udp:${e.udpPort}`:"",e.tcpPort?`tcp:${e.tcpPort}`:"",e.tlsPort?`tls:${e.tlsPort}`:""].join(","),fqdns:e.fqdns?e.fqdns.join():"none"}}setRelayManagerTimers(e){this.relayManagerTimers=e}setSendModalities(e){this.allowedAudioSend=e.audio.some((e=>Wg(e))),this.allowedVideoSend=e.video.some((e=>Wg(e))),this.allowedScreensharingSend=e.sharing.some((e=>Wg(e)))}setIceInitTimestamp(e){this.iceInitTime||(this.iceInitTime=e)}setFinalAnswerTimestamp(e){this.finalAnswerTime||(this.finalAnswerTime=e)}setIceConnectedStateTimestamp(e){this.iceConnectedStateTime||(this.iceConnectedStateTime=e)}dtmfResult(e){e?++this.dtmfSuccess:++this.dtmfFailure}setUsedDevices(e){this.usedDevices&&JSON.stringify(e)!==JSON.stringify(this.usedDevices)&&this.deviceSelectionChangeCount++,this.usedDevices=e}setDevicesCount(e){this.devicesCount=e}setMediaQosEnabled(e){this.mediaQosEnabled=e}setPortRangeConfigured(e){this.portRangeConfigured=e}devicesChanged(){this.devicesChangeCount++}deviceChangedByPoll(){this.devicesPollChangeCount++}registerOutputRawMediaAccess(){this.rawOutputAudioAccess.attempt++,this.rawOutputAudioAccess.timer.start()}registerSetInputRawMedia(e){this.rawInputAudioOverride.attempt++,e?this.rawInputAudioOverride.timer.start():this.rawInputAudioOverride.timer.stop()}getReport(){const e=this.usedDevices||{microphone:"none",speaker:"none",camera:"none"};return{RawOutputAudioAccessDurationRatio:this.getDurationRatio(this.rawOutputAudioAccess.timer.elapsed),RawOutputAudioAccessAttempted:this.rawOutputAudioAccess.attempt,RawInputAudioOverrideDurationRatio:this.getDurationRatio(this.rawInputAudioOverride.timer.elapsed),RawInputAudioOverrideAttempted:this.rawInputAudioOverride.attempt,SessionId:this.sessionId,CallNumber:this.callNumber,NoIceCandidatesBadEventCount:this.noIceCandidatesBadEventCount,NoIceCandidatesGoodEventCount:this.noIceCandidatesGoodEventCount,NoRelayIceCandidatesBadEventCount:this.noRelayIceCandidatesBadEventCount,NoRelayIceCandidatesGoodEventCount:this.noRelayIceCandidatesGoodEventCount,CameraInUseBadEventCount:this.cameraInUseBadEventCount,CameraInUseGoodEventCount:this.cameraInUseGoodEventCount,MicrophoneInUseBadEventCount:this.microphoneInUseBadEventCount,MicrophoneInUseGoodEventCount:this.microphoneInUseGoodEventCount,CameraFreezeStartEventCount:this.cameraFreezeStartEventCount,CameraFreezeEndEventCount:this.cameraFreezeEndEventCount,RetargetIncomingCount:this.retargetIncomingCount,RetargetOutgoingCount:this.retargetOutgoingCount,RetargetCompletedCount:this.retargetCompletedCount,RetargetRejectedCount:this.retargetRejectedCount,ReconnectAttemptedCount:this.reconnectAttemptedCount,ReconnectConnectedCount:this.reconnectConnectedCount,EscalationAttemptedCount:this.escalationAttemptedCount,EscalationCompletedCount:this.escalationCompletedCount,EscalationRejectedCount:this.escalationRejectedCount,CreationTime:this.getHpTimeFromMillis(this.creationTime),InitTime:this.getHpTimeFromMillis(this.creationTime),TerminationTime:this.getHpTimeFromMillis(this.terminationTime),CallDuration:this.getHpTimeFromMillis(this.getCurrentDuration()),InitialNegotiationType:this.initialNegotiationType||"none",InitialNegotiationCompleted:this.initialNegotiationCompleted,ActiveModalities:JSON.stringify(this.activeModalities),NegotiationCount:this.negotiationCount,RejectedNegotiationCount:this.rejectedNegotiationCount,MediaLegId:this.mediaLegId,MultiParty:this.multiParty,ErrorType:this.mediaError.type,ErrorDetail:this.mediaError.detail,TerminationReason:this.terminationReason,IncompatibleOffer:this.incompatibleOffer,DtmfSuccess:this.dtmfSuccess,DtmfFailure:this.dtmfFailure,Relay:this.relay?JSON.stringify(this.relay):"none",RelayManager:this.relayManagerTimers?JSON.stringify(this.relayManagerTimers):"none",AllowedAudioSend:this.allowedAudioSend,AllowedVideoSend:this.allowedVideoSend,AllowedScreensharingSend:this.allowedScreensharingSend,IceInitTime:this.getHpTimeFromMillis(this.iceInitTime),FinalAnswerTime:this.getHpTimeFromMillis(this.finalAnswerTime),IceConnectedStateTime:this.getHpTimeFromMillis(this.iceConnectedStateTime),UsedMicrophone:e.microphone,UsedSpeaker:e.speaker,UsedCamera:e.camera,DeviceSelectionChangeCount:this.deviceSelectionChangeCount,DevicesChangeCount:this.devicesChangeCount,DevicesPollChangeCount:this.devicesPollChangeCount,DevicesCount:this.devicesCount?JSON.stringify(this.devicesCount):"none",ETag:this.ETag||"",ConfigIds:this.configIds?Array.isArray(this.configIds)?this.configIds.join(","):this.configIds:"",CallMutedRatio:this.getDurationRatio(this.mute.elapsed),CallOsMuted:this.getHpTimeFromMillis(this.osMute.elapsed),CallHwSilent:this.getHpTimeFromMillis(this.hwSilent.elapsed),CallSwMuted:this.getHpTimeFromMillis(this.swMute.elapsed),CallSpeakerMuted:this.getHpTimeFromMillis(this.speakerMute.elapsed),CallIsSpeaking:this.getHpTimeFromMillis(this.isSpeaking.elapsed),NetworkRecvGood:this.networkRecv.getCount("Good")-1,NetworkRecvPoor:this.networkRecv.getCount("Poor"),NetworkRecvBad:this.networkRecv.getCount("Bad"),NetworkSendGood:this.networkSend.getCount("Good")-1,NetworkSendPoor:this.networkSend.getCount("Poor"),NetworkSendBad:this.networkSend.getCount("Bad"),NetworkRecvGoodRatio:this.getDurationRatio(this.networkRecv.getElapsed("Good")),NetworkRecvPoorRatio:this.getDurationRatio(this.networkRecv.getElapsed("Poor")),NetworkRecvBadRatio:this.getDurationRatio(this.networkRecv.getElapsed("Bad")),NetworkSendGoodRatio:this.getDurationRatio(this.networkSend.getElapsed("Good")),NetworkSendPoorRatio:this.getDurationRatio(this.networkSend.getElapsed("Poor")),NetworkSendBadRatio:this.getDurationRatio(this.networkSend.getElapsed("Bad")),DeviceEvents:JSON.stringify(this.deviceTelemetryEvents),DeviceList:JSON.stringify(this.deviceList),DeviceListDebug:JSON.stringify(this.deviceDebugStrings),VideoEffects:JSON.stringify(this.videoEffectsTelemetryEvents.items),AudioEffects:JSON.stringify(this.audioEffectsTelemetryEvents.items),PermissionStates:JSON.stringify(this.permissionStates),ReconnectAttempts:this.reconnectStats.getReport(),NetworkEvents:JSON.stringify(kt(Et(this.sessionDiagnostics?.getObjectRef().reconnect?.tmpRecords,this.configProvider.config.diagnostics.telemetryLimits.numNetworkEvents),"startTime",this.creationTime)),ReconnectInProgress:this.reconnectStats.isReconnecting(),TransportReconnectedCount:this.transportReconnectedCount,UFDs:JSON.stringify(this.ufds),MediaQosEnabled:this.mediaQosEnabled,PortRangeConfigured:this.portRangeConfigured,RollbackNegotiation:JSON.stringify(this.rollbackNegotiation),hardwareConcurrency:Bg.hardwareConcurrency,GPUName:Bg.unmaskedGlRenderer,Connection_Downlink:Ot(this.connectionDownlinkSeries.items,(e=>e)),Connection_EffectiveType:Ot(this.connectionEffectiveTypeSeries.items,(e=>e)),Connection_Rtt:Ot(this.connectionRttSeries.items,(e=>e)),Connection_SaveData:Fk?.connection?.saveData,MediaByPassEnabled:!!this.configProvider.mediaConfig.mediaBypassEnabled,CallConstraints:JSON.stringify(this.configProvider.getCallConstraintsTelemetry()),DominantSpeaker:JSON.stringify(ik(this.sessionDiagnostics?.getObjectRef().dominantSpeaker,this.terminationTime))}}generateStatistics(e,t,i=!1){if(this.setMediaLegId(t.process()),"WebRtcMediaStats"!==e.type)throw new Error(`Unknown stats type - ${e.type}`);if(i){const e=this.deviceTelemetryEvents.length;this.deviceTelemetryEvents.splice(0,e-1),this.deviceDebugStrings=XR,this.audioEffectsTelemetryEvents.clear()}e.data.metrics=this.getReport();const n=this.sessionDiagnostics?.getObjectRef().statsErrors;if(n?.length)if(e.data.Extensions?.WebRTCStats?.statsErrors){const t=JSON.parse(e.data.Extensions.WebRTCStats.statsErrors);t.push(...n),e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(t)}else e.data.Extensions.WebRTCStats.statsErrors=JSON.stringify(n);const r={};return Xe(e.data,((e,t,i)=>{let n=0;Bk.test(e)?(n=13,r[t]="IPv4"):Vk.test(e)&&(n=4,r[t]="IPv6"),i[t]={type:n,value:e,__VALUE__:!0}})),e.data.metrics.piiFields={type:0,value:JSON.stringify(r),__VALUE__:!0},e}registerTransportConnected(){this.transportDisconnected&&(this.transportDisconnected=!1,this.transportReconnectedCount++)}registerTransportDisconnected(){this.transportDisconnected=!0}registerTransportFailed(){this.transportDisconnected=!1}resetError(){this.setError({type:"none",detail:"none"})}offering(){return{started:()=>{this.currentNegotiationType="Offering",this.negotiationStarted()}}}answering(){return{started:()=>{this.currentNegotiationType="Answering",this.negotiationStarted()}}}negotiationStarted(){this.initialNegotiationType=this.initialNegotiationType||this.currentNegotiationType,++this.negotiationCount}current(){return{completed:e=>{this.initialNegotiationCompleted=!0,this.activeModalities=e,this.resetError()},rejected:()=>{++this.rejectedNegotiationCount}}}getDurationRatio(e){const t=this.getCurrentDuration();return e/(0!==t?t:1)}getCurrentDuration(){return this.durationTimer.elapsed}getHpTimeFromMillis(e){return 1e4*e}},$k=class{constructor(e,t,i,n){this.onActiveSpeakersChanged=e,this.onDominantSpeakersChanged=t,this.diagnostics=i,this.logger=n}setStrategy(e){this.disposeStrategy(),this.dshStrategy=e,this.dshStrategy?.setOnDominantSpeakerChanged(this.onDominantSpeakerHistoryChanged.bind(this)),this.diagnostics?.setCurrentActiveStrategy("client")}onContributingSourcesChanged(e){this.onActiveSpeakersChanged(e),this.dshStrategy?.setSources(e)}onDominantSpeakerHistoryChanged(e,t){this.onDominantSpeakersChanged(e),this.diagnostics?.recordHistoryEvent(e,t),"client"!==t&&this.dshStrategy&&(this.logger.safe.info("Disposing client DSH strategy and switching to MP provided DSH"),this.disposeStrategy())}dispose(){this.disposeStrategy(),this.onActiveSpeakersChanged=null,this.onDominantSpeakersChanged=null}disposeStrategy(){this.dshStrategy?.dispose(),this.dshStrategy=null}},Gk=4294967040,jk=class{constructor(){this.ssrc=Math.floor(Math.random()*(Gk-1))+1}nextAudioStreamSsrc(){return this.nextSsrc(0)}nextVideoStreamSsrc(){return this.nextSsrc(99)}nextSsrc(e){let t=this.ssrc;do{t=this.ssrc,this.ssrc=(this.ssrc+e+1)%Gk,0===this.ssrc&&(this.ssrc=1)}while(t+e>Gk);return{min:t,max:t+e}}},zk=class{};zk.SourceNone=-1,zk.SourceAny=-2;var Wk=class{constructor(e){this.listener=e,this.streams=[]}add(e){this.streams.some((t=>t.getId()===e.getId()))||(this.streams.push(e),this.listener.streamAdded(e))}remove(e){let t;nt(this.streams,(i=>i.getId()===e&&(t=i,!0)))&&this.listener.streamRemoved(t)}getStreams(){return this.streams}clear(){this.streams.forEach((e=>e.dispose())),this.streams=[]}},qk=class{constructor(e){this.subscription=e}get subscribedStream(){return this.subscription.stream?.getMediaStream()}get msi(){return this.checkDisposed(),this.subscription.msi}get modality(){return this.checkDisposed(),this.subscription.modality}get localMsi(){return this.checkDisposed(),this.subscription.localMsi}setOnMediaStreamChangedHandler(e){this.checkDisposed(),this.mediaStreamChanged=e,this.subscription.isStreamReady&&this.notifyMediaStreamChanged()}setOnErrorHandler(e){this.checkDisposed(),this.error=e}dispose(){this.subscription&&(this.subscription.dispose(Te(),this),this.subscription=null)}unsubscribe(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=null)}notifyMediaStreamChanged(){if(this.mediaStreamChanged){const e=this.subscription.stream,t=this.subscription.isStreamReady;this.mediaStreamChanged(e&&t?e.getMediaStream():null)}}notifyError(e){this.error&&this.error(e)}checkDisposed(){if(!this.subscription)throw new Error("subscription disposed")}},Kk=class extends qe{constructor(e,t,i){super(),this.modality=e,this.msi=t,this.disposeDelay=i,this.clients=[],this.streamReady=!1}createClient(){const e=new qk(this);return this.clients.push(e),e}get isStreamReady(){return this.streamReady}get localMsi(){return this.subStream?.getSourceStreamId()}get isInactive(){return!this.clients.length}get stream(){return this.subStream}set stream(e){try{if(e===this.subStream)return;this.subStream&&(this.unsubscribe(!1),this.notifyStreamChanged()),this.subStream=e,e&&(this.streamReady=!1,e.requestSource(this.msi).then((()=>{this.streamReady=!0,this.notifyStreamChanged()})).catch((e=>{this.notifyError(e)})))}catch(e){this.event("onFailed").raise(this,e)}}notifyError(e){this.clients.forEach((t=>{t.notifyError(e)})),this.event("onFailed").raise(this,e)}dispose(e,t){t?(nt(this.clients,(e=>e===t)),this.isInactive&&(this.disposeTimeout=window.setTimeout((()=>{this.disposeTimeout=null,this.unsubscribeIfInactive()}),this.disposeDelay))):(this.clients=[],this.unsubscribe())}unsubscribeIfInactive(){this.isInactive&&(this.disposeTimeout&&clearTimeout(this.disposeTimeout),this.unsubscribe())}unsubscribe(e=!0){this.subStream&&(this.subStream.requestSource(zk.SourceNone).catch((()=>{})),this.streamReady=!1,this.subStream=null),e&&this.event("onDisposed").raise(this)}notifyStreamChanged(){this.clients.forEach((e=>e.notifyMediaStreamChanged())),this.event("onStreamChanged").raise()}},Jk=class extends qe{constructor(e,t,i,n){super(e),this.configProvider=t,this.diagnostics=n,this.videoSubscriptions=[],this.subscriptionEvents=new Map,this.setLogger(e),this.diagnostics??(this.diagnostics=new _A(this.configProvider,(()=>{}))),this.setStreamProvider(i),this.logger.safe.info("created")}getSubscriptionsCount(){return this.videoSubscriptions.length}setStreamProvider(e){this.streamProvider=e,this.streamProvider.setOnStreamsChangedHandler((()=>this.streamsChanged()))}setLogger(e){this.logger=e}subscribeVideo(e,t=zk.SourceAny){let i=this.videoSubscriptions.find((i=>i.msi===t&&i.modality===e));if(!i){const n=Date.now();this.disposeInactiveSubscriptionIfNeeded(e);const r=this.getAvailableStream(e),a=r?.getSourceStreamId();this.logger.safe.info(`creating new subscription #${t} for modality ${e}`),this.event("onSubscriptionChanged").raise(1,e,t,a,null),this.diagnostics.addSubscribe(e,t,a),i=new Kk(e,t,this.configProvider.config.webrtcVideoSubscriptionDisposeTimeout);const s=[];s.push(i.on("onDisposed",(e=>this.onSubscriptionDisposed(e)))),s.push(i.on("onStreamChanged",(()=>{const r=i.stream?.getId(),a=i.localMsi;if(this.updateTrackIds(),i.isStreamReady){const i=Date.now();this.event("onSubscriptionChanged").raise(2,e,t,a,i-n,r),this.diagnostics.addSubscribed(e,t,a,i-n)}}))),s.push(i.on("onFailed",((e,t)=>this.onSubscriptionFailed(e,t)))),this.subscriptionEvents.set(i,s),this.videoSubscriptions.push(i),r&&this.assignStream(i,r)}return i.createClient()}dispose(){const e=Te();this.videoSubscriptions.concat().forEach((t=>t.dispose(e))),this.streamProvider.setOnStreamsChangedHandler(null),super.dispose(),this.logger.safe.info("disposed")}reriseSubscribeEvents(){this.logger.safe.info(`rerising subscription events: ${this.videoSubscriptions.length}`);const e=[];this.videoSubscriptions.forEach((t=>{const i=t.modality,n=t.msi,r=t.localMsi;this.event("onSubscriptionChanged").raise(1,i,n,r),this.diagnostics.addSubscribe(i,n,r),e.push(...this.getSubscriptionVideoTrackIds(t))})),this.diagnostics.subscribedTrackIds=e}setDiagnostics(e){this.diagnostics=e??new _A(this.configProvider,(e=>{this.logger.safe.warn(`Unhandled stats error from inactive subscription manager: ${e}`)}))}streamChangedByMsi(e){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`);const t=this.videoSubscriptions.find((t=>t.msi===e));t?this.assignSubscriptionToStream(t):this.logger.safe.error(`Subscription for msi ${e} not found`)}streamsChanged(){this.logger.safe.info(`streams changed, subscriptions active: ${this.videoSubscriptions.length}`),this.videoSubscriptions.forEach((e=>{this.assignSubscriptionToStream(e)}))}assignSubscriptionToStream(e){const t=!e.stream||this.isStreamRemoved(e.stream);if(this.logger.safe.info(`Subscription for ${e.modality} ${e.msi} needs new stream: ${t}`),!t)return;const i=this.getAvailableStream(e.modality);i?this.assignStream(e,i):this.resignStream(e)}getAvailableStream(e){return this.streamProvider.getStreams().find((t=>e===t.getModality()&&t.getMsi()===zk.SourceNone))}isStreamRemoved(e){return!this.streamProvider.getStreams().some((t=>t===e))}assignStream(e,t){this.logger.safe.info(`assigning stream #${t.getId()} to subscription #${e.msi}`),e.stream=t}resignStream(e){e.stream&&(this.logger.safe.info(`removing stream from subscription #${e.msi}`),e.stream=null)}disposeInactiveSubscriptionIfNeeded(e){this.getAvailableStream(e)||this.videoSubscriptions.find((t=>t.modality===e&&t.isInactive))?.unsubscribeIfInactive()}onSubscriptionDisposed(e){const t=Te(),i=e.modality,n=e.msi,r=e.localMsi;this.event("onSubscriptionChanged").raise(3,i,n,r),this.diagnostics.addUnsubscribe(i,n,r),this.logger.safe.info(`disposing subscription for ${i} #${n}`),nt(this.videoSubscriptions,(t=>t===e)),this.streamsChanged(),this.updateTrackIds(),this.subscriptionEvents.has(e)&&(this.subscriptionEvents.get(e).forEach((e=>e.dispose(t))),this.subscriptionEvents.delete(e))}updateTrackIds(){const e=[],t=[];this.videoSubscriptions.forEach((i=>{if(!i.isStreamReady)return;const n=i.stream?.getId().split("-")[1];t.push(n),e.push(...this.getSubscriptionVideoTrackIds(i))})),this.event("onTrackIdsChanged").raise(e),this.diagnostics.subscribedTrackIds=e,this.configProvider.config.subscribeToSsrcForVideo&&this.event("onTrackSsrcChanged").raise(t)}getSubscriptionVideoTrackIds(e){return e?.stream?.getMediaStream()?.getVideoTracks().map((e=>e.id))??[]}onSubscriptionFailed(e,t){this.event("onSubscriptionFailed").raise(-1,e.modality,e.msi,e.localMsi,t),this.diagnostics.addFailed(e.modality,e.msi,e.localMsi,Be(t))}},Yk=f(ye()),Qk=class{constructor(e,t,i){this.logger=e,this.qualityManager=t,this.configProvider=i}getControlItem(){return this.controlItem}setControlItem(e){this.controlItem=e}dispose(){this.controlItem=null}setVideoControlMessage(e){this.controlItem=this.messageToControlItem(e),this.logger.safe.info(`BW limit requested to ${this.controlItem.bandwidth}`)}modifyDescriptor(e){if(!this.controlItem)return e;const t=Yk.parse(e.sdp);if(!t.media[1])return this.logger.unsafe.warn("video modality is disabled, skipping sdp modification, ",e),e;const i=this.getCurrentResolutionBitrate();this.logger.safe.info(`Select the BW limit as min of requested ${this.controlItem.bandwidth} and Current Resolution Max BR ${i}`);const n=this.getSessionBitrate(t),r=Math.min(i,this.controlItem.bandwidth,n);if(t.media[1].bandwidth)t.media[1].bandwidth[0].limit=r;else{const e={limit:r,type:"AS"};t.media[1].bandwidth=[e]}return e.sdp=Yk.write(t),e}messageToControlItem(e){const t=new PA(e.controlVideoStreaming.controlInfo[0].fmtParams),i="max-br";if(!t.contains(i))return null;const n=Math.round(1.2*+t.get(i));return{sourceId:e.controlVideoStreaming.controlInfo[0].sourceId,streamMsid:e.controlVideoStreaming.controlInfo[0].streamMsid,bandwidth:n}}getCurrentResolutionBitrate(){const e=this.qualityManager.getCurrentResolution(),t=Zw.Send.getResolutionByFs(e);return e&&t?Math.floor(Zw.Send.getBitrateForResolution(t.width,t.height).maxBitrate/1e3):Number.MAX_VALUE}getSessionBitrate(e){let t=Number.MAX_SAFE_INTEGER;return this.configProvider.mediaConfig.maxBandwidthInKbps&&(t=this.configProvider.mediaConfig.maxBandwidthInKbps),e.bandwidth&&(t=Math.min(e.bandwidth[0].limit,t)),t-(this.configProvider.config.audioBandwidthInKbps||0)}},Zk=class{constructor(e,t,i){this.pc=e,this.configProvider=t,this.logger=i.createChild("MediaRollbackModifier")}modifyDescriptor(e){const t=Yk.parse(e.sdp);return Yk.parse(this.pc.localDescription.sdp).media.forEach(((e,i)=>{const n=t.media[i];(zA(e)&&!e.bundleOnly||!n||zA(n))&&(this.logger.safe.info(`Adding disabled media ${e.type}, position ${i}`),t.media[i]=gM(e.type,void 0,e.protocol,void 0))})),new JP(this.configProvider).modify(t),e.sdp=Yk.write(t),e}},Xk=class{constructor(e){this.manager=null,this.extensionType=e}initialize(e){e.manager&&(this.manager=e.manager),e.logger&&(this.logger=e.logger.createChild(this.extensionType)),e.configProvider&&(this.configProvider=e.configProvider)}dispose(){this.manager&&(this.manager=null),this.logger&&(this.logger.safe.info("disposed"),this.logger=this.logger.createChild("DISPOSED"))}configure(e){this.options=e}getOptions(){return this.options}getType(){return this.extensionType}},eD=class extends Xk{constructor(){super("dominantSpeakerHistory"),this.callback=null}initialize(e){super.initialize(e),this.extensionManagerSubscription=this.manager.on("onDominantHistoryMessage",((e,t)=>this.onDominantHistoryMessage(e,t))),e&&e.callback&&(this.callback=e.callback)}dispose(){this.extensionManagerSubscription.dispose(),this.extensionManagerSubscription=null,this.callback=null,super.dispose()}onDominantHistoryMessage(e,t){this.callback&&("server"===t?this.callback(e.history,t):"signaling"===t&&this.callback(e.previousDominantSpeakerHistory,t))}},tD=class{constructor(e,t,i,n,r,a){this.logger=e,this.emulator=t,this.qualityManager=i,this.diagnostics=n,this.configProvider=r,this.statsGatherer=a,this.previousSequenceNumber=new Map,this.modifiers=this.configProvider.mediaConfig.simulcastSessionEnabled?[]:[new Qk(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider)]}dispose(){this.cleanupDevToolsInjector(),this.modifiers&&(this.modifiers.forEach((e=>e.dispose())),this.modifiers=null),this.emulator=null,this.logger=this.logger.createChild("DISPOSED")}handleMessage(e){const t=e.controlInfo[0].sourceId;if(this.previousSequenceNumber.has(t)&&e.sequenceNumber<this.previousSequenceNumber.get(t))return this.statsGatherer.addVideoControlMessage(!0),this.diagnostics?.addVideoControlMessage(!0),this.logger.safe.info(`Discarded old media stream control message for sourceId ${t}: (${JSON.stringify(e)})`),Promise.resolve();this.previousSequenceNumber.set(t,e.sequenceNumber),this.statsGatherer.addVideoControlMessage(),this.diagnostics?.addVideoControlMessage(),this.configProvider.config.enableDevtoolsAPI&&this.injectFmtpHandler(e);const i={controlVideoStreaming:e};return this.configureResolution(i),this.modifiers.length?(this.modifiers.forEach((e=>e.setVideoControlMessage(i))),this.emulator.renegotiate(this.modifiers)):Promise.resolve()}configureResolution(e){this.logger.safe.info(`Signaling FMTP: ${JSON.stringify(e.controlVideoStreaming)}`);const t=String(e.controlVideoStreaming.sequenceNumber),i=e.controlVideoStreaming.controlInfo[0].fmtParamsList,n=e.controlVideoStreaming.controlInfo[0].fmtParams,r=i&&this.configProvider.config.webrtcFmtParamListSupported?this.parseFmtParamsList(i):[this.parseFmtParams(n)],a=+e.controlVideoStreaming.controlInfo[0].sourceId,s=[{causeId:t,isSimulcast:r.some((e=>void 0!==e.rid))||r.length>1,capabilities:r,sourceId:a}];this.qualityManager.setMaxCapabilities(s)}parseFmtParamsList(e){return e.map((e=>this.parseFmtParams(e)))}parseFmtParams(e){const t=new PA(e);return{maxFs:+t.get(Qe.VIDEO_CAPABILITIES.MAX_FS_PATH),maxMbps:+t.get(Qe.VIDEO_CAPABILITIES.MAX_MBPS_PATH),maxFps:+t.get(Qe.VIDEO_CAPABILITIES.MAX_FPS_PATH)/100,maxBr:1200*+t.get(Qe.VIDEO_CAPABILITIES.MAX_BR_PATH),ssrc:+t.get(Qe.VIDEO_CAPABILITIES.SSRC_PATH),rid:t.get(Qe.VIDEO_CAPABILITIES.RID_PATH),keyframe:this.shouldGenerateKeyFrame(t),vlaDebug:t.get(Qe.VIDEO_CAPABILITIES.VLA_DEBUG)}}shouldGenerateKeyFrame(e){return e.get(Qe.VIDEO_CAPABILITIES.KEYFRAME_PATH)?!!+e.get(Qe.VIDEO_CAPABILITIES.KEYFRAME_PATH):this.configProvider.config.webrtcAllowRestoreKeyframe}injectFmtpHandler(e){const t=window;t&&t.webMA&&(t.webMA.fmtp||(t.webMA.fmtp={handleMessage:this.handleMessage.bind(this)}),t.webMA.fmtp.lastFmtp=e)}cleanupDevToolsInjector(){const e=window;e&&e.webMA&&delete e.webMA.fmtp}},iD=class{constructor(){this.sequence=0}getVideoControlMessage(e,t,i){const n={controlVideoStreaming:{sequenceNumber:++this.sequence,globalTimeStamp:(new Date).toString(),controlInfo:[{control:"start",sourceId:t,streamMsid:e}]}};return i&&(n.controlVideoStreaming.controlInfo[0].fmtParams=AA(i)),n}getSourceRequestMessage(e,t,i,n,r){if(!n)throw new Error("Failed to construct SourceRequestMessage, missing fmtParams");const a={sourceId:t,streamMsid:e,fmtParams:n};return a.subStreamIndex=r,{applyChannelParameters:{multiChannelParameter:{mids:[i],mediaParameter:JSON.stringify({controlVideoStreaming:{sequenceNumber:++this.sequence,controlInfo:a}})}}}}getBandwidthInfoMessage(e,t){return{applyChannelParameters:{multiChannelParameter:{mids:e,mediaParameter:JSON.stringify({remoteUplinkBWE:{bw:t.toString()}})}}}}getMaxVideoSendCapabilitiesMessage(e){function t(e){return 16*Math.ceil(e/16)}const{streamMIDs:i,capabilities:n,useMax:r,sendMaxFs:a,sendMaxMbps:s}=e;let o=t(n.maxWidth),l=t(n.maxHeight);r&&(o=l=Math.max(o,l));const c={[Qe.VIDEO_CAPABILITIES.MAX_FPS_PATH]:n.maxFps,[Qe.VIDEO_CAPABILITIES.MAX_WIDTH]:o,[Qe.VIDEO_CAPABILITIES.MAX_HEIGHT]:l};return a&&(c[Qe.VIDEO_CAPABILITIES.MAX_FS_PATH]=n.maxFs),s&&(c[Qe.VIDEO_CAPABILITIES.MAX_MBPS_PATH]=n.maxMbps),{applyChannelParameters:{multiChannelParameter:{mids:i,mediaParameter:JSON.stringify({maxVideoSendCapabilities:{caps:c}})}}}}},nD=class{constructor(e){this.logger=e}dispose(){this.sender=null}configure(e){this.sender=e.sender}async sendMessage(e,t){if(!this.checkConfigured())return this.logger.safe.warn("extension not configured with sender"),null;let i,n;return"ApplyChannelParametersSourceRequest"===e&&(i=JSON.parse(t.applyChannelParameters.multiChannelParameter.mediaParameter),n=i.controlVideoStreaming.sequenceNumber),this.logger.safe.info(`sending video control message: ${JSON.stringify(t)}`),this.sender.send(e,t,i,n)}checkConfigured(){return!!this.sender}},rD=class extends Xk{constructor(){super("videoStreamControl"),this.messageGenerator=new iD}initialize(e){super.initialize(e),this.subscribeListeners(),this.sourceRequester=new nD(e.logger),this.streamConfigurationHandler=new tD(e.logger,e.negotiationEmulator,e.qualityManager,e.diagnostics,e.configProvider,e.statisticsGatherer)}configure(e){super.configure(e),this.sourceRequester.configure(e)}sendSourceRequest(e,t,i,n,r){if(this.configProvider?.config.useApplyChannelParametersForSourceRequests){const a=this.messageGenerator.getSourceRequestMessage(e,t,i,n,r);return this.sourceRequester.sendMessage("ApplyChannelParametersSourceRequest",a)}const a=this.messageGenerator.getVideoControlMessage(e,t,n?.[0]);return this.sourceRequester.sendMessage("ControlVideoStreaming",a)}sendBandwidthInfo(e,t){const i=this.messageGenerator.getBandwidthInfoMessage(e,t);return this.sourceRequester.sendMessage("ApplyChannelParametersBandwidth",i)}sendMaxVideoSendCapabilities(e,t){const i=this.messageGenerator.getMaxVideoSendCapabilitiesMessage({streamMIDs:e,capabilities:t,sendMaxFs:this.configProvider.config.maxSendVideoCapabilitiesReportingSendMaxFs,sendMaxMbps:this.configProvider.config.maxSendVideoCapabilitiesReportingSendMaxMbps,useMax:this.configProvider.config.maxSendVideoCapabilitiesReportingUseMaximumWidthHeight});return this.sourceRequester.sendMessage("ApplyChannelParametersVideoCapabilities",i)}dispose(){this.unsubscribeListeners(),this.streamConfigurationHandler&&(this.streamConfigurationHandler.dispose(),this.streamConfigurationHandler=null),this.sourceRequester&&(this.sourceRequester.dispose(),this.sourceRequester=null),super.dispose()}onMediaStreamControlMessage(e){this.streamConfigurationHandler.handleMessage(e)}subscribeListeners(){this.extensionManagerSubscription=this.manager.on("onMediaStreamControlMessage",(e=>this.onMediaStreamControlMessage(e)))}unsubscribeListeners(){this.extensionManagerSubscription.dispose(),this.extensionManagerSubscription=null}},aD=class extends Xk{constructor(){super("bandwidthTelemetry")}initialize(e){super.initialize(e),this.statisticsGatherer=e.statisticsGatherer,this.diagnostics=e.diagnostics,this.extensionManagerSubscription=this.manager.on("onBandwidthMessage",(e=>this.onBandwidthMessage(e)))}dispose(){super.dispose(),this.extensionManagerSubscription.dispose(),this.extensionManagerSubscription=null}onBandwidthMessage(e){this.statisticsGatherer.addReportedReceiveBandwidth(e.bw),this.diagnostics.addReportedReceiveBandwidth(e.bw)}},sD=class{constructor(e){this.key=e.config.bwSeedOptions.localStorageKey||"bwSeed";const t=localStorage.getItem(this.key);parseInt(t)||localStorage.setItem(this.key,e.config.bwSeedOptions.constValue.toString())}getSeed(){const e=localStorage.getItem(this.key),t=parseInt(e);return isNaN(t)?void 0:t}saveSeed(e){localStorage.setItem(this.key,e.toString())}static localStorageAvailable(){try{const e=window.localStorage,t="someKey",i="someValue";return e.setItem(t,i),e.removeItem(t),!0}catch(e){return!1}}},oD=class e{constructor(t){e.value??(e.value=t.config.bwSeedOptions.constValue)}getSeed(){return e.value}saveSeed(t){e.value=t}},lD=class{constructor(e){this.value=e}addValue(e){}getAggregated(){return this.value}},cD=class{addValue(e){this.value=e}getAggregated(){return this.value}},dD=class{constructor(e){this.values=new uA(e)}addValue(e){this.values.add(e)}getAggregated(){return Math.floor(it(this.values.items))}},uD=class{constructor(){this.total=0,this.duration=0,this.max=0,this.minNonZero=Number.MAX_SAFE_INTEGER}get avg(){return 0!==this.duration?this.total/this.duration:0}get maxSample(){return this.max}get minNonZeroSample(){return this.minNonZero}captureSample(e){(e||0===e)&&(this.total+=e,this.duration++,this.max=Math.max(e,this.max),0!==e&&(this.minNonZero=Math.min(e,this.minNonZero)))}},hD=class{constructor(){this.sampleCounts={}}get min(){const e=Object.keys(this.sampleCounts).map(Number).filter((e=>e>0));return e.length>0?Math.min(...e):0}get max(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?Math.max(...e):0}get mode(){const e=Object.keys(this.sampleCounts).map(Number);return e.length>0?e.reduce(((e,t)=>this.sampleCounts[t]>this.sampleCounts[e]?t:e),e[0]):0}captureSample(e){var t;if(void 0!==e){const i=`${e}`;(t=this.sampleCounts)[i]??(t[i]=0),this.sampleCounts[i]++}}},pD=class{get delta(){if(void 0!==this.cur&&void 0!==this.last)return this.cur-this.last}captureSample(e,t){void 0!==e&&(void 0!==this.cur&&(this.last=this.cur),this.cur=e)}},gD=class{constructor(e=0){this.precision=e}get delta(){if(void 0!==this.currentSample&&void 0!==this.prevSample){let e=1;return void 0!==this.currentTimestamp&&void 0!==this.prevTimestamp&&(e=(this.currentTimestamp-this.prevTimestamp)/1e3),e&&Ct((this.currentSample-this.prevSample)/e,this.precision)}}captureSample(e,t){if(this.currentTimestamp!==t){if(void 0===e)return this.prevSample=void 0,this.currentSample=void 0,this.prevTimestamp=void 0,void(this.currentTimestamp=void 0);void 0!==this.currentSample&&(this.prevSample=this.currentSample),this.prevTimestamp=this.currentTimestamp,this.currentTimestamp=t,this.currentSample=e}}},mD=class{constructor(){this.startTime=Date.now()}get elapsed(){return Ct((Date.now()-this.startTime)/1e3,0)}},fD=class{constructor(){this.eventCount=0,this.totalActiveDuration=0,this.countBuckets={seconds1to3:0,seconds3to5:0,seconds5to8:0,seconds8to15:0,seconds15to60:0,seconds60toMax:0},this.timestampBuckets={seconds1to3:[],seconds3to5:[],seconds5to8:[],seconds8to15:[],seconds15to60:[],seconds60toMax:[]},this.averager=new uD}get active(){return!!this.current}get ongoingDuration(){return this.current?.elapsed||0}get avgDuration(){return this.averager.avg}get longestDuration(){return this.averager.maxSample}get numEvents(){return this.eventCount}get totalDuration(){return this.current?this.totalActiveDuration+this.current.elapsed:this.totalActiveDuration}get timestamps(){return lt(this.timestampBuckets)}get counts(){return lt(this.countBuckets)}set active(e){if(!this.current&&e)this.current=new mD;else if(this.current&&!e){const e=this.current.elapsed;this.averager.captureSample(e),this.totalActiveDuration+=e;for(const t of Object.keys(Qe.HISTOGRAM_BATCH))if(e<=Qe.HISTOGRAM_BATCH[t]){this.countBuckets[t]++,this.timestampBuckets[t].push(this.current.startTime);break}this.eventCount++,this.current=void 0}}},vD=class{constructor(){this.sampleChangeCount=0,this.sampleDurations={}}get durations(){return lt(this.sampleDurations)}get sortedDurations(){return Object.keys(this.sampleDurations).sort(((e,t)=>this.sampleDurations[t]-this.sampleDurations[e]))}get durationRatios(){const e={};let t=0;for(const e in this.sampleDurations)t+=this.sampleDurations[e];for(const i in this.sampleDurations)e[i]=Ct(this.sampleDurations[i]/t*100);return e}get changeCount(){return this.sampleChangeCount}captureSample(e){this.sampleDurations[e]||(this.sampleDurations[e]=0),this.sampleDurations[e]++,e!==this.lastSample&&(this.sampleChangeCount++,this.lastSample=e)}},SD=class{constructor(e,t){this.validTimeBetweenFramesArrival=e,this.invalidFPSAboveMax=t,this.lastSampleTimestamp=-1,this.fpsHarmonicSumWeigtsTs=0,this.fpsHarmonicWeigtedSumsFramePerDelayTs=0}captureSample(e){const t=Date.now();if(e>0&&this.lastSampleTimestamp>0){const i=t-this.lastSampleTimestamp;if(this.lastSampleTimestamp=t,i<0||i>this.validTimeBetweenFramesArrival||e>this.invalidFPSAboveMax)return;const n=i/e;this.fpsHarmonicSumWeigtsTs+=i,this.fpsHarmonicWeigtedSumsFramePerDelayTs+=i*n}(this.lastSampleTimestamp<0||0===e)&&(this.lastSampleTimestamp=t)}get harmonicMean(){return this.fpsHarmonicWeigtedSumsFramePerDelayTs>0?1e3*this.fpsHarmonicSumWeigtsTs/this.fpsHarmonicWeigtedSumsFramePerDelayTs:0}},yD=class{constructor(e){this.samplesNum=e,this.samples=[],this.lastReport={avg:-1,max:-1,median:-1,volatilityPercent:-1}}isReportComplete(){return this.samples.length===this.samplesNum}getReport(){return this.lastReport}captureSample(e){void 0===e||e<0||(Tt(this.samples,e,this.samplesNum),this.lastReport={avg:this.getAvg(),max:this.getMax(),median:this.getMedian(),volatilityPercent:this.getVolatility()})}getAvg(){return it(this.samples)}getMax(){return Math.max(...this.samples)}getMedian(){return this.samples.sort(((e,t)=>e-t)),this.samples.length%2==1?this.samples[Math.floor(this.samples.length/2)]:(this.samples[this.samples.length/2]+this.samples[this.samples.length/2-1])/2}getVolatility(){const e=this.getAvg();if(0===e)return 0;let t=0;return this.samples.forEach((i=>{t+=Math.abs(i-e)})),Ct(t/this.samples.length*100/e,2)}},CD=class{constructor(){this.duration=0,this.reportAggr={avg:0,max:0,median:0,volatilityPercent:0}}captureSample(e){!e||e.avg<0||(this.reportAggr={avg:this.reportAggr.avg+e.avg,max:Math.max(this.reportAggr.max,e.max),median:this.reportAggr.median+e.median,volatilityPercent:this.reportAggr.volatilityPercent+e.volatilityPercent},this.duration++)}getReport(){if(0!==this.duration)return{avg:this.reportAggr.avg/this.duration,max:this.reportAggr.max,median:this.reportAggr.median/this.duration,volatilityPercent:this.reportAggr.volatilityPercent/this.duration}}},_D=class{constructor(e=0){this.allowedOvershoot=e,this.past=[],this.totalOvershootDuration=0,this.lastAllowed=0}get isOvershooting(){return!!this.current}get events(){return this.current?[...this.past,this.current]:this.past}get totalDuration(){return this.totalOvershootDuration}captureSample(e,t){const i=Ct(e-t);i>this.allowedOvershoot&&(0===this.lastAllowed||t===this.lastAllowed||!this.current&&t>this.lastAllowed)?(this.totalOvershootDuration++,this.current?(this.current.min=Math.min(this.current.min,i),this.current.max=Math.max(this.current.max,i)):this.current={timestamp:Date.now(),min:i,max:i}):this.current&&(this.current.duration=Date.now()-this.current.timestamp,this.past.push(this.current),this.current=void 0),this.lastAllowed=t}},ED=class{constructor(e=100){this.minPackets=e,this.prevLost=0,this.prevReceived=0}calculate(e,t){if(void 0===e||void 0===t)return;const i=e-this.prevReceived,n=t-this.prevLost;return i+n<this.minPackets?void 0:(this.prevReceived=e,this.prevLost=t,n*this.minPackets/(n+i))}},TD=class{constructor(){this.capturedSamples=[]}captureSample(e){e&&this.capturedSamples.push(e)}calculateStd(){if(!this.capturedSamples.length)return;const e=this.capturedSamples.reduce(((e,t)=>e+t),0)/this.capturedSamples.length,t=this.capturedSamples.map((t=>(t-e)**2)),i=t.reduce(((e,t)=>e+t),0)/t.length;return Ct(Math.sqrt(i),2)}getFirst(){return this.capturedSamples[0]}getLast(){if(this.capturedSamples.length)return this.capturedSamples[this.capturedSamples.length-1]}calculatePercentile(e){if(!this.capturedSamples.length)return;const t=this.capturedSamples.sort(((e,t)=>e-t)),i=(t.length-1)*e,n=Math.floor(i),r=i-n;return void 0!==t[n+1]?t[n]+r*(t[n+1]-t[n]):t[n]}};function bD(e){if(!e)return;const t=["libvpx","ffmpeg"];let i=!0;for(const n of t)if(e.toLowerCase().includes(n)){i=!1;break}return i}var ID=class{constructor(e){this.samplesCount=e,this.capturedSamples=[]}captureSample(e){void 0!==e&&Tt(this.capturedSamples,e,this.samplesCount)}getRate(){if(!this.capturedSamples.length)return;const e=this.samplesCount/this.capturedSamples.length;return this.capturedSamples.reduce(((e,t)=>e+t))*e/this.samplesCount}},wD=class{constructor(e=5){this.limit=e,this.curWidth=0,this.curHeight=0,this.resolutionSwitches=[]}captureSample(e,t){e===this.curWidth&&t===this.curHeight||(Tt(this.resolutionSwitches,`${e}x${t}`,this.limit),this.curWidth=e,this.curHeight=t)}get switches(){if(this.resolutionSwitches.length)return this.resolutionSwitches}};function RD(e,t,i){return e&&t?Math.ceil(e/Qe.MACROBLOCK_SIZE)*Math.ceil(t/Qe.MACROBLOCK_SIZE)*i:0}var AD=class{constructor(){this.macroblockRateAveragerReceived=new uD,this.macroblockRateAveragerDecoded=new uD,this.maxDecoderLoss=0,this.decoderLoss=0}captureSample(e,t){this.macroblockRateAveragerReceived.captureSample(e),this.macroblockRateAveragerDecoded.captureSample(t);let i=this.maxDecoderLoss;e&&(i=(e-t)/e*100),this.decoderLoss=i,this.maxDecoderLoss=Math.max(i,this.maxDecoderLoss)}getReport(){return{macroblockRateReceivedMax:this.macroblockRateAveragerReceived.maxSample,macroblockRateReceivedAvg:this.macroblockRateAveragerReceived.avg,macroblockRateDecodedMax:this.macroblockRateAveragerDecoded.maxSample,macroblockRateDecodedAvg:this.macroblockRateAveragerDecoded.avg,macroblockRateMaxDecoderLossPercent:Math.floor(this.maxDecoderLoss),macroblockRateDecoderLossPercent:Math.floor(this.decoderLoss)}}},PD=class{constructor(){this.codecReport={}}captureSample(e,t){var i,n;const r=e.split("/")[1];return void 0===this.activeMsi||this.activeMsi!==t?(this.activeMsi=t,this.previousCodec=r,void((i=this.codecReport)[t]??(i[t]={[r]:1,codecSwitchCounter:0}))):this.previousCodec!==r?((n=this.codecReport[t])[r]??(n[r]=0),this.codecReport[t][r]++,this.codecReport[t].codecSwitchCounter++,void(this.previousCodec=r)):void this.codecReport[t][r]++}get report(){return this.codecReport}},MD=class{constructor(){this.bandwidthAverager=new uD}addValue(e){this.bandwidthAverager.captureSample(e)}getAggregated(){return Math.floor(this.bandwidthAverager.avg)}},kD=class{constructor(e){this.configProvider=e,this.aggregator=this.getAggregator(),this.storage=this.getStorage(),this.cappingValue=this.configProvider.config.bwSeedOptions.cappingValue,this.minValue=this.configProvider.config.bwSeedOptions.minValue??-1}getSeed(){const e=this.storage.getSeed()??-1;return this.cappingValue>0?Math.min(Math.max(e,this.minValue),this.cappingValue):Math.max(e,this.minValue)}saveSeed(e){this.aggregator.addValue(e);const t=this.aggregator.getAggregated();this.storage.saveSeed(t)}getAggregator(){switch(this.configProvider.config.bwSeedOptions.aggregation){case"avg":return this.configProvider.config.bwSeedOptions.aggregateLastN>0?new dD(this.configProvider.config.bwSeedOptions.aggregateLastN):new MD;case"last":return new cD;default:return new lD(this.configProvider.config.bwSeedOptions.constValue)}}getStorage(){return this.configProvider.config.bwSeedOptions.useLocalStorage&&sD.localStorageAvailable()?new sD(this.configProvider):new oD(this.configProvider)}},DD=class extends Xk{constructor(){super("bandwidthCache")}initialize(e){super.initialize(e),this.bandwidthCache=new kD(e.configProvider),this.onBandwidthMessageSubscription=this.manager.on("onBandwidthMessage",(e=>{this.bandwidthCache.saveSeed(e.bw)}))}getBWSeed(){return this.bandwidthCache.getSeed()}dispose(){super.dispose(),this.onBandwidthMessageSubscription?.dispose(),this.onBandwidthMessageSubscription=null}},OD=class{static getExtension(e){switch(e){case"dominantSpeakerHistory":return new eD;case"videoStreamControl":return new rD;case"bandwidthTelemetry":return new aD;case"bandwidthCache":return new DD;default:throw new Error(`Extension of type ${e} is not found`)}}},ND=class extends qe{constructor(e){super(e),this.logger=e,this.extensions=[]}dispose(){this.extensions.map((e=>e.dispose())),this.extensions=[],super.dispose()}addExtension(e,t){t.manager||(t.manager=this);const i=OD.getExtension(e);i.initialize(t),this.extensions.push(i)}getExtension(e){return this.extensions.find((t=>t.getType()===e))}configureExtension(e,t){this.getExtension(e)?.configure(t)}processNotification(e,t){switch(e){case"ControlVideoStreaming":this.event("onMediaStreamControlMessage").raise(t);break;case"DominantSpeakerInfo":this.event("onDominantHistoryMessage").raise(t,"signaling");break;case"McpDominantSpeakerInfo":this.event("onDominantHistoryMessage").raise(t,"server");break;case"BandwithNotification":this.event("onBandwidthMessage").raise(t);break;default:this.logger.safe.error(`Notification message handler not found for type: ${e}`)}}},LD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send){this.diagnostics.handlePresentationAudioInputLevel();for(const i of e.send)try{t.add(i.outboundRTP.id);let e=this.sendExtenders.get(i.outboundRTP.id)??new UD(this.diagnostics,this.configProvider);i.outboundRTP.bytesSent<e.lastBytes&&(e=new UD(this.diagnostics,this.configProvider)),this.sendExtenders.set(i.outboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:send",Be(e))}}if(Lt(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new xD(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new xD(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("AudioStatsProcessor:recv",Be(e))}Lt(this.recvExtenders,t)}},xD=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new ED,this.bytesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.totalSamplesReceivedDiff=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.concealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.silentConcealedSamplesDiff=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.concealedRatioAverager=new uD,this.stretchedRatioAverager=new uD,this.codecSwitchesTracker=new vD,this.packetDurationTracker=new vD,this.jitterAverager=new uD,this.jitterBufferDelayAverager=new uD,this.lastBytes=0}processSample(e){let t,i,n,r,a;const s=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDiff.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp),this.totalSamplesReceivedDiff.captureSample(e.inboundRTP.totalSamplesReceived,e.inboundRTP.timestamp),this.concealedSamplesDiff.captureSample(e.inboundRTP.concealedSamples,e.inboundRTP.timestamp),this.silentConcealedSamplesDiff.captureSample(e.inboundRTP.silentConcealedSamples,e.inboundRTP.timestamp);const o=this.bytesReceivedDiff.delta&&8*this.bytesReceivedDiff.delta;this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const l=e.inboundRTP.jitterBufferDelay&&e.inboundRTP.jitterBufferEmittedCount&&Ct(e.inboundRTP.jitterBufferDelay/e.inboundRTP.jitterBufferEmittedCount*1e3,0);if(this.jitterAverager.captureSample(1e3*e.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(e.inboundRTP.jitterBufferDelay),t=this.totalSamplesReceivedDiff.delta&&this.concealedSamplesDiff.delta&&this.silentConcealedSamplesDiff.delta&&Ct((this.concealedSamplesDiff.delta-this.silentConcealedSamplesDiff.delta)/this.totalSamplesReceivedDiff.delta),e.customHealerStats){e.customHealerStats.numSamplesPerFrame&&(r=e.customHealerStats.decodedSamples/e.customHealerStats.numSamplesPerFrame,a=e.customHealerStats.cngSamples/e.customHealerStats.numSamplesPerFrame),t=e.customHealerStats.healedSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),n=e.customHealerStats.concealSamples&&e.customHealerStats.concealSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples),i=e.customHealerStats.stretchSamples&&e.customHealerStats.stretchSamples/(e.customHealerStats.decodedSamples+e.customHealerStats.healedSamples);const s=e.customHealerStats.packetDurationInMs&&e.customHealerStats.packetDurationInMs>100?100:e.customHealerStats.packetDurationInMs;this.concealedRatioAverager.captureSample(n),this.stretchedRatioAverager.captureSample(i),this.codecSwitchesTracker.captureSample(`${e.customHealerStats.pullAdspPayloadType}`),this.packetDurationTracker.captureSample(`${s}`)}e.extensions={lossRate:s,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,healedRatio:t,jitterBufferMs:l,bitrate:o||0,customHealerStats:e.customHealerStats&&{concealedDataRatio:n,concealedDataRatioMax:this.concealedRatioAverager.maxSample,stretchedDataRatio:i,stretchedDataRatioMax:this.stretchedRatioAverager.maxSample,numberOfDecodedFrames:r,usageMetricsCodecId:this.codecSwitchesTracker.sortedDurations,percentageOfPtime:this.packetDurationTracker.durationRatios,pushPacketProcessingTimes:e.customHealerStats.pushProcessingTimes,pullPacketProcessingTimes:e.customHealerStats.pullProcessingTimes,pullProcessingTimePerStreamNumber:e.customHealerStats.pullProcessingTimePerStreamNumber,cnpPushCount:e.customHealerStats.cnpPushCount,cnpPullCount:e.customHealerStats.cnpPullCount,numberOfCNFrames:a,redPacketsCount:e.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:e.customHealerStats.pullNumOfStreamsCounter},jitterAvg:Ct(this.jitterAverager.avg),jitterBufferDelayMs:Ct(this.jitterBufferDelayAverager.avg)},this.duration++}},FD=class{constructor(){this.duration=0,this.lossRateAverager=new uD,this.bitrateAverager=new uD,this.jitterBufferAverager=new uD,this.jitterAverager=new uD,this.jitterBufferDelayAverager=new uD,this.healedRatioAverager=new uD}processSample(e,t,i){const n=e[0],r={inboundRTP:n.inboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.healedRatioAverager.captureSample(n.extensions.healedRatio),this.jitterBufferAverager.captureSample(n.extensions.jitterBufferMs),this.jitterAverager.captureSample(1e3*n.inboundRTP.jitter),this.jitterBufferDelayAverager.captureSample(n.inboundRTP.jitterBufferDelay);const e=n.inboundRTP.packetsReceived+n.inboundRTP.packetsLost;r.aggregated={lossRateMax:this.lossRateAverager.maxSample,lossRateAvg:this.lossRateAverager.avg,networkAvgLossRate:e>0?n.inboundRTP.packetsLost/e:0,duration:this.duration,bitrateAvg:Ct(this.bitrateAverager.avg,0),bitrateMax:Ct(this.bitrateAverager.maxSample,0),jitterAvg:this.jitterAverager.avg,avgJitterBufferSize:this.jitterBufferAverager.avg,healedRatioAvg:this.healedRatioAverager.avg,healedRatioMax:this.healedRatioAverager.maxSample,customHealerStats:n.extensions.customHealerStats&&{concealedDataRatio:n.extensions.customHealerStats.concealedDataRatio,concealedDataRatioMax:n.extensions.customHealerStats.concealedDataRatioMax,stretchedDataRatio:n.extensions.customHealerStats.stretchedDataRatio,stretchedDataRatioMax:n.extensions.customHealerStats.stretchedDataRatioMax,numberOfDecodedFrames:n.extensions.customHealerStats.numberOfDecodedFrames,usageMetricsCodecId:n.extensions.customHealerStats.usageMetricsCodecId,percentageOfPtime:n.extensions.customHealerStats.percentageOfPtime,pushPacketProcessingTimes:n.extensions.customHealerStats.pushPacketProcessingTimes,pullPacketProcessingTimes:n.extensions.customHealerStats.pullPacketProcessingTimes,pullProcessingTimePerStreamNumber:n.extensions.customHealerStats.pullProcessingTimePerStreamNumber,cnpPushCount:n.extensions.customHealerStats.cnpPushCount,cnpPullCount:n.extensions.customHealerStats.cnpPullCount,numberOfCNFrames:n.extensions.customHealerStats.numberOfCNFrames,redPacketsCount:n.extensions.customHealerStats.redPacketsCount,pullNumOfStreamsCounter:n.extensions.customHealerStats.pullNumOfStreamsCounter}},this.duration++}Tt(t,r,i)}},UD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new ED,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.bytesSendDiff=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.rttAverager=new uD,this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost)??0;this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDiff.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDiff.delta;this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,bitrate:i?8*i:0,rttAvg:Ct(this.rttAverager.avg),callIsMuted:this.diagnostics.callIsMuted,rawInputVolume:this.diagnostics.audioLevel},this.duration++}},BD=class{constructor(e){this.diagnostics=e,this.duration=0,this.lossRateAverager=new uD,this.bitrateAverager=new uD,this.rttAverager=new uD}processSample(e,t,i){const n=e[0],r={outboundRTP:n.outboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),r.aggregated={duration:this.duration,lossRateMax:this.lossRateAverager.maxSample,bitrateAvg:Ct(this.bitrateAverager.avg,0),bitrateMax:Ct(this.bitrateAverager.maxSample,0),rttAvg:Ct(this.rttAverager.avg),rttMax:Ct(this.rttAverager.maxSample),rawInputVolume:this.diagnostics.audioLevel,audioLevel:n.track?.audioLevel??n.mediaSource?.audioLevel},this.duration++),Tt(t,r,i)}},VD=g,HD={fs:0,fps:1},$D=class{constructor(e){this.logger=e,this.allowed=new Map,this.lastParams=new Map,this.currentEvents=new Map,this.finishedEvents=[]}setMaxCapabilities(e){e.forEach((e=>{if(e.ssrc||0===e.ssrc){this.finishIfActive(e.ssrc),this.allowed.set(e.ssrc,{fs:e.maxFs+HD.fs,fps:e.maxFps+HD.fps});const t=this.lastParams.get(e.ssrc);t&&this.setCurrentParams(e.ssrc,t.fs,t.fps)}}))}setCurrentParams(e,t,i){this.lastParams.set(e,{fs:t,fps:i});const n=this.getAllowedParams(e);n&&(t>n.fs||i>n.fps)?(this.captureOvershoot(e,i,n.fps,"fps"),this.captureOvershoot(e,t,n.fs,"fs")):n&&this.finishIfActive(e)}flush(){this.currentEvents.forEach(((e,t)=>this.finishIfActive(t)))}getEvents(){const e=[...lt(this.finishedEvents)],t=Date.now();return this.currentEvents.forEach((i=>i.forEach((i=>e.push({ssrc:i.ssrc,timestamp:i.timestamp,duration:t-i.timestamp,overshootType:i.overshootType,amount:i.amount}))))),e}captureOvershoot(e,t,i,n){const r=this.currentEvents.get(e)||[],a=r.findIndex((e=>e.overshootType===n)),s=r[a],o=t-i,l=HD[n];o<=l&&s?(s.duration=Date.now()-s.timestamp,this.finishedEvents.push(s),this.logger.debug(`stopped overshooting ${n} by ${s.amount}`),r.splice(a,1)):o>l&&!s?(this.logger.safe.info(`overshooting ${n} by ${t-i}`),r.push({ssrc:e,timestamp:Date.now(),duration:-1,overshootType:n,amount:{min:o,max:o}})):o>l&&s&&(s.amount={min:Math.min(s.amount.min,o),max:Math.max(s.amount.max,o)}),r.length?this.currentEvents.set(e,r):this.currentEvents.has(e)&&this.currentEvents.delete(e)}getAllowedParams(e){return this.allowed.get(e)||this.allowed.get(0)}finishIfActive(e){const t=this.currentEvents.get(e);if(t){const i=Date.now();t.forEach((t=>{t.duration=i-t.timestamp,this.finishedEvents.push(t),this.logger.debug(`finished overshooting ${t.overshootType} by min:${t.amount.min} max:${t.amount.max} for ${t.duration}ms for ssrc ${e}`)})),this.currentEvents.delete(e)}}},GD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.recvExtenders=new Map,this.sendExtenders=new Map}processStats(e){if(!e)return;const t=new Set;if(e.send&&(0,VD.flatMap)(e.send,(e=>[e,...e.altLayouts??[]])).forEach((e=>{try{t.add(e.outboundRTP.id);let i=this.sendExtenders.get(e.outboundRTP.id)??new WD(this.diagnostics,this.configProvider);e.outboundRTP.bytesSent<i.lastBytes&&(i=new WD(this.diagnostics,this.configProvider)),this.sendExtenders.set(e.outboundRTP.id,i),i.processSample(e)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:send",Be(e))}})),Lt(this.sendExtenders,t),t.clear(),e.recv)for(const i of e.recv)try{t.add(i.inboundRTP.id);let e=this.recvExtenders.get(i.inboundRTP.id)??new jD(this.configProvider);i.inboundRTP.bytesReceived<e.lastBytes&&(e=new jD(this.configProvider)),this.recvExtenders.set(i.inboundRTP.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("VideoStatsProcessor:recv",Be(e))}Lt(this.recvExtenders,t)}},jD=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new ED,this.bytesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.framesReceivedDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.framesDecodedDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.trackFramesDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.decodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new gD(2):new pD,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.freezeHistogram=new fD,this.harmonicDecodedFps=new SD(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.prevTimeToFirstFrame=-1,this.lastBytes=0,this.macroblockStatsTracker=new AD}processSample(e){const t=this.lossRateCalculator.calculate(e.inboundRTP.packetsReceived,e.inboundRTP.packetsLost)??0;this.framesReceivedDelta.captureSample(e.inboundRTP.framesReceived,e.inboundRTP.timestamp),this.framesDecodedDelta.captureSample(e.inboundRTP.framesDecoded,e.inboundRTP.timestamp),this.trackFramesDelta.captureSample(e.inboundRTP.framesReceived??e.track?.framesReceived,e.inboundRTP.timestamp),this.packetsDelta.captureSample(e.inboundRTP.packetsReceived,e.inboundRTP.timestamp),this.packetsLostDelta.captureSample(e.inboundRTP.packetsLost,e.inboundRTP.timestamp);const i=this.framesReceivedDelta.delta,n=this.framesDecodedDelta.delta;this.harmonicDecodedFps.captureSample(n),this.decodeTimeDelta.captureSample(e.inboundRTP.totalDecodeTime,e.inboundRTP.timestamp);const r=this.decodeTimeDelta.delta&&n&&Ct(this.decodeTimeDelta.delta/n*1e3,0),a=e.renderer?.timeToFirstFrame??-1;this.freezeHistogram.active=-1!==a&&-1!==this.prevTimeToFirstFrame&&(0===n||0===i),this.prevTimeToFirstFrame=a,this.lastBytes=e.inboundRTP.bytesReceived,this.bytesReceivedDelta.captureSample(e.inboundRTP.bytesReceived,e.inboundRTP.timestamp);const s=this.bytesReceivedDelta.delta,o=e.inboundRTP.jitterBufferEmittedCount&&Ct((e.inboundRTP.jitterBufferDelay??0)/e.inboundRTP.jitterBufferEmittedCount*1e3),l=RD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,i||0),c=RD(e.inboundRTP.frameWidth,e.inboundRTP.frameHeight,n||0);this.macroblockStatsTracker.captureSample(l,c),e.extensions={lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,frameRateReceived:i,frameRateDecoded:n,trackRecvFps:this.trackFramesDelta.delta,decodeTime:r||0,jitterBufferMs:o,bitrate:s?8*s:0,isFrozen:this.freezeHistogram.active,macroblockRateReceived:l,macroblockRateDecoded:c,macroblockRateStats:this.macroblockStatsTracker.getReport(),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,powerEfficient:void 0!==e.inboundRTP.powerEfficientDecoder?e.inboundRTP.powerEfficientDecoder:bD(e.inboundRTP.decoderImplementation),totalFreezeFraction:this.duration?this.freezeHistogram.totalDuration/this.duration:0,fpsHarmonicAverage:Ct(this.harmonicDecodedFps.harmonicMean)},this.duration++}},zD=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new uD,this.bitrateAverager=new uD,this.jitterAverager=new uD,this.frameRateAverager=new uD,this.freezeHistogram=new fD,this.harmonicDecodedFps=new SD(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.resolutionDurations=new vD,this.codecCalculator=new PD}processSample(e,t,i){const n=e.sort(((e,t)=>t.inboundRTP.frameHeight*t.inboundRTP.frameWidth-e.inboundRTP.frameHeight*e.inboundRTP.frameWidth))[0],r={inboundRTP:n.inboundRTP};n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec,this.configProvider?.config.isAv1Allowed&&"sharing"===n.mediaEntity?.modality&&this.codecCalculator.captureSample(n.codec.mimeType,n.renderer?.msi)),n.track&&(r.track=n.track),n.remoteOutboundRTP&&(r.remoteOutboundRTP=n.remoteOutboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions&&(this.harmonicDecodedFps.captureSample(n.extensions.frameRateDecoded),this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.jitterAverager.captureSample(1e3*(n.inboundRTP.jitter??0)),this.frameRateAverager.captureSample(n.extensions.frameRateReceived??n.extensions.frameRateDecoded),this.freezeHistogram.active=n.extensions.isFrozen,n.inboundRTP.frameWidth&&n.inboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.inboundRTP.frameWidth}x${n.inboundRTP.frameHeight}`),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,avgFrameRate:Ct(this.frameRateAverager.avg),fpsHarmonicAverage:Ct(this.harmonicDecodedFps.harmonicMean),avgJitterBufferSize:Ct(this.jitterAverager.avg),bitrateAvg:Ct(this.bitrateAverager.avg,0),bitrateMax:Ct(this.bitrateAverager.maxSample,0),bitrateMinNonZero:Ct(this.bitrateAverager.minNonZeroSample,0),ongoingFreezeDuration:this.freezeHistogram.ongoingDuration,numFreezes:this.freezeHistogram.numEvents,avgFreezeDuration:Ct(this.freezeHistogram.avgDuration),longestFreeze:this.freezeHistogram.longestDuration,totalFreezeDuration:this.freezeHistogram.totalDuration,freezeCountHistogram:this.freezeHistogram.counts,freezeTimestampsHistogram:this.freezeHistogram.timestamps,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,macroblockRateStats:n.extensions.macroblockRateStats,codecReport:this.codecCalculator?.report},this.duration++),Tt(t,r,i)}},WD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.duration=0,this.lossRateCalculator=new ED,this.lossRateAverager=new uD,this.captureFreezeIntervalsCount=0,this.bytesSendDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.encodedFramesDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.sentFramesDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.packetsLostDelta=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.harmonicEncodedFps=new SD(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax),this.encodeTimeDelta=this.useLastSampleDeltaPerSecondConverter?new gD(2):new pD,this.qpDelta=this.useLastSampleDeltaPerSecondConverter?new gD(3):new pD,this.fsOvershoot=new _D,this.fpsOvershoot=new _D(1),this.brOvershoot=new _D,this.plisDelta=new pD,this.pliRate=new ID(60),this.resolutionSwitcherTracker=new wD(this.configProvider.config.diagnostics.collectionLimits.numResolutionSwitches),this.bitrateAverager=new uD,this.rttAverager=new uD,this.lastBytes=0}processSample(e){const t=this.lossRateCalculator.calculate(e.remoteInboundRTP?.packetsReceived,e.remoteInboundRTP?.packetsLost);this.lossRateAverager.captureSample(t),this.plisDelta.captureSample(e.outboundRTP.pliCount),this.pliRate.captureSample(this.plisDelta.delta),this.packetsDelta.captureSample(e.outboundRTP.packetsSent,e.outboundRTP.timestamp),this.packetsLostDelta.captureSample(e.remoteInboundRTP?.packetsLost,e.remoteInboundRTP?.timestamp),this.lastBytes=e.outboundRTP.bytesSent,this.bytesSendDelta.captureSample(e.outboundRTP.bytesSent,e.outboundRTP.timestamp);const i=this.bytesSendDelta.delta,n=i?8*i:void 0;this.bitrateAverager.captureSample(n),this.rttAverager.captureSample(1e3*(e.remoteInboundRTP?.roundTripTime??0)),this.encodedFramesDelta.captureSample(e.outboundRTP.framesEncoded,e.outboundRTP.timestamp);const r=this.encodedFramesDelta.delta;this.sentFramesDelta.captureSample(e.outboundRTP.framesSent,e.outboundRTP.timestamp);const a=this.sentFramesDelta.delta||0;this.harmonicEncodedFps.captureSample(r);const s=e.mediaSource?.framesPerSecond;0===s&&void 0!==this.lastCaptureFramerate&&this.lastCaptureFramerate>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFramerate=s,this.encodeTimeDelta.captureSample(e.outboundRTP.totalEncodeTime,e.outboundRTP.timestamp);const o=this.encodeTimeDelta.delta&&r&&Ct(this.encodeTimeDelta.delta/r*1e3,0);this.qpDelta.captureSample(e.outboundRTP.qpSum,e.outboundRTP.timestamp);const l=this.qpDelta.delta&&r&&Ct(this.qpDelta.delta/r,2);e.outboundRTP.frameWidth&&e.outboundRTP.frameHeight&&this.resolutionSwitcherTracker.captureSample(e.outboundRTP.frameWidth,e.outboundRTP.frameHeight);const c=this.diagnostics.deviceManager?.latestCameraOpenResolution,d=e.appliedCapabilities??e.requestedCapabilities;d&&(void 0!==e.outboundRTP.frameHeight&&void 0!==e.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(e.outboundRTP.frameHeight/16*(e.outboundRTP.frameWidth/16),d.maxFs),this.fpsOvershoot.captureSample(a,d.maxFps),d.maxBr&&this.brOvershoot.captureSample(n,d.maxBr));const u=[];for(const e of this.fsOvershoot.events)u.push({...e,overshootType:"fs"});for(const e of this.fpsOvershoot.events)u.push({...e,overshootType:"fps"});for(const e of this.brOvershoot.events)u.push({...e,overshootType:"br"});u.sort(((e,t)=>e.timestamp-t.timestamp)),e.extensions={cameraOpenResolution:c,lossRate:t,packetsPerSecond:this.packetsDelta.delta,packetsLostPerSecond:this.packetsLostDelta.delta,duration:this.duration,pliRate:this.pliRate.getRate(),frameRateEncoded:this.encodedFramesDelta.delta,frameRateSent:a,bitrate:n||0,encodeTime:o||0,qp:l||0,captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:u,powerEfficient:void 0!==e.outboundRTP.powerEfficientEncoder?e.outboundRTP.powerEfficientEncoder:bD(e.outboundRTP.encoderImplementation),bitrateAvg:Ct(this.bitrateAverager.avg,0),rttAvg:Ct(this.rttAverager.avg)},this.duration++}},qD=class{constructor(e){this.configProvider=e,this.duration=0,this.lossRateAverager=new uD,this.bitrateAverager=new uD,this.sendBWEAverager=new uD,this.rttAverager=new uD,this.framerateAverager=new uD,this.captureFpsAverager=new uD,this.captureFreezeIntervalsCount=0,this.lastCaptureFps=void 0,this.resolutionDurations=new vD,this.fsOvershoot=new _D,this.fpsOvershoot=new _D(1),this.brOvershoot=new _D,this.harmonicEncodedFps=new SD(this.configProvider.config.webrtcStatPollInterval*this.configProvider.config.coeffOfValidTimeDelayBetweenFramesArrival,this.configProvider.config.invalidFPSAboveMax)}processSample(e,t,i){e.length>1&&e.sort(((e,t)=>{const i=e.appliedCapabilities??e.requestedCapabilities,n=t.appliedCapabilities??t.requestedCapabilities;return i?.maxMbps&&n?.maxMbps?n.maxMbps-i.maxMbps:0}));const n=e[0],r={outboundRTP:n.outboundRTP};if(n.transport&&Object.defineProperty(r,"transport",{value:n.transport,configurable:!1,enumerable:!1}),n.codec&&(r.codec=n.codec),n.track&&(r.track=n.track),n.mediaSource&&(r.mediaSource=n.mediaSource),n.remoteInboundRTP&&(r.remoteInboundRTP=n.remoteInboundRTP),n.extensions&&(r.extensions=n.extensions),n.extensions){this.lossRateAverager.captureSample(n.extensions.lossRate),this.bitrateAverager.captureSample(n.extensions.bitrate),this.sendBWEAverager.captureSample(n.transport?.selectedCandidatePair?.availableOutgoingBitrate),this.rttAverager.captureSample(n.remoteInboundRTP?.roundTripTime),this.framerateAverager.captureSample(n.extensions.frameRateSent);const e=n.mediaSource?.framesPerSecond;this.captureFpsAverager.captureSample(e),0===e&&void 0!==this.lastCaptureFps&&this.lastCaptureFps>0&&this.captureFreezeIntervalsCount++,this.lastCaptureFps=e,n.outboundRTP.frameWidth&&n.outboundRTP.frameHeight&&this.resolutionDurations.captureSample(`${n.outboundRTP.frameWidth}x${n.outboundRTP.frameHeight}`);const t=n.appliedCapabilities??n.requestedCapabilities;t&&(void 0!==n.outboundRTP.frameHeight&&void 0!==n.outboundRTP.frameWidth&&this.fsOvershoot.captureSample(n.outboundRTP.frameHeight/16*(n.outboundRTP.frameWidth/16),t.maxFs),this.fpsOvershoot.captureSample(n.extensions.frameRateSent,t.maxFps),t.maxBr&&this.brOvershoot.captureSample(n.extensions?.bitrate,t.maxBr)),this.harmonicEncodedFps.captureSample(n.extensions.frameRateEncoded);const i=[];for(const e of this.fsOvershoot.events)i.push({...e,overshootType:"fs"});for(const e of this.fpsOvershoot.events)i.push({...e,overshootType:"fps"});for(const e of this.brOvershoot.events)i.push({...e,overshootType:"br"});i.sort(((e,t)=>e.timestamp-t.timestamp)),r.aggregated={lossRateMax:this.lossRateAverager.maxSample,duration:this.duration,frameRateAvg:Ct(this.framerateAverager.avg),captureFramerateAvg:Ct(this.captureFpsAverager.avg),fpsHarmonicAverage:Ct(this.harmonicEncodedFps.harmonicMean),qpAvg:Ct(n.outboundRTP.qpSum/n.outboundRTP.framesSent),rttAvg:Ct(this.rttAverager.avg),bitrateAvg:Ct(this.bitrateAverager.avg,0),bitrateMax:Ct(this.bitrateAverager.maxSample,0),bitrateMinNonZero:Ct(this.bitrateAverager.minNonZeroSample,0),bweAvg:Ct(this.sendBWEAverager.avg,0),captureFreezeIntervalsCount:this.captureFreezeIntervalsCount,numResolutionSwitches:this.resolutionDurations.changeCount,resolutionDurations:this.resolutionDurations.durations,resolutionDurationRatios:this.resolutionDurations.durationRatios,isFsOvershooting:this.fsOvershoot.isOvershooting,isFpsOvershooting:this.fpsOvershoot.isOvershooting,isBrOvershooting:this.brOvershoot.isOvershooting,totalFsOvershootDuration:this.fsOvershoot.totalDuration,totalFpsOvershootDuration:this.fpsOvershoot.totalDuration,totalBrOvershootDuration:this.brOvershoot.totalDuration,overshootEvents:i},this.duration++}Tt(t,r,i)}},KD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){const t=new Set;for(const i in e)try{t.add(i);const n=e[i],r=this.extenders.get(n.id)??new JD(this.configProvider,this.diagnostics);this.extenders.set(n.id,r),r.processSample(n)}catch(e){this.diagnostics.addStatsError("TransportStatsProcessor",Be(e))}Lt(this.extenders,t)}},JD=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.bwJumpsHistogramCollector=new fD,this.sendBWEAverager=new uD,this.recvBWEAverager=new uD,this.sendBW=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.recvBW=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.sendBWAverager=new uD,this.recvBWAverager=new uD}processSample(e){this.sendBWEAverager.captureSample(e.selectedCandidatePair?.availableOutgoingBitrate),this.recvBWEAverager.captureSample(e.selectedCandidatePair?.availableIncomingBitrate),this.sendBW.captureSample(e.selectedCandidatePair?.bytesSent,e.selectedCandidatePair?.timestamp),this.recvBW.captureSample(e.selectedCandidatePair?.bytesReceived,e.selectedCandidatePair?.timestamp);const t=this.sendBW.delta,i=this.recvBW.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendBWAverager.captureSample(n),this.recvBWAverager.captureSample(r);const a=e.selectedCandidatePair?.availableOutgoingBitrate;a&&(this.bwJumpsHistogramCollector.active=this.bwJumpsHistogramCollector.active&&a<this.configProvider.config.webrtcBWJumpUpperLimit||a<this.configProvider.config.webrtcBWJumpLowerLimit),e.extensions={sendBWEAvg:Ct(this.sendBWEAverager.avg,0),sendBWEMax:Ct(this.sendBWEAverager.maxSample,0),recvBWEAvg:Ct(this.recvBWEAverager.avg,0),recvBWEMax:Ct(this.recvBWEAverager.maxSample,0),sendBitrate:n,recvBitrate:r,sendBWAvg:Ct(this.sendBWAverager.avg,0),sendBWMax:Ct(this.sendBWAverager.maxSample,0),recvBWAvg:Ct(this.recvBWAverager.avg,0),recvBWMax:Ct(this.recvBWAverager.maxSample,0),bwJumpsHistogram:this.bwJumpsHistogramCollector.counts,reflexiveLocalIP:this.diagnostics.reflexiveLocalIP}}},YD=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.extenders=new Map}processStats(e){if(!e)return;const t=new Set;for(const i of e)try{t.add(i.id);const e=this.extenders.get(i.id)??new QD(this.configProvider);this.extenders.set(i.id,e),e.processSample(i)}catch(e){this.diagnostics.addStatsError("DataChannelStatsProcessor",Be(e))}Lt(this.extenders,t)}},QD=class{constructor(e){this.configProvider=e,this.useLastSampleDeltaPerSecondConverter=this.configProvider.config.diagnostics.features.useLastSampleDeltaPerSecondConverter,this.sendBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.recvBytesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.sendMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new gD:new pD,this.recvMessagesDeltaCalculator=this.useLastSampleDeltaPerSecondConverter?new gD:new pD}processSample(e){this.sendBytesDeltaCalculator.captureSample(e.bytesSent,e.timestamp),this.recvBytesDeltaCalculator.captureSample(e.bytesReceived,e.timestamp);const t=this.sendBytesDeltaCalculator.delta,i=this.recvBytesDeltaCalculator.delta,n=t?8*t:void 0,r=i?8*i:void 0;this.sendMessagesDeltaCalculator.captureSample(e.messagesSent,e.timestamp),this.recvMessagesDeltaCalculator.captureSample(e.messagesReceived,e.timestamp);const a=this.sendMessagesDeltaCalculator.delta,s=this.recvMessagesDeltaCalculator.delta;e.extensions={sendBitrate:n,recvBitrate:r,sendMessageRate:a,recvMessageRate:s}}},ZD=class{constructor(e){this.collecVideoStatsAfterSubscription=e,this.videoStatsEvent=[],this.count=0}prepareCollectingStatsOnSubscribed(e){this.count=0,this.videoStatsEvent.push({ts:Date.now(),framesDecoded:[],bytesReceived:[],height:[],msi:e})}captureStatsOnSubscribed(e,t,i,n){if(this.count>=this.collecVideoStatsAfterSubscription)return;const r=It(this.videoStatsEvent);r&&(r.framesDecoded.push(e),r.bytesReceived.push(t),void 0!==i&&r.height.push(i)),this.count++}getStatsOnSubscribed(){return this.videoStatsEvent}},XD=class{constructor(e,t,i,n){this.slidingWindowSize=e,this.maxDeviation=t,this.minBandwidth=i,this.directionalityCheck=n,this.slidingWindow=new uA(this.slidingWindowSize),this.currentModality=null,this.previousModality=null,this.inProcess=!1}processBandwidth(e,t,i){this.currentModality?this.handleStopEvent(t,i):this.handleStartEvent(t,i),this.inProcess&&(this.stabilizationTime++,this.slidingWindow.add(e),this.inProcess=!this.slidingWindow.isFull||!this.isBandwidthStable())}getReport(e=!1){if(void 0!==this.stabilizationTime)return{time:this.inProcess?this.stabilizationTime:Math.max(this.stabilizationTime-this.slidingWindowSize,0),bandwidth:e?Ct(this.averageBandwidth,2):this.averageBandwidth,finished:!this.inProcess,modality:this.previousModality}}handleStartEvent(e,t){this.currentModality=this.GetModalityString(e),t&&this.currentModality&&!this.previousModality&&(this.previousModality=this.currentModality,this.stabilizationTime=0,this.slidingWindow.clear(),this.inProcess=!0)}handleStopEvent(e,t){t&&(this.directionalityCheck(e.audio)||this.directionalityCheck(e.video)||this.directionalityCheck(e.sharing))||(this.currentModality=null,this.inProcess=!1)}GetModalityString(e){return[this.directionalityCheck(e.audio)?Qe.MODALITY.audio:null,this.directionalityCheck(e.video)?Qe.MODALITY.video:null,this.directionalityCheck(e.sharing)?Qe.MODALITY.sharing:null].filter(Boolean).join(", ")}isBandwidthStable(){if(this.averageBandwidth=it(this.slidingWindow.items),this.averageBandwidth<this.minBandwidth)return!1;{const e=this.averageBandwidth*this.maxDeviation,t=this.averageBandwidth-e,i=this.averageBandwidth+e;return this.slidingWindow.items.every((e=>mt(e,t,i)))}}},eO=class{constructor(e,t){this.diagnostics=e,this.configProvider=t,this.uplinkStabilizationTelemetry=new XD(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wg),this.downlinkSabilizationTelemetry=new XD(this.configProvider.config.downlinkBWStabilizationSlidingWindowSize,this.configProvider.config.downlinkBWStabilizationMaxDeviation,this.configProvider.config.downlinkBWStabilizationMinBandwidth,qg),this.bandwidthCalculator=new TD,this.bandwidthAvg=new uD}processStats(e){const t=this.diagnostics.getObjectRef(),i=t?.activeModalities;if(!i||!e.transports)return;const n=e.transports[Object.keys(e.transports)[0]],r=t?.reportedReceiveBandwidth?.[t.reportedReceiveBandwidth.length-1],a=n?.selectedCandidatePair?.availableOutgoingBitrate,s=e.audio?.send?.length>0||e.video?.send?.length>0||e.sharing?.send?.length>0,o=e.audio?.recv?.length>0||e.video?.recv?.length>0||e.sharing?.recv?.length>0;this.bweType!==t?.bweType&&(this.bandwidthCalculator=new TD,this.bandwidthAvg=new uD,this.bweType=t?.bweType);const l="REMB"===t?.bweType?"availableIncomingBitrate":"availableOutgoingBitrate",c=n?.selectedCandidatePair?.[l];this.bandwidthCalculator.captureSample(c),this.bandwidthAvg.captureSample(c);try{this.uplinkStabilizationTelemetry.processBandwidth(a,i,s),this.downlinkSabilizationTelemetry.processBandwidth(r,i,o)}catch(e){this.diagnostics.addStatsError("BandwithStatsProcessor",Be(e))}}getStabilizedReport(e=!1){return this.uplinkStabilizationTelemetry.getReport(e)}getDownlinkStabilizedReport(e=!1){return this.downlinkSabilizationTelemetry.getReport(e)}calculateBwPercentiles(){if(!this.bandwidthCalculator.getFirst())return;const e=this.configProvider.config.bwPercentiles,t={};return e.forEach((e=>{Object.defineProperty(t,e,{value:this.bandwidthCalculator.calculatePercentile(e/100),enumerable:!0})})),t}getBandwidthReport(){return{startOfTheCall:this.bandwidthCalculator.getFirst(),endOfTheCall:this.bandwidthCalculator.getLast(),std:this.bandwidthCalculator.calculateStd(),bwPercentiles:this.calculateBwPercentiles(),avgBwe:Ct(this.bandwidthAvg.avg,2)}}},tO=class{constructor(e,t){this.configProvider=e,this.diagnostics=t,this.dataChannelStatsProcessor=new YD(this.diagnostics,this.configProvider),this.transportStatsProcessor=new KD(this.diagnostics,this.configProvider),this.audioStatsProcessor=new LD(this.diagnostics,this.configProvider),this.videoStatsProcessor=new GD(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new GD(this.diagnostics,this.configProvider),this.bandwithStatsProcessor=new eO(this.diagnostics,this.configProvider),this.macroblockStatsTracker=new AD,this.statsAggregators={audio:{recv:new FD,send:new BD(this.diagnostics)},video:{recv:new zD(this.configProvider),send:new qD(this.configProvider)},sharing:{recv:new zD(this.configProvider),send:new qD(this.configProvider)}},this.aggregatedModalityStats={},this.recvVideoStreamsCounter=new hD,this.multiviewData={},this.multiviewKeySet=new Set,this.statsOnSubscribedData={video:{},sharing:{}},this.statsOnSubscribed={video:[],sharing:[]},this.diagnostics.aggregatedStatsRef=this.aggregatedModalityStats,this.diagnostics.statsOnSubscribed=this.statsOnSubscribed,this.diagnostics.bandwidthDiagnostic=this.bandwithStatsProcessor}processStats(e){this.dataChannelStatsProcessor.processStats(e.data),this.transportStatsProcessor.processStats(e.transports),this.audioStatsProcessor.processStats(e.audio),this.videoStatsProcessor.processStats(e.video),this.sharingStatsProcessor.processStats(e.sharing),this.bandwithStatsProcessor.processStats(e),this.diagnostics.bwStabiliationTime=this.bandwithStatsProcessor.getStabilizedReport(!0),this.diagnostics.bwDownlinkStabiliationTime=this.bandwithStatsProcessor.getDownlinkStabilizedReport(!0),this.recvVideoStreamsCounter.captureSample(e.video?.recv?.length),this.diagnostics.recvVideoStreamsCount={min:this.recvVideoStreamsCounter.min,max:this.recvVideoStreamsCounter.max,mode:this.recvVideoStreamsCounter.mode};try{this.processAggregated(e)}catch(e){this.diagnostics.addStatsError("webrtcStatistics:processAggregated",Be(e))}try{this.processMultiview(e.video?.recv??[])}catch(e){this.diagnostics.addStatsError("webrtcStatistics:processMultiview",Be(e))}try{const e=navigator?.connection;e&&this.diagnostics.addNetworkInfo({downlink:e.downlink,rtt:e.rtt,effectiveType:e.effectiveType,saveData:e.saveData})}catch(e){this.diagnostics.addStatsError("webrtcStatistics:processStats(networkInfo)",Be(e))}try{this.processMacroblockRateStats(e.video?.recv)}catch(e){this.diagnostics.addStatsError("webrtcStatistics: processMacroblockRateStats",Be(e))}}signalNoConnection(){this.transportStatsProcessor=new KD(this.diagnostics,this.configProvider),this.audioStatsProcessor=new LD(this.diagnostics,this.configProvider),this.videoStatsProcessor=new GD(this.diagnostics,this.configProvider),this.sharingStatsProcessor=new GD(this.diagnostics,this.configProvider)}processMultiview(e){const t=new Set;for(const i of e){const e=i.inboundRTP.id;t.add(e);let n=this.multiviewData[e];n&&this.multiviewKeySet.has(e)?n.stats.duration++:(n={bitrateAverager:new uD,jitterAverager:new uD,frameRateAverager:new uD,freezeHistogram:new fD,resolutionDurations:new vD,isRenderingEvents:[],statsOnSubscribed:new ZD(this.configProvider.config.diagnostics.telemetryLimits.maxVideoStatsAfterSubscription),stats:{ssrc:i.inboundRTP.ssrc,startTime:Date.now(),duration:0,framesDecoded:[],bytesReceived:[],height:[],width:[]}},n.statsOnSubscribed.prepareCollectingStatsOnSubscribed(i.renderer?.msi),this.multiviewData[e]=n),n.statsOnSubscribed.captureStatsOnSubscribed(i.inboundRTP.framesDecoded,i.inboundRTP.bytesReceived,i.inboundRTP.frameHeight),n.bitrateAverager.captureSample(i.extensions?.bitrate),n.jitterAverager.captureSample(1e3*(i.inboundRTP.jitter??0)),n.frameRateAverager.captureSample(i.extensions.frameRateReceived),n.freezeHistogram.active=i.extensions?.isFrozen,i.inboundRTP.frameWidth&&i.inboundRTP.frameHeight&&n.resolutionDurations.captureSample(`${i.inboundRTP.frameWidth}x${i.inboundRTP.frameHeight}`);const r=i.renderer?.isRendering??!1;(!n.isRenderingEvents.length&&r||n.isRenderingEvents.length&&It(n.isRenderingEvents).isRendering!==r)&&Tt(n.isRenderingEvents,{isRendering:r,ts:Date.now()},this.configProvider.config.diagnostics.collectionLimits.numIsRenderingEvents),n.stats.frameRateAvg=Ct(n.frameRateAverager.avg),n.stats.bitrateAvg=Ct(n.bitrateAverager.avg,0),n.stats.bitrateMax=Ct(n.bitrateAverager.maxSample,0),n.stats.bitrateMinNonZero=Ct(n.bitrateAverager.minNonZeroSample),n.stats.freezeHistogram=n.freezeHistogram.counts,n.stats.freezeTimestamps=n.freezeHistogram.timestamps,n.stats.avgFreezeDuration=Ct(n.freezeHistogram.avgDuration),n.stats.totalFreezeDuration=n.freezeHistogram.totalDuration,n.stats.ongoingFreeze=n.freezeHistogram.active,n.stats.ongoingFreezeDuration=n.freezeHistogram.ongoingDuration,n.stats.numResolutionSwitches=n.resolutionDurations.changeCount,n.stats.rendererSize=`${i.renderer?.rendererSize?.width}x${i.renderer?.rendererSize?.height}`,n.stats.resolutionDurations=n.resolutionDurations.durations,n.stats.timeToFirstFrame=i.renderer?.timeToFirstFrame,n.stats.timeToFirstFrameSinceSubscriptionStart=i.renderer?.timeToFirstFrameSinceSubscriptionStart,n.stats.isRenderingEvents=n.isRenderingEvents,n.stats.statsOnSubscribed=n.statsOnSubscribed.getStatsOnSubscribed(),n.stats.msi=i.renderer?.msi,n.stats.rendererStates=i.renderer?.rendererStates,Tt(n.stats.framesDecoded,i.inboundRTP.framesDecoded,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Tt(n.stats.bytesReceived,i.inboundRTP.bytesReceived,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Tt(n.stats.height,i.inboundRTP.frameHeight,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),Tt(n.stats.width,i.inboundRTP.frameWidth,this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples);const a=i.extensions?.macroblockRateStats??{};for(const e in a)n.stats[e]=Ct(a[e],0)}this.diagnostics.multiViewStats=Object.values(this.multiviewData).map((e=>e.stats)),this.multiviewKeySet=t}processAggregated(e){for(const t of["audio","video","sharing"])if(e[t])for(const i in e[t])this.processAggregatedModality(e,t,i)}processAggregatedModality(e,t,i){var n,r;const a=e[t]?.[i]?.length??0;a>0&&((n=this.aggregatedModalityStats)[t]??(n[t]={}),(r=this.aggregatedModalityStats[t])[i]??(r[i]=[]),a>1&&("audio"===t||"sharing"===t)&&this.diagnostics.addStatsError("webrtcStatistics:processAggregatedModality",`Multiple ${t} ${i} streams: ${a}`),this.statsAggregators[t][i].processSample(e[t][i],this.aggregatedModalityStats[t][i],this.configProvider.config.diagnostics.telemetryLimits.numAggregatedSamples),"sharing"!==t&&"video"!==t||"recv"!==i||this.processStatsOnSubscribed(e[t][i],t))}processStatsOnSubscribed(e,t){const i=new Set;for(const n of e)if(n.inboundRTP){const e=`${n.inboundRTP.id}x${n.renderer?.msi}`;let r=this.statsOnSubscribedData[t]?.[e];i.add(e),r||(r=new ZD(this.configProvider.config.diagnostics.telemetryLimits.maxVideoStatsAfterSubscription),r.prepareCollectingStatsOnSubscribed(n.renderer?.msi),this.statsOnSubscribedData[t][e]=r,this.statsOnSubscribed[t].push(...r.getStatsOnSubscribed())),r.captureStatsOnSubscribed(n.inboundRTP.framesDecoded,n.inboundRTP.bytesReceived)}!function(e,t){const i=[];for(const n of Object.keys(e))t.has(n)||i.push(n);for(const t of i)delete e[t]}(this.statsOnSubscribedData[t],i)}processMacroblockRateStats(e){if(!e?.length)return;let t=0,i=0;for(const n of e)t+=n.extensions?.macroblockRateReceived,i+=n.extensions?.macroblockRateDecoded;this.macroblockStatsTracker.captureSample(t,i),this.diagnostics.setTotalVideoRecvMblocksRates(this.macroblockStatsTracker.getReport())}},iO=g,nO=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.webrtcStats=new tO(this.configProvider,this.diagnostics),this.ssrcToRecvTrackMap=new Map,this.activeChannels={}}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}signalNoConnection(){this.webrtcStats.signalNoConnection()}processRawReport(e){this.diagnostics.latestRawReport=e;const t={loopTime:-1,fetchTime:-1,convertTime:-1,processingTime:-1,legacyProcessingTime:-1};try{let i=Pt(),n=i;const r=this.convertStatsReport(e);return r.perfCounters=t,i=Pt(),t.convertTime=i-n,n=i,this.webrtcStats.processStats(r),this.diagnostics.addStatsReport(r),i=Pt(),t.processingTime=i-n,r}catch(e){const t=Be(e);return this.logger.safe.error(`Error processing raw stats: ${t}`),void this.diagnostics.addStatsError("StatisticsGatherer:processRawReport",t)}}setSsrcTrackPair(e,t){null===t?this.ssrcToRecvTrackMap.delete(e):this.ssrcToRecvTrackMap.set(e,t)}convertStatsReport(e){const t={transports:this.processTransportStats(e)};return this.appendPcStats(e,t),this.appendSendMediaStats(e,t),this.appendRecvMediaStats(e,t),e["data-channel"]&&(t.data=Object.values(e["data-channel"])),t}processTransportStats(e){if(e.transport){const t={};for(const i in e.transport){const n=e.transport[i];if(t[i]=ot(n),n.selectedCandidatePairId){const r=ot(e["candidate-pair"][n.selectedCandidatePairId]);r.localCandidate=e["local-candidate"][r.localCandidateId],r.remoteCandidate=e["remote-candidate"][r.remoteCandidateId],t[i].selectedCandidatePair=r}n.localCertificateId&&e.certificate&&(t[i].localCertificate=e.certificate[n.localCertificateId]),n.remoteCertificateId&&e.certificate&&(t[i].remoteCertificate=e.certificate[n.remoteCertificateId])}return t}if(e["candidate-pair"]){const t={};for(const i in e["candidate-pair"]){const n=ot(e["candidate-pair"][i]);n.selected&&(n.localCandidate=e["local-candidate"][n.localCandidateId],n.remoteCandidate=e["remote-candidate"][n.remoteCandidateId],t.faketransport={id:"faketransport",timestamp:n.timestamp,type:"transport",selectedCandidatePair:n,selectedCandidatePairId:n.id})}return t}}appendPcStats(e,t){let i="";e["peer-connection"]&&(Object.keys(e["peer-connection"]).forEach((e=>{""===i?i=e:(this.logger.safe.error(`Unexpected second peer connection stats id ${e}, also found ${i}`),this.diagnostics.addStatsError("StatisticsGatherer","Unexpected second peer connection stats"))})),t.peerConnection=e["peer-connection"][i])}appendSendMediaStats(e,t){var i,n,r,a;for(const s in e["outbound-rtp"]){const o=e["outbound-rtp"][s],l={outboundRTP:o};o.codecId&&e.codec&&(l.codec=e.codec[o.codecId]),Object.defineProperty(l,"transport",{value:t.transports[o.transportId??"faketransport"],configurable:!1,enumerable:!1}),o.remoteId&&e["remote-inbound-rtp"]&&(l.remoteInboundRTP=e["remote-inbound-rtp"][o.remoteId]),o.mediaSourceId&&e["media-source"]&&(l.mediaSource=e["media-source"][o.mediaSourceId]),o.trackId&&e.track&&(l.track=e.track[o.trackId]);const c=lO(this.mediaManager,l.track?.trackIdentifier??l.mediaSource?.trackIdentifier,o.rid)??oO(this.mediaManager,o.ssrc,o.rid)??hO(this.mediaManager,l.outboundRTP.mid,o.rid);if(!c?.getLocalTrackId())continue;l.mediaEntity=c.serialize(),!l.mediaSource&&l.mediaEntity&&e["media-source"]&&(l.mediaSource=Object.values(e["media-source"]).find((e=>e.trackIdentifier===l.mediaEntity.localTrackId)));const d="video"===o.kind?"sharing"===c?.getModality()?"sharing":"video":o.kind;if((i=this.activeChannels)[d]??(i[d]={}),(n=this.activeChannels[d]).send??(n.send={}),Wg(this.diagnostics.getObjectRef().activeModalities?.[d])){if(t[d]||(t[d]={}),t[d].send||(t[d].send=[]),"video"===o.kind){const e=cO(this.diagnostics,d,o.ssrc)??cO(this.diagnostics,d,0);e&&(l.requestedCapabilities=e);const i=dO(this.diagnostics,d,o.ssrc)??dO(this.diagnostics,d,0);i&&(l.appliedCapabilities=i);const n=t[d].send.find((e=>e.outboundRTP.trackId===l.outboundRTP.trackId));if(n){const e=parseInt(n.outboundRTP.rid,10)>parseInt(l.outboundRTP.rid,10);if(!n.altLayouts&&e&&(n.altLayouts=[]),e)n.altLayouts.push(l);else{l.altLayouts=[],l.altLayouts.push(n);const e=t[d].send.indexOf(n);t[d].send[e]=l}continue}}this.activeChannels[d].send[o.id]=l,t[d].send.push(l)}else this.activeChannels[d].send[o.id]&&"sharing"!==d&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[d]??(r[d]={}),(a=t.inactiveTracks[d]).send??(a.send=[]),t.inactiveTracks[d].send.push(this.activeChannels[d].send[o.id]))}}appendRecvMediaStats(e,t){var i,n,r,a;const s=this.diagnostics.getObjectRef().subscriptionManager?.subscribedTrackIds;for(const o in e["inbound-rtp"]){const l=e["inbound-rtp"][o],c={inboundRTP:l};l.codecId&&e.codec&&(c.codec=e.codec[l.codecId]),"audio"===l.kind&&c.inboundRTP.ssrc===this.audioDecoderStatsProvider?.ssrc&&(c.codec||(c.codec={transportId:l.transportId??"faketransport",id:"fakeCodec",payloadType:999,timestamp:l.timestamp,type:"codec",mimeType:"unk"}),c.codec.mimeType=this.audioDecoderStatsProvider.codecName,c.inboundRTP=(0,iO.merge)(c.inboundRTP,this.audioDecoderStatsProvider.getWebRtcCompatibaleStats()),c.customHealerStats=this.audioDecoderStatsProvider.getWasmStats()),t.transports[l.transportId??"faketransport"]&&Object.defineProperty(c,"transport",{value:t.transports[l.transportId??"faketransport"],configurable:!1,enumerable:!1}),l.remoteId&&e["remote-outbound-rtp"]&&(c.remoteOutboundRTP=e["remote-outbound-rtp"][l.remoteId]);const d=c.inboundRTP.trackIdentifier??this.ssrcToRecvTrackMap.get(l.ssrc);if(l.trackId||d){l.trackId&&e.track?c.track=e.track[l.trackId]:d&&(c.track={id:"ssrcToTrackId",kind:l.kind,timestamp:l.timestamp,type:"track",trackIdentifier:d});const t=uO(this.diagnostics,c.track?.trackIdentifier);t&&(c.renderer=t)}const u=sO(this.mediaManager,c.track?.trackIdentifier)??aO(this.mediaManager,l.ssrc);if(!u)continue;c.mediaEntity=u.serialize();const h="video"===l.kind&&c.track?"sharing"===u?.getModality()?"sharing":"video":l.kind;(i=this.activeChannels)[h]??(i[h]={}),(n=this.activeChannels[h]).recv??(n.recv={}),"video"!==l.kind||s.some((e=>e&&e===c.track?.trackIdentifier))?qg(this.diagnostics.getObjectRef().activeModalities?.[h])&&(t[h]||(t[h]={}),t[h].recv||(t[h].recv=[]),this.activeChannels[h].recv[l.id]=c,t[h].recv.push(c)):this.activeChannels[h].recv[l.id]&&"sharing"!==h&&(t.inactiveTracks??(t.inactiveTracks={}),(r=t.inactiveTracks)[h]??(r[h]={}),(a=t.inactiveTracks[h]).recv??(a.recv=[]),t.inactiveTracks[h].recv.push(this.activeChannels[h].recv[l.id]))}}};function rO(e,t){return!t||e.getSimulcastContext()?.activeRids.map(String).some((e=>e===t))}function aO(e,t){return e.getMediaEntities().find((e=>e.getRemoteSsrc()===t))}function sO(e,t){const i=e.getMediaEntities();return void 0!==t?i.find((e=>e.getRemoteTrackId()===t)):void 0}function oO(e,t,i){return e.getMediaEntities().find((e=>e.getLocalSsrc()===t&&rO(e,i)))}function lO(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getLocalTrackId()===t&&rO(e,i))):void 0}function cO(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcRequestedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcRequestedCapabilities[`${i}`]:void 0}function dO(e,t,i){const n=e.getObjectRef().qualityManager;return"video"===t?n?.currentVideoSsrcAppliedCapabilities[`${i}`]:"sharing"===t?n?.currentSharingSsrcAppliedCapabilities[`${i}`]:void 0}function uO(e,t){return e.getObjectRef().remoteVideoManager?.renderers.find((e=>e.trackId===t))}function hO(e,t,i){const n=e.getMediaEntities();return t?n.find((e=>e.getMid()===t&&rO(e,i))):void 0}var pO=class{constructor(){this.googCandidatePair={},this.ssrc={},this.googComponent={},this.VideoBwe={bweforvideo:{}}}},gO=class{constructor(){this.statistics=new pO,this.statsDiffMap=new Map,this.ssrcTrackMap=new Map}build(e){return this.statistics=new pO,this.constructGoogCandidatePair(e),this.constructGoogSsrc(e),this.constructGoogComponent(e),this.constructDataChannel(e),this.constructBwe(e),this.statistics}setSsrcTrackPair(e,t){null===t?this.ssrcTrackMap.delete(e):this.ssrcTrackMap.set(e,t)}setAudioDecoderStatsProvider(e){this.audioDecoderStatsProvider=e}constructGoogSsrc(e){const t={};if(e.hasOwnProperty("outbound-rtp")){const i=e["outbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_send`,a=this.constructSendSsrc(e,i[n]);t[r]=a}))}if(e.hasOwnProperty("inbound-rtp")){const i=e["inbound-rtp"];Object.keys(i).forEach((n=>{const r=`ssrc_${i[n].ssrc}_recv`,a=this.constructRecvSsrc(e,i[n]);t[r]=a}))}this.statistics.ssrc=t}constructSendSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=t.mediaSourceId?e["media-source"][t.mediaSourceId]:null,r=e["remote-inbound-rtp"]?.[t.remoteId],a=`ssrc_${t.ssrc}_send`,s=n?.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let o={id:a,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesSent:t.bytesSent,bytesSentDiff:this.calculateDiff(a,t.bytesSent,4),packetsSent:t.packetsSent,packetsLost:r?.packetsLost,jitter:r?.jitter,googRtt:this.getRtt(r),googCodecName:this.getCodec(e,t.codecId),transportId:t.transportId,googTrackId:s};return"audio"===o.mediaType&&(o={...o,...this.constructAudioSendSsrc(t,n)}),"video"===o.mediaType&&(o={...o,...this.constructVideoSendSsrc(t,n,a,i)}),ct(o)}constructAudioSendSsrc(e,t){return{audioInputLevel:t?.audioLevel,totalAudioEnergy:t?.totalAudioEnergy,fecPacketsSent:e.fecPacketsSent}}constructVideoSendSsrc(e,t,i,n){return{framesEncoded:e.framesEncoded,googFrameRateEncoded:this.calculateDiff(i,e.framesEncoded,2),googFrameRateSent:this.calculateDiff(i,e.framesSent??n?.framesSent,1),googFrameRateInput:t?.framesPerSecond,googFrameHeightSent:e.frameHeight??n?.frameHeight,googFrameWidthSent:e.frameWidth??n?.frameWidth,googFrameHeightInput:t?.height,googFrameWidthInput:t?.width,hugeFramesSent:e.hugeFramesSent??n?.hugeFramesSent,keyFramesEncoded:e.keyFramesEncoded,qpSum:e.qpSum,qp:this.calculateDiff(i,e.qpSum,8),googPlisReceived:e.pliCount,googFirsReceived:e.firCount,googNacksReceived:e.nackCount,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,codecImplementationName:e.encoderImplementation,rid:e.rid,encodeTime:e.totalEncodeTime&&Math.round(1e3*this.calculateDiff(i,e.totalEncodeTime,6))}}constructRecvSsrc(e,t){const i=t.trackId?e.track[t.trackId]:null,n=`ssrc_${t.ssrc}_recv`,r=t.trackIdentifier??i?.trackIdentifier??this.ssrcTrackMap.get(t.ssrc);let a={id:n,ssrc:t.ssrc,mediaType:t.mediaType??t.kind,bytesReceived:t.bytesReceived,bytesReceivedDiff:this.calculateDiff(n,t.bytesReceived,5),packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,jitter:t.jitter,googJitterBufferMs:t.jitterBufferEmittedCount&&Math.round(t.jitterBufferDelay/t.jitterBufferEmittedCount*1e3),googCodecName:this.getCodec(e,t.codecId),googTrackId:r,transportId:t.transportId};return"audio"===a.mediaType&&(a={...a,...this.constructAudioRecvSsrc(t,i)}),"video"===a.mediaType&&(a={...a,...this.constructVideoRecvSsrc(t,n,i)}),ct(a)}constructAudioRecvSsrc(e,t){const i=this.audioDecoderStatsProvider?.ssrc===e.ssrc?this.audioDecoderStatsProvider?.getWebRtcCompatibaleStats():e,n={audioOutputLevel:i.audioLevel??t?.audioLevel,totalAudioEnergy:i.totalAudioEnergy??t?.totalAudioEnergy,concealedSamples:i.concealedSamples,silentConcealedSamples:i.silentConcealedSamples,totalSamplesReceived:i.totalSamplesReceived,healedRatio:i.totalSamplesReceived&&(i.concealedSamples-i.silentConcealedSamples)/i.totalSamplesReceived,fecPacketsReceived:i.fecPacketsReceived,fecPacketsDiscarded:i.fecPacketsDiscarded,packetsDiscarded:i.packetsDiscarded};if(this.audioDecoderStatsProvider?.ssrc===e.ssrc){n.googJitterBufferMs=i.jitterBufferEmittedCount&&Math.round(i.jitterBufferDelay/i.jitterBufferEmittedCount*1e3),n.googCodecName=this.audioDecoderStatsProvider.codecName;const e=this.audioDecoderStatsProvider.getDecoderStats();n.pushCount=e.pushCount,n.pushErrCount=e.pushErrCount,n.pullCount=e.pullCount,n.pullErrCount=e.pullErrCount}return n}constructVideoRecvSsrc(e,t,i){return{framesDecoded:e.framesDecoded,googFrameRateDecoded:this.calculateDiff(t,e.framesDecoded,3),googFrameRateReceived:this.calculateDiff(t,e.framesReceived??i?.framesReceived,0),googFrameHeightReceived:e.frameHeight??i?.frameHeight,googFrameWidthReceived:e.frameWidth??i?.frameWidth,keyFramesDecoded:e.keyFramesDecoded,googPlisSent:e.pliCount,googFirsSent:e.firCount,googNacksSent:e.nackCount,codecImplementationName:e.decoderImplementation,decodeTime:e.totalDecodeTime&&Math.round(1e3*this.calculateDiff(t,e.totalDecodeTime,7))}}constructGoogCandidatePair(e){const t=e["candidate-pair"];t&&Object.keys(t).forEach((i=>{const n=this.constructPair(e,t[i]);this.statistics.googCandidatePair[n.id]=n}))}constructPair(e,t){const i=e["local-candidate"][t.localCandidateId],n=e["remote-candidate"][t.remoteCandidateId];return ct({bytesReceived:t.bytesReceived,bytesSent:t.bytesSent,googTransportType:i.protocol,googRtt:t.currentRoundTripTime?Math.round(1e3*t.currentRoundTripTime):void 0,googLocalAddress:`${i.ip?i.ip:i.address}:${i.port}`,googLocalCandidateType:i.candidateType,localRelayProtocol:i.relayProtocol,localNetworkType:i.networkType,googRemoteAddress:`${n.ip?n.ip:n.address}:${n.port}`,googRemoteCandidateType:n.candidateType,googActiveConnection:t.nominated,requestsReceived:t.requestsReceived,requestsSent:t.requestsSent,responsesReceived:t.responsesReceived,responsesSent:t.responsesSent,consentRequestsSent:t.consentRequestsSent,id:t.id,remoteCandidateId:t.remoteCandidateId,localCandidateId:t.localCandidateId,googWritable:t.writable,selected:t.selected,packetsDiscardedOnSend:t.packetsDiscardedOnSend})}constructGoogComponent(e){e.transport&&Object.keys(e.transport).forEach((t=>{this.statistics.googComponent[t]={id:t,selectedCandidatePairId:e.transport[t].selectedCandidatePairId}}))}constructDataChannel(e){if(!e.hasOwnProperty("data-channel"))return;const t=e["data-channel"];this.statistics.data=Object.keys(t).map((e=>{const i=t[e];return{bytesReceived:i.bytesReceived,bytesSent:i.bytesSent,dataChannelIdentifier:i.dataChannelIdentifier,label:i.label,messagesReceived:i.messagesReceived,messagesSent:i.messagesSent,protocol:i.protocol,state:i.state,timestamp:i.timestamp,type:i.type}}))}constructBwe(e){const t=Object.values(e["outbound-rtp"]??{})?.find((e=>{const t=e.mediaType??e.kind;return"audio"===t||"video"===t}));if(!t)return;const i=e.transport?.[t.transportId];if(!i)return;const n=e["candidate-pair"]?.[i.selectedCandidatePairId];if(!n)return;const r={googAvailableSendBandwidth:n.availableOutgoingBitrate,googAvailableReceiveBandwidth:n.availableIncomingBitrate};this.statistics.VideoBwe.bweforvideo=ct(r)}getRtt(e){const t=e?.roundTripTime;return t?Math.round(1e3*t):void 0}getCodec(e,t){if(t&&e.codec&&e.codec[t])return e.codec[t].mimeType.split("/")[1]}calculateDiff(e,t,i){if(void 0===t)return;let n=t;const r=this.statsDiffMap.has(e)?this.statsDiffMap.get(e):new Map;if(r.has(i)){const e=r.get(i);e<=t&&(n=t-e)}return r.set(i,t),this.statsDiffMap.set(e,r),isNaN(n)?void 0:n}},mO=g,fO=g,vO=class{constructor(e){this.healedRatio=0,this.healedRatioMax=0,this.healedRatioDuration=0,this.healedRatioTotal=0,this.totalSamplesReceivedDiff=0;const t=e.config;this.networkDetectionDuration=t.webrtcStatNetworkDetectionDuration,this.networkRecvQualityDiagnostics=t.networkRecvQualityDiagnostics,this.networkRecvQualityDiagnostics&&(this.healedRatioAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.concealedSamplesDiffAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.silentConcealedSamplesDiffAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize),this.totalSamplesReceivedDiffAccumulator=new uA(t.webrtcHealedRatioExtendedWindowSize))}captureHealedRatioSamples(e,t,i){!e||!t||!i||e.length<=this.networkDetectionDuration||t.length<=this.networkDetectionDuration||i.length<=this.networkDetectionDuration||this.setHealedRatioPerDuration(e,t,i)}getHealedRatioMax(){return this.healedRatioMax}getHealedRatioAvg(){return this.healedRatioDuration?this.healedRatioTotal/this.healedRatioDuration:0}getHealedRatio(){return this.healedRatio}getTotalSamplesReceivedDiff(){return this.totalSamplesReceivedDiff}setHealedRatioPerDuration(e,t,i){const n=-1-this.networkDetectionDuration,r=Math.max((0,fO.last)(e)-(0,fO.nth)(e,n),0),a=Math.max((0,fO.last)(t)-(0,fO.nth)(t,n),0);this.totalSamplesReceivedDiff=Math.max((0,fO.last)(i)-(0,fO.nth)(i,n),0),0!==this.totalSamplesReceivedDiff&&(this.healedRatio=(r-a)/this.totalSamplesReceivedDiff,this.healedRatioDuration++,this.healedRatioTotal+=this.healedRatio,this.healedRatioMax=Math.max(this.healedRatioMax,this.healedRatio),this.networkRecvQualityDiagnostics&&(this.concealedSamplesAccumulator.add((0,fO.last)(e)),this.silentConcealedSamplesAccumulator.add((0,fO.last)(t)),this.totalSamplesReceivedAccumulator.add((0,fO.last)(i)),this.concealedSamplesDiffAccumulator.add(r),this.silentConcealedSamplesDiffAccumulator.add(a),this.totalSamplesReceivedDiffAccumulator.add(this.totalSamplesReceivedDiff),this.healedRatioAccumulator.add(this.healedRatio)))}getDiagnostics(e){return{quality:(0,fO.last)(e),qualityLevels:e,concealedSamples:this.concealedSamplesAccumulator.items,silentConcealedSamples:this.silentConcealedSamplesAccumulator.items,totalSamplesReceived:this.totalSamplesReceivedAccumulator.items,concealedSamplesDiff:this.concealedSamplesDiffAccumulator.items,silentConcealedSamplesDiff:this.silentConcealedSamplesDiffAccumulator.items,totalSamplesReceivedDiff:this.totalSamplesReceivedDiffAccumulator.items,healedRatio:this.healedRatioAccumulator.items.map((e=>Ct(e)))}}},SO=class{constructor(e=100){this.minPacketsReceivedToCalculatePacketLossRate=e,this.packetsReceivedForPrevWindow=0,this.packetsLostForPrevWindow=0,this.packetLostRateMax=0,this.totalPacketsLost=0,this.totalPacketsRecv=0,this.packetsLostDuration=0}capturePacketsLostAndPacketsReceived(e,t){this.packetsLostDuration+=Qe.TIME_INTERVAL.SEC_1,this.totalPacketsRecv=t,this.totalPacketsLost=e,this.calculateMaxLostRateInWindowSize(e,t)}getPacketsLostRateMax(){return this.packetLostRateMax}getNetworkAvgLostRate(){const e=this.totalPacketsLost+this.totalPacketsRecv;return e>0?this.totalPacketsLost/e:0}getAvgPacketsLost(){return this.totalPacketsLost?Ct(this.totalPacketsLost/this.packetsLostDuration,2):0}calculateMaxLostRateInWindowSize(e,t){const i=t-this.packetsReceivedForPrevWindow;if(i<this.minPacketsReceivedToCalculatePacketLossRate)return;this.packetsReceivedForPrevWindow=t;const n=e-this.packetsLostForPrevWindow;this.packetsLostForPrevWindow=e,this.packetLostRateMax=Math.max(Ct(n*this.minPacketsReceivedToCalculatePacketLossRate/(n+i),2),this.packetLostRateMax)}},yO=class{constructor(e){this.configProvider=e,this.audioAnalyzers=new Map,this.jitterBufferDuration=0,this.jitterBufferTotal=0,this.jitterTotal=0,this.jitterDuration=0,this.rttDuration=0,this.rttTotal=0,this.rttMax=0,this.jitterMax=0,this.webrtcAudioPacketLossRate=new SO(e.config.minPacketsReceivedToCalculatePacketLossRate)}captureJitterBuffer(e){this.jitterBufferDuration+=Qe.TIME_INTERVAL.SEC_1,this.jitterBufferTotal+=e}captureJitter(e){const t=1e3*e;this.jitterTotal+=t,this.jitterMax=Math.max(t,this.jitterMax),this.jitterDuration+=Qe.TIME_INTERVAL.SEC_1}getJitterAvg(){return this.jitterDuration?Ct(this.jitterTotal/this.jitterDuration):0}getAvgJitterBuffer(){return this.jitterBufferDuration?Math.round(this.jitterBufferTotal/this.jitterBufferDuration):0}capturePacketsLostAndPacketsReceived(e,t){this.webrtcAudioPacketLossRate.capturePacketsLostAndPacketsReceived(e,t)}getPacketsLostRateMax(){return this.webrtcAudioPacketLossRate.getPacketsLostRateMax()}getNetworkAvgLostRate(){return this.webrtcAudioPacketLossRate.getNetworkAvgLostRate()}getAvgPacketsLost(){return this.webrtcAudioPacketLossRate.getAvgPacketsLost()}captureRtt(e){if(null!==e){const t=parseInt(e);this.rttDuration+=Qe.TIME_INTERVAL.SEC_1,this.rttTotal+=t,this.rttMax=Math.max(this.rttMax,t)}}getAvgRtt(){return this.rttDuration?Ct(this.rttTotal/this.rttDuration):0}getMaxRtt(){return this.rttMax}getJitterMax(){return this.jitterMax}updateSendStream(e,t){if(!this.configProvider.config.useAudioAnalyzer)return;const i=this.audioAnalyzers.get(t);i&&(i.dispose(),this.audioAnalyzers.delete(t)),e?.rawStream?.getAudioTracks().length&&this.audioAnalyzers.set(t,new bM(e.rawStream))}getInputLevel(e){const t=this.audioAnalyzers.get(e);return t?.getInputLevel()}},CO=class{constructor(e,t){this.dropBadBandwidth=e,this.dropGoodBandwidth=t,this.dropDurationCounts={},Object.keys(Qe.HISTOGRAM_BATCH).forEach((e=>{this.dropDurationCounts[e]=0}))}recordSendBandwidth(e){this.currentDropDuration&&e<this.dropGoodBandwidth||e<this.dropBadBandwidth?this.initiateDrop():this.currentDropDuration&&e>this.dropGoodBandwidth&&this.recoverDrop()}getReport(){const e=ot(this.dropDurationCounts);return this.currentDropDuration&&(e.ongoingDuration=this.currentDropDuration),e}initiateDrop(){this.currentDropDuration?this.currentDropDuration++:this.currentDropDuration=1}recoverDrop(){for(const e of Object.keys(Qe.HISTOGRAM_BATCH))if(this.currentDropDuration<=Qe.HISTOGRAM_BATCH[e]){this.dropDurationCounts[e]+=1,this.currentDropDuration=0;break}}},_O=g,EO=class{constructor(e,t,i,n){this.lowThreshold=e,this.highThreshold=t,this.isLowerBetter=i,this.curInLowerRange=i,this.stateTracker=new TO(n)}onSample(e,t){let i=this.curInLowerRange;this.curInLowerRange?e>this.highThreshold&&(i=!1):e<this.lowThreshold&&(i=!0);const n=this.stateTracker.onNewState(this.getQuality(i),t);return n!==this.getQuality(this.curInLowerRange)&&(this.curInLowerRange=i),n}getQuality(e){return e===this.isLowerBetter?"Good":"Bad"}},TO=class{constructor(e){this.stickinessTime=e}onNewState(e,t){return"Good"!==e&&"Bad"!==e?this.curState:0===this.stickinessTime?e:e===this.curState?(this.stickTimerStarted=0,this.curState):("Bad"===this.curState?0===this.stickTimerStarted?this.stickTimerStarted=t:t-this.stickTimerStarted>this.stickinessTime&&(this.curState=e,this.stickTimerStarted=0):(this.curState=e,this.stickTimerStarted=0),this.curState)}},bO=class{constructor(e,t,i,n){this.stateProcessor=e,this.windowSize=t,this.extendedWindowSize=i,this.addDiagnosticData=n,this.dataAccumulator=new uA(i),this.avgAccumulator=new uA(i)}getLatestSendQuality(e,t,i){if(this.dataAccumulator.add(e),this.dataAccumulator.items.length>=this.windowSize){const e=this.dataAccumulator.items.slice(-this.windowSize),i=(0,_O.mean)(e);return this.addDiagnosticData&&this.avgAccumulator.add(i),this.stateProcessor.onSample(i,t)}return i}getData(){return this.dataAccumulator.items.map((e=>Ct(e)))}getAggregatedData(){return this.avgAccumulator.items.map((e=>Ct(e)))}},IO=class{constructor(e,t,i){this.configProvider=e,this.newStatsApi=t,this.webrtcHealedRatio=i,this.sendAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiffAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.lostDiffAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.totalAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendQualityAccumulator=new uA(this.configProvider.config.webrtcLossRateExtendedWindowSize),this.sendDiagnosticsEnabled=this.configProvider.config.networkSendQualityDiagnostics,this.recvDiagnosticsEnabled=this.configProvider.config.networkRecvQualityDiagnostics,this.recvQualityAccumulator=new uA(this.configProvider.config.webrtcHealedRatioExtendedWindowSize);const n=Number(this.configProvider.config.webrtcStatNetworkDetectionHysteresis);this.networkDetectionBadLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionBadLevel)+n/2,this.networkDetectionBadLevelLow=this.networkDetectionBadLevelHigh-n,this.networkDetectionGoodLevelHigh=Number(this.configProvider.config.webrtcStatNetworkDetectionGoodLevel)+n/2,this.networkDetectionGoodLevelLow=this.networkDetectionGoodLevelHigh-n;const r=new EO(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),a=new EO(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime);this.jitterCalculator=new bO(r,e.config.webrtcJitterWindowSize,e.config.webrtcJitterExtendedWindowSize,this.sendDiagnosticsEnabled),this.lossRateCalculator=new bO(a,e.config.webrtcLossRateWindowSize,e.config.webrtcLossRateExtendedWindowSize,this.sendDiagnosticsEnabled)}calculateNetworkSendQualityLevel(e,t,i,n){if(!e||!t)return{quality:n};if(e.length<2||t.length<2||(0,_O.last)(e)<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return{quality:n};const r=Date.now(),a=(0,_O.last)(i),s=this.jitterCalculator.getLatestSendQuality(a,r,n),[o,l]=e.slice(-2),[c,d]=t.slice(-2),u=this.getLossRate(l,o,d,c),h=this.lossRateCalculator.getLatestSendQuality(u,r,n),p="Good"===s&&"Good"===h?"Good":"Bad";return this.sendDiagnosticsEnabled&&(this.sendAccumulator.add(l),this.lostAccumulator.add(d),this.sendQualityAccumulator.add(p)),this.sendDiagnosticsEnabled?{quality:p,packetsSend:this.sendAccumulator.items,packetsLost:this.lostAccumulator.items,packetsSendDiff:this.sendDiffAccumulator.items,packetsLostDiff:this.lostDiffAccumulator.items,lossRates:this.lossRateCalculator.getData(),lossRatesAggregated:this.lossRateCalculator.getAggregatedData(),jitter:this.jitterCalculator.getData(),jitterAggregated:this.jitterCalculator.getAggregatedData(),qualityLevels:this.sendQualityAccumulator.items}:{quality:p}}calculateNetworkRecvQualityLevel(e){if(this.newStatsApi){const t=e;return this.calculateNetworkRecvQualityLevelNewStatsApi(t.concealedSamples,t.silentConcealedSamples,t.totalSamplesReceived,t.oldNetworkLevel)}{const t=e;return this.calculateNetworkRecvQualityLevelLegacyStatsApi(t.googDecodingCTN,t.googDecodingPLC,t.oldNetworkLevel)}}calculateNetworkRecvQualityLevelLegacyStatsApi(e,t,i){const n=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||!t||e.length<2*n)return{quality:i};let r=e.length-1-n;const a=e[e.length-1];for(;r>=0&&a-e[r]<100*n;)r--;if(r<0)return{quality:i};const s=a-e[r],o=t[t.length-1]-t[r];if(s<=0)return{quality:i};const l=o/s;return{quality:this.getRecvQuality(l,i)}}calculateNetworkRecvQualityLevelNewStatsApi(e,t,i,n){const r=this.configProvider.config.webrtcStatNetworkDetectionDuration;if(!e||e.length<=r||!t||t.length<=r||!i||i.length<=r)return{quality:n};if((0,_O.last)(i)<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality)return{quality:n};if(0===this.webrtcHealedRatio.getTotalSamplesReceivedDiff())return{quality:n};const a=this.webrtcHealedRatio.getHealedRatio(),s=this.getRecvQuality(a,n);return this.recvDiagnosticsEnabled?(this.recvQualityAccumulator.add(s),this.webrtcHealedRatio.getDiagnostics(this.recvQualityAccumulator.items)):{quality:s}}getRecvQuality(e,t){return e<this.networkDetectionGoodLevelLow?"Good":e<this.networkDetectionGoodLevelHigh?"Good"===t?"Good":"Poor":e<this.networkDetectionBadLevelLow?"Poor":e<this.networkDetectionBadLevelHigh?"Bad"===t?"Bad":"Poor":"Bad"}getLossRate(e,t,i,n){const r=e-t,a=i-n,s=r+a;return this.sendDiagnosticsEnabled&&(this.sendDiffAccumulator.add(r),this.lostDiffAccumulator.add(a),this.totalAccumulator.add(s)),s>0?a/s:0}},wO=class{constructor(e){this.configProvider=e,this.qualityLimitationReasonEvents=[]}setQualityLimitationReason(e){this.lastQualityLimitationReason!==e&&this.qualityLimitationReasonEvents.push({event:e,startTime:Date.now(),endTime:Date.now()}),this.qualityLimitationReasonEvents.length>this.configProvider.config.maxStoredQualityLimitationReasonEvents&&this.qualityLimitationReasonEvents.shift(),this.lastQualityLimitationReason=e}getQualityLimitationReasonEvents(){return this.qualityLimitationReasonEvents.reduce(((e,t,i)=>"none"===t.event?e:[...e,{...t,endTime:this.qualityLimitationReasonEvents[i+1]?.startTime??Date.now()}]),[])}},RO=class{constructor(){this.bitrateData={[Qe.MEDIA_DIRECTION.SEND]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0,allocateBW:0,allocateBWSamples:0},[Qe.MEDIA_DIRECTION.RECV]:{lastBytes:0,lastTimestamp:0,maxSample:0,bitrateTotal:0,nSamples:0}}}captureSample(e,t){const i=Date.now()/1e3;if(0!==this.bitrateData[e].lastTimestamp&&t>this.bitrateData[e].lastBytes){const n=i-this.bitrateData[e].lastTimestamp,r=8*(t-this.bitrateData[e].lastBytes)/n;this.onBitrateSample(e,r)}this.bitrateData[e].lastTimestamp=i,this.bitrateData[e].lastBytes=t}getMax(e){return Math.round(this.bitrateData[e].maxSample)}getAvg(e){return 0===this.bitrateData[e].nSamples?0:Math.round(this.bitrateData[e].bitrateTotal/this.bitrateData[e].nSamples)}stopCapture(e){this.bitrateData[e].lastBytes=0,this.bitrateData[e].lastTimestamp=0}onBitrateSample(e,t){t>this.bitrateData[e].maxSample&&(this.bitrateData[e].maxSample=t),this.bitrateData[e].bitrateTotal+=t,this.bitrateData[e].nSamples++}captureAllocateBandwidth(e){if(e){const t=parseInt(e[e.length-1]);this.bitrateData[Qe.MEDIA_DIRECTION.SEND].allocateBW+=t,this.bitrateData[Qe.MEDIA_DIRECTION.SEND].allocateBWSamples+=1}}getAllocateBandwidthAvg(){const e=this.bitrateData[Qe.MEDIA_DIRECTION.SEND].allocateBW,t=this.bitrateData[Qe.MEDIA_DIRECTION.SEND].allocateBWSamples;if(e>0&&t>0)return Math.floor(e/t)}},AO=class{constructor(e,t){this.maxAppliedCapabilitiesCount=t,this.events=[],this.events.push({eventType:"req",timestamp:Date.now(),capabilities:e.capabilities,isSimulcast:e.isSimulcastEnabled})}setMaxCapabilitiesApplied(e){this.events.push({eventType:"app",timestamp:Date.now(),capabilities:e.capabilities,error:e.error?`${e.error}`:"none"}),this.maxAppliedCapabilitiesCount&&this.events.length>this.maxAppliedCapabilitiesCount+1&&this.events.splice(1,1)}getEvents(){return this.events}},PO=class{constructor(e,t){this.configProvider=e,this.logger=t,this.resolutionChangeRequestRecords={},this.currentResolutionsByRid={},this.resolutionChangeCounterByRid={},this.events=[],this.errors=[]}setMaxCapabilitesRequested(e){const t=new AO(e,this.configProvider.config.webrtcLastAppliedVideoCapabilitiesCount);this.events.push({causeId:e.causeId,seq:t}),this.recordResolutionChange(e),this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.length>this.configProvider.config.webrtcLastAppliedVideoCapabilitiesSequenceCount&&this.events.shift()}setMaxCapabilitesApplied(e){const t=this.events.find((t=>t.causeId===e.causeId));t?(t.seq.setMaxCapabilitiesApplied(e),e.error&&this.errors.push(t)):this.logger.safe.warn(`Requested capabilities with id ${e.causeId} not found`)}getEvents(){return this.events.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getErrors(){return this.errors.map((e=>({causeId:e.causeId,events:e.seq.getEvents()})))}getResolutionRecords(){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo)return{req:this.resolutionChangeRequestRecords,count:this.resolutionChangeCounterByRid}}recordResolutionChange(e){if(this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo){const t=Object.keys(this.currentResolutionsByRid),i=e=>e.rid||"default";[...t,...e.capabilities.map((e=>i(e)))].forEach((t=>{const n=e.capabilities.find((e=>i(e)===t)),r=this.currentResolutionsByRid[t]||0,a=n?.maxFs||0;if(r===a)return;this.resolutionChangeRequestRecords[t]||(this.resolutionChangeRequestRecords[t]=[],this.resolutionChangeCounterByRid[t]=0);const s=this.resolutionChangeRequestRecords[t].find((e=>e.from===r&&e.to===a));s?s.counter++:this.resolutionChangeRequestRecords[t].push({from:r,to:a,counter:1}),this.currentResolutionsByRid[t]=a,this.resolutionChangeCounterByRid[t]++}))}}},MO=class{constructor(){this.delayCur=[],this.delayTotal=0,this.delayEventCount=0}analyzeDelay(e,t){if(t&&""!==t){this.delayCur.length===e&&this.delayCur.shift();const i=parseInt(t);this.delayCur.push(i),this.delayTotal+=i,this.delayEventCount+=Qe.TIME_INTERVAL.SEC_1}}getDelayCur(){if(this.delayCur.length>0){const e=this.delayCur.reduce(((e,t)=>e+t))/this.delayCur.length;return e<0?0:e}}getDelayAvg(){if(this.delayEventCount>0&&this.delayTotal>0){const e=this.delayTotal/this.delayEventCount;return e<0?0:e}}},kO=class{constructor(e,t){this.configProvider=e,this.startTime=t,this.recvTotalFreezeDuration=-1,this.recvFreezeDurations=[],this.recvFreezeIsOngoing=!1,this.recvCurrentFreezeDuration=0,this.recvFreezeCount=0,this.receiveFreezeDurationCounts={},this.longestRecvFreezeDuration=0,this.sendCameraFreezeIntervalsCount=0,this.previousInputFrame=0,this.recvCurrentFreezeStartTimestamp=0,this.receiveFreezeDurationTimestamps={},this.finalFreezeIsOngoing=!1,this.finalRecvCurrentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0,Object.keys(Qe.HISTOGRAM_BATCH).forEach((e=>{this.receiveFreezeDurationCounts[e]=0,this.receiveFreezeDurationTimestamps[e]=[]}))}gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:n}){if(e){const r=parseInt(e[e.length-1],10),a=t?.length>0?parseInt(t[t.length-1],10):void 0;void 0!==i&&"ScreenShare"!==n&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&!this.configProvider.config.isRenderingBasedOnRawStatistics&&this.calculateBitrate(i,r),-1===this.recvTotalFreezeDuration&&(this.recvTotalFreezeDuration=0),r>0&&(this.mediaStarted=!0),0!==r&&0!==a||!this.mediaStarted?r>0&&(void 0===a||a>0)&&this.recvFreezeIsOngoing&&this.stopRecvDataGathering(!1):(this.recvFreezeIsOngoing||(this.recvCurrentFreezeStartTimestamp=Date.now()-this.startTime),this.recvFreezeIsOngoing=!0,this.recvCurrentFreezeDuration+=Qe.TIME_INTERVAL.SEC_1,this.recvTotalFreezeDuration+=Qe.TIME_INTERVAL.SEC_1)}}getIsRendering(e){return this.recvCurrentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted}detectCaptureFreeze(e){if(e){const t=parseInt(e[e.length-1],10);this.previousInputFrame>0&&0===t&&(this.sendCameraFreezeIntervalsCount+=1),this.previousInputFrame=t}}getSendCameraFreezeIntervals(){return this.sendCameraFreezeIntervalsCount>0?this.sendCameraFreezeIntervalsCount:void 0}stopRecvDataGathering(e=!0){this.finalFreezeIsOngoing=this.recvFreezeIsOngoing,this.recvFreezeIsOngoing=!1,e&&(this.mediaStarted=!1),this.recvCurrentFreezeDuration>0&&(this.populateLongestRecvFreezeDuration(),this.populateRecvFreezeDurationCounts(),this.recvFreezeDurations.push(this.recvCurrentFreezeDuration),this.recvFreezeCount+=1),this.finalRecvCurrentFreezeDuration=this.recvCurrentFreezeDuration,this.recvCurrentFreezeDuration=0}getRecvFreezeDurationCounts(){return this.recvFreezeCount>0?JSON.stringify(this.receiveFreezeDurationCounts):void 0}getRecvFreezeDurationTimestamps(e){if(0===this.recvFreezeCount)return;const t={};return Object.keys(this.receiveFreezeDurationTimestamps).forEach((i=>{const n=this.receiveFreezeDurationTimestamps[i].length;t[i]=n>e?this.receiveFreezeDurationTimestamps[i].slice(n-e):this.receiveFreezeDurationTimestamps[i]})),JSON.stringify(t)}getRecvFreezeIsOngoing(e){return this.finalRecvCurrentFreezeDuration>=e&&this.finalFreezeIsOngoing}getRecvTotalFreezeDuration(){return this.recvTotalFreezeDuration>=0?this.recvTotalFreezeDuration:void 0}getRecvAvgFreezeDuration(){if(this.recvTotalFreezeDuration>0&&this.recvFreezeCount>0)return this.recvTotalFreezeDuration/this.recvFreezeCount}getLongestRecvFreezeDuration(){return this.longestRecvFreezeDuration>0?this.longestRecvFreezeDuration:void 0}populateRecvFreezeDurationCounts(){for(const e of Object.keys(Qe.HISTOGRAM_BATCH))if(this.recvCurrentFreezeDuration<=Qe.HISTOGRAM_BATCH[e]){this.receiveFreezeDurationCounts[e]+=1,this.receiveFreezeDurationTimestamps[e].push(this.recvCurrentFreezeStartTimestamp);break}this.recvCurrentFreezeStartTimestamp=0}populateLongestRecvFreezeDuration(){this.recvCurrentFreezeDuration>this.longestRecvFreezeDuration&&(this.longestRecvFreezeDuration=this.recvCurrentFreezeDuration)}calculateBitrate(e,t){const i=(e-this.lastBytesRecv)/125;this.lastBytesRecv=e,i<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}},DO=class{constructor(){this.mediaData={[Qe.MEDIA_DIRECTION.SEND]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0},[Qe.MEDIA_DIRECTION.RECV]:{totalMediaDuration:-1,totalFrameCount:0,mediaStartTimestamp:new Date,mediaStarted:!1,timeSinceLastDecode:0,cameraFrameRate:0}},this.gatheringSendData=!1}captureMediaData(e,t,i){const n=this.mediaData[e];if(e===Qe.MEDIA_DIRECTION.SEND&&(this.gatheringSendData=!0),t){const e=parseInt(t[t.length-1],10);n.totalFrameCount+=e}if(i){-1===n.totalMediaDuration&&(n.totalMediaDuration=0);const e=parseInt(i[i.length-1],10);n.mediaStarted||e>0&&(n.mediaStarted=!0,n.mediaStartTimestamp=new Date)}n.mediaStarted&&(n.totalMediaDuration+=Qe.TIME_INTERVAL.SEC_1)}captureFrameRate(e){const t=this.mediaData[Qe.MEDIA_DIRECTION.SEND];if(e){const i=parseInt(e[e.length-1],10);t.cameraFrameRate+=i}}stopRecvDataGathering(){const e=this.mediaData[Qe.MEDIA_DIRECTION.RECV],t=(new Date).getTime();e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t-e.mediaStartTimestamp.getTime())/1e3):0,e.mediaStarted=!1}isGatheringSendData(){return this.gatheringSendData}stopSendDataGathering(){const e=this.mediaData[Qe.MEDIA_DIRECTION.SEND],t=new Date;e.timeSinceLastDecode=e.totalMediaDuration>0?Math.round((t.getTime()-e.mediaStartTimestamp.getTime())/1e3):0,this.gatheringSendData=!1,e.mediaStarted=!1}getAvgFrameRate(e){const t=this.mediaData[e];if(t.totalMediaDuration>0&&t.totalFrameCount>0)return t.totalFrameCount/t.totalMediaDuration}getTotalDuration(e){const t=this.mediaData[e];return t.totalMediaDuration>=0?t.totalMediaDuration:void 0}getTimeSinceLastDecode(e){const t=this.mediaData[e];return t.timeSinceLastDecode>0?t.timeSinceLastDecode:void 0}getSendCameraFramerate(){const e=this.mediaData[Qe.MEDIA_DIRECTION.SEND];if(e.totalMediaDuration>0)return e.cameraFrameRate/e.totalMediaDuration}},OO=class{constructor(){this.qpData={[Qe.MEDIA_DIRECTION.SEND]:{frames:0,qpSum:0},[Qe.MEDIA_DIRECTION.RECV]:{frames:0,qpSum:0}}}captureQpData(e,t,i){const n=this.qpData[e];if(i&&i.length>0){const e=parseInt(i[i.length-1],10);e>0&&(n.frames=e)}if(t){const e=parseInt(t,10);e>0&&(n.qpSum=e)}}getQpAverage(e){const t=this.qpData[e];if(t.qpSum>0&&t.frames>0)return t.qpSum/t.frames}},NO=class{constructor(){this.resolutionChangedCount=0,this.resDurations={},this.preferredResolutionDurations={},this.preferredResolutions=[]}get resolutionSwitchCount(){return this.resolutionChangedCount}get resolutionDurationRatios(){return this.countResolutionDurationRatio(this.resDurations)}get preferredResolutionDurationRatios(){return this.countResolutionDurationRatio(this.preferredResolutionDurations)}get preferredResolution(){return this.preferredResolutions}captureSample(e){e&&e.width&&e.height&&(this.isResolutionChanged(this.lastResolution,e)&&this.resolutionChanged(e),this.updateResolutionDuration(this.getResolutionKey(e),this.resDurations)),this.lastPreferredResolution&&this.updatePreferredResolutionDurations()}capturePreferredResolution(e,t){const i=this.getResolutionKey(e);this.preferredResolution.includes(i)||(this.preferredResolutions.length>=t&&this.preferredResolutions.shift(),this.preferredResolutions.push(i)),this.isResolutionChanged(this.lastPreferredResolution,e)&&(this.preferredResolutionChanged(e),this.updatePreferredResolutionDurations())}getResolutionKey(e){return`${e.width}x${e.height}`}isResolutionChanged(e,t){return!e||e.width!==t.width||e.height!==t.height}countResolutionDurationRatio(e){const t={};let i=0;for(const t in e)i+=e[t];for(const n in e)t[n]=Ct(e[n]/i*100,2);return t}updatePreferredResolutionDurations(){this.updateResolutionDuration(this.getResolutionKey(this.lastPreferredResolution),this.preferredResolutionDurations)}updateResolutionDuration(e,t){t[e]||(t[e]=0),t[e]++}preferredResolutionChanged(e){this.lastPreferredResolution=e}resolutionChanged(e){this.lastResolution=e,this.resolutionChangedCount++}},LO=class{constructor(){this.streamsTimers={}}countRecvStreams(e){const t=`${e}`;this.streamsTimers.hasOwnProperty(t)||(this.streamsTimers[t]=0),this.streamsTimers[t]++}getStreamCounts(){const e={min:void 0,max:void 0,mode:void 0},t=Object.keys(this.streamsTimers).map(Number);return 0===t.length||1===t.length&&0===t[0]||(e.min=Math.min(...t.filter((e=>e>0))),e.max=Math.max(...t),e.mode=t.reduce(((e,t)=>this.streamsTimers[t]>this.streamsTimers[e]?t:e),t[0])),e}},xO=class{constructor(e){this.configProvider=e,this.subscriptionEvents=[],this.subscriptionCounters={attempted:0,subscribed:0,unsubscribed:0,failed:0}}addSubscriptionEvent(e){switch(this.subscriptionEvents.length>this.configProvider.config.webrtcSubscriptionEventLimit&&this.subscriptionEvents.shift(),this.subscriptionEvents.push(e),e.evt){case 1:this.subscriptionCounters.attempted++;break;case 2:this.subscriptionCounters.subscribed++;break;case 3:this.subscriptionCounters.unsubscribed++;break;case-1:this.subscriptionCounters.failed++}}getSubscriptionEvents(){return this.subscriptionEvents.length>0?{events:this.subscriptionEvents}:void 0}getSubscriptionCounters(){return this.subscriptionEvents.length>0?this.subscriptionCounters:void 0}},FO=class{constructor(e,t,i,n="Video"){this.startTime=e,this.configProvider=t,this.logger=i,this.mediaType=n,this.subscriptionCounter=0,this.videoFreezeTelemetry=new kO(this.configProvider,this.startTime),this.videoDelayTelemetry=new MO,this.videoSubscriptionEvents=new xO(this.configProvider),this.videoQPEvents=new OO,this.videoResolutionTelemetry=new NO,this.videoGeneralTelemetry=new DO,this.videoStreamsCounters=new LO,this.videoBitrate=new RO,this.videoMaxCapabilities=new PO(this.configProvider,this.logger),this.videoOvershoot=new $D(this.logger),this.videoQualityLimitations=new wO(this.configProvider),this.videoPacketLostRate=new SO(this.configProvider.config.minPacketsReceivedToCalculatePacketLossRate),this.videoStatsOnSubscribed=new ZD(this.configProvider.config.maxVideoStatsAfterSubscription),this.videoResolutionSwitchTracker=new wD(this.configProvider.config.diagnostics?.collectionLimits?.numResolutionSwitches),this.timeToFirstFrame=-1,this.timeToFirstFrameSinceSubscriptionStart=-1,this.currentTrackId="",this.recvTotalFreezeDurationMs=0,this.isRenderingEvents=[]}get trackId(){return this.currentTrackId}set trackId(e){this.currentTrackId=e}get isRecvDataGatheringEnabled(){return this.subscriptionCounter>0}startStopRecvDataGathering(e){this.logger.safe.info("Receive data gathering is "+(e?"enabled":"disabled")),e?this.subscriptionCounter++:this.subscriptionCounter--,this.subscriptionCounter<0&&this.logger.safe.error(`Subscription counter should not be less than 0. Actual value is ${this.subscriptionCounter}`),0===this.subscriptionCounter&&this.stopRecvGathering()}stopDataGathering(){this.stopRecvGathering(),this.stopSendGathering()}stopRecvGathering(){this.videoFreezeTelemetry.stopRecvDataGathering(),this.videoGeneralTelemetry.stopRecvDataGathering(),this.videoBitrate.stopCapture(Qe.MEDIA_DIRECTION.RECV)}isSendGathering(){return this.videoGeneralTelemetry.isGatheringSendData()}stopSendGathering(){this.videoGeneralTelemetry.stopSendDataGathering(),this.videoBitrate.stopCapture(Qe.MEDIA_DIRECTION.SEND),this.videoOvershoot.flush()}gatherRecvFreezeData(e,t,i){this.videoFreezeTelemetry.gatherFreezeData({frameRateDecoded:e,frameRateRecv:t,bytesReceived:i,mediaType:this.mediaType})}detectCaptureFreeze(e){this.videoFreezeTelemetry.detectCaptureFreeze(e)}getRecvFreezeDurationCounts(){return this.videoFreezeTelemetry.getRecvFreezeDurationCounts()}getRecvFreezeDurationTimestamps(){return this.videoFreezeTelemetry.getRecvFreezeDurationTimestamps(this.configProvider.config.maxVideoFreezeTimestampsInBucket)}getRecvTotalFreezeDuration(){return this.videoFreezeTelemetry.getRecvTotalFreezeDuration()}setRecvTotalFreezeDurationMs(e){this.recvTotalFreezeDurationMs=void 0!==e?this.recvTotalFreezeDurationMs+=e:void 0}analyzeDelay(e,t){this.videoDelayTelemetry.analyzeDelay(e,t)}getDelayCur(){return this.videoDelayTelemetry.getDelayCur()}getDelayAvg(){return this.videoDelayTelemetry.getDelayAvg()}addSubscriptionEvent(e){this.videoSubscriptionEvents.addSubscriptionEvent(e)}getSubscriptionEvents(){return this.videoSubscriptionEvents.getSubscriptionEvents()}getSubscriptionCounters(){return this.videoSubscriptionEvents.getSubscriptionCounters()}captureQpData(e,t,i){this.videoQPEvents.captureQpData(e,t,i)}getQpAverage(e){return this.videoQPEvents.getQpAverage(e)}captureMediaData(e,t,i){this.videoGeneralTelemetry.captureMediaData(e,t,i)}getIsRendering(){const e=this.configProvider.config.notRenderingTimeInterval["Video"===this.mediaType?"video":"sharing"];return this.videoFreezeTelemetry.getIsRendering(e)}captureFrameRate(e){this.videoGeneralTelemetry.captureFrameRate(e)}getTotalDuration(e){return this.videoGeneralTelemetry.getTotalDuration(e)}captureResolutionSample(e){this.videoResolutionTelemetry.captureSample(e)}countRecvStreams(e){this.videoStreamsCounters.countRecvStreams(e)}captureBitrateSample(e,t){this.videoBitrate.captureSample(e,t)}captureAllocateBandwidth(e){this.videoBitrate.captureAllocateBandwidth(e)}capturePreferredResolution(e,t){this.videoResolutionTelemetry.capturePreferredResolution(e,t)}setMaxCapabilitesRequested(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesRequested(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}setMaxCapabilitesApplied(e,t=!1){this.videoMaxCapabilities.setMaxCapabilitesApplied(e),t||1===e.capabilities.length&&!e.capabilities[0]?.ssrc||this.setMaxCapabilitiesOvershoot(e.capabilities)}getMaxCapabilitiesEvents(){const e=this.videoMaxCapabilities.getEvents();return JSON.stringify(e)}getMaxCapabilitiesResolutionChanges(){const e=this.videoMaxCapabilities.getResolutionRecords();return e?JSON.stringify(e):""}getMaxCapabilitiesErrors(){const e=this.videoMaxCapabilities.getErrors();return e?JSON.stringify(e):""}setCurrentParameters(e,t,i){this.videoOvershoot.setCurrentParams(e,t.height/16*(t.width/16),i)}setMaxCapabilitiesOvershoot(e){this.videoOvershoot.setMaxCapabilities(e)}getOvershootEvents(){let e=this.videoOvershoot.getEvents();return e=e.slice(Math.max(0,e.length-(this.configProvider.config.maxReportedOvershootingEvents+1)),e.length),e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify(e)}getOvershootTotalDurations(){const e=this.videoOvershoot.getEvents();return e.forEach((e=>e.timestamp=e.timestamp-this.startTime)),JSON.stringify({fs:e.reduce(((e,t)=>"fs"===t.overshootType?e+t.duration:e),0),fps:e.reduce(((e,t)=>"fps"===t.overshootType?e+t.duration:e),0)})}setQualityLimitationReason(e){this.videoQualityLimitations.setQualityLimitationReason(e)}getQualityLimitationReasonEvents(){return this.videoQualityLimitations.getQualityLimitationReasonEvents()}captureTimeToFirstFrame(e,t){-1!==e&&(this.timeToFirstFrame=e,this.timeToFirstFrameSinceSubscriptionStart=t)}getTimeToFirstFrame(){return this.timeToFirstFrame}setIsRendering(e){Tt(this.isRenderingEvents,{isRendering:e,ts:Date.now()},this.configProvider.config.diagnostics.telemetryLimits.numIsRenderingEvents)}capturePacketsLostAndPacketsReceved(e,t){this.videoPacketLostRate.capturePacketsLostAndPacketsReceived(e,t)}setMsi(e){this.msi=e}setLocalMsi(e){this.localMsi=e}prepareCollectingStatsOnSubscribed(e){this.videoStatsOnSubscribed.prepareCollectingStatsOnSubscribed(e)}captureStatsOnSubscribed(e,t){this.videoStatsOnSubscribed.captureStatsOnSubscribed(e,t)}calculateResolutinSwitches(e,t){this.videoResolutionSwitchTracker.captureSample(e,t)}getReport(e,t,i=!1){const n={};if(n[t+"DurationSeconds"]=this.getTotalDuration(e),n[t+"QpAvg"]=this.getQpAverage(e),n[t+"frameRateAvg"]=this.videoGeneralTelemetry.getAvgFrameRate(e),n[t+"bitrateAvg"]=this.videoBitrate.getAvg(e),n[t+"bitrateMax"]=this.videoBitrate.getMax(e),e===Qe.MEDIA_DIRECTION.SEND)n[t+"DelayCur"]=this.getDelayCur(),n[t+"DelayAvg"]=this.getDelayAvg(),n[t+"TimeSinceLastEncodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"AllocateBWAvg"]=this.videoBitrate.getAllocateBandwidthAvg(),n[t+"CaptureFramerateAvg"]=this.videoGeneralTelemetry.getSendCameraFramerate(),n[t+"FreezeIntervals"]=this.videoFreezeTelemetry.getSendCameraFreezeIntervals(),n[t+"MaxCapabilities"]=i?"":this.getMaxCapabilitiesEvents(),n[t+"MaxCapabilitiesErrors"]=i?"":this.getMaxCapabilitiesErrors(),n[t+"OvershootEvents"]=this.getOvershootEvents(),n[t+"OvershootDurations"]=this.getOvershootTotalDurations(),n[t+"qualityLimitationReasonEvents"]=JSON.stringify(this.getQualityLimitationReasonEvents()),n[t+"MaxCapabilitiesResolutions"]=this.getMaxCapabilitiesResolutionChanges(),n[t+"ResolutionsSwitches"]=this.videoResolutionSwitchTracker.switches?JSON.stringify(this.videoResolutionSwitchTracker.switches):"";else if(e===Qe.MEDIA_DIRECTION.RECV){n[t+"TimeSinceLastDecodeStart"]=this.videoGeneralTelemetry.getTimeSinceLastDecode(e),n[t+"FreezeHistogram"]=this.getRecvFreezeDurationCounts(),n[t+"FreezeTimestamps"]=this.getRecvFreezeDurationTimestamps(),n[t+"LongestFreezeDuration"]=this.videoFreezeTelemetry.getLongestRecvFreezeDuration(),n[t+"RecvAvgFreezeDuration"]=this.videoFreezeTelemetry.getRecvAvgFreezeDuration(),n[t+"TotalFreezeDuration"]=this.getRecvTotalFreezeDuration(),n[t+"TotalFreezeDurationMs"]=this.recvTotalFreezeDurationMs,n[t+"OngoingFreeze"]=this.videoFreezeTelemetry.getRecvFreezeIsOngoing(this.configProvider.config.webrtcEndOfCallFreezeThreshold),n[t+"NumResolutionSwitches"]=this.videoResolutionTelemetry.resolutionSwitchCount,n[t+"PreferredResolution"]=this.videoResolutionTelemetry.preferredResolution,n[t+"PreferredResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.preferredResolutionDurationRatios),n[t+"packetsLostRateMax"]=this.videoPacketLostRate.getPacketsLostRateMax(),n[t+"ResolutionDurations"]=JSON.stringify(this.videoResolutionTelemetry.resolutionDurationRatios);const i=this.videoStreamsCounters.getStreamCounts();n[t+"StreamsMin"]=i.min,n[t+"StreamsMax"]=i.max,n[t+"StreamsMode"]=i.mode,n[t+"TimeToFirstFrame"]=this.timeToFirstFrame,n[t+"TimeToFirstFrameSinceSubscriptionStart"]=this.timeToFirstFrameSinceSubscriptionStart,n[t+"LocalMsi"]=this.localMsi,n[t+"Msi"]=this.msi,n[t+"isRenderingEvents"]=JSON.stringify(this.isRenderingEvents),n[t+"statsOnSubscribed"]=JSON.stringify(this.videoStatsOnSubscribed.getStatsOnSubscribed())}return n}},UO=Symbol("mslbase"),BO=Symbol("mslsamples"),VO=class{constructor(e,t){this.logger=e,this.configProvider=t,this.currentLayouts={},this.collectedModalitySessions=[],this.startTimestamp=Date.now()}get collectedSessions(){return this.collectedModalitySessions}get highestFidelitySSRC(){if(!this.currentModalitySession)return;let e;for(const t in this.currentLayouts)e=this.getHigherFidelitySSRC(t,e);return parseInt(e)}processStats(e){const t=Object.values(e.ssrc??{}).filter((e=>e.rid&&e.ssrc&&e.googFrameHeightInput&&this.lastMaxCapabilitiesEvent?.capabilities.some((t=>t.rid===e.rid)))),i=new Map(t.map((e=>[`${e.ssrc}`,e.rid])));for(const e in this.currentLayouts)i.has(e)||this.collectLayout(e);!this.currentModalitySession&&i.size>0&&(this.currentModalitySession={timestamp:Date.now()-this.startTimestamp,duration:0,numLayouts:0,layouts:[]},this.logger.safe.info("Modality session started")),t.forEach((e=>{this.currentLayouts[`${e.ssrc}`]||this.addLayout(e)})),0===i.size&&this.currentModalitySession&&this.collectSession(),t.forEach((e=>this.processLayoutData(e)))}setMaxCapabilities(e,t){if(this.lastMaxCapabilitiesEvent=e,Object.keys(this.currentLayouts).length)for(const i of e.capabilities){const n=Object.values(this.currentLayouts).find((e=>e.rid===i.rid));n&&(t?(Tt(n.fmtp,{...i,timestamp:Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-n.timestamp,causeId:e.causeId},this.configProvider.config.simulcastTelemetryNumFMTP),n.gatherer.setMaxCapabilitesApplied(e)):n.gatherer.setMaxCapabilitesRequested(e),n.gatherer.setMaxCapabilitiesOvershoot([i]))}}finish(){this.logger.safe.info("Finishing statistics gathering");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession&&this.collectSession()}addLayout(e){const t=`${e.ssrc}`,i=e.rid,n=this.lastMaxCapabilitiesEvent?.capabilities.find((e=>e.rid===i));this.logger.safe.info(`Adding layout for ssrc ${t} rid ${i}`);const r=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,a=new FO(r,this.configProvider,this.logger.createChild(`Telemetry#${t}`));this.currentLayouts[t]={ssrc:e.ssrc,rid:i,fmtp:[{...n,timestamp:r,causeId:this.lastMaxCapabilitiesEvent?.causeId}],timestamp:r,duration:0,gatherer:a,[UO]:{firCount:e.googFirsReceived,nackCount:e.googNacksReceived,pliCount:e.googPlisReceived,framesEncoded:e.framesEncoded,bytesSent:e.bytesSent,packetsSent:e.packetsSent,packetsLost:e.packetsLost,qpSum:e.qpSum},[BO]:{firCount:[],nackCount:[],pliCount:[],framesEncoded:[],bytesSent:[],packetsSent:[],packetsLost:[],qpSum:[],frameHeightInput:[],frameHeightSent:[],frameRateInput:[],frameRateSent:[]}},a.setMaxCapabilitiesOvershoot([n]),this.currentModalitySession.numLayouts++}processLayoutData(e){const t=`${e.ssrc}`,i=this.currentLayouts[t];this.processMediaStats(i,e),i.gatherer.captureMediaData(Qe.MEDIA_DIRECTION.SEND,[String(e.googFrameRateSent)],[String(e.framesEncoded)]),i.gatherer.captureFrameRate([String(e.googFrameRateInput)]),i.gatherer.captureQpData(Qe.MEDIA_DIRECTION.SEND,String(e.qpSum),[String(e.framesEncoded)]),i.gatherer.captureBitrateSample(Qe.MEDIA_DIRECTION.SEND,e.bytesSent),i.gatherer.detectCaptureFreeze([String(e.googFrameRateInput)]),i.gatherer.setCurrentParameters(e.ssrc,{width:e.googFrameWidthSent,height:e.googFrameHeightSent},e.googFrameRateSent)}processMediaStats(e,t){const i=e[UO],n=t.googFirsReceived-i.firCount,r=t.googNacksReceived-i.nackCount,a=t.googPlisReceived-i.pliCount,s=t.framesEncoded-i.framesEncoded,o=t.bytesSent-i.bytesSent,l=t.packetsSent-i.packetsSent,c=t.packetsLost-i.packetsLost,d=t.qpSum-i.qpSum,u=e[BO],h=this.configProvider.config.webrtcStatStoredRecordsNumber;Tt(u.firCount,n,h),Tt(u.nackCount,r,h),Tt(u.pliCount,a,h),Tt(u.framesEncoded,s,h),Tt(u.bytesSent,o,h),Tt(u.packetsSent,l,h),Tt(u.packetsLost,c,h),Tt(u.qpSum,d,h),Tt(u.frameHeightInput,t.googFrameHeightInput,h),Tt(u.frameHeightSent,t.googFrameHeightSent,h),Tt(u.frameRateInput,t.googFrameRateInput,h),Tt(u.frameRateSent,t.googFrameRateSent,h)}collectLayout(e){this.logger.safe.info(`Collecting layout for ssrc ${e}`),this.currentLayouts[e].duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp-this.currentLayouts[e].timestamp,this.currentLayouts[e].gatherer.isSendGathering()&&this.currentLayouts[e].gatherer.stopSendGathering();const t=this.currentLayouts[e].gatherer.getReport(Qe.MEDIA_DIRECTION.SEND,"",!1);for(const i in t)this.currentLayouts[e][i]=t[i];for(const t in this.currentLayouts[e][BO])this.currentLayouts[e][t]=Ot(this.currentLayouts[e][BO][t],(e=>e));delete this.currentLayouts[e].gatherer,Tt(this.currentModalitySession.layouts,this.currentLayouts[e],this.configProvider.config.simulcastTelemetryLayoutsPerSession),delete this.currentLayouts[e]}collectSession(){this.logger.safe.info("Collecting session");for(const e in this.currentLayouts)this.collectLayout(e);this.currentModalitySession.duration=Date.now()-this.startTimestamp-this.currentModalitySession.timestamp,Tt(this.collectedModalitySessions,this.currentModalitySession,this.configProvider.config.simulcastTelemetryNumModalitySessions),this.currentModalitySession=void 0,this.lastMaxCapabilitiesEvent=void 0}getHigherFidelitySSRC(e,t){if(!e||!t)return e||t;const[i]=this.currentLayouts[e].fmtp.slice(-1),[n]=this.currentLayouts[t].fmtp.slice(-1);return(i?.maxMbps??0)>0&&(n?.maxMbps??0)>0?i.maxMbps>n.maxMbps?e:t:e||t}},HO=["googFrameHeightReceived","googFrameWidthReceived","googFrameHeightSent","googFrameWidthSent","googFrameRateInput","googFrameRateSent","googNacksSent","googNacksReceived","googPlisSent","googPlisReceived","googFirsSent","googFirsReceived","framesDecoded","googFrameRateDecoded","googFrameRateReceived","framesEncoded","packetsLost","packetsSent","packetsReceived","bytesReceived","bytesSent","googEncodeUsagePercent","audioInputLevel","audioOutputLevel","googDecodingCTN","googDecodingPLC","keyFramesEncoded","keyFramesDecoded","googRtt","concealedSamples","silentConcealedSamples","totalSamplesReceived","healedRatio","jitter","googJitterBufferMs","qpSum","fecPacketsReceived","fecPacketsDiscarded","fecPacketsSent","packetsDiscarded","pushCount","pushErrCount","pullCount","pullErrCount"],$O=["bytesSent","bytesReceived","googRtt","packetsSent","requestsSent","consentRequestsSent","responsesSent","requestsReceived","responsesReceived"],GO=["googAvailableReceiveBandwidth","googAvailableSendBandwidth","googTransmitBitrate"];function jO(e,t,i){const n=i.value;i.value=function(...e){try{return n.apply(this,e)}catch(e){this.processStatsError(t,e)}}}var zO=class{constructor(e,t,i,n,r,a){this.logger=e,this.sessionInfo=t,this.configProvider=i,this.mediaManager=n,this.multiparty=r,this.newStatsApi=a,this.statsErrors=[],this.subscribedTrackIds=[],this.iceCandidateErrors=[],this.terminated=!1,this.hwSilent=!1,this.isSpeaking=!1,this.networkSendLevel={quality:"Good"},this.networkRecvLevel={quality:"Good"},this.audioTelemetry=new yO(this.configProvider),this.cameraOpenResolution={width:0,height:0},this.streamSenderStarted={},this.totalVideoControlMessages=0,this.outOfOrderVideoControlMessages=0,this.subscribedTrackSsrc=[],this.multiViewVideoTelemetry={},this.h264AvailableProfiles=[],this.timeToFirstFrame={},this.timeToFirstFrameSinceSubscriptionStart={},this.missedInitialPreferredResolution={},this.MSIDs=new Set,this.MSIDsPairs={},this.timerTrackerManager=new RM(this.configProvider.config.enableTimerTracker),this.extensions={WebRTCStats:{},AudioTransportRecvBitrate:0,AudioTransportSendBitrate:0,AudioPayloadSendBitrate:0,AudioPayloadRecvBitrate:0,VideoPayloadSendBitrate:0,VideoPayloadRecvBitrate:0,TimerAudioTransportRecvBitrate:0,TimerAudioTransportSendBitrate:0,TimerAudioPayloadRecvBitrate:0,TimerAudioPayloadSendBitrate:0,TimerVideoPayloadRecvBitrate:0,TimerVideoPayloadSendBitrate:0,StartTime:Date.now(),EndTime:Date.now(),Audio_recv_jitterBufferAvgSize:0,Audio_recv_jitterMax:0,Audio_recv_jitterAvg:0,Audio_send_rttAvg:0,Audio_send_rttMax:0,MaxSessionBandwidth:0,Video_recv_MSIDs:[],CallSetupTimeTracker:"",Audio_send_presentationUserAPIDuration:"",Audio_send_presentationDuration:""},this.report={type:"WebRtcMediaStats",data:{Extensions:this.extensions}},this.lastSSRCs=new Map,this.videoTelemetry=new FO(this.extensions.StartTime,this.configProvider,this.logger.createChild("Video"),"Video"),this.sharingTelemetry=new FO(this.extensions.StartTime,this.configProvider,this.logger.createChild("Sharing"),"ScreenShare"),this.dataTelemetry=new zp,this.bandwidthTelemetry=new CO(this.configProvider.config.webrtcBWJumpLowerLimit,this.configProvider.config.webrtcBWJumpUpperLimit),this.stabilizationTelemetry=new XD(this.configProvider.config.uplinkBWStabilizationSlidingWindowSize,this.configProvider.config.uplinkBWStabilizationMaxDeviation,this.configProvider.config.uplinkBWStabilizationMinBandwidth,Wg),this.storedRecordsNumber=Number(this.configProvider.config.webrtcStatStoredRecordsNumber),this.hwSilentDetectionDuration=Number(this.configProvider.config.webrtcStatHwSilentDetectionDuration),this.hwSilentDetectionLevel=Number(this.configProvider.config.webrtcStatHwSilentDetectionLevel),this.audioHealedRatioTelemetry=new vO(this.configProvider),this.networkQualityTelemetry=new IO(this.configProvider,this.newStatsApi,this.audioHealedRatioTelemetry),this.speakingWhileMutedBadDuration=Number(this.configProvider.config.webrtcSpeakingWhileMutedBadDuration),this.speakingWhileMutedDetectionLevel=Number(this.configProvider.config.webrtcSpeakingWhileMutedDetectionLevel),this.videoDelayTimePeriod=this.configProvider.config.webrtcVideoDelayThreshold,this.maxStoredPreferredResolutions=this.configProvider.config.maxStoredPreferredResolutionCount,this.simulcastVideo=new VO(this.logger.createChild("simulcastVideo"),this.configProvider),this.simulcastSharing=new VO(this.logger.createChild("simulcastSharing"),this.configProvider)}get currentVideoRecvTrackId(){return this.extensions.WebRTCStats.ssrc_video_recv?.googTrackId}get currentSharingRecvTrackId(){return this.extensions.WebRTCStats.ssrc_sharing_recv?.googTrackId}get isMultiViewVideoTelemetry(){return Object.getOwnPropertyNames(this.multiViewVideoTelemetry).length>0}onDeviceEvent(e){if("stream_acquired"===e.eventType){const t=e.payload;"Video"===t.mediaType&&(this.cameraOpenResolution=t.resolution)}}onMaxCapabilitiesRequested(e){(e.modality===Qe.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesRequested(e),(e.modality===Qe.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!1)}onMaxCapabilitiesApplied(e){(e.modality===Qe.MODALITY.video?this.videoTelemetry:this.sharingTelemetry).setMaxCapabilitesApplied(e),(e.modality===Qe.MODALITY.video?this.simulcastVideo:this.simulcastSharing).setMaxCapabilities(e,!0)}setSubscribedTrackIds(e){this.subscribedTrackIds=e||[]}setSubscribedTrackSsrc(e){this.subscribedTrackSsrc=e||[]}addSubscriptionEvent(e,t,i,n,r,a,s){const o={evt:e,ts:Date.now()-this.extensions.StartTime,msi:i,localMsi:n,duration:a};r&&(o.error=Be(r));const l=this.getHandlerForModality(t);if(l.addSubscriptionEvent(o),s&&this.setMSIDsPair(i,n,s),1===e||3===e){const t=1===e;l.startStopRecvDataGathering(t)}2===e&&l.prepareCollectingStatsOnSubscribed(i)}setMSIDsPair(e,t,i){const n=`ssrc_${i.replace(/\D/g,"")}_recv`;this.MSIDsPairs[n]={msi:e,localMsi:t}}getHandlerForModality(e){switch(e){case Qe.MODALITY.video:return this.videoTelemetry;case Qe.MODALITY.sharing:return this.sharingTelemetry;default:throw new Error(`Handler not found for modality: ${e}`)}}setTerminated(){this.extensions.EndTime=(new Date).getTime(),this.terminated=!0}startWaitingForStreamStart(e){this.streamStartDetection||this.sessionInfo.setOfferedModalities(e),this.streamStartDetection=!0}recordDataChannelProtocolEvent(e){this.dataTelemetry.recordDataChannelProtocolEvent(e)}setSessionDataChannelState(e){this.dataTelemetry.setSessionDataChannelState(e)}recordDataChannelError(e){this.dataTelemetry.recordDataChannelError(e)}processStatsDict(e){if(this.processSimulcastStats(e),this.constructWebRtcReportForSingleStream(this.extensions.WebRTCStats,e),this.streamStartDetection&&(this.setStartTime(this.sessionInfo.offeredModalities)||this.terminated)&&(this.streamStartDetection=!1),Object.keys(this.missedInitialPreferredResolution).length>0&&(this.currentVideoRecvTrackId||this.currentSharingRecvTrackId)&&this.setMissedInitialPreferredResolution(),this.constructWebRTCDataReport(this.extensions.WebRTCStats,e),this.calculateHwSilentState(),this.calculateSpeakingState(),this.setHealedRatioSamples(),this.calculateNetworkRecvQualityLevel(),this.calculateNetworkSendQualityLevel(),this.sessionInfo.activeModalities&&(this.processBandwidthStats(),this.processAudioStats(),this.processVideoStatsRecv(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_recv,!0),this.processVideoStatsSend(this.videoTelemetry,this.extensions.WebRTCStats.ssrc_video_send),this.processSharingStats(),this.processStreamsCounters()),this.configProvider.config.enableMultiViewStats){const t=this.extensions.WebRTCStats[Qe.MULTIPLE_RECV_STREAMS]?this.extensions.WebRTCStats[Qe.MULTIPLE_RECV_STREAMS]:{};this.constructWebRtcReportForMultipleStreams(t,e);for(const e of Object.keys(t)){const i=t[e];this.processVideoStatsRecv(this.multiViewVideoTelemetry[e],i)}this.extensions.WebRTCStats[Qe.MULTIPLE_RECV_STREAMS]=t}this.extensions.WebRTCStats.statsErrors=JSON.stringify(this.statsErrors)}setTimeToFirstFrame(e,t,i){i in this.timeToFirstFrame||(this.timeToFirstFrame[i]=e,this.timeToFirstFrameSinceSubscriptionStart[i]=t)}getCurrentTimeToFirstFrame(e){return this.timeToFirstFrame[e]?this.timeToFirstFrame[e]:-1}getCurrentTimeToFirstFrameSinceSubscriptionStart(e){return this.timeToFirstFrameSinceSubscriptionStart[e]?this.timeToFirstFrameSinceSubscriptionStart[e]:-1}getVideoTelemetryBySsrc(e){let t;return this.extensions.WebRTCStats.ssrc_video_recv&&this.extensions.WebRTCStats.ssrc_video_recv.id===e?t=this.videoTelemetry:this.extensions.WebRTCStats.ssrc_sharing_recv&&this.extensions.WebRTCStats.ssrc_sharing_recv.id===e?t=this.sharingTelemetry:this.isMultiViewVideoTelemetry&&(t=this.multiViewVideoTelemetry[e]),t}getIsRendering(e){const t=this.getVideoTelemetryBySsrc(e);return t?t.getIsRendering():void 0}setFreezeDuration(e,t){for(const i of Object.keys(this.multiViewVideoTelemetry))this.multiViewVideoTelemetry[i].trackId===t&&this.isSubscribed(t)&&this.multiViewVideoTelemetry[i].setRecvTotalFreezeDurationMs(e);this.currentSharingRecvTrackId===t&&this.isSubscribed(t)&&this.sharingTelemetry.setRecvTotalFreezeDurationMs(e),this.currentVideoRecvTrackId===t&&this.isSubscribed(t)&&this.videoTelemetry.setRecvTotalFreezeDurationMs(e)}addVideoControlMessage(e){this.totalVideoControlMessages++,e&&this.outOfOrderVideoControlMessages++}setStreamSenderStarted(e,t){this.streamSenderStarted[e]=t}addReportedReceiveBandwidth(e){this.limitCaptureAmount(this.extensions,"ReportedReceiveBandwidth",e)}setHealedRatioSamples(){this.audioHealedRatioTelemetry.captureHealedRatioSamples(this.extensions?.WebRTCStats?.ssrc_audio_recv?.concealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.silentConcealedSamples,this.extensions?.WebRTCStats?.ssrc_audio_recv?.totalSamplesReceived)}processSimulcastStats(e){this.simulcastVideo.processStats(e),this.simulcastSharing.processStats(e)}processBandwidthStats(){const e=this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth;if(e){const t=this.streamSenderStarted.Video||this.streamSenderStarted.ScreenShare;this.bandwidthTelemetry.recordSendBandwidth(e[e.length-1]),this.stabilizationTelemetry.processBandwidth(parseInt(e[e.length-1]),this.sessionInfo.activeModalities,t)}}processAudioStats(){if(this.extensions.WebRTCStats.ssrc_audio_send&&this.limitCaptureAmount(this.extensions,"Audio_send_RawInputVolume",this.audioTelemetry.getInputLevel("Audio")),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.googJitterBufferMs&&this.audioTelemetry.captureJitterBuffer((0,mO.last)(this.extensions.WebRTCStats.ssrc_audio_recv.googJitterBufferMs)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.packetsLost&&this.extensions.WebRTCStats.ssrc_audio_recv?.packetsReceived&&this.audioTelemetry.capturePacketsLostAndPacketsReceived((0,mO.last)(this.extensions.WebRTCStats.ssrc_audio_recv.packetsLost),(0,mO.last)(this.extensions.WebRTCStats.ssrc_audio_recv.packetsReceived)),void 0!==this.extensions.WebRTCStats.ssrc_audio_recv?.jitter&&this.audioTelemetry.captureJitter((0,mO.last)(this.extensions.WebRTCStats.ssrc_audio_recv.jitter)),this.extensions.WebRTCStats.ssrc_audio_send?.googRtt){const e=this.extensions.WebRTCStats.ssrc_audio_send.googRtt;this.audioTelemetry.captureRtt(e[e.length-1])}}stopGatheringIfNeeded(e,t,i,n){const r=`${t}${i}`;n!==this.lastSSRCs.get(r)&&(this.lastSSRCs.set(r,n),t===Qe.MEDIA_DIRECTION.SEND?e.stopSendGathering():e.stopRecvGathering())}processVideoStatsSend(e,t){t&&Wg(this.sessionInfo.activeModalities.video)?(this.stopGatheringIfNeeded(e,Qe.MEDIA_DIRECTION.SEND,"Video",t.ssrc),e.captureMediaData(Qe.MEDIA_DIRECTION.SEND,t.googFrameRateSent,t.framesEncoded),e.captureFrameRate(t.googFrameRateInput),e.analyzeDelay(this.videoDelayTimePeriod,t.googAvgEncodeMs),e.captureQpData(Qe.MEDIA_DIRECTION.SEND,t.qpSum,t.framesEncoded),e.captureBitrateSample(Qe.MEDIA_DIRECTION.SEND,this.getLastSampleInt(t.bytesSent)),e.detectCaptureFreeze(t.googFrameRateInput),e.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),e.setCurrentParameters(parseInt(t.ssrc),{width:this.getLastSampleInt(t.googFrameWidthSent),height:this.getLastSampleInt(t.googFrameHeightSent)},this.getLastSampleInt(t.googFrameRateSent)),e.setQualityLimitationReason(t.qualityLimitationReason),this.configProvider.config.specCompliantSimulcast?.collectResolutionInfo&&e.calculateResolutinSwitches(this.getLastSampleInt(t.googFrameWidthSent),this.getLastSampleInt(t.googFrameHeightSent))):e.isSendGathering()&&(e.stopSendGathering(),this.lastSSRCs.delete(`${Qe.MEDIA_DIRECTION.SEND}Video`))}processVideoStatsRecv(e,t,i=!1){t&&qg(this.sessionInfo.activeModalities.video)&&this.videoTelemetry.isRecvDataGatheringEnabled?(i&&this.stopGatheringIfNeeded(e,Qe.MEDIA_DIRECTION.RECV,"Video",t.ssrc),e.trackId=t.googTrackId,e.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived,this.getLastSampleInt(t.bytesReceived)),e.captureMediaData(Qe.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),e.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),e.captureQpData(Qe.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),e.captureBitrateSample(Qe.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),e.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),this.extensions.WebRTCStats.ssrc_video_recv?.packetsLost&&this.extensions.WebRTCStats.ssrc_video_recv?.packetsReceived&&this.videoTelemetry.capturePacketsLostAndPacketsReceved((0,mO.last)(this.extensions.WebRTCStats.ssrc_video_recv.packetsLost),(0,mO.last)(this.extensions.WebRTCStats.ssrc_video_recv.packetsReceived)),e.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):i&&this.lastSSRCs.delete(`${Qe.MEDIA_DIRECTION.RECV}Video`)}processSharingStats(){const e=this.extensions.WebRTCStats.ssrc_sharing_send,t=this.extensions.WebRTCStats.ssrc_sharing_recv;e&&Wg(this.sessionInfo.activeModalities.sharing)?(this.stopGatheringIfNeeded(this.sharingTelemetry,Qe.MEDIA_DIRECTION.SEND,"Sharing",e.ssrc),this.sharingTelemetry.captureMediaData(Qe.MEDIA_DIRECTION.SEND,e.googFrameRateSent,e.framesEncoded),this.sharingTelemetry.captureFrameRate(e.googFrameRateInput),this.sharingTelemetry.analyzeDelay(this.videoDelayTimePeriod,e.googAvgEncodeMs),this.sharingTelemetry.captureQpData(Qe.MEDIA_DIRECTION.SEND,e.qpSum,e.framesEncoded),this.sharingTelemetry.captureBitrateSample(Qe.MEDIA_DIRECTION.SEND,this.getLastSampleInt(e.bytesSent)),this.sharingTelemetry.detectCaptureFreeze(e.googFrameRateInput),this.sharingTelemetry.captureAllocateBandwidth(this.extensions.WebRTCStats.bweStat?.googAvailableSendBandwidth),this.sharingTelemetry.setCurrentParameters(parseInt(e.ssrc),{width:this.getLastSampleInt(e.googFrameWidthSent),height:this.getLastSampleInt(e.googFrameHeightSent)},this.getLastSampleInt(e.googFrameRateSent)),this.limitCaptureAmount(this.extensions,"Sharing_send_RawInputVolume",this.audioTelemetry.getInputLevel("ScreenShare"))):this.sharingTelemetry.isSendGathering()&&(this.sharingTelemetry.stopSendGathering(),this.lastSSRCs.delete(`${Qe.MEDIA_DIRECTION.SEND}Sharing`)),t&&qg(this.sessionInfo.activeModalities.sharing)&&this.sharingTelemetry.isRecvDataGatheringEnabled?(this.stopGatheringIfNeeded(this.sharingTelemetry,Qe.MEDIA_DIRECTION.RECV,"Sharing",t.ssrc),this.sharingTelemetry.trackId=t.googTrackId,this.sharingTelemetry.gatherRecvFreezeData(t.googFrameRateDecoded,t.googFrameRateReceived),this.sharingTelemetry.captureMediaData(Qe.MEDIA_DIRECTION.RECV,t.googFrameRateReceived,t.googFrameRateDecoded),this.sharingTelemetry.captureTimeToFirstFrame(this.getCurrentTimeToFirstFrame(t.googTrackId),this.getCurrentTimeToFirstFrameSinceSubscriptionStart(t.googTrackId)),this.sharingTelemetry.captureQpData(Qe.MEDIA_DIRECTION.RECV,t.qpSum,t.framesDecoded),this.sharingTelemetry.captureBitrateSample(Qe.MEDIA_DIRECTION.RECV,this.getLastSampleInt(t.bytesReceived)),this.sharingTelemetry.captureResolutionSample({width:this.getLastSampleInt(t.googFrameWidthReceived),height:this.getLastSampleInt(t.googFrameHeightReceived)}),this.sharingTelemetry.captureStatsOnSubscribed(this.getLastSampleInt(t.framesDecoded),this.getLastSampleInt(t.bytesReceived))):this.lastSSRCs.delete(`${Qe.MEDIA_DIRECTION.RECV}Sharing`)}processStreamsCounters(){const e=this.extensions.WebRTCStats.recvCounters;e&&(this.videoTelemetry.countRecvStreams(e[Qe.MODALITY.video]),this.sharingTelemetry.countRecvStreams(e[Qe.MODALITY.sharing]))}setMissedInitialPreferredResolution(){Ze(this.missedInitialPreferredResolution,((e,t)=>{this.setPreferredResolution(t,e)})),this.missedInitialPreferredResolution={}}setPreferredResolution(e,t,i){if((i===Qe.MEDIA_TYPE.video&&!this.currentVideoRecvTrackId||i===Qe.MEDIA_TYPE.sharing&&!this.currentSharingRecvTrackId)&&(this.missedInitialPreferredResolution[e]=t),this.currentVideoRecvTrackId===e&&this.videoTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.currentSharingRecvTrackId===e&&this.sharingTelemetry.capturePreferredResolution(t,this.maxStoredPreferredResolutions),this.isMultiViewVideoTelemetry){const i=this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(e)];i&&i.capturePreferredResolution(t,this.maxStoredPreferredResolutions)}}setIsRendering(e,t,i){t===Qe.MEDIA_TYPE.video&&this.videoTelemetry.setIsRendering(e),t===Qe.MEDIA_TYPE.sharing&&this.sharingTelemetry.setIsRendering(e),this.isMultiViewVideoTelemetry&&this.multiViewVideoTelemetry[this.getSsrcIdFromMultipleVideoStream(i)]?.setIsRendering(e)}setReportedSendBandwidth(e){this.extensions.ReportedSendBWMax||this.extensions.ReportedSendBWMin?e>this.extensions.ReportedSendBWMax?this.extensions.ReportedSendBWMax=e:e<this.extensions.ReportedSendBWMin&&(this.extensions.ReportedSendBWMin=e):(this.extensions.ReportedSendBWMax=e,this.extensions.ReportedSendBWMin=e)}setMaxSessionBandwidth(e){this.extensions.MaxSessionBandwidth=e}isSubscribed(e,t){let i=this.subscribedTrackIds.some((t=>t===e));return!i&&this.configProvider.config.subscribeToSsrcForVideo&&(i=this.subscribedTrackSsrc.some((e=>e===`${t}`))),i||!this.multiparty&&this.configProvider.config.subscribeToSsrcForVideo}getReport(e=!1,t=!1){try{t&&this.resetPairValues(),e||(this.videoTelemetry.stopDataGathering(),this.sharingTelemetry.stopDataGathering());const i=this.videoTelemetry.getTotalDuration(Qe.MEDIA_DIRECTION.RECV),n=this.videoTelemetry.getTotalDuration(Qe.MEDIA_DIRECTION.SEND),r=this.sharingTelemetry.getTotalDuration(Qe.MEDIA_DIRECTION.RECV),a=this.sharingTelemetry.getTotalDuration(Qe.MEDIA_DIRECTION.SEND);if(i>=0&&(Ze(this.videoTelemetry.getReport(Qe.MEDIA_DIRECTION.RECV,"Video_recv_",t),((e,t)=>this.extensions[t]=e)),!at(this.multiViewVideoTelemetry))){const e=[];for(const i of Object.keys(this.multiViewVideoTelemetry)){const n={id:i};Ze(this.multiViewVideoTelemetry[i].getReport(Qe.MEDIA_DIRECTION.RECV,"Video",t),((e,t)=>{void 0!==e&&(n[t]=e)})),e.push(n)}this.extensions[Qe.MULTIPLE_RECV_STREAMS]=JSON.stringify(e)}r>=0&&Ze(this.sharingTelemetry.getReport(Qe.MEDIA_DIRECTION.RECV,"Sharing_recv_",t),((e,t)=>this.extensions[t]=e)),n>=0&&(Ze(this.videoTelemetry.getReport(Qe.MEDIA_DIRECTION.SEND,"Video_send_",t),((e,t)=>this.extensions[t]=e)),this.extensions.Bandwidth_jumpsHistogram=JSON.stringify(this.bandwidthTelemetry.getReport()),this.extensions.Bandwidth_uplinkStabilizationTime=JSON.stringify(this.stabilizationTelemetry.getReport(!0)),this.extensions.Video_send_CameraOpenWidth=this.cameraOpenResolution.width,this.extensions.Video_send_CameraOpenHeight=this.cameraOpenResolution.height),a>=0&&Ze(this.sharingTelemetry.getReport(Qe.MEDIA_DIRECTION.SEND,"Sharing_send_",t),((e,t)=>this.extensions[t]=e)),Ze(this.dataTelemetry.getReport("Data_"),((e,t)=>this.extensions[t]=e)),e||t||(this.simulcastVideo.finish(),this.extensions.Video_send_Simulcast=JSON.stringify(this.simulcastVideo.collectedSessions),this.simulcastSharing.finish(),this.extensions.Sharing_send_Simulcast=JSON.stringify(this.simulcastSharing.collectedSessions)),this.iceCandidateErrors.length>0&&(this.extensions.iceCandidateErrors=JSON.stringify(this.iceCandidateErrors)),this.extensions.Audio_recv_jitterBufferAvgSize=this.audioTelemetry.getAvgJitterBuffer(),this.extensions.Audio_recv_packetsLostRateMax=this.audioTelemetry.getPacketsLostRateMax(),this.extensions.Audio_recv_networkAvgLossRate=this.audioTelemetry.getNetworkAvgLostRate(),this.extensions.Audio_recv_jitterMax=this.audioTelemetry.getJitterMax(),this.extensions.Audio_recv_jitterAvg=this.audioTelemetry.getJitterAvg(),this.extensions.Video_SubscriptionEvents=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionEvents()),this.extensions.Video_SubscriptionCounters=t?"":JSON.stringify(this.videoTelemetry.getSubscriptionCounters()),this.extensions.Sharing_SubscriptionEvents=t?"":JSON.stringify(this.sharingTelemetry.getSubscriptionEvents()),this.extensions.Sharing_SubscriptionCounters=t?"":JSON.stringify(this.sharingTelemetry.getSubscriptionCounters()),this.extensions.Audio_recv_healedRatioMax=this.audioHealedRatioTelemetry.getHealedRatioMax(),this.extensions.Audio_recv_healedRatioAvg=this.audioHealedRatioTelemetry.getHealedRatioAvg(),this.extensions.Audio_recv_packetsLostAvg=this.audioTelemetry.getAvgPacketsLost(),this.extensions.Audio_send_rttAvg=this.audioTelemetry.getAvgRtt(),this.extensions.Audio_send_rttMax=this.audioTelemetry.getMaxRtt(),this.extensions.CallSetupTimeTracker=JSON.stringify(this.timerTrackerManager.getReport());for(const e of Object.keys(this.extensions))void 0===this.extensions[e]&&delete this.extensions[e];return delete this.extensions.WebRTCStats[Qe.MULTIPLE_RECV_STREAMS],this.sessionInfo.fillExtensionInfo(this.extensions),Object.keys(this.extensions.WebRTCStats).length>0&&!this.extensions.WebRTCStats.hasStatsError&&this.calculateAverages(),this.extensions.H264_available_profiles=this.h264AvailableProfiles.join(),this.extensions.Video_recv_MSIDs=Array.from(this.MSIDs),this.totalVideoControlMessages>0&&(this.extensions.totalVideoControlMessages=this.totalVideoControlMessages,this.extensions.outOfOrderVideoControlMessages=this.outOfOrderVideoControlMessages),lt(this.report)}catch(e){throw this.processStatsError("Report",e),{error:e,partialReport:lt(this.report)}}}getAudioHwSilent(){return this.hwSilent}getSpeakingState(){return this.isSpeaking}getNetworkSendLevel(){return this.networkSendLevel}getNetworkRecvLevel(){return this.networkRecvLevel}addIceCandidateError(e){this.iceCandidateErrors.push(e)}clearIceCandidateErrors(){this.iceCandidateErrors=[]}addH264AvailableProfiles(e){this.h264AvailableProfiles=[...new Set(this.h264AvailableProfiles.concat(e))]}updateSendStream(e,t){this.audioTelemetry.updateSendStream(e,t)}getTimerTracker(e,t){return this.timerTrackerManager.getTimerTracker(e,t)}resetPairValues(){Object.keys(this.extensions.WebRTCStats).forEach((e=>{delete this.extensions.WebRTCStats[e].pair}))}limitCaptureAmount(e,t,i){void 0!==i&&(e[t]=Array.isArray(e[t])?e[t]:[],e[t].push(i),e[t].length>this.storedRecordsNumber&&e[t].shift())}setStartTime(e){const t=this.extensions.WebRTCStats;if(!t.ssrc_audio_send||!t.ssrc_audio_recv)return!1;const i=(e,t)=>!e||t&&-1===t?t:(new Date).getTime();return this.extensions.TimerAudioPayloadRecvBitrate=qg(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioPayloadRecvBitrate):-1,this.extensions.TimerAudioPayloadSendBitrate=Wg(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioPayloadSendBitrate):-1,this.extensions.TimerAudioTransportRecvBitrate=qg(e.audio)?i(t.ssrc_audio_recv.bytesReceived,this.extensions.TimerAudioTransportRecvBitrate):-1,this.extensions.TimerAudioTransportSendBitrate=Wg(e.audio)?i(t.ssrc_audio_send.bytesSent,this.extensions.TimerAudioTransportSendBitrate):-1,!!(t.ssrc_video_send&&t.ssrc_video_recv&&(this.extensions.TimerVideoPayloadRecvBitrate=qg(e.video)?i(t.ssrc_video_recv.bytesReceived,this.extensions.TimerVideoPayloadRecvBitrate):-1,this.extensions.TimerVideoPayloadSendBitrate=Wg(e.video)?i(t.ssrc_video_send.bytesSent,this.extensions.TimerVideoSendBitrate):-1,this.extensions.TimerVideoPayloadRecvBitrate&&this.extensions.TimerVideoPayloadSendBitrate&&this.extensions.TimerAudioPayloadRecvBitrate&&this.extensions.TimerAudioPayloadSendBitrate&&this.extensions.TimerAudioTransportRecvBitrate&&this.extensions.TimerAudioTransportSendBitrate))}calculateAverages(){const e=this.extensions.EndTime,t=(t,i)=>t&&e-i>0&&0!==i&&-1!==i?Math.round(8*t/(e-i)):0,i=e=>{const t=e.split(".").reduce(((e,t)=>null==e?e:e[t]),this.extensions.WebRTCStats);return Array.isArray(t)?t[t.length-1]:t};this.extensions.AudioPayloadRecvBitrate=t(i("ssrc_audio_recv.bytesReceived"),this.extensions.TimerAudioPayloadRecvBitrate),this.extensions.AudioPayloadSendBitrate=t(i("ssrc_audio_send.bytesSent"),this.extensions.TimerAudioPayloadSendBitrate),this.extensions.VideoPayloadRecvBitrate=t(i("ssrc_video_recv.bytesReceived"),this.extensions.TimerVideoPayloadRecvBitrate),this.extensions.VideoPayloadSendBitrate=t(i("ssrc_video_send.bytesSent"),this.extensions.TimerVideoPayloadSendBitrate),this.extensions.AudioTransportRecvBitrate=t(i("ssrc_audio_send.pair.bytesReceived"),this.extensions.TimerAudioTransportRecvBitrate),this.extensions.AudioTransportSendBitrate=t(i("ssrc_audio_send.pair.bytesSent"),this.extensions.TimerAudioTransportSendBitrate)}addFilteredFields(e,t,i=[]){for(const n in t)if(t.hasOwnProperty(n)&&"type"!==n)if(-1!==i.indexOf(n)){const i=e[n]||[];i.push(this.formatFields(t,n)),i.length>this.storedRecordsNumber&&i.shift(),e[n]||(e[n]=i)}else e[n]=t[n]}formatFields(e,t){const i=e[t];switch(t){case"audioInputLevel":case"audioOutputLevel":return this.newStatsApi?Math.floor(65535*i):2*i;case"googJitterBufferMs":return parseInt(i);case"healedRatio":return Ct(parseFloat(i),this.configProvider.config.healedRatioPrecision);case"jitter":return Ct(parseFloat(i),this.configProvider.config.jitterPrecision);default:return i}}processSource(e,t,i){let n;if(this.addFilteredFields(e,t,HO),t.transportId){const r=i.googComponent?.[t.transportId];e.transport||(e.transport={}),r&&(this.addFilteredFields(e.transport,r),r.selectedCandidatePairId&&(n=i.googCandidatePair?.[r.selectedCandidatePairId]))}else n=Object.values(i.googCandidatePair).find((e=>e.selected));n&&(e.pair||(e.pair={}),this.addFilteredFields(e.pair,n,$O))}getWebrtcReport(e,t,i,n){const r=e.ssrc[i],a=n?r.id.replace(/[0-9]+/,n):r.id;t[a]?r.ssrc!==t[a].ssrc&&(a.endsWith("video_send")?this.videoTelemetry.stopSendGathering():a.endsWith("video_recv")?this.videoTelemetry.stopRecvGathering():a.endsWith("sharing_send")?this.sharingTelemetry.stopSendGathering():a.endsWith("sharing_recv")&&this.sharingTelemetry.stopRecvGathering()):t[a]={},this.processSource(t[a],r,e)}constructWebRTCDataReport(e,t){if(!t.data?.length)return;const i=t.data.sort(((e,t)=>t.timestamp-e.timestamp)),n=i.find((e=>"open"===e.state));e.data=n||i[0]}constructWebRtcReportForSingleStream(e,t){if(!t.ssrc)return;const i=this.selectSsrcsToCollect(t.ssrc);e.recvCounters=i.recvCounters,delete i.recvCounters,delete i.multiRecv,Ze(i,(i=>{Ze(i,((i,n)=>{this.getWebrtcReport(t,e,i,n)}))})),t.VideoBwe?.bweforvideo&&(e.bweStat||(e.bweStat={}),this.addFilteredFields(e.bweStat,t.VideoBwe.bweforvideo,GO))}constructWebRtcReportForMultipleStreams(e,t){t.ssrc&&this.selectSsrcsToCollect(t.ssrc).multiRecv.forEach((i=>this.getWebrtcReport(t,e,i)))}getMediaType(e,t){let i=t?t.getModality():e.mediaType;return e.googTrackId?.match("applicationsharing")&&i!==Qe.MEDIA_TYPE.sharing&&(i=Qe.MEDIA_TYPE.sharing),i}selectSsrcsToCollect(e){const t={send:{},recv:{},recvCounters:{video:0,sharing:0},multiRecv:[]};if(!this.sessionInfo.activeModalities)return t;let i=[];for(const n of Object.keys(e)){const r=e[n],a=r.googTrackId;if(!a&&r.mediaType!==Qe.MEDIA_TYPE.audio)continue;const s=this.getMediaEntity(a,r),o=this.getMediaType(r,s),l=s?.getXSourceStreamId();if(n.endsWith("send"))switch(o){case Qe.MEDIA_TYPE.audio:Wg(this.sessionInfo.activeModalities.audio)&&(t.send.audio=n);break;case Qe.MEDIA_TYPE.video:if(this.extensions.Video_send_SourceId=l,this.simulcastVideo.highestFidelitySSRC){this.simulcastVideo.highestFidelitySSRC===r.ssrc&&(t.send.video=n);break}this.streamSenderStarted.Video&&Wg(this.sessionInfo.activeModalities.video)&&s?.getLocalTrackId()&&(s?.getLocalTrackId()===r.googTrackId||this.configProvider.config.statsAllowAnyVideoSendTrack&&!t.send.video)&&(!r.rid||"1"===r.rid)&&(t.send.video=n);break;case Qe.MEDIA_TYPE.sharing:if(this.simulcastSharing.highestFidelitySSRC){this.simulcastSharing.highestFidelitySSRC===r.ssrc&&(t.send.sharing=n);break}this.streamSenderStarted.ScreenShare&&Wg(this.sessionInfo.activeModalities.sharing)&&s?.getLocalTrackId()===r.googTrackId&&(t.send.sharing=n);break;default:this.logger.warn(`Unknown media type '${o}'`)}else if(n.endsWith("recv"))switch(o){case Qe.MEDIA_TYPE.audio:qg(this.sessionInfo.activeModalities.audio)&&(t.recv.audio=n);break;case Qe.MEDIA_TYPE.video:void 0!==l&&this.MSIDs.add(l),this.isSubscribed(r.googTrackId,r.ssrc)&&qg(this.sessionInfo.activeModalities.video)&&(i.push(r),+r.googFrameRateReceived>0&&t.recvCounters[Qe.MODALITY.video]++);break;case Qe.MEDIA_TYPE.sharing:this.isSubscribed(r.googTrackId,r.ssrc)&&qg(this.sessionInfo.activeModalities.sharing)&&(t.recv.sharing=n,+r.googFrameRateReceived>0&&t.recvCounters[Qe.MODALITY.sharing]++);break;default:this.logger.warn(`Unknown media type '${o}'`)}}if(i.length>0){i=i.sort(((e,t)=>+t.googFrameHeightReceived-+e.googFrameHeightReceived));const e=i.find((e=>e.mediaType===Qe.MEDIA_TYPE.video));e&&(t.recv.video=e.id),this.multiparty&&this.configProvider.config.enableMultiViewStats&&(t.multiRecv=i.map((e=>e.id)),t.multiRecv.forEach((e=>{this.multiViewVideoTelemetry[e]||(this.multiViewVideoTelemetry[e]=new FO(this.extensions.StartTime,this.configProvider,this.logger.createChild(`Video[${e}]`,"Video")),this.multiViewVideoTelemetry[e].setMsi(this.MSIDsPairs[e]?.msi),this.multiViewVideoTelemetry[e].setLocalMsi(this.MSIDsPairs[e]?.localMsi),this.multiViewVideoTelemetry[e].prepareCollectingStatsOnSubscribed(this.MSIDsPairs[e]?.msi))})))}return t}getMediaEntityForTrack(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getLocalTrackId()===e||t.getRemoteTrackId()===e))}getMediaEntityByRemoteSsrc(e){if(e)return this.mediaManager.getMediaEntities().find((t=>t.getRemoteSsrc()===+e))}getMediaEntity(e,t){const i=`${t.ssrc}`,n=t.id;let r=this.getMediaEntityForTrack(e);return!r&&this.configProvider.config.subscribeToSsrcForVideo&&n.endsWith("recv")&&(r=this.getMediaEntityByRemoteSsrc(i)),r}calculateHwSilentState(){const e=this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<2*this.hwSilentDetectionDuration)return;let t=!0;for(let i=e.length-this.hwSilentDetectionDuration-1;i<e.length;i++)if(e[i]>this.hwSilentDetectionLevel){t=!1;break}this.hwSilent!==t&&(this.hwSilent=t,this.logger.safe.info(`HW silent changed to ${this.hwSilent}`))}calculateSpeakingState(){const e=this.newStatsApi&&this.configProvider.config.useAudioAnalyzer?this.extensions.Audio_send_RawInputVolume:this.extensions.WebRTCStats.ssrc_audio_send?.audioInputLevel;if(!e||e.length<=this.speakingWhileMutedBadDuration)return;let t=!1;for(let i=e.length-this.speakingWhileMutedBadDuration;i<e.length;i++)if(e[i]>this.speakingWhileMutedDetectionLevel){t=!0;break}this.isSpeaking=t}calculateNetworkRecvQualityLevel(){this.configProvider.config.enableNetworkRecvQualityUFD&&this.extensions.WebRTCStats.ssrc_audio_recv&&(this.networkRecvLevel=this.networkQualityTelemetry.calculateNetworkRecvQualityLevel({googDecodingCTN:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingCTN??[],googDecodingPLC:this.extensions.WebRTCStats.ssrc_audio_recv.googDecodingPLC??[],concealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.concealedSamples??[],silentConcealedSamples:this.extensions.WebRTCStats.ssrc_audio_recv.silentConcealedSamples??[],totalSamplesReceived:this.extensions.WebRTCStats.ssrc_audio_recv.totalSamplesReceived??[],oldNetworkLevel:this.networkRecvLevel.quality}))}calculateNetworkSendQualityLevel(){this.extensions.WebRTCStats.ssrc_audio_send&&(this.networkSendLevel=this.networkQualityTelemetry.calculateNetworkSendQualityLevel(this.extensions.WebRTCStats.ssrc_audio_send.packetsSent,this.extensions.WebRTCStats.ssrc_audio_send.packetsLost,this.extensions.WebRTCStats.ssrc_audio_send.jitter,this.networkSendLevel.quality))}processStatsError(e,t){const i=Be(t);this.logger.safe.error(`webrtcStatistics error [${e}]: ${i}`);const n=this.statsErrors.find((t=>t.error===i&&t.origin===e));n?n.count++:this.statsErrors.push({origin:e,error:i,count:1}),this.statsErrors.length>10&&this.statsErrors.splice(1)}getLastSampleInt(e){return"number"==typeof e?e:e&&parseInt(e[e.length-1])||0}getSsrcIdFromMultipleVideoStream(e){let t;const i=this.extensions.WebRTCStats[Qe.MULTIPLE_RECV_STREAMS]||{};for(const n in i){const r=i[n];if(r&&r.googTrackId===e){t=n;break}}return t}};v([jO],zO.prototype,"onDeviceEvent",1),v([jO],zO.prototype,"onMaxCapabilitiesRequested",1),v([jO],zO.prototype,"onMaxCapabilitiesApplied",1),v([jO],zO.prototype,"addSubscriptionEvent",1),v([jO],zO.prototype,"processSimulcastStats",1),v([jO],zO.prototype,"processBandwidthStats",1),v([jO],zO.prototype,"processAudioStats",1),v([jO],zO.prototype,"processVideoStatsSend",1),v([jO],zO.prototype,"processVideoStatsRecv",1),v([jO],zO.prototype,"processSharingStats",1),v([jO],zO.prototype,"processStreamsCounters",1),v([jO],zO.prototype,"setMissedInitialPreferredResolution",1),v([jO],zO.prototype,"setPreferredResolution",1),v([jO],zO.prototype,"setIsRendering",1),v([jO],zO.prototype,"setReportedSendBandwidth",1),v([jO],zO.prototype,"setMaxSessionBandwidth",1),v([jO],zO.prototype,"setStartTime",1),v([jO],zO.prototype,"calculateAverages",1),v([jO],zO.prototype,"addFilteredFields",1),v([jO],zO.prototype,"formatFields",1),v([jO],zO.prototype,"processSource",1),v([jO],zO.prototype,"getWebrtcReport",1),v([jO],zO.prototype,"constructWebRTCDataReport",1),v([jO],zO.prototype,"constructWebRtcReportForSingleStream",1),v([jO],zO.prototype,"constructWebRtcReportForMultipleStreams",1),v([jO],zO.prototype,"selectSsrcsToCollect",1),v([jO],zO.prototype,"calculateHwSilentState",1),v([jO],zO.prototype,"calculateSpeakingState",1),v([jO],zO.prototype,"calculateNetworkRecvQualityLevel",1),v([jO],zO.prototype,"calculateNetworkSendQualityLevel",1);var WO=class extends qe{constructor(e,t,i,n){super(),this.logger=e,this.configProvider=t,this.mediaManager=i,this.window=Ug.window,this._sessionInfo=new TM,this.statisticsMapper=new gO,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.webRtcStatistics=new zO(this.logger.createChild("WebrtcStatistics"),this._sessionInfo,this.configProvider,i,n,this.useNewStatsApi)}setAudioDecoderStatsProvider(e){this.statisticsMapper?.setAudioDecoderStatsProvider(e)}get sessionInfo(){return this._sessionInfo}get isDisposed(){return null===this.pc&&0===this.interval}initialize(e){this.pc=e}startWaitingForStreamStart(e){this.webRtcStatistics.startWaitingForStreamStart(e)}onDeviceEvent(e){this.webRtcStatistics.onDeviceEvent(e)}onMaxCapabilitiesRequested(e){this.webRtcStatistics.onMaxCapabilitiesRequested(e)}onMaxCapabilitiesApplied(e){this.webRtcStatistics.onMaxCapabilitiesApplied(e)}onSendersChanged(e,t){this.webRtcStatistics.setStreamSenderStarted(e,t)}addSubscriptionEvent(e,t,i,n,r,a,s){this.webRtcStatistics.addSubscriptionEvent(e,t,i,n,r,a,s)}setSubscribedTrackIds(e){this.webRtcStatistics.setSubscribedTrackIds(e)}setSubscribedTrackSsrc(e){this.webRtcStatistics.setSubscribedTrackSsrc(e)}setPreferredResolution(e,t,i){this.webRtcStatistics.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.webRtcStatistics.setIsRendering(e,t,i)}setReportedSendBandwidth(e){this.webRtcStatistics.setReportedSendBandwidth(e)}setMaxSessionBandwidth(e){this.webRtcStatistics.setMaxSessionBandwidth(e)}setTerminated(){this.webRtcStatistics.setTerminated()}addIceCandidateError(e){this.webRtcStatistics.addIceCandidateError(e)}clearIceCandidateErrors(){this.webRtcStatistics.clearIceCandidateErrors()}recordDataChannelProtocolEvent(e){this.webRtcStatistics.recordDataChannelProtocolEvent(e)}setSessionDataChannelState(e){this.webRtcStatistics.setSessionDataChannelState(e)}recordDataChannelError(e){this.webRtcStatistics.recordDataChannelError(e)}updateSendStream(e,t){this.webRtcStatistics.updateSendStream(e,t)}getTimerTracker(e,t){return this.webRtcStatistics.getTimerTracker(e,t)}setH264AvailableProfiles(e){if(!e?.codecs)return;let t=[];e.codecs.forEach((e=>{if("h264"===e.mimeType&&e.sdpFmtpLine){const i=/profile-level-id=(.{6})/.exec(e.sdpFmtpLine);i?.[1]&&(t=t.concat(i[1]))}})),this.webRtcStatistics.addH264AvailableProfiles(t)}processRawReport(e){this.processStatsDict(this.statisticsMapper.build(e))}processLegacyReport(e){this.processStatsDict(function(e){const t={};return e.result().forEach((e=>{e.names().forEach((i=>{t[e.type]=t[e.type]||{},t[e.type][e.id]=t[e.type][e.id]||{},t[e.type][e.id][i]=e.stat(i)})),t[e.type][e.id].id=e.id})),t}(e))}getReport(e,t=!1){const i=this.webRtcStatistics.getReport(e,t);return this.addStreamInfoForE2ETests(i),i}dispose(){this.interval&&(this.window.clearInterval(this.interval),this.interval=0),this.pc=null}getLastStatistics(){return this.statistics}setTimeToFirstFrame(e,t,i){this.webRtcStatistics.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.webRtcStatistics.setFreezeDuration(e,t)}addVideoControlMessage(e=!1){this.webRtcStatistics.addVideoControlMessage(e)}setSsrcTrackPair(e,t){this.statisticsMapper.setSsrcTrackPair(e,t)}updateStatsWithLocalSsrcTrackInfo(){for(const e of this.mediaManager.getMediaEntities()){const t=e.getLocalSsrc();t&&this.statisticsMapper.setSsrcTrackPair(t,e.getLocalTrackId())}}addReportedReceiveBandwidth(e){this.webRtcStatistics.addReportedReceiveBandwidth(e)}addStreamInfoForE2ETests(e){const t=this._sessionInfo.negotiatedModalities;if(t&&!this.isDisposed)try{e.localStreams=this.getSendersReport(this.pc.getSenders(),{audio:Wg(t.audio),video:Wg(t.video)}),e.remoteStreams=this.getReceiversReport(this.pc.getReceivers(),{audio:qg(t.audio),video:qg(t.video)})}catch(e){this.logger.safe.warn(`addStreamInfoForE2ETests failed: ${Be(e)}`)}}getReceiversReport(e,t){const i=[];return e.forEach((e=>{const n={tracks:[]};i.push(n),e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}getSendersReport(e,t){const i=[],n={tracks:[]};return i.push(n),e.forEach((e=>{e.track&&("audio"===e.track.kind&&t.audio||"video"===e.track.kind&&t.video)&&n.tracks.push({stream:void 0,track:e.track})})),i}processStatsDict(e){this.webRtcStatistics.processStatsDict(e);let t=0,i=0;const n=e.VideoBwe?.bweforvideo;n&&(t=Number(n.googAvailableReceiveBandwidth),i=Number(n.googAvailableSendBandwidth));const r=1e3*((this.configProvider.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(this.configProvider.config.audioBandwidthInKbps||0)),a=isNaN(t)?0:t,s=isNaN(i)?0:i,o={estimatedReceiveBandwidth:Math.min(a,r),estimatedSendBandwidth:Math.min(s,r),remoteVideoStreams:{},localVideoStreams:{},isSpeaking:this.webRtcStatistics.getSpeakingState(),audioHwSilent:this.webRtcStatistics.getAudioHwSilent(),networkSendLevel:this.webRtcStatistics.getNetworkSendLevel(),networkRecvLevel:this.webRtcStatistics.getNetworkRecvLevel()};Ze(e.ssrc,(e=>{if("video"!==e.mediaType)return;const t=e.googTrackId,i=e.id;-1!==i.indexOf("_recv")?(o.remoteVideoStreams[t]={trackId:t,frameRateReceived:Number(e.googFrameRateReceived),frameRateDecoded:Number(e.googFrameRateDecoded),framesDecoded:Number(e.framesDecoded)},this.configProvider.config.isRenderingBasedOnRawStatistics||(o.remoteVideoStreams[t].isRendering=this.webRtcStatistics.getIsRendering(i))):t&&-1!==i.indexOf("_send")&&(o.localVideoStreams[t]={trackId:t,ssrc:Number(e.ssrc),frameRateInput:Number(e.googFrameRateInput)})})),ut(this.statistics,o)||(this.statistics=o,this.notifyStatisticsChanged())}notifyStatisticsChanged(){this.event("onStatisticsChanged").raise(this.statistics)}},qO=class extends qe{constructor(e,t,i,n,r){super(),this.logger=e,this.configProvider=t,this.diagnostics=i,this.mediaManager=n,this.window=Ug.window,this.useNewStatsApi=this.configProvider.config.webrtcUseNewStatsApi&&this.configProvider.mediaConfig.simulcastSessionEnabled,this.loopIntervalTracker=new yD(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.loopIntervalAggregator=new CD,this.fetchTimeTracker=new yD(this.configProvider.config.diagnostics.performanceMonitoring.fluctuationSamplesNum),this.fetchTimeAggregator=new CD,this.gathererV1=new WO(this.logger.createChild("V1"),this.configProvider,this.mediaManager,r),this.gathererV1.on("onStatisticsChanged",(e=>this.event("onStatisticsChanged").raise(e))),this.useNewStatsApi&&t.config.diagnostics.sideBySide&&(this.gathererV2=new nO(this.logger.createChild("V2"),this.configProvider,this.diagnostics,this.mediaManager))}initialize(e){this.pc=e,this.gathererV1.initialize(e),this.interval??(this.interval=this.window.setInterval((()=>this.processStats()),this.configProvider.config.webrtcStatPollInterval))}setAudioDecoderStatsProvider(e){this.gathererV1.setAudioDecoderStatsProvider(e),this.gathererV2?.setAudioDecoderStatsProvider(e)}dispose(){super.dispose(),this.interval&&(this.window.clearInterval(this.interval),this.interval=void 0),this.gathererV1.dispose(),this.pc=void 0}get isDisposed(){return!this.pc&&void 0===this.interval}async processStats(){if(this.configProvider.config.diagnostics.collectWhileNotConnected){if(!this.pc||"closed"===this.pc.iceConnectionState)return}else if(!this.pc||"connected"!==this.pc.iceConnectionState&&"completed"!==this.pc.iceConnectionState)return void this.gathererV2?.signalNoConnection();if(this.useNewStatsApi){const e=Pt(),t=void 0===this.loopTimer?-1:e-this.loopTimer;this.loopTimer=e,this.loopIntervalTracker.captureSample(t),this.loopIntervalAggregator.captureSample(this.loopIntervalTracker.getReport());const i=this.loopIntervalAggregator.getReport();i&&(this.diagnostics.loopIntervalMax=i.max,this.diagnostics.loopIntervalMedian=i.median);const n={};(await this.pc.getStats()).forEach((e=>{this.cleanupPii(e);const t=e.type;delete e.type,n[t]??(n[t]={}),n[t][e.id]=e}));const r=Pt()-e;this.fetchTimeTracker.captureSample(r),this.fetchTimeAggregator.captureSample(this.fetchTimeTracker.getReport());const a=this.fetchTimeAggregator.getReport();a&&(this.diagnostics.fetchTimeMax=a.max,this.diagnostics.fetchTimeMedian=a.median);const s=this.gathererV2?.processRawReport(n);let o=Pt();this.gathererV1.processRawReport(n),o=Pt()-o,s&&this.event("onDiagnosticUpdated").raise(s),s?.perfCounters&&(s.perfCounters.loopTime=t,s.perfCounters.fetchTime=r,s.perfCounters.legacyProcessingTime=o)}else this.pc.getStats((e=>{e.result&&this.gathererV1.processLegacyReport(e)}))}cleanupPii(e){switch(e.type){case"local-candidate":case"remote-candidate":{const t=e;Object.defineProperty(t,"address",{enumerable:!1}),Object.defineProperty(t,"url",{enumerable:!1}),Object.defineProperty(t,"relatedAddress",{enumerable:!1}),Object.defineProperty(t,"ip",{enumerable:!1}),Object.defineProperty(t,"usernameFragment",{enumerable:!1});break}case"certificate":{const t=e;Object.defineProperty(t,"fingerprint",{enumerable:!1}),Object.defineProperty(t,"base64Certificate",{enumerable:!1});break}}}get sessionInfo(){return this.gathererV1.sessionInfo}setReportedSendBandwidth(e){this.gathererV1.setReportedSendBandwidth(e)}onMaxCapabilitiesApplied(e){this.gathererV1.onMaxCapabilitiesApplied(e)}clearIceCandidateErrors(){this.gathererV1.clearIceCandidateErrors()}setSsrcTrackPair(e,t){this.gathererV1.setSsrcTrackPair(e,t),this.gathererV2?.setSsrcTrackPair(e,t)}addSubscriptionEvent(e,t,i,n,r,a,s){this.gathererV1.addSubscriptionEvent(e,t,i,n,r,a,s)}setSubscribedTrackSsrc(e){this.gathererV1.setSubscribedTrackSsrc(e)}addIceCandidateError(e){this.gathererV1.addIceCandidateError(e)}setH264AvailableProfiles(e){this.gathererV1.setH264AvailableProfiles(e)}setTerminated(){this.gathererV1.setTerminated()}onDeviceEvent(e){this.gathererV1.onDeviceEvent(e)}getReport(e,t=!1){const i=this.gathererV1.getReport(e,t);if(this.gathererV2&&this.configProvider.config.diagnostics.sideBySide){const e=this.loopIntervalAggregator.getReport();e&&(i.data.Extensions.LoopIntervalMax=`${Ct(e.max,1)}`,i.data.Extensions.LoopIntervalMedian=`${Ct(e.median,1)}`);const t=this.fetchTimeAggregator.getReport();t&&(i.data.Extensions.FetchTimeMax=`${Ct(t.max,1)}`,i.data.Extensions.FetchTimeMedian=`${Ct(t.median,1)}`);const n=this.diagnostics.getObjectRef();i.data.Extensions.multipleVideoStreams=JSON.stringify(kt(n.multiViewStats,"startTime",n.startTime)),i.data.Extensions.OvcToSubscriptions=JSON.stringify(n.ovcToSubscriptionEvents),i.data.Extensions.videoPerformanceEvent=JSON.stringify(n.videoPerformanceEvent);const r=n.bandwidthReport;"REMB"===n.bweType?(i.data.Extensions.StartCallBWE=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWE=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStd=JSON.stringify(r?.std),i.data.Extensions.BwPercentiles=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwe=JSON.stringify(r?.avgBwe)):(i.data.Extensions.StartCallBWESendSide=JSON.stringify(r?.startOfTheCall),i.data.Extensions.EndCallBWESendSide=JSON.stringify(r?.endOfTheCall),i.data.Extensions.BWEStdSendSide=JSON.stringify(r?.std),i.data.Extensions.BwPercentilesSendSide=JSON.stringify(r?.bwPercentiles),i.data.Extensions.AvgBwSendSide=JSON.stringify(r?.avgBwe)),i.data.Extensions.InitialBWSeed=JSON.stringify(n.initialBWSeed),i.data.Extensions.SentBWSeed=JSON.stringify(n.sentBWSeed),i.data.Extensions.Bandwidth_downlinkStabilizationTime=JSON.stringify(n.bwDownlinkStabilizationTime);const a=n.aggregatedModalityStats?.video?.recv||[],s=n.aggregatedModalityStats?.audio?.recv||[],o=n.aggregatedModalityStats?.sharing?.recv||[],l=a[a.length-1],c=o[o.length-1],d=l?.aggregated?.macroblockRateStats??{},u=s[s.length-1]?.aggregated?.customHealerStats??{};if(u?.pullPacketProcessingTimes){const e=Ft(u.pullPacketProcessingTimes);u.pullPacketProcessingTimeP50=e.getPercentile(.5),u.pullPacketProcessingTimeP95=e.getPercentile(.95)}if(u?.pushPacketProcessingTimes){const e=Ft(u.pushPacketProcessingTimes);u.pushPacketProcessingTimeP50=e.getPercentile(.5),u.pushPacketProcessingTimeP95=e.getPercentile(.95)}for(const e in d)i.data.Extensions[`Video_recv_${e}`]=`${Ct(d[e],0)}`;for(const e in n.totalVideoRecvMblocksRates)i.data.Extensions[`totalVideoRecv_${e}`]=`${Ct(n.totalVideoRecvMblocksRates[e],0)}`;for(const e in u)if(void 0!==u[e]){const t="number"!=typeof u[e]?JSON.stringify(u[e]):u[e];i.data.Extensions[`Audio_recv_customHealer_${e}`]=t}i.data.Extensions.CallSetupTimeTracker=JSON.stringify(n.timerTrackerReport),i.data.Extensions.Audio_send_presentationAPIUserDuration=JSON.stringify(n.presentationAPIUserDuration),i.data.Extensions.Audio_send_presentationDuration=JSON.stringify(n.presentationAudioDuration),i.data.Extensions.CodecSupport=JSON.stringify(n.codecSupport),i.data.Extensions.Video_recv_FpsHarmonicAverage=l?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_FpsHarmonicAverage=c?.extensions.fpsHarmonicAverage?.toString(),i.data.Extensions.Sharing_recv_CodecReport=JSON.stringify(c?.aggregated.codecReport),this.configProvider.config.diagnostics.features.takeFreezeTelemetryFromGathererV2&&(a.length&&(i.data.Extensions.Video_recv_FreezeHistogram=JSON.stringify(l.aggregated.freezeCountHistogram),i.data.Extensions.Video_recv_LongestFreezeDuration=JSON.stringify(l?.aggregated?.longestFreeze),i.data.Extensions.Video_recv_OngoingFreeze=JSON.stringify(l?.extensions?.isFrozen),i.data.Extensions.Video_recv_OngoingFreezeDuration=JSON.stringify(l?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Video_recv_TotalFreezeDuration=JSON.stringify(l?.aggregated?.totalFreezeDuration),i.data.Extensions.Video_recv_RecvAvgFreezeDuration=JSON.stringify(l?.aggregated?.avgFreezeDuration),i.data.Extensions.Video_recv_FreezeTimestamps=JSON.stringify(Dt(l?.aggregated?.freezeTimestampsHistogram,n.startTime))),o.length&&(i.data.Extensions.Sharing_recv_FreezeHistogram=JSON.stringify(c.aggregated.freezeCountHistogram),i.data.Extensions.Sharing_recv_LongestFreezeDuration=JSON.stringify(c?.aggregated?.longestFreeze),i.data.Extensions.Sharing_recv_OngoingFreeze=JSON.stringify(c?.extensions?.isFrozen),i.data.Extensions.Sharing_recv_OngoingFreezeDuration=JSON.stringify(c?.aggregated?.ongoingFreezeDuration),i.data.Extensions.Sharing_recv_TotalFreezeDuration=JSON.stringify(c?.aggregated?.totalFreezeDuration),i.data.Extensions.Sharing_recv_RecvAvgFreezeDuration=JSON.stringify(c?.aggregated?.avgFreezeDuration),i.data.Extensions.Sharing_recv_FreezeTimestamps=JSON.stringify(Dt(c?.aggregated?.freezeTimestampsHistogram,n.startTime)))),i.data.Extensions.EarlyMedia={NumStatsPolls:`${n.earlyMediaNumStatsPolls}`}}return i}startWaitingForStreamStart(e){this.gathererV1.startWaitingForStreamStart(e)}getTimerTracker(e,t){return this.gathererV1.getTimerTracker(e,t)}getLastStatistics(){return this.gathererV1.getLastStatistics()}updateSendStream(e,t){this.gathererV1.updateSendStream(e,t)}setSubscribedTrackIds(e){this.gathererV1.setSubscribedTrackIds(e)}setMaxSessionBandwidth(e){this.gathererV1.setMaxSessionBandwidth(e)}updateStatsWithLocalSsrcTrackInfo(){this.gathererV1.updateStatsWithLocalSsrcTrackInfo()}onSendersChanged(e,t){this.gathererV1.onSendersChanged(e,t)}setPreferredResolution(e,t,i){this.gathererV1.setPreferredResolution(e,t,i)}setIsRendering(e,t,i){this.gathererV1.setIsRendering(e,t,i)}setTimeToFirstFrame(e,t,i){this.gathererV1.setTimeToFirstFrame(e,t,i)}setFreezeDuration(e,t){this.gathererV1.setFreezeDuration(e,t)}addVideoControlMessage(e){this.gathererV1.addVideoControlMessage(e)}setSessionDataChannelState(e){this.gathererV1.setSessionDataChannelState(e)}recordDataChannelError(e){this.gathererV1.recordDataChannelError(e)}onMaxCapabilitiesRequested(e){this.gathererV1.onMaxCapabilitiesRequested(e)}recordDataChannelProtocolEvent(e){this.gathererV1.recordDataChannelProtocolEvent(e)}addReportedReceiveBandwidth(e){this.gathererV1.addReportedReceiveBandwidth(e)}},KO=101,JO=[48e3,32e3,24e3,16e3,12e3],YO=class{constructor(e){this.context=e,this.cname=dt(),this.dataMedia={type:Qe.MEDIA_TYPE.data,protocol:Qe.PROFILES.rtpSavp,port:0},this.configProvider=e.configProvider,this.logger=e.getLogger().createChild("WebkitSdpTrans")}fixTelephoneEvent(e){let t;return JO.forEach((t=>{LA(e,{codec:"telephone-event",rate:t})})),MA(e,KO,999),DA(e,{codec:"telephone-event",rate:8e3},(e=>(t=e.rtp.payload,e.rtp.payload=KO,e))),MA(e,999,t||KO),t}toLocal(e,t,i){const n=t.isEmpty(),r=lt(e);let a;return r.media.forEach((e=>{if("audio"===e.type)n&&(a=this.fixTelephoneEvent(e)),ZO(e);else{a&&MA(e,KO,a);const i=t.getLocalSsrcs().get(HA(e));this.enforceFixedSsrc(e,i)}const r=Sm(this.configProvider,e.type);"offer"===i&&iN(e,r,n,this.logger)})),new qP(this.configProvider).modify(r),delete r.extmapAllowMixed,r}toOffer(e,t,i){return this.fromNative(e,t,i,!0)}toAnswer(e,t,i){return this.fromNative(e,t,i,!1)}toRemote(e,t,i,n){const r=lt(e);let a,s,o=this.configProvider.mediaConfig.maxBandwidthInKbps;r.bandwidth&&(!o||o>e.bandwidth[0].limit)&&(o=e.bandwidth[0].limit),r.media.forEach(((e,i)=>{t.getMediaEntity(i).isDisabled()&&e.type!==Qe.MEDIA_TYPE.audio&&(e.port=0)}));let l=function(e){return e.groups?e.groups.find((e=>"BUNDLE"===e.type)):null}(r);if(!l){let e=!1;r.media.forEach(((i,n)=>{const r=t.getMediaEntity(n);!e&&r.isEnabled()?(i.mid=r.getMid(),e=!0):(r.disable(),i.port=0)})),e&&(r.groups||(r.groups=[]),l={type:"BUNDLE"},r.groups.push(l))}r.media.forEach((e=>{const t=HA(e);i[t]===Qe.MEDIA_STATE.send&&(e.direction&&e.direction.toLowerCase()===Qe.MEDIA_STATE.receive||(e.direction=Qe.MEDIA_STATE.receive))}));const c=r.media.filter((e=>e.type===Qe.MEDIA_TYPE.video));if(c.length>0){const e=c.filter((e=>0!==e.port));if(e.length>0){s=lt(e[0]),s.bandwidth&&delete s.bandwidth;const t=this.configProvider.config.audioBandwidthInKbps?this.configProvider.config.audioBandwidthInKbps:0;o&&o-t>0&&(s.bandwidth=[{limit:o-t,type:"AS"}]),s.mid="video",s.direction=null,delete s.label,s.ssrcs=[],s.ssrcGroups=[],delete s.msid,e.forEach((e=>{e.ssrcs&&(s.ssrcs=s.ssrcs.concat(e.ssrcs)),e.ssrcGroups&&(s.ssrcGroups=s.ssrcGroups.concat(e.ssrcGroups)),s.direction=function(e,t){return e===Qe.MEDIA_STATE.sendReceive||t===Qe.MEDIA_STATE.sendReceive?Qe.MEDIA_STATE.sendReceive:e===t?e:e&&t&&e!==t?Qe.MEDIA_STATE.sendReceive:e||t}(s.direction,e.direction||Qe.MEDIA_STATE.sendReceive)})),QO(s)}else s=eN(Qe.MEDIA_TYPE.video,void 0,c[0].protocol,c[0].payloads)}const d=r.media.find((e=>e.type===Qe.MEDIA_TYPE.audio));if(d)if(0!==d.port)a=lt(d),a.mid="audio",delete a.label,function(e){LA(e,{codec:"g722",rate:8e3,encoding:2})}(a),ZO(a),QO(a);else{a=eN(Qe.MEDIA_TYPE.audio,void 0,d.protocol,d.payloads);const e=r.media.find((e=>!!e.iceUfrag));e&&(a.port=9,a.direction="inactive",a.mid="audio",a.iceUfrag=e.iceUfrag,a.icePwd=e.icePwd,a.rtcpMux="rtcp-mux",e.crypto&&(a.crypto=e.crypto),e.fingerprint&&(a.fingerprint=e.fingerprint,a.setup=e.setup),a.rtp=[{payload:0,codec:"PCMU",rate:8e3}],a.payloads="0")}r.media.forEach(((e,t)=>{e.type===Qe.MEDIA_TYPE.data&&(e.type=Qe.MEDIA_TYPE.dataChannel,e.payloads=Qe.PAYLOAD_TYPE.DATA_CHANNEL,e.protocol=Qe.PROFILES.udpDtlsSctp,e.mid="data",delete e.xDataProtocol,delete e.direction,zA(e)&&(r.media[t]=eN(e.type,void 0,e.protocol,e.payloads)))}));const u=vm(this.context)?r.media.find((e=>e.type===Qe.MEDIA_TYPE.dataChannel)):null;r.media=[a,s,u].filter((e=>e)),t.getMediaEntities()[0].getModality()!==Qe.MODALITY.audio&&r.media.reverse();const h=mm(this.context),p=tm(e);return r.media.forEach((e=>{e.type!==Qe.MEDIA_TYPE.dataChannel&&(!h&&e.fingerprint&&e.crypto&&delete e.crypto,e.protocol=!p.dtls||p.sdes&&h?Qe.PROFILES.rtpSavpf:Qe.PROFILES.udpTlsRtpSavpf)})),"offer"===n&&(iN(a,this.configProvider.config.allowedAudioCodecs,!1,this.logger),iN(s,this.configProvider.config.allowedVideoCodecs,!1,this.logger)),XO(r,this.configProvider.mediaConfig.isTransportUnbundled),r}splitMedia(e,t,i,n,r){const a=e.getMid(),s=e.getModality(),o=lt(t);if(o.label=$A(s),o.direction=n,o.mid=a,o.ssrcs=[],o.ssrcGroups=[],e.getModality()===Qe.MODALITY.data)return o.type=Qe.MEDIA_TYPE.data,o.payloads=Qe.PAYLOAD_TYPE.X_DATA,o;const l=i.filter((e=>e.modality===s));if(l&&l.length){const e=[];t.ssrcs&&(l.forEach((i=>{const n=t.ssrcs.filter((e=>"msid"===e.attribute&&i.trackId===tN(e.value))).map((e=>e.id));e.push(...n)})),o.ssrcs=t.ssrcs.filter((t=>e.indexOf(t.id)>-1)),o.ssrcs.forEach((e=>{"cname"===e.attribute&&(e.value=this.cname)}))),t.ssrcGroups&&(o.ssrcGroups=t.ssrcGroups.filter((t=>t.ssrcs.split(" ").find((t=>e.indexOf(+t)>-1)))))}else{if(n===Qe.MEDIA_STATE.send||n===Qe.MEDIA_STATE.sendReceive)return eN(t.type,$A(s),t.protocol,t.payloads);n!==Qe.MEDIA_STATE.receive&&n!==Qe.MEDIA_STATE.inactive||(r[t.type].ssrcs&&r[t.type].ssrcs[0]?o.ssrcs=[{id:r[t.type].ssrcs[0].id,attribute:"cname",value:this.cname}]:t.type===Qe.MEDIA_TYPE.audio?o.ssrcs=[{id:4195875351,attribute:"cname",value:this.cname}]:t.type===Qe.MEDIA_TYPE.video&&(o.ssrcs=[{id:1,attribute:"cname",value:this.cname}]))}return o}fromNative(e,t,i,n){const r=lt(e),a=this.configProvider.mediaConfig.maxBandwidthInKbps;a&&(r.bandwidth=[{limit:a,type:"CT"}]),new KP(this.configProvider).modify(r);const s=r.media.find((e=>e.type===Qe.MEDIA_TYPE.audio)),o=r.media.find((e=>e.type===Qe.MEDIA_TYPE.video)),l=r.media.find((e=>e.type===Qe.MEDIA_TYPE.dataChannel)),c={};c[Qe.MODALITY.audio]=s,c[Qe.MODALITY.video]=o,c[Qe.MODALITY.sharing]=o,c[Qe.MODALITY.data]=l||this.dataMedia;const d={};d[Qe.MEDIA_TYPE.audio]=s,d[Qe.MEDIA_TYPE.video]=o,d[Qe.MEDIA_TYPE.data]=l||this.dataMedia;const u={};return u[Qe.MODALITY.audio]=t.getMediaEntitiesByModality(Qe.MODALITY.audio)[0],u[Qe.MODALITY.video]=t.getMediaEntitiesByModality(Qe.MODALITY.video)[0],u[Qe.MODALITY.sharing]=t.getMediaEntitiesByModality(Qe.MODALITY.sharing)[0],u[Qe.MODALITY.data]=t.getMediaEntitiesByModality(Qe.MODALITY.data)[0],r.media=[],t.getMediaEntities().forEach((e=>{let a,s=i[e.getModality()];!e.isEnabled()||0===c[e.getModality()].port||e!==u[e.getModality()]&&s===Qe.MEDIA_STATE.send?(a=eN(e.getType(),$A(e.getModality()),c[e.getModality()].protocol,c[e.getModality()].payloads),c[e.getModality()].payloads===Qe.PAYLOAD_TYPE.DATA_CHANNEL&&(a.payloads=Qe.PAYLOAD_TYPE.DATA_CHANNEL)):(s!==Qe.MEDIA_STATE.inactive&&e!==u[e.getModality()]&&(s=Qe.MEDIA_STATE.receive),a=this.splitMedia(e,c[e.getModality()],t.getLocalTracksInfo(),s,d),e!==u[e.getModality()]&&(a.candidates=[]));const o=c[e.getModality()].setup;o&&("actpass"!==o?e.setExtension("setup",o):n&&void 0!==e.getExtension("setup")&&(a.setup="actpass"!==e.getExtension("setup")?e.getExtension("setup"):o));const l=c[e.getModality()].iceUfrag,h=e.getExtension("iceUfrag");e.setExtension("iceRestart",!!l&&!!h&&h!==l),e.setExtension("iceUfrag",l),zA(a)&&e.disable(),r.media.push(a)})),new hP(this.context,i.data).modify(r),XO(r,this.configProvider.mediaConfig.isTransportUnbundled),r}enforceFixedSsrc(e,t){let i=-1;if(!e.ssrcs)return;const n=[];if(e.ssrcs.forEach((e=>{"msid"===e.attribute&&n.push({ssrc:e.id,trackId:tN(e.value)})})),e.ssrcs.forEach((e=>{"cname"===e.attribute&&i++,t&&(e.id=this.getVideoSSRC(i,t))})),e.ssrcGroups){const t=e.ssrcs.filter((e=>"cname"===e.attribute)).map((e=>e.id));e.ssrcGroups.forEach(((e,i)=>{e.ssrcs=[t[2*i],t[2*i+1]].join(" ")}))}}getVideoSSRC(e,t){return e%2==1?t+50:t}};function QO(e){const t=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);e.ext&&(e.ext=e.ext.filter((e=>!t.has(e.uri))))}function ZO(e){LA(e,{codec:"CN",rate:16e3})}function XO(e,t){const i=e.groups?.findIndex((e=>"BUNDLE"===e.type)),n=e.groups?e.groups[i]:void 0;n&&(t?(n.mids=e.media.filter((e=>e.type===Qe.MEDIA_TYPE.video)).map((e=>e.mid)).filter((e=>e)).join(" "),n.mids||delete e.groups[i]):n.mids=e.media.map((e=>e.mid)).filter((e=>e)).join(" "))}function eN(e,t,i,n){return{type:e,port:0,label:t,payloads:n,protocol:i}}function tN(e){return e.split(" ")[1]}function iN(e,t,i,n){t.length&&e?.port&&BA(e,_m(t),i,n)}var nN=f(ye()),rN=class{getCapabilities(e){const t=RTCRtpReceiver.getCapabilities(e);return t.codecs.forEach((e=>{const t=e.mimeType.toLowerCase().split("/");e.mimeType=t[1]||t[0]})),Promise.resolve(t)}},aN=class{constructor(e,t){this.noRequiredCodecsWorkaround=t,this.selfGlobal=e.global.capabilityGatherer=e.global.capabilityGatherer||{},this.getCapabilities("video")}async getCapabilities(e){if("video"!==e&&"audio"!==e)return Promise.reject(new Error(`capabilities for ${e} are not supported`));if(!this.selfGlobal.gatherTask){const e=km();this.selfGlobal.gatherTask=e.promise;const t=void 0!==Ug.window.webkitRTCPeerConnection,i=t?new Ug.window.webkitRTCPeerConnection(null):new Ug.window.RTCPeerConnection(null),n=e=>t?new Promise(((t,n)=>{i.createOffer(t,n,e)})):(this.noRequiredCodecsWorkaround&&i.addTrack(i.addTransceiver("video").receiver.track),i.createOffer(e));try{const t=await n({offerToReceiveVideo:1,offerToReceiveAudio:1}),r={};nN.parse(t.sdp).media.forEach((e=>{r[e.type]=e.rtp.map((t=>{const i={mimeType:t.codec.toLowerCase()};if("video"===e.type){const n=e.fmtp?.find((e=>e.payload===t.payload));i.sdpFmtpLine=n?.config}return i}))})),i.close(),e.resolve(r)}catch(t){this.selfGlobal.gatherTask=null,i.close(),e.reject(t)}}return this.selfGlobal.gatherTask.then((t=>({codecs:t[e]})))}},sN=(e,t,i=!1)=>!t&&Bg.hasCapabilitiesApi()?new rN:new aN(e,i),oN=f(ye()),lN="rollback";function cN(){const e=[].slice.apply(arguments);let t=e[0]&&dN(e[0].type);e.splice(0,t?1:0,null);const i=new(Function.prototype.bind.apply(Ug.window.RTCSessionDescription,e)),n=Object.getOwnPropertyDescriptor(Ug.window.RTCSessionDescription.prototype,"type");return Object.defineProperty(i,"type",{get:()=>t?lN:n.get.call(i),set(e){t=dN(e),t||n.set.call(i,e)}}),i}function dN(e){return lN===e}var uN=()=>cN,hN=[{codec:"telephone-event",rate:8e3},{codec:"cn",rate:16e3}];function pN(e){const t=[],i=uN(),n=[].slice.apply(arguments);n.splice(0,1,null),function(e,t){n[1]&&n[1][e]&&(n[1][t]=n[1][e])}("iceTransportPolicy","iceTransports");const r=new(Function.prototype.bind.apply(Ug.window.webkitRTCPeerConnection,n));function a(e,t){let i;Object.defineProperty(this,"dtmf",{get:()=>"audio"===e.kind?(i=i||r.createDTMFSender(e),i):null}),this.track=e,this._stream=t}return[{name:"createOffer",reverseArgs:!0},"createAnswer","setRemoteDescription","setLocalDescription"].forEach((function(e){const t=e.name||e,i=r[t];r[t]=function(){const t=arguments;return new Promise((function(n,a){const s=[n,a];t.length>0&&s.splice(e.reverseArgs?s.length:0,0,t[0]),i.apply(r,s)}))}})),function(){["createOffer","createAnswer","setLocalDescription"].forEach((function(t){const i=r[t];r[t]=function(){const t=arguments;return e.getCapabilities("video").then((function(){return i.apply(i,t)}))}}));const t=r.setRemoteDescription;r.setRemoteDescription=function(i){return e.getCapabilities("video").then((function(e){const n=e.codecs,r=oN.parse(i.sdp);return r.media.forEach((function(e){if("video"===e.type&&(e.rtp.some((function(e){return n.some((function(t){return e.codec.toLowerCase()===t.mimeType}))}))?function(e){DA(e,{codec:"h264",rate:9e4},(function(e){if(e.fmtp){const t=new PA,i=new PA(e.fmtp.config);["level-asymmetry-allowed","packetization-mode","profile-level-id"].forEach((function(e){if(i.contains(e)){let n=i.get(e);"profile-level-id"===e&&(n="42C02A"),t.setIfMissing(e,n)}})),e.fmtp.config=t.toString()}}))}(e):e.port=0),!function(e){return"RTP/SAVPF"!==e.protocol}(e)){const t=jA(r);t?e.crypto=t.crypto:e.port||r.media.some((function(t){return!!t.port&&(e.crypto=t.crypto,!0)}))}})),i.sdp=oN.write(r),t(i)}))}}(),function(){const e=r.createAnswer;r.createAnswer=function(){const t=arguments;return e.apply(r,t).then((function(e){if(!r.localDescription||!r.localDescription.sdp)return e;const t=oN.parse(r.localDescription.sdp),n=[];if(t.media.forEach((function(e){hN.forEach((function(t){DA(e,t,(function(e){n.push(e)}))}))})),n.length){const t=oN.parse(e.sdp);let r=!1;t.media.forEach((function(e){n.forEach((function(t){DA(e,{codec:t.rtp.codec,rate:t.rtp.rate},(function(e){e.rtp.payload!==t.rtp.payload&&(e.rtp.payload=t.rtp.payload,r=!0)}))}))})),r&&(e=new i({type:e.type,sdp:oN.write(t)}))}return e}))}}(),function(){const e=r.createOffer;r.createOffer=function(t){const i=arguments;return t&&t.offerToReceiveVideo>1&&(t.offerToReceiveVideo=1),e.apply(r,i)}}(),r.getSenders&&r.addTrack&&r.removeTrack||(r.getSenders=function(){return t.slice()},r.addTrack=function(e,i){if(!e||!i)throw new Error("both media track and stream need to be provided");r.getLocalStreams().some((function(e){return e.id===i.id}))||r.addStream(i);let n=t.find((function(t){return t.track.id===e.id}));return n||(n=new a(e,i),t.push(n)),n},r.removeTrack=function(e){r.getLocalStreams().filter((function(t){return t.id===e._stream.id})).forEach((function(e){r.removeStream(e)})),nt(t,(t=>t===e))}),r}var gN=e=>pN.bind(null,e),mN=class{constructor(e){const t=e.configProvider.config.useSdpCapabilitiesLegacySession,i=e.configProvider.config.noRequiredCodecsWorkaround;this.RTCRtpReceiver=sN(e,t,i),this.SdpTransform=YO,this.RTCPeerConnection=gN(this.RTCRtpReceiver),this.RTCSessionDescription=uN()}};function fN(){function e(){throw new Error("unsupported platform")}this.SdpTransform=e,this.RTCPeerConnection=e,this.RTCSessionDescription=e,this.RTCRtpReceiver=e}var vN=e=>void 0!==Ug.window.webkitRTCPeerConnection?new mN(e):new fN,SN=class{constructor(e,t,i,n){this.logger=e,this.configProvider=t,this.activeSpeakerManager=i,this.contributingSourcesProvider=n,this.lastSources=[],this.poll=()=>{const e=this.contributingSourcesProvider.getContributingSources();if(!e)return this.logger.safe.info("Contributing sources are not supported on this client"),void this.dispose();this.activeSpeakerManager.onContributingSourcesChanged(e.filter((e=>{const t=this.lastSources.find((t=>t.source===e.source));return!t||t.timestamp!==e.timestamp})).map((e=>e.source))),this.updateLastSources(e),this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)},this.contributingSourcesProvider=n,this.logger.safe.info("Polling started"),this.timer=window.setTimeout(this.poll,this.configProvider.config.webrtcContributingSourcesPollingInterval)}dispose(){this.timer&&(window.clearTimeout(this.timer),this.timer=void 0),this.contributingSourcesProvider=void 0,this.logger.safe.info("Polling stopped")}updateLastSources(e){this.lastSources=e.map((e=>({source:e.source,timestamp:e.timestamp})))}},yN=class{constructor(e,t){this.logger=e,this.peerConnection=t}getContributingSources(){try{if(!this.peerConnection?.getReceivers)return;const e=this.peerConnection.getReceivers().find((e=>"audio"===e.track.kind));return e?e.getContributingSources?.():[]}catch(e){return void this.logger.safe.error("Failed to get contributing sources",e)}}},CN=g,_N=[2812,4218,8437,16875,33750,67500,108e3,135e3,198e3,244800,27e4,352500,52e4],EN=class{constructor(e,t,i,n){this.initialMaxFS=e,this.initialMaxFPS=t,this.isAv1Allowed=i,this.h264SubscribeProfile=n,this.maxFS=e,this.maxFPS=t}setMaxFS(e,t){return!(this.maxFS===e||(this.maxFS=e,!t)||(t(this),0))}getMaxFS(){return this.maxFS}getMaxFPS(){return this.maxFPS}getMaxMBPS(){return this.calculateMbps(this.maxFS,this.maxFPS)}calculateMbps(e,t){return gt(_N,e*t/100,!0)}resetToInitial(){this.maxFS=this.initialMaxFS,this.maxFPS=this.initialMaxFPS}fmtpParams(){return{"max-fs":this.getMaxFS(),"max-mbps":this.getMaxMBPS(),"max-fps":this.getMaxFPS()}}buildFmtp(){const e=[];let t=this.fmtpParams();return this.h264SubscribeProfile&&(t["profile-level-id"]=this.h264SubscribeProfile),e.push(t),this.isAv1Allowed&&(t=this.fmtpParams(),t.codec="AV1",e.push(t)),e}},TN=class e{constructor(e,t){this.entity=e,this.configProvider=t}static getVideoCababilities(e,t,i){if(e!==Qe.MEDIA_TYPE.video)return null;let n,r;t===Qe.MODALITY.sharing?(n=i.config.webrtcScreensharingCapabilityMaxFS,r=i.config.webrtcScreensharingCapabilityMaxFPS):(n=i.config.webrtcVideoCapabilityMaxFS,r=i.config.webrtcVideoCapabilityMaxFPS,i.config.useMultiviewLimitsOnInitialRequest&&i.config.multiviewResolutionLimits[1]&&(n=Zw.Send.getResolutionForHeight(i.config.multiviewResolutionLimits[1]).fs));const a=i.config.isAv1Allowed&&t===Qe.MODALITY.sharing;return new EN(n,r,a,i.config.h264SubscribeProfile)}static create(t,i,n){const r=function(e){switch(e){case Qe.MODALITY.audio:return Qe.MEDIA_TYPE.audio;case Qe.MODALITY.video:case Qe.MODALITY.sharing:return Qe.MEDIA_TYPE.video;case Qe.MODALITY.data:return Qe.MEDIA_TYPE.data;default:return null}}(i),a=new e({modality:i,mid:n,mtype:r,extensions:{}},t);return a.localRecvCapabilities=e.getVideoCababilities(r,i,t),a}clone(){const t=new e((0,CN.cloneDeep)(this.entity),this.configProvider);return t.setSimulcastContext(this.simulcastContext),t.localRecvCapabilities=this.localRecvCapabilities,t.remoteRecvCapabilities=this.remoteRecvCapabilities,t}getModality(){return this.entity.modality}getType(){return this.entity.mtype}getMid(){return this.entity.mid}disable(){this.entity.mid=null}update(t,i){this.entity.modality!==t&&(this.localRecvCapabilities=e.getVideoCababilities(this.entity.mtype,t,this.configProvider)),this.entity.modality=t,this.entity.mid=i,this.isEnabled()&&this.setExtension("rollback",!1)}isDisabled(){return!this.entity.mid}isEnabled(){return!!this.entity.mid}getLocalRecvCapabilities(){return this.localRecvCapabilities}getRemoteRecvCapabilities(){return{sourceId:this.getXSourceStreamId(),capabilities:this.remoteRecvCapabilities?[this.remoteRecvCapabilities]:[]}}setRemoteRecvCapabilities(e){this.remoteRecvCapabilities=e}getRemoteStreamId(){return this.entity.remoteStreamId}setRemoteStreamId(e){this.entity.remoteStreamId=e}setRemoteSsrc(e){this.entity.remoteSsrc=e}getRemoteSsrc(){return this.entity.remoteSsrc}setLocalSsrc(e){this.entity.localSsrc=e}getLocalSsrc(){return this.entity.localSsrc}getRemoteTrackId(){return this.entity.remoteTrackId}setRemoteTrackId(e){this.entity.remoteTrackId=e}getXSourceStreamId(){return this.entity.xSourceStreamId}setXSourceStreamId(e){this.entity.xSourceStreamId=e}setLocalTrackId(e){this.entity.localTrackId=e}getLocalTrackId(){return this.entity.localTrackId}setSubStreamIndex(e){this.entity.subStreamIndex=e}getSubstreamIndex(){return this.entity.subStreamIndex}getExtension(e){return this.entity.extensions[e]}setExtension(e,t){this.entity.extensions[e]=t}getRtpHeaderExtensions(){return this.entity.rtpExt}setRtpHeaderExtensions(e){this.entity.rtpExt=e}setSimulcastContext(e){this.simulcastContext=e}getSimulcastContext(){return this.simulcastContext}serialize(){return lt(this.entity)}},bN=class{constructor(e){this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.localSsrcs=new Map,this.ssrcGenerator=new jk,this.logger=e.logger.createChild("MM"),this.configProvider=e.configProvider,this.numVideoChannels=e.numVideoChannels}fromOffer(e,t){e.media.forEach((e=>{if(e.type===Qe.MEDIA_TYPE.audio)Qe.MODALITY.audio in t&&this.addMediaEntity(Qe.MODALITY.audio);else if(e.type===Qe.MEDIA_TYPE.video){if(Qe.MODALITY.video in t)for(let e=0;e<this.numVideoChannels;e++)this.addMediaEntity(Qe.MODALITY.video);Qe.MODALITY.sharing in t&&this.addMediaEntity(Qe.MODALITY.sharing)}else e.type===Qe.MEDIA_TYPE.data&&Qe.MODALITY.data in t&&this.addMediaEntity(Qe.MODALITY.data)}))}fromRemote(e,t){e.media.forEach(((e,i)=>{const n=HA(e);if(zA(e)||!(n in t))this.mediaEntities[i]?this.mediaEntities[i].disable():this.addDisabledMediaEntity(n),this.mediaEntities[i].setRemoteStreamId(null),this.mediaEntities[i].setRemoteTrackId(null);else{if(this.mediaEntities[i]?this.mediaEntities[i].update(n,e.mid||this.generateMid(i)):this.addMediaEntity(n,e.mid||this.generateMid(i)),e.msid)this.mediaEntities[i].setRemoteStreamId(e.msid.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(e.msid.split(" ")[1]);else if(e.ssrcs){const t=e.ssrcs.find((e=>"msid"===e.attribute));t?(this.mediaEntities[i].setRemoteStreamId(t.value.split(" ")[0]),this.mediaEntities[i].setRemoteTrackId(t.value.split(" ")[1])):this.logger.safe.warn(`No ssrc msid for media of type ${e.type} with mid ${e.mid}`)}const t=e.xSourceStreamId||this.generateSourceStreamId(i);this.mediaEntities[i].setXSourceStreamId(t)}}))}isEmpty(){return 0===this.mediaEntities.length}addMediaEntity(e,t){this.createMediaEntity(e,t||this.generateMid(this.mediaEntities.length))}addDisabledMediaEntity(e){this.createMediaEntity(e)}getMediaEntities(){return this.mediaEntities}createMediaEntity(e,t){const i=TN.create(this.configProvider,e,t);return this.mediaEntities.push(i),i}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[]}syncModalities(e,t,i){this.disableModalities(t),i||(this.enableModalities(t),this.addModalities(t))}enableModalities(e){this.mediaEntities.forEach(((t,i)=>{t.getModality()in e&&t.isDisabled()&&t.update(t.getModality(),this.generateMid(i))}))}disableModalities(e){this.mediaEntities.forEach((t=>{t.getModality()in e||t.disable()}))}setRollbackUpdateHandler(e){}addModalities(e){const t={};this.mediaEntities.map((e=>e.getModality())).forEach((e=>{t[e]=!0}));for(const i in e)i in t||this.addMediaEntity(i)}setLocalTracksInfo(e){this.mediaTracks=e,this.updateLocalSsrc(this.mediaTracks)}getLocalTracksInfo(){return this.mediaTracks}getLocalSsrcs(){return this.localSsrcs}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?t.setLocalTrackId(e.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)})))}updateMediaEntitiesWithActivityState(e,t){}backup(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[]}rollback(){this.mediaEntities=this.mediaEntitiesBackup}generateSourceStreamId(e){return e+10}generateMid(e){return`media_${e}`}updateLocalSsrc(e){e.forEach((e=>{if(!this.localSsrcs.get(e.modality)){const t=this.ssrcGenerator.nextVideoStreamSsrc().min;this.logger.safe.debug(`Ssrc updated for modality: ${e.modality}: ${t}`),this.localSsrcs.set(e.modality,t)}}))}},IN=f(ye()),wN=class{constructor(e,t,i,n,r){this.logger=e,this.RtcDescType=t,this.sessionDescription=i,this.negotiationQueue=n,this.mediaManager=r}dispose(){this.peerConnection=null}configure(e){this.peerConnection=e}renegotiateNow(){return this.renegotiate(null,!0)}renegotiate(e,t=!1,i="local"){if(!this.peerConnection)throw new Error("trying to renegotiate during empty peerConnection");const n="local"===i?this.createNegotiationTaskForHaveLocalOffer(e):this.createNegotiationTaskForHaveRemoteOffer(e);return t?(this.logger.safe.info(`forced ${i} renegotiation starting`),Promise.resolve(n())):this.negotiationQueue.add(n)}normalizeRemoteSdpSDES(e,t){if(t.media[0].crypto)e.media.forEach((e=>{delete e.fingerprint,delete e.setup,e.crypto=e.crypto.filter((e=>t.media[0].crypto.some((t=>t.id===e.id)))).slice(0,1)})),e.fingerprint&&delete e.fingerprint;else{const t=this.mediaManager.getMediaEntities().find((e=>void 0!==e.getExtension("setup")));e.media.forEach((e=>{const i=t?.getExtension("setup")||"actpass";"actpass"===e.setup&&(e.setup="active"===i?"passive":"active")}))}}normalizeRemoteSdpExtensions(e,t){e.media.forEach(((e,i)=>{const n=new Set(t.media[i].ext?.map((e=>e.value))||[]);e.ext=e.ext?.filter((e=>n.has(e.value)))}))}throwIfNoPeerConnection(){if(!this.peerConnection)throw this.logger.safe.warn("no peer connection present"),new Error("trying to renegotiate during empty peerConnection")}createNegotiationTaskForHaveLocalOffer(e){return()=>{let t=this.peerConnection.remoteDescription.sdp;const i=this.peerConnection.localDescription.sdp;this.logger.safe.info(`local renegotiation starting remoteSdp=${!!t} localSdp=${!!i}`);const n=IN.parse(t),r=IN.parse(i);this.normalizeRemoteSdpSDES(n,r),this.normalizeRemoteSdpExtensions(n,r),t=IN.write(n);let a=new this.RtcDescType({sdp:t,type:"answer"});return e&&e.forEach((e=>{a=e.modifyDescriptor(a)})),Promise.resolve().then((()=>(this.logger.safe.info("creating offer"),this.throwIfNoPeerConnection(),this.peerConnection.createOffer()))).then((e=>{this.throwIfNoPeerConnection();const t=this.sessionDescription.createLocalOffer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"offer"});return this.logger.safe.info("setting local description"),this.logger.unsafe.debug(`local description, sdp: ${i.sdp}`),this.peerConnection.setLocalDescription(i)})).then((()=>(this.throwIfNoPeerConnection(),this.logger.safe.info("setting remote description"),this.logger.unsafe.debug(`remote description, sdp: ${a.sdp}`),this.peerConnection.setRemoteDescription(a)))).then((e=>(this.logger.safe.debug("local renegotiation done"),e))).catch((e=>{throw this.logger.safe.error("local renegotiation failed: ",e.toString()),e}))}}createNegotiationTaskForHaveRemoteOffer(e){return this.logger.safe.info("createNegotiationTaskForRemote"),()=>(this.logger.safe.info("proceed with setting local sdp start"),Promise.resolve().then((()=>(this.logger.safe.info("creating answer"),this.throwIfNoPeerConnection(),this.peerConnection.createAnswer()))).then((e=>{this.logger.safe.info("applying answer"),this.throwIfNoPeerConnection();const t=this.sessionDescription.createLocalAnswer(e.sdp),i=new this.RtcDescType({sdp:t.toLocal(),type:"answer"});return this.logger.safe.info("setting [answer] local description"),this.logger.unsafe.debug(`[answer] local description, sdp: ${i.sdp}`),this.peerConnection.setLocalDescription(i)})).then((e=>(this.logger.safe.info("local answer for renegotiation is done"),e))).catch((e=>{throw this.logger.safe.error("local answer for renegotiation failed: ",e.toString()),e})))}},RN=15e3,AN=class{constructor(e,t,i){this.settings=e,this.listener=t,this.logger=i,this.lastSendBW=0,this.coolingDown=!1,this.cooldownTimer=null,this.cooldownEnd=0,this.active=!1,this.maxResolution=this.settings.maxResolution,this.settings.scalingEnabled?this.active=!0:this.logger.safe.info("Resolution management disabled: no resolution management for 1x1 calls")}dispose(){this.currentResolution=null,this.pendingResolution=null,this.maxResolution=null,this.listener=null,this.active=!1,clearTimeout(this.cooldownTimer),this.cooldownTimer=null,this.listener=null}setMaxResolution(e){const t=Zw.Send.getResolutionByFs(e);t!==this.maxResolution&&(this.logger.safe.info(`Setting max resolution: ${t}`),this.maxResolution=t,this.lastSendBW&&this.processEstimatedBandwidth(this.lastSendBW))}updateEstimatedSendBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Send BW: ${e}`),this.processEstimatedBandwidth(e))}resetCurrentResolution(){this.currentResolution=null}getCurrentResolution(){return this.currentResolution?.fs}setCurrentResolution(e){this.currentResolution=e}applyRes(e){this.pendingResolution=e,this.coolingDown&&(!this.currentResolution||e.fs>this.currentResolution.fs)||(this.coolingDown=!0,this.logger.safe.info(`Changing resolution to ${e}`),this.listener&&this.listener.onResolutionChanged(e.fs).then((t=>{t?(e===this.pendingResolution&&(this.pendingResolution=null),this.coolingDown&&!this.currentResolution&&(this.coolingDown=!1),this.currentResolution=e,this.cooldown()):(this.logger.safe.info("Unable to apply resolution at the moment"),this.cooldown(5e3))})).catch((e=>{this.logger.safe.error(`Error while applying new resolution: ${JSON.stringify(e)}`),this.pendingResolution=null})))}cooldown(e=RN){!this.active||this.coolingDown&&this.cooldownEnd-Date.now()>RN||(this.cooldownTimer&&clearTimeout(this.cooldownTimer),this.coolingDown=!0,this.cooldownEnd=Date.now()+RN,this.cooldownTimer=setTimeout((()=>{this.logger.safe.debug("Resolution changer cooled down"),this.coolingDown=!1,this.cooldownTimer=null,this.pendingResolution?this.proposeResolution(this.pendingResolution):this.processEstimatedBandwidth(this.lastSendBW)}),e))}proposeResolution(e){let t=e;this.maxResolution&&this.maxResolution.fs<t.fs&&(t=this.maxResolution),this.currentResolution&&t.fs===this.currentResolution.fs||this.applyRes(t)}processEstimatedBandwidth(e){const{lowRes:t,highRes:i}=Zw.Send.getResolutionForBitrate(e),n=e<this.lastSendBW?i:t;e<this.lastSendBW&&n&&this.currentResolution&&this.currentResolution.fs<n.fs||(n&&this.proposeResolution(n),this.lastSendBW=e)}};function PN(e,t){const i=1e3*((t.mediaConfig.maxBandwidthInKbps||Math.floor(Number.MAX_SAFE_INTEGER/1e3))-(t.config.audioBandwidthInKbps||0)),n=e.transport?.selectedCandidatePair?.availableOutgoingBitrate??0;return Math.min(i,n)}var MN=class extends qe{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.lastReportedAgo=1/0,this._forceUpdate=!1}forceUpdate(){this._forceUpdate=!0}onBandwidthChanged(e){this._forceUpdate?this.updateBandwidth(e,"forceUpdate"):this.processEstimatedBandwidth(e)}processEstimatedBandwidth(e){if(this.lastReportedAgo++,!e||this.bandwidth===e)return;const t=this.configProvider.config.webrtcSendBandwidthIgnoredUpdateLimit,i=this.configProvider.config.webrtcSendBandwidthThreshold,n=this.lastReportedAgo===1/0,r=!t&&!i,a=t&&this.lastReportedAgo>=t,s=i&&Math.abs((e-this.bandwidth)/this.bandwidth)>=i;if(n||r||a||s){const t=+n|+r<<1|+a<<2|+s<<3,i=this.getUpdateReason(t);this.updateBandwidth(e,i)}}updateBandwidth(e,t){this.bandwidth=e,this.logger.safe.debug(`Updating send bandwidth: ${this.bandwidth}, reason: ${t}`),this.notifySendBandwidthChanged()}notifySendBandwidthChanged(){this._forceUpdate=!1,this.event("onSendBandwidthChanged").raise(this.bandwidth),this.lastReportedAgo=0}getUpdateReason(e){return 1&e?"firstReport":2&e?"throttlingDisabled":4&e?"noReportsForTooLong":8&e?"bigMovement":"none"}},kN=class{constructor(e,t,i,n,r,a,s){this.listener=e,this.statisticsGatherer=t,this.diagnostics=i,this.logger=n,this.configProvider=r,this.isSimulcastEnabled=s,this.serialQueue=new Hw(this.logger),this.modality=Qe.MODALITY.video;const o=a.maxResolution?{maxFs:a.maxResolution.fs}:null;this.validator=new oR(this.logger.createChild("CapsValidator"),o),this.resolutionManager=new AN(a,this,this.logger.createChild("rm")),this.statisticsGatherer.on("onStatisticsChanged",(e=>this.onStatisticsChanged(e))),this.statisticsGatherer.on("onDiagnosticUpdated",(e=>this.onDiagnosticUpdated(e)))}async setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.causeId=e;const n=this.validator.ensureValidity(t[0]);this.streamSenderParams={...t[0],...n},this.resolutionManager.setMaxResolution(this.streamSenderParams.maxFs),this.configProvider.mediaConfig.simulcastSessionEnabled&&await this.applyCapabilities(this.getParamsToApply())}resetCurrentResolution(){this.resolutionManager.resetCurrentResolution()}getCurrentResolution(){return this.resolutionManager.getCurrentResolution()}setCurrentResolution(e){this.resolutionManager.setCurrentResolution(e)}async onResolutionChanged(e){return this.applyCapabilities(this.getParamsToApply(e))}dispose(){this.resolutionManager.dispose(),this.resolutionManager=null}async applyCapabilities(e){return e?this.lastAppliedSenderParams===e?(this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}`),!0):(this.logger.safe.info(`Capabilities to apply: ${JSON.stringify(e)}`),this.lastAppliedSenderParams=e,this.listener.onReceiveCapabilitiesChanged(this.modality,this.causeId,[e])):(this.logger.safe.error("Send capabilities are not set. Cannot apply constraints"),!1)}getParamsToApply(e){if(!this.streamSenderParams)return null;const t=e||this.resolutionManager.getCurrentResolution();if(!t||this.streamSenderParams.maxFs<=t)return this.streamSenderParams;const i=ot(this.streamSenderParams);return i.maxFs=t,i}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.resolutionManager.updateEstimatedSendBandwidth(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!e.video?.send?.length||!e.video.send[0])return;const t=PN(e.video.send[0],this.configProvider);this.resolutionManager.updateEstimatedSendBandwidth(t)}}};v([cA()],kN.prototype,"applyCapabilities",1);var DN=class{constructor(e,t,i,n,r){this.modality=e,this.listener=t,this.statisticsGatherer=i,this.diagnostics=n,this.isSimulcastEnabled=r}setMaxCapabilities(e,t){const i={modality:this.modality,causeId:e,capabilities:t,isSimulcastEnabled:this.isSimulcastEnabled};this.statisticsGatherer.onMaxCapabilitiesRequested(i),this.diagnostics?.onMaxCapabilitiesRequested(i),this.listener.onReceiveCapabilitiesChanged(this.modality,e,t)}dispose(){}resetCurrentResolution(){}getCurrentResolution(){return null}setCurrentResolution(e){}},ON=class{constructor(e,t,i,n,r,a){this.logger=e,this.settings=t,this.listener=i,this.statsGatherer=n,this.diagnostics=r,this.configProvider=a,this.mediaSourceModels=[],this.pendingCapabilities=new Map,this.statsGatherer.on("onDiagnosticUpdated",(e=>this.onDiagnosticUpdated(e))),this.statsGatherer.on("onStatisticsChanged",(e=>this.onStatisticsChanged(e)))}dispose(){this.mediaSourceModels.forEach((e=>{e.handler&&(e.handler.dispose(),e.handler=null)})),this.mediaSourceModels=null,this.sendBandwidthCalculator&&this.disableSendBandwidthCalculator()}updateRegisteredSources(e){this.logger.safe.info(`Local media params updated: ${JSON.stringify(e)}`);const t=[];this.mediaSourceModels.forEach((e=>t.push(e.sourceId)));const i=e.map((e=>e.sourceId)),n=vt(t,i);this.removeSourcesWithIds(n);const r=vt(i,t);this.addSourcesWithIds(r,e),this.settings.sendBandwidthNotificationsEnabled&&this.updateSendBandwidthCalculator()}setMaxCapabilities(e){for(const t of e){if(!t.capabilities.length)continue;if(!t.sourceId){this.logger.safe.info(`SourceId is not defined to apply recv capabilities: ${JSON.stringify(t)}`);continue}const e=this.getModelWithSourceId(t.sourceId);if(!e){this.logger.safe.info(`Model is not registered for sourceId: ${t.sourceId}`),this.configProvider.config.enableCachingFMTP&&this.pendingCapabilities.set(t.sourceId,t);continue}this.logger.safe.info(`Capabilities handler found for sourceId: ${t.sourceId}`);const i=this.getOrCreateHandlerForModel(e,t.isSimulcast);i?i.setMaxCapabilities(t.causeId,t.capabilities):this.logger.safe.info(`Handler is not found for sourceId: ${t.sourceId}`)}this.logger.safe.debug("Max capabilities application completed")}setPendingCapabilities(){if(!this.configProvider.config.enableCachingFMTP)return;this.logger.safe.info(`Apply pending capabilties for sources [${Array.from(this.pendingCapabilities.keys())}]`);const e=Array.from(this.pendingCapabilities.values());this.setMaxCapabilities(e),this.pendingCapabilities.clear()}clearPendingCapabilities(){this.pendingCapabilities.clear()}resetCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Qe.MODALITY.video));e?.handler&&e.handler.resetCurrentResolution()}getCurrentResolution(){const e=this.mediaSourceModels.find((e=>e.modality===Qe.MODALITY.video));return e?.handler?e.handler.getCurrentResolution():this.currentResolution?.fs}setCurrentResolution(e){const t=this.mediaSourceModels.find((e=>e.modality===Qe.MODALITY.video));t?.handler?t.handler.setCurrentResolution(e):this.currentResolution=e}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.sendBandwidthCalculator.onBandwidthChanged(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){if(this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation){if(!e.video?.send?.length||!e.video?.send[0])return;const t=PN(e.video.send[0],this.configProvider);this.sendBandwidthCalculator.onBandwidthChanged(t)}}getOrCreateHandlerForModel(e,t){return e.handler||(e.handler=this.getCapabilitiesHandler(e.modality,t)),e.handler}addSourcesWithIds(e,t){e.forEach((e=>{const i=t.find((t=>t.sourceId===e));this.registerSource(e,i.modality)}))}removeSourcesWithIds(e){e.forEach((e=>this.unregisterSource(e)))}registerSource(e,t){this.logger.safe.info(`SourceId ${e} registered with mediaType: ${t}`),this.mediaSourceModels.push({modality:t,sourceId:e})}unregisterSource(e){const t=this.mediaSourceModels.find((t=>t.sourceId===e));t?(t.handler&&t.handler.dispose(),this.mediaSourceModels.splice(this.mediaSourceModels.indexOf(t),1),this.logger.safe.info(`SourceId ${e} unregistered`)):this.logger.safe.info(`Model doesn't exist with sourceId ${e}`)}updateSendBandwidthCalculator(){this.mediaSourceModels.some((e=>[Qe.MODALITY.video,Qe.MODALITY.sharing].indexOf(e.modality)>-1))?this.enableSendBandwidthCalculator():this.disableSendBandwidthCalculator()}enableSendBandwidthCalculator(){this.sendBandwidthCalculator||(this.sendBandwidthCalculator=new MN(this.configProvider,this.logger.createChild("SendBwCalc")),this.sendBandwidthCalculatorSubscription=this.sendBandwidthCalculator.on("onSendBandwidthChanged",(e=>this.onSendBandwidthChanged(e))))}disableSendBandwidthCalculator(){this.sendBandwidthCalculatorSubscription&&(this.sendBandwidthCalculatorSubscription.dispose(),this.sendBandwidthCalculatorSubscription=null),this.sendBandwidthCalculator&&(this.sendBandwidthCalculator.dispose(),this.sendBandwidthCalculator=null)}getModelWithSourceId(e){return this.mediaSourceModels.find((t=>t.sourceId===e))}getCapabilitiesHandler(e,t){if(e===Qe.MODALITY.audio)return null;if(e===Qe.MODALITY.video&&!t&&this.settings.customBwEstimationEnabled){const e=new kN(this.listener,this.statsGatherer,this.diagnostics,this.logger.createChild("ach"),this.configProvider,this.settings,t);return this.currentResolution&&e.setCurrentResolution(this.currentResolution),e}return new DN(e,this.listener,this.statsGatherer,this.diagnostics,t)}onSendBandwidthChanged(e){return this.listener.onSendBandwidthChanged(e).catch((e=>{this.logger.safe.error("Error while reporting send bandwidth change",e),this.sendBandwidthCalculator.forceUpdate()}))}},NN=class extends qe{constructor(e,t,i,n,r,a){super(e),this.logger=e,this.multiParty=t,this.configProvider=i,this.mediaManager=n,this.statsGatherer=r,this.diagnostics=a,this.rendererResolutions=new Map,this.rendererResolutionsApplied=new Map,this.rendererResolutionMax=new Map,this.hasPendingLimitResolutionUpdate=!1}addRenderer(e){this.rendererResolutions.set(e,{width:0,height:0}),e.on("onRendererSizeChanged",((e,t)=>{this.onRendererSizeChanged(e,t)})),this.scheduleUpdateLimitedResolutions()}removeRenderer(e){this.rendererResolutions.delete(e),this.rendererResolutionsApplied.delete(e),this.rendererResolutionMax.delete(e),this.scheduleUpdateLimitedResolutions()}clearRenderers(){this.rendererResolutions.clear(),this.rendererResolutionsApplied.clear(),this.rendererResolutionMax.clear()}getMaxAllowedVideoFS(){const e=this.getMaxHeightFromConfig(this.renderersCount);return this.getMaxFSForHeight(e)}limitResolutionOnPoorPerformance(e){const t=this.getRendererByMsi(e);if(!t)return;const i=t.resolution.height>t.resolution.width,n=Zw.Recv.getNextLowerResolution(t.resolution.width,t.resolution.height);if(!n)return void this.logger.safe.info("Poor perf. Lowest resolution reached. Not limiting resolution");const r={width:i?n.height:n.width,height:i?n.width:n.height};this.rendererResolutionMax.set(t.renderer,r),this.diagnostics?.registerResolutionChanageRequest({ts:Date.now(),msi:t.renderer.getMsi(),res:r}),this.logger.safe.info(`Poor perf. Limiting resolution for renderer msi: ${t.renderer.getMsi()} from ${t.resolution.height}p to ${r.height}p`),this.onRendererSizeChanged(t.renderer,r)}get renderersCount(){return this.rendererResolutions.size}getMaxFSForHeight(e){return this.limitMaxFS(Zw.Recv.getResolutionForHeight(e).fs)}getRendererByMsi(e){for(const[t,i]of this.rendererResolutions.entries())if(t.getMsi()===e)return{renderer:t,resolution:i};return null}applyRendererResolution(e,t){this.setMaxFSCapabilities(e,t),this.rendererResolutionsApplied.set(e,t);const i=e.getMediaStream()&&e.getMediaStream().getVideoTracks();i?.[0]&&this.statsGatherer.setPreferredResolution(i[0].id,t,e.getModality())}onRendererSizeChanged(e,t){this.rendererResolutions.set(e,t),this.scheduleUpdateLimitedResolutions()}scheduleUpdateLimitedResolutions(){this.hasPendingLimitResolutionUpdate||(this.hasPendingLimitResolutionUpdate=!0,window.setTimeout((()=>{this.hasPendingLimitResolutionUpdate=!1;const e=this.groupMaxRenderersResolutionsByMsi();this.logger.safe.info(`Updating resolution limits: renderers count ${this.renderersCount}`),this.spotlightedRenderer=this.findSpotlightedRenderer(),this.spotlightedRenderer&&this.logger.safe.info(`Spotlighted renderer: ${this.spotlightedRenderer.getMsi()}`);for(const[t,i]of this.rendererResolutions.entries()){if(!i.height)continue;const n=e.get(t.getMsi()),r=this.limitRendererResolution(t,n||i),a=this.rendererResolutionsApplied.get(t);(!a||a.height!==r.height||a.width!==r.width)&&this.applyRendererResolution(t,r)}}),this.configProvider.config.multiviewResolutionLimitUpdateThrottleDelay))}findSpotlightedRenderer(){if(1===this.renderersCount||!this.configProvider.config.isSpotlightEnabled)return;let e,t=0,i=0;for(const[n,r]of this.rendererResolutions.entries()){if(!r.height)continue;i++;const a=Zw.Recv.getMaxFS(r.width,r.height);a>t?(e=n,t=a):a===t&&(e=void 0)}return i<=1?void 0:e}getMaxHeightFromConfig(e,t=!1){return t?this.configProvider.config.maxSpotlightResolution:this.configProvider.config.multiviewResolutionLimits[`${e}`]||this.configProvider.config.multiviewResolutionLimits.more}getMaxHeight(e){const t=this.spotlightedRenderer?.getMsi()===e.getMsi();let i=this.getMaxHeightFromConfig(this.renderersCount,t);const n=this.rendererResolutionMax.get(e);return n&&(i=Math.min(i,Math.min(n.height,n.width))),i}limitRendererResolution(e,t){const i=this.getMaxHeight(e);if(!i)return t;if(t.height>t.width&&t.width>i){const e=i/t.width;return{height:Math.ceil(t.height*e),width:i,limited:!0}}if(t.width>t.height&&t.height>i){const e=i/t.height;return{height:i,width:Math.ceil(t.width*e),limited:!0}}return t}setMaxFSCapabilities(e,t){const i=e.getMediaStream();if(!i)return void this.logger.safe.warn("renderer has no stream attached");const n=this.mediaManager.getMediaEntityByRemoteStreamId(i.id);if(!n?.getLocalRecvCapabilities())return void this.logger.safe.warn(`no capabilities for provided modality: ${e.getModality()}`);const r=t.limited?this.getMaxFSForHeight(t.height):this.getMaxFS(t.width,t.height),a=n.getLocalRecvCapabilities();a.setMaxFS(r,(()=>{if(this.logger.safe.info(`updated max-fs video capability to ${r} for renderer msi: ${e.getMsi()}`),this.multiParty&&this.configProvider.config.webrtcMultiPartyRecvVideoSignaling){const t=e.getMsi(),n=a.buildFmtp();this.event("onSourceRequestRequired").raise(i.id,t,n)}else this.event("onNegotiationRequired").raise()}))}getMaxFS(e,t){return this.limitMaxFS(Zw.Recv.getMaxFS(e,t))}limitMaxFS(e){return this.multiParty?Math.min(e,this.configProvider.config.webrtcMultiPartyRecvVideoMaxFS):Math.min(e,this.configProvider.config.webrtcRecvVideoMaxFS)}groupMaxRenderersResolutionsByMsi(){const e=new Map;return this.rendererResolutions.forEach(((t,i)=>{const n=i.getMsi(),r=e.get(n);(!r||t.width>r.width&&t.height>r.height)&&e.set(n,t)})),e}},LN=class extends qe{constructor(e,t){super(),this.configProvider=e,this.getModality=t,this.isRendering=!1,this.currentFreezeDuration=0,this.mediaStarted=!1,this.lastBytesRecv=0,this.currentLowBitrateDuration=0}captureRawStatistics(e){const t=e.googFrameRateDecoded,i=e.googFrameRateReceived,n=e.bytesReceived;void 0!==n&&this.getModality()!==Qe.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateBitrate(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Qe.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}updateRenderingTracker(e){const t=e.extensions.frameRateDecoded||0,i=e.extensions.frameRateReceived||0,n=e.extensions.bitrate;void 0!==n&&this.getModality()!==Qe.MODALITY.sharing&&this.configProvider.config.isBytesRecvUsedInIsRenderingCalculation&&this.calculateLowBitrateDuration(n,t),t>0&&(this.mediaStarted=!0),0===t||0===i?this.currentFreezeDuration+=Qe.TIME_INTERVAL.SEC_1:t>0&&(void 0===i||i>0)&&(this.currentFreezeDuration=0);const r=this.configProvider.config.notRenderingTimeInterval[this.getModality()];this.setIsRendering(r)}calculateLowBitrateDuration(e,t){e/1e3<this.configProvider.config.notRenderingLowBitrateThreshold&&t<this.configProvider.config.notRenderingLowFramerateThreshold?this.currentLowBitrateDuration++:this.currentLowBitrateDuration=0}calculateBitrate(e,t){const i=8*(e-this.lastBytesRecv);this.lastBytesRecv=e,this.calculateLowBitrateDuration(i,t)}setIsRendering(e){const t=this.currentFreezeDuration<e&&this.currentLowBitrateDuration<e&&this.mediaStarted;t!==this.isRendering&&(this.isRendering=t,this.event("onIsRenderingChanged").raise(this.isRendering))}},xN=class extends qe{constructor(e,t,i){super(),this.videoElement=e,this.configProvider=t,this.getTimeToFirstFrame=i,this.prevCurrentTime=0,this.prevDecodedFrameCount=0,this.prevTimestamp=Date.now(),this.currentFreezeDuration=0,this.freezeDurationTimer=window.setInterval((()=>{this.calcFreezeDurationMs()}),this.configProvider.config.freezeIntervalFrequency)}calcFreezeDurationMs(){const e=this.videoElement.currentTime,t=e===this.prevCurrentTime,i=this.videoElement.webkitDecodedFrameCount,n=void 0===i||i===this.prevDecodedFrameCount;if(this.prevCurrentTime=e,this.prevDecodedFrameCount=i,-1!==this.getTimeToFirstFrame())if(t&&n){const e=Date.now();this.currentFreezeDuration+=e-this.prevTimestamp,this.prevTimestamp=e}else{if(this.currentFreezeDuration>this.configProvider.config.freezeMinDuration){const e=this.calcFreeze();this.event("onFreezeEnded").raise(e)}this.currentFreezeDuration=0}this.prevTimestamp=Date.now()}getEndOfTheFreeze(){let e=0;return this.currentFreezeDuration>0&&(e=this.calcFreeze(),this.currentFreezeDuration=0),e}dispose(){const e=this.getEndOfTheFreeze();this.event("onFreezeEnded").raise(e),clearInterval(this.freezeDurationTimer)}calcFreeze(){const e=Date.now()-this.prevTimestamp;return this.currentFreezeDuration+e}},FN=class extends Kw{constructor(e,t,i,n,r,a){super(r,e.createChild("remote"),t),this.diagnostics=i,this.subscriptionManager=n,this.sessionDiagnostics=a,this.disposed=!1,this.currentIsRendering=!1,this.startTimeTTFF=0,this.timeToFirstFrame=-1,this.isTimeToFirstFrameReported=!1,this.configProvider.config.freezeIntervalFrequency&&(this.freezeTracker=new xN(this.getVideoElement(),this.configProvider,(()=>this.timeToFirstFrame)),this.freezeTracker.on("onFreezeEnded",(e=>{this.diagnostics?.addFreezeDuration(e),this.event("onFreezeEnded").raise(e)}))),this.configProvider.config.isRenderingBasedOnRawStatistics&&(this.isRenderingTracker=new LN(this.configProvider,this.getModality.bind(this)),this.isRenderingChangedSubscription=this.isRenderingTracker.on("onIsRenderingChanged",(e=>{this.setIsRendering(e)}))),this.overlayStats=new jw(this.configProvider.config.showStatsInCall,r,this)}getEndOfTheFreeze(){return this.freezeTracker?.getEndOfTheFreeze()}resetTimeToFirstFrameFlag(){this.isTimeToFirstFrameReported=!1}setIsRendering(e){this.currentIsRendering!==e&&(this.currentIsRendering=e,this.captureIsRenderingEvent(e))}updateStatsOverlay(e){this.overlayStats.setStats(e)}updateIsRenderingTracker(e){this.isRenderingTracker?.updateRenderingTracker(e)}subscribeVideoAsync(e,t){return this.timeToFirstFrameSinceSubscriptionStart=Date.now(),new Promise(((i,n)=>{this.modality=t?Qe.MODALITY.sharing:Qe.MODALITY.video,this.diagnostics&&(this.diagnostics.msi=e,this.diagnostics.modality=this.modality),this.trackElementSizeChange(),this.unsubscribe(),this.sessionDiagnostics&&this.modality===Qe.MODALITY.video&&(this.on("onVideoSizeChanged",((t,i)=>{if(this.sessionDiagnostics.registerResolutionChanageEvent({ts:Date.now(),msi:e,res:{width:t,height:i}}),!this.isTimeToFirstFrameReported){if(-1===this.timeToFirstFrame){const e=Date.now();this.timeToFirstFrame=e-this.startTimeTTFF,this.timeToFirstFrameSinceSubscriptionStart=Date.now()-this.timeToFirstFrameSinceSubscriptionStart}const e=this.getTrackId();e&&(this.diagnostics.timeToFirstFrameSinceSubscriptionStart=this.timeToFirstFrameSinceSubscriptionStart,this.diagnostics.timeToFirstFrame=this.timeToFirstFrame,this.sizeTracker?.triggerVideoElementSizeChange(),this.event("onVideoStarted").raise(this.timeToFirstFrame,this.timeToFirstFrameSinceSubscriptionStart,e),this.isTimeToFirstFrameReported=!0)}})),this.on("onVideoRendererStateChanged",(e=>{this.diagnostics.addStateChange(e)})));const r=this.subscriptionManager.subscribeVideo(this.modality,e);this.subscription=r,this.logger.safe.info(`subscribing renderer to type: ${r.modality} msi: ${r.msi}`),r.setOnMediaStreamChangedHandler((e=>{const t=this.getMediaStream();this.attachMediaStream(e),e&&(this.startTimeTTFF=Date.now());const n=this.getTrackId();n&&this.diagnostics&&(this.diagnostics.trackId=n),this.logger.safe.info(`subscribed renderer to type: ${r.modality} msi: ${r.msi} on stream #${e?e.id:"none"}`),e&&t!==e&&this.sizeTracker?.triggerVideoElementSizeChange(),i()})),r.setOnErrorHandler((t=>{this.logger.safe.error(`failed to subscribe renderer ${Be(t)}`),"webRtcSession cleanup"===JSON.stringify(t)&&(this.logger.safe.info(`Retry to subscribe to video stream with msi: ${e}. Previous session was cleaned up`),this.subscriptionManager.streamChangedByMsi(e),i()),n(t)}))}))}dispose(){this.disposed?this.logger.safe.warn("renderer already disposed"):(this.disposed=!0,this.logger.safe.info("disposing"),this.unsubscribe(),this.captureIsRenderingEvent(!1),this.freezeTracker?.dispose(),this.isRenderingChangedSubscription?.dispose(),this.overlayStats.dispose(),this.diagnostics?.dispose(),this.event("onRendererDisposed").raise(this),super.dispose())}getModality(){return this.modality}getMsi(){return this.subscription?.msi??zk.SourceNone}getLocalMsi(){return this.subscription?.localMsi}getCurrentResolution(){return this.resolution??{width:0,height:0}}unsubscribeNow(){this.subscription?.unsubscribe(),this.subscription=null}trackElementSizeChange(){const e=this.modality===Qe.MODALITY.sharing,t=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMin:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMin,i=e?this.configProvider.config.webrtcScreensharingCapabilityCheckIntervalMax:this.configProvider.config.webrtcVideoCapabilityCheckIntervalMax;t&&i?(this.sizeTracker=new Xw(this.getVideoElement(),t,i,this.configProvider.config.enableDevicePixelRatio),this.sizeTracker.changed((()=>this.onSizeTrackerChanged()))):this.logger.safe.info("skipping video size tracking")}onSizeTrackerChanged(){this.resolution={width:this.sizeTracker.width,height:this.sizeTracker.height},this.logger.safe.info(`video renderer size changed to ${this.resolution.width}x${this.resolution.height}`),this.diagnostics&&(this.diagnostics.rendererSize=this.resolution),this.event("onRendererSizeChanged").raise(this,this.resolution)}unsubscribe(){this.subscription?.dispose(),this.subscription=null}captureIsRenderingEvent(e){this.diagnostics&&(this.diagnostics.isRendering=e),this.event("onIsRenderingChanged").raise(e,this.getModality(),this.getTrackId())}},UN=class{constructor(e,t,i,n,r,a){this.logger=e,this.configProvider=t,this.statsGatherer=i,this.sessionDiagnostics=n,this.remoteVideoResolutionManager=r,this.domOverrides=a,this.remoteRendererSubscriptions=new Map,this.diagnostics=n?.newRemoteVideoManagerDiagnostics()}createRenderer(e,t,i){const n=new FN((i??this.logger).createChild("videorenderer"),this.configProvider,this.diagnostics?.newRendererDiagnostics(),t,e,this.sessionDiagnostics);return this.domOverrides.onMediaElementAdded&&this.domOverrides.onMediaElementAdded(n.getVideoElement()),this.addRenderer(n),n}moveRenderers(e){this.renderers.forEach((t=>{t.resetTimeToFirstFrameFlag(),e.addRenderer(t),this.removeRenderer(t)}))}getMaxAllowedVideoFS(){return this.remoteVideoResolutionManager.getMaxAllowedVideoFS()}dispose(){this.renderers.forEach((e=>e.resetTimeToFirstFrameFlag())),this.renderers.forEach((e=>{const t=e.getTrackId(),i=e.getEndOfTheFreeze();this.statsGatherer.setFreezeDuration(i,t)})),this.remoteRendererSubscriptions.forEach(((e,t)=>{t.dispose(),e.forEach((e=>e.dispose()))})),this.remoteRendererSubscriptions.clear(),this.remoteVideoResolutionManager.clearRenderers()}processStatsReport(e){this.configProvider.config.isRenderingBasedOnRawStatistics&&this.onDiagnosticUpdated(e),this.updateOverlayStats(e)}processLegacyStats(e){this.configProvider.config.isRenderingBasedOnRawStatistics||this.renderers.forEach((t=>{const i=t.getTrackId();if(e.remoteVideoStreams[i]){const n=e.remoteVideoStreams[i].isRendering;void 0!==n&&t.setIsRendering(n)}}))}playVideo(){this.renderers.forEach((e=>e.playVideo()))}get renderers(){return Array.from(this.remoteRendererSubscriptions,(([e])=>e))}addRenderer(e){this.remoteRendererSubscriptions.set(e,this.subscribeOnEvents(e)),this.logger.safe.info("Added renderer to manager"),this.remoteVideoResolutionManager.addRenderer(e)}generateVideoRecvStats(e){const t=new Map,i=e=>{e?.forEach((e=>{const i=e.track?.trackIdentifier??e.inboundRTP.trackIdentifier;t.set(i,e)}))};return i(e.sharing?.recv),i(e.video?.recv),t}updateOverlayStats(e){const t=this.generateVideoRecvStats(e);this.renderers.forEach((e=>{const i=e.getTrackId();t.has(i)&&e.updateStatsOverlay(t.get(i))}))}onDiagnosticUpdated(e){const t=[...e.video?.recv??[],...e.sharing?.recv??[]];if(t.length){const e=new Map;t.forEach((t=>{e.set(t.track?.trackIdentifier,t)})),this.renderers.forEach((t=>{const i=t.getTrackId();e.has(i)&&t.updateIsRenderingTracker(e.get(i))}))}}subscribeOnEvents(e){return[e.on("onRendererDisposed",(e=>this.onRendererDisposed(e))),e.on("onVideoStarted",((e,t,i)=>this.onVideoStarted(e,t,i))),e.on("onFreezeEnded",(t=>{const i=e.getTrackId();this.statsGatherer.setFreezeDuration(t,i)})),e.on("onIsRenderingChanged",((e,t,i)=>this.statsGatherer.setIsRendering(e,t,i)))]}onRendererDisposed(e){this.logger.safe.debug("Renderer removed from manager"),this.removeRenderer(e),this.domOverrides.onMediaElementRemoved&&this.domOverrides.onMediaElementRemoved(e.getVideoElement())}removeRenderer(e){this.remoteRendererSubscriptions.get(e).forEach((e=>e.dispose())),this.remoteRendererSubscriptions.delete(e),this.remoteVideoResolutionManager.removeRenderer(e)}onVideoStarted(e,t,i){this.statsGatherer.setTimeToFirstFrame(e,t,i)}},BN=class extends qe{constructor(e,t,i){super(),this.configProvider=t,this.callDeviceManager=i,this.lastFramerateInput=-1,this.trackInfo=[],this.timeoutId=null,this.logger=e.createChild("localStreamWatcher"),this.callDeviceManagerSub=i.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, updating subscriptions"),this.handleDeviceManagerChange()}))}get effectsManager(){return this.callDeviceManager.getDeviceManager("Video").effectsManager}startWatching(e){this.configProvider.config.videoCaptureFreezeTimeout&&(this.trackInfo=e,this.videoEffectManagerSubscription||(this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e)))))}stopWatching(){this.trackInfo=[],this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=null,0!==this.lastFramerateInput||this.timeoutId||this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")),this.disposeTimer(),this.lastFramerateInput=-1}dispose(e){this.callDeviceManagerSub?.dispose(),super.dispose(e),this.stopWatching()}onDiagnosticUpdated(e){if(!this.trackInfo.length||!e.video?.send?.length)return;const t=e.video?.send[0];let i,n=0;[t,...t.altLayouts??[]].forEach((e=>{const t=e.mediaSource,r=t?.framesPerSecond??0;this.trackInfo.some((e=>e.trackId===t.trackIdentifier))&&(!i||n<r)&&(i=t,n=r)})),i?n!==this.lastFramerateInput&&(0===n?this.scheduleCaptureFreezeStart(i.trackIdentifier,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${i.trackIdentifier}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=n):this.logger.safe.warn("WebRTC Stats for send video not found")}onStatisticsChanged(e){if(!this.trackInfo.length)return;let t;Object.keys(e.localVideoStreams).forEach((i=>{const n=e.localVideoStreams[i];this.trackInfo.some((e=>e.trackId===n.trackId))&&(!t||t.frameRateInput<n.frameRateInput)&&(t=n)})),t?t.frameRateInput!==this.lastFramerateInput&&(0===t.frameRateInput?this.scheduleCaptureFreezeStart(t.trackId,!this.effectsManager.isEffectEnabled("Video")):0===this.lastFramerateInput&&(this.timeoutId?this.disposeTimer():(this.logger.info(`onVideoCaptureFreeze end for trackId: ${t.trackId}`),this.event("onVideoCaptureFreeze").raise(!1,!this.effectsManager.isEffectEnabled("Video")))),this.lastFramerateInput=t.frameRateInput):this.logger.safe.warn("WebRTC Stats for send video not found")}onVideoFreezeDetected(e){this.logger.info(`onVideoCaptureFreeze, webcam freeze detected trackId: ${e}`),this.event("onVideoCaptureFreeze").raise(!1,!0)}scheduleCaptureFreezeStart(e,t){this.timeoutId=window.setTimeout((()=>{this.timeoutId=null,this.logger.info(`onVideoCaptureFreeze start for trackId: ${e}`),this.event("onVideoCaptureFreeze").raise(!0,t)}),this.configProvider.config.videoCaptureFreezeTimeout)}disposeTimer(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handleDeviceManagerChange(){this.videoEffectManagerSubscription?.dispose(),this.videoEffectManagerSubscription=this.effectsManager.on("videoFreezeDetected",(e=>this.onVideoFreezeDetected(e)))}},VN=class{constructor(e,t,i,n,r,a,s){this.mediaStream=e,this.receiver=t,this.modality=i,this.sourceStreamId=n,this.controller=r,this.videoCapabilties=a,this.getMaxAllowedVideoFS=s,this.msi=zk.SourceNone,this.operations=Promise.resolve()}dispose(){this.receiver=null,this.mediaStream=null}getId(){return this.mediaStream.id}getModality(){return this.modality}getMsi(){return this.msi}getMediaStream(){return this.mediaStream}getReceiver(){return this.receiver}getSourceStreamId(){return this.sourceStreamId}requestSource(e){this.msi=e;const t=this.operations.then((()=>{let t;return this.videoCapabilties&&(this.videoCapabilties.resetToInitial(),this.getMaxAllowedVideoFS&&this.videoCapabilties.setMaxFS(Math.min(this.getMaxAllowedVideoFS(),this.videoCapabilties.getMaxFS())),t=this.videoCapabilties.buildFmtp(),this.videoCapabilties.resetToInitial()),this.controller.requestSource(this.mediaStream.id,e,t)}));return this.operations=t.catch((()=>{})),t}},HN=class{constructor(e){this.queue=[],this.logger=e}cleanup(){this.queue.forEach((e=>{e.reject({notSent:e.tones})})),this.queue=[]}waitForNotification(e){return e?(this.logger.unsafe.info("sending dtmf tones: ",e),new Promise(((t,i)=>{this.queue.push({tones:e,resolve:t,reject:i})}))):Promise.reject(new Error("invalid input"))}toneSent(e){this.queue[0]&&(e===this.queue[0].tones[0]?(this.queue[0].tones=this.queue[0].tones.substr(1),""===this.queue[0].tones&&(this.queue[0].resolve(),this.queue.shift())):(this.queue[0].reject(new Error(`sent tone does not match: expected '${this.queue[0].tones[0]}' got '${e}'`)),this.queue.shift(),this.toneSent(e)))}},$N=class{constructor(e){this.webRtcSender=null,this.configProvider=e.configProvider,this.queue=new HN(e.logger)}sendDtmf(e,t){return e&&e.getSenders?(this.syncSender(e),this.webRtcSender?(this.webRtcSender.ontonechange=this.onToneChange.bind(this),this.webRtcSender.insertDTMF(this.webRtcSender.toneBuffer+t,this.configProvider.config.dtmf.toneDuration,this.configProvider.config.dtmf.toneGap),this.queue.waitForNotification(t)):Promise.reject(new Error("not available"))):Promise.reject(new Error("bad peerConnection"))}canSendDtmf(e){return!(!e||!e.getSenders)&&(this.syncSender(e),!!this.webRtcSender&&this.webRtcSender.canInsertDTMF)}dispose(){this.queue.cleanup()}syncSender(e){const t=e.getSenders().filter((e=>e.track&&"audio"===e.track.kind)).filter((e=>e.dtmf&&e.dtmf.canInsertDTMF))[0];this.webRtcSender&&t&&t.dtmf!==this.webRtcSender&&(this.webRtcSender.ontonechange=null,this.queue.cleanup()),this.webRtcSender=t?t.dtmf:null}onToneChange(e){e.tone&&this.queue.toneSent(e.tone)}},GN=e=>new $N(e),jN=0,zN=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc-"+ ++jN),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.webrtcAdapter=vN({global:this.context.maContext,configProvider:this.configProvider}),this.iceHostCandidateOnly=this.multiParty&&ft("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new bN({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:!1}),this.sessionDescription=_M.build({sdpTransform:new this.webrtcAdapter.SdpTransform(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=ft("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new Wk({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.stats=new qO(this.logger.createChild("stats"),this.configProvider,void 0,this.mediaManager,this.multiParty),this.maxResolution=this.multiParty?Zw.Send.getResolutionByFs(this.configProvider.config.webrtcMultipartyMaxScalingFs):Zw.Send.getResolutionByFs(this.configProvider.config.webrtcMaxScalingFs),this.qualityManager=new ON(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,cooldownTimeout:this.configProvider.config.webrtcResolutionManagerCooldownTimeout,retryDelay:this.configProvider.config.webrtcResolutionManagerRetryDelay,maxResolution:this.maxResolution,customBwEstimationEnabled:!0,sendBandwidthNotificationsEnabled:this.multiParty&&this.configProvider.config.webrtcSendBandwidthNotificationsEnabled},{onReceiveCapabilitiesChanged:(e,t,i)=>this.applyCapabilitiesForModality(e,t,i),onSendBandwidthChanged:e=>this.onSendBandwidthChanged(e)},this.stats,void 0,this.configProvider),this.localVideoStreamWatcher=new BN(this.logger,this.configProvider,this.context.callDeviceManager),this.activeSpeakerManager=new $k(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,null,this.logger.createChild("ActiveSpeakerManager")),this.senders={},this.negotiationQueue=new Hw(this.logger),this.negotiationEmulator=new wN(this.logger.createChild("negotiationEmulator"),this.webrtcAdapter.RTCSessionDescription,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.extensionsManager=this.setupExtensionsManager(),this.toBeCalledAfterConnected=[],this.iceTransportPolicy=this.configProvider.config.iceTransportPolicyForced||this.context.config.iceTransportPolicy||Qe.ICE_TRANSPORT_POLICY.all,this.isMuteHold=!1,this.peerConnection=null,this.mediaStreams=new Map,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new Jh,this.relayCandidateGathered=!1,this.iceCandidatesTimer=null,this.triggerRenegotiationFlag=!1,this.canTriggerRenegotiation=!0,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.forceMediaStreamUpdate=!1,this.negotiatedModalities={},this.disabledModalities={},this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({}),this.terminated=!1,this.initiator=!1,this.streamsChangedListener=null,this.dtmfSender=GN({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=ft("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new Jk(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.remoteVideoResolutionManager=new NN(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.stats),this.remoteVideoManager=new UN(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.stats,void 0,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.hwSilent=!1,this.configuredModalitiesPromise=Promise.resolve(),this.negotiationCompletedPromise=new Jh,this.ssrcGenerator=new jk,this.ssrcs={Audio:this.getSsrcRangeForMediaType("Audio"),Video:this.getSsrcRangeForMediaType("Video"),ScreenShare:this.getSsrcRangeForMediaType("ScreenShare")},this.forceKeyFramePromise=null,this.ufdManager=e.getUfdManager(),this.stats.on("onStatisticsChanged",(e=>{this.remoteVideoManager.processLegacyStats(e),this.localVideoStreamWatcher?.onStatisticsChanged(e),this.updateQualityLevels(e)})),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),this.setSubsForSubscriptionManager(),this.localVideoStreamWatcher.on("onVideoCaptureFreeze",(e=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"Bad":"Good","Video")})),this.configProvider.mediaConfig.maxBandwidthInKbps&&this.stats.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.createAudioRenderer(),this.configProvider.config.webrtcVideoScaling&&this.onOptimalVideoReceiversCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount)}get audioStream(){return this.mediaStreams.get("Audio")}get videoStream(){return this.mediaStreams.get("Video")}get displayStream(){return this.mediaStreams.get("ScreenShare")}useNullAudioStreamClient(){}getIncomingRawAudioStream(){return null}configureSpatialAudio(e,t){}setParticipantSpatialAudioPositions(e,t){}getAcceptedTypes(){return this.allowedMediaContentType}clone(t=!1){const i=ot(this.context);i.config=ot(this.context.config),i.config.webrtcMediaContentType=this.mediaContentType,i.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,t?i.config.isConference=!0:(i.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(i.config.webrtcIceGatheringTimeoutIncreased=!0));const n=new e(i,this.callId,this.callback);return this.relayManagerProvider&&(n.relayManagerProvider=this.relayManagerProvider),n.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,n}setInternals(e){if(e.extensionsManager&&this.extensionsManager){const t=e.extensionsManager.getExtension("videoStreamControl");t&&t.getOptions()&&this.extensionsManager.configureExtension("videoStreamControl",t.getOptions())}e.subscriptionManager&&(this.subscriptionManager&&this.subscriptionManager.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setStreamProvider({getStreams:()=>this.getStreams(),setOnStreamsChangedHandler:e=>this.onStreamsChanged(e)}),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager&&e.remoteVideoManager.moveRenderers(this.remoteVideoManager)}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.stats.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.stats.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,a)=>this.stats.addSubscriptionEvent(e,t,i,n,null,r,a))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.stats.addSubscriptionEvent(e,t,i,n,r)))]}move(e,t){e.setInternals({subscriptionManager:this.subscriptionManager,extensionsManager:this.extensionsManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager}),e.muteHold(this.isMuteHold,t),this.doAudioMute?e.muteInputAsync(t):e.unmuteInputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMuteAsync with mute state ${t}, audio stream exists: ${!!this.audioStream}`),"Audio"===e&&this.audioStream?this.audioStream.setMuted(t,i):"Video"===e&&this.videoStream?this.videoStream.setMuted(t,i):"ScreenShare"===e&&this.displayStream&&this.displayStream.setMuted(t,i),this.updateQualityLevels(this.stats.getLastStatistics())}setCallConstraints(e,t){return Promise.reject(new Error("Not supported"))}configureModalitiesAsync(e,t){const i=this.configuredModalitiesPromise.then((()=>{if(!e||!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const i=!this.configuredModalities||!Xg(e,this.negotiatedModalities);return this.configuredModalities=e,this.logger.safe.info(`[${t}] configure modalities`,`audio: ${e.audio}`,`video: ${e.video}`,`sharing: ${e.sharing}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?this.peerConnection.signalingState:"-"}`,`needNewRenegotiation: ${i}`),i&&this.triggerRenegotiation(!1,t),this.configuredModalities}));return this.configuredModalitiesPromise=i.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${Be(e)}`)})).then((()=>{})),i.then((()=>{}))}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}getSubscriptionManager(){return null}createAudioElement(e){}createOfferAsync(e){const t=this.negotiationQueue.add((()=>new Promise((t=>{this.logger.safe.info(`[${e}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiator=!0,this.throwIfModalitiesNotConfigured("no configured modalities to create offer for"),this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,this.offeredModalities=this.negotiatingModalities,this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[Qe.MODALITY.data]&&this.multiParty&&(this.offeredModalities[Qe.MODALITY.data]=Qe.MEDIA_STATE.inactive),Jg(this.offeredModalities)&&!at(this.negotiatedModalities)&&Object.keys(this.offeredModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.offeredModalities[e]})),t(this.updatePeerConnectionStreamsAsync(this.offeredModalities,!0,!0,e).then((()=>{const t=this.createNegotiationConstraints(this.offeredModalities);return this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)} constraints: ${JSON.stringify(t)}`),this.peerConnection.createOffer(t)})).then((t=>{this.logger.unsafe.debug(`[${e}] create [offer] offer from peer connection`,"sdp:",t.sdp);const i=this.sessionDescription.createLocalOffer(t.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(e),this.stats.startWaitingForStreamStart(this.offeredModalities);const n=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"offer"});return this.setupIceGatheringTimeout(e),Promise.all([this.peerConnection.setLocalDescription(n),this.iceCandidatesDeferred.promise])})).then((()=>{const t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);t.updateModalities(this.offeredModalities),this.checkIceCandidates(t);const i=t.toOffer();this.logger.unsafe.debug("CREATE OFFER","sdp:",i);const n={blob:i,contentType:this.mediaContentType};return""===this.configProvider.config.webrtcRequiredFeatures||this.multiParty||(n.requiredFeatures=this.configProvider.config.webrtcRequiredFeatures),this.configProvider.countryCode&&(n.clientLocation=this.configProvider.countryCode),this.doRetargetIfNeeded(n,t,e),n})))}))),e);return this.resetNegotiationQueue(e),t}processOfferAsync(e,t){const i=this.negotiationQueue.add((()=>new Promise((i=>{const n=e.blob;if(this.logger.unsafe.debug(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&(ht(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),e.requiredFeatures){const t=this.configProvider.config.webrtcRejectedFeatures.split(",");pt(e.requiredFeatures.split(","),t)}this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.canTriggerRenegotiation=!1,this.offeredModalities=jg(this.offeredDescription.getModalities()),this.peerConnection||(this.context.configProvider.mediaConfig.isTransportUnbundled?this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled());let r=Promise.resolve(this.offeredModalities);if(Wg(this.offeredModalities.video)||qg(this.offeredModalities.video)||Wg(this.offeredModalities.sharing)||qg(this.offeredModalities.sharing)){const e=this.offeredDescription.getVideoCodecs();r=this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((i=>{if(!i.codecs.some((t=>e.some((e=>t.mimeType===e))))){this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`);const e=ot(this.offeredModalities);return this.disabledModalities.video=e.video,this.disabledModalities.sharing=e.sharing,e.video=void 0,e.sharing=void 0,e}return this.offeredModalities})).catch((e=>(this.logger.safe.error(`[${t}] failed to get video capability ${Be(e)}`),this.offeredModalities)))}i(r.then((e=>(this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(e)}`),e))))}))),t);return this.resetNegotiationQueue(t),i}createAnswerAsync(e,t){return new Promise((i=>{if(e)return void i({blob:"",contentType:this.mediaContentType});this.logger.safe.info(`[${t}] create [answer] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),this.throwIfModalitiesNotConfigured("no configured modalities to create answer for"),this.negotiatingModalities=this.configuredModalities;let n=Yg(this.offeredModalities,this.negotiatingModalities);const r=this.offeredDescription.clone();i(this.updatePeerConnectionStreamsAsync(n,!0,!1,t).then((()=>this.handleCodecSwitchUnsupported(t))).then((()=>{const e=this.offeredDescription.toRemote(n);this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources();const i=new this.webrtcAdapter.RTCSessionDescription({sdp:e,type:"offer"});return this.updateDescriptor(i,r),this.logger.unsafe.info(`[${t}] create [answer] set remote description`,"negotiated:",n,"sdp:",i.sdp),this.peerConnection.setRemoteDescription(i)})).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.updatePeerConnectionStreamsAsync(n,!1,!0,t)))).then((()=>(this.handleSharingRecvCapabilities(r),this.handleVideoRecvCapabilities(r)))).then((()=>this.peerConnection.createAnswer())).then((e=>{this.logger.unsafe.debug(`[${t}] create [answer] answer from peer connection`,"sdp:",e.sdp);const i=this.sessionDescription.createLocalAnswer(e.sdp);this.hasIceCandidates(i)||this.resetCandidateGathering(t),this.stats.startWaitingForStreamStart(n);const r=new this.webrtcAdapter.RTCSessionDescription({sdp:i.toLocal(),type:"answer"});return this.setupIceGatheringTimeout(t),Promise.all([this.peerConnection.setLocalDescription(r),this.iceCandidatesDeferred.promise])})).then((()=>{const e=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);e.updateModalities(n),this.checkIceCandidates(e);const i=e.toAnswer();n=e.getModalities(),Zg(this.configuredModalities,this.negotiatingModalities,n)||this.triggerRenegotiation(!0,t),this.setNegotiatedModalities(n),this.stats.sessionInfo.setBweType(e.getBweType()),this.logger.unsafe.debug("CREATE ANSWER","sdp:",i);const r={blob:i,contentType:this.mediaContentType};return this.configProvider.countryCode&&(r.clientLocation=this.configProvider.countryCode),r})))}))}processAnswerAsync(e,t,i){const n=e.blob;if(this.logger.unsafe.debug(i?"PROCESS PRANSWER":"PROCESS ANSWER","sdp:",n),i)return this.logger.safe.info(`[${t}] process [pranswer] ignored`),Promise.resolve();this.mediaContentType=e.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType);const r=this.sessionDescription.createRemoteAnswer(n),a=r.clone(),s=jg(r.getModalities());this.setNegotiatedModalities(s);const o=r.toRemote(this.negotiatedModalities);this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.registerMediaSources(),this.stats.sessionInfo.setBweType(r.getBweType());const l=new this.webrtcAdapter.RTCSessionDescription({sdp:o,type:"answer"});return this.updateDescriptor(l,a),this.logger.unsafe.info(`[${t}] process [answer] set remote description`,"negotiated:",this.negotiatedModalities,"sdp:",l.sdp),this.peerConnection.setRemoteDescription(l).then((()=>(this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized(),this.negotiatedModalities))).then((()=>(this.handleSharingRecvCapabilities(a),this.handleVideoRecvCapabilities(a)))).then((e=>{e&&this.triggerRenegotiation(!0,t)}))}completeNegotiationAsync(e){return new Promise((t=>{this.mediaManager.commit();const i=this.configuredModalities,n=this.forceMediaStreamUpdate&&!Jg(this.negotiatedModalities)||!Zg(i,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,r=!n;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${r} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),n&&this.triggerRenegotiation(!1,e),this.negotiationCompletedPromise.resolve(),t({isComplete:r,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})}))}rejectNegotiationAsync(e,t,i=!1){return Promise.resolve().then((()=>{if(this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${Be(e)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.peerConnection){if("have-local-offer"===this.peerConnection.signalingState)return this.logger.safe.info(`[${t}] rolling back local description`),this.configProvider.config.webrtcHandleRollback?(this.logger.safe.info(`[${t}] rolling back using local renegotiation`),this.negotiationEmulator.renegotiateNow().then((()=>{this.logger.safe.info(`[${t}] rolling back using local complete`)}))):this.peerConnection.setLocalDescription(new this.webrtcAdapter.RTCSessionDescription({type:"rollback"}));this.logger.safe.error(`[${t}] cannot rollback local description in currrent state: ${this.peerConnection.signalingState}`)}})).then((()=>{this.canTriggerRenegotiation=!0,this.negotiationCompletedPromise.reject("negotiation rejected"),this.getAddedMediaTypes(this.negotiatedModalities,this.negotiatingModalities).forEach((e=>{this.removeTrackByMediaType(e),this.disposeStreamByMediaType(e)})),this.registerLocalStreams()})).then((()=>(i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator})))}startMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}completeMediaDescriptionsUpdateAsync(e){return Promise.reject(new Error("Not supported"))}rejectMediaDescriptionsUpdateAsync(e,t){return Promise.reject(new Error("Not supported"))}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){return this.terminated||(this.statisticsReport=this.statisticsReport.then((()=>this.stats.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))),this.statisticsReport}getLastKnownStats(e=!1){return this.stats.getReport(!1,e)}muteHold(e,t){this.isMuteHold=e;const i=[Qe.MODALITY.audio,Qe.MODALITY.video,Qe.MODALITY.sharing].filter((e=>Wg(this.negotiatedModalities[e])&&(e!==Qe.MODALITY.audio||!this.doAudioMute)));for(const n of i)this.setMute(om(n),e,t)}async muteInputAsync(e){this.doAudioMute=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.doAudioMute=!1,this.setMute("Audio",!1,e)}muteOutputAsync(e){return this.audioRenderer.setMuted(!0,e),Promise.resolve()}unmuteOutputAsync(e){return this.audioRenderer.setMuted(!1,e),Promise.resolve()}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(e=Te()){const t=new Jh;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}getExtensionsManager(){return this.extensionsManager}onDeviceEvent(e){this.stats.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&(this.audioRenderer&&this.audioRenderer.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),Jg(this.negotiatedModalities)||(this.forceMediaStreamUpdate=!0,this.triggerRenegotiation(!0)))}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.stats.setTerminated(),this.canTriggerRenegotiation=!1,this.cleanUp(e);try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${Be(t)}`)}finally{this.stats.dispose(),this.terminated=!0}}processNotification(e,t){this.extensionsManager.processNotification(e,t)}cleanUp(e){this.negotiationQueue.dispose(),this.localVideoStreamWatcher.dispose(),this.remoteVideoManager.dispose(),this.resetPeerConnection(e),this.subscriptionManagerSubs.forEach((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.clearIceDisconnectedTimer(),this.extensionsManager&&this.extensionsManager.dispose(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(e){this.logger.safe.info(`[${e}] reset peer connection`),this.audioRenderer&&this.audioRenderer.dispose(),this.dtmfSender&&(this.dtmfSender.dispose(),this.dtmfSender=null),this.peerConnection&&this.peerConnection.close(),this.toBeCalledAfterConnected=[],this.disposeStreams(),this.peerConnection=null,this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.resetCandidateGathering(e),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(e=Te()){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new Jh,e)}setNegotiationPromise(e,t=Te()){this.terminated||(this.negotiationCompletedPromise=e,this.negotiationQueue.add(this.negotiationCompletedPromise,t))}setupExtensionsManager(){const e=new ND(this.logger.createChild("ExtMgr"));return e.addExtension("dominantSpeakerHistory",{logger:this.logger,callback:this.activeSpeakerManager.onDominantSpeakerHistoryChanged.bind(this.activeSpeakerManager)}),e.addExtension("videoStreamControl",{logger:this.logger,negotiationEmulator:this.negotiationEmulator,qualityManager:this.qualityManager,configProvider:this.configProvider,statisticsGatherer:this.stats}),e}updateQualityLevels(e){if(!e)return;this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel});const t=!(!e.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",t?"Bad":"Good")}triggerRenegotiation(e,t=Te()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(t)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(e){if(!this.configuredModalities)throw new Error(e)}addTrack(e,t,i){if(!e)return;const n=this.modalityByMediaType(i);if(this.logger.safe.info(`add media track kind: ${e.kind} id: ${e.id}`),this.senders[n])throw new Error("track already created, modality:"+n+", kind:"+e.kind+", id:"+e.id);"closed"!==this.peerConnection.iceConnectionState&&(this.senders[n]=this.peerConnection.addTrack(e,t))}registerMediaSources(){const e=[];if(this.mediaStreams.forEach(((t,i)=>{const n={sourceId:this.getSourceIdForStream(t),defaultSSRC:this.ssrcs[i].min,modality:this.modalityByMediaType(i)};e.push(n)})),this.qualityManager.updateRegisteredSources(e),this.videoStream){const e=this.videoStream.getResolution();this.qualityManager.setCurrentResolution(new Yw(e.width,e.height))}}updateStream(e,t){return e.start().then((()=>{try{const i=this.mediaStreams.get(t);if(i&&e.isSameStream(i))return e.dispose(),null;if(this.updateSsrcRangeForMediaType(t),this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),!this.peerConnection)return e.dispose(),null;if(this.addTrack(e.rawTrack,e.rawStream,t),e.onApplyConstraints=i=>{this.removeTrackByMediaType(t),i.then((()=>{this.addTrack(e.rawTrack,e.rawStream,t),this.registerLocalStreams(),this.mediaManager.updateMediaEntitiesWithLocalTracks()}))},this.mediaStreams.set(t,e),"Video"===t){const e=[this.getMediaTrackInfo(t)];this.localVideoStreamWatcher.startWatching(e)}}catch(i){throw this.removeTrackByMediaType(t),this.disposeStreamByMediaType(t),e.dispose(),i}}))}getSourceIdForStream(e){const t=e.rawStream.getTracks()[0].id,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}updatePeerConnectionStreamsAsync(e,t,i,n){const r=Wg(this.negotiatedModalities.audio),a=Wg(this.negotiatedModalities.video),s=Wg(this.negotiatedModalities.sharing),o=Jg(this.negotiatedModalities),l=Wg(e.audio),c=Wg(e.video),d=Wg(e.sharing),u=Jg(e);return o||u||(this.stats.onSendersChanged("Audio",l),this.stats.onSendersChanged("Video",c),this.stats.onSendersChanged("ScreenShare",d)),this.assurePeerConnectionAsync(n).then((async()=>{if(this.logger.safe.info("updatePeerConnectionStreamsAsync","pc state",this.peerConnection.signalingState,"hold","[",o,"->",u,"]","audio","[",r,"->",l,"]","video","[",a,"->",c,"]","sharing","[",s,"->",d,"]"),o!==u){if(this.videoStream&&this.videoStream.setHold(u),this.audioStream&&this.audioStream.setHold(u),this.displayStream&&this.displayStream.setHold(u),u)return;if(!u&&this.audioStream){this.removeTrackByMediaType("Audio");const e=this.audioStream.clone();this.audioStream.dispose(),this.mediaStreams.set("Audio",e),this.addTrack(this.audioStream.rawStream.getAudioTracks()[0],this.audioStream.rawStream,"Audio")}}if((r!==l||a!==c||s!==d||this.forceMediaStreamUpdate)&&(i&&(this.forceMediaStreamUpdate=!1),t&&(this.logger.safe.info("not using any media(track api) track, remove all senders"),l||(this.removeTrackByMediaType("Audio"),this.disposeStreamByMediaType("Audio")),i&&c||(this.removeTrackByMediaType("Video"),this.disposeStreamByMediaType("Video")),i&&d||(this.removeTrackByMediaType("ScreenShare"),this.disposeStreamByMediaType("ScreenShare"))),i)){const e=[];if(c){const t=await this.deviceManager.getVideoStream(!1);e.push(this.updateStream(t,"Video"))}if(d){const t=this.deviceManager.getDisplayStream();e.push(this.updateStream(t,"ScreenShare"))}if(l){const t=await this.deviceManager.getAudioStream(!1);e.push(this.updateStream(t,"Audio").then((()=>{this.audioStream.setMuted(this.doAudioMute)})))}return Promise.all(e).then((()=>this.registerLocalStreams()))}}))}getMediaTrackInfo(e){const t=this.modalityByMediaType(e),i=this.mediaStreams.get(e).rawStream.getTracks()[0].id;return i||this.logger.safe.error(`No media track for modality found: ${t}`),{trackId:i,modality:t}}getSsrcRangeForMediaType(e){const t={min:1,max:1};switch(e){case"Audio":return this.ssrcGenerator.nextAudioStreamSsrc();case"Video":case"ScreenShare":return this.ssrcGenerator.nextVideoStreamSsrc();default:return t}}updateSsrcRangeForMediaType(e){"Video"!==e&&"ScreenShare"!==e||(this.ssrcs[e]=this.ssrcGenerator.nextVideoStreamSsrc())}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!1,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}registerLocalStreams(){const e=[];this.mediaStreams.forEach(((t,i)=>{e.push(this.getMediaTrackInfo(i))})),this.mediaManager.setLocalTracksInfo(e)}handleVideoRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&qg(e.getModalities().video)){if(this.videoStream){const t=e.getVideoRecvCapabilities();if(!t)return this.logger.safe.error("No fmt params found for video modality"),Promise.resolve(!1);const i=this.generateReceiveCapabilities(t,this.videoStream);this.qualityManager.setMaxCapabilities([i])}this.logger.safe.error("remote endpoint didn't specify video receive capability")}return Promise.resolve(!1)}handleSharingRecvCapabilities(e){if(this.configProvider.config.enableLocalVideoConstraints&&qg(e.getModalities().sharing)&&this.displayStream){const t=e.getSharingRecvCapabilities();if(!t)return void this.logger.safe.error("No fmt params found for sharing modality");const i=this.generateReceiveCapabilities(t,this.displayStream);this.qualityManager.setMaxCapabilities([i])}}generateReceiveCapabilities(e,t){const i={ssrc:0,rid:"0",keyframe:!1,...e},n={causeId:Te(),isSimulcast:!1,sourceId:this.getSourceIdForStream(t),capabilities:[i]};return this.logger.safe.info(`Generated receive capabilities for stream ${t.id}: ${JSON.stringify(n)}`),n}updateDescriptor(e,t){const i=t.getVideoRecvCapabilities(),n={sourceId:0,streamMsid:0,bandwidth:0};if(i&&this.videoStream&&!this.displayStream&&(n.sourceId=this.getSourceIdForStream(this.videoStream),n.streamMsid=this.videoStream.id,n.bandwidth=i.maxBr?i.maxBr:Number.MAX_VALUE),n.bandwidth>0){n.bandwidth=Math.floor(n.bandwidth/1200);const t=new Qk(this.logger.createChild("rembModifier"),this.qualityManager,this.configProvider);t.setControlItem(n),t.modifyDescriptor(e)}}removeTrackByMediaType(e){return this.removeTracksByModality(this.modalityByMediaType(e))}modalityByMediaType(e){switch(e){case"Audio":return Qe.MODALITY.audio;case"Video":return Qe.MODALITY.video;case"ScreenShare":return Qe.MODALITY.sharing;default:throw new Error(`Modality is not defined for media type: ${e}`)}}removeTracksByModality(e){this.forceKeyFramePromise&&"sharing"===e?this.forceKeyFramePromise.then((()=>{this.removeTracksByModality(e)})):e in this.senders&&(this.logger.safe.info(`remove sender track kind: ${this.senders[e].track.kind} track id: ${this.senders[e].track.id}`),"closed"!==this.peerConnection.iceConnectionState&&this.peerConnection.removeTrack(this.senders[e]),delete this.senders[e])}handleCodecSwitchUnsupported(e){return this.offeredDescription.isCodecSwitchSupported()?Promise.resolve():this.webrtcAdapter.RTCRtpReceiver.getCapabilities(Qe.MEDIA_TYPE.audio).then((e=>{const t=e.codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(t)})).catch((t=>{this.logger.safe.error(`[${e}] failed to set primary codec based on audio capability ${Be(t)}`)}))}disposeStreamByMediaType(e){const t=this.mediaStreams.get(e);t&&(this.mediaStreams.delete(e),t.dispose(),"Video"===e&&this.localVideoStreamWatcher.stopWatching())}disposeStreams(){this.mediaStreams.forEach(((e,t)=>this.disposeStreamByMediaType(t)))}assurePeerConnectionAsync(e){if(!this.peerConnectionPromise){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info("fetching relay details from RelayManager...");const t={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};this.peerConnectionPromise=this.relayManagerProvider.getRelayManager().queryRelaysAsync(t).then((t=>{if(this.terminated)throw new Error("session already disposed");const i={optional:[]},n=Mk(t,this.configProvider.config),r=this.configureCrypto(i);this.configureCpuThreshold(i),this.logger.safe.info("create peer connection");const a=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle",s=this.peerConnection=new this.webrtcAdapter.RTCPeerConnection({iceServers:n,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,bundlePolicy:a,sdpSemantics:"plan-b",audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===r,offerExtmapAllowMixed:!1},i);this.negotiationEmulator.configure(s),this.stats.initialize(s),this.stats.sessionInfo.setIceServers(n),this.stats.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.stats.sessionInfo.setBundlePolicy(a),this.webrtcAdapter.RTCRtpReceiver.getCapabilities("video").then((e=>this.stats.setH264AvailableProfiles(e))),s.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${s.signalingState}`)},s.onsignalingstatechange=()=>{this.stats.sessionInfo.setSignalingConnectionState(s.signalingState),this.logger.safe.info(`onsignalingstatechange signalingState: ${s.signalingState}`)},s.onicecandidateerror=e=>{const[t,i]=[e.address,e.port];this.logger.safe.warn(`On ICE candidate error ${e.url} | ${t}:${i}: code ${e.errorCode}: ${e.errorText}`),this.isConnected()&&!this.iceCandidatesDeferred.isPending||this.stats.addIceCandidateError({address:t,port:+i,url:e.url,errorCode:e.errorCode,errorText:e.errorText})};const o=e=>{if(!this.isConnected())return this.logger.safe.info("onaddstream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>o(e)));const t=e.stream;this.logger.safe.info(`onaddstream stream: ${t.id}`);let i=this.mediaManager.getMediaEntityByRemoteStreamId(t.id);if(i||(this.logger.safe.info(`cannot find media entity with stream id ${t.id} trying to fallback`),t.getAudioTracks()[0]&&(i=this.mediaManager.getMediaEntitiesByModality(Qe.MODALITY.audio)[0])),i){const e=this.createReceiveStream(t,i);this.receiveStreamCollection.add(e)}else this.logger.safe.error(`could not find media entity for an added stream: ${t.id}`)};s.onaddstream=o,s.ontrack=e=>{this.logger.safe.info(`ontrack track: ${e.track}`)};const l=e=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>l(e)));this.logger.safe.info(`onremovestream stream: ${e.stream.id}`),this.receiveStreamCollection.remove(e.stream.id)};s.onremovestream=l,s.onicecandidate=t=>{const i=t.candidate;if(i){const t=nm(i.candidate);this.logger.safe.info(`[${e}] onicecandidate candidate: prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1&&(this.stats.sessionInfo.setRelayCandidateInfo({priority:i.priority||i.candidate.split(" ")[3],time:Date.now()-this.iceRelayCandidatesGatherStartTime}),this.relayCandidateGathered=!0)}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const r=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,a=this.iceHostCandidateOnly||0===n.length;if(!i&&r||a){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.isConnected(),s.iceConnectionState,s.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.stats.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},s.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${s.iceGatheringState}`)},s.oniceconnectionstatechange=()=>{const e=Te();if(!this.terminated){if(this.stats.sessionInfo.setIceConnectionState(s.iceConnectionState),this.logger.safe.info(`[${e}] oniceconnectionstatechange iceConnectionState: ${s.iceConnectionState} pc.signalingState: ${s.signalingState}`),"connected"===s.iceConnectionState||"completed"===s.iceConnectionState)this.onTransportConnected(e);else if("failed"===s.iceConnectionState){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${e}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(e);this.raiseError({type:Qe.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},e),this.configProvider.config.webrtcCloseAfterIceFailure&&s.close(),this.onTransportFailed()}"disconnected"===s.iceConnectionState?(this.onTransportDisconnected(e),this.startIceDisconnectedTimer(e)):this.clearIceDisconnectedTimer()}},this.multiParty&&(this.contributingSources=new SN(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new yN(this.logger.createChild("ContributingSourcesProvider"),s)))}))}return this.peerConnectionPromise}configureCrypto(e){let t=!1;const i=mm(this.context);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.stats.sessionInfo.setOfferedSrtpInfo(e),t=!e.dtls||e.sdes&&i}else t=i;return t&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1})),this.stats.sessionInfo.setNegotiatedSrtpInfo({dtls:!t,sdes:!!t}),t?0:1}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(e){if(this.logger.safe.info(`[${e}] audio transport connected`),this.stats.clearIceCandidateErrors(),!this.terminated)for(this.callbacks.onAudioStateChanged(Qe.STREAMING_STATE.active,e),this.callbacks.onTransportConnected&&this.callbacks.onTransportConnected(e);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}onTransportDisconnected(e){this.callbacks.onTransportDisconnected&&this.callbacks.onTransportDisconnected(e)}onTransportFailed(){this.callbacks.onTransportFailed&&this.callbacks.onTransportFailed()}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise CONSTANTS.MEDIAthis._ERROR.iceConnectionError`),this.raiseError({type:Qe.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=Te()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}createNegotiationConstraints(e){function t(e){return!!e&&(qg(e)||"inactive"===e)}return{offerToReceiveAudio:t(e.audio),offerToReceiveVideo:t(e.video)||t(e.sharing)}}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Jh}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Qe.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&("connected"===this.peerConnection.iceConnectionState||"completed"===this.peerConnection.iceConnectionState))return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}doRetargetIfNeeded(e,t,i){const n=t.isIceRestart();this.logger.safe.info(`[${i}] ICE restart: ${n}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription?.isMSRTC()&&n&&!this.multiParty&&t.getSrtpInfo().sdes&&(e.newOffer=!0)}getAddedMediaTypes(e,t){e||(e={}),t||(t={});const i=[];return WN(e.audio,t.audio)&&i.push("Audio"),WN(e.video,t.video)&&i.push("Video"),WN(e.sharing,t.sharing)&&i.push("ScreenShare"),i}applyCapabilitiesForModality(e,t,i){return e===Qe.MODALITY.video?this.applyCapabilitiesForVideo(t,i[0]):e===Qe.MODALITY.sharing?this.applyCapabilitiesForSharing(t,i[0]):Promise.resolve(!1)}applyCapabilitiesForSharing(e,t){return this.displayStream?this.applyCapabilities(this.displayStream,t).then((i=>(this.stats.onMaxCapabilitiesApplied({causeId:e,modality:Qe.MODALITY.sharing,capabilities:[t]}),this.configProvider.config.webrtcAllowRestoreKeyframe?this.forceKeyframe(this.senders[Qe.MODALITY.sharing]).then((()=>i)):Promise.resolve(i)))):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no sharing stream is sent, no renegotiation`),Promise.resolve(!1))}forceKeyframe(e){if(!e)return this.logger.safe.error("forceKeyframe: No sender available for sharing"),null;if(this.forceKeyFramePromise)return this.logger.safe.warn("forceKeyframe: already in progress"),this.forceKeyFramePromise;this.logger.safe.info("Restoring keyframe");const t=e.track;return this.forceKeyFramePromise=e.replaceTrack(null).then((()=>e.replaceTrack(t))).then((()=>{this.forceKeyFramePromise=null,this.logger.safe.info("Restoring keyframe finished")})).catch((e=>{this.forceKeyFramePromise=null,this.logger.safe.error(`Restoring keyframe failed: ${e}`),delete this.senders[Qe.MODALITY.sharing]})),this.forceKeyFramePromise}applyCapabilitiesForVideo(e,t){return this.negotiationCompletedPromise.isPending?(this.logger.safe.info("##### Renegotiation is in progress, no local resolution switch for now #####"),this.negotiationCompletedPromise.promise.then((()=>Promise.resolve(!1)))):this.videoStream?this.scheduleApplyCapabilities(this.videoStream,e,t):(this.logger.safe.info(`${JSON.stringify(t)} is ignored as no video is sent, no renegotiation`),Promise.resolve(!0))}scheduleApplyCapabilities(e,t,i){this.logger.safe.info("Queueing local renegotiation...");let n=!1;return this.negotiationQueue.add((()=>(this.logger.safe.info("############# LOCAL RENEGOTIATION START #############"),this.applyCapabilities(e,i).then((()=>{this.stats.onMaxCapabilitiesApplied({causeId:t,modality:Qe.MODALITY.video,capabilities:[i]}),n=!0})))),t),this.negotiationEmulator.renegotiate().then((()=>(this.logger.safe.info(`############# LOCAL RENEGOTIATION END. RESULT: ${n}  #############`),n)))}applyCapabilities(e,t){return e?(this.logger.safe.info(`Changing resolution to ${JSON.stringify(t)}`),e.applyCapabilities(t)):(this.logger.safe.info(`Resolution ${JSON.stringify(t)} ignored, no stream is being sent`),Promise.resolve(!1))}onOptimalVideoReceiversCountChanged(e){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e)}async onSendBandwidthChanged(e){if(!this.isConnected())return;const t=this.extensionsManager.getExtension("videoStreamControl"),i=this.mediaManager.getMediaEntities().filter((e=>[Qe.MODALITY.video,Qe.MODALITY.sharing].indexOf(e.getModality())>-1)).filter((e=>e.isEnabled())).map((e=>e.getMid()));return 0!==i.length?t.sendBandwidthInfo(i,e).then((()=>{this.stats.setReportedSendBandwidth(e)})):void 0}getStreams(){return this.receiveStreamCollection.getStreams()}onStreamsChanged(e){this.streamsChangedListener=e}notifyStreamsChanged(){this.logger.safe.info(`Scheduling stream changed notification: ${this.streamsChangedNotificationScheduled}`),this.streamsChangedNotificationScheduled||this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.streamsChangedListener&&this.streamsChangedListener()}))}streamAdded(e){Qe.MODALITY.audio===e.getModality()&&(this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),this.audioRenderer.play(e.getMediaStream())),this.notifyStreamsChanged()}streamRemoved(e){Qe.MODALITY.audio===e.getModality()&&this.audioRenderer.getStream()===e.getMediaStream()&&this.audioRenderer.stop(),this.notifyStreamsChanged()}setNegotiatedModalities(e){this.negotiatedModalities=e,this.stats.sessionInfo.setNegotiatedModalities(e)}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}createAudioRenderer(){this.audioRenderer=new Vw(this.logger.createChild("AudioRenderer"),this.configProvider),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved)}isConnected(){const e=this.peerConnection;return e&&("connected"===e.iceConnectionState||"completed"===e.iceConnectionState)}isFailed(){return this.peerConnection&&("failed"===this.peerConnection.iceConnectionState||"closed"===this.peerConnection.iceConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}createReceiveStream(e,t){const i=this.configProvider.config.addFmtpToInitialSubscription?t.getLocalRecvCapabilities():null,n=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&t.getModality()!==Qe.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null;return new VN(e,null,t.getModality(),+t.getXSourceStreamId(),this,i,n)}requestSource(e,t,i){if(!this.multiParty)return Promise.resolve();const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);return!this.isMuteHold&&this.negotiatedModalities[n.getModality()]!==Qe.MEDIA_STATE.inactive||t===zk.SourceNone?this.negotiationCompletedPromise.isPending?this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>this.requestSource(e,t))):Promise.resolve().then((()=>this.extensionsManager.getExtension("videoStreamControl").sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex()))):Dm(10).then((()=>this.requestSource(e,t)))}getSessionConfig(){return this.configProvider}getUnmixedAudioProvider(){return null}};function WN(e,t){return!Wg(e)&&Wg(t)}var qN={build:(e,t,i)=>new zN(e,t,i)},KN=class{constructor(e,t,i,n){this.worker=e,this.clientId=t,this.transformType=i,this.listener=n,this.worker.subscribeClient(this.clientId,this.transformType,(e=>this.processMsg(e))),this.worker.sendTransformCommand(this.clientId,{operation:"add",transformType:this.transformType})}processMsg(e){if(this.listener&&e.name in this.listener)return this.listener[e.name].apply(this.listener,e.args);throw`unexpected message received for transform type ${this.transformType}: ${JSON.stringify(e)}`}},JN=class{constructor(e){this.logger=e}createBaseInstanse(e){this.imp=new YN(this.logger.safe),e.addTransform(this.imp)}createWorkerInstanse(e,t){this.imp=new QN(e,t)}},YN=class{constructor(e){this.logger=e,this.transformType=0}transform(e){return this.processChunk(e),e}dispose(){}getStartCodeSize(e){const t=e.getUint32(0);return 1===t?4:256==(4294967040&t)?3:0}processChunk(e){if("key"!==e.type)return;const t=this.isH264KeyFrame(e.data)?`${this.getH264Profile(e.data)}(H264)`:"unknown";this.logger.info(`keyframe metadata: ${JSON.stringify(e.getMetadata())}, profile=${t}`)}isH264KeyFrame(e){if(e.byteLength<7)return!1;const t=new DataView(e),i=this.getStartCodeSize(t);return!!i&&7==(31&t.getUint8(i))}getH264Profile(e){const t=new DataView(e),i=this.getStartCodeSize(t);return(16777215&t.getUint32(i)).toString(16)}},QN=class extends KN{constructor(e,t){super(e,t,0,void 0)}},ZN=g,XN=[Qe.MODALITY.audio,Qe.MODALITY.video,Qe.MODALITY.sharing],eL=class{constructor(e,t,i,n,r){this.peerConnection=t,this.mediaManager=i,this.reinvitelessContext=r,this.entityTransceiverMap=new Map,this.logger=e.createChild("TM"),this.configProvider=n.configProvider,this.isMultiparty=n.config.isConference,this.isPstnCall=n.config.isPstnCall,this.isParkedCall=n.config.isParkedCall,this.numVideoChannels=this.isMultiparty&&this.configProvider.config.numVideoChannelsGvc||1,n.configProvider.config.enableRollbackHandler&&this.mediaManager.setRollbackUpdateHandler(this.handleMediaEntitiesRollback.bind(this))}getTransceivers(){return this.peerConnection.getTransceivers().filter(nL)}assureTransceivers(e){this.assureNegotiatedOrder(),this.addModalities(e),this.logTransceiversInfo("assureTransceivers"),this.setDirections(e)}syncTransceivers(e){this.syncWithMediaEntities(),this.setDirections(e)}assureNegotiatedOrder(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{-1!==XN.indexOf(t.getModality())&&(rL(this.entityTransceiverMap.get(t),e)||this.createTransceiverForEntity(t))}))}addModalities(e){const t=this.mediaManager.isEmpty();this.isMultiparty||!t||this.isPstnCall||(e.video=e.video||"inactive",e.sharing=e.sharing||"inactive"),this.configProvider.config.webrctRemoveVideoModalitiesForPstn&&this.isPstnCall&&!this.isParkedCall&&(delete e.video,delete e.sharing);for(const i of XN){if(this.mediaManager.getMediaEntitiesByModality(i)[0]||!e[i])continue;const n=i===Qe.MODALITY.video?this.numVideoChannels:1;(0,ZN.times)(n,(e=>{const n=this.mediaManager.createMediaEntity(i);n.setExtension("reinviteless",t&&this.reinvitelessContext.maxStreamsForModality[i]>e),this.createTransceiverForEntity(n)}))}}createTransceiverForEntity(e){const t=e.getModality();this.logger.safe.info(`createTransceiver: modality=${t}`);const i=t===Qe.MODALITY.audio?Qe.MEDIA_TYPE.audio:Qe.MEDIA_TYPE.video,n=e.getSimulcastContext(),r=this.createTransceiver(i,n);this.setCodecPreferences(r,i,!0),this.setExtensionPreferences(r,t),this.entityTransceiverMap.set(e,r),e.setExtension("unnegotiatedModality",!0)}setCodecPreferences(e,t,i){const n=Sm(this.configProvider,t);if(!n?.length||!Bg.hasCapabilitiesApi()||this.configProvider.config.filterCodecsInSdp)return;const r=Ug.window.RTCRtpReceiver.getCapabilities(t);if(!r)return;const a=[];if(i)for(const e of n){const t=r.codecs.filter((t=>tL(e,t)));a.push(...t)}else for(const e of r.codecs)n.some((t=>tL(t,e)))&&a.push(e);a.length&&e.setCodecPreferences&&e.setCodecPreferences(a)}setExtensionPreferences(e,t){if(!this.configProvider.config.headerExtensionsToUpdate?.[t])return;if(!e.getHeaderExtensionsToNegotiate||!e.setHeaderExtensionsToNegotiate)return void this.logger.safe.debug("setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate is not supported");const i=this.configProvider.config.headerExtensionsToUpdate[t],n=e.getHeaderExtensionsToNegotiate();for(const e of n){const t=i.find((t=>t.uri===e.uri));t&&(e.direction=t.direction)}try{e.setHeaderExtensionsToNegotiate(n)}catch(e){this.logger.safe.error(`setExtensionPreferences: transceiver.setHeaderExtensionsToNegotiate failed, err ${Be(e)}`)}}async createSender(e,t,i){const n=await this.associateTrackWithTransceiver(e,t,i);if(!n)throw new Error(`Transceiver for modality=${i} is not found`);const r=this.findEntityForTransceiver(n),a=i!==Qe.MODALITY.sharing||r?.getExtension("reinviteless")?Qe.MEDIA_STATE.sendReceive:Qe.MEDIA_STATE.send;return n.direction=a,this.logger.safe.info(`Replace track completed direction:${n.direction} for transceiver mid=${n.mid}`),n.sender}removeSender(e){this.removeSenderInternal(e,!1)}async removeSenderAsync(e){return this.removeSenderInternal(e,!0)}removeSenderInternal(e,t){if("closed"===(this.peerConnection.connectionState||this.peerConnection.iceConnectionState))return void this.logger.safe.info("Not removing sender from pc, connection is closed");const i=this.getTransceivers().find((t=>t.sender===e));if(!i)throw new Error(`Transceiver for sender with track=${e.track?.id} is not found`);const n=this.findEntityForTransceiver(i),r=!!n?.getExtension("reinviteless");this.logger.safe.info(`Remove sender with track=${e.track?.id} for transceiver mid=${i.mid}, reinviteless=${r}, doAsync=${t}`);let a=Promise.resolve();return r&&t?a=i.sender.replaceTrack(null):this.peerConnection.removeTrack(e),t?a:void 0}createTransceiver(e,t){const i={direction:"inactive"};return this.addSimulcastEnvelopeIfNeeded(i,t),this.peerConnection.addTransceiver(e,i)}addSimulcastEnvelopeIfNeeded(e,t){t?.shouldUseSimulcast()&&(e.sendEncodings=(0,ZN.times)(t.config.layerScaleFactors.length,(e=>{const i=`${t.ridList[e]}`,n=t.config.layerScaleFactors[e];return this.logger.safe.debug(`Added layer ${e} with rid: ${i} SF: ${n}`),{rid:i,scaleResolutionDownBy:n}})))}async associateTrackWithTransceiver(e,t,i){const n=this.findAvailableTransceiverToSend(i);if(n){this.logger.safe.info(`Associate track=${e?.id} (${i}) with existing transceiver mid=${n.mid}`);try{await n.sender.replaceTrack(e),this.configProvider.config.useSetStreamsForSender&&n.sender.setStreams&&n.sender.setStreams(t)}catch(e){throw this.logger.safe.error(`replaceTrack failed, err ${JSON.stringify(e)}`),e}return n}return null}syncWithMediaEntities(){const e=this.getTransceivers();this.mediaManager.getMediaEntities().forEach((t=>{let i=this.entityTransceiverMap.get(t);i=rL(i,e)?i:e.find((e=>e.mid===t.getMid())),this.entityTransceiverMap.set(t,i)})),this.logTransceiversInfo("syncWithMediaEntities")}getTransceiversByModality(e){return this.mediaManager.getMediaEntitiesByModality(e).map((e=>this.entityTransceiverMap.get(e))).filter(nL)}setDirections(e){const t=!Jg(e);for(const i of XN)for(const[n,r]of this.getTransceiversByModality(i).entries()){const a=this.findEntityForTransceiver(r);if(a?.getExtension("reinviteless")&&t){r.direction="sendrecv";continue}const s=e[i]||Qe.MEDIA_STATE.inactive;r.direction=0===n&&r.currentDirection?s:iL(s)}this.logTransceiversInfo("setDirections")}handleMediaEntitiesRollback(e,t){e.forEach((e=>{const i=this.entityTransceiverMap.get(e),n=t.find((t=>t.getMid()===e.getMid()));this.entityTransceiverMap.set(n,i)})),this.logTransceiversInfo("handleMediaEntitiesRollback")}findAvailableTransceiverToSend(e){const t=this.mediaManager.getMediaEntitiesByModality(e)[0];return this.entityTransceiverMap.get(t)}findEntityForTransceiver(e){for(const[t,i]of this.entityTransceiverMap)if(i===e)return t}logTransceiversInfo(e){let t=`${e}: transceivers details:`;for(const e of XN){const i=this.getTransceiversByModality(e);t+=` ${e}(${i.length}) [${i.map((e=>`mid=${e.mid}, direction=${e.direction}`)).join(";")}]`}this.logger.safe.debug(t)}};function tL(e,t){return!(!(0,ZN.isUndefined)(e.channels)&&e.channels!==t.channels||!(0,ZN.isUndefined)(e.clockRate)&&e.clockRate!==t.clockRate||!(0,ZN.isUndefined)(e.mimeType)&&e.mimeType.toLowerCase()!==t.mimeType.toLowerCase()||!(0,ZN.isUndefined)(e.sdpFmtpLine)&&-1===t.sdpFmtpLine.toLowerCase().indexOf(e.sdpFmtpLine.toLowerCase()))}function iL(e){let t=e;return Wg(e)&&(t=zg(e)),t||Qe.MEDIA_STATE.inactive}function nL(e){return e&&"stopped"!==e.direction&&!e.stopped}function rL(e,t){return nL(e)&&-1!==t.indexOf(e)}var aL=class{constructor(e,t){this.transforms=[];const i=new TransformStream({transform:(e,t)=>{let i=e;for(const e of this.transforms)if(i=e.transform(i),!i)return;t.enqueue(i)}});e.pipeThrough(i).pipeTo(t)}clearTransforms(){for(const e of this.transforms)e.dispose();this.transforms=[]}addTransform(e){this.transforms.push(e)}getTransform(e){return this.transforms.find((t=>t.transformType===e))}},sL=class{constructor(e,t){this.logger=t,this.clientsMap=new Map,this.loaded=!1,this.initDefer=km();try{this.worker=e.getWorker(),this.worker.onmessage=e=>this.handleEvent(e.data),this.worker.onerror=e=>{this.logger.safe.error(`error inside worker: ${e.message}`),this.initDefer.resolve()}}catch(e){this.logger.safe.error("failed to create worker"),this.initDefer.resolve()}}initialize(){return Promise.race([this.initDefer.promise,Dm(5e3)])}isWorkerLoaded(){return this.loaded}sendTransformCommand(e,t,i=[]){const n={type:"transform",clientId:e,payload:t};this.worker.postMessage(n,i)}subscribeClient(e,t,i){const n=this.clientsMap.get(e)??new Map;n.set(t,i),this.clientsMap.set(e,n)}dispose(){this.worker.postMessage({type:"generic",payload:{operation:"dispose"}}),this.worker.terminate()}handleEvent(e){switch(e.type){case"init":this.initDefer.resolve(),this.loaded=!0;break;case"transform":{const t=this.clientsMap.get(e.payload.clientId),i=t?.get(e.payload.event.transformType);i?.(e.payload.event),i||this.logger.safe.error(`received event for unknown Client ${e.payload.clientId} or transformType ${e.payload.event.transformType}`)}break;case"log":switch(e.level){case"debug":this.logger.safe.debug(e.msg);break;case"info":this.logger.safe.info(e.msg);break;case"warn":this.logger.safe.warn(e.msg);break;case"error":this.logger.safe.error(e.msg);break;default:this.logger.safe.error(`unknown log level ${e.level}`)}break;default:this.logger.safe.error(`received unsupported event from worker ${e.type}`)}}},oL=class extends qe{constructor(e,t,i){super(),this.configProvider=e,this.workerProvider=t,this.logger=i,this.transformsCollections=new Map}async initialize(){return this.configProvider.config.useInsertableStreams&&this.workerProvider&&Bg.hasEncodedStreamApi()&&(this.worker=new sL(this.workerProvider,this.logger)),this.worker?this.worker.initialize():Promise.resolve()}initTransformsCollection(e,t,i){const n=Bg.hasScriptTransformApi()||this.workerProvider;if(!this.configProvider.config.useInsertableStreams||!Bg.hasEncodedStreamApi()||n&&!this.isWorkerLoaded())return null;if(!this.transformsCollections.has(e)){const n=this.worker?new cL(this.worker,e):new lL(e);this.transformsCollections.set(e,{collection:n,mediaType:i,objType:t})}const r=this.transformsCollections.get(e);return this.event("onTransformsCollectionCreated").raise(r),r.collection}clearTransformsCollection(e){const t=this.transformsCollections.get(e);t&&(this.event("onTransformsCollectionCleared").raise(t),t.collection.clearTransforms())}dispose(){for(const e of this.transformsCollections.values())this.event("onTransformsCollectionCleared").raise(e),e.collection.clearTransforms();this.transformsCollections.clear(),this.worker?.dispose(),super.dispose()}isWorkerLoaded(){return!!this.worker?.isWorkerLoaded()}},lL=class{constructor(e){const{readable:t,writable:i}=e.createEncodedStreams();this.streamTransformer=new aL(t,i)}addTransform(e){e.createBaseInstanse(this.streamTransformer)}clearTransforms(){this.streamTransformer.clearTransforms()}},cL=class{constructor(e,t){if(this.workerHandler=e,this.clientId=t.track.id,Bg.hasScriptTransformApi())return void(t.transform=new RTCRtpScriptTransform(this.workerHandler.worker,{clientId:this.clientId}));const{readable:i,writable:n}=t.createEncodedStreams(),r=[i,n];this.workerHandler.sendTransformCommand(this.clientId,{operation:"init",readable:i,writable:n},r)}addTransform(e){e.createWorkerInstanse(this.workerHandler,this.clientId)}clearTransforms(){this.workerHandler.sendTransformCommand(this.clientId,{operation:"clear"})}},dL=g,uL=class extends qe{constructor(e,t){super(t),this.logger=t,this.id=-1,this.parentId=-1,this.rawStream=null,this.rawTrack=null,this.deviceId=null,this.mediaType=e}start(){return this.logger.safe.debug("start"),Promise.resolve()}clone(){return this.logger.safe.debug("clone"),this}setMuted(e,t){this.logger.safe.debug("setMuted")}setHold(e){this.logger.safe.debug("setHold")}getResolution(){return this.logger.safe.debug("getResolution"),{width:240,height:180}}getFrameRate(){return this.logger.safe.debug("getFrameRate"),1}hasAudio(){return this.logger.safe.debug("hasAudio"),!1}hasVideo(){return this.logger.safe.debug("hasVideo"),!1}isSameStream(e){return this.logger.safe.debug("isSameStream"),e===this}applyCapabilities(e){return this.logger.safe.debug("applyCapabilities"),Promise.resolve(!1)}onApplyConstraints(e){this.logger.safe.debug("onApplyConstraints")}update(e){this.logger.safe.debug("update")}isActive(){return!1}isDisposed(){return!1}},hL=class e extends qe{constructor(e,t,i,n){super(n),this.callDeviceManager=e,this.configProvider=t,this.serialQueue=i,this.logger=n,this.mediaStreams={Audio:null,Video:null,ScreenShare:null},this.streamSubscriptions=new Map,this.deviceManagerSubscriptions=[],this.isNullAudioStream=!1}get currentMediaTypes(){return st(this.streams).filter((e=>!!this.streams[e]))}get streams(){return this.mediaStreams}useNullAudioStreamClient(){this.isNullAudioStream=!0}async update(e,t){const i=st(e).filter((t=>e[t]));return ut(i,this.currentMediaTypes)?(this.logger.safe.info("Requested modalities have not changed. Do nothing"),cm(this.streams)):(this.logger.safe.info(`Starting media session with modalities: ${JSON.stringify(e)}`),await this.updateStreams(i,t),this.subscribeOnDeviceManagerEvents(),cm(this.streams))}async stopAsync(){this.logger.safe.info("Stopping streams async"),this.stop()}stop(){this.logger.safe.info("Stopping streams"),this.unsubscribeFromDeviceManagerEvents(),st(this.mediaStreams).forEach((e=>this.removeStreamByType(e)))}async ensureUpdateCompleted(){this.logger.safe.debug("streams updated")}dispose(){this.stop(),super.dispose()}async updateStreams(e,t){const i=this.getAvailableMediaTypes(),n=(0,dL.intersection)(e,i),r=st(this.mediaStreams).filter((e=>this.mediaStreams[e])),a=t?[]:vt(n,r),s=vt(r,n);this.logger.safe.info(`Adding media streams for types: ${JSON.stringify(a)}`),await Promise.all(a.map((async e=>{await this.addStream(e,!1),this.mediaStreams[e]&&this.event("onStreamAdded").raise(e)}))),this.logger.safe.info(`Removing media streams for types: ${JSON.stringify(s)}`),s.forEach((e=>{this.event("onStreamRemoving").raise(e),this.removeStreamByType(e)}))}getAvailableMediaTypes(){const e=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices(),t=[];return e.microphone&&t.push("Audio"),e.camera&&t.push("Video"),t.push("ScreenShare"),t}async addStream(e,t){if(this.mediaStreams[e])return void this.logger.safe.warn(`Stream with type: ${e} is already registered`);const i=await this.getStream(e,t);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i}removeStreamByType(e){const t=this.mediaStreams[e];t?(this.unsubscribeFromMediaStreamEvents(t),t.dispose(),this.mediaStreams[e]=null):this.logger.safe.warn(`Stream with type: ${e} is not registered`)}async updateStream(e,t,i=!1){i&&"Audio"===e?await this.updateStreamWithEffect(e):(this.removeStreamByType(e),await this.addStream(e,t)),this.event("onStreamUpdated").raise(e)}async updateStreamWithEffect(e){const t=this.mediaStreams[e];t&&this.unsubscribeFromMediaStreamEvents(t);const i=await this.getStreamByMediaType(e,!0);this.subscribeOnMediaStreamEvents(i);try{await i.start()}catch(t){return this.logger.safe.error(`updateStreamWithEffect. Media stream request error: ${JSON.stringify(t)}`),void this.event("onStreamError").raise(e,t)}this.mediaStreams[e]=i,t?.dispose()}subscribeOnMediaStreamEvents(e){if(this.streamSubscriptions.has(e))return;const t=[];t.push(e.on("onStreamClientError",((e,t)=>this.onStreamError(e,t)))),t.push(e.on("onStreamClientDisposing",(e=>this.onStreamDisposing(e)))),this.streamSubscriptions.set(e,t)}unsubscribeFromMediaStreamEvents(e){this.streamSubscriptions.has(e)&&(this.streamSubscriptions.get(e).forEach((e=>e.dispose())),this.streamSubscriptions.delete(e))}async getStream(e,t){const i=this.mediaStreams[e];return i?(this.logger.safe.info(`Stream exists with id: ${i.id}, type: ${e}`),i):this.getStreamByMediaType(e,t)}async getStreamByMediaType(e,t){switch(e){case"Audio":return this.isNullAudioStream?new uL("Audio",this.logger.createChild("NullStreamClient")):this.getDeviceManagerByType("Audio").getAudioStream(t,"sessionStream");case"Video":return this.getDeviceManagerByType("Video").getVideoStream(t,"sessionStream");case"ScreenShare":return this.getDeviceManagerByType("ScreenShare").getDisplayStream("sessionStream");default:throw new Error(`Media type is not supported: ${e}`)}}getMediaTypeForStream(e){const t=Object.keys(this.mediaStreams).find((t=>this.mediaStreams[t]===e));return t||this.logger.safe.error(`Media type is not found for stream: ${Be(e)}`),t}subscribeOnDeviceManagerEvents(){if(0!==this.deviceManagerSubscriptions.length)return;if(this.callDeviceManager.isVirtualDeviceEnabled){const e=this.callDeviceManager.on("onSelectedVirtualDevicesChanged",((e,t)=>{const i=e;if(!e.camera){this.logger.info("Virtual DeviceID for camera is undefined, falling back to default device");const{camera:e}=this.callDeviceManager.getDefaultDeviceManager().getSelectedDevices();i.camera=e}this.callDeviceManager.isModalityEnabled("Video")&&t.camera!==i.camera&&(this.logger.info("Updating stream for camera"),this.updateStreamForVirtualDeviceChange("Video")),this.callDeviceManager.isModalityEnabled("ScreenShare")&&t.screenshare!==i.screenshare&&(this.logger.info("Updating stream for screenshare"),this.updateStreamForVirtualDeviceChange("ScreenShare"))}));this.deviceManagerSubscriptions.push(e)}const e=this.callDeviceManager.getDefaultDeviceManager();this.deviceManagerSubscriptions.push(e.on("onSelectedDevicesChanged",((e,t)=>this.onSelectedDevicesChanged(e,t))),e.on("onStreamUpdateRequested",((e,t)=>this.requestStreamUpdate(e,!1,t))),e.on("onAudioSharingToggled",(e=>this.onAudioSharingToggled(e))))}unsubscribeFromDeviceManagerEvents(){0!==this.deviceManagerSubscriptions.length&&(this.deviceManagerSubscriptions.forEach((e=>e.dispose())),this.deviceManagerSubscriptions=[])}getMediaTypesToUpdate(e,t){const i=[];return this.currentMediaTypes.some((e=>"Audio"===e))&&e.microphone&&e.microphone!==t.microphone&&i.push("Audio"),!this.callDeviceManager.getSelectedDevices().camera&&this.currentMediaTypes.some((e=>"Video"===e))&&e.camera&&e.camera!==t.camera&&i.push("Video"),i}removeStream(e){const t=this.getMediaTypeForStream(e);this.removeStreamByType(t)}async onSelectedDevicesChanged(t,i){if(this.configProvider.config.enablePermissionsWorkaround&&e.isDeviceListEmpty(t,i))return void this.logger.safe.info("Device list is empty, permission workaround enabled");const n=this.getMediaTypesToUpdate(t,i);this.logger.safe.info(`Media types to update: ${JSON.stringify(n)}`),await Promise.all(n.map((e=>this.updateStream(e,!1))))}async onAudioSharingToggled(e){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&e)return this.updateStream("ScreenShare",!0)}async requestStreamUpdate(e,t,i=!1){if(this.currentMediaTypes.some((t=>t===e))||t)return this.logger.safe.debug(`UpdateStream with media type: ${e}, force: ${t}`),this.updateStream(e,t,i);this.logger.safe.debug(`Stream with media type: ${e} is not active. Do nothing`)}onStreamError(e,t){this.removeStream(e)}onStreamDisposing(e){this.removeStream(e)}static isDeviceListEmpty(e,t){return!e.camera&&!e.microphone||!t.microphone&&!t.camera}getDeviceManagerByType(e){return this.callDeviceManager.getDeviceManager(e)}async updateStreamForVirtualDeviceChange(e){return this.updateStream(e,!1)}};v([cA()],hL.prototype,"update",1),v([cA()],hL.prototype,"stopAsync",1),v([cA()],hL.prototype,"ensureUpdateCompleted",1),v([cA()],hL.prototype,"onSelectedDevicesChanged",1),v([cA()],hL.prototype,"onAudioSharingToggled",1),v([cA()],hL.prototype,"requestStreamUpdate",1),v([cA()],hL.prototype,"updateStreamForVirtualDeviceChange",1);var pL=hL,gL=g,mL=[5e4,1e6,15e5,2e6,25e5,375e4,4e6],fL=[7e4,2e5,4e5,8e5,15e5,2499990,25e5];var vL=class{constructor(e){this.logger=e,this.availableBandwidth=0,this.receivers=new Map,this.currentLayout={},this.ladders={}}setAvailableBandwidth(e){this.availableBandwidth=e,this.logger.safe.debug(`Total available bandwidth updated: ${e}`),this.updateLayouts()}addReceiverCapability(e,t){this.logger.safe.debug(`Receiver maxBr set: ${e}/${t}`),this.receivers.set(e,t),this.updateLayouts()}removeReceiver(e){this.logger.safe.debug(`Receiver maxBr removed: ${e}`),this.receivers.delete(e),this.updateLayouts()}getLayouts(){return this.currentLayout}setLadder(e,t){this.ladders[e]=t}updateLayouts(){const e=this.generateLayouts();(0,gL.isEqual)(e,this.currentLayout)||(this.currentLayout=e,this.logger.safe.debug(`Bandwidth distribution updated: ${Be(e)}`))}generateLayouts(){const e={},t={};for(const i of Object.keys(this.ladders)){const n=this.receivers.get(i);n&&(t[i]=n||Number.MAX_SAFE_INTEGER,e[i]=0)}let i=this.availableBandwidth,n=0;const r=()=>{if(!i)return!1;for(const e of Object.values(t))if(e)return!0;return!1};for(;r();){for(const r of Object.keys(e)){const a=this.ladders[r];let s=a[n]||a[a.length-1];s=Math.min(s,i,t[r]),e[r]+=s,i-=s,t[r]-=s}n++}return e}},SL=class{constructor(e,t,i){this.timeout=t,this.logger=i,this.isFirstTimeDeferred=!0,this.internalCallback=t=>{this.logger.safe.debug(`Trigger reason: ${t}`),e()}}invoke(e){if(this.logger.safe.debug(`Schedule shouldDefer: ${e}`),this.createTimerIfNeeded(e),this.timer)return e?this.startTimer():this.stopTimerAndTrigger();this.internalCallback("request")}dispose(){this.stopTimer()}startTimer(){this.timer.isActive||(this.timer.start(this.timeout),this.logger.safe.debug(`Timer started for : ${this.timeout}ms`))}stopTimer(){this.timer?.isActive&&(this.timer.stop(),this.logger.safe.debug("Timer stopped"))}stopTimerAndTrigger(){this.stopTimer(),this.internalCallback("request")}createTimerIfNeeded(e){e&&this.isFirstTimeDeferred&&(this.isFirstTimeDeferred=!1,this.timer=new Mm((()=>{this.internalCallback("timeout"),this.timer=null})))}},yL=class{constructor(e){this.logger=e,this.currentFrameSize=Zw.Send.initialResolution.fs}setAvailableBandwidth(e){e!==this.lastSendBW&&(this.logger.safe.debug(`Available bandwidth updated ${e}`),this.processEstimatedBandwidth(e))}setMaxFrameSize(e){this.logger.safe.debug(`SetMaxFrameSize ${e}`),e!==this.maxFrameSize?(this.maxFrameSize=e,this.lastSendBW?(this.logger.safe.debug(`Setting max frame size: ${e}`),this.processEstimatedBandwidth(this.lastSendBW)):this.logger.safe.debug("Last send bwe is not defined. Do nothing")):this.logger.safe.debug(`Max frame size did not change. Do nothing, maxFs: ${e}`)}getFrameSize(){return this.currentFrameSize}processEstimatedBandwidth(e){if(this.logger.safe.debug(`Process estimated bandwidth ${e}`),0===e)return this.lastSendBW=0,void this.proposeResolution(0);const{lowRes:t,highRes:i}=Zw.Send.getResolutionForBitrate(e);this.logger.safe.debug("low",t,"hi",i);const n=e<this.lastSendBW?i.fs:t.fs;e<this.lastSendBW&&this.currentFrameSize<n?this.logger.safe.debug(`proposed resolution is above the existing one, so we should stay on the current resolution, last bw: ${e}`):(n&&this.proposeResolution(n),this.logger.safe.debug(`Updating last bw: ${e}`),this.lastSendBW=e)}proposeResolution(e){this.logger.safe.debug(`Propose resolution ${e}`);const t=this.maxFrameSize?Math.min(e,this.maxFrameSize):e;t!==this.currentFrameSize&&(this.currentFrameSize=t,this.logger.safe.debug(`Proposed new frame size: ${t} based on bandwidth: ${this.lastSendBW}`))}},CL=[{bwe:2e5,param:5e5},{bwe:5e5,param:12e5},{bwe:8e5,param:25e5},{bwe:12e5,param:4e6}],_L=[{bwe:2e5,param:240},{bwe:3e5,param:405},{bwe:5e5,param:920},{bwe:9e5,param:2040}],EL=(e,t,i)=>{for(const n of i)if(t<n.bwe)return Math.min(e,n.param);return e},TL=(e,t,i=CL)=>EL(e,t,i),bL=class extends qe{constructor(e,t,i){super(t),this.configProvider=e,this.logger=t,this.layoutsNumber=i,this.totalBandwidth=1e8,this.totalBandwidthMax=0,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),this.outputLayouts=null,super.dispose()}setAvailableBandwidth(e){this.storeAvailableBandwidth(e),this.inputLayouts?(this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.debug("Layouts are not set. Skip update")}setLayouts(e,t){this.storeAvailableBandwidth(t),e.length===this.layoutsNumber?(this.logger.safe.debug(`Set layouts: ${JSON.stringify(e)}`),this.inputLayouts=this.getPrioritizedLayouts(e),this.recalculateLayouts(),this.checkForChangesAndNotify()):this.logger.safe.warn(`Incorrect number of layouts! ${JSON.stringify(e)}, expected ${this.layoutsNumber}`)}getLayouts(){return this.inputLayouts}getPrioritizedLayouts(e){return e}checkForChangesAndNotify(){const e=this.getLayouts();ut(this.outputLayouts,e)?this.logger.safe.debug("Layout has not changed, skip update"):(this.outputLayouts=e.slice(),this.event("onLayoutsChanged").raise())}storeAvailableBandwidth(e){this.logger.safe.debug(`Set available bandwidth: ${e}`),this.totalBandwidth=e,this.totalBandwidthMax=Math.max(this.totalBandwidthMax,this.totalBandwidth)}},IL=class extends bL{constructor(e,t){super(e,t,2),this.resolutionManager=new yL(this.logger.createChild("BWEControlledResolutionManager"))}getLayouts(){return this.hiFiLayout?[this.loFiLayout,this.hiFiLayout]:[this.loFiLayout]}dispose(){super.dispose(),this.resolutionManager=null}getHighLayoutBandwidth(e){const t=this.inputLayouts?.[0].maxBr||0,i=Math.max(e-t,0);this.logger.safe.debug(`Setting available bandwidth for layouts. High: ${i}, low: ${t||"not set"}, total: ${e}`);const n=this.configProvider.config.specCompliantSimulcast?.allowedBweOvershootRatio||1;return Math.floor(i*n)}recalculateLayouts(){const e=this.hiFiLayout,t=this.getHighLayoutBandwidth(this.totalBandwidth);this.resolutionManager.setAvailableBandwidth(t),this.resolutionManager.setMaxFrameSize(this.inputLayouts[1].maxFs),this.loFiLayout=this.getMinimalLayoutParams(this.inputLayouts),this.hiFiLayout=this.getHighLayoutParams(this.inputLayouts,t,this.loFiLayout),this.loFiLayout=this.adjustLowLayoutBasedOnHighLayout(this.hiFiLayout,this.loFiLayout,e)}adjustLowLayoutBasedOnHighLayout(e,t,i){return this.configProvider.config.useMediaQualityControllerForceKeyFrame&&!e&&i&&(this.logger.safe.debug("Forcing kayframe on low layout due to disabling high layout"),t.keyframe=!0),e?(t.maxBr===e.maxBr&&t.maxBr--,t):t}getPrioritizedLayouts(e){return e.sort(((e,t)=>e.maxFs-t.maxFs?e.maxFs-t.maxFs:e.maxFps-t.maxFps))}getHighLayoutParams(e,t,i){const n=e[1];if(n.maxBr<=t)return this.logger.safe.debug(`High layout bandwidth suits requested caps. Applying as-is: ${JSON.stringify(n)}`),n;const r={...e[1],maxFs:this.resolutionManager.getFrameSize(),maxBr:Math.min(t,e[1].maxBr),maxFps:e[1].maxFps},a=r.maxBr<i.maxBr||r.maxFs<i.maxFs||r.maxFs===i.maxFs&&r.maxFps<=i.maxFps,s=`Potential high layout: ${JSON.stringify(r)}`;return!this.hiFiLayout&&a?(this.logger.safe.debug(`High layout is already disabled. Do nothing. ${s}`),null):this.hiFiLayout&&a?(this.logger.safe.debug(`High layout gets disabled. ${s}`),null):(this.hiFiLayout&&ut(r,this.hiFiLayout)?this.logger.safe.debug(`High layout has not been changed. Do nothing. ${s}`):this.hiFiLayout?this.logger.safe.debug(`High layout updated. ${s}`):this.logger.safe.debug(`High layout enabled. ${s}`),r)}getMinimalLayoutParams(e){const t=Math.min(e[0].maxBr,e[1].maxBr),i=this.configProvider.config.specCompliantSimulcast.maxBrControlEnabled?TL(t,this.totalBandwidth,this.configProvider.config.specCompliantSimulcast.bitrateToBweTable):t;return{...e[0],maxBr:i,maxFps:Math.min(e[0].maxFps,e[1].maxFps),maxFs:Math.min(e[0].maxFs,e[1].maxFs)}}},wL=class extends bL{constructor(e,t,i){super(t,i,1),this.couldLimitFs=e}getLayouts(){return[this.layout]}recalculateLayouts(){let e=this.inputLayouts[0].maxFs;if(this.configProvider.config.specCompliantSimulcast.allowResLimit&&this.couldLimitFs&&this.totalBandwidthMax){const t=this.configProvider.config.specCompliantSimulcast.fsToBweTable;e=((e,t,i=_L)=>EL(e,t,i))(this.inputLayouts[0].maxFs,this.totalBandwidthMax,t)}const t=this.configProvider.config.specCompliantSimulcast.bitrateToBweTable,i=TL(this.inputLayouts[0].maxBr,this.totalBandwidth,t);this.layout={...this.inputLayouts[0],maxFs:e,maxBr:i}}},RL=class extends qe{constructor(e){super(e),this.logger=e,this.logger.safe.debug("Created")}dispose(){this.logger.safe.debug("Disposed"),super.dispose()}setAvailableBandwidth(e){this.logger.safe.debug(`Available bandwidth updated ${e}`)}setLayouts(e,t){this.layouts=e,this.setAvailableBandwidth(t)}getLayouts(){return this.layouts}},AL=class extends qe{constructor(e,t,i,n){super(n),this.supportSingleBwControl=e,this.configProvider=i,this.logger=n,this.multiStream=!1,this.deferredOperation=new SL((()=>this.updateStrategy()),this.configProvider.config.layoutControlTimeout,this.logger.createChild("DeferredOperation")),this.createStrategy(this.multiStream,t)}configure(e){const t=this.isMultiStream(e);this.multiStream!==t&&(this.multiStream=t,this.deferredOperation.invoke(this.multiStream&&!this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled))}setLayouts(e,t){ut(this.latestLayouts,e)&&this.latestBandwidth===t?this.logger.safe.debug("Layouts and bandwidth are not changed. Skipping update"):(this.latestLayouts=e,this.latestBandwidth=t,this.strategy.setLayouts(this.latestLayouts,t))}setAvailableBandwidth(e){this.latestBandwidth!==e?(this.strategy.setAvailableBandwidth(e),this.latestBandwidth=e):this.logger.safe.debug("Bandwidth is not changed. Skipping update")}getLayouts(){return this.strategy.getLayouts()}dispose(){this.strategy.dispose(),this.strategy=null,this.deferredOperation.dispose(),this.deferredOperation=null,super.dispose()}updateStrategy(){this.strategy.dispose(),this.createStrategy(this.multiStream),this.latestLayouts&&this.strategy.setLayouts(this.latestLayouts,this.latestBandwidth)}isMultiStream(e){return e>1}createStrategy(e,t=!1){this.strategy=this.getNewStrategy(e,t),this.strategy.on("onLayoutsChanged",(()=>{this.event("onLayoutsChanged").raise()}))}getNewStrategy(e,t){return e?new IL(this.configProvider,this.logger.createChild("BWEControlledStrategy")):this.configProvider.config.specCompliantSimulcast?.maxBrControlEnabled&&this.supportSingleBwControl?new wL(t,this.configProvider,this.logger.createChild("BWEControlledStrategySingle")):new RL(this.logger.createChild("NoControlStrategy"))}},PL=class extends qe{constructor(e,t){super(t),this.configProvider=e,this.logger=t,this.bandwidthAllocator=null,this.sendBandwidthCalculator=new MN(this.configProvider,this.logger.createChild("SendBandwidthCalculator")),this.layoutProviders=new Map,this.hadLayoutProvider=new Set,this.bandwidthAllocator=function(e,t){const i=new vL(e.createChild("BandwidthAllocator"));return i.setLadder("ScreenShare",t.config.sharingBitrateLadderOverride||mL),i.setLadder("Video",t.config.videoBitrateLadderOverride||fL),i}(this.logger,this.configProvider),this.sendBandwidthCalculator.on("onSendBandwidthChanged",(e=>this.onAvailableBandwidthChanged(e)))}dispose(){this.bandwidthAllocator=null,this.layoutProviders.forEach((e=>e.dispose())),this.layoutProviders.clear(),this.layoutProviders=null,super.dispose()}addReceiver(e,t){this.logger.safe.debug(`Set receiver max capabilities for ${e}: ${JSON.stringify(t)}`),this.configureProviders(e,t.length);const i=t.map((e=>e.maxBr)).reduce(((e,t)=>e+t));this.bandwidthAllocator.addReceiverCapability(e,i);const n=this.bandwidthAllocator.getLayouts();this.layoutProviders.get(e).setLayouts(t,n[e]),this.updateBandwidthDistribution()}removeReceiver(e){this.logger.safe.debug(`Removing receiver for ${e}`),this.layoutProviders.get(e)?.dispose(),this.layoutProviders.delete(e),this.bandwidthAllocator.removeReceiver(e),this.updateBandwidthDistribution()}getLayouts(e){return this.layoutProviders.get(e).getLayouts()}onStatisticsChanged(e){this.sendBandwidthCalculator.onBandwidthChanged(e.estimatedSendBandwidth)}onDiagnosticUpdated(e){e.video?.send?.length&&e.video?.send[0]&&this.sendBandwidthCalculator.onBandwidthChanged(PN(e.video.send[0],this.configProvider))}configureProviders(e,t){if(!this.layoutProviders.has(e)){const t=this.createProvider(e);this.layoutProviders.set(e,t)}this.layoutProviders.get(e).configure(t)}createProvider(e){const t=new AL("Video"===e,!this.hadLayoutProvider.has(e),this.configProvider,this.logger.createChild(`LG:${e}`));return t.on("onLayoutsChanged",(()=>{const i=t.getLayouts();this.logger.safe.debug(`New layouts generated: ${JSON.stringify(i)}`),this.event("onLayoutsUpdated").raise(e)})),this.hadLayoutProvider.add(e),t}onAvailableBandwidthChanged(e){this.bandwidthAllocator.setAvailableBandwidth(e),this.updateBandwidthDistribution()}updateBandwidthDistribution(){const e=this.bandwidthAllocator.getLayouts();for(const[t,i]of Object.entries(e))this.layoutProviders.get(t)?.setAvailableBandwidth(i)}},ML=g;function kL(e,t,i){if("Video"!==e||!i)return i;const{maxBitrate:n,maxResolution:r,maxFramerate:a}=t.config.outgoingVideoLimit??{},s=n??1/0,o=r?(e=>Zw.Send.getResolutionForHeight(e).fs)(r):1/0,l=a??1/0;return s===1/0&&o===1/0&&l===1/0?i:i.map((e=>({...e,maxFs:tt(e.maxFs,o),maxBr:tt(e.maxBr,s),maxFps:tt(e.maxFps,l)})))}var DL=class{constructor(e,t,i,n,r){this.sender=e,this.streamResolution=t,this.maxSimulcastLayerCount=i,this.logger=n,this.configProvider=r}async setCapabilities(e){if(!(0,ML.isEqual)(this.currentCapabilities,e))return this.defaultCapabilities=(0,ML.cloneDeep)(e),this.currentCapabilities=(0,ML.cloneDeep)(e),await this.generateKeyFrameIfNeeded(e),this.applyCapabilities(e,0);this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`)}async updateStreamQualityParams(e,t,i){if(e&&!(0,ML.isEqual)(this.streamResolution,e))return this.logger.safe.debug(`Stream params changed: ${JSON.stringify(e)}@${t}`),this.streamResolution=e,this.applyCapabilities(this.currentCapabilities,i);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async stop(){return this.logger.safe.info("Stopping senders."),this.deactivateSenders()}applyCallConstraints(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.currentCapabilities=kL(this.sender.mediaType,this.configProvider,this.defaultCapabilities),this.applyCapabilities(this.currentCapabilities,3)}getScaleFactor(e){const t=Zw.Send.getResolutionByFs(e),i=this.streamResolution;let n=Math.min(i.width,i.height)/t.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(i)} and new Fs: ${e} as ${n}`),n<1&&(this.logger.safe.error("Scale factor cannot be less than 1! Limiting to 1"),n=1),n}deactivateSenders(){const e=this.sender.rtpSender.getParameters();return e.encodings.forEach((e=>e.active=!1)),this.logger.safe.info(`Stopping senders. Encoding params to set: ${JSON.stringify(e.encodings)}`),this.sender.rtpSender.setParameters(e)}async generateKeyFrameIfNeeded(e){const t=this.sender.rtpSender.getParameters(),i=[];if(e.forEach((e=>{const n=this.getEncondingIndexForRid(e.rid,t.encodings),r=t.encodings[n];e.keyframe&&r.active?(this.logger.safe.info(`Keyframe is needed for encoder with index ${n}`),i.push(n)):this.logger.safe.info(`Keyframe is not needed for index ${n} because encoding is active: ${r.active} or KF is requested: ${e.keyframe}`)})),0===i.length)return void this.logger.safe.info("No keyframes needed. Skipping");const n=this.getParamsForKeyFrame(t,i);return this.logger.safe.info(`Applying keyframe encoding params new: ${JSON.stringify(n.encodings)}, old: ${JSON.stringify(t.encodings)}`),this.sender.rtpSender.setParameters(n)}async applyCapabilities(e,t){if(!e)return void this.logger.safe.info("Capabilities are not set. Do nothing");await this.applyStreamCapabilities(e,t);const i=this.sender.rtpSender.getParameters(),n=(0,ML.cloneDeep)(i);return e.forEach((e=>{const t=this.getEncondingIndexForRid(e.rid,i.encodings);this.updateEncodingsWithCaps(i.encodings[t],e)})),this.updateActiveStates(i,e),this.logger.safe.info(`Encoding params new: ${JSON.stringify(i.encodings)}, old: ${JSON.stringify(n.encodings)}`),this.sender.rtpSender.setParameters(i)}async applyStreamCapabilities(e,t){if(!this.configProvider.config.specCompliantSimulcast?.video?.useApplyConstraints||2===t||!e.length||"Video"!==this.sender.mediaType)return;let i=e[0];for(const t of e)i.maxFs<t.maxFs&&(i=t);e.length>1&&(i=(0,ML.cloneDeep)(i),i.maxFs=Math.max(this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast||0,i.maxFs)),this.streamResolution=await this.sender.applyStreamCapabilities(i)}getEncondingIndexForRid(e,t){if(!e)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const i=t.findIndex((t=>t.rid===e));return i<0||i-1>this.maxSimulcastLayerCount?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):i}updateEncodingsWithCaps(e,t){e?(e.maxBitrate=t.maxBr,e.scaleResolutionDownBy=this.getScaleFactor(t.maxFs),e.maxFramerate=t.maxFps):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(t)}`)}updateActiveStates(e,t){const i=e.encodings.map((e=>e.rid)),n=i.filter((e=>t.some((t=>e===t.rid)))),r=vt(i,n);n.forEach((t=>this.changeEncodingState(e,t,!0))),r.forEach((t=>this.changeEncodingState(e,t,!1)))}changeEncodingState(e,t,i){const n=e.encodings.find((e=>e.rid===t));n?n.active=i:this.logger.safe.error(`Encoding not found for RID: ${t}`)}getParamsForKeyFrame(e,t){const i=(0,ML.cloneDeep)(e);return t.forEach((e=>{i.encodings[e].active&&i.encodings[e].scaleResolutionDownBy&&(i.encodings[e]=this.getEncodingParamsForKeyFrame(i.encodings[e]))})),i}getEncodingParamsForKeyFrame(e){const t=(0,ML.cloneDeep)(e);return t.scaleResolutionDownBy&&(t.scaleResolutionDownBy=1.1*e.scaleResolutionDownBy),t}},OL=class{constructor(e,t,i){this.sender=e,this.logger=t,this.configProvider=i}applyCallConstraints(e){this.logger.safe.info(`[${e}] Applying call constraints`);const t=kL(this.sender.mediaType,this.configProvider,this.currentCapabilities);return this.setCapabilities(t)}async setCapabilities(e){if(0===e.length||1!==e.length)return void this.logger.safe.error("Incorrect number of sender params!");this.currentCapabilities=e;const t=this.currentCapabilities?.find((e=>"1"===e.rid))??this.currentCapabilities?.[0];await this.sender.setParameters(t),await this.sender.start()}updateStreamQualityParams(e,t,i){return this.sender.updateStreamQualityParams(e,t,i)}async stop(){await this.sender.stop()}},NL=g,LL=new Set(["maintain-framerate","maintain-resolution","balanced"]),xL=class{constructor(e,t){this.configProvider=e,this.logger=t}async setActive(e,t){const i=this.getSenderParameters(e);return i.encodings[0].active=t,this.setSenderParameters(e,i,"setActive")}getScaleFactor(e,t){if(!t.width||!t.height)return this.logger.safe.warn("Stream resolution is not set yet. Cannot calculate scale factor. Returning 1"),1;const i=Zw.Send.getResolutionByFs(e);let n=Math.min(t.width,t.height)/i.height;return this.logger.safe.debug(`Scale factor is taken from resolution: ${JSON.stringify(t)} and new Fs: ${e} as ${n}`),n<1&&(this.logger.safe.warn("Scale factor cannot be less than 1! Limiting to 1"),n=1),n}async generateKeyFrameIfNeeded(e,t){if(!t.track)return void this.logger.safe.info("No track attached. Skipping");const i=this.getSenderParameters(t),n=e.filter((e=>e.keyframe)).map((e=>e.rid));if(0!==n.length&&i.encodings.some((e=>e.active)))if(this.configProvider.config.useKeyFrameApi){const e=[];i.encodings.forEach((t=>{!t.active||t.rid&&!n.includes(t.rid)?e.push({keyFrame:!1}):e.push({keyFrame:!0})})),await this.setSenderParameters(t,i,"generateKeyFrameAPI",!0,{encodingOptions:e})}else{const e=i.encodings.map(((e,t)=>e.active?e.rid&&!n.includes(e.rid)?null:{idx:t,factor:e.scaleResolutionDownBy||1}:null)).filter((e=>e));for(const t of e)i.encodings[t.idx].scaleResolutionDownBy=t.factor*this.configProvider.config.forceKeyFrameV2ScaleFactor;this.logger.safe.debug(`Restoring keyframe starting. Update scaleResolutionDownBy for encodings: ${JSON.stringify(i.encodings)}`),await this.setSenderParameters(t,i,"generateKeyFrameStart");const r=this.getSenderParameters(t);for(const t of e)r.encodings[t.idx].scaleResolutionDownBy=t.factor;await this.setSenderParameters(t,r,"generateKeyFrameEnd"),this.logger.safe.debug(`Restoring keyframe completed. Set scaleResolutionDownBy back for encodings: ${JSON.stringify(r.encodings)}`)}else this.logger.safe.info("No keyframes needed. Skipping")}getSenderParameters(e){const t=e.getParameters();if(t.encodings?.length||(t.encodings=[{}]),this.configProvider.config.reuseLastSetParameters&&this.lastSetEncodings){this.logger.safe.info(`Override returned encodings ${JSON.stringify(t.encodings)}`);const e=(0,NL.merge)((0,NL.cloneDeep)(t.encodings),this.lastSetEncodings);this.logger.safe.info(`Overrided encodings ${JSON.stringify(e)}`),t.encodings=e}return t}async setSenderParameters(e,t,i,n=!0,r){try{await e.setParameters(t,r),this.logger.safe.info(`${i}: Parameters applied for sender: encodings: ${JSON.stringify(t.encodings)}, degradationPreference: ${t.degradationPreference}`),this.lastSetEncodings=t.encodings}catch(e){const r=`${i}: setParameters failed. Parameters: ${JSON.stringify(t.encodings)}, error:  ${Be(e)}`;if(this.logger.safe.error(r),n)throw new Error(r)}}getAdjustedBitrate(e,t){let i=e||0;const n=Zw.Send.getResolutionRecord(t.width,t.height);return i=Math.min(i||n.maxBitrate,n.maxBitrate),i}async updateStreamParameters(e,t,i){if(e.getCurrentConstraints().withEffect&&t?.maxFs){const i=Zw.Send.getResolutionByFs(t.maxFs),n={width:i.width,height:i.height};this.logger.safe.info(`Applying video constrains for video effetcs ${JSON.stringify(n)}`),e.resetEffectsOutputConstraints(n)}i&&await e.applyCapabilities(t)}augmentDegradationPreference(e,t){LL.has(t)&&e.degradationPreference!==t&&(e.degradationPreference=t,this.logger.safe.info(`degradationPreference changed to: ${e.degradationPreference}`))}},FL=class{constructor(e,t,i){this.maxSimulcastLayerCount=e,this.configProvider=t,this.logger=i,this.capabiltiesHelper=new xL(this.configProvider,this.logger)}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this.streamResolution=e.getResolution()}setActive(e){return this.capabiltiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,NL.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):(this.defaultCapabilities=(0,NL.cloneDeep)(e),this.currentCapabilities=(0,NL.cloneDeep)(e),await this.applyLastCapabilities(),await this.capabiltiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender))}async updateStreamQualityParams(e,t,i){if(e&&!(0,NL.isEqual)(this.streamResolution,e))return this.streamResolution=e,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(e)}@${t}`),this.applyLastCapabilities();this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(){}async stopSender(){this.logger.safe.info("Stopping senders.");const e=this.capabiltiesHelper.getSenderParameters(this.rtpSender);return e.encodings.forEach((e=>e.active=!1)),this.capabiltiesHelper.setSenderParameters(this.rtpSender,e,"Stopping senders")}async applyLastCapabilities(){if(!this.currentCapabilities)return void this.logger.safe.info("Capabilities are not set. Do nothing");this.currentCapabilities=kL(this.stream.mediaType,this.configProvider,this.defaultCapabilities),await this.applyStreamCapabilities(this.currentCapabilities);const e=this.capabiltiesHelper.getSenderParameters(this.rtpSender),t=(0,NL.cloneDeep)(e);return this.currentCapabilities.forEach((t=>{const i=this.getEncondingIndexForRid(t.rid,e.encodings);this.updateEncodingsWithCaps(e.encodings[i],t)})),this.capabiltiesHelper.augmentDegradationPreference(e,this.configProvider.config.degradationPreference),this.updateActiveStates(e,this.currentCapabilities),this.logger.safe.info(`Encoding params new: ${JSON.stringify(e.encodings)}, old: ${JSON.stringify(t.encodings)}`),this.capabiltiesHelper.setSenderParameters(this.rtpSender,e,"applyCapabilities")}async applyCallConstraints(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities()}async applyStreamCapabilities(e){if("Video"!==this.stream.mediaType||!e.length)return;let t=e[0];for(const i of e)t.maxFs<i.maxFs&&(t=i);e.length>1&&(t=(0,NL.cloneDeep)(t),t.maxFs=Math.max(this.configProvider.config.specCompliantSimulcast.video.minFsForSimulcast||0,t.maxFs));const i=this.configProvider.config.specCompliantSimulcast.video.useApplyConstraints;await this.capabiltiesHelper.updateStreamParameters(this.stream,t,i),i&&(this.streamResolution=this.stream.getResolution())}getEncondingIndexForRid(e,t){if(!e)return this.logger.safe.error("No RID found in incoming params. Returning index 0"),0;const i=t.findIndex((t=>t.rid===e));return i<0||i-1>this.maxSimulcastLayerCount?(this.logger.safe.error("Incorrect index deduced from requested RID. Returning index 0"),0):i}updateEncodingsWithCaps(e,t){e?(e.maxBitrate=t.maxBr,e.scaleResolutionDownBy=this.capabiltiesHelper.getScaleFactor(t.maxFs,this.streamResolution),e.maxFramerate=t.maxFps):this.logger.safe.error(`SenderParams does not exist for caps: ${JSON.stringify(t)}`)}updateActiveStates(e,t){const i=e.encodings.map((e=>e.rid)),n=i.filter((e=>t.some((t=>e===t.rid)))),r=vt(i,n);n.forEach((t=>this.changeEncodingState(e,t,!0))),r.forEach((t=>this.changeEncodingState(e,t,!1)))}changeEncodingState(e,t,i){const n=e.encodings.find((e=>e.rid===t));n?n.active=i:this.logger.safe.error(`Encoding not found for RID: ${t}`)}},UL=class{constructor(e,t){this.configProvider=e,this.logger=t,this.capabiltiesHelper=new xL(this.configProvider,this.logger)}get params(){return this.currentCapabilities?.find((e=>"1"===e.rid))??this.currentCapabilities?.[0]}async applyCallConstraints(e){return this.logger.safe.info(`[${e}] Applying call constraints`),this.applyLastCapabilities(3)}setSender(e){this.rtpSender=e}updateStream(e){this.stream=e,this.streamResolution=e.getResolution()}setActive(e){return this.capabiltiesHelper.setActive(this.rtpSender,e)}async setCapabilities(e){(0,NL.isEqual)(this.currentCapabilities,e)?this.logger.safe.info(`Capabilities already applied: ${JSON.stringify(e)}. Do nothing`):1===e.length?(this.defaultCapabilities=(0,NL.cloneDeep)(e),this.currentCapabilities=(0,NL.cloneDeep)(e),await this.applyLastCapabilities(0),await this.capabiltiesHelper.generateKeyFrameIfNeeded(e,this.rtpSender)):this.logger.safe.error("Incorrect number of sender params!")}async updateStreamQualityParams(e,t,i){if(e&&!(0,NL.isEqual)(this.streamResolution,e))return this.streamResolution=e,this.logger.safe.debug(`Stream params changed: ${JSON.stringify(e)}@${t}`),this.applyLastCapabilities(i);this.logger.safe.debug(`Resolution is not defined or same: ${JSON.stringify(e)}@${t}`)}async startSender(e){this.logger.safe.info(`Replace sender with track: ${e.id}`),await this.rtpSender.replaceTrack(e),this.logger.safe.info("replaceTrack completed"),this.configProvider.config.applySenderParamsBeforeStart&&this.currentCapabilities&&await this.capabiltiesHelper.generateKeyFrameIfNeeded(this.currentCapabilities,this.rtpSender)}async stopSender(){this.logger.safe.info("Replace sender with track: null"),await this.rtpSender.replaceTrack(null),this.logger.safe.info("replaceTrack completed")}async applyLastCapabilities(e){this.currentCapabilities?(this.currentCapabilities=kL(this.stream.mediaType,this.configProvider,this.defaultCapabilities),this.logger.safe.info(`Applying params: ${JSON.stringify(this.params)}`),await this.applyParams(this.params,e),await this.applyBitrate(this.params.maxBr)):this.logger.safe.debug("Capabilities are not yet set, nothing to apply")}applyBitrate(e){let t=e||0;return"Video"===this.stream.mediaType&&(t=this.capabiltiesHelper.getAdjustedBitrate(t,this.streamResolution)),this.setSingleEncodingParameters(this.rtpSender,{maxBitrate:t},"applyBitrate",!1)}async applyParams(e,t){if(this.configProvider.config.useSetParametersToApplyCapabilities)return this.setSingleEncodingParameters(this.rtpSender,{scaleResolutionDownBy:this.capabiltiesHelper.getScaleFactor(e.maxFs,this.streamResolution),maxFramerate:e.maxFps},"applyParams");2!==t&&await this.capabiltiesHelper.updateStreamParameters(this.stream,e,!0)}async setSingleEncodingParameters(e,t,i,n=!0){const r=this.capabiltiesHelper.getSenderParameters(e);return(0,NL.merge)(r.encodings[0],t),0===r.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?r.encodings[0].maxBitrate=void 0:delete r.encodings[0].maxBitrate),this.capabiltiesHelper.augmentDegradationPreference(r,this.configProvider.config.degradationPreference),this.capabiltiesHelper.setSenderParameters(this.rtpSender,r,i,n)}},BL=class{constructor(e,t,i){this.transitionStates=e,this.logger=i,this.stateInternal=t}get state(){return this.stateInternal}isDestinationStateValid(e){return this.transitionStates[this.stateInternal].indexOf(e)>-1}setState(e){return this.isDestinationStateValid(e)?(this.stateInternal=e,!0):(this.logger.safe.info(`Invalid state transition ${this.stateInternal} -> ${e}`),!1)}isCurrentStateMatchedWith(e){return this.stateInternal===e||(this.logger.safe.info(`State does not match. Current: ${this.stateInternal} required: ${e}`),!1)}},VL=g,HL=class{constructor(e,t=document.body){this.logger=e,this.parentElement=t,this.container=this.createContainerElement(),this.video=this.createVideoElement(),this.canvas=this.createCanvasElement(),this.context=this.canvas.getContext("2d"),this.medaiQuery=window.matchMedia("(orientation: portrait)"),this.isPortrait=this.medaiQuery.matches,this.captureFrameRate=30,this.mediaQueryChangeListener=e=>{this.isPortrait=e.matches},this.container.append(this.video,this.canvas),this.parentElement.prepend(this.container),this.medaiQuery.addEventListener("change",this.mediaQueryChangeListener)}modify(e){this.logger.safe.info("modify()"),this.clearAnimationFrames(),this.disposeStream(),this.stream=this.canvas.captureStream(this.captureFrameRate),this.video.srcObject=new MediaStream([e]),this.video.play();let t=e.getSettings(),i=0,n=0;const r=()=>{t=e.getSettings();const a=this.isPortrait?Math.min(t.width,t.height):Math.max(t.width,t.height),s=this.isPortrait?Math.max(t.width,t.height):Math.min(t.width,t.height);i===a&&n===s||(this.canvas.width=a,this.canvas.height=s,i=a,n=s),this.context.drawImage(this.video,0,0,a,s),this.animationFrame=requestAnimationFrame(r)};return this.animationFrame=requestAnimationFrame(r),this.stream.getVideoTracks()[0]}dispose(){this.logger.safe.info("dispose()"),this.clearAnimationFrames(),this.disposeStream(),this.container.parentElement.removeChild(this.container),this.medaiQuery.removeEventListener("change",this.mediaQueryChangeListener)}disposeStream(){this.stream&&(this.stream.getTracks().forEach((e=>e.stop())),this.stream=void 0)}createContainerElement(){const e=document.createElement("div");return e.style.opacity="0",e.style.position="fixed",e.style.zIndex="-2147483648",e.style.pointerEvents="none",e.style.top="0",e.style.left="0",e.style.bottom="0",e.style.right="0",e}createVideoElement(){const e=document.createElement("video");return e.setAttribute("muted",""),e.setAttribute("playsinline",""),e.setAttribute("autoplay",""),e.style.top="0",e.style.left="0",e}createCanvasElement(){const e=document.createElement("canvas");return e.style.right="0",e.style.bottom="0",e}clearAnimationFrames(){this.logger.safe.info("clearAnimationFrames()"),this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=void 0)}},$L=class extends qe{constructor(e){super(e),this.logger=e,this.audioContext=new Ug.window.AudioContext,this.destination=this.audioContext.createMediaStreamDestination(),this.streamNodeMap=new Map,this.logger.safe.info(`Destination stream: ${this.destination.stream.id}, track: ${this.getDestinationTrack().id}`),this.subscribeOnMediaTrackEvents(this.getDestinationTrack())}get numberOfStreams(){return this.streamNodeMap.size}addSourceStream(e){if(!e.rawStream)return;if(this.streamNodeMap.has(e.rawStream))return;const t=e.on("onStreamClientDisposing",(()=>{this.removeSourceStream(e.rawStream),t.dispose()}));this.logger.safe.info(`Add stream: ${e.rawStream.id}, track: ${GL(e.rawStream).id}`),this.addStream(e.rawStream,e.mediaType)}getDestinationTrack(){return GL(this.destination.stream)}dispose(){super.dispose(),this.unsubscribeFromMediaTrackEvents(this.getDestinationTrack());for(const e of this.streamNodeMap.keys())this.removeSourceStream(e);this.audioContext.close(),this.audioContext=null}addStream(e,t="Audio"){const i=this.audioContext.createMediaStreamSource(e);i.connect(this.destination),this.streamNodeMap.set(e,{mediaType:t,sourceNode:i})}removeSourceStream(e){const t=this.streamNodeMap.get(e);t&&(this.logger.safe.info(`Remove stream: ${e.id}, track: ${GL(e).id}`),t.sourceNode.disconnect(),this.streamNodeMap.delete(e))}subscribeOnMediaTrackEvents(e){e.onended=t=>{this.logger.safe.info(`Track ${e.id} ended: ${JSON.stringify(t)}`)},e.onmute=()=>{this.logger.safe.info(`Track ${e.id} muted`)},e.onunmute=()=>{this.logger.safe.info(`Track ${e.id} unmuted`)}}unsubscribeFromMediaTrackEvents(e){e.onended=null,e.onmute=null,e.onunmute=null}};function GL(e){return e.getAudioTracks()[0]}var jL=class{constructor(e){this.logger=e}createBaseInstanse(e){this.imp=new zL,e.addTransform(this.imp)}createWorkerInstanse(e,t){this.imp=new WL(e,t)}mute(e){this.logger.safe.info(`Dropping audio chunks: ${e}`),this.imp.mute(e)}},zL=class{constructor(){this.transformType=1,this.muted=!1}transform(e){return this.muted?null:e}mute(e){this.muted=e}dispose(){}},WL=class extends KN{constructor(e,t){super(e,t,1,void 0)}mute(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"mute",args:[e]}})}},qL=class extends qe{constructor(e,t,i,n,r,a){super(),this.mediaConnection=e,this.contextStream=i,this.logger=n,this.configProvider=r,this.encStreamsManager=a,this.isActive=!1,this.isMuted=!1,this.configProvider.config.renderThroughCanvas&&(this.videoThroughCanvas=new HL(this.logger.createChild("videoThroughCanvas"))),this.stream=t.clone("streamSender ctor"),this.streamResolution=this.stream.getResolution()}get rtpSender(){return this.sender}get trackId(){const e=this.rawTrack;return e?.id}get mediaType(){return this.stream.mediaType}get rawTrack(){return this.audioMixer?.getDestinationTrack()||this.stream.rawTrack}get canvasedRawTrack(){return this.configProvider.config.renderThroughCanvas?"Video"!==this.stream.mediaType?this.rawTrack:this.videoThroughCanvas?.modify(this.rawTrack)??this.rawTrack:this.rawTrack}async init(){this.sender=await this.createSender(),this.isActive=!0,this.addStreamTransforms()}async start(){this.isActive?this.logger.safe.info("Already active. Do nothing"):(this.logger.safe.info("Starting"),this.isActive=!0,await this.wakeSender(),this.params&&await this.applyParams(this.params,0),this.logger.safe.info("Started"))}async stop(){if(this.isActive){if(this.logger.safe.info("Stopping"),this.isActive=!1,"Audio"!==this.stream.mediaType){const e=this.configProvider.config.webrtcDisabledSenderBitrate;await this.applyBitrate(e,!1)}await this.sleepSender(),this.logger.safe.info("Stopped")}else this.logger.safe.info("Already stopped. Do nothing")}setMuted(e,t,i){this.isMuted=e,this.stream.setMuted(e,t),e&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(e),!this.configProvider.config.requestNewStreamOnUnmute||e||i||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(e,t){return this.activateSender(!e,t)}async setMainStream(e){if(this.stream.dispose(),this.stream=e.clone("streamSender setMainStream"),this.streamResolution=this.stream.getResolution(),this.stream.setMuted(this.isMuted),this.params&&await this.applyCapabilities(this.params,1),this.audioMixer?.addSourceStream(this.stream),this.isActive){const e=this.rawTrack?.id;this.logger.safe.info(`Replace sender with track: ${e}`),await this.sender.replaceTrack(this.canvasedRawTrack),this.logger.safe.info("Replace completed")}}async addAdditionalStream(e){if("Audio"===this.stream.mediaType){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&this.setupAudioMixer(),this.audioMixer||this.logger.safe.error(`addAdditionalStream is called when audioMixer is not created. Main stream type is ${this.stream.mediaType}.`),this.audioMixer?.addSourceStream(e),this.audioMuteTransform?.mute(!1),this.configProvider.config.postponeAudioMixerForAudioSharing){if(!this.sender)return void this.logger.safe.error("Sender not created, cannot replace track");this.logger.safe.info(`addAdditionalStream replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.canvasedRawTrack),this.logger.safe.info("addAdditionalStream replace completed")}}else this.logger.safe.error("Not adding additional stream for non-audio stream")}async setParameters(e,t=!1,i=0){if(t||this.params!==e){if(this.params=e,this.isActive)return this.applyParams(this.params,i);this.logger.safe.info("Sender is not active, preserving params")}}dispose(){this.removeSender(),this.cleanUp()}async terminateAsync(){await this.removeSenderAsync(),this.cleanUp()}getActiveStreamIndexes(){return this.getSenderParameters().encodings.filter((e=>e.active)).map((e=>+e.rid))}async updateStreamQualityParams(e,t,i){if(this.configProvider.config.useSetParametersToApplyCapabilities)if(e){if(this.logger.safe.debug(`Stream resolution has changed to ${JSON.stringify(e)}@${t}, re-applying send parameters`),this.streamResolution=e,this.params)return this.setParameters(this.params,!0,i);this.logger.safe.debug("Params are not yet set, do nothing")}else this.logger.safe.debug(`Resolution is not defined: ${JSON.stringify(e)}@${t}`)}async applyStreamCapabilities(e){return await this.stream.applyCapabilities(e),this.stream.getResolution()}async applyParams(e,t){this.logger.safe.info(`Applying params: ${JSON.stringify(e)}`),await this.applyCapabilities(e,t),await this.applyBitrate(e.maxBr),this.params.keyframe&&await this.forceKeyframe()}applyBitrate(e,t=!0){const i=t?this.getAdjustedBitrate(e):e;return this.setEncodingParameters({maxBitrate:i},"applyBitrate")}getAdjustedBitrate(e){let t=e||0;if("Video"===this.stream.mediaType){const e=Zw.Send.getResolutionRecord(this.streamResolution.width,this.streamResolution.height);t=Math.min(t||e.maxBitrate,e.maxBitrate)}return t}async activateSender(e,t){await this.setEncodingParameters({active:e},"activateSender"),this.logger.safe.info(`[${t}] Active state applied isActive = ${e}`)}async forceKeyframe(){if(!this.sender)return this.logger.safe.error("No sender available"),null;if(!this.sender.track)return void this.logger.safe.info("Sender track does not exist, not restoring keyframe");this.logger.safe.info("Restoring keyframe starting");const e=this.getSenderParameters().encodings[0].scaleResolutionDownBy||1;await this.setEncodingParameters({scaleResolutionDownBy:e*this.configProvider.config.forceKeyFrameV2ScaleFactor},"forceKeyframe start"),await this.setEncodingParameters({scaleResolutionDownBy:e},"forceKeyframe end"),this.logger.safe.info("Restoring keyframe finished")}removeSender(){this.logger.safe.info("Removing sender from pc");try{this.mediaConnection.removeSender(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${Be(e)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${Be(e)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.canvasedRawTrack,this.contextStream,lm(this.stream.mediaType))}async wakeSender(){this.logger.safe.info("Wake started"),await this.sender.replaceTrack(this.canvasedRawTrack),this.logger.safe.info("Wake completed")}async sleepSender(){this.logger.safe.info("Sleep started"),await this.sender.replaceTrack(null),this.logger.safe.info("Sleep completed")}addStreamTransforms(){const e=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);e&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new jL(this.logger.createChild("SendAudioPayload")),e.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&e.addTransform(new JN(this.logger.createChild(`SendStreamAnalyzer [${this.stream.mediaType}]`))))}clearStreamTransforms(){this.encStreamsManager.clearTransformsCollection(this.sender)}setupAudioMixer(){this.configProvider.config.enableAudioSharing?"Audio"===this.stream.mediaType?this.configProvider.config.audioSharingMemoryLeakFix&&this.audioMixer?this.logger.safe.debug("Audio mixer already created, not creating new one"):(this.audioMixer=new $L(this.logger.createChild("AudioMixer")),this.audioMixer.addSourceStream(this.stream)):this.logger.safe.error("Not setting up audio mixer for non-audio stream"):this.logger.safe.info("Audio sharing is disabled, not setting up audio mixer")}getSenderParameters(){const e=this.sender.getParameters();return e.encodings?.length||(e.encodings=[{}]),e}async setEncodingParameters(e,t,i=!1){const n=this.getSenderParameters();(0,VL.merge)(n.encodings[0],e),0===n.encodings[0].maxBitrate&&(this.configProvider.config.setParametersMaxBitrateUndefined?n.encodings[0].maxBitrate=void 0:delete n.encodings[0].maxBitrate);try{await this.sender.setParameters(n),this.logger.safe.info(`${t}: Parameters applied for sender: ${JSON.stringify(n.encodings[0])}`)}catch(e){if(this.logger.safe.error(`${t}: setParameters failed: ${Be(e)}, parameters ${JSON.stringify(n.encodings[0])}`),i)throw e}}async applyCapabilities(e,t){this.configProvider.config.useSetParametersToApplyCapabilities?await this.setEncodingParameters({scaleResolutionDownBy:this.getScaleFactor(e.maxFs),maxFramerate:e.maxFps},"applyCapabilities",!0):2!==t&&await this.applyStreamCapabilities(e)}getScaleFactor(e){const t=Zw.Send.getResolutionByFs(e),{width:i,height:n}=this.streamResolution,r=Math.min(i,n)/t.height;return this.logger.safe.debug(`Current stream resolution: ${i}x${n}, scale factor: ${r}`),r<1?(this.logger.safe.warn(`Resolution scale factor is less than 1: ${r}`),1):r}cleanUp(){super.dispose(),this.clearStreamTransforms(),this.sender=null,this.audioMixer?.dispose(),this.stream.dispose(),this.stream=null,this.isActive=!1,this.videoThroughCanvas?.dispose()}},KL=class extends qe{constructor(e,t,i,n,r,a,s){super(),this.mediaConnection=e,this.contextStream=i,this.logger=n,this.configProvider=r,this.encStreamsManager=a,this.capabilitiesManager=s,this.isActive=!1,this.isMuted=!1,this.stream=t.clone("streamSender ctor"),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.updateStream(this.stream)}get rawTrack(){return this.audioMixer?.getDestinationTrack()||this.stream.rawTrack}get trackId(){const e=this.rawTrack;return e?.id}get rtpSender(){throw new Error("rtpSender getter not implemented.")}get mediaType(){throw new Error("mediaType getter not implemented.")}setParameters(e){throw new Error("setParameters not implemented.")}applyStreamCapabilities(e){throw new Error("applyStreamCapabilities not implemented.")}applyCallConstraints(e){return this.capabilitiesManager.applyCallConstraints(e)}async init(){this.sender=await this.createSender(),this.isActive=!0,this.addStreamTransforms(),this.capabilitiesManager.setSender(this.sender)}async start(){this.isActive?this.logger.safe.info("Already active. Do nothing"):(this.logger.safe.info("Starting"),this.isActive=!0,await this.capabilitiesManager.startSender(this.rawTrack),this.logger.safe.info("Started"))}async stop(){this.isActive?(this.logger.safe.info("Stopping"),this.isActive=!1,await this.capabilitiesManager.stopSender(),this.logger.safe.info("Stopped")):this.logger.safe.info("Already stopped. Do nothing")}async setCapabilities(e){this.configProvider.config.applySenderParamsBeforeStart||await this.start(),await this.capabilitiesManager.setCapabilities(e),await this.start()}updateStreamQualityParams(e,t,i){return this.capabilitiesManager.updateStreamQualityParams(e,t,i)}setMuted(e,t,i){this.isMuted=e,this.stream.setMuted(e,t),e&&this.audioMixer&&1!==this.audioMixer.numberOfStreams||this.audioMuteTransform?.mute(e),!this.configProvider.config.requestNewStreamOnUnmute||e||i||this.stream.isActive()||this.event("onNewStreamNeeded").raise()}async setHold(e,t){if(this.configProvider.config.holdSkipActivation)return;const i=!e;this.logger.safe.info(`[${t}] change isActive state to ${i}`);try{return this.capabilitiesManager.setActive(i)}catch(e){const n=this.configProvider.config.holdRetryActivationDelay;if(n>=0)return this.logger.safe.info(`[${t}] retrying after delay of ${n}`),await yi(n),this.logger.safe.info(`[${t}] change isActive state to ${i}, second attempt`),this.capabilitiesManager.setActive(i);throw e}}async setMainStream(e){return this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=e.clone("streamSender setMainStream"),this.stream.setMuted(this.isMuted),this.audioMixer?.addSourceStream(this.stream),this.isActive&&(this.logger.safe.info(`Replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("Replace completed")),this.capabilitiesManager.updateStream(this.stream),this.subscribeOnStreamClientMuted(),this.capabilitiesManager.applyLastCapabilities(1)}async addAdditionalStream(e){if("Audio"===this.stream.mediaType){if(this.configProvider.config.postponeAudioMixerForAudioSharing&&this.setupAudioMixer(),this.audioMixer||this.logger.safe.error(`addAdditionalStream is called when audioMixer is not created. Main stream type is ${this.stream.mediaType}.`),this.audioMixer?.addSourceStream(e),this.audioMuteTransform?.mute(!1),this.configProvider.config.postponeAudioMixerForAudioSharing){if(!this.sender)return void this.logger.safe.error("Sender not created, cannot replace track");this.logger.safe.info(`addAdditionalStream replace sender with track: ${this.rawTrack?.id}`),await this.sender.replaceTrack(this.rawTrack),this.logger.safe.info("addAdditionalStream replace completed")}}else this.logger.safe.error("Not adding additional stream for non-audio stream")}dispose(){this.removeSender(),this.cleanUp()}async terminateAsync(){await this.removeSenderAsync(),this.cleanUp()}getActiveStreamIndexes(){return this.getSenderParameters().encodings.filter((e=>e.active)).map((e=>+e.rid))}removeSender(){this.logger.safe.info("Removing sender from pc");try{this.mediaConnection.removeSender(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${Be(e)}`)}}async removeSenderAsync(){this.logger.safe.info("Removing sender from pc");try{await this.mediaConnection.removeSenderAsync(this.sender)}catch(e){this.logger.safe.warn(`Error removing sender: ${Be(e)}`)}}async createSender(){return this.configProvider.config.postponeAudioMixerForAudioSharing||this.setupAudioMixer(),this.mediaConnection.createSender(this.rawTrack,this.contextStream,lm(this.stream.mediaType))}addStreamTransforms(){const e=this.encStreamsManager.initTransformsCollection(this.sender,"Sender",this.stream.mediaType);e&&("Audio"===this.stream.mediaType?this.configProvider.config.useInsertableStreams?.audioExtendedMute&&(this.audioMuteTransform=new jL(this.logger.createChild("SendAudioPayload")),e.addTransform(this.audioMuteTransform)):this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&e.addTransform(new JN(this.logger.createChild(`SendStreamAnalyzer [${this.stream.mediaType}]`))))}clearStreamTransforms(){this.encStreamsManager.clearTransformsCollection(this.sender)}setupAudioMixer(){this.configProvider.config.enableAudioSharing?"Audio"===this.stream.mediaType?this.configProvider.config.audioSharingMemoryLeakFix&&this.audioMixer?this.logger.safe.debug("Audio mixer already created, not creating new one"):(this.audioMixer=new $L(this.logger.createChild("AudioMixer")),this.audioMixer.addSourceStream(this.stream)):this.logger.safe.error("Not setting up audio mixer for non-audio stream"):this.logger.safe.info("Audio sharing is disabled, not setting up audio mixer")}getSenderParameters(){const e=this.sender.getParameters();return e.encodings?.length||(e.encodings=[{}]),e}subscribeOnStreamClientMuted(){this.configProvider.config.recoverOnStreamUnmute&&(this.onStreamClientMutedSubscription=this.stream.on("onStreamClientMuted",(async(e,t)=>{t||await this.capabilitiesManager.applyLastCapabilities(1)})))}cleanUp(){super.dispose(),this.clearStreamTransforms(),this.sender=null,this.audioMixer?.dispose(),this.stream.dispose(),this.onStreamClientMutedSubscription?.dispose(),this.stream=null,this.isActive=!1}},JL=class e extends qe{constructor(t,i,n,r,a,s,o,l,c,d){super(),this.mediaConnection=t,this.mainStream=i,this.contextStream=n,this.mediaType=r,this.serialQueue=a,this.logger=s,this.configProvider=o,this.isAlwaysActive=l,this.encStreamsManager=c,this.simulcastContext=d,this.isMuted=!1,this.isHold=!1,this.previousParameters=[],this.state=new BL(e.transitionStates,"NotStarted",this.logger),this.pendingStream=null,this.pendingParams=null,this.subscribeOnQualityUpdates(this.mainStream)}async start(){this.state.setState("Started")&&(this.sender=this.createSenderModel(),await this.sender.init(),this.notifyMaxVideoSendCapabilitiesChanged(),this.configProvider.config.deactiveAudioSender&&"Audio"===this.mediaType&&await this.sender.stop(),this.subscribeForSenderEvents())}async activate(){this.state.setState("Active")&&(this.pendingStream&&(await this.updateStreamInternal(this.pendingStream),this.pendingStream=null),this.isAlwaysActive&&!this.isMuted&&"Audio"===this.mediaType&&await this.sender.start(),this.isAlwaysActive?(this.event("onSendersChanged").raise(this,!0),this.logger.safe.info("Sender set to always active. Do not stopping")):await this.capabilitiesManager.stop(),this.configProvider.config.enableCachingFMTP&&this.pendingParams&&(this.logger.safe.info("Apply pending parameters"),await this.updateParametersInternal(this.pendingParams),this.pendingParams=null))}updateStream(e){return this.updateStreamInternal(e)}async addAdditionalStream(e){return this.sender.addAdditionalStream(e)}async updateParameters(e){if(this.state.isCurrentStateMatchedWith("Active"))return this.updateParametersInternal(e);this.configProvider.config.enableCachingFMTP?(this.logger.safe.info("Postpone params update until sender is activated"),this.pendingParams=e):this.logger.safe.warn("Ignore params update as sender is not activate")}async terminateAsync(){this.state.setState("Disposed")&&(this.logger.safe.info("Terminating async"),await this.sender.terminateAsync(),this.cleanUp())}dispose(){this.state.setState("Disposed")&&(this.logger.safe.info("Disposing"),this.sender.dispose(),this.cleanUp())}async setHold(e,t){if(this.isHold!==e)return this.logger.safe.info(`[${t}] Setting hold to: ${e}`),this.isHold=e,this.sender.setHold(e,t);this.logger.safe.info(`[${t}] Already in hold=${e} state`)}setMuted(e,t,i){this.logger.safe.info(`[${t}] Setting muted to: ${e}`),this.isMuted=e,this.sender.setMuted(this.isMuted,t,i),!this.isMuted&&"Audio"===this.mediaType&&this.state.isCurrentStateMatchedWith("Active")&&this.sender.start()}getActiveStreamIndexes(){return this.sender?this.sender.getActiveStreamIndexes():[]}getTrackInfo(){return{modality:lm(this.mediaType),trackId:this.sender.trackId}}applyCallConstraints(e){return this.capabilitiesManager.applyCallConstraints(e)}createSenderModel(){if(this.configProvider.config.useSenderV2){const e=new KL(this.mediaConnection,this.mainStream,this.contextStream,this.logger.createChild("SenderV2"),this.configProvider,this.encStreamsManager,this.getCapabilitiesManagerV2(this.simulcastContext));return this.capabilitiesManager=e,e}const e=new qL(this.mediaConnection,this.mainStream,this.contextStream,this.logger.createChild("Sender"),this.configProvider,this.encStreamsManager);return this.capabilitiesManager=this.getCapabilitiesManager(e,this.simulcastContext),e}subscribeForSenderEvents(){this.sender.on("onNewStreamNeeded",(()=>this.event("onNewStreamNeeded").raise()))}getCapabilitiesManager(e,t){return t?.shouldUseSimulcast()?new DL(e,this.mainStream.getResolution(),t.config.layerScaleFactors.length,this.logger.createChild("SimCapMgr"),this.configProvider):new OL(e,this.logger.createChild("SnglCapMgr"),this.configProvider)}getCapabilitiesManagerV2(e){return e?.shouldUseSimulcast()?new FL(e.config.layerScaleFactors.length,this.configProvider,this.logger.createChild("SimCapMgrV2")):new UL(this.configProvider,this.logger.createChild("SnglCapMgrV2"))}async updateStreamInternal(e){return this.state.isCurrentStateMatchedWith("Active")?this.mainStream!==e?(this.logger.safe.debug(`Switching streams: ${this.mainStream.parentId}:${this.mainStream.id} -> ${e.parentId}:${e.id}`),this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=e,this.subscribeOnQualityUpdates(this.mainStream),this.notifyMaxVideoSendCapabilitiesChanged(),await this.sender.setMainStream(this.mainStream),this.capabilitiesManager.updateStreamQualityParams(this.mainStream.getResolution(),this.mainStream.getFrameRate(),1)):void this.logger.safe.info("Stream has not been changed. Skipping update"):(this.logger.safe.info("Postponing stream update until sender is activated"),void this.setPendingStream(e))}async updateParametersInternal(e){await this.capabilitiesManager.setCapabilities(e),function(e,t,i){const n=[];return e.forEach((e=>{t.some((t=>i(e,t)))||n.push(e)})),0===n.length&&e.length===t.length}(this.previousParameters,e,((e,t)=>e.ssrc===t.ssrc))||(this.previousParameters=e,this.event("onSendersChanged").raise(this,!0))}setPendingStream(e){this.pendingStream=e;const t=e.on("onStreamClientDisposing",(()=>{this.pendingStream===e&&(this.pendingStream=null,t.dispose())}))}subscribeOnQualityUpdates(e){this.sub=e.on("onStreamQualityChanged",((e,t,i,n)=>this.updateStreamQualityParams(t,i,n)))}updateStreamQualityParams(e,t,i){return i===mh.EffectQualityChangeReason.Performance&&this.notifyMaxVideoSendCapabilitiesChanged({resolution:e,fps:t}),this.capabilitiesManager.updateStreamQualityParams(e,t,2)}unsubscribeFromQualityEvents(){this.sub?.dispose(),this.sub=null}notifyMaxVideoSendCapabilitiesChanged(e){if(!["Video","ScreenShare"].includes(this.mediaType))return;const{width:t,height:i}=e?.resolution??this.mainStream.getResolution(),n=e?.fps??this.mainStream.getFrameRate();if(!t||!i||!n)return;const r=new Yw(t,i),a={maxFs:r.fs,maxMbps:r.fs*n,maxFps:n,maxWidth:r.width,maxHeight:r.height};this.logger.safe.info(`Capabilities for ${this.mediaType} stream: ${JSON.stringify(a)}`),this.event("onMaxVideoSendCapabilitiesChanged").raise(a)}cleanUp(){this.unsubscribeFromQualityEvents(),this.mainStream.dispose(),this.mainStream=null,this.pendingStream&&this.pendingStream.dispose(),this.pendingStream=null,this.sender=null,this.contextStream=null,this.event("onSendersChanged").raise(this,!1),super.dispose()}};JL.transitionStates={NotStarted:["Started","Disposed"],Started:["Active","Disposed"],Active:["NotStarted","Disposed"],Disposed:[]},v([cA()],JL.prototype,"start",1),v([cA()],JL.prototype,"activate",1),v([cA()],JL.prototype,"updateStream",1),v([cA()],JL.prototype,"addAdditionalStream",1),v([cA()],JL.prototype,"updateParameters",1),v([cA()],JL.prototype,"terminateAsync",1),v([cA()],JL.prototype,"setHold",1),v([cA()],JL.prototype,"updateStreamQualityParams",1);var YL=JL,QL=class extends qe{constructor(e,t,i,n,r,a,s,o){super(t),this.mediaManager=e,this.logger=t,this.callDeviceManager=i,this.configProvider=n,this.statisticsGatherer=r,this.diagnostics=a,this.isMultiparty=s,this.encStreamsManager=o,this.senders=new Map,this.previousMediaModalitites={Audio:!1,Video:!1,ScreenShare:!1},this.serialQueue=new Hw(this.logger),this.muted=new Map([["Audio",!1],["Video",!1]]),this.subs=new Map,this.senderId=0,this.callConstraintsCauseId=void 0,this.streamsProvider=new pL(i,n,this.serialQueue,this.logger.createChild("StreamsProvider")),this.subscribeToStreamProviderEvents(),this.localVideoStreamWatcher=new BN(this.logger,this.configProvider,this.callDeviceManager),this.statisticsGatherer.on("onDiagnosticUpdated",(e=>this.onDiagnosticUpdated(e))),this.statisticsGatherer.on("onStatisticsChanged",(e=>this.onStatisticsChanged(e))),this.subscribeToStreamWatcherEvents(),this.configProvider.config.useMediaQualityController&&(this.mediaQualityController=new PL(this.configProvider,this.logger.createChild("MQC")),this.mediaQualityController.on("onLayoutsUpdated",(e=>this.updateLayouts(e))))}onStatisticsChanged(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation||this.mediaQualityController?.onStatisticsChanged(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher||this.localVideoStreamWatcher?.onStatisticsChanged(e)}onDiagnosticUpdated(e){this.configProvider.config.diagnostics.features.useNewSendBandwidthCalculation&&this.mediaQualityController?.onDiagnosticUpdated(e),this.configProvider.config.diagnostics.features.useNewStatsForLocalVideoStreamWatcher&&this.localVideoStreamWatcher?.onDiagnosticUpdated(e)}dispose(){this.senders.forEach(((e,t)=>{this.event("onSendStreamChanged").raise(null,t),this.configProvider.config.disposeSendersSync?e.dispose():e.terminateAsync()})),this.senders.clear(),this.subs.forEach((e=>e.forEach((e=>e.dispose())))),this.subs.clear(),this.mediaConnection=null,this.unsubscribeFromStreamProviderEvents(),this.configProvider.config.disposeStreamsSync?this.streamsProvider.stop():this.streamsProvider.stopAsync(),this.streamsProvider=null,this.localVideoStreamWatcherSubs?.dispose(),this.localVideoStreamWatcher?.dispose(),this.localVideoStreamWatcher=null,this.mediaManager=null,this.logger=this.logger.createChild("DISPOSED"),this.mediaQualityController?.dispose(),this.mediaQualityController=null,super.dispose()}registerRtpSenderManager(e){this.mediaConnection=e}useNullAudioStreamClient(){this.streamsProvider.useNullAudioStreamClient()}async update(e,t,i,n){n?.mark("startUpdateStreams");const r=am(e),a=await this.updateStreams(r,t);return n?.markAndMeasure("startUpdateStreams","updateStreamsWithModalities"),await this.updateSenders(),n?.markAndMeasure("updateStreamsWithModalities","updateSenders"),this.applyMuteState(i,!0),this.setAndUpdateLocalTracksInfo(!1),this.previousMediaModalitites=ot(a),sm(e,this.previousMediaModalitites)}async activate(e){this.logger.info(`[${e}] activate senders`),await Promise.all([...this.senders.values()].map((async e=>e.activate())))}applyCallConstraints(e){const t=this.senders.get("Video");return t?t.applyCallConstraints(e):(this.logger.info(`[${e}] Caching call constraints until sender is created`),this.callConstraintsCauseId=e,this.applyCallConstraintsDeferred=km(),this.applyCallConstraintsDeferred.promise)}async applyCapabilities(e,t,i){this.logger.safe.info(`[${e}] Applying incoming ${t} FMTP: ${JSON.stringify(i)}`);const n=om(t);this.lastCauseId=e;let r=i;return this.mediaQualityController&&(this.mediaQualityController.addReceiver(n,i),r=this.mediaQualityController.getLayouts(n)),this.updateParameters(e,n,r)}getLocalMediaSources(){const e=this.getTracksInfo(),t=[];return e.forEach((e=>{t.some((t=>t.modality===e.modality))||t.push({sourceId:this.getSourceIdForTrack(e),modality:e.modality})})),t}setMuted(e,t,i){this.muted.set(e,t),this.applyMuteState(i,!1)}async setHold(e,t){await Promise.all([...this.senders.values()].map((async i=>i.setHold(e,t))))}async updateParameters(e,t,i){try{await this.applyCapabilitiesForMediaType(t,i),this.logger.safe.debug(`[${e}] Capabilities completed`);const n={modality:lm(t),causeId:e,capabilities:i};this.statisticsGatherer.onMaxCapabilitiesApplied(n),this.diagnostics?.onMaxCapabilitiesApplied(n)}catch(n){const r=Be(n);this.logger.safe.error(`[${e}] Error applying capabilities ${r}`);const a={modality:lm(t),causeId:e,capabilities:i,error:r};this.statisticsGatherer.onMaxCapabilitiesApplied(a),this.diagnostics?.onMaxCapabilitiesApplied(a)}}async applyCapabilitiesForMediaType(e,t){const i=this.senders.get(e);if(i)return i.updateParameters(t);this.logger.safe.info(`[${this.lastCauseId}] Capabilities ignored ${JSON.stringify(t)} ignored, no sender for media type ${JSON.stringify(e)}`)}applyMuteState(e,t){for(const[i,n]of this.muted)this.senders.get(i)&&this.senders.get(i).setMuted(n,e,t)}setAndUpdateLocalTracksInfo(e){const t=this.getTracksInfo();this.mediaManager.setLocalTracksInfo(t),e&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statisticsGatherer.updateStatsWithLocalSsrcTrackInfo())}getTracksInfo(){const e=[];return this.senders.forEach((t=>{e.push(t.getTrackInfo())})),e}async updateStreams(e,t){const i=await this.streamsProvider.update(e,t);return this.logger.safe.info(`Streams updated, modalities requested: ${JSON.stringify(e)}, result: ${JSON.stringify(i)}`),i}async updateSenders(){await this.streamsProvider.ensureUpdateCompleted();const e=cm(this.streamsProvider.streams);await Promise.all(st(e).map((async t=>{const i=e[t];if(i===this.previousMediaModalitites[t])return void this.logger.safe.info(`Sender for mediaType: ${JSON.stringify(t)} are not changed. enabled=${i}`);if(!i)return this.logger.safe.info(`Removing sender for mediaType: ${JSON.stringify(t)}`),void await this.removeSender(t);const n=this.streamsProvider.streams[t];if(await this.createAndStartSender(n,t),this.logger.safe.info(`Sender for mediaType: ${JSON.stringify(t)} is added`),this.applyCallConstraintsDeferred&&"Video"===t){const e=this.senders.get("Video");try{await e.applyCallConstraints(this.callConstraintsCauseId),this.applyCallConstraintsDeferred.resolve()}catch(e){this.applyCallConstraintsDeferred.reject(e)}this.applyCallConstraintsDeferred=void 0,this.callConstraintsCauseId=void 0}await this.addAudioSharingStream(n),this.event("onSendStreamChanged").raise(n,t)}))),this.logger.safe.info("Senders updated")}createAndStartSender(e,t){if(this.senders.get(t))return this.logger.safe.error(`Sender already created, modality: ${JSON.stringify(t)}`),this.senders.get(t).start();const i=this.mediaManager.getMediaEntitiesByModality(lm(t))[0],n=i?.getSimulcastContext(),r="Audio"===t||!this.isMultiparty||!!n?.shouldUseSimulcast(),a=new YL(this.mediaConnection,e,new MediaStream,t,this.serialQueue,this.logger.createChild(`Sender_${JSON.stringify(t)}:${this.senderId++}`),this.configProvider,r,this.encStreamsManager,n);this.senders.set(t,a);const s=[a.on("onSendersChanged",((e,t)=>this.onSenderStateChanged(e,t))),a.on("onNewStreamNeeded",(()=>this.streamsProvider.requestStreamUpdate(t,!0))),a.on("onMaxVideoSendCapabilitiesChanged",(e=>this.event("onMaxVideoSendCapabilitiesChanged").raise(t,e)))];return this.subs.set(a,s),a.start()}async removeSender(e){const t=this.senders.get(e);t&&(this.senders.delete(e),this.event("onSendStreamChanged").raise(null,e),await t.terminateAsync(),this.subs.get(t).forEach((e=>e.dispose())),this.subs.delete(t),this.logger.safe.info(`Removed sender with mediaType: ${JSON.stringify(e)}`)),this.mediaQualityController?.removeReceiver(e)}async updateLayouts(e){const t=this.mediaQualityController.getLayouts(e);return this.logger.safe.debug(`Update layouts for ${e}: ${JSON.stringify(t)}`),this.updateParameters(this.lastCauseId,e,t)}getSourceIdForTrack(e){const t=e.trackId,i=this.mediaManager.getMediaEntityByLocalTrackId(t);return i?(this.logger.safe.info(`Media entity found: ${JSON.stringify(i.getXSourceStreamId())}`),i.getXSourceStreamId()):(this.logger.safe.error(`Media entity is not found for stream: ${JSON.stringify(t)}`),0)}subscribeToStreamProviderEvents(){this.streamProviderSubscriptions=[this.streamsProvider.on("onStreamAdded",(e=>this.onStreamUpdated(e,!1))),this.streamsProvider.on("onStreamUpdated",(e=>this.onStreamUpdated(e,!0)))]}unsubscribeFromStreamProviderEvents(){this.streamProviderSubscriptions.forEach((e=>e.dispose())),this.streamProviderSubscriptions=null}subscribeToStreamWatcherEvents(){this.localVideoStreamWatcherSubs=this.localVideoStreamWatcher.on("onVideoCaptureFreeze",((e,t)=>{e||(t?this.diagnostics.registerWebcamFreeze():this.diagnostics.registerProcessedStreamFreeze()),this.event("onVideoCaptureFreeze").raise(e)}))}async onStreamUpdated(e,t){if(!this.senders.has(e))return void this.logger.safe.warn(`Sender with media type ${e} does not exist, do not update media stream`);let i=this.streamsProvider.streams[e];if(i||(this.logger.safe.info(`Stream is missing for mediaType: ${e}, using fake stream...`),i=new uL(e,this.logger.createChild("NullStreamClient"))),i.isDisposed())return void this.logger.safe.info(`Stream is already disposed for mediaType: ${e}`);this.event("onSendStreamChanged").raise(i,e);const n=this.senders.get(e);await this.addAudioSharingStream(i),await n.updateStream(i),this.setAndUpdateLocalTracksInfo(t)}onSenderStateChanged(e,t){if(this.mediaManager&&this.mediaManager.updateMediaEntitiesWithActivityState(e.mediaType,e.getActiveStreamIndexes()),this.statisticsGatherer.onSendersChanged(e.mediaType,t),"Video"===e.mediaType)if(t){const e=this.getTracksInfo().filter((e=>e.modality===Qe.MODALITY.video));this.localVideoStreamWatcher.startWatching(e)}else this.localVideoStreamWatcher.stopWatching()}async addAudioSharingStream(e){"ScreenShare"===e.mediaType&&e.hasAudio()&&(this.logger.safe.info("Adding audio stream from sharing to audio sender"),await(this.senders.get("Audio")?.addAdditionalStream(e)))}},ZL=class{constructor(e,t,i,n,r){this.pc=e,this.cryptoMethod=t,this.logger=i,this.configProvider=n,this.stateChangedCallback=r,this.logger=i.createChild("TransportStateProvider"),this.subscribeForConnectionState()}get hasPcConnectionState(){return"connectionState"in this.pc&&this.configProvider.config.useConnectionState}subscribeForConnectionState(){this.pc.oniceconnectionstatechange=()=>{this.logger.safe.info(`RTCPeerConnection oniceconnectionstatechange iceConnectionState: ${this.pc.iceConnectionState} pc.signalingState: ${this.pc.signalingState}`),this.shouldRaise(0)&&this.stateChangedCallback(this.pc.iceConnectionState)},1===this.cryptoMethod&&this.hasPcConnectionState&&(this.pc.onconnectionstatechange=()=>{this.logger.safe.info(`RTCPeerConnection onconnectionStatechange connectionState: ${this.pc.connectionState} pc.signalingState: ${this.pc.signalingState}`),this.shouldRaise(1)&&this.stateChangedCallback(this.pc.connectionState)})}subscribeForDtlsTransportState(){if(!this.configProvider.config.useDtlsTrasportConnectionCheck||this.transport||1!==this.cryptoMethod||this.hasPcConnectionState)return;const e=this.pc.getReceivers().find((e=>!!e.transport));this.transport=e&&e.transport,this.transport&&(this.transport.onstatechange=()=>{this.logger.safe.info(`RTCDtlsTransport onstatechange state: ${this.transport.state} pc.signalingState: ${this.pc.signalingState}`),this.shouldRaise(2)&&this.stateChangedCallback(this.transport.state)})}dispose(){this.pc.oniceconnectionstatechange=null,this.transport&&(this.transport.onstatechange=null,this.transport=null),this.pc.onconnectionstatechange&&(this.pc.onconnectionstatechange=null),this.pc=null,this.stateChangedCallback=null}shouldRaise(e){switch(e){case 2:if(1!==this.cryptoMethod)throw new Error(`DTLS transport is used with cryptoMethod=${this.cryptoMethod}`);return!this.configProvider.config.ignoreClosedDtlsTransportState||"closed"!==this.transport.state;case 1:return 1===this.cryptoMethod&&!this.transport;case 0:return!(!this.configProvider.config.ignoreClosedDtlsTransportState||!this.transport||"closed"!==this.pc.iceConnectionState)||0===this.cryptoMethod||!this.transport&&!this.hasPcConnectionState||this.transport&&"disconnected"===this.pc.iceConnectionState||"connected"===this.transport?.state&&"connected"===this.pc.iceConnectionState;default:return this.logger.safe.error(`unknown StateMethod=${e}`),!1}}},XL=class{constructor(e,t,i,n,r){this.recvStream=e,this.mainTrack=t,this.receiveStreamCollection=i,this.logger=n,this.settings=r,this.removeOtherTracks(t),this.subscribeOnStreamEvents()}get stream(){return this.recvStream.getMediaStream()}dispose(){this.unsubscribeFromStreamEvents(),this.receiveStreamCollection=null,this.mainTrack=null,this.recvStream.dispose()}getId(){return this.recvStream.getId()}getModality(){return this.recvStream.getModality()}getMsi(){return this.recvStream.getMsi()}getMediaStream(){return this.stream}getReceiver(){return this.recvStream.getReceiver()}requestSource(e){return this.recvStream.requestSource(e)}getSourceStreamId(){return this.recvStream.getSourceStreamId()}removeOtherTracks(e){this.settings.onAddTrackRemoveOtherTracks&&this.stream.getTracks().forEach((t=>{t.id!==e.id&&this.stream.removeTrack(t)}))}subscribeOnStreamEvents(){const e=e=>this.logger.safe.info(`${e} track: ${this.mainTrack.id}, stream: ${this.stream.id}`);this.stream.onremovetrack=()=>{e("onremovetrack"),this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onended=()=>{e("onended"),this.settings.removeRecvStreamOnEnded&&this.receiveStreamCollection.remove(this.stream.id)},this.mainTrack.onmute=()=>e("onmute"),this.mainTrack.onunmute=()=>e("onunmute")}unsubscribeFromStreamEvents(){this.stream.onremovetrack=null,this.mainTrack.onended=null,this.mainTrack.onmute=null,this.mainTrack.onunmute=null}},ex=class{constructor(e){this.startTimestamp=0,this.totalTime=0,this.lastActiveTime=0,this.id=e}},tx=class{constructor(e){this.speakersHistory=[],this.sources=[],this.configProvider=e.configProvider,this.ping=this.setupTimer()}setSources(e=[]){const t=e.map(this.getOrCreateSource.bind(this)),i=this.excludeSources(this.sources,t);t.forEach((e=>{this.isAlreadyActive(e)||this.updateSourceTimestamp(e),this.updateSourceLastActiveTime(e)})),i.forEach((e=>{this.updateTotalTime(e),this.resetStartTimestamp(e)})),this.ping||(this.ping=this.setupTimer())}setOnDominantSpeakerChanged(e){this.callback=e}dispose(){this.clearTimer(),this.sources=null,this.callback=null}excludeSources(e,t){return e.filter((e=>!t.some((t=>e.id===t.id))))}trigger(){if(!this.hasAnyoneSpoken())return void this.clearTimer();const e=this.sources.map(this.updateTotalTime).sort(((e,t)=>t.totalTime-e.totalTime||t.lastActiveTime-e.lastActiveTime)).map((e=>e.id)).slice(0,this.configProvider.config.ovcMaxCount);e.length&&!ut(this.speakersHistory,e)&&(this.speakersHistory=e,this.callback&&this.callback(this.speakersHistory,"client")),this.sources.map(this.resetTotalTime).filter(this.isAlreadyActive).forEach(this.updateSourceTimestamp)}isAlreadyActive(e){return!!e.startTimestamp}setupTimer(){return window.setInterval(this.trigger.bind(this),this.configProvider.config.activeSpeaker.timeToPromote)}clearTimer(){this.ping&&(clearInterval(this.ping),this.ping=null)}getOrCreateSource(e){if(this.isExist(e))return this.sourceById(e);{const t=new ex(e);return this.sources.push(t),t}}isExist(e){return this.sources.some((t=>e===t.id))}hasAnyoneSpoken(){return this.sources.some((e=>0!==e.startTimestamp||0!==e.totalTime))}sourceById(e){return this.sources.find((t=>e===t.id))}updateSourceTimestamp(e){e.startTimestamp=Date.now()}updateSourceLastActiveTime(e){e.lastActiveTime=Date.now()}updateTotalTime(e){return e.startTimestamp&&(e.totalTime+=Date.now()-e.startTimestamp),e}resetStartTimestamp(e){return e.startTimestamp=0,e}resetTotalTime(e){return e.totalTime=0,e}},ix=class{constructor(e){this.modifierList=e}modify(e){for(const t of this.modifierList)t.modify(e)}},nx=class{constructor(e,t,i,n){this.context=e,this.mediaManager=t,this.modalities=i,this.cname=n}build(e){switch(e.sdpSource){case 0:return new ix([new qP(this.context.configProvider),new RP(this.context.configProvider),new nM(this.mediaManager,this.context.configProvider),new iM(this.mediaManager),new FP(this.context.configProvider),new OP(this.context.configProvider),new MP(this.mediaManager,this.context.configProvider,e.sdpType),new PP(this.mediaManager,this.context.configProvider),new pM(this.context.configProvider,e.sdpType)]);case 2:return new ix([new cP(this.mediaManager,this.modalities),new AP,new dP(this.mediaManager,!0),new QP(this.context.configProvider,this.mediaManager),new vP(this.modalities,this.mediaManager),new VP,new xP,new UP,new BP(this.context.configProvider),new LP(this.context.configProvider),new WP(this.context.configProvider),new yP,new oP(this.context),new eM(this.mediaManager),new wP(this.context.configProvider),new lM,new oM(this.context.configProvider),new rM(this.context.configProvider),new EP(this.mediaManager,this.modalities,this.context.configProvider),new fP(this.context),new cM(this.context.configProvider),new gP(this.context.configProvider),new MP(this.mediaManager,this.context.configProvider,e.sdpType),new kP(this.mediaManager,this.context.configProvider,e.sdpType),new $P(this.context.configProvider,this.context.getLogger()),new _P,new uM(this.context.configProvider),new JP(this.context.configProvider)]);case 1:return new ix([new hP(this.context,this.modalities.data),new dP(this.mediaManager,!1),new TP(this.context.configProvider),new cP(this.mediaManager,this.modalities),new CP(this.mediaManager),new xP,new NP(this.context.configProvider),new lP(this.mediaManager,"offer"===e.sdpType,this.context.configProvider),new tM(this.mediaManager,this.context.getLogger()),new sM(this.context.configProvider,this.mediaManager),new SP(this.context.config.isConference,this.cname),new bP(this.mediaManager),new IP,new KP(this.context.configProvider),new mP(this.context.configProvider),new dM(this.context.configProvider),new hM(this.context.configProvider),new kP(this.mediaManager,this.context.configProvider,e.sdpType),new zP(this.mediaManager,this.context.configProvider,e.sdpType),new JP(this.context.configProvider)])}}},rx=class{constructor(e){this.context=e,this.cname=dt()}toLocal(e,t,i){return this.modify({sdpSource:0,sdpType:i},e,t)}toOffer(e,t,i){return this.modify({sdpSource:1,sdpType:"offer"},e,t,i)}toAnswer(e,t,i){return this.modify({sdpSource:1,sdpType:"answer"},e,t,i)}toRemote(e,t,i,n){return this.modify({sdpSource:2,sdpType:n},e,t,i)}modify(e,t,i,n){const r=new nx(this.context,i,n,this.cname).build(e),a=lt(t);return r.modify(a),a}},ax=class{get sdp(){return this.originalDescription.sdp}set sdp(e){this.originalDescription=new Ug.window.RTCSessionDescription({sdp:e,type:this.originalDescription.type})}get type(){return this.originalDescription.type}set type(e){this.originalDescription=new Ug.window.RTCSessionDescription({sdp:this.originalDescription.sdp,type:e})}constructor(e){this.originalDescription=new Ug.window.RTCSessionDescription(e)}toJSON(){return this.originalDescription.toJSON()}},sx=g,ox=class{constructor(e,t,i){this.mediaEntity=e,this.logger=t,this.configProvider=i,this.activeRids=[],this.isLocalDescSet=!1,this.enabledLocally=!1,this.enabledRemotely=!1;const n=om(this.mediaEntity.getModality());this.config=Cm(n,this.configProvider),this.config?this.logger.safe.debug(`Adding simulcast info to ${e.getModality()} with mid: ${e.getMid()}, config: ${JSON.stringify(this.config)}`):this.logger.safe.debug(`Simulast is disabled for ${e.getModality()}`)}get ridList(){return this.config?(0,sx.times)(this.config.layerScaleFactors.length,(e=>e+1)):[]}localDescriptionIsApplied(){this.isLocalDescSet=!0}enableInLocalDesc(){this.enabledLocally=!0}shouldBeEnabledInLocalDesc(){return!!this.config&&(this.config.enableLocally||this.enabledRemotely)}enableInRemoteDesc(){this.enabledRemotely=!0}shouldBeEnabledInRemoteDesc(){return!!this.config&&(this.enabledLocally||this.config.allowEnableRemotely&&this.isMidRidHeaderExtPresented()&&!this.isLocalDescSet)}shouldUseSimulcast(){return this.shouldBeEnabledInLocalDesc()}getSsrcRange(){return this.shouldUseSimulcast()?99:0}isMidRidHeaderExtPresented(){const e=this.mediaEntity.getRtpHeaderExtensions();return e?.some((e=>"mid"===e.headerType||"rid"===e.headerType||"rrid"===e.headerType))}},lx={toffset:"toffset","abs-send-time":"abs-send-time","video-orientation":"video-orientation","draft-holmer-rmcat-transport-wide-cc-extensions-01":"transport-cc","video-content-type":"video-content-type","video-timing":"video-timing","color-space":"color-space","video-layers-allocation00":"vla","video-layers-allocation00-non-advertised":"non-adv-vla",mid:"mid","rtp-stream-id":"rid","repaired-rtp-stream-id":"rrid","fast_bandwidth_feedback#version_3":"fast_bandwidth_feedback#version_3","frame-counters-gvc":"frame-counters-gvc"},cx=class{constructor(e){this.context=e,this.mediaEntities=[],this.mediaEntitiesBackup=[],this.mediaTracks=[],this.ssrcGenerator=new jk,this.rollbackHandlers=[],this.logger=e.logger.createChild("MM2"),this.configProvider=e.configProvider}fromOffer(e,t,i=!1){this.updateMediaEntitiesFromModel(e,i),this.updateSharingEntity(!!t.sharing),e.media.forEach((e=>{const t=this.getMediaEntityByMid(e.mid);t&&this.saveLocalSsrc(t,e)}))}fromRemote(e,t){const i=0===this.mediaEntities.length;this.updateMediaEntitiesFromModel(e,!1,t),e.media.forEach(((e,t)=>{const i=this.getMediaEntityByMid(e.mid);i&&(this.saveRemoteMsid(i,e),this.saveRemoteSsrc(i,e),this.saveRtpHeaderExtensions(i,e),i.setXSourceStreamId(e.xSourceStreamId||this.generateSourceStreamId(t)),i.setRemoteRecvCapabilities(WA(e)),i.setSubStreamIndex(e.subStreamIndex))})),i&&this.updateReinvitelessState(e)}isEmpty(){return 0===this.mediaEntities.length}createMediaEntity(e,t){const i=TN.create(this.configProvider,e,t);return this.context.useSimulcast&&!this.mediaEntities.find((t=>t.getModality()===e))&&this.setSimulcastContext(i),i.setExtension("reinviteless",!1),this.mediaEntities.push(i),i}getMediaEntities(){return this.mediaEntities}getMediaEntity(e){return this.mediaEntities[e]}getMediaEntityByMid(e){return this.mediaEntities.find((t=>t.getMid()===e))}getMediaEntitiesByModality(e){return this.mediaEntities.filter((t=>t.getModality()===e))}getMediaEntitiesByMediaType(e){const t=om(e);return this.getMediaEntitiesByModality(t)}getMediaEntityByRemoteStreamId(e){return this.mediaEntities.find((t=>t.getRemoteStreamId()===e))}getMediaEntityByLocalTrackId(e){return this.mediaEntities.find((t=>t.getLocalTrackId()===e))}getMediaEntityByXSourceStreamId(e){return this.mediaEntities.find((t=>t.getXSourceStreamId()===e))}reset(){this.mediaEntities=[],this.rollbackHandlers=[]}syncModalities(e,t,i=!1){this.fromOffer(e,t,i)}setLocalTracksInfo(e){this.mediaTracks=e}getLocalTracksInfo(){return this.mediaTracks}backup(){this.logger.safe.debug("backup"),this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{this.mediaEntitiesBackup.push(e.clone())}))}commit(){this.mediaEntitiesBackup=[],this.mediaEntities.forEach((e=>{e.setExtension("unnegotiatedModality",!1)}))}rollback(){this.logger.safe.debug(`rollback, if backup exists: ${!!this.mediaEntitiesBackup.length}`),this.mediaEntitiesBackup.length&&(this.rollbackHandlers.forEach((e=>e(this.mediaEntities,this.mediaEntitiesBackup))),this.mediaEntities.forEach(((e,t)=>{this.mediaEntitiesBackup[t]?this.mediaEntities[t]=this.mediaEntitiesBackup[t]:(e.disable(),e.setExtension("rollback",!0))})))}updateMediaEntitiesWithLocalTracks(){this.mediaTracks&&(this.mediaEntities.forEach((e=>e.setLocalTrackId(null))),this.mediaTracks.forEach((e=>{const t=this.getMediaEntitiesByModality(e.modality)[0];t?t.setLocalTrackId(e.trackId):this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(e.modality)}`)})))}updateMediaEntitiesWithActivityState(e,t){this.logger.safe.debug(`Updating activity indexes for ${e} to ${JSON.stringify(t)}`);const i=lm(e),n=this.getMediaEntitiesByModality(i)[0];if(!n)return void this.logger.safe.error(`Media entity is not found for modality: ${JSON.stringify(i)}`);const r=n.getSimulcastContext();r&&(r.activeRids=t)}setRollbackUpdateHandler(e){this.rollbackHandlers.push(e)}saveRtpHeaderExtensions(e,t){if(e.isDisabled())return void e.setRtpHeaderExtensions(void 0);const i=t.ext?.map((e=>this.getHeaderExtension(e)));this.logger.safe.debug(`RTP header ext for mid=${t.mid}, modality=${e.getModality()}: ${JSON.stringify(i)}`),e.setRtpHeaderExtensions(i)}getHeaderExtension(e){let t="unknown";for(const[i,n]of Object.entries(lx))if(e.uri.endsWith(i)){t=n;break}return{headerType:t,value:e.value}}saveRemoteMsid(e,t){if(zA(t))e.setRemoteStreamId(null);else if(t.msid)e.setRemoteStreamId(t.msid.split(" ")[0]);else if(t.ssrcs){const i=t.ssrcs.find((e=>"msid"===e.attribute));i?e.setRemoteStreamId(i.value.split(" ")[0]):this.logger.safe.warn(`No ssrc msid for media of type ${t.type} with mid ${t.mid}`)}}saveRemoteSsrc(e,t){if(t.ssrcs?.length){const i=t.ssrcs[0];e.setRemoteSsrc(i.id)}}saveLocalSsrc(e,t){const i=t.ssrcs?.[0]?.id;if(!Wg(t.direction))return void e.setLocalSsrc(i);const n=i||e.getLocalSsrc()||this.ssrcGenerator.nextVideoStreamSsrc().min;e.setLocalSsrc(n)}updateMediaEntitiesFromModel(e,t,i){e.media.forEach(((e,n)=>{this.mediaEntities[n]?zA(e)?this.mediaEntities[n].disable():this.mediaEntities[n].update(this.mediaEntities[n].getModality(),e.mid||this.mediaEntities[n].getMid()):t||this.createMediaEntity(HA(e),e.mid||n.toString()),this.mediaEntities[n]&&i&&!(this.mediaEntities[n].getModality()in i)&&this.mediaEntities[n].disable()}))}updateSharingEntity(e){if(e&&!this.getMediaEntitiesByModality(Qe.MODALITY.sharing).length){const e=this.getMediaEntitiesByModality(Qe.MODALITY.video).pop();e.update(Qe.MODALITY.sharing,e.getMid())}}setSimulcastContext(e){if(!e||e.getSimulcastContext())return;const t=new ox(e,this.logger.createChild(`SimContext:${e.getModality()}`),this.configProvider);e.setSimulcastContext(t)}generateSourceStreamId(e){return e+10}updateReinvitelessState(e){const t={[Qe.MODALITY.audio]:0,[Qe.MODALITY.video]:0,[Qe.MODALITY.sharing]:0};for(const i of e.media){const e=HA(i);void 0!==t[e]&&t[e]++;const n=this.getMediaEntityByMid(i.mid);if(n){const r=this.context.reinviteltessContext?.maxStreamsForModality[e]>=t?.[e]&&(!i.direction||"sendrecv"===i.direction);n.setExtension("reinviteless",r)}}}};var dx=class extends KN{constructor(e,t,i){super(e,t,2,i)}init(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e]}})}setCodec(e,t){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e,t]}})}passWriteableStreams(e,t){const i=e.concat(t);this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"passWriteableStreams",args:[e,t]}},i)}setAvailableStreams(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setAvailableStreams",args:[e]}})}setRecvPayloads(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setRecvPayloads",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}sendApiRecordingData(){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"sendApiRecordingData",args:[]}})}},ux=class{constructor(e){this.logger=e,this.audioContext=new AudioContext,this.destination=this.audioContext.createMediaStreamDestination()}get stream(){return this.destination.stream}isSingleInputStream(){return 0===this.mixerImp?.mixerType}dispose(){this.audioContext.close(),this.audioContext=null}setMixerType(e,t){this.mixerImp?.mixerType!==e&&(this.mixerImp?.reset(),this.mixerImp=this.createMixer(e),this.mixerImp.setupMixer(this.audioContext,this.destination,t))}setStreamSources(e){this.mixerImp.setStreamSources?.(e)}setParticipantSpatialAudioPositions(e){this.mixerImp.setParticipantSpatialAudioPositions?.(e)}createMixer(e){switch(e){case 0:return new px;case 1:return new gx(this.logger.createChild("MixingStreamsMixer"));case-1:return new hx;default:throw new Error(`unknown mixer type: ${e}`)}}},hx=class{constructor(){this.mixerType=-1}reset(){}setupMixer(e,t,i){}},px=class{constructor(){this.mixerType=0}reset(){this.sourceNode.disconnect()}setupMixer(e,t,i){this.sourceNode=e.createMediaStreamSource(i[0]),this.sourceNode.connect(t)}},gx=class{constructor(e){this.logger=e,this.sourcePositions=new Map,this.pannerNodes=[],this.mixerType=1}reset(){for(const e of this.pannerNodes)e.disconnect();this.pannerNodes=[]}setupMixer(e,t,i){for(const n of i){const i=e.createMediaStreamSource(n),r=new PannerNode(e,{panningModel:"HRTF"});i.connect(r),r.connect(t),this.pannerNodes.push(r)}this.logger.safe.info(`setupMixer is done for ${i.length} streams.`)}setStreamSources(e){for(let t=0;t<e.length;t++)this.setStreamPosition(t,e[t])}setParticipantSpatialAudioPositions(e){this.sourcePositions=new Map(e.map((e=>[e.sourceId,e])))}setStreamPosition(e,t){const i=this.sourcePositions.get(t)??{sourceId:t,x:0,y:0},n=this.pannerNodes[e];n.positionX.value=i.x,n.positionY.value=i.y}},mx=class extends We{constructor(e){super(),this.logger=e,this.mediaStreams=[],this.cnStream=null,this.isActive=!1}get active(){return this.isActive}get streams(){return this.mediaStreams}get comfortNoiseStream(){return this.cnStream}setupStreams(e,t){this.logger.safe.debug(`setup ${e} streams with extra Comfort Noise stream: ${t}`),this.mediaStreams=[];const i=[];for(;e--;){const e=new MediaStreamTrackGenerator({kind:"audio"});i.push(e),this.streams.push(new MediaStream([e]))}const n=t?new MediaStreamTrackGenerator({kind:"audio"}):null;return this.cnStream=n?new MediaStream([n]):null,this.event("onStreamsChanged").raise(),{streams:i.map((e=>e.writable)),cnStream:n?.writable}}setStreamSources(e){this.isActive&&this.event("onStreamSourcesUpdated").raise(e)}activateUnmixedProvider(e){this.isActive!==e&&(this.isActive=e,this.event("onActiveStateChanged").raise())}},fx=class extends qe{constructor(e,t){super(),this.logger=e,this.maxNumOfStreamsFactor=t,this.statsProvider=new vx,this.streamMixer=new ux(this.logger),this.unmixedAudioProvider=new mx(this.logger),this.codec="None",this.recvPayloads=[],this.initCompleted=!1,this.enabledApiRecording=!1;try{this.enabledApiRecording="true"===localStorage.getItem("enableApiRecording")}catch{}this.injectWebMA()}get stream(){return this.streamMixer.stream}dispose(){super.dispose(),this.streamMixer.dispose(),this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM decoder transform"),e.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM decoder transform"),this.imp=null,this.initCompleted=!1,this.codec="None",this.streamMixer.setMixerType(-1,[])}createBaseInstanse(e){this.logger.warn("WASM decoder could only be instantiated in worker")}createWorkerInstanse(e,t){this.imp=function(e,t,i){return new dx(e,t,i)}(e,t,this),this.imp.init(this.enabledApiRecording)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.initCompleted)return this.logger.safe.debug("Decoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}setRecvPayloads(e){this.recvPayloads=e,this.imp?.setRecvPayloads(e)}negotiationCompleted(e){this.logger.safe.debug(`Negotiation completed, negotiated=${e}`),e||(this.codec="None",this.imp?.setCodec(this.codec,this.streamMixer.isSingleInputStream()))}setParticipantSpatialAudioPositions(e){this.streamMixer.setParticipantSpatialAudioPositions(e)}getStatsProvider(){return this.statsProvider}getUnmixedAudioProvider(){return this.unmixedAudioProvider}async storeApiRecording(){if(this.enabledApiRecording&&this.initCompleted)return this.recordingCompletePromise?.resolve(),this.recordingCompletePromise=new Jh,this.imp.sendApiRecordingData(),this.recordingCompletePromise.promise}initDone(e,t){if(this.healerCapabilities=t,this.logger.safe.info(`Init done, errorCode=${e}`),0!==e)return void this.event("initFailed").raise(e);this.logger.safe.info(`healerCapabilities=${JSON.stringify(t)}`),this.initCompleted=!0;const i=Math.floor(this.healerCapabilities.maxNumStreamsPerPacket*this.maxNumOfStreamsFactor),n=this.unmixedAudioProvider.setupStreams(i,!0);this.imp.passWriteableStreams(n.streams,n.cnStream),this.setCodecInternal(),this.imp.setRecvPayloads(this.recvPayloads)}usedDecoderChanged(e){this.logger.safe.info(`Used decoder changed to custom=${e}, configured codec=${this.codec}`),this.event("usedDecoderChanged").raise(e),this.unmixedAudioProvider.activateUnmixedProvider(e&&"MUCHv2"===this.codec)}packetReceived(e,t,i){this.statsProvider.ssrc=t,this.statsProvider.addPushStats(e,i)}newDataWrittenToStreams(e){const t=Array.from(new Int32Array(e));this.unmixedAudioProvider.setStreamSources(t),this.streamMixer.setStreamSources(t);const i=t.reduce(((e,t,i)=>(0===t&&e.push(i),e)),[]);this.imp?.setAvailableStreams(i)}packetDecoded(e,t,i){this.statsProvider.addPullStats(e,t,i,i.extra.samplingRatekHz*this.healerCapabilities.frameLengthMs)}apiRecordingAvailable(e,t,i){if(this.logger.safe.debug(`API recording available: errorCode=${e}, name=${t}, buffer length=${i.byteLength}`),this.recordingCompletePromise?.resolve(),0===i.byteLength)return;const n=new Blob([i],{type:"application/octet-stream"}),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=t,a.click()}setCodecInternal(){this.streamMixer.setMixerType(function(e){switch(e){case"SatinFB":return 0;case"MUCHv2":return 1;case"None":return-1;default:throw new Error(`unknown codec: ${e}`)}}(this.codec),this.unmixedAudioProvider.streams),this.imp.setCodec(this.codec,this.streamMixer.isSingleInputStream()),this.statsProvider.codecName=this.codec}injectWebMA(){const e=window.webMA;e&&(e.wasmDecoder={debugLogging:e=>this.imp?.debugLogging(e),sendApiRecordingData:()=>this.imp?.sendApiRecordingData()})}removeWebMA(){const e=window.webMA;e&&delete e.wasmDecoder}};var vx=class{constructor(){this.customHealerStats={numSamplesPerFrame:0,FECPayloadDecodedSamples:0,concealSamples:0,stretchSamples:0,healedSamples:0,decodedSamples:0,redPacketsCount:0,pushProcessingTimes:{},pullProcessingTimes:{},pullProcessingTimePerStreamNumber:{},pullNumOfStreamsCounter:{}},this.inboudStats={silentConcealedSamples:0,concealedSamples:0,totalSamplesReceived:0,audioLevel:0,jitterBufferDelay:0,jitterBufferEmittedCount:0},this.decoderStats={pushCount:0,pushErrCount:0,pullCount:0,pullErrCount:0},this.packetPushProccesingTimes=new Sx(0,1e3),this.packetPullProccesingTimes=new Sx(0,1e3),this.numOfStreamsCounter=new Sx(0,10),this.pullProcessingTimePerStreamNumber={}}get codecName(){return this.codec}set codecName(e){this.codec=e}addPushStats(e,t){this.decoderStats.pushCount++,this.decoderStats.pushErrCount+=0!==e?1:0,this.inboudStats.jitterBufferDelay+=t.webrtc.jitterBufferDelay,this.customHealerStats.packetDurationInMs=t.extra.packetDurationInMs,this.packetPushProccesingTimes.addSample(t.extra.processingTime),this.customHealerStats.pushProcessingTimes=this.packetPushProccesingTimes.getFrequencies(),this.customHealerStats.cnpPushCount=t.extra.totalCountCNPackets,this.customHealerStats.redPacketsCount+=0!==t.extra.redundancyTimestampOffset?1:0}addPullStats(e,t,i,n){var r;this.decoderStats.pullCount++,this.decoderStats.pullErrCount+=0!==e?1:0,this.inboudStats.audioLevel=i.webrtc.audioLevel,this.inboudStats.totalAudioEnergy=i.webrtc.totalAudioEnergy,this.inboudStats.jitterBufferEmittedCount=i.webrtc.jitterBufferEmittedCount,this.inboudStats.totalSamplesReceived=i.webrtc.totalSamplesReceived,this.inboudStats.concealedSamples=i.webrtc.concealedSamples,this.inboudStats.silentConcealedSamples=i.webrtc.silentConcealedSamples,this.numOfStreamsCounter.addSample(t),this.customHealerStats.FECPayloadDecodedSamples=i.extra.FECPayloadDecodedSamples,this.customHealerStats.numSamplesPerFrame=n,this.customHealerStats.pullAdspPayloadType=i.extra.pullAdspPayloadType,this.customHealerStats.concealSamples=i.extra.concealSamples,this.customHealerStats.stretchSamples=i.extra.stretchSamples,this.customHealerStats.healedSamples=i.extra.healedSamples,this.customHealerStats.decodedSamples=i.extra.decodeSamples,this.packetPullProccesingTimes.addSample(i.extra.processingTime),this.customHealerStats.pullProcessingTimes=this.packetPullProccesingTimes.getFrequencies(),this.customHealerStats.cnpPullCount=i.extra.totalCountCNGeneratedFrames,this.customHealerStats.cngSamples=i.extra.cngSamples,this.customHealerStats.pullNumOfStreamsCounter=this.numOfStreamsCounter.getFrequencies(),(r=this.pullProcessingTimePerStreamNumber)[t]??(r[t]=new Sx(0,200)),this.pullProcessingTimePerStreamNumber[t].addSample(i.extra.processingTime);for(const e of Object.keys(this.pullProcessingTimePerStreamNumber))this.customHealerStats.pullProcessingTimePerStreamNumber[e]=this.pullProcessingTimePerStreamNumber[e].getFrequencies()}getWebRtcCompatibaleStats(){return this.inboudStats}getWasmStats(){return this.customHealerStats}getDecoderStats(){return this.decoderStats}},Sx=class{constructor(e,t){this.minSample=e,this.maxSample=t,this.frequencyDict={}}addSample(e){if(void 0===e)return;const t=Math.min(this.maxSample,Math.max(this.minSample,e));this.frequencyDict[t]=(this.frequencyDict[t]??0)+1}getFrequencies(){return{...this.frequencyDict}}};var yx=class extends KN{constructor(e,t,i){super(e,t,3,i)}init(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"init",args:[e]}})}setCodec(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"setCodec",args:[e]}})}debugLogging(e){this.worker.sendTransformCommand(this.clientId,{operation:"invoke",func:{transformType:this.transformType,name:"debugLogging",args:[e]}})}},Cx=["SatinFB"],_x=class extends qe{constructor(e){super(),this.logger=e,this.codec="None",this.injectWebMA()}dispose(){super.dispose(),this.removeWebMA()}activateTransform(e){this.logger.safe.debug("Activating WASM encoder transform"),e.addTransform(this)}deactivateTransform(){this.logger.safe.debug("Deactivating WASM encoder transform"),this.imp=null,this.encodersInitCodes=void 0,this.codec="None"}createBaseInstanse(e){this.logger.warn("WASM encoder could only be instantiated in worker")}createWorkerInstanse(e,t){this.imp=function(e,t,i){return new yx(e,t,i)}(e,t,this),this.imp.init(Cx)}setCodec(e){if(this.logger.safe.debug(`Setting codec to ${e}`),!this.encodersInitCodes)return this.logger.safe.debug("Encoder is not initialized yet, postponing codec setting"),void(this.codec=e);this.codec!==e&&(this.codec=e,this.setCodecInternal())}isCodecAllowed(e){return Cx.includes(e)}negotiationCompleted(e){e||(this.codec="None",this.imp?.setCodec(this.codec))}initDone(e){this.logger.safe.info(`initDone: ${JSON.stringify(e)}`),this.encodersInitCodes=e,this.setCodecInternal()}packetEncoded(e){0!==e&&this.logger.safe.info(`encode failed: ${e}`)}setCodecInternal(){const e=this.encodersInitCodes[this.codec]??-2147024809;if("None"!==this.codec&&0!==e)return this.logger.safe.error(`WASM encoder is failed to init codec ${this.codec}, err code: ${e}`),void this.event("initCodecFailed").raise(e);this.imp.setCodec(this.codec)}injectWebMA(){const e=window.webMA;e&&(e.wasmEncoder={debugLogging:e=>this.imp?.debugLogging(e)})}removeWebMA(){const e=window.webMA;e&&delete e.wasmEncoder}},Ex=g,Tx=class extends qe{constructor(e,t,i){super(),this.encStreamsManager=e,this.logger=t,this.configProvider=i,this.isEnabled=!1,this.sessionStats=new Ix,this.subs=[],this.codecContext=this.configProvider.mediaConfig.audioCodecContext,this.codecConfig=this.configProvider.config.useInsertableStreams?.audioWasmCodec}get decoder(){return this.decoderImp}get encoder(){return this.encoderImp}init(e){if(!e||!this.codecContext||!this.codecConfig?.enable)return;this.isEnabled=!0;const t=this.codecConfig.maxNumOfStreamsFactor||1;this.decoderImp=new fx(this.logger.createChild("AudioWasmDecoder"),t),this.codecConfig.enableSend&&(this.encoderImp=new _x(this.logger.createChild("AudioWasmEncoder"))),this.subscribeToStreamManagerEvents(this.encStreamsManager),this.subscribeToCodecsEvents()}dispose(){super.dispose(),this.unsubscribeFromEvents(),this.decoderImp?.dispose(),this.encoderImp?.dispose()}getSessionEvents(){return this.sessionStats.getSessionEvents()}prepareForNegotiation(e){if(!this.isEnabled)return;const t=this.configProvider.mediaConfig.spatialAudioEnabled?"MUCHv2":this.codecConfig.codec||"None";this.codecContext.codec!==t&&(this.codecContext.initSendFailed=!1),this.codecContext.lastUsedCodec=this.codecContext.codec,this.codecContext.codec=t,this.codecContext.enabledLocally=!this.codecContext.initFailed&&"None"!==t,this.codecContext.enabledForSend=this.codecContext.enabledLocally&&!this.codecContext.initSendFailed&&!!this.codecConfig?.enableSend&&this.encoder?.isCodecAllowed(t),this.logger.safe.info(`Audio codec state: context=${JSON.stringify(this.codecContext)}`),this.codecContext.initFailed||!e&&this.codecContext.disabledRemotely||(this.sessionStats.toggleState("None"!==t),this.decoderImp?.setCodec(t),this.encoderImp?.setCodec(this.codecContext.enabledForSend?t:"None"))}negotiationCompleted(){if(!this.isEnabled)return!1;const e=this.codecContext.enabledLocally&&!this.codecContext.disabledRemotely;return this.decoderImp?.negotiationCompleted(e),this.encoderImp?.negotiationCompleted(e),this.sessionStats.negotiationCompleted(e,this.codecContext.enabledForSend),e}configureSpatialAudio(e,t){return!!this.isEnabled&&((e&&"MUCHv2"!==this.codecContext.codec||!e&&"MUCHv2"===this.codecContext.codec)&&this.event("negotiationNeeded").raise(t),!0)}subscribeToStreamManagerEvents(e){this.subs.push(e.on("onTransformsCollectionCreated",(e=>this.handleTransformsCollectionCreated(e))),e.on("onTransformsCollectionCleared",(e=>this.handleTransformsCollectionCleared(e))))}handleTransformsCollectionCreated(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.activateTransform(e.collection):this.encoderImp&&"Sender"===e.objType&&this.encoderImp.activateTransform(e.collection))}handleTransformsCollectionCleared(e){"Audio"===e.mediaType&&(this.decoderImp&&"Receiver"===e.objType?this.decoderImp.deactivateTransform():this.encoderImp&&"Sender"===e.objType&&this.encoderImp.deactivateTransform())}subscribeToCodecsEvents(){this.decoderImp&&this.subs.push(this.decoderImp.on("initFailed",(e=>this.handleCodecInitFailed("decoder",e)))),this.encoderImp&&this.subs.push(this.encoderImp.on("initCodecFailed",(e=>this.handleCodecInitFailed("encoder",e))))}unsubscribeFromEvents(){this.subs.forEach((e=>e.dispose())),this.subs=[]}handleCodecInitFailed(e,t){"decoder"===e?this.codecContext.initFailed=!0:this.codecContext.initSendFailed=!0;const i=Te();this.logger.safe.warn(`[${i}] Audio ${e} init failed ${t}`),this.sessionStats.initFailed(t,e),this.event("negotiationNeeded").raise(i)}},bx=class e{constructor(){this.sessionEvents={negotiationAttempts:[],toggleCount:0,negotiatedCount:0,failedNegotiationCount:0,decoderInitError:0,encoderInitError:0}}toggleState(t){this.sessionEvents.toggleCount++,this.inProgressNegotiation={ts:Date.now(),enabled:t,negotiated:!1,sendEnabled:!1},Tt(this.sessionEvents.negotiationAttempts,this.inProgressNegotiation,e.maxStoreNegotiations)}negotiationCompleted(e,t){this.inProgressNegotiation&&(this.sessionEvents.negotiatedCount+=e?1:0,this.sessionEvents.failedNegotiationCount+=this.inProgressNegotiation.enabled&&!e?1:0,this.inProgressNegotiation.negotiated=e,this.inProgressNegotiation.sendEnabled=t,this.inProgressNegotiation=void 0)}initFailed(e,t){"decoder"===t?this.sessionEvents.decoderInitError=e:this.sessionEvents.encoderInitError=e}getSessionEvents(){return(0,Ex.clone)(this.sessionEvents)}};bx.maxStoreNegotiations=5;var Ix=bx,wx=class extends qe{constructor(e,t){super(),this.configProvider=e,this.logger=t,this.bandwidthEstimationAvailable=!1,this.smoothingWindow=[],this.totalSamples=0,this.isStarted=!1,this.maxCountStatic=this.configProvider.config.ovcMaxCount,this.previousParticipantsCount=0;const i=window.navigator;this.updateStaticConstraint(i.hardwareConcurrency,this.configProvider.config.ovcAvailableConcurrencyForBiggerGrid,4),this.updateStaticConstraint(i.deviceMemory,this.configProvider.config.ovcMemoryForBiggerGrid,4),this.throttler=new Rx(this.logger.createChild("ovcThrottler"),this.configProvider.config.ovcRampDownCooldown,this.configProvider.config.ovcRampUpCooldown)}start(){this.isStarted=!0,this.throttler.changed((()=>this.event("calculatorStateChanged").raise(2,{ovc:this.throttler.value,ovcPayload:this.payload})))}stop(){this.isStarted=!1}dispose(){super.dispose(),this.throttler.dispose()}processEstimatedBandwidth(e){const t=this.getOVCEstimate(e),i=Math.max(1,Math.min(t,this.maxCountStatic));this.payload={bandwidth:e,reason:0},this.throttler.setValue(i,0)}updateParticipantCount(e){if(!this.configProvider||e===this.previousParticipantsCount)return;const t=this.configProvider.config.ovcXLParticipantsCount;e>t&&this.previousParticipantsCount<=t&&(this.maxCountStatic=this.configProvider.config.ovcMaxCountXL),e<=t&&this.previousParticipantsCount>t&&(this.maxCountStatic=this.configProvider.config.ovcMaxCount),this.previousParticipantsCount=e;let i=this.maxCountStatic;this.payload?.bandwidth&&(i=this.getOVCEstimate(this.payload.bandwidth),this.payload.reason=1),this.throttler.setValue(Math.max(1,Math.min(i,this.maxCountStatic)),1)}getOVCEstimate(e){this.bandwidthEstimationAvailable||(this.bandwidthEstimationAvailable=this.isStarted&&e>0&&(this.totalSamples++>=this.configProvider.config.ovcIgnoreFirstSamples||Math.floor(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver>=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount));let t=this.configProvider.config.nonEstimatedDefaultVideoReceiversCount;return this.bandwidthEstimationAvailable&&(t=Math.floor(this.sampleSmoothed(e)/this.configProvider.config.ovcBandwidthPerVideoReceiver)),t}sampleSmoothed(e){if(this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples?this.smoothingWindow.shift():this.smoothingWindow.length===this.configProvider.config.ovcSlidingWindowSamples-1&&(this.smoothingWindow=this.smoothingWindow.map((()=>e))),this.smoothingWindow.push(e),this.smoothingWindow.length>=this.configProvider.config.ovcSlidingWindowSamples){const e=this.smoothingWindow.slice().sort(),t=it(e);return e[e.length-1]-(e[e.length-1]-t*(1-this.configProvider.config.ovcSlidingWindowPercentile))}return e}updateStaticConstraint(e,t,i){e&&e<t&&(this.maxCountStatic=Math.min(this.maxCountStatic,i))}},Rx=class extends qe{constructor(e,t,i){super(e),this.logger=e,this.throttleDownCooldown=t,this.throttleUpCooldown=i,this.wasRampingUp=!0,this.lastUpdateTime=0}get value(){return this.lastValue}setValue(e,t){if(e===this.lastValue)return;const i=e>this.lastValue,n=void 0!==this.lastValue&&i!==this.wasRampingUp?i?this.throttleUpCooldown:this.throttleDownCooldown:-1,r=Date.now();r-this.lastUpdateTime<n&&(1!==t||i)||(void 0!==this.lastValue&&(this.lastUpdateTime=r,this.wasRampingUp=i),this.logger.safe.info(`optimal video receivers count updated ${this.lastValue} -> ${e}`),this.lastValue=e,this.raiseChanged())}},Ax=class e{constructor(e,t=30){this.logger=e,this.maxEventNum=t,this.report=[],this.started=!1}isSupported(){return Boolean(window.chrome?.runtime?.connect)}start(){this.isSupported?(this.started=!0,this.logger.debug("Starting collecting CPU metric"),this.port=window.chrome.runtime.connect(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{e&&Tt(this.report,{timeStamp:Date.now(),value:e},this.maxEventNum)}))):this.logger.debug("Chrome runtime is not supported")}stop(){this.port?.disconnect(),this.port=null,this.started=!1}getSamples(){return this.report}getLastSample(){return It(this.report)}getCurrentCpuSample(){return new Promise(((t,i)=>{this.started&&t(It(this.report)),this.isSupported()||i("Not supported"),this.port=window.chrome.runtime.connect(e.extensionID,{name:e.extensionName}),this.port.onMessage.addListener((e=>{this.stop(),e||i("Not supported"),t({timeStamp:Date.now(),value:e})}))}))}clearStats(){this.report=[]}};Ax.extensionID="nkeimhogjdpnpccoofpliimaahmaaome",Ax.extensionName="processCpu";var Px=Ax,Mx=class{constructor(e){this.logger=e,this.started=!1}static isSupported(){return void 0!==globalThis.PressureObserver}get cpuState(){return this.currentCpuState}start(){if(this.logger.safe.debug("Starting CPU pressure observer"),this.started)this.logger.safe.debug("CPU pressure observer is already started");else{try{this.cpuObserver=new globalThis.PressureObserver((e=>{e.forEach((t=>{"cpu"===t.source&&this.currentCpuState!==t.state&&(this.logger.safe.debug(`CPU pressure state changed: ${JSON.stringify(e)}`),this.currentCpuState=t.state)}))}),{sampleRate:1})}catch(e){throw this.logger.safe.error(`Error while creating pressure observer: ${e}`),e}this.started=!0,this.cpuObserver?.observe("cpu")}}stop(){this.started=!1,this.cpuObserver?.disconnect()}},kx=class{static getStrategy(e){switch(e.config.diagnostics.performanceMonitoring.monitoringStrategy){case"decodeTime":default:return new Dx(e);case"renderedFps":return new Ox(e);case"rendererVolatility":return new Nx(e)}}},Dx=class{constructor(e){this.configProvider=e,this.decodeThresholds=this.configProvider.config.diagnostics.performanceMonitoring.decodeThresholds,this.defaultThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultThrehold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=this.decodeThresholds[e.frameHeight]||this.defaultThreshold,r=e.decodeTimeTracker.getReport();return r.median>n.maxDecodeTime&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),r.median<n.maxDecodeTime&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},Ox=class{constructor(e){this.configProvider=e,this.fpsDiffThresholds=this.configProvider.config.diagnostics.performanceMonitoring.fpsDiffThresholds,this.defaultFpsDiffThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultFpsDiffThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=this.fpsDiffThresholds[e.frameHeight]||this.defaultFpsDiffThreshold,r=e.incomingFps.getReport(),a=e.rendererFps.getReport(),s=r.median-a.median;return s>=n.fpsDiff&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),s<n.fpsDiff&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},Nx=class{constructor(e){this.configProvider=e,this.volatilityThresholds=this.configProvider.config.diagnostics.performanceMonitoring.volatilityThresholds,this.defaultVolatilityThreshold=this.configProvider.config.diagnostics.performanceMonitoring.defaultVolatilityThreshold,this.badPerfCount=new Map}checkQuality(e){let t=!1,i=!1;const n=this.volatilityThresholds[e.frameHeight]||this.defaultVolatilityThreshold,r=e.rendererFps.getReport(),a=e.incomingFps.getReport(),s=Math.abs(r.volatilityPercent-a.volatilityPercent);return n&&s>=n&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)||1),t=!0),s<n&&this.badPerfCount.get(e.msi)&&(this.badPerfCount.set(e.msi,this.badPerfCount.get(e.msi)-1),i=!0),t?0:i?2:1}},Lx=class extends qe{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,this.paused=!1,this.started=!1,this.cpuMetricCollector=new Px(this.logger,this.configProvider.config.diagnostics.performanceMonitoring.cpuMetricCollector),this.trackInterval=this.configProvider.config.diagnostics.performanceMonitoring.remoteVideoTrackInterval,this.badPerfIds=new Set,this.perfTrackerMap=new Map,this.subs=[],this.rendererFpsCap=40,this.configProvider.config.diagnostics.performanceMonitoring.useComputePressure&&Mx.isSupported()&&(this.cpuPressureObserver=new Mx(this.logger))}start(){this.logger.safe.debug("Starting RemoteVideoPerformanceCalculator"),this.started?this.logger.safe.debug("RemoteVideoPerformanceCalculator already running. Do nothing."):(this.calculatorStrategy=kx.getStrategy(this.configProvider),this.started=!0,this.cpuPressureObserver?.start(),this.subs.push(this.statsGatherer.on("onDiagnosticUpdated",(e=>this.processStats(e)))))}stop(){this.logger.safe.debug("Stopping RemoteVideoPerformanceCalculator"),this.started=!1,this.subs.forEach((e=>{e.dispose()})),this.cpuMetricCollector.stop(),this.cpuPressureObserver?.stop()}dispose(){this.logger.safe.debug("Disposing RemoteVideoPerformanceCalculator"),this.cleanupMaps(),this.stop()}cleanupMaps(){this.badPerfIds.clear(),this.perfTrackerMap.clear()}async processStats(e){this.paused||e.video?.recv?.length&&e.video?.recv?.forEach((async t=>{const i=t.renderer?.msi;if(!this.perfTrackerMap.has(i)){const e={id:t.mediaEntity.remoteTrackId,decodeTimeTracker:new yD(this.trackInterval),macroblockLossTracker:new yD(this.trackInterval),macroblockMaxLossTracker:0,freezeDurationPercent:0,frameHeight:0,rendererFps:new yD(this.trackInterval),incomingFps:new yD(this.trackInterval),framesReceived:0,framesDecoded:0,decoder:"",msi:i};this.perfTrackerMap.set(i,e)}const n=this.perfTrackerMap.get(i);if(t.inboundRTP.totalDecodeTime&&t.inboundRTP.framesDecoded){const e=Ct(t.inboundRTP.totalDecodeTime/t.inboundRTP.framesDecoded*1e3,2);n.decodeTimeTracker.captureSample(e)}const r=t.extensions.macroblockRateStats?.macroblockRateDecoderLossPercent;n.macroblockLossTracker.captureSample(r),n.macroblockMaxLossTracker=t.extensions.macroblockRateStats?.macroblockRateMaxDecoderLossPercent,t.extensions.duration&&(n.freezeDurationPercent=t.extensions.totalFreezeDuration/t.extensions.duration*100),n.frameHeight=t.inboundRTP.frameHeight||0,void 0!==t.extensions.frameRateDecoded&&void 0!==t.inboundRTP.framesPerSecond&&t.extensions.frameRateDecoded<=this.rendererFpsCap&&t.inboundRTP.framesPerSecond<=this.rendererFpsCap&&(n.rendererFps.captureSample(t.extensions.frameRateDecoded),n.incomingFps.captureSample(t.inboundRTP.framesPerSecond)),t.inboundRTP.framesReceived&&t.inboundRTP.framesDecoded&&(n.framesReceived=t.inboundRTP.framesReceived,n.framesDecoded=t.inboundRTP.framesDecoded),n.decoder=t.inboundRTP.decoderImplementation,n.rendererFps.isReportComplete()&&n.incomingFps.isReportComplete()&&n.decodeTimeTracker.isReportComplete()&&(this.paused=!0,await this.checkQuality(n,e.perfCounters),this.paused=!1)}))}async checkQuality(e,t){const i=[];let n;try{n=await this.cpuMetricCollector.getCurrentCpuSample()}catch{this.logger.safe.debug("CPU sampling is not supported")}const r={ts:Date.now(),trackId:e.id,decodeTime:e.decodeTimeTracker.getReport(),macroblockLossPercent:e.macroblockLossTracker.getReport(),macroblockMaxLossPercent:e.macroblockMaxLossTracker,freezeDurationPercent:e.freezeDurationPercent,perfCounters:t,cpuUsage:n,rendererFps:e.rendererFps.getReport(),incomingFps:e.incomingFps.getReport(),framesDecoded:e.framesDecoded,framesReceived:e.framesReceived,msi:e.msi,frameHeight:e.frameHeight,decoder:e.decoder};i.push(r);const a=this.calculatorStrategy.checkQuality(e);0===a&&(this.diagnostics.registerVideoPerformanceEvent(i,1),this.logger.safe.debug(`Bad perf detected for msi ${e.msi}: ${JSON.stringify(i)}`),this.event("calculatorStateChanged").raise(1,{msi:e.msi})),2===a&&(this.diagnostics.registerVideoPerformanceEvent(i,0),this.logger.safe.debug(`Good perf detected for msi ${e.msi}: ${JSON.stringify(i)}`),this.event("calculatorStateChanged").raise(0,{msi:e.msi})),this.perfTrackerMap.delete(e.msi)}},xx=class extends qe{constructor(e,t,i,n){super(),this.statsGatherer=e,this.diagnostics=t,this.configProvider=i,this.logger=n,this.calculators=new Map,this.subs=[]}on(e,t){switch(e){case"onIncomingVideoQualityChanged":this.addCalculator(0),this.startCalculator(0);break;case"onOptimalVideoCountChanged":this.addCalculator(2),this.startCalculator(2)}return this.subscribe({changed:void 0,on:{name:String(e),handler:t}})}addCalculator(e){let t=this.calculators.get(e);if(!t){switch(e){case 0:if(!this.configProvider.config.diagnostics.performanceMonitoring.enableRemoteVideoCalculator)return;t=new Lx(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("RemoteVideoPerformanceCalculator"));break;case 2:if(!this.configProvider.config.enableOptimalVideoCount)return;t=new wx(this.configProvider,this.logger.createChild("OptimalVideoCountCalculator"));break;case 1:throw new Error("Not implemented")}this.subs.push(t.on("calculatorStateChanged",((t,i)=>{this.handleChanged(e,t,i)}))),this.calculators.set(e,t)}}startCalculator(e){this.logger.safe.debug(`adding calculator with id ${e}`);const t=this.calculators.get(e);t&&t.start()}stopCalculator(e){this.logger.safe.debug(`stopping calculator with id ${e}`);const t=this.calculators.get(e);t&&t.stop()}processNotification(e,t){switch(e){case"BandwithNotification":this.calculators.get(2)?.processEstimatedBandwidth(t.bw);break;case"ParticipantCountChanged":this.calculators.get(2)?.updateParticipantCount(t.count);break;default:this.logger.safe.info(`Notification message handler not found for type: ${e}`)}}dispose(){super.dispose(),this.calculators.forEach((e=>{e.dispose()})),this.subs.forEach((e=>{e.dispose()}))}handleChanged(e,t,i){switch(this.logger.info(`calculatorStateChanged  ${t}: calculatorType ${e} ${JSON.stringify(i)}`),e){case 0:this.configProvider.config.diagnostics.performanceMonitoring.enableLowerResolution&&this.event("onIncomingVideoQualityChanged").raise(t,i?.msi);break;case 2:this.event("onOptimalVideoCountChanged").raise(i?.ovc,i?.ovcPayload)}}},Fx=g,Ux=class{constructor(e){this.configProvider=e,this.outboundNetworkQuality="Good",this.inboundNetworkQuality="Good",this.jitterAccumulator=new uA(this.configProvider.config.webrtcJitterWindowSize),this.healedRatioAccumulator=new uA(this.configProvider.config.webrtcHealedRatioWindowSize),this.jitterStateProcessor=new EO(e.config.webrtcJitterLowThreshold,e.config.webrtcJitterHighThreshold,!0,e.config.webrtcJitterSticknessTime),this.lossRateStateProcessor=new EO(e.config.webrtcLossRateLowThreshold,e.config.webrtcLossRateHighThreshold,!0,e.config.webrtcLossRateSticknessTime)}processReport(e){e.audio?.recv?.length&&(this.inboundNetworkQuality=this.processInboundSample((0,Fx.last)(e.audio.recv))),e.audio?.send?.length&&(this.outboundNetworkQuality=this.processOutboundSample((0,Fx.last)(e.audio.send)))}getInboundNetworkQuality(){return this.inboundNetworkQuality}getOutboundNetworkQuality(){return this.outboundNetworkQuality}processInboundSample(e){const t=this.inboundNetworkQuality,{totalSamplesReceived:i}=e.inboundRTP,{healedRatio:n}=e.extensions??{};null!=n&&this.healedRatioAccumulator.add(n);const r=(0,Fx.mean)(this.healedRatioAccumulator.items);return!i||i<this.configProvider.config.webrtcMinAudioSamplesRecvForNetworkRecvQuality?t:r&&this.healedRatioAccumulator.isFull?this.determineInboundQualityLevel(r):t}determineInboundQualityLevel(e){const t=this.inboundNetworkQuality,i=this.configProvider.config.webrtcStatNetworkDetectionHysteresis,n=this.configProvider.config.webrtcStatNetworkDetectionBadLevel,r=this.configProvider.config.webrtcStatNetworkDetectionGoodLevel;return e<r-i/2?"Good":e<r+i/2?"Good"===t?"Good":"Poor":e<n-i/2?"Poor":e<n+i/2?"Bad"===t?"Bad":"Poor":"Bad"}processOutboundSample(e){const t=this.outboundNetworkQuality,{packetsSent:i,timestamp:n}=e.outboundRTP,{jitter:r}=e.remoteInboundRTP??{},{lossRate:a}=e.extensions??{};if(!i||i<this.configProvider.config.webrtcMinPacketsSentForNetworkSendQuality)return t;null!=r&&this.jitterAccumulator.add(r);const s=(0,Fx.mean)(this.jitterAccumulator.items),o=this.jitterAccumulator.isFull?this.jitterStateProcessor.onSample(s,n):"Good",l=a?this.lossRateStateProcessor.onSample(a,n):"Good";return"Good"===o&&"Good"===l?"Good":"Bad"}},Bx=g,Vx=class{constructor(e){this.configProvider=e,this.speechWindow=new uA(e.config.webrtcSpeakingWhileMutedDetectionWindow)}processReport(e){if(!e.audio?.send?.length)return!1;const t=e.audio.send[0],{rawInputVolume:i,callIsMuted:n}=t.extensions??{},{audioLevel:r}=t.mediaSource??{},{useAudioAnalyzer:a,webrtcSpeakingWhileMutedDetectionLevel:s}=this.configProvider.config;if(!n)return this.speechWindow.clear(),!1;const o=a?i:r;return null!=o&&this.speechWindow.add(o),!!this.speechWindow.isFull&&(0,Bx.mean)(this.speechWindow.items)>s}},Hx=0,$x=class e{constructor(e,t,i){this.context=e,this.callId=t,this.callback=i,this.callbacks={},this.multiParty=this.context.config?.isConference,this.configProvider=this.context.configProvider,this.logger=this.context.getLogger().createChild("webrtc2-"+ ++Hx),this.deviceManager=this.context.callDeviceManager.getDefaultDeviceManager(),this.capabilityGatherer=sN({global:this.context.maContext},this.configProvider.config.useSdpCapabilities,this.configProvider.config.noRequiredCodecsWorkaround),this.reinvitelessContext=Rm(this.context.config.reinvitelessConfig,this.multiParty),this.iceHostCandidateOnly=this.multiParty&&ft("iceHostCandidateOnly",this.context.config,this.configProvider.config),this.mediaManager=new cx({logger:this.logger,configProvider:this.configProvider,numVideoChannels:this.multiParty&&this.configProvider.config.numVideoChannelsGvc||1,useSimulcast:this.multiParty,reinviteltessContext:this.reinvitelessContext}),this.sessionDescription=_M.build({sdpTransform:new rx(this.context),mediaManager:this.mediaManager,logger:this.logger,configProvider:this.configProvider,configuration:this.getStreamTransformConfiguration()}),this.allowedMediaContentType=ft("webrtcAllowedMediaContentType",this.context.config,this.configProvider.config).concat(),this.receiveStreamCollection=new Wk({streamAdded:e=>this.streamAdded(e),streamRemoved:e=>this.streamRemoved(e)}),this.diagnostics=this.context.diagnostics,this.qmDiagnostics=this.diagnostics?.newQualityManagerDiagnostics(),this.statsGatherer=new qO(this.logger.createChild("stats"),this.configProvider,this.diagnostics,this.mediaManager,this.multiParty),this.networkQualityDiagnostics=new Ux(this.configProvider),this.speechDetectionDiagnostics=new Vx(this.configProvider),this.qualityManager=new ON(this.logger.createChild("qm"),{scalingEnabled:this.configProvider.config.webrtcVideoScaling,customBwEstimationEnabled:this.configProvider.config.webrtcEnabledCustomBwEstimationForVideo,sendBandwidthNotificationsEnabled:this.multiParty&&this.configProvider.config.webrtcSendBandwidthNotificationsEnabled},this,this.statsGatherer,this.qmDiagnostics,this.configProvider),this.activeSpeakerManager=new $k(this.callback.onContributingSourcesChanged,this.callback.onDominantSpeakerChanged,this.diagnostics?.dshDiagnostics,this.logger.createChild("ActiveSpeakerManager")),this.negotiationQueue=new Hw(this.logger),this.negotiationEmulator=new wN(this.logger.createChild("negotiationEmulator"),ax,this.sessionDescription,this.negotiationQueue,this.mediaManager),this.extensionsManager=this.setupExtensionsManager(),this.wasConnected=!1,this.toBeCalledAfterConnected=[],this.peerConnection=null,this.doAudioMute=this.context.config.muted,this.iceCandidatesDeferred=new Jh,this.iceCandidatesTimer=null,this.relayCandidateGathered=!1,this.iceCandidateReceived=!1,this.triggerRenegotiationFlag=!1,this.canTriggerRenegotiation=!0,this.noIceCandidates=!1,this.noRelayIceCandidates=!1,this.forceMediaStreamUpdate=!1,this.negotiatedModalities={},this.disabledModalities={},this.reinvitelessRequestedModalities={},this.reinvitelessAppliedModalities={},this.iceDisconnectedTimer=null,this.statisticsReport=Promise.resolve({type:"WebRtcMediaStats",data:{}}),this.terminated=!1,this.initiator=!1,this.streamsChangedListener=null,this.dtmfSender=GN({logger:this.logger,configProvider:this.configProvider}),this.mediaContentType=ft("webrtcMediaContentType",this.context.config,this.configProvider.config),this.streamsChangedNotificationScheduled=!1,this.subscriptionManager=new Jk(this.logger.createChild("subs"),this.configProvider,{getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e},this.diagnostics?.newSubscriptionManagerDiagnostics()),this.remoteVideoResolutionManager=new NN(this.logger.createChild("rvrm"),this.multiParty,this.configProvider,this.mediaManager,this.statsGatherer,this.diagnostics),this.remoteVideoManager=new UN(this.logger.createChild("RemoteVideoManager"),this.configProvider,this.statsGatherer,this.diagnostics,this.remoteVideoResolutionManager,this.context.maContext.domOverrides),this.transceiverManager=null,this.encStreamsManager=new oL(this.configProvider,this.context.maContext.getEncodedStreamsWorkerProvider?.(),this.logger.createChild("EncodedStreamsManager")),this.streamSendersManager=new QL(this.mediaManager,this.logger.createChild("SSM"),this.context.callDeviceManager,this.configProvider,this.statsGatherer,this.qmDiagnostics,this.multiParty,this.encStreamsManager),this.hwSilent=!1,this.configuredModalitiesPromise=Promise.resolve(),this.negotiationCompletedPromise=new Jh,this.transportStateProvider=null,this.deviceManagerSubs=[],this.isMuteHold=!1,this.rawIncomingAudioStreamManager=new Np(this.logger.createChild("rawIncomingAudioStream")),this.useNullAudioStream=!1,this.audioCodecManager=new Tx(this.encStreamsManager,this.logger,this.configProvider),this.perfMonitorSubs=[],this.ufdManager=e.getUfdManager(),this.statsGatherer.on("onDiagnosticUpdated",(e=>this.processStatsReport(e))),this.statsGatherer.on("onStatisticsChanged",(e=>this.processLegacyStats(e))),this.negotiationCompletedPromise.promise.catch((()=>{})),this.negotiationCompletedPromise.reject("placeholder"),this.remoteVideoResolutionManager.on("onNegotiationRequired",(()=>this.triggerRenegotiation(!0))),this.remoteVideoResolutionManager.on("onSourceRequestRequired",((e,t,i)=>this.requestSource(e,t,i))),this.performanceMonitor=new xx(this.statsGatherer,this.diagnostics,this.configProvider,this.logger.createChild("PerformanceMonitor")),this.setSubsForSubscriptionManager(),this.setSubsForStreamManagerEvents(),this.configProvider.mediaConfig.maxBandwidthInKbps&&(this.statsGatherer.setMaxSessionBandwidth(this.configProvider.mediaConfig.maxBandwidthInKbps),this.diagnostics&&(this.diagnostics.maxSessionBandwidth=this.configProvider.mediaConfig.maxBandwidthInKbps)),this.createAudioRenderer(),this.setSubsForDeviceManager(),this.context.callDeviceManager.isVirtualDeviceEnabled&&this.setupCallDeviceManagerSubs(),this.configProvider.config.enableActiveSpeakerBasedDSH&&this.activeSpeakerManager.setStrategy(new tx({configProvider:this.configProvider})),this.perfMonitorSubs.push(this.performanceMonitor.on("onIncomingVideoQualityChanged",((e,t)=>{this.onIncomingVideoQualityChanged(e,t)}))),this.configProvider.config.webrtcVideoScaling&&(this.perfMonitorSubs.push(this.performanceMonitor.on("onOptimalVideoCountChanged",((e,t)=>{this.onOptimalVideoCountChanged(e,t)}))),this.onOptimalVideoCountChanged(this.configProvider.config.nonEstimatedDefaultVideoReceiversCount))}get iceTransportPolicy(){return this.configProvider.getIceTransportPolicy()}getAcceptedTypes(){return this.allowedMediaContentType}clone(t,i){const n=ot(this.context);n.config=ot(this.context.config),n.config.webrtcMediaContentType=this.mediaContentType,n.config.webrtcAllowedMediaContentType=this.allowedMediaContentType,n.configProvider=i,n.diagnostics=this.context.diagnostics?.newNativeSession(!1),t?(n.config.isConference=!0,n.config.isPstnCall=!1):(n.config.iceHostCandidateOnly=!1,this.configProvider.config.waitForRelayOnReconnect&&(n.config.webrtcIceGatheringTimeoutIncreased=!0));const r=new e(n,this.callId,this.callback);return this.useNullAudioStream&&r.useNullAudioStreamClient(),this.relayManagerProvider&&(r.relayManagerProvider=this.relayManagerProvider),r.callbacks.onNegotiationRequired=this.callbacks.onNegotiationRequired,r}async setCallConstraints(e,t){const i=this.configProvider.setCallConstraints(e);if(this.logger.safe.info(`[${t}] Setting call constraints ${JSON.stringify(i)}, enableDynamicCallConstraints: ${this.configProvider.config.enableDynamicCallConstraints}`),this.configProvider.config.enableDynamicCallConstraints)try{await this.streamSendersManager.applyCallConstraints(t),this.configProvider.addCallConstraintsTelemetryEvent(i,"applied")}catch(e){throw this.logger.safe.error(`Error while applying constraints: ${e}`),e}else this.configProvider.addCallConstraintsTelemetryEvent(i,"applied");return i}setInternals(e,t){if(this.logger.safe.info(`[${t}] Setting internals from previous session`),this.diagnostics?.commitNativeSession(),e.extensionsManager&&this.extensionsManager){const t=e.extensionsManager.getExtension("videoStreamControl");t?.getOptions()&&this.extensionsManager.configureExtension("videoStreamControl",t.getOptions())}e.subscriptionManager&&(this.subscriptionManager?.dispose(),this.subscriptionManager=e.subscriptionManager,this.subscriptionManager.setDiagnostics(this.diagnostics?.newSubscriptionManagerDiagnostics()),this.subscriptionManager.setStreamProvider({getStreams:()=>this.receiveStreamCollection.getStreams(),setOnStreamsChangedHandler:e=>this.streamsChangedListener=e}),this.subscriptionManager.setLogger(this.logger.createChild("subs")),this.setSubsForSubscriptionManager(),this.subscriptionManager.reriseSubscribeEvents(),this.notifyStreamsChanged()),e.audioRenderer&&(e.audioRenderer.play(this.audioRenderer.getStream()),this.audioRenderer=e.audioRenderer),e.remoteVideoManager?.moveRenderers(this.remoteVideoManager),e.rawIncomingAudioStreamManager&&this.rawIncomingAudioStreamManager.updateHandlers(e.rawIncomingAudioStreamManager.handlerMap),this.audioRenderer.getStream()&&this.rawIncomingAudioStreamManager.streamChanged(this.audioRenderer.getStream())}setSubsForDeviceManager(){const e=this.getVideoDeviceManager();this.deviceManagerSubs=[e.on("onLocalRendererStarted",(e=>e.setStatsProvider(this.statsGatherer)))],this.configProvider.config.enablePlayVideoOnStreamUnmuteWorkaround&&this.deviceManagerSubs.push(e.on("onAudioStreamMuted",(e=>{e||this.remoteVideoManager.playVideo()})))}setSubsForSubscriptionManager(){this.subscriptionManagerSubs=[this.subscriptionManager.on("onTrackIdsChanged",(e=>this.statsGatherer.setSubscribedTrackIds(e))),this.subscriptionManager.on("onTrackSsrcChanged",(e=>this.statsGatherer.setSubscribedTrackSsrc(e))),this.subscriptionManager.on("onSubscriptionChanged",((e,t,i,n,r,a)=>this.onSubscriptionChanged(e,t,i,n,r,a))),this.subscriptionManager.on("onSubscriptionFailed",((e,t,i,n,r)=>this.statsGatherer.addSubscriptionEvent(e,t,i,n,r)))]}onSubscriptionChanged(e,t,i,n,r,a){t===Qe.MODALITY.video&&(2===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount()),3===e&&this.diagnostics.addSubscriptionToOvcEvent(this.subscriptionManager.getSubscriptionsCount())),this.statsGatherer.addSubscriptionEvent(e,t,i,n,null,r,a)}setSubsForStreamManagerEvents(){this.streamSendersManager.on("onSendStreamChanged",((e,t)=>{this.statsGatherer.updateSendStream(e,t),e?.hasAudio()&&this.diagnostics?.setAudioSendStream(e,t),this.diagnostics?.setPresentationAudioOnScreenSharing(e,t)})),this.streamSendersManager.on("onVideoCaptureFreeze",(e=>{this.isConnected()&&this.ufdManager.signalEvent("VideoCaptureDeviceFreeze",e?"Bad":"Good","Video")})),this.streamSendersManager.on("onMaxVideoSendCapabilitiesChanged",((e,t)=>this.onMaxVideoSendCapabilitiesChanged(e,t)))}move(e,t){this.logger.safe.info(`[${t}] moving to new session`),e.setInternals({subscriptionManager:this.subscriptionManager,extensionsManager:this.extensionsManager,audioRenderer:this.audioRenderer,remoteVideoManager:this.remoteVideoManager,rawIncomingAudioStreamManager:this.rawIncomingAudioStreamManager},t),e.muteHold(this.isMuteHold,t),this.doAudioMute?e.muteInputAsync(t):e.unmuteInputAsync(t),this.subscriptionManager=null,this.audioRenderer=null,this.rawIncomingAudioStreamManager=null,this.callbacks.onTerminated=null}setMute(e,t,i){this.logger.safe.info(`[${i}] call setMute for ${e} with mute state ${t}`),this.streamSendersManager.setMuted(e,t,i),this.processLegacyStats(this.statsGatherer.getLastStatistics())}configureModalitiesAsync(e,t){const i=(async()=>{if(await this.configuredModalitiesPromise,!e||!e.audio&&!e.video&&!e.sharing)throw new Error(`Invalid parameters! ${JSON.stringify(e)}`);const i=ot(e),n=ot(this.negotiatedModalities);this.configProvider.config.alwaysNegotiateDataChannel&&(delete i.data,delete n.data);const r=!this.configuredModalities||!Xg(i,n);this.configuredModalities=e,this.logger.safe.info(`[${t}] configure modalities`,`audio: ${e.audio}`,`video: ${e.video}`,`sharing: ${e.sharing}`,`data: ${e.data}`,`peerconnection: ${!!this.peerConnection}`,`pc.signalingState: ${this.peerConnection?.signalingState??"-"}`,`needNewRenegotiation: ${r}`),r&&(this.updateSendStreamsReinviteless(t)||(this.configProvider.config.removeSendersOnConfigureModalities&&!Jg(this.configuredModalities)&&await this.streamSendersManager.update(this.configuredModalities,!0,t),this.triggerRenegotiation(!1,t)))})();return this.configuredModalitiesPromise=i.catch((e=>{this.logger.safe.warn(`[${t}] Error during configuring modalities: ${Be(e)}`)})),i}getConfiguredModalities(){return this.configuredModalities}getDisabledModalities(){return this.disabledModalities}createAudioElement(e){this.audioRenderer.assureAudioElement(e)}useNullAudioStreamClient(){this.useNullAudioStream=!0,this.streamSendersManager.useNullAudioStreamClient()}createOfferAsync(e){const t=this.negotiationQueue.add((()=>this.doCreateOfferAsync(e)),e);return this.resetNegotiationQueue(e),t}getTimerTracker(e,t){return this.diagnostics?this.diagnostics.getTimerTracker(e,t):this.statsGatherer.getTimerTracker(e,t)}async doCreateOfferAsync(e){const t=this.getTimerTracker("createOfferAsync",{first:!0});t.mark("start"),this.logger.safe.info(`[${e}] create [offer] configured: ${JSON.stringify(this.configuredModalities)}`),this.initiator=!0,this.throwIfModalitiesNotConfigured("no configured modalities to create offer for"),this.canTriggerRenegotiation=!1,this.negotiatingModalities=this.configuredModalities,await this.assurePeerConnectionAsync(e,t.clone("assurePeerConnectionAsync")),t.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${e}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.peerConnection.signalingState)}`),Jg(this.negotiatingModalities)&&!at(this.negotiatedModalities)&&Object.keys(this.negotiatingModalities).forEach((e=>{void 0===this.negotiatedModalities[e]&&delete this.negotiatingModalities[e]})),this.transceiverManager.assureTransceivers(this.negotiatingModalities);const i=await this.assureStreamsAndDataChannel(this.negotiatingModalities,e,t.clone("assureStreamsAndDataChannel"));t.markAndMeasure("assurePeerConnectionAsync","assureStreamsAndDataChannel"),this.offeredModalities=i,!vm(this.context)&&this.configProvider.config.webrtcNegotiateDisabledDataModality&&!this.offeredModalities[Qe.MODALITY.data]&&this.multiParty&&(this.offeredModalities[Qe.MODALITY.data]=Qe.MEDIA_STATE.inactive),this.configureAudioCodec(),this.logger.safe.info(`[${e}] create [offer] offered: ${JSON.stringify(this.offeredModalities)}`);const n=await this.peerConnection.createOffer();t.markAndMeasure("assureStreamsAndDataChannel","createOffer"),this.logger.unsafe.debug(`[${e}] create [offer] offer from peer connection, sdp: ${n.sdp}`);const r=this.sessionDescription.createLocalOffer(n.sdp);this.hasIceCandidates(r)||this.resetCandidateGathering(e),this.statsGatherer.startWaitingForStreamStart(this.offeredModalities),this.diagnostics&&(this.diagnostics.offeredModalities=i),this.setupIceGatheringTimeout(e);const a=r.toLocal();this.logger.unsafe.debug(`[${e}] create [offer] set local description`,"sdp:",a),await this.peerConnection.setLocalDescription({sdp:a,type:"offer"}),t.markAndMeasure("createOffer","sLD"),await this.iceCandidatesDeferred.promise,t.markAndMeasure("sLD","candidates");const s=this.sessionDescription.createLocalOffer(this.peerConnection.localDescription.sdp);this.fixLocalDescription(s),s.updateModalities(this.offeredModalities),this.checkIceCandidates(s);const o=s.toOffer();this.logger.unsafe.debug(`[${e}] CREATE OFFER`,"sdp:",o);const l={blob:o,contentType:this.mediaContentType};return""===this.configProvider.mediaConfig.webrtcRequiredFeatures||this.multiParty||(l.requiredFeatures=this.configProvider.mediaConfig.webrtcRequiredFeatures),this.audioCodecManager.decoder?.setRecvPayloads(s.getPayloadsForMedia(Qe.MEDIA_TYPE.audio)),this.configProvider.countryCode&&(l.clientLocation=this.configProvider.countryCode),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)})),this.doRetargetIfNeeded(l,r,e),this.reinvitelessContext.enabled&&(this.mediaManager.updateMediaEntitiesWithLocalTracks(),l.mediaDescriptions=this.getMediaDescriptions(this.offeredModalities)),this.setBWSeed(l),t.markAndMeasure("start","createOfferAsync"),l}processOfferAsync(e,t){const i=this.negotiationQueue.add((()=>this.doProcessOfferAsync(e,t)),t);return this.resetNegotiationQueue(t),i}async doProcessOfferAsync(e,t){const i=this.getTimerTracker("processOfferAsync",{first:!0});i.mark("start"),this.mediaManager.backup();const n=e.blob;if(this.logger.unsafe.debug(`[${t}] process [offer]`,"sdp:",n),this.configProvider.config.webrtcCompareContentTypeInOffer&&(ht(e.contentType,this.allowedMediaContentType),this.mediaContentType=e.contentType),this.checkOfferOriginator(e),this.offerOriginator=e.originator,e.requiredFeatures){const t=this.configProvider.mediaConfig.webrtcRejectedFeatures.split(",");pt(e.requiredFeatures.split(","),t)}if(this.initiator=!1,this.offeredDescription=this.sessionDescription.createRemoteOffer(n),this.configProvider.config.multiStreamSupported){const e=function(e){const t=e.match(/a=x-multi-stream:(\d+)/);if(t)return parseInt(t[1])}(n),i=this.configProvider.config.numVideoChannelsGvc-this.configProvider.config.nonMultiStreamChannels;this.context.configProvider.mediaConfig.multiStreamChannelsOffered=e,e&&e<i&&(this.logger.safe.info(`Received ${e} multi stream channels, ${i} channels supported`),this.triggerRenegotiation(!0,t))}this.canTriggerRenegotiation=!1,this.offeredModalities=jg(this.offeredDescription.getModalities()),this.assignUnbundledTransport();let r=this.configProvider.config.removeUnsupportedVideoModality?this.offeredModalities:ot(this.offeredModalities);if(Wg(this.offeredModalities.video)||qg(this.offeredModalities.video)||Wg(this.offeredModalities.sharing)||qg(this.offeredModalities.sharing)){const n=this.offeredDescription.getVideoCodecs();try{i.mark("startGetCapabilities");const e=await this.capabilityGatherer.getCapabilities("video");i.markAndMeasure("startGetCapabilities","getCapabilities"),e.codecs.some((e=>n.some((t=>e.mimeType===t&&this.configProvider.config.primaryVideoCodecs.includes(t)))))||(this.logger.safe.warn(`[${t}] offer doesn't contain any supported video codecs`),this.disabledModalities.video=r.video,this.disabledModalities.sharing=r.sharing,delete r.video,delete r.sharing)}catch(e){this.logger.safe.error(`[${t}] failed to get video capability ${Be(e)}`)}}return(!vm(this.context)&&(Wg(this.offeredModalities.data)||qg(this.offeredModalities.data))||this.dataChannel&&"Failed"===this.dataChannel.state)&&(this.logger.safe.info(`[${t}] Supressing data modality as data channel is not possible`),r=ot(r),delete r.data),i.markAndMeasure("start","processOfferAsync"),this.logger.safe.info(`[${t}] process [offer] offered: ${JSON.stringify(this.offeredModalities)} acceptable: ${JSON.stringify(r)}`),r}assignUnbundledTransport(){this.peerConnection||(this.context.configProvider.mediaConfig.isTransportUnbundled?this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.couldBeUnbundled():this.context.configProvider.mediaConfig.isTransportUnbundled=this.offeredDescription.isUnbundled())}checkOfferOriginator(e){if(this.offerOriginator&&this.offerOriginator!==e.originator&&this.configProvider.config.rejectIncompatibleOriginator)throw{detail:"mediaContent.originator is different on renegotiation",type:Qe.MEDIA_ERROR.incompatibleOriginator}}async createAnswerAsync(e,t){if(e)return{blob:"",contentType:this.mediaContentType};const i=this.getTimerTracker("createAnswerAsync",{first:!0});i.mark("start"),this.logger.safe.info(`[${t}] create [answer] offered: ${JSON.stringify(this.offeredModalities)} configured: ${JSON.stringify(this.configuredModalities)}`),this.throwIfModalitiesNotConfigured("no configured modalities to create answer for");const n=this.configuredModalities;let r=this.negotiatingModalities=Yg(this.offeredModalities,n);await this.assurePeerConnectionAsync(t,i.clone("assurePeerConnectionAsync")),i.markAndMeasure("start","assurePeerConnectionAsync"),this.logger.safe.info(`[${t}] updatePeerConnectionStreamsAsync, pc state: ${JSON.stringify(this.peerConnection.signalingState)}`),await this.handleCodecSwitchUnsupported(t),i.markAndMeasure("assurePeerConnectionAsync","handleCodecSwitchUnsupported"),this.configureAudioCodec();const a=this.offeredDescription.toRemote(r);this.logger.unsafe.info(`[${t}] create [answer] set remote description', 'negotiated:`,r,"sdp:",a),await this.peerConnection.setRemoteDescription({sdp:a,type:"offer"}),i.markAndMeasure("handleCodecSwitchUnsupported","setRemoteDescription"),this.transceiverManager.syncTransceivers(r),this.mediaManager.getMediaEntities().forEach((e=>{e.setExtension("midApplied",!0)})),await this.assureStreamsAndDataChannel(r,t,i.clone("assureStreamsAndDataChannel")),i.markAndMeasure("setRemoteDescription","assureStreamsAndDataChannel"),this.callbacks.onTransportInitialized&&this.callbacks.onTransportInitialized();const s=await this.peerConnection.createAnswer();i.markAndMeasure("assureStreamsAndDataChannel","createAnswer"),this.logger.unsafe.debug(`[${t}] create [answer] answer from peer connection`,"sdp:",s.sdp);const o=this.sessionDescription.createLocalAnswer(s.sdp);this.hasIceCandidates(o)||this.resetCandidateGathering(t),this.statsGatherer.startWaitingForStreamStart(r),this.diagnostics&&(this.diagnostics.offeredModalities=r),this.setupIceGatheringTimeout(t);const l=o.toLocal();this.logger.unsafe.debug(`[${t}] create [answer] set local description`,"sdp:",l),await this.peerConnection.setLocalDescription({sdp:l,type:"answer"}),i.markAndMeasure("createAnswer","sLD"),await this.iceCandidatesDeferred.promise,i.markAndMeasure("sLD","candidates");const c=this.sessionDescription.createLocalAnswer(this.peerConnection.localDescription.sdp);this.fixLocalDescription(c),c.updateModalities(r),this.checkIceCandidates(c);const d=c.toAnswer();this.audioCodecManager.decoder?.setRecvPayloads(c.getPayloadsForMedia(Qe.MEDIA_TYPE.audio)),this.checkAudioCodecNegotiated(t),await this.streamSendersManager.activate(t),i.markAndMeasure("candidates","streamSendersManagerActivate"),this.updateLocalMediaSources(),this.applyReceiveCapabilities(),r=c.getModalities(),this.reinvitelessContext.enabled&&(r=im(this.negotiatingModalities,r)),Zg(this.configuredModalities,this.negotiatingModalities,r)||this.triggerRenegotiation(!0,t),this.setNegotiatedModalities(r),this.statsGatherer.sessionInfo.setBweType(c.getBweType()),this.diagnostics&&(this.diagnostics.bweType=c.getBweType()),this.logger.unsafe.debug(`[${t}] CREATE ANSWER`,"sdp:",d);const u={blob:d,contentType:this.mediaContentType};return this.configProvider.countryCode&&(u.clientLocation=this.configProvider.countryCode),this.reinvitelessContext.enabled&&(u.mediaDescriptions=this.getMediaDescriptions(r)),this.setBWSeed(u),i.markAndMeasure("start","createAnswerAsync"),u}async processAnswerAsync(e,t,i,n=!1){const r=e.blob;this.logger.unsafe.debug(i?`[${t}] PROCESS PRANSWER`:`[${t}] PROCESS ANSWER`,"sdp:",r);const a=i?"pranswer":"answer";if(i&&(!Em(this.context,n)||"have-local-offer"!==this.peerConnection.signalingState))return void this.logger.safe.info(`[${t}] process [${a}] ignored`);const s=this.getTimerTracker(i?"processProvisionalAnswerAsync":"processAnswerAsync",{first:!0});s.mark("start");const o=this.sessionDescription.createRemoteAnswer(r);let l=jg(o.getModalities());this.reinvitelessContext.enabled&&(l=im(this.offeredModalities,l));const c=o.toRemote(l);i||(this.mediaContentType=e.contentType,-1===this.allowedMediaContentType.indexOf(this.mediaContentType)&&this.allowedMediaContentType.push(this.mediaContentType),Jg(l)||(await this.streamSendersManager.update(l,!0,t),s.markAndMeasure("start","streamSendersManagerUpdate"),Wg(this.offeredModalities.data)&&!l.data&&this.dataChannel?.disable()),this.setNegotiatedModalities(l),this.updateLocalMediaSources(),this.statsGatherer.sessionInfo.setBweType(o.getBweType()),this.diagnostics&&(this.diagnostics.bweType=o.getBweType())),this.callbacks.onTransportInitialized?.(),this.logger.unsafe.info(`[${t}] process [${a}] set remote description`,"negotiated:",l,"sdp:",c),s.mark("startSetRemoteDescription"),await this.peerConnection.setRemoteDescription({sdp:c,type:a}),s.markAndMeasure("startSetRemoteDescription","setRemoteDescription"),i||(await this.streamSendersManager.activate(t),s.markAndMeasure("setRemoteDescription","streamSendersManagerActivate"),this.applyReceiveCapabilities(),this.checkAudioCodecNegotiated(t),this.transceiverManager.syncTransceivers(l),s.markAndMeasure("start","processAnswerAsync"))}async completeNegotiationAsync(e){this.mediaManager.commit();const t=this.configuredModalities,i=this.forceMediaStreamUpdate&&!Jg(this.negotiatedModalities)||!Zg(t,this.negotiatingModalities,this.negotiatedModalities)||this.triggerRenegotiationFlag,n=!i;this.canTriggerRenegotiation=!0,this.logger.safe.info(`[${e}] negotiation completed isComplete: ${n} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),i&&this.triggerRenegotiation(!1,e);for(const e of this.getVideoDeviceManager().getLocalVideoRenderers())e.setStatsProvider(this.statsGatherer);return this.negotiationCompletedPromise.resolve(),{isComplete:n,activeModalities:this.negotiatedModalities,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator}}async rejectNegotiationAsync(e,t,i=!1){let n;this.mediaManager.rollback(),this.logger.safe.warn(`[${t}] negotiation rejected isComplete: ${!i} error: ${Be(e)} configured: ${JSON.stringify(this.configuredModalities)} negotiating: ${JSON.stringify(this.negotiatingModalities)} offered: ${JSON.stringify(this.offeredModalities)} negotiated: ${JSON.stringify(this.negotiatedModalities)}`),this.qualityManager.clearPendingCapabilities();const r=this.getModalitiesForRollback(t);if(this.transceiverManager?.syncTransceivers(r),await this.assureStreamsAndDataChannel(r,t),"have-local-offer"===this.peerConnection?.signalingState){n={},this.logger.safe.info(`[${t}] rolling back local description`);try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRollback){n.type="LocalRN",this.logger.safe.info(`[${t}] rolling back using local renegotiation`);const e=[new Zk(this.peerConnection,this.configProvider,this.logger)];await this.negotiationEmulator.renegotiate(e,!0),this.logger.safe.info(`[${t}] rolling back using local complete`)}else this.logger.safe.info(`[${t}] rolling back using rollback`),n.type="Rollback",await this.peerConnection.setLocalDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error`,e),n.error=e}}else if("have-remote-offer"===this.peerConnection?.signalingState){n={};try{if(!this.isRollbackSupported||this.configProvider.config.webrtcHandleRemoteRollback){n.type="RemoteRN",this.logger.safe.info(`[${t}] applying answer for remote renegotiation`);const e=[new Zk(this.peerConnection,this.configProvider,this.logger)];await this.negotiationEmulator.renegotiate(e,!0,"remote")}else this.logger.safe.info(`[${t}] rolling back using rollback on remote description`),n.type="Rollback",await this.peerConnection.setRemoteDescription({type:"rollback"})}catch(e){this.logger.safe.error(`[${t}] rollback error`,e),n.error=e}}else this.peerConnection&&this.logger.safe.error(`[${t}] cannot rollback local description in current state: ${this.peerConnection.signalingState}`);return this.canTriggerRenegotiation=!0,this.negotiationCompletedPromise.reject("negotiation rejected"),i&&(this.logger.safe.info(`[${t}] retrying failed negotiation`),this.triggerRenegotiation(!1,t)),{isComplete:!i,activeModalities:r,offeredModalities:this.offeredModalities,attemptedModalities:this.negotiatingModalities,configuredModalities:this.configuredModalities,initiator:this.initiator,rollback:n}}async startMediaDescriptionsUpdateAsync(e){return this.reinvitelessAppliedModalities=await this.assureStreamsAndDataChannel(this.reinvitelessRequestedModalities,e),this.updateLocalMediaSources(),await this.streamSendersManager.activate(e),this.getMediaDescriptions(this.reinvitelessAppliedModalities)}async completeMediaDescriptionsUpdateAsync(e){this.logger.safe.info(`[${e}] complete media descriptions update`),this.setNegotiatedModalities(this.reinvitelessAppliedModalities);const t=this.reinvitelessAppliedModalities,i=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:t,requestedModalities:i}}async rejectMediaDescriptionsUpdateAsync(e,t=!1){this.logger.safe.info(`[${e}] reject media descriptions update`),t&&(this.logger.safe.info(`[${e}] trigger renegotiation after failed media descriptions update`),this.triggerRenegotiation(!1,e));const i=await this.streamSendersManager.update(this.negotiatedModalities,!0,e),n=this.reinvitelessRequestedModalities;return this.reinvitelessAppliedModalities={},this.reinvitelessRequestedModalities={},{appliedModalities:i,requestedModalities:n}}createRemoteRenderer(e){return this.remoteVideoManager.createRenderer(e,this.subscriptionManager,this.logger)}getStatsAsync(e){if(this.statsGatherer&&!this.statsGatherer.isDisposed){if(this.audioCodecManager){const e=this.audioCodecManager.getSessionEvents();this.statsGatherer.sessionInfo.setAudiocCodecEvents(e),this.diagnostics&&(this.diagnostics.audioCodecEvents=e)}this.statisticsReport=this.statisticsReport.then((()=>this.statsGatherer.getReport(e))).catch((e=>(this.logger.safe.error(`getting statistics should never fail: ${e.error}`),e.partialReport)))}return this.statisticsReport}getLastKnownStats(e){return this.statsGatherer.getReport(!1,e)}muteHold(e,t){this.logger.safe.info(`[${t}] set muteHold state ${e}`),this.isMuteHold=e;const i=[Qe.MODALITY.audio,Qe.MODALITY.video,Qe.MODALITY.sharing].filter((e=>Wg(this.negotiatedModalities[e])&&(e!==Qe.MODALITY.audio||!this.doAudioMute)));for(const n of i)this.setMute(om(n),e,t)}async muteInputAsync(e){this.doAudioMute=!0,this.setMute("Audio",!0,e)}async unmuteInputAsync(e){this.doAudioMute=!1,this.setMute("Audio",!1,e)}muteOutputAsync(e){return this.audioRenderer.setMuted(!0,e)}unmuteOutputAsync(e){return this.audioRenderer.setMuted(!1,e)}sendDtmf(e){return this.dtmfSender.sendDtmf(this.peerConnection,e)}canSendDtmf(){return this.dtmfSender.canSendDtmf(this.peerConnection)}pauseNegotiations(e=Te()){const t=new Jh;return this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.setNegotiationPromise(t,e)})),t}getExtensionsManager(){return this.extensionsManager}onDeviceEvent(e){this.statsGatherer.onDeviceEvent(e)}deviceSelectionChanged(){this.peerConnection&&this.audioRenderer?.getStream()&&this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId())}async terminate(e,t,i=!0){this.logger.safe.info(`[${e}] terminate`),this.statsGatherer.setTerminated(),this.diagnostics?.terminate(),this.perfMonitorSubs.forEach((e=>e?.dispose())),this.performanceMonitor.dispose(),this.terminated=!0,this.canTriggerRenegotiation=!1,await(this.audioCodecManager.decoder?.storeApiRecording()),this.cleanUp(e);try{i&&await this.getStatsAsync(!1)}catch(t){this.logger.safe.error(`[${e}] Error while gathering stats ${Be(t)}`)}finally{this.statsGatherer.dispose()}}getIncomingRawAudioStream(){this.logger.info("IRawStream for incoming audio stream requested");const e=this.audioRenderer.getStream();return this.rawIncomingAudioStreamManager.createIRawStreamClient(e)}getUnmixedAudioProvider(){return this.audioCodecManager.decoder?.getUnmixedAudioProvider()}configureSpatialAudio(e,t){this.configProvider.mediaConfig.spatialAudioEnabled=e,this.audioCodecManager.configureSpatialAudio(e,t)||this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable","Bad","Audio",!0,t)}setParticipantSpatialAudioPositions(e,t){if(!this.configProvider.mediaConfig.spatialAudioEnabled||!this.audioCodecManager?.decoder)throw this.logger.safe.error(`[${t}] setParticipantSpatialAudioPositions is called while MUCH audio decoder is not created or not enabled`),"setParticipantSpatialAudioPositions not allowed";this.audioCodecManager.decoder?.setParticipantSpatialAudioPositions(e)}processNotification(e,t){this.performanceMonitor.processNotification(e,t)}cleanUp(e){this.negotiationQueue.dispose(),this.rawIncomingAudioStreamManager?.dispose(),this.remoteVideoManager.dispose(),this.dataChannel&&(this.dataChannel.dispose(),this.dataChannel=null),this.deviceManager.effectsManager.setAecRefStream(null),this.resetPeerConnection(e),this.subscriptionManagerSubs.forEach((e=>e.dispose())),this.subscriptionManager&&this.subscriptionManager.dispose(),this.deviceManagerSubs.forEach((e=>e.dispose())),this.callDeviceManagerSub?.dispose(),this.clearIceDisconnectedTimer(),this.extensionsManager&&this.extensionsManager.dispose(),this.callbacks.onTerminated&&this.callbacks.onTerminated(),this.negotiationCompletedPromise.reject("webRtcSession cleanup")}resetPeerConnection(e){this.logger.safe.info(`[${e}] reset peer connection`),this.contributingSources?.dispose(),this.activeSpeakerManager.dispose(),this.qualityManager?.dispose(),this.qualityManager=null,this.audioRenderer?.dispose(),this.dtmfSender?.dispose(),this.dtmfSender=null,this.streamSendersManager?.dispose(),this.streamSendersManager=null,this.transceiverManager=null,this.encStreamsManager.dispose(),this.receiveStreamCollection.clear(),this.transportStateProvider?.dispose(),this.transportStateProvider=null,this.audioCodecManager.dispose(),this.mediaManager.reset(),this.peerConnection?.close(),this.peerConnection=null,this.toBeCalledAfterConnected=[],this.negotiationEmulator.configure(null),this.peerConnectionPromise=null,this.resetCandidateGathering(e),this.canTriggerRenegotiation=!0,this.negotiatedModalities={}}resetNegotiationQueue(e){this.negotiationCompletedPromise.reject("promise expired"),this.setNegotiationPromise(new Jh,e)}setNegotiationPromise(e,t=Te()){this.terminated||(this.negotiationCompletedPromise=e,this.negotiationQueue.add(this.negotiationCompletedPromise,t))}setupExtensionsManager(){const e=new ND(this.logger.createChild("ExtMgr"));return e.addExtension("dominantSpeakerHistory",{logger:this.logger,callback:this.activeSpeakerManager.onDominantSpeakerHistoryChanged.bind(this.activeSpeakerManager)}),e.addExtension("videoStreamControl",{logger:this.logger,negotiationEmulator:this.negotiationEmulator,qualityManager:this.qualityManager,diagnostics:this.qmDiagnostics,configProvider:this.configProvider,statisticsGatherer:this.statsGatherer}),e.addExtension("bandwidthTelemetry",{statisticsGatherer:this.statsGatherer,diagnostics:this.diagnostics}),this.configProvider.config.setBWSeed&&e.addExtension("bandwidthCache",{logger:this.logger,configProvider:this.configProvider}),e}processStatsReport(e){if(this.remoteVideoManager.processStatsReport(e),this.configProvider.config.diagnostics.features.useNewNetworkUFD){this.networkQualityDiagnostics.processReport(e);const t=this.networkQualityDiagnostics.getInboundNetworkQuality();this.ufdManager.signalEvent("NetworkRecvQuality",t);const i=this.networkQualityDiagnostics.getOutboundNetworkQuality();this.ufdManager.signalEvent("NetworkSendQuality",this.doAudioMute?"Good":i)}this.configProvider.config.diagnostics.features.useNewSpeakingWhileMutedUFD&&this.ufdManager.signalEvent("DeviceSpeakWhileMuted",this.speechDetectionDiagnostics.processReport(e)?"Bad":"Good")}processLegacyStats(e){if(e&&(this.remoteVideoManager.processLegacyStats(e),this.hwSilent!==e.audioHwSilent&&(this.hwSilent=e.audioHwSilent,this.callbacks.onAudioHwSilentChanged&&this.callbacks.onAudioHwSilentChanged(this.hwSilent)),this.configProvider.config.diagnostics.features.useNewNetworkUFD||(this.ufdManager.signalEvent("NetworkRecvQuality",e.networkRecvLevel.quality,void 0,void 0,void 0,void 0,{recvQualityData:e.networkRecvLevel}),this.ufdManager.signalEvent("NetworkSendQuality",this.doAudioMute?"Good":e.networkSendLevel.quality,void 0,void 0,void 0,void 0,{sendQualityData:e.networkSendLevel})),!this.configProvider.config.diagnostics.features.useNewSpeakingWhileMutedUFD)){const t=!(!e.isSpeaking||!this.doAudioMute);this.ufdManager.signalEvent("DeviceSpeakWhileMuted",t?"Bad":"Good")}}triggerRenegotiation(e,t=Te()){this.canTriggerRenegotiation?(this.canTriggerRenegotiation=!1,this.triggerRenegotiationFlag=!1,this.logger.safe.info(`[${t}] triggering renegotiation`),this.mediaManager.backup(),this.callbacks.onNegotiationRequired&&this.callbacks.onNegotiationRequired(t)):e&&(this.logger.safe.info(`[${t}] renegotiation postponed`),this.triggerRenegotiationFlag=!0)}throwIfModalitiesNotConfigured(e){if(!this.configuredModalities)throw new Error(e)}async handleCodecSwitchUnsupported(e){if(!this.offeredDescription.isCodecSwitchSupported())try{const e=(await this.capabilityGatherer.getCapabilities(Qe.MEDIA_TYPE.audio)).codecs.map((e=>e.mimeType));this.offeredDescription.usePrimaryAudioCodecOnly(e)}catch(t){this.logger.safe.error(`[${e}] failed to set primary codec based on audio capability ${Be(t)}`)}}assurePeerConnectionAsync(e,t){return this.peerConnectionPromise??(this.peerConnectionPromise=this.getPeerConnectionPromise(e,t)),this.peerConnectionPromise}async getPeerConnectionPromise(e,t){if(!this.relayManagerProvider)throw new Error("relay manager provider is not set!");this.logger.safe.info(`[${e}] fetching relay details from RelayManager...`);const i={relayType:"turn",isRemoteClientLync:this.context.config.isRemoteClientLync};t.mark("startQueryRelaysAsync");const n=await this.relayManagerProvider.getRelayManager().queryRelaysAsync(i);if(t.markAndMeasure("startQueryRelaysAsync","queryRelaysAsync"),this.terminated)throw new Error("session already disposed");const r={optional:[]},a=Mk(n,this.configProvider.config),s=this.configureCrypto(r);this.configureCpuThreshold(r),this.logger.safe.info("create peer connection");const o="unified-plan",l=this.context.configProvider.mediaConfig.isTransportUnbundled?"balanced":"max-bundle";try{this.peerConnection=new Ug.window.RTCPeerConnection({iceServers:a,rtcpMuxPolicy:"require",iceTransportPolicy:this.iceTransportPolicy,iceCandidatePoolSize:this.configProvider.config.iceCandidatePoolSize,bundlePolicy:l,sdpSemantics:o,audioPortRange:this.configProvider.mediaConfig.audioPortRange,videoPortRange:this.configProvider.mediaConfig.videoPortRange,enableDtlsSrtp:1===s,encodedInsertableStreams:!!this.configProvider.config.useInsertableStreams},r)}catch(e){throw e.code===DOMException.INVALID_STATE_ERR&&this.ufdManager.signalEvent("NoNetwork","Bad"),e}const c=this.peerConnection;this.isRollbackSupported=1===s&&this.context.configProvider.userAgentConfig.isBrowserRollbackSupported,this.negotiationEmulator.configure(c),this.statsGatherer.initialize(c),this.statsGatherer.sessionInfo.setIceServers(a),this.statsGatherer.sessionInfo.setIceTransportPolicy(this.iceTransportPolicy),this.statsGatherer.sessionInfo.setSdpSemantics(o),this.statsGatherer.sessionInfo.setBundlePolicy(l),this.diagnostics&&(this.diagnostics.iceServers=a,this.diagnostics.iceTransportPolicy=this.iceTransportPolicy,this.diagnostics.sdpSemantics=o,this.diagnostics.bundlePolicy=l),await this.checkVideoCodecsSupport(),t.markAndMeasure("queryRelaysAsync","checkVideoCodecsSupport"),c.onnegotiationneeded=()=>{this.logger.safe.info(`onnegotiationneeded signalingState: ${c.signalingState}`)},c.onsignalingstatechange=()=>{const e=Te();this.statsGatherer.sessionInfo.setSignalingConnectionState(c.signalingState),this.diagnostics&&(this.diagnostics.signalingConnectionState=c.signalingState),this.logger.safe.info(`[${e}] onsignalingstatechange signalingState: ${c.signalingState}`),this.transportStateProvider&&this.transportStateProvider.subscribeForDtlsTransportState(),this.configProvider.config.reconnectOnPcClose&&!this.terminated&&"closed"===c.signalingState&&this.isTransportConnected()&&this.raiseError({type:Qe.MEDIA_ERROR.unexpectedClose,detail:"PeerConnection is closed"},e)},c.onicecandidateerror=e=>{const t=e,[i,n]=[t.address,t.port];if(this.logger.safe.warn(`On ICE candidate error ${t.url} | ${i}:${n}: code ${t.errorCode}: ${t.errorText}`),!this.isConnected()||this.iceCandidatesDeferred.isPending){const e={address:i,port:+n,url:t.url,errorCode:t.errorCode,errorText:t.errorText};this.statsGatherer.addIceCandidateError(e),this.diagnostics?.addIceCandidateError(e)}};const d=e=>{const{track:t,receiver:i,transceiver:n}=e,r=e.streams[0]??new MediaStream([t]);if(!(this.configProvider.config.addAudioStreamBeforeConnection&&Qe.TRACK_KIND.audio===t.kind||this.isConnected()))return this.logger.safe.info("ontrack handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>d(e)));this.logger.safe.info(`ontrack track ${t.id}, stream: ${r?.id}, transceiver=${n?.mid}`);let a=r?.active;if(!a&&this.configProvider.config.useInactiveAudioTrack&&"audio"===t.kind&&(this.logger.safe.warn("ontrack override forcing to use inactive audio stream"),a=!0),!a||"stopped"===n?.currentDirection||n?.stopped)return void this.logger.safe.info("ontrack ignore non active stream");let s=this.mediaManager.getMediaEntityByRemoteStreamId(r.id);if(s||(this.logger.safe.info(`cannot find media entity with stream id ${r.id} trying to fallback`),r.getAudioTracks()[0]&&(s=this.mediaManager.getMediaEntitiesByModality(Qe.MODALITY.audio)[0])),s){const e=this.createReceiveStream(r,i,t,s);s.setRemoteTrackId(t.id),this.addReceiveStreamTransforms(i,s.getModality()),this.receiveStreamCollection.add(e)}else this.logger.safe.error(`could not find media entity for an added stream: ${r.id}`)};c.onaddstream=e=>{this.logger.safe.info(`onaddstream stream: ${e.stream.id}`)},c.ontrack=d;const u=e=>{if(!this.isConnected())return this.logger.safe.info("onremovestream handling postponed till PC is connected"),void this.toBeCalledAfterConnected.push((()=>u(e)));this.logger.safe.info(`onremovestream stream: ${e.stream.id}`),this.receiveStreamCollection.remove(e.stream.id)};c.onremovestream=u,c.onicecandidate=t=>{const i=t.candidate;if(i){const t=nm(i.candidate);if(this.logger.safe.info(`[${e}] onicecandidate candidate: component:${t.component} protocol:${t.protocol} prio:${t.priority} type:${t.type} port:${t.port}`),this.logger.unsafe.info(`[${e}] candidate details: ${i.candidate}`),"1"!==t.component)return;if(this.iceCandidateReceived=!0,this.statsGatherer.sessionInfo.setCandidateDetails(t),this.diagnostics?.setCandidateDetails(t),!this.relayCandidateGathered&&i.candidate.indexOf("typ relay")>-1){const e={priority:i.priority?.toString()||t.priority,time:Date.now()-this.iceRelayCandidatesGatherStartTime};this.statsGatherer.sessionInfo.setRelayCandidateInfo(e),this.diagnostics&&(this.diagnostics.relayCandidateInfo=e),this.relayCandidateGathered=!0}}else this.logger.safe.info(`[${e}] onicecandidate candidate: null`);if(!this.iceCandidatesDeferred.isPending)return;const n=!this.initiator||!this.context.config.webrtcIceGatheringTimeoutIncreased,r=this.iceHostCandidateOnly||0===a.length;if(!i&&n||r){i&&this.logger.safe.info(`[${e}] Not waiting for ICE candidates, hoping that host/prflx is enough`),this.logger.safe.info(`[${e}] Is connected:`,this.isConnected(),c.iceConnectionState,c.signalingState);let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&i&&(t=this.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledIceCandidates()),t&&this.completeCandidateGathering(e)}else if(this.relayCandidateGathered){let t=!0;this.context.configProvider.mediaConfig.isTransportUnbundled&&(t=this.sessionDescription.createLocalOffer(c.localDescription.sdp).hasUnbundledRelayIceCandidates()),t&&(this.statsGatherer.clearIceCandidateErrors(),this.diagnostics?.clearIceCandidateErrors(),this.completeCandidateGathering(e))}},c.onicegatheringstatechange=()=>{this.logger.safe.info(`onicegatheringstatechange iceGatheringState: ${c.iceGatheringState}`)};const h=i=>{if(this.terminated)return;const n=this.wasConnected?Te():e,r=this.lastTransportConnectionState;if(this.lastTransportConnectionState=i,this.statsGatherer.sessionInfo.setIceConnectionState(i),this.diagnostics&&(this.diagnostics.iceConnectionState=i),"connecting"===i&&t.mark("transportConnecting"),"connected"===i||"completed"===i)t.markAndMeasure("transportConnecting","transportConnected"),this.onTransportConnected(n);else if("failed"===i||"closed"===i&&"failed"!==r){if(this.iceCandidatesDeferred.isPending)return this.logger.safe.info(`[${n}] ice failed while gathering candidates, suppressing error`),void this.completeCandidateGathering(n);this.raiseError({type:Qe.MEDIA_ERROR.iceConnectionError,detail:"ice transport failed"},n),this.configProvider.config.webrtcCloseAfterIceFailure&&c.close(),this.callbacks.onTransportFailed?.()}"disconnected"===i?(this.callbacks.onTransportDisconnected?.(e),this.startIceDisconnectedTimer(n)):this.clearIceDisconnectedTimer()};this.transportStateProvider=new ZL(c,s,this.logger,this.configProvider,(e=>h(e))),this.transceiverManager=new eL(this.logger,this.peerConnection,this.mediaManager,this.context,this.reinvitelessContext),this.streamSendersManager.registerRtpSenderManager(this.transceiverManager),vm(this.context)&&!this.dataChannel&&(this.dataChannel=new rg(this.peerConnection,this.statsGatherer,this.logger,this.configProvider),this.callback.onDataChannelUpdated(this.dataChannel)),this.multiParty&&(this.contributingSources=new SN(this.logger.createChild("ContributingSources"),this.configProvider,this.activeSpeakerManager,new yN(this.logger.createChild("ContributingSourcesProvider"),c))),t.mark("startInitialize"),await this.encStreamsManager.initialize(),t.markAndMeasure("startInitialize","encStreamsManagerInitialize");const p=this.encStreamsManager.isWorkerLoaded();this.initAudioCodec(p),this.statsGatherer.sessionInfo.setEncodedStreamWorkerLoaded(p),this.diagnostics&&(this.diagnostics.encodedStreamWorker=p)}configureCrypto(e){let t=!1;const i=mm(this.context);if(this.offeredDescription){const e=this.offeredDescription.getSrtpInfo();this.statsGatherer.sessionInfo.setOfferedSrtpInfo(e),this.diagnostics&&(this.diagnostics.offeredSrtp=e),t=!e.dtls||e.sdes&&i}else t=i;t&&(this.logger.safe.info("configuring peer connection to use sdes"),e.optional.push({DtlsSrtpKeyAgreement:!1}));const n={dtls:!t,sdes:!!t};return this.statsGatherer.sessionInfo.setNegotiatedSrtpInfo(n),this.diagnostics&&(this.diagnostics.negotiatedSrtp=n),t?0:1}configureCpuThreshold(e){this.configProvider.config.webrtcNativeCpuOveruseDisabled&&this.multiParty&&e.optional.push({googCpuOveruseDetection:!1})}completeCandidateGathering(e){this.iceCandidatesDeferred.isPending&&(this.logger.safe.info(`[${e}] ICE candidates gathered completely`),this.iceCandidatesDeferred.resolve())}onTransportConnected(e){if(this.logger.safe.info(`[${e}] audio transport connected`),this.statsGatherer.clearIceCandidateErrors(),this.diagnostics?.clearIceCandidateErrors(),!this.terminated)for(this.wasConnected=!0,this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval&&"have-remote-pranswer"===this.peerConnection.signalingState?this.handleEarlyMediaAudioState(e):this.callbacks.onAudioStateChanged?.(Qe.STREAMING_STATE.active,e),this.callbacks.onTransportConnected?.(e);this.toBeCalledAfterConnected.length;)this.toBeCalledAfterConnected.shift()()}handleEarlyMediaAudioState(e){const t=this.peerConnection.getReceivers().filter((e=>"audio"===e.track.kind))[0];if(!t)return this.logger.safe.warn(`[${e}] Connected transport with provisional answer with no audio receiver`),void this.callbacks.onAudioStateChanged?.(Qe.STREAMING_STATE.active,e);this.callbacks.onAudioStateChanged?.(Qe.STREAMING_STATE.started,e);const i=setInterval((async()=>{try{let n;this.logger.safe.debug(`[${e}] Polling audio receiver stats to detect early media start`);const r=await t.getStats();this.diagnostics?.registerEarlyMediaPoll();for(const e of r.values())if("inbound-rtp"===e.type){n=e;break}(this.terminated||!n||n.bytesReceived>0||"have-remote-pranswer"!==this.peerConnection.signalingState)&&(this.logger.safe.debug(`[${e}] Finished polling early media audio stats ${!this.terminated}`),this.terminated||this.callbacks.onAudioStateChanged?.(Qe.STREAMING_STATE.active,e),clearInterval(i))}catch(t){const n=Be(t);this.logger.safe.error(`[${e}] Error polling stats for pranswer: ${n}`),this.diagnostics?.addStatsError("WebrtcSession::earlyMediaPolling",n),this.callbacks.onAudioStateChanged?.(Qe.STREAMING_STATE.active,e),clearInterval(i)}}),this.configProvider.config.webrtcPranswerWaitForMediaPollingInterval)}startIceDisconnectedTimer(e){this.configProvider.config.iceDisconnectedTimeoutMs&&(this.iceDisconnectedTimer=setTimeout((()=>{this.logger.safe.error(`[${e}] ice disconnected for ${this.configProvider.config.iceDisconnectedTimeoutMs}ms. Raise ${Qe.MEDIA_ERROR.iceConnectionError}`),this.raiseError({type:Qe.MEDIA_ERROR.iceConnectionError,detail:"ice transport disconnected"},e)}),this.configProvider.config.iceDisconnectedTimeoutMs))}clearIceDisconnectedTimer(){this.iceDisconnectedTimer&&(clearTimeout(this.iceDisconnectedTimer),this.iceDisconnectedTimer=null)}raiseError(e,t=Te()){this.logger.safe.error(`[${t}] Media error occurred type: ${e.type} detail: ${e.detail}`),this.callbacks.onSessionErrorOccurred&&this.callbacks.onSessionErrorOccurred(e,t)}resetCandidateGathering(e){this.logger.safe.info(`[${e}] reset candidate gathering`),this.iceCandidatesDeferred.promise.then((()=>{}),(()=>{})),this.iceCandidatesDeferred.reject(new Error("reset candidate gathering")),this.iceCandidatesDeferred=new Jh,this.iceCandidateReceived=!1}checkIceCandidates(e){const t=this.hasIceCandidates(e);if(t===this.noIceCandidates&&(this.noIceCandidates=!this.noIceCandidates,this.ufdManager.signalEvent("NoNetwork",this.noIceCandidates?"Bad":"Good"),this.noIceCandidates))throw{type:Qe.MEDIA_ERROR.noNetworkError,detail:"no ice candidates"};if(t){const t=this.hasRelayIceCandidates(e);if(t===this.noRelayIceCandidates){if(!t&&this.isIceConnected())return;this.noRelayIceCandidates=!this.noRelayIceCandidates,this.ufdManager.signalEvent("NetworkRelaysNotReachable",this.noRelayIceCandidates?"Bad":"Good")}}}hasIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledIceCandidates():e.hasIceCandidates()}hasRelayIceCandidates(e){return this.configProvider.mediaConfig.isTransportUnbundled?e.hasUnbundledRelayIceCandidates():e.hasRelayIceCandidates()}doRetargetIfNeeded(e,t,i){const n=t.isIceRestart();this.logger.safe.info(`[${i}] ICE restart: ${n}`),this.context.configProvider.mediaConfig.isTransportUnbundled&&this.offeredDescription&&this.offeredDescription.isMSRTC()&&n&&!this.multiParty&&t.getSrtpInfo().sdes&&(e.newOffer=!0)}notifyStreamsChanged(){this.logger.safe.info(`Scheduling stream changed notification: ${this.streamsChangedNotificationScheduled}`),this.streamsChangedNotificationScheduled||this.negotiationCompletedPromise.promise.catch((()=>{})).then((()=>{this.streamsChangedNotificationScheduled=!1,this.streamsChangedListener&&this.streamsChangedListener()}))}async streamAdded(e){if(Qe.MODALITY.audio===e.getModality()&&(this.webrtcAudioRecvStream=e.getMediaStream(),await this.audioRenderer.setOutputDevice(this.deviceManager.getOutputDeviceId()),await this.updateAudioRendererStream(this.webrtcAudioRecvStream)),this.configProvider.config.mapSsrcToTrackForStats){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);this.statsGatherer.setSsrcTrackPair(t.getRemoteSsrc(),t.getRemoteTrackId())}this.notifyStreamsChanged()}async updateAudioRendererStream(e){await this.audioRenderer.play(e),await this.deviceManager.effectsManager.setAecRefStream(e),this.rawIncomingAudioStreamManager.streamChanged(e)}streamRemoved(e){if(Qe.MODALITY.audio===e.getModality())this.audioRenderer.getStream()===e.getMediaStream()&&(this.audioRenderer.stop(),this.rawIncomingAudioStreamManager.streamChanged(null)),this.deviceManager.effectsManager.setAecRefStream(null),this.webrtcAudioRecvStream=null;else if(Qe.MODALITY.video===e.getModality()){const t=this.mediaManager.getMediaEntityByRemoteStreamId(e.getMediaStream().id);t?.getLocalRecvCapabilities()?.resetToInitial()}this.clearReceiveStreamTransforms(e.getReceiver()),e.dispose(),this.notifyStreamsChanged()}setNegotiatedModalities(e){this.logger.safe.info(`setNegotiatedModalities ${JSON.stringify(e)}`),this.negotiatedModalities=e,this.statsGatherer.sessionInfo.setNegotiatedModalities(e),this.diagnostics&&(this.diagnostics.negotiatedModalities=e)}setupIceGatheringTimeout(e){this.iceRelayCandidatesGatherStartTime=Date.now();const t=this.context.config.webrtcIceGatheringTimeoutIncreased?this.configProvider.config.relayWaitSaneTimeoutMs:this.configProvider.config.webrtcIceGatheringTimeoutMs;if(!t)return;this.iceCandidatesTimer>0&&clearTimeout(this.iceCandidatesTimer);const i=this.iceCandidatesDeferred;this.iceCandidatesTimer=setTimeout((()=>{this.iceCandidatesTimer=0,i.isPending&&(this.logger.safe.warn(`[${e}] ICE candidates gathering terminated due to timeout ${t}`),i.resolve())}),t)}isConnected(){return this.isTransportConnected()&&"closed"!==this.peerConnection.signalingState}isFailed(){return this.peerConnection&&("failed"===this.lastTransportConnectionState||"closed"===this.lastTransportConnectionState)}hasRelayCandidates(){return this.relayCandidateGathered}isIceConnected(){return"connected"===this.peerConnection?.iceConnectionState||"completed"===this.peerConnection?.iceConnectionState}isTransportConnected(){return this.peerConnection&&("connected"===this.lastTransportConnectionState||"completed"===this.lastTransportConnectionState)}createReceiveStream(e,t,i,n){const r=this.configProvider.config.addFmtpToInitialSubscription?n.getLocalRecvCapabilities():null,a=this.configProvider.config.useMultiviewLimitsOnInitialRequest&&n.getModality()!==Qe.MODALITY.sharing?()=>this.remoteVideoManager.getMaxAllowedVideoFS():null,s=new VN(e,t,n.getModality(),+n.getXSourceStreamId(),this,r,a);return new XL(s,i,this.receiveStreamCollection,this.logger.createChild("RecvStream"),this.configProvider.config)}async requestSource(e,t,i){if(!this.multiParty)return;const n=this.mediaManager.getMediaEntityByRemoteStreamId(e);if((this.isMuteHold||this.negotiatedModalities[n.getModality()]===Qe.MEDIA_STATE.inactive)&&t!==zk.SourceNone)return await Dm(10),this.requestSource(e,t);if(this.negotiationCompletedPromise.isPending)try{await this.negotiationCompletedPromise.promise}catch{this.logger.safe.error("source request should be sent even if negotiation rejected")}if(!this.isConnected()){this.logger.safe.info("requestSource is postponed till transport is connected");const e=km();this.toBeCalledAfterConnected.push((()=>e.resolve())),await e.promise}return this.extensionsManager.getExtension("videoStreamControl").sendSourceRequest(n.getXSourceStreamId(),t,n?.getMid(),i,n.getSubstreamIndex())}async assureStreamsAndDataChannel(e,t,i){this.logger.safe.info(`[${t}] assureStreamsAndDataChannel `,this.negotiatedModalities,"offered",this.offeredModalities," mod ",e),this.dataChannel&&this.dataChannel.updateDataModalityState(e.data),i?.mark("startConfigureHold");const n=await this.configureHold(this.negotiatedModalities,e,t);if(i?.markAndMeasure("startConfigureHold","configureHold"),n)return this.logger.safe.info(`[${t}] Hold is configured. Not updating streams`),e;const r=await this.streamSendersManager.update(e,!1,t,i?.clone("updateStreams"));return i?.markAndMeasure("configureHold","updateStreams"),this.dataChannel&&e.data&&(r.data=e.data),r}async configureHold(e,t,i){const n=Jg(e),r=Jg(t);return n!==r&&await this.streamSendersManager.setHold(r,i),r}getStreamTransformConfiguration(){return{unifiedPlanEnabled:!0,addPrefixForMsid:this.configProvider.config.addPrefixForMsidInSdp}}applyReceiveCapabilities(){const e=this.mediaManager.getMediaEntities().map((e=>e.getRemoteRecvCapabilities()));this.multiParty?this.qualityManager.setPendingCapabilities():this.qualityManager.setMaxCapabilities(e)}async onReceiveCapabilitiesChanged(e,t,i){if(!this.streamSendersManager)return!1;try{return await this.streamSendersManager.applyCapabilities(t,e,i),!0}catch(e){return!1}}onOptimalVideoCountChanged(e,t){this.callback.onOptimalVideoReceiversCountChanged&&this.callback.onOptimalVideoReceiversCountChanged(e),this.diagnostics.addOvcSubscriptionReport(e,this.subscriptionManager?.getSubscriptionsCount(),t)}async onSendBandwidthChanged(e){if(!this.isConnected())return;const t=this.extensionsManager.getExtension("videoStreamControl"),i=this.mediaManager.getMediaEntities().filter((e=>[Qe.MODALITY.video,Qe.MODALITY.sharing].indexOf(e.getModality())>-1)).filter((e=>e.isEnabled())).map((e=>e.getMid()));0!==i.length&&(await t.sendBandwidthInfo(i,e),this.statsGatherer.setReportedSendBandwidth(e),this.diagnostics&&(this.diagnostics.reportedSendBandwidth=e))}onMaxVideoSendCapabilitiesChanged(e,t){if("Video"===e&&this.configProvider.config.maxSendVideoCapabilitiesReportingForVideoEnabled||"ScreenShare"===e&&this.configProvider.config.maxSendVideoCapabilitiesReportingForSharingEnabled)return this.isConnected()?void this.notifyMaxVideoCapabilitiesChanged(e,t):(this.logger.safe.info("sendMaxVideoSendCapabilities is postponed till transport is connected"),void this.toBeCalledAfterConnected.push((()=>this.notifyMaxVideoCapabilitiesChanged(e,t))))}notifyMaxVideoCapabilitiesChanged(e,t){const i=this.extensionsManager.getExtension("videoStreamControl"),n=lm(e),r=this.mediaManager.getMediaEntitiesByModality(n)[0];if(!r)return;const a=r.getMid();i.sendMaxVideoSendCapabilities([a],t)}createAudioRenderer(){this.audioRenderer=new Vw(this.logger.createChild("AudioRenderer"),this.configProvider),this.context.maContext.domOverrides.onMediaElementAdded&&this.audioRenderer.on("onAudioElementAdded",this.context.maContext.domOverrides.onMediaElementAdded),this.context.maContext.domOverrides.onMediaElementRemoved&&this.audioRenderer.on("onAudioElementRemoved",this.context.maContext.domOverrides.onMediaElementRemoved),this.audioRenderer.on("onAudioPlaybackError",((e,t,i)=>this.onAudioPlaybackError(e,t,i)))}onAudioPlaybackError(e,t,i){const n={type:t,detail:i,isAudio:!0};this.deviceManager.raiseTelemetryEvent("reconnect_on_audio_playback_error",{error:e,mediaError:t,message:i}),this.context.reconnectRetry&&this.configProvider.config.audioRendererFailedRetryCodes?.includes(e)&&(this.logger.warn(`Reconnect required, attempt No: ${this.context.reconnectRetry}`),this.context.reconnectRetry--,this.raiseError(n))}getModalitiesForRollback(e){const t=im(this.negotiatedModalities,this.negotiatingModalities);return this.logger.safe.debug(`[${e}] configured modalities for rollback: ${JSON.stringify(t)}`),t}fixLocalDescription(e){this.configProvider.config.insertFakeCandidateIfNeeded&&(this.iceCandidateReceived||!this.iceCandidateReceived&&this.isIceConnected())&&e.insertFakeCandidateIfNeeded(this.statsGatherer.sessionInfo,this.diagnostics),e.fixDataModality()}getSessionConfig(){return this.configProvider}getLocalMediaTrackId(e){const t=this.mediaManager.getLocalTracksInfo(),i=lm(e),n=t.find((e=>e.modality===i));return n?n.trackId:null}addReceiveStreamTransforms(e,t){const i=this.encStreamsManager.initTransformsCollection(e,"Receiver",om(t));i&&t!==Qe.MODALITY.audio&&this.configProvider.config.useInsertableStreams?.videoStreamAnalyzer&&i.addTransform(new JN(this.logger.createChild(`RecvStreamAnalyzer [${t}/${e.track.id}]`)))}clearReceiveStreamTransforms(e){this.encStreamsManager.clearTransformsCollection(e)}async checkVideoCodecsSupport(){try{const e=await this.capabilityGatherer.getCapabilities("video");this.statsGatherer.setH264AvailableProfiles(e);const t=await Bg.isCodecsSupported(this.configProvider.config.hevcCodecs);this.diagnostics&&(this.diagnostics.videoCapabilities=e,this.diagnostics.isCodecsSupported=t);const i=new Set(e?.codecs?.map((e=>e.mimeType.toLocaleLowerCase()))||[]);for(const e of this.configProvider.config.requiredVideoCodecs)if(!i.has(e)){this.ufdManager.signalEvent("NoRequiredVideoCodecs","Bad","Video");break}}catch(e){this.logger.safe.error(`failed to get video capability ${Be(e)}`)}}getMediaDescriptions(e){if(Jg(e))return{};const t=[];for(const i of this.mediaManager.getMediaEntities()){if(!i.getExtension("reinviteless"))continue;const n=e[i.getModality()],r={mid:i.getMid(),direction:!i.getLocalTrackId()&&Wg(n)?zg(n):n};t.push(r)}return{descriptions:t}}updateSendStreamsReinviteless(e){if(at(this.negotiatedModalities)||Jg(this.negotiatedModalities)||Jg(this.configuredModalities))return!1;this.reinvitelessRequestedModalities=ot(this.negotiatedModalities);for(const[e,t]of Object.entries(this.configuredModalities)){const i=this.mediaManager.getMediaEntitiesByModality(e)[0];i?.getExtension("reinviteless")&&(this.reinvitelessRequestedModalities[e]=t)}return!ut(this.reinvitelessRequestedModalities,this.negotiatedModalities)&&(this.callbacks?.onUpdateMediaDescriptionsRequired?.(e),ut(this.reinvitelessRequestedModalities,this.configuredModalities))}setBWSeed(e){if(!this.configProvider.config.setBWSeed)return;const t=this.extensionsManager.getExtension("bandwidthCache").getBWSeed();e.applyChannelParameters={multiChannelParameter:{mids:this.configProvider.config.bwSeedOptions.mids,mediaParameter:JSON.stringify({sendSideBWSeed:{seedValueBitsPerSec:t}})}},this.diagnostics.sentBWSeed=t}getSubscriptionManager(){return this.subscriptionManager}initAudioCodec(e){this.audioCodecManager.init(e);const t=this.audioCodecManager.decoder;t&&(t.on("usedDecoderChanged",(e=>{this.updateAudioRendererStream(e?t.stream:this.webrtcAudioRecvStream),this.statsGatherer.setAudioDecoderStatsProvider(e?t.getStatsProvider():void 0)})),this.audioCodecManager.on("negotiationNeeded",(e=>this.triggerRenegotiation(!0,e))))}configureAudioCodec(){this.audioCodecManager.prepareForNegotiation(this.initiator)}checkAudioCodecNegotiated(e){const t=this.audioCodecManager.negotiationCompleted();if(this.configProvider.mediaConfig.spatialAudioEnabled){const i=t?"Good":"Bad";this.ufdManager.signalEvent("SpatialAudioMUCHUnavailable",i,"Audio",!0,e)}}onIncomingVideoQualityChanged(e,t){1===e&&this.remoteVideoResolutionManager.limitResolutionOnPoorPerformance(t)}getVideoDeviceManager(){return this.context.callDeviceManager.getDeviceManager("Video")}setupCallDeviceManagerSubs(){this.callDeviceManagerSub=this.context.callDeviceManager.on("onSelectedVirtualDevicesChanged",(()=>{this.logger.info("VirtualDevice changed, disposing deviceManager subscriptions"),this.deviceManagerSubs.forEach((e=>e.dispose())),this.logger.info("New subscriptions for deviceManager created"),this.setSubsForDeviceManager()}))}updateLocalMediaSources(){this.mediaManager.updateMediaEntitiesWithLocalTracks(),this.configProvider.config.mapSsrcToTrackForStats&&this.statsGatherer.updateStatsWithLocalSsrcTrackInfo();const e=this.streamSendersManager.getLocalMediaSources();this.qualityManager.updateRegisteredSources(e)}},Gx={build:(e,t,i)=>new $x(e,t,i)},jx=class{constructor(e,t,i,n,r,a,s,o){this.logger=e,this.context=t,this.configProvider=i,this.diagnostics=n,this.ufdManager=r,this.deviceManager=a,this.capabilities=s,this.midCallTelemetry=o,this.activeSessions=[],this.pendingDeviceTelemetryEvents=[],this.pendingVideoEffectsTelemetryEvents=[],this.pendingAudioEffectsTelemetryEvents=[],this.callsCount=0,this.mediaConfig={},this.configProvider.on("configUpdated",(()=>this.configApplied())),this.deviceManager.on("onDeviceTelemetryEvent",(e=>this.onDeviceTelemetryEvent(e))),this.deviceManager.on("onVideoEffectsTelemetryEvent",(e=>this.onVideoEffectsTelemetryEvent(e))),this.deviceManager.on("onAudioEffectsTelemetryEvent",(e=>this.onAudioEffectsTelemetryEvent(e)))}createSession(e,t,i,n){this.configProvider.setMediaConfiguration(this.mediaConfig);const r=this.configProvider.getConfigView(i?.isConference),a=this.logger,s=this.diagnostics.newSession(r,t,this.logger.createChild("sessionDiagnostics")),o={getLogger:()=>a,getUfdManager:()=>this.ufdManager,maContext:this.context,config:i??{},configProvider:r,diagnostics:s.newNativeSessionDiag(),reconnectRetry:r.config.audioRendererFailedReconnectTimes,callDeviceManager:n},l=(r.mediaConfig.simulcastSessionEnabled?Gx:qN).build(o,t,e),c=new Hk(r,++this.callsCount,s);c.setMediaQosEnabled(!!this.mediaConfig.enableMediaQoS),c.setPortRangeConfigured(!!this.mediaConfig.mediaPortRanges);const d=new Lk(l,t,o,e,c,this.configProvider,s);for(d.on("onTerminated",(e=>this.onSessionTerminated(e))),this.activeSessions.push(d),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector=Ck.getInstance(this.logger.createChild("WebRtcInternals"),r),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length);this.pendingDeviceTelemetryEvents.length>0;)d.registerDeviceTelemetryEvent(this.pendingDeviceTelemetryEvents.pop());for(;this.pendingVideoEffectsTelemetryEvents.length>0;)d.registerVideoEffectsTelemetryEvent(this.pendingVideoEffectsTelemetryEvents.pop());for(;this.pendingAudioEffectsTelemetryEvents.length>0;)d.registerAudioEffectsTelemetryEvent(this.pendingAudioEffectsTelemetryEvents.pop());return d}getDeviceManager(){return this.deviceManager}getCapabilities(){return this.capabilities}getScreenSharingManager(){return new Tk(this.deviceManager)}updateConfig(e,t,i,n){this.configProvider.updateConfig(e,t,i,n)}getConfig(){return this.configProvider.config}getConfigProvider(){return this.configProvider}setMediaConfig(e){(0,vk.merge)(this.mediaConfig,e),this.diagnostics.mediaConfig=this.mediaConfig}getMediaLogs(){return this.webRtcInternalsCollector?this.webRtcInternalsCollector.collect():Promise.resolve("")}dispose(e){return Promise.all([this.deviceManager.dispose(),this.capabilities.dispose(),...this.activeSessions.map((async t=>{await t.terminate(e,{}).catch((()=>{})),t.dispose()}))]).then((()=>{}),(()=>{}))}handleSendMidCallTelemetry(e){this.midCallTelemetry?.on("sendMidCallTelemetry",e)}configApplied(){window&&(this.configProvider.config.enableDevtoolsAPI?window.webMA||this.injectDevtoolsAPI():window.webMA&&delete window.webMA)}injectDevtoolsAPI(){const e={config:{addOverride:(e,t)=>this.configProvider.setConsoleOverride(e,t),setOverrides:e=>this.configProvider.setConsoleOverrides(e),clearOverride:e=>this.configProvider.clearConsoleOverride(e),clearAllOverrides:()=>this.configProvider.clearAllConsoleOverrides(),setConstraints:e=>this.configProvider.setCallConstraints(e),setRelayConfigOverride:e=>this.context.getRelayManager().setRelayOverride(e)},diagnosticsReport:this.diagnostics.reportGenerator,deviceManager:{setAudioProcessingFlags:e=>this.deviceManager.setAudioProcessingFlags(e)}};window.webMA=e}onDeviceTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerDeviceTelemetryEvent(e))):this.pendingDeviceTelemetryEvents.push(e)}onVideoEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerVideoEffectsTelemetryEvent(e))):this.pendingVideoEffectsTelemetryEvents.push(e)}onAudioEffectsTelemetryEvent(e){this.activeSessions.length>0?this.activeSessions.forEach((t=>t.registerAudioEffectsTelemetryEvent(e))):this.pendingAudioEffectsTelemetryEvents.push(e)}onSessionTerminated(e){nt(this.activeSessions,(t=>t===e)),this.configProvider.updateSessionCount(this.activeSessions.length),this.webRtcInternalsCollector.updateSessionCount(this.activeSessions.length),0===this.activeSessions.length&&this.ufdManager.reset()}},zx=class{static build(e,t,i,n,r,a,s,o){return new jx(e,t,i,n,r,a,s,o)}};zx.constants=Qe,zx.helper=Mg;var Wx=class{constructor(e,t){this.getWorker=e,this.logger=t,this.createWasmCVWorker=()=>(this.logger.info("Creating wasmcv worker"),this.create({msg:"wasmcv"})),this.createEncodedStreamsWorker=()=>(this.logger.info("Creating encoded-stream worker"),this.create({msg:"encoded-stream"}))}get audioWorklet(){return null}create(e){const t=this.getWorker();return t.onerror=t=>{this.logger.error(`Worker ${JSON.stringify(e)} error: ${t.message}`)},t.onmessage=t=>{this.logger.info(`Worker ${JSON.stringify(e)} event: ${JSON.stringify(t.data)}`)},t.postMessage(e),t}},qx=class{constructor(e,t,i){e.logger??(e.logger=new sf),e.domOverrides??(e.domOverrides={}),this.config=e;const n=e.mediaSettings;Lg(e.clientInformation),this.logger=new fk(e.safeLogger?.createChild("MA",n.debug),e.logger.createChild("MA",n.debug)),this.configProvider=new Fw(this.logger.createChild("configProvider"),i,n);const r=new yA(this.configProvider);this.mediaAgentDiagnostics=new mk(this.configProvider,r),this.ufdManager=new cf(this.logger.createChild("UFD"),this.configProvider),this.configProvider.config.useGenericWorkerLoader&&e.createWasmWorkerCbs.createGenericWebRTCWorker&&(this.wasmLoader=new Wx(e.createWasmWorkerCbs.createGenericWebRTCWorker,this.logger.createChild("WasmLoader"))),this.deviceManager=new SA(this.logger.createChild("DeviceManager"),this.configProvider,r,e.domOverrides,this.ufdManager,e.webcvProvider,e.wasmdnsProvider,e.wasmaecProvider,e.wasmVqeProvider,this.wasmLoader||e.createWasmWorkerCbs),this.capabilities=new of(this.configProvider),Zw.initialize(this.configProvider),t.on("OnECSChanged",(()=>{const e=t.getEcsConfig("SkypeWebMedia","mediaAgent");e?this.configProvider.updateConfig(e,t.ETag,t.getEcsConfig("ConfigIDs","SkypeWebMedia"),t.getEcsConfig("Headers","CountryCode")):this.logger.warn("No SkypeWebMedia.mediaAgent config.")}))}getDeviceManager(){return this.deviceManager}async buildAgent(e,t,i){if(!Bg.hasMediaApi())throw[new Kx(`${e} not supported by media agent provider`,"not_supported")];if(this.config?.detectH264Support&&!await Bg.hasH264CodecSupport(this.config.logger))throw[new Kx("H264 is not supported","not_supported")];const n=await async function(e,t){if(e?.createEncodedStreamsWorker)return{getWorker:()=>e.createEncodedStreamsWorker()};if(t){const e=await t.getWorkerUrl();return{getWorker:()=>new Worker(e)}}return null}(this.config.createWasmWorkerCbs,this.config.encodedStreamsWorkerProvider),r=t.createRelayManager(this.configProvider),a={getRelayManager:()=>r,getWebCVProvider:()=>this.config.webcvProvider,getWasmDnsProvider:()=>this.config.wasmdnsProvider,getWasmAecProvider:()=>this.config.wasmaecProvider,getWasmVqeProvider:()=>this.config.wasmVqeProvider,getEncodedStreamsWorkerProvider:()=>n,domOverrides:this.config.domOverrides,configProvider:this.configProvider};a.getRelayManager().initialize();const s=zx.build(this.logger,a,this.configProvider,this.mediaAgentDiagnostics,this.ufdManager,this.deviceManager,this.capabilities,i);return s.constants=zx.constants,s}},Kx=class extends Error{constructor(e,t="failure"){super(e),this.reason=t}};var Jx=class{constructor(){this.supportedPlatforms=new Map([["Chrome","59.0"],["EdgeAnaheim","79.0"],["Safari","13.1"],["Electron","3.0"],["Firefox","96.0"],["WebView2","1.0"]]),this.experimentalPlatforms=new Map}getPlatformSupportLevel(e){const t=ri(),i=this.supportedPlatforms.get(t.name);if(e&&i&&ym(t.version,i))return 1;if(e&&!i){if("Chromium"===t.engine||"ChromiumAVD"===t.engine)return 2;const e=this.experimentalPlatforms.get(t.name);if(e&&ym(t.version,e))return 2}return 0}},Yx=class extends We{constructor(e){super(),this.ecsFilters=e,this.config=null}get ETag(){return this.etag}async setEcsConfig(e){this.config=JSON.parse(e.ecsBlob),this.etag=e.etag,this.event("OnECSChanged").raise()}async setUserEcsServerUrl(e,t){throw new Error("Not implemented")}async getUserEcsServerUrl(e){throw new Error("Not implemented")}async setActiveUserForEcs(e){throw new Error("Not implemented")}async getEcsQueryParameters(){const e={CLRelease:"2024.14.01.23"},t="_TS_BUILC_VERSION_".replace("C","D"),i=this.ecsFilters?.["UserInfo.Ring"]?.value,n=this.getTeamsExperience();e.CLRelease===t&&(e.CLRelease="9999.99"),i&&(e.audienceGroup=i,e.teamsRing=i),n&&(e.Experience=n);const r=ri();return e.BrowserName=r.name,e.BrowserEngine=r.engine,e.BrowserVersion=r.version,e.FormFactor=r.formFactor,Bg.hardwareConcurrency&&(e.CPUCount=Bg.hardwareConcurrency),JSON.stringify(e)}async ecsGetUserQueryParameters(e){return this.getEcsQueryParameters()}async shouldTriggerCQF(e,t,i){throw new Error("Not implemented")}getEcsConfig(e,t){const i=this.config&&this.config[e];return t?i&&i[t]:i}createEcsConfiguration(){return new class{constructor(e){this.provider=e}getBoolean(e,t){return this.provider.getEcsConfig(e,t)}getNumber(e,t){return this.provider.getEcsConfig(e,t)}getString(e,t){const i=this.provider.getEcsConfig(e,t);return JSON.stringify(i)}}(this)}getTeamsExperience(){return!0===this.ecsFilters?.isTeams2?.value?"teams2":!1===this.ecsFilters?.isTeams2?.value?"teams1":void 0}},Qx=class{constructor(e){this._sharingSource=e}getId(){return this._sharingSource.getId()}getDeviceId(){return this._sharingSource.getDeviceId()}getType(){return this.mapSharingSourceType(this._sharingSource.getType())}getPreview(e,t,i){return Promise.reject("not implemented")}getPreviewAsync(e,t){return this._sharingSource.getPreviewAsync(e,t)}getDescription(){return this._sharingSource.getDescription()}getIcon(e,t){return this._sharingSource.getIcon(e,t)}getBounds(){}mapSharingSourceType(e){switch(e){case 1:return 1;case 2:return 2;case 3:return 3;default:throw new Error("Invalid sharing source type")}}},Zx=class extends We{constructor(e){super(),this._screenSharingManager=e,this._screenSharingManager.onScreensChanged((()=>{this.event("screensChanged").raise()}))}enumerateScreensAsync(){return this._screenSharingManager.enumerateScreensAsync().then((e=>e.map((e=>new Qx(e)))))}enumerateWindowsAsync(){return this._screenSharingManager.enumerateWindowsAsync().then((e=>e.map((e=>new Qx(e)))))}enumerateCamerasAsync(){return this._screenSharingManager.enumerateCamerasAsync().then((e=>e.map((e=>new Qx(e)))))}},Xx=p;function eF(e,t){return null==e?t:e}function tF(e,t){return e||t}var iF,nF,rF=class{constructor(e,t,i,n){this.signalingAgentConfig=e,this.ecsProvider=t,this.logger=i,this.telemetryLogger=n,this.ecsProvider.on("OnECSChanged",(()=>this.onEcsUpdate())),this.signalingAgentConfig.clientInformation+="/TsCallingVersion=2024.14.01.23/Ovb=7b433484b6052f263c376357e5f0a7c2fecbb27f",this.signalingAgentConfig.piiScrubber={omit:Xx.pii.Omit,mri:Xx.pii.Mri},this.signalingAgent=new sh(this.getSignalingAgentConfig())}getSignalingAgent(){return this.signalingAgent}onEcsUpdate(){const e=this.ecsProvider.getEcsConfig("SkypeCalling");this.logger.info(`onEcsUpdate, ecsTag=${this.ecsProvider.ETag||""}, ecsConfig=${JSON.stringify(e)}`),this.signalingAgentConfig=((e,t)=>{if(!t)return e;const i={...e};if(t.ngIncoming&&t.ngOutgoing){const n=function(e,t){return t&&e?"enabled":e?"recvOnly":!1===e&&!1===t?"disabled":void 0}(t.ngIncoming.isVBSSEnabled,t.ngOutgoing.isVBSSEnabled);i.cloudScreenSharingFlag=eF(n,e.cloudScreenSharingFlag)}return t.ngOutgoing&&(i.emergencyCallCountry=function(e,t){return!1===e?"":t}(t.ngOutgoing.isEmergencyCallingEnabled,e.emergencyCallCountry),i.isGVCOutgoingEnabled=eF(t.ngOutgoing.isGVCEnabled,e.isGVCOutgoingEnabled),i.brokerEnabledOutgoing=eF(t.ngOutgoing.isBrokerEnabled,e.brokerEnabledOutgoing)),t.ngIncoming&&(i.isGVCJoiningEnabled=eF(t.ngIncoming.isGVCEnabled,e.isGVCJoiningEnabled),i.brokerEnabledIncoming=eF(t.ngIncoming.isBrokerEnabled,e.brokerEnabledIncoming)),i.conversationServiceUrl=tF(t.conversationServiceUrl,e.conversationServiceUrl),i.uploadLogRequestUrl=tF(t.uploadLogRequestUrl,e.uploadLogRequestUrl),i.isConversationServiceUrlFromEcs=!!t.conversationServiceUrl,i.isUploadLogRequestUrlFromEcs=!!t.uploadLogRequestUrl,i.callingTokenLogicalUrl=tF(t.callingTokenLogicalUrl,e.callingTokenLogicalUrl),i.doHostlessCalling=eF(t.allowHostlessCalls,e.doHostlessCalling),i.supportsCompressedServicePayload=eF(t.supportCompressedTrouterPayload,e.supportsCompressedServicePayload),i.brokerRequestBatching=eF(t.allowBrokerSubscribeBatching,e.brokerRequestBatching),i.brokerExclusively=eF(t.brokerExclusively,e.brokerExclusively),i.handleMediaOfferFromPushNotification=eF(t.handleMediaOfferFromPushNotification,e.handleMediaOfferFromPushNotification),i.handleNewOfferRequest=eF(t.handleNewOfferRequest,e.handleNewOfferRequest),i.sendProgressFromCC=eF(t.sendProgressFromCC,e.sendProgressFromCC),i.useInternalHttpDispatcher=eF(t.webInternalHttpDispatcher,e.useInternalHttpDispatcher),(t.webInternalHttpDispatcherConfigNetworkRequest||e.requestTypeHttpDispatcherConfigMap)&&(t.webInternalHttpDispatcherConfigNetworkRequest=t.webInternalHttpDispatcherConfigNetworkRequest||{},e.requestTypeHttpDispatcherConfigMap=e.requestTypeHttpDispatcherConfigMap||{},i.requestTypeHttpDispatcherConfigMap={...e.requestTypeHttpDispatcherConfigMap,...t.webInternalHttpDispatcherConfigNetworkRequest}),(t.operationTypeHttpDispatcherConfigMap||e.operationTypeHttpDispatcherConfigMap)&&(t.operationTypeHttpDispatcherConfigMap=t.operationTypeHttpDispatcherConfigMap||{},e.operationTypeHttpDispatcherConfigMap=e.operationTypeHttpDispatcherConfigMap||{},i.operationTypeHttpDispatcherConfigMap={...e.operationTypeHttpDispatcherConfigMap,...t.operationTypeHttpDispatcherConfigMap}),(t.csaTimeoutConfiguration||e.csaTimeoutConfiguration)&&(t.csaTimeoutConfiguration=t.csaTimeoutConfiguration||{},e.csaTimeoutConfiguration=e.csaTimeoutConfiguration||{},i.csaTimeoutConfiguration={...e.csaTimeoutConfiguration,...t.csaTimeoutConfiguration}),i.autoJoinOnConflict=eF(t.autoJoinOnConflict,e.autoJoinOnConflict),i.enableQuickSendAcceptanceAck=eF(t.enableQuickSendAcceptanceAck,e.enableQuickSendAcceptanceAck),i.supportMediaRetargetWhileIncomingRenegotiation=eF(t.supportMediaRetargetWhileIncomingRenegotiation,e.supportMediaRetargetWhileIncomingRenegotiation),i.enableCallEstablishmentTimeoutsForStartJoinCall=eF(t.enableCallEstablishmentTimeoutsForStartJoinCall,e.enableCallEstablishmentTimeoutsForStartJoinCall),i.callingServiceSupportsCAETokens=eF(t.callingServiceSupportsCAETokens,e.callingServiceSupportsCAETokens),i.callingServiceSupportsAADTokens=eF(t.callingServiceSupportsAADTokens,e.callingServiceSupportsAADTokens),i.aadTokenExpirationTimeInSeconds=eF(t.aadTokenExpirationTimeInSeconds,e.aadTokenExpirationTimeInSeconds),i.caeTokenExpirationTimeInSeconds=eF(t.caeTokenExpirationTimeInSeconds,e.caeTokenExpirationTimeInSeconds),i.disableTokenMigrationHeader=eF(t.disableTokenMigrationHeader,e.disableTokenMigrationHeader),i.enablePublishTokenTelemetry=eF(t.enablePublishTokenTelemetry,e.enablePublishTokenTelemetry),i.refreshTimeBeforeTokenTimeoutInSeconds=eF(t.refreshTimeBeforeTokenTimeoutInSeconds,e.refreshTimeBeforeTokenTimeoutInSeconds),i.forceClearExpiredTokens=eF(t.forceClearExpiredTokens,e.forceClearExpiredTokens),i.enableRefreshToken=eF(t.enableRefreshToken,e.enableRefreshToken),i.enableAsyncDisablePreheat=eF(t.enableAsyncDisablePreheat,e.enableAsyncDisablePreheat),i.forceLowercaseHttpHeaders=eF(t.forceLowercaseHttpHeaders,e.forceLowercaseHttpHeaders),i.enableResolveScreenSharingWhenNegotiationComplete=eF(t.enableResolveScreenSharingWhenNegotiationComplete,e.enableResolveScreenSharingWhenNegotiationComplete),i.maxReinvitelessMediaForVideoForWeb=eF(t.maxReinvitelessMediaForVideoForWeb,e.maxReinvitelessMediaForVideoForWeb),i.maxReinvitelessMediaForVBSSForWeb=eF(t.maxReinvitelessMediaForVBSSForWeb,e.maxReinvitelessMediaForVBSSForWeb),i.enableRefreshTokenRetry=eF(t.enableRefreshTokenRetry,e.enableRefreshTokenRetry),i.enableRefreshTokenRetryInSeconds=eF(t.enableRefreshTokenRetryInSeconds,e.enableRefreshTokenRetryInSeconds),i.enableConversationTypeUpdateOnCallEnd=eF(t.enableConversationTypeUpdateOnCallEnd,e.enableConversationTypeUpdateOnCallEnd),i.supportMissingTokenTypesInResponse=eF(t.supportMissingTokenTypesInResponse,e.supportMissingTokenTypesInResponse),i.useSkypeTokenWhenNoAuthenticateHeader=eF(t.useSkypeTokenWhenNoAuthenticateHeader,e.useSkypeTokenWhenNoAuthenticateHeader),i.enableAutoPromotion=eF(t.enableAutoPromotion,e.enableAutoPromotion),i.enableTokenCache=eF(t.enableTokenCache,e.enableTokenCache),i.enableBatchedSendMessageStatus=eF(t.enableBatchedSendMessageStatus,e.enableBatchedSendMessageStatus),i.enableBatchedReceiveMessage=eF(t.enableBatchedReceiveMessage,e.enableBatchedReceiveMessage),i.enableTokenCacheForGenericTokenAPI=eF(t.enableTokenCacheForGenericTokenAPI,e.enableTokenCacheForGenericTokenAPI),i.disableRealTimeModeFromRoster=eF(t.disableRealTimeModeFromRoster,e.disableRealTimeModeFromRoster),i.enableLongOutgoing1To1SetupTimeoutForWeb=eF(t.enableLongOutgoing1To1SetupTimeoutForWeb,e.enableLongOutgoing1To1SetupTimeoutForWeb),i})(this.signalingAgentConfig,e),this.signalingAgentConfig.ecsEtag=this.ecsProvider.ETag,this.signalingAgent.updateSignalingAgentConfig(this.getSignalingAgentConfig())}getSignalingAgentConfig(){return this.signalingAgentConfig.oneDsTelemetryLogger=this.telemetryLogger,this.signalingAgentConfig}},aF=(e,t,i,n)=>new rF(e,t,i,n);function sF(e){return Ty(e)&&e>=1&&e<=2}(nF=iF||(iF={}))[nF.LocalStorage=1]="LocalStorage",nF[nF.SessionStorage=2]="SessionStorage",nF[nF.IndexedDb=3]="IndexedDb";var oF="result",lF="DBError: Unable to open database",cF="Database is not open",dF="DBError: Failed to delete the database",uF=["indexedDB"],hF=my,pF=Ey;function gF(e,t){gC("QUnit")&&console&&console.log("IndexedDbHelper ["+e+"] "+t)}function mF(e,t,i){e&&e.warnToConsole("IndexedDbHelper ["+t+"] "+i)}function fF(e,t,i,n){return function(r){i(new Error(t)),gF(e,"["+n+"] event rejected")}}var vF=[];function SF(e,t){for(var i=null,n=0;n<vF.length;n++)if((i=vF[n]).name===e)return i;return i={name:e,sch:new jT("IndexedDbHelper["+e+"]",t),dbHdl:[],add:function(t){i.dbHdl.push(t),gF(e,"- dbOpened (add) -- hdls ["+i.dbHdl.length+"]")},remove:function(t){for(var n=i.dbHdl,r=0;r<n.length;r++)if(n[r]===t){n.splice(r,1);break}gF(e,"- dbClosed (remove) -- hdls ["+i.dbHdl.length+"]")},isOpen:function(){return i.dbHdl.length>0},openHdl:function(){return i.dbHdl.length>0?i.dbHdl[0]:null}},vF.push(i),i}var yF=function(){function e(t){bv(e,this,(function(e){var i=function(){var e=Uf()||{},t=null;if(e)try{for(var i=0;i<uF.length;i++)if((t=e[uF[i]])&&hF(t.open))return t}catch(e){t=null}return t||null}()||null;function n(e,i){var n=e.db.transaction(i,"readwrite");return n.onabort=function(){mF(t,e.dbName,"txn.onabort")},n.onerror=function(){mF(t,e.dbName,"txn.onerror")},n.oncomplete=function(){gF(e.dbName,"txn.oncomplete")},{db:e,store:n.objectStore(i),tx:n,tbl:i,openCursor:function(t,n){return a(e,i,t,n)},newTransaction:function(t){return r(e,i,t)}}}function r(e,t,i){if(!e||!e.db)return FT.reject(new Error(cF));try{var r=i(n(e,t));return r instanceof FT?r:FT.resolve(r)}catch(e){return FT.reject(e)}}function a(e,t,i,r){if(!e||!e.db)return FT.reject(new Error(cF));var a=null;return i&&pF(i)?a=new CF(i):i&&i.isMatch&&(a=i),new FT((function(i,s){var o=[],l=null,c=null;a&&a.keyRange&&(c=a.keyRange());var d=n(e,t);(l=c?d.store.openCursor(c):d.store.openCursor()).onerror=fF(d.db.dbName,"DBError: Failed to Open Cursor",s,"openCursor"),l.onsuccess=function(e){var t=e.target[oF];if(t){var n={store:d,cursor:t,continue:function(){t.continue()},done:function(){i(o)}},l=t.value;if(!a||a.isMatch(l))if(r)try{switch(r(n,l,o)){case 2:i(o);break;case 1:break;default:n.continue()}}catch(e){s(e)}else o.push(l),n.continue();else n.continue()}else i(o)}}))}function s(e,t,i,n){return SF(e).sch.scheduleEvent(i,t,n)}e.isAvailable=function(){return!!i},e.openDb=function(e,n,o,l){return s(e,"openDb",(function(s){return new FT((function(c,d){var u=!1;function h(t,i,s,o,l){var c={db:i,dbName:e,dbVersion:n,ctx:null,isNew:o,txn:s?s.transaction:null};return l||(c.openStore=function(e,t){return r(c,e,t)},c.openCursor=function(e,t,i){return a(c,e,t,i)}),c}function p(i,n){var r=SF(e);r.add(i),i.onabort=function(n){mF(t,e,"onabort -- closing the Db"),r.remove(i)},i.onerror=function(n){mF(t,e,"onerror -- closing the Db"),r.remove(i)},i.onclose=function(n){mF(t,e,"onclose -- closing the Db"),r.remove(i)},i.onversionchange=function(n){mF(t,e,"onversionchange -- force closing the Db"),i.close(),r.remove(i)};var a,s=null;r.dbHdl.length>0&&(s=r.dbHdl[0]),a=h(0,s,n,u);try{o(a).then((function(e){c(e)}),d)}catch(e){d(e)}}var g=SF(e);if(null==i)d(new Error("No available storage factory"));else if(g.isOpen()){var m=h(0,g.openHdl(),null,!1);o(m).then(c,d)}else{var f=i.open(e,n);f.onblocked=function(i){mF(t,e,"Db Open Blocked event ["+s+"] - "+(f.error||"")),d(new Error(lF))},f.onerror=function(i){mF(t,e,"Db Open Error event ["+s+"] - "+(f.error||"")),d(new Error(lF))},f.onupgradeneeded=function(t){gF(e,"Db Open Create/Upgrade needed event ["+s+"]");try{var i=t.target[oF];if(!i)return void d(new Error(lF));!function(e,t){var i=h(0,e,t,!0,!0);if(l)u=!0,l(i).then((function(){i.txn||(i.txn=t.transaction)}),(function(e){try{t.transaction&&t.transaction.abort()}finally{d(e)}}));else try{t.transaction&&t.transaction.abort()}finally{d(new Error("DBError: Database upgrade required"))}}(i,f)}catch(t){fF(e,lF,d,s)(t)}},f.onsuccess=function(e){var t=e.target[oF];t?p(t,f):d(new Error(lF))}}}))}))},e.closeDb=function(e){s(e,"closeDb",(function(t){var i=SF(e),n=i.dbHdl,r=n.length;if(r>0){for(var a=0;a<r;a++)n[a].close();i.dbHdl=[]}return FT.resolve(1)}))},e.deleteDb=function(e){return null==i?FT.resolve(!1):s(e,"deleteDb",(function(n){var r=SF(e),a=r.dbHdl,s=a.length;if(s>0){mF(t,e,"Db is open ["+s+"] force closing");for(var o=0;o<s;o++)a[o].close();r.dbHdl=[]}return new FT((function(r,a){setTimeout((function(){try{gF(e,"["+n+"] starting");var s=i.deleteDatabase(e);s.onerror=function(i){mF(t,e,"["+n+"] error!!"),a(new Error(dF))},s.onblocked=function(i){mF(t,e,"["+n+"] blocked!!"),a(new Error(dF))},s.onupgradeneeded=function(i){mF(t,e,"["+n+"] upgrade needed!!"),a(new Error(dF))},s.onsuccess=function(t){gF(e,"["+n+"] complete"),r(!0)},gF(e,"["+n+"] started")}catch(i){mF(t,e,"["+n+"] threw - "+i),a(new Error(dF+" - "+i))}}),0)}))}))},e.getDbDetails=function(e){return s(e,"getDbDetails",(function(t){return null!=i&&i.databases?new FT((function(t,n){i.databases().then((function(i){for(var r=0;r<i.length;r++)if(i[r].name===e)return void t(i[r]);n(new Error("DBError: Database does not exist"))}),n)})):FT.reject(new Error("DBError: Feature not supported"))}),2e3)}}))}return e.__ieDyn=1,e}(),CF=function(){function e(t){var i=[],n=null;bv(e,this,(function(e){e.keyRange=function(){return n},e.parseQuery=function(t){if(i=[],t)for(var r=t.split(";"),a=0;a<r.length;a++){var s=r[a],o=s.indexOf("=");if(-1!==o){var l=s.substring(0,o),c=s.substring(o+1);0===l.indexOf("#")&&(l=l.substring(1),n||(n=IDBKeyRange.bound(c,c+""))),e.startsWith(l,c)}}},e.startsWith=function(e,t){i.push({name:e,value:t,type:0})},e.contains=function(e,t){i.push({name:e,value:t,type:1})},e.isMatch=function(e){if(!i||0===i.length)return!0;if(!e)return!1;for(var t=0;t<i.length;t++){var n=i[t],r=e[n.name];if(r)if(0===n.type){if(0!==r.indexOf(n.value))return!1}else if(1===n.type&&-1===r.indexOf(n.value))return!1}return!0},t&&e.parseQuery(t)}))}return e.__ieDyn=1,e}(),_F=6e5,EF=1008e4,TF="DBError: Unable to add event",bF="Evts",IF="iKey",wF=sF;function RF(){return(new Date).getTime()}function AF(e){return e.openStore(IF,(function(t){return new FT((function(i,n){var r={iKey:e.ctx.iKey,tm:RF()},a=t.store.put(r);a.onsuccess=function(e){i(a.result.toString())},a.onerror=function(e){n(new Error(TF))},a.onerror=function(e,t){return function(i){return t(new Error(e))}}("DBError: Unable to update iKey",n)}))}))}function PF(e){for(var t=[],i=2;i>=1;i--)for(var n=0;n<e.length;n++){var r=e[n];r&&r.evt.persistence===i&&t.push(r.evt)}return t}function MF(e){return function(t){return e.continue()}}function kF(e){var t=e.cursor.delete();return t.onerror=MF(e),t.onsuccess=MF(e),1}function DF(e,t,i){return e.openCursor(bF,t,(function(e,t,n){return i(t)?(n.push(t),kF(e)):0}))}function OF(e){return e.openCursor(bF,"#key="+e.ctx.iKeyPrefix(),(function(t,i){var n=i.key;if(0===n.indexOf(e.ctx.iKeyPrefix())&&-1===n.indexOf(e.ctx.evtKeyPrefix())&&function(e,t){var i=e.tm;return RF()-i>t}(i,_F)){i.key=e.ctx.evtKeyPrefix()+i.id;var r=t.store.store.put(i);return r.onerror=MF(t),r.onsuccess=function(e){try{kF(t)}catch(e){t.continue()}},1}return 0}))}function NF(e){return new FT((function(t,i){(function(e){return new FT((function(t,i){var n=!1;e.openCursor(IF,null,(function(e,t,i){var r=t.tm;return RF()-r<EF?0:(n=!0,2)})).then((function(){if(n){var r={};DF(e,null,(function(e){if(!e||!e.evt||!e.evt.iKey)return!0;var t=e.tm;return RF()-t>EF||(r[e.evt.iKey]=1,!1)})).then((function(){var n=[];e.openCursor(IF,null,(function(e,t,i){var a=t.tm;return RF()-a<EF||r[t.iKey]?0:(n.push(t),kF(e))})).then((function(){t(n)}),i)}),i)}else t([])}),i)}))})(e).then((function(){OF(e).then(t,t)}),i)}))}var LF=function(){function e(t){bv(e,this,(function(e){var i=null,n=null,r="Unknown",a=null,s=null,o=null,l=-1,c=0;function d(e){return i.openDb(n,1,(function(t){return new FT((function(i,n){var l={iKey:r,storageId:a,iKeyPrefix:function(){return s},evtKeyPrefix:function(){return o}};t.ctx=l,AF(t).then((function(){e(t).then(i,n)}),n)}))}),(function(e){return new FT((function(t,i){(function(e){e.objectStoreNames.contains(bF)||e.createObjectStore(bF,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),e.objectStoreNames.contains(IF)||e.createObjectStore(IF,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})})(e.db),t()}))}))}function u(e,t,i){return new FT((function(n,r){function a(t,i){(function(e,t){return new FT((function(i,n){var r=0,a=e.ctx.evtKeyPrefix();function s(){i(r)}function o(e,t){return new FT((function(i){var n=e.store.delete(t.key);n.onsuccess=function(e){r++,i()},n.onerror=function(e){i()}}))}e.openCursor(bF,"#key="+a,(function(e,i,n){return i.evt.persistence<=t&&0===i.key.indexOf(a)&&(function(e,t){for(var i=0;i<e.length;i++)if(t.tm<e[i].tm)return void e.splice(i,0,t);e.push(t)}(n,i),n.length>10&&n.splice(n.length-1,1)),0})).then((function(t){0!==t.length?e.openStore(bF,(function(e){for(var i=[],n=0;n<t.length;n++)i.push(o(e,t[n]));return FT.all(i).then(s,s)})):s()}),(function(){i(0)}))}))})(e,t).then((function(e){e>0&&(c-=e),i(e)}),(function(e){i(0)}))}function s(e){n(t.evt)}function o(){e.openStore(bF,(function(o){var l=o.store.put(t);l.onsuccess=function(r){i&&AF(e).then(s,s),c++,n(t.evt)},l.onerror=function(s){function o(i){0===i&&r(new Error(TF)),u(e,t,!1).then((function(e){n(t.evt)}),(function(){r(new Error(TF))}))}i?a(1,(function(e){e>0?o(e):t.evt.persistence>=2?a(2,(function(e){o(e)})):r(new Error(TF))})):r(new Error(TF))}}))}l>0&&c>=l?a(1,(function(e){0===e?t.evt.persistence>=2?a(2,(function(e){o()})):r(new Error(TF)):o()})):o()}))}e.id=t,e.initialize=function(t){var c=t.itemCtx.diagLog();if(!(i=new yF(c)).isAvailable())return i=null,!1;var u=t.itemCtx.getCfg(),h=t.storageConfig||{};return n=h.indexedDbName||"AppInsightEvents.1",r=u.instrumentationKey||r,a=e.id||t.id||pE(),o=(s=r+"::")+a+"::",l=h.maxStorageItems>0?h.maxStorageItems:l,d((function(e){return e.isNew?FT.resolve(!0):NF(e)})).then((function(e){}),(function(e){c.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),i=null})),!0},e.supportsSyncRequests=function(){return!1},e.getAllEvents=function(){return null!=i&&i.isAvailable()?d((function(e){return new FT((function(t,i){(function(e,t){return e.openCursor(bF,t,(function(e,t,i){return i.push(t),0}))})(e,"#key="+e.ctx.evtKeyPrefix()).then((function(e){c=e.length,t(PF(e))}),i)}))})):FT.resolve([])},e.addEvent=function(e,t,n){return null!=i&&i.isAvailable()?(t.id=t.id||pE(),wF(t.persistence)||(t.persistence=1),d((function(i){var n=e||t.id,r={key:i.ctx.evtKeyPrefix()+n,id:n,evt:t,tm:RF(),v:1};return u(i,r,!0)}))):FT.resolve(t)},e.removeEvents=function(e){if(null==i||!i.isAvailable())return FT.resolve([]);var t=[];return new FT((function(i,n){d((function(i){return i.openCursor(bF,"#key="+i.ctx.iKey,(function(i,n,r){if(-1!==function(e,t){for(var i=t.length,n=0;n<i;n++)if(e===t[n].id)return n;return-1}(n.id,e)){var a=i.cursor.delete();return a.onerror=MF(i),a.onsuccess=function(){t.push(n.evt),i.continue()},1}return 0}))})).then((function(e){c-=t.length,i(t)}),(function(e){c-=t.length,i(t)}))}))},e.clear=function(){return null!=i&&i.isAvailable()?new FT((function(e,t){d((function(e){return DF(e,"#key="+e.ctx.evtKeyPrefix(),(function(t){return 0===t.key.indexOf(e.ctx.evtKeyPrefix())}))})).then((function(t){c=0,e(PF(t))}),t)})):FT.resolve([])},e.teardown=function(){i&&i.closeDb(n)}}))}return e.__ieDyn=1,e}(),xF="AWTEvents";function FF(e){var t=Uf()||{},i=null;try{if(i=t[e]){var n="__storage_test__";i.setItem(n,n),i.removeItem(n)}}catch(e){(function(e,t){var i=!1;return t instanceof DOMException&&(22!==t.code&&"QuotaExceededError"!==t.name&&1014!==t.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||e&&0!==e.length&&(i=!0)),i})(i,e)||(i=null)}return i}function UF(e,t){if(e)for(var i=Dy(e),n=0;n<i.length;n++){var r=i[n];if(!t(e[r],r))break}}function BF(e){var t=!0;return UF(e,(function(e,i){return e&&(t=!1),t})),t}function VF(e,t){for(var i=1,n=0,r=function(){var e=[],r=t[i];if(UF(r,(function(t,i){return e.push(i),++n<10})),n>0){for(var a=0;a<e.length;a++)delete r[e[a]];return{value:!0}}i++};i<=e&&n<10;){var a=r();if("object"==typeof a)return a.value}return n>0}var HF=sF,$F=function(){function e(t,i){bv(e,this,(function(e){var n=null,r=xF,a=null,s=null,o=null,l=5e6,c=null,d=null;function u(e,t){return{key:e,db:t}}function h(e,t){void 0===t&&(t=!0);var i=null;if(n){var r=n.getItem(e);if(r)try{i=JSON.parse(r)}catch(t){n.removeItem(e)}}return t&&!i&&(i={events:{1:{},2:{},3:{}},lastAccessTime:0}),u(e,i)}function p(e,t){void 0===t&&(t=!0);var i=!0,r=e.db;if(r){t&&(r.lastAccessTime=(new Date).getTime());for(var a=1;a<=2;a++)if(!BF(r.events[a])){i=!1;break}}try{if(i)n&&n.removeItem(e.key);else{var s=JSON.stringify(r);if(s.length>l)return!1;n&&n.setItem(e.key,s)}}catch(e){return!1}return!0}function g(e){var t=[],i=h(e,!1),r=i.db;if(r){var a=r.events;try{for(var s=1;s<=2;s++)UF(a[s],(function(e,i){return e&&t.push(e),!0}))}catch(e){}n&&n.removeItem(i.key)}return t}e.id=i,n=FF(t)||null,e.initialize=function(t){if(!n)return!1;var i=t.storageConfig||{};return l=i.maxStorageSizeInBytes>0?i.maxStorageSizeInBytes:l,r=i.storageKey||xF,a=e.id||t.id||pE(),d=r+"."+a,c=r+"Version",s=t.itemCtx.getCfg().instrumentationKey,o=bT(s)||s,function(){if(n){for(var e=n.getItem(c),t=[],i=h(d),a=!1,s=0;s<n.length;s++){var l=n.key(s);if(0===l.indexOf(r)&&l!==c){if("3"!==e){t.push(u(l,null));continue}var g=h(l,!1),m=g.db;if(m){if((new Date).getTime()-m.lastAccessTime>6e5){for(var f=1,v=function(){var e=m.events[f],t=i.db.events[f];UF(e,(function(i,n){return(bT(i.iKey)||i.iKey)===o&&(t[n]=i,delete e[n]),!0})),f++};f<=2;)v();a=!0,t.push(g)}}else t.push(u(l,null))}}for(s=0;s<t.length;s++)p(t[s],!1);a&&p(i),n.setItem(c,"3")}}(),!0},e.supportsSyncRequests=function(){return!0},e.getAllEvents=function(){try{var e=[],t=h(d,!1).db;if(t)for(var i=t.events,n=2;n>=1;n--)UF(i[n],(function(t){return t&&(bT(t.iKey)||t.iKey)===o&&e.push(t),!0}));return FT.resolve(e)}catch(e){return FT.reject(e)}},e.addEvent=function(e,t,i){try{var n=h(d);t.id=t.id||pE(),HF(t.persistence)||(t.persistence=1);for(var r=t.persistence,a=t.id,s=n.db.events;;){if(s[r][a]=t,p(n))return FT.resolve(t);if(delete s[r][a],!VF(r,s))return FT.reject(new Error("Unable to free up event space"))}}catch(e){return FT.reject(e)}},e.removeEvents=function(e){try{var t=h(d,!1),i=t.db;if(i){var n=i.events;try{for(var r=0;r<e.length;++r){var a=e[r];delete n[a.persistence][a.id]}if(p(t))return FT.resolve(e)}catch(e){}e=g(t.key)}return FT.resolve(e)}catch(e){return FT.reject(e)}},e.clear=function(){try{var e=[],t=h(d,!1),i=t.db;if(i){for(var n=i.events,r=function(t){var i=n[t];UF(i,(function(t){return t&&(bT(t.iKey)||t.iKey)===o&&(delete i[t.id],e.push(t)),!0}))},a=2;a>=1;a--)r(a);p(t)}return FT.resolve(e)}catch(e){return FT.reject(e)}},e.teardown=function(){try{var e=h(d,!1),t=e.db;t&&(t.lastAccessTime=0,p(e,!1))}catch(e){}}}))}return e.__ieDyn=1,e}(),GF=sF,jF=function(e){function t(){var i=e.call(this)||this;return i.identifier="LocalStorage",i.priority=1009,i.version="3.2.9",bv(t,i,(function(e,t){var i,n,r,a;function s(){i=!1,n=!1,r=null,a=[]}function o(e,t){r||(r=new jT("LocalStorage")),r.scheduleEvent((function(e){return t(e)}),e)}function l(t){JC(e.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){o("sendToNext",(function(i){return t.provider.getAllEvents().then((function(i){for(var n=0;n<i.length;n++)try{var r=i[n];(bT(r.iKey)||r.iKey)===t.tenantId&&e.processNext(r,t.coreRootCtx.createNew())}catch(e){}}))}))}),(function(){return{iKeyConfig:t}}))}function c(t,i){JC(e.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){o("removeEvents",(function(e){var n=[];return Ry(i,(function(e){(bT(e.iKey)||e.iKey)===t.tenantId&&n.push(e)})),n.length>0?t.provider.removeEvents(n).then((function(e){})).catch((function(e){})):FT.resolve()}))}),(function(){return{iKeyConfig:t,events:i}}))}function d(e){var t=new LF;return t.initialize(e)||(t=null),t}function u(e,t){var i=new $F(e);return i.initialize(t)||(i=null),i}function h(t,i,n,r){var s=e.identifier,o=t.extensionConfig=t.extensionConfig||[],h=o[s]=o[s]||{};h.providers||(h.providers=[iF.LocalStorage,iF.IndexedDb]);var p=function(t,i,n,r){t&&(t.extensionConfig=t.extensionConfig||[]),!r&&i&&(r=i.getProcessTelContext().getNext());var a=null,s=e._getTelCtx().getNext();return s&&(a=s.getPlugin()),new OE(r,t,i,a)}(t,i,0,r),g={itemCtx:p,storageConfig:h,id:e.id},m=function(e){for(var t=e.storageConfig.providers,i=null,n=0;!i&&n<t.length&&n<5;)switch(t[n++]){case iF.LocalStorage:i=u("localStorage",e);break;case iF.SessionStorage:i=u("sessionStorage",e);break;case iF.IndexedDb:i=d(e)}return i}(g);if(m){var f={iKey:t.instrumentationKey,tenantId:bT(t.instrumentationKey)||t.instrumentationKey,minPersistenceCacheLevel:1,coreRootCtx:p,providerContext:g,provider:m};GF(h.minPersistenceLevel||-1)&&(f.minPersistenceCacheLevel=h.minPersistenceLevel),a.push(f),i.addNotificationListener({eventsSent:function(e){c(f,e)},eventsDiscarded:function(e,t){c(f,e)}}),l(f)}}s(),e.initialize=function(e,n,a,s){JC(n,(function(){return"LocalStorageChannel.initialize"}),(function(){i||(t.initialize(e,n,a),t.setInitialized(!1),i=!0,r=new jT("LocalStorage",n.logger)),h(e,n,0,s)}),(function(){return{coreConfig:e,core:n,extensions:a,pluginChain:s}}))},e.processTelemetry=function(t,r){var s=t;if(i&&!n){r=e._getTelCtx(r),MT(t,e.identifier);var l=null;Ry(a,(function(e){e.iKey===t.iKey&&(l=e)}));var c=l?l.provider:null;if(s.sync||!c)return void e.processNext(s,r);s.id=s.id||pE(),sF(s.persistence)||(s.persistence=1),function(e,t){return!(t.sync||t.persistence<e.minPersistenceCacheLevel)}(l,s)&&o("processTelemetry",(function(e){return c.addEvent(s.id,s,r)}))}e.processNext(s,r)},e.pause=function(){n=!0},e.resume=function(){JC(e.core,(function(){return"LocalStorageChannel:resume"}),(function(){n=!1,Ry(a,(function(e){e.provider&&l(e)}))}))},e._doTeardown=function(e,t){Ry(a,(function(e){var t=e.provider;t&&t.teardown()})),s()},e.flush=function(e,t){}})),i}return jf(t,e),t.__ieDyn=1,t}(BE),zF=jF,WF=class{constructor(e,t,i,n,r,a,s){this.logger=e,this.configProvider=t,this.clientInfo=i,this.eventLatency=n,this.contextProvider=r,this.accountCollectorURL=a,this.envOverride=s,this.manager=new ww,this.managerConfig=this.createConfigForManager(),this.currentTransmitProfile=Qe.REPORTING_PROFILE.RT_PROFILE,this.initManager(),this.uiVersion=this.getUiVersion(),this.configProvider.on("configUpdated",(()=>this.updateChannelConfig()))}createLogger(e){return new qF(e,this.manager,this.logger,this.configProvider,this.uiVersion,this.eventLatency,this.contextProvider,this.envOverride)}createConfigForManager(){const e={extensionConfig:{LocalStorage:{storageKey:"TsCalling"}},propertyConfiguration:{populateBrowserInfo:!0,populateOperatingSystemInfo:!0},channelConfiguration:{eventsLimitInMem:this.configProvider.config.eventsLimitInMem},endpointUrl:this.accountCollectorURL,enableCompoundKey:this.configProvider.config.enableCompoundKey};if(this.configProvider.config.useLocalStorageForOneDs){const t=new zF;e.channels=[[t]]}return e}getUiVersion(){const e=this.clientInfo.match(/^.*?\/(\d+\/)(.*?)\/.*$/);return e?e[1]+e[2]:this.clientInfo}updateChannelConfig(){this.configProvider.config.eventsLimitInMem!==this.managerConfig.channelConfiguration.eventsLimitInMem&&this.manager.getPostChannel().setEventQueueLimits(this.configProvider.config.eventsLimitInMem),this.setTransmitProfile()}initManager(){this.manager.create(this.managerConfig,[]),this.manager.getPostChannel()._notificationManager.addNotificationListener({eventsDiscarded:(e,t)=>this.logDiscardedEvents(e,t),eventsSent:e=>this.logSentEvents(e)}),this.setTransmitProfile()}logDiscardedEvents(e,t){let i="discarded events:";e.forEach((e=>i=`${i+e.name};`)),this.logger.info(`${i} reason:${t}`)}logSentEvents(e){let t=`sent events: ${e[0]?.data?.CorrelationId&&ft("value",e[0].data.CorrelationId)}:`;e.forEach((e=>{t=`${t+e.name};`})),this.logger.info(`${t}`)}setTransmitProfile(){this.configProvider.config.transmitProfileTimings.length&&this.manager.getPostChannel()._loadTransmitProfiles({[this.configProvider.config.transmitProfileName]:this.configProvider.config.transmitProfileTimings}),this.configProvider.config.transmitProfileName!==this.currentTransmitProfile&&this.manager.getPostChannel()._setTransmitProfile(this.configProvider.config.transmitProfileName),this.currentTransmitProfile=this.configProvider.config.transmitProfileName}},qF=class{constructor(e,t,i,n,r,a,s,o){this.tenant=e,this.manager=t,this.logger=i,this.configProvider=n,this.uiVersion=r,this.eventLatency=a,this.contextProvider=s,this.envOverride=o,this.instanceConfig={extensions:[],extensionConfig:[]}}sendEvent(e){this.setEnvPropertiesToEveryEvent();const t=this.configProvider.config.telemetryTenants[this.tenant],i=this.manager.getInst(t)??this.manager.newInst(t,this.instanceConfig,[]),n=e.props,r={};switch(this.logger.info(`preparing event for delievery: ${e.props?.CorrelationId??""}/${e.eventName}`),this.tenant){case"signaling":n.SkypeId&&(r.user_id={value:n.SkypeId,kind:10},r.Skype_InitiatingUser_Username={value:n.SkypeId,kind:10},r.SkypeId={value:n.SkypeId,kind:10},delete n.SkypeId),this.uiVersion&&(r.ui_version={value:this.uiVersion,kind:0});break;case"media":case"tlePlayer":this.uiVersion&&(r.uiVersion={value:this.uiVersion,kind:0});break;case"realtimeMedia":this.uiVersion&&(r["AppInfo.Version"]={value:this.uiVersion,kind:0})}for(const e of Object.keys(n)){const t=n[e];r[e]={value:t?.value??t,kind:t?.piiKind??0}}const a={name:e.eventName,data:r,latency:this.eventLatency,persistence:fT.Normal};this.configProvider.config.useSendBeaconSync&&(a.sync=2),this.logger.info(`about to send event ${JSON.stringify(a)}`),i.track(a)}setEnvPropertiesToEveryEvent(){const e=this.contextProvider?.();if(!ut(this.ctx,e)&&(this.ctx=e,this.ctx))if(this.envOverride){for(const e of Object.keys(this.envOverride||{}))if(this.ctx[e]){const t=this.ctx[e].piiKind??0,i=xt(this.ctx[e].value);this.manager.getPropertyManager().setProperty(this.envOverride[e],{value:i,kind:t})}}else for(const e of Object.keys(this.ctx)){const t=this.ctx[e].piiKind??0,i=xt(this.ctx[e].value);this.manager.getPropertyManager().setProperty(e,{value:i,kind:t})}}},KF=class extends We{constructor(e,t,i){super(),this.relayManager=e,this.configProvider=t,this.logger=i,this.currentInfo={},this.currentAreaContent={},this.isEnabled=!1,this.isEnabled=this.configProvider.config.enableE911,t.on("configUpdated",(()=>{const e=this.isEnabled;this.isEnabled=this.configProvider.config.enableE911,!this.isEnabled||e===this.isEnabled&&this.prober||(this.prober?.dispose(),this.prober=void 0,this.configProvider.config.probeE911OnInit&&this.probeForIP("config"))}))}get info(){return this.currentInfo}get areaContent(){return this.currentAreaContent}async getInfo(){return this.isEnabled&&!this.prober&&await this.probeForIP("publicGetInfo"),this.currentInfo}setClientInfo(e,t){if(this.isEnabled)switch(this.logger.info(`Client info for ${e} set`),e){case 3:this.mergeClientAreaInfo(JSON.parse(t));break;case 1:break;case 2:this.mergeClientNetworkInfo(JSON.parse(t))}}mergeClientAreaInfo(e){const t=JSON.stringify(this.currentAreaContent);this.currentAreaContent.geoCoordinates=e.geoCoordinates,ct(this.currentAreaContent),JSON.stringify(this.currentAreaContent)!==t&&this.raiseChanged()}mergeClientNetworkInfo(e){if(0===Object.keys(e).length){const e=Object.keys(this.currentInfo).length+Object.keys(this.currentAreaContent).length;return this.currentInfo={},this.currentAreaContent={},void(e>0&&this.raiseChanged())}const t=this.currentInfo.bssid!==e.bssid||this.currentInfo.bssidv6!==e.bssidv6||this.currentInfo.mac!==e.mac||this.currentInfo.macv6!==e.macv6||this.currentInfo.subnetLengthIpv4!==e.subnetLengthIpv4||this.currentInfo.subnetLengthIpv6!==e.subnetLengthIpv6,i=this.currentInfo.e911;this.currentInfo.bssid=e.bssid,this.currentInfo.bssidv6=e.bssidv6,this.currentInfo.e911=e.e911,this.currentInfo.mac=e.mac,this.currentInfo.macv6=e.macv6,this.currentInfo.subnetLengthIpv4=e.subnetLengthIpv4,this.currentInfo.subnetLengthIpv6=e.subnetLengthIpv6,ct(this.currentInfo),t?this.probeForIP("clientNetworkInfoChanged").then((e=>{e||this.raiseChanged()})):JSON.stringify(i)!==JSON.stringify(e.e911)&&this.raiseChanged()}async probeForIP(e){return this.probingPromise?(this.logger.info(`Probing already in progress, tried to start for: ${e}`),this.probingPromise):(this.probingPromise=this.probeForIPInternal(e),this.probingPromise.then((e=>(this.probingPromise=void 0,e))).catch((e=>(this.probingPromise=void 0,this.logger.error(`E911 probing failed: ${Be(e)}`),!1))))}async probeForIPInternal(e){this.logger.info(`Probing for public IP address: ${e}`);const t=await this.ensureProber();if(await t.ensureOnline(),t.ipFromRelay){if((this.currentInfo.ipv4||this.currentInfo.ipv6)!==t.ipFromRelay)return delete this.currentInfo.ipv4,delete this.currentInfo.ipv6,this.currentInfo[Vg.test(t.ipFromRelay)?"ipv4":"ipv6"]=t.ipFromRelay,this.raiseChanged(),!0}else if(0!==Object.keys(this.currentInfo).length)return this.currentInfo={},this.raiseChanged(),!0;return!1}async ensureProber(){if(this.prober)return this.prober;const e=kk(await this.relayManager.queryRelaysAsync({relayType:"turn"}),this.configProvider.config);return this.prober=new Pk(e,new fk(this.logger.createChild("Prober"),this.logger.createChild("ProberUnsafe"))),this.prober}};var JF=class{constructor(){this.reports={}}watch(e){const t={time:Date.now(),duration:-1};return this.reports[e]&&(e=`${e}_last`),this.reports[e]=t,{end:e=>{e?t.error=e:t.duration=Date.now()-t.time}}}getReports(){return this.reports}},YF="trapTokenFetch",QF=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new JF,this.context=e,this.logger=e.logger.createChild("RM"),this.request=e.request}initialize(){this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e)}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getAuthTokenStats(){}getStats(){return this.timers.getReports()}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",Be(t)):this.logger.error("failed to retrieve relays",Be(t)),null)));return t}refreshRelaysFromConfig(){this.request.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}updateRelaysAsync(){const e=this.config.Service.tokenUrl;let t;const i=this.context.trapTokenCredentialsProvider?async()=>(t=this.timers.watch(YF),this.context.trapTokenCredentialsProvider()):async()=>{const i=this.timers.watch("skypeTokenFetch");let n="";try{n=await this.context.tokenProvider(),this.logger.info("fetching skypeToken")}catch(e){throw i.end(Be(e)),e}return i.end(),t=this.timers.watch(YF),(await this.request.get(e,{headers:{"X-Skypetoken":n,"api-version":2}})).response};return this.logger.info("Fetch TRAP token "+(this.context.trapTokenCredentialsProvider?"with provider":"directly")),i().then((e=>{t.end();let i=0;const n=this.config.Token.earlyRefreshMinutes,r=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),i=Math.max(e.expires-60*n,e.expires*r/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*i);const a=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:'"rtcmedia"',s=function(e){return{expires:e.expires,username:e.username,password:e.password,realm:e.realm}}(this.getTrapToken(a)),o={Skype:[{addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn",...s}],Lync:[{addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn",...s}],Turn:[{addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn",...s}]};return this.logger.info("relays from trap",o),o})).catch((e=>{throw t&&t.end(Be(e)),e}))}storeTrapTokens(e){if(!e?.tokens)return void this.logger.error("failed to get tokens from trap response");const t={};e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}})),this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch("configFetch");try{const t=await this.context.configProvider();e.end(),this.logger.info("retrieved configuration:",t),t&&(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",Be(t)),e.end(Be(t))}}};var ZF=class{constructor(){this.reports={}}watch(e){const t={time:Date.now(),duration:-1};return this.reports[e]&&(e=`${e}_last`),this.reports[e]=t,{end:e=>{e?t.error=e:t.duration=Date.now()-t.time}}}getReports(){return this.reports}},XF=class{constructor(e){this.updateRelaysPromise=null,this.trapTokens={},this.relaysOverride=[],this.timers=new ZF,this.context=e,this.authTokenFetcher=this.context.authTokenFetcher,this.logger=e.logger.createChild("RM2")}initialize(){}setRelayOverride(e){this.relaysOverride=e}setDefaultRelayConfig(e){this.config??(this.config=e),this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync(!0))}setClientSupportsGenericTokenApi(e){this.authTokenFetcher.supportsGenericTokenApi=e}async queryRelaysAsync(e={}){if(this.logger.info("query relays"),this.relaysOverride.length>0)return this.relaysOverride;this.updateRelaysPromise||(this.updateRelaysPromise=this.updateRelaysFromConfigAsync());const t=await this.updateRelaysPromise;return t?"turn"===e.relayType?t.Turn:e.isRemoteClientLync?t.Lync:t.Skype:[]}getStats(){return this.timers.getReports()}getAuthTokenStats(){return this.context.authTokenFetcher.getStats()}updateRelaysFromConfigAsync(e=!1){const t=this.getConfigAsync().then((()=>this.updateRelaysAsync())).then((e=>(this.updateRelaysPromise=t,e))).catch((t=>(this.updateRelaysPromise=null,e?this.logger.warn("failed to retrieve relays",Be(t)):this.logger.error("failed to retrieve relays",Be(t)),null)));return t}refreshRelaysFromConfig(){this.context.isOnline()?this.updateRelaysFromConfigAsync():(this.updateRelaysPromise=null,this.logger.warn("not refreshing relays due to no network connection"))}async updateRelaysAsync(){const e=this.context.configProvider?.useNewTokenApi?"aadTokenFetch":"skypeTokenFetch",t=this.timers.watch(e),i=Te();this.logger.info(`${i}[RM2] Fetch TRAP token`);try{const e=await this.context.authTokenFetcher.fetchTrapToken(i,this.config);t.end();let n=0;const r=this.config.Token.earlyRefreshMinutes,a=this.config.Token.earlyRefreshPercentage;this.storeTrapTokens(e),n=Math.max(e.expires-60*r,e.expires*a/100),setTimeout(this.refreshRelaysFromConfig.bind(this),1e3*n);const s=this.config.Relay.Turn.realm?this.config.Relay.Turn.realm:'"rtcmedia"',o=function(e){return{expires:e.expires,username:e.username,password:e.password,realm:e.realm}}(this.getTrapToken(s)),l={Skype:[{addresses:this.config.Relay.Skype.addresses,fqdns:this.config.Relay.Skype.fqdns,tcpPort:this.config.Relay.Skype.tcpPort,udpPort:this.config.Relay.Skype.udpPort,type:"msturn",...o}],Lync:[{addresses:this.config.Relay.Lync.addresses,fqdns:this.config.Relay.Lync.fqdns,tcpPort:this.config.Relay.Lync.tcpPort,udpPort:this.config.Relay.Lync.udpPort,type:"msturn",...o}],Turn:[{addresses:this.config.Relay.Turn.addresses,fqdns:this.config.Relay.Turn.fqdns,tcpPort:this.config.Relay.Turn.tcpPort,udpPort:this.config.Relay.Turn.udpPort,tlsPort:this.config.Relay.Turn.tlsPort,type:"turn",...o}]};return this.logger.info("relays from trap",l),l}catch(e){throw this.logger.info(`Fetch TRAP token failed with error ${e}`),t&&t.end(Be(e)),e}}storeTrapTokens(e){const t={};if(e?.tokens)e.tokens.forEach((i=>{t[i.realm]={expires:e.expires,username:i.username,password:i.password,realm:i.realm}}));else{if(!e.realm)return void this.logger.error("failed to get tokens from trap response");t[e.realm]=e}this.trapTokens=t}getTrapToken(e){if("string"==typeof e){const t=e.replace(/^"|"$/g,""),i=`"${t}"`,n=this.trapTokens[i]||this.trapTokens[t];if(n)return n}throw new Error(`token for relay not found, realm: ${e}`)}async getConfigAsync(){this.logger.info("retrieving configuration");const e=this.timers.watch("configFetch");try{const t=await this.context.relayConfigProvider();e.end(),this.logger.info("retrieved configuration:",t),t&&(this.config=t),this.logger.info("applied configuration:",this.config)}catch(t){this.logger.warn("failed to retrieve configuration",Be(t)),e.end(Be(t))}}};var eU=class{constructor(e,t,i,n,r){this.signalingAgentProvider=t,this.request=i,this.tokenProviders=n,this.configProvider=r,this.errors=[],this.clientSupportsGenericTokenAPI=!1,this.logger=e.createChild("AuthTokenFetcher")}set supportsGenericTokenApi(e){this.clientSupportsGenericTokenAPI=e}buildHeaders(e,t){const i={"api-version":2};switch(this.configProvider?.useTokenMigrationHeader&&(i["X-MS-Migration"]="True"),e){case 4:case 8:return i.Authorization=`Bearer ${t}`,i;case 1:return i["X-Skypetoken"]=t,i;default:throw new Error(`TokenType ${e} is not supported`)}}serviceSupportedTokenTypes(e){let t=null;if(void 0===e)t=this.clientSupportedTokenTypes();else{const i=e?.toLowerCase();t=this.constructTokenType(i)}return null===t&&this.configProvider?.useSkypeTokenWhenNoAuthenticateHeader&&(t|=1),t}extractWwwauthenticateHeaders(e){let t={};if(e){const i=Ut(e,"www-authenticate");i&&(t={authenticationHeaders:[i]})}return t}convertStringToTokenType(e){switch(e){case"cae":return 8;case"aad":return 4;case"skype":return 1;default:return this.logger.info("[authTokenFetcher][convertStringToTokenType]unexpected: unrecognized token type ${tokenType}"),null}}getTokenTypeFromHeaders(e,t){if(!this.clientSupportsGenericTokenAPI)return 1;let i=null;const n=t?.authenticationHeaders;if(!n&&e)this.configProvider?.useSkypeTokenWehnNoAuthHeader?(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] no www-authenticate header received, fallback to skype token"),i=1):(this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has not provided www-authenticate headers. use client supported tokens"),i=this.clientSupportedTokenTypes());else if(n||e){if(n&&e)for(const e of n){const t=Bt(e);if(this.configProvider?.supportMissingTokenTypesInResponse&&0===t.length)this.logger.info("[authTokenFetcher][getAuthHeadersTokenTypes] Service has www-authenticate header, but no token types. Use client supported tokens"),i=this.clientSupportedTokenTypes();else for(const e of t){const t=this.convertStringToTokenType(e.toLowerCase());this.configProvider?.clientSupportsCaeToken&&8===t&&(i|=8),this.configProvider?.clientSupportsAadToken&&4===t&&(i|=4),this.configProvider?.clientSupportsSkypeToken&&1===t&&(i|=1)}}}else this.logger.info("[authTokenFetcher][getTokenTypeFromHeaders] retrying to fetch token woth client supported tokens"),i=this.clientSupportedTokenTypes();return i}constructTokenType(e){let t=null;return e.includes("aad")&&this.configProvider?.clientSupportsAadToken&&(t|=4),e.includes("cae")&&this.configProvider?.clientSupportsCaeToken&&(t|=8),e.includes("skype")&&this.configProvider?.clientSupportsSkypeToken&&(t|=1),t}getTokenMetadataForTrapService(e,t,i){const n={verb:"POST",path:e},r=JSON.stringify(n);let a=null;const s=this.extractWwwauthenticateHeaders(i),o=!!s?.authenticationHeaders;return a=i?this.getTokenTypeFromHeaders(o,s):this.serviceSupportedTokenTypes(t),this.logger.info(`[authTokenFetcher][getTokenMetadata] return token type=${a}, factoJson=${r}`),{tokenType:a,factorsJson:r,requestMetadataJson:s,isUnauthorized:o}}clientSupportedTokenTypes(){let e=null;return this.configProvider?.clientSupportsAadToken&&(e|=4),this.configProvider?.clientSupportsCaeToken&&(e|=8),this.configProvider?.clientSupportsSkypeToken&&(e|=1),e}async handleAuthTokenFailure(e,t,i,n){this.logger.info("[authTokenFetcher][handleAuthTokenFailure] failed to fetch token, retrying");try{const r=this.getTokenMetadataForTrapService(t,void 0,i);return this.logger.info(`[authTokenFetcher][handleAuthTokenFailure] token request options=${r}`),r.invalidToken=n,await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(e,!1,r)}catch(e){this.errors.push(Be(e)),this.logger.error(`[authTokenFetcher] failed to fetch token trough new api with error: ${Be(e)}, quiting`)}}getRequestToken(e){const t=Ut(e,"X-Skypetoken");if(t)return t;const i=Ut(e,"Authorization");if(i){const e=i.split(" ");if(2===e.length)return e[1]}}async fetchTrapCredentials(e,t,i){const n=this.buildHeaders(t,e),r=await this.request.get(i,{headers:n});return r?.response}async fetchTrapTokenWithNewTokenApi(e,t,i){let n;this.logger.info(`${i}[authTokenFetcher] fetching token through fetchTrapTokenWithNewTokenApi`);const r=this.getTokenMetadataForTrapService(e,t);try{return n=await this.signalingAgentProvider.getSignalingAgent().authTokenManager.getToken(i,!1,r),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}catch(t){this.errors.push(Be(t)),this.logger.error(`${i}[authTokenFetcher] fetchTrapTokenWithNewTokenApi failed with ${Be(t)}, retrying...`);const r=t?.response?.headers;if(r){const t=this.getRequestToken(r);return n=await this.handleAuthTokenFailure(i,e,r,t),this.tokenTypeFetched=this.signalingAgentProvider.getSignalingAgent().authTokenManager.getLastTokenType(i),await this.fetchTrapCredentials(n,this.tokenTypeFetched,e)}throw t}}async fetchTrapTokenThroughProvider(){return this.logger.info("[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokenThroughProvider"),this.tokenProviders.trapTokenCredentialsProvider()}async fetchTrapTokensWithLegacyTokenFetcher(e,t){this.logger.info(`${t}[authTokenFetcher][authTokenFetcher] fetching token through fetchTrapTokensWithLegacyTokenFetcher`);try{this.tokenTypeFetched=1;const t=await this.tokenProviders.skypeTokenProvider();return(await this.request.get(e,{headers:{"X-Skypetoken":t,"api-version":2}})).response}catch(e){throw this.errors.push(Be(e)),this.logger.error(`${t}[authTokenFetcher] fetchTrapTokensWithLegacyTokenFetcher failed with ${Be(e)}`),e}}getStats(){return{tokenType:this.tokenTypeFetched,errors:this.errors}}async fetchTrapToken(e,t){let i;this.logger.info(`${e}[AuthTokenFetcher] Start fetching token`);const n=t.Service.tokenUrl,r=t.Service.supportedTokenTypes;return i=this.configProvider?.useNewTokenApi?this.fetchTrapTokenWithNewTokenApi(n,r,e):this.tokenProviders.trapTokenCredentialsProvider?this.fetchTrapTokenThroughProvider():this.fetchTrapTokensWithLegacyTokenFetcher(n,e),i}},tU=class{constructor(e,t,i){this.config=e,this.signalingAgentProvider=t,this.logger=i}createRelayManager(e){return this.relayManager||(this.configProvider=e,this.relayManager=this.config.relayManager||this.buildRelayManager(this.config.httpRequestDispatcher,this.config.tokenProvider,this.config.configProvider,this.config.appStateProvider,this.config.trapTokenCredentialsProvider,e)),this.relayManager}getRelayManager(){return this.relayManager}buildRelayManager(e,t,i,n,r,a){const s=e||new Ve(this.logger),o={get:(e,t)=>s.getAsync(e,s.getRequestOptions("GET",t?.headers,null,t?.timeout)),isOnline:n.isOnline};if(this.configProvider.config.useNewTokenApi){const e=new eU(this.logger,this.signalingAgentProvider,o,{skypeTokenProvider:t,trapTokenCredentialsProvider:r},a?.config);return function(e){return new XF(e)}({logger:this.logger,relayConfigProvider:()=>i.getRelayConfig(),isOnline:n.isOnline,authTokenFetcher:e,configProvider:this.configProvider?.config})}return function(e){return new QF(e)}({logger:this.logger,tokenProvider:t,trapTokenCredentialsProvider:r,configProvider:()=>i.getRelayConfig(),request:{get:(e,t)=>s.getAsync(e,s.getRequestOptions("GET",t?.headers,null,t?.timeout)),isOnline:n.isOnline}})}},iU=class extends Error{constructor(e,t=1){super(e),this.callSupport=t}};function nU(e){let t={};return e.telemetryLoggers?t=e.telemetryLoggers:e.telemetryService?.getGenericTelemetryLogger&&e.telemetryTenants?Object.keys(e.telemetryTenants).forEach((i=>t[i]=e.telemetryService.getGenericTelemetryLogger(e.telemetryTenants[i]))):e.telemetryService&&(e.telemetryService.sendEvents||e.telemetryService.getCallingAdapter)&&(e.telemetryService.sendEvents&&(t.media={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}},t.tlePlayer={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendEvents([t])}}),e.telemetryService?.sendRealTimeEvents&&(t.realtimeMedia={sendEvent(t){t.eventName&&(t.eventName=t.eventName.replace(/^(mdsc_)/,"")),e.telemetryService.sendRealTimeEvents([t])}}),e.telemetryService.getCallingAdapter&&(t.signaling={sendEvent(t){e.telemetryService.getCallingAdapter().sendEvent(t.eventName,t.props)}})),t}var rU=class e extends We{constructor(e,t){super(),this._config=e,this._ecsProvider=t,this.callRegistries=[],this._logger=new Qt(this._config.logger).createChild("PluginlessStack"),this._platformManager=new Jx,this._waitForAccountConfiguration=new Jh,this.platformCallConstraintsProvider=new Yt(this._logger.createChild("PlatformConstraintsProvider"))}async initializeMediaAgent(e){let t,i=null;if(!this._mediaAgentProvider)throw new iU("PluginlessStack initialize MediaAgent error, Media Stack not initialized",i);try{this._relayManagerFactory=new tU(e,this._signalingAgentProvider,this._logger),t=await this._mediaAgentProvider.buildAgent(this._config.platformType,this._relayManagerFactory,this._midCallTelemetry)}catch(e){i=e.some((e=>"incompatible_version"===e.reason))?2:1}if(!this._config.usePlatformSupportApi&&!this._config.callSettings?.useLwjForAllCalls){if(i)throw new iU("PluginlessStack initialization failed",i);{const e=(new Jx).getPlatformSupportLevel(!0);if(1!==e&&2!==e)throw new iU("PluginlessStack initialization failed",1)}}t?(this._screenSharingManager=new Zx(t.getScreenSharingManager()),this._waitForAccountConfigurationTimeout=window.setTimeout((()=>{this._waitForAccountConfiguration.resolve(void 0),this._waitForAccountConfigurationTimeout=void 0}),3e4),this._oneDsTelemetryLoggers=function(e,t,i,n,r,a){const s={signaling:[],media:[],tlePlayer:[],realtimeMedia:[]};let o={signaling:{sendEvent:e=>s.signaling.push(e)},media:{sendEvent:e=>s.media.push(e)},tlePlayer:{sendEvent:e=>s.tlePlayer.push(e)},realtimeMedia:{sendEvent:e=>s.realtimeMedia.push(e)}};return t.getConfigReceivedOrTimeout().then((async()=>{let l=(await r)?.serviceUrls?.OneDsCollectorUrl;if(l=l??t.config.collectorUrl,l){const r=new WF(e,t,i,t.config.eventLatency,n,l);o.signaling=r.createLogger("signaling"),o.media=r.createLogger("media"),o.tlePlayer=r.createLogger("tlePlayer");const a=new WF(e,t,i,t.config.eventLatencyRealTime,n,l,{"UserInfo.Ring":"Ring","UserInfo.TenantId":"TenantId","AppInfo.ClientType":"client_type","UserInfo.ETag":"AppInfo.EcsEtag",appversion:"First/Second Client VDI Desktop Version",vdiMode:"First/Second Client VDI Mode",vdiConnectedState:"First/Second Client VDI Connected State",vdiShimVersion:"First/Second Client VDI Shim Version",vdiProvider:"First/Second Client VDI Provider Version"});o.realtimeMedia=a.createLogger("realtimeMedia")}else o=nU(a);for(const[e,t]of Object.entries(s))for(const i of t)o[e].sendEvent(i)})),o}(this._logger.createChild("OneDsLogger"),t.getConfigProvider(),e.clientInformation,this._config.telemetryContextProvider,this._waitForAccountConfiguration.promise,this._config),t.getConfigProvider().config.useOneDsLogger&&(this.signalingLoggerAdapter={sendEvent:(e,t)=>{const i={eventName:e,props:t};this._oneDsTelemetryLoggers.signaling.sendEvent(i)}}),this._mediaAgent=t,this._e911=new KF(this._relayManagerFactory.getRelayManager(),this._mediaAgent.getConfigProvider(),this._logger.createChild("E911")),this._e911?.changed((()=>{this.event("e911InfoChanged").raise(this._e911?.info,this._e911?.areaContent)}))):this._deviceManager=new Xi}async initializeSignalingAgentProvider(e){this._trouterService=e.trouterService,this._signalingAgentProvider=aF(e.signalingAgentConfig,this._ecsProvider,this._config.logger,this.signalingLoggerAdapter)}static async build(t,i,n){try{const r=new e({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.logger,telemetryLoggers:t.telemetryLoggers,telemetryService:t.telemetryService,telemetryTenants:t.telemetryTenants,telemetryContextProvider:t.telemetryContextProvider,platformType:t.platformType,callSettings:t.callSettings,usePlatformSupportApi:t.usePlatformSupportApi,clientInformation:t.signalingAgentConfig.clientInformation},i);return r.initializeMediaProvider({detectH264Support:t.mediaAgentFactoryConfig.detectH264Support,domOverrides:t.mediaAgentFactoryConfig.domOverrides,mediaSettings:t.mediaAgentFactoryConfig.settings,logger:t.mediaAgentFactoryConfig.logger,safeLogger:t.mediaAgentFactoryConfig.safeLogger,webcvProvider:t.mediaAgentFactoryConfig.webcvProvider,wasmdnsProvider:t.mediaAgentFactoryConfig.wasmdnsProvider,wasmaecProvider:t.mediaAgentFactoryConfig.wasmaecProvider,wasmVqeProvider:t.mediaAgentFactoryConfig.wasmVqeProvider,createWasmWorkerCbs:t.mediaAgentFactoryConfig.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.mediaAgentFactoryConfig.encodedStreamsWorkerProvider,clientInformation:t.signalingAgentConfig.clientInformation}),r.setMidCallTelemetry(n),r.initializeSignalingAgentProvider({signalingAgentConfig:t.signalingAgentConfig,trouterService:t.trouterService}),await r.initializeMediaAgent({httpRequestDispatcher:t.mediaAgentFactoryConfig.httpRequestDispatcher,tokenProvider:t.mediaAgentFactoryConfig.tokenProvider,configProvider:t.mediaAgentFactoryConfig.configProvider,appStateProvider:t.mediaAgentFactoryConfig.appStateProvider,clientInformation:t.signalingAgentConfig.clientInformation,trapTokenCredentialsProvider:t.mediaAgentFactoryConfig.trapTokenCredentialsProvider,relayManager:t.mediaAgentFactoryConfig.relayManager}),r}catch(t){throw t instanceof iU?t:new iU(`${t}`)}}static async buildBaseStack(t,i){const n=new e(t,i);return n.initializeMediaProvider({detectH264Support:t.detectH264Support,domOverrides:t.domOverrides,mediaSettings:t.mediaSettings,logger:t.logger,safeLogger:t.safeLogger,webcvProvider:t.webcvProvider,wasmdnsProvider:t.wasmdnsProvider,wasmaecProvider:t.wasmaecProvider,wasmVqeProvider:t.wasmVqeProvider,createWasmWorkerCbs:t.createWasmWorkerCbs,encodedStreamsWorkerProvider:t.encodedStreamsWorkerProvider,clientInformation:t.clientInformation}),n}async init(){}async dispose(e=Te()){const t=this._logger.createFnLogger("dispose",e);t.info("Dispose"),this._ecsProvider.dispose(),this._e911?.dispose();const i=e=>{t.warn("Failed:",e)},n=this.callRegistries.map((t=>t.dispose(e).catch(i)));await Promise.all(n),await this._mediaAgent.dispose(e).catch(i),t.info("media agent is disposed"),this.callRegistries=[],t.info("call registries are disposed"),this._screenSharingManager&&(this._screenSharingManager.dispose(e),this._screenSharingManager=void 0,t.info("screensharing manager is disposed")),this._deviceManager=void 0,super.dispose()}getCallRegistry(){return this._logger.info("returning default callRegistry"),this.callRegistries[0]?this.callRegistries[0]:this._createCallRegistry()}async createCallRegistry(e,t=Te()){const i=e?Pe(e.id):void 0,n=this._logger.createFnLogger(`createCallRegistry[identity=${i}]`,t),r=this.callRegistries.find((t=>t.identity===e.id));return r&&!r.isDisposing?(n.info(`callRegistry already exists for ${Pe(e.id)}`),r):(r?.isDisposing&&await r.disposePromise,this._createCallRegistry(e))}createCompositor(e){throw new Error("Method not implemented.")}_createCallRegistry(e){if(!this._trouterService)throw new iU("Unable to create call registry, trouter service undefined");if(!this._mediaAgent)throw new iU("Unable to create call registry, media agent undefined");if(!this._signalingAgentProvider)throw new iU("Unable to create call registry, signaling agent undefined");const t=new jm(this._trouterService,this._signalingAgentProvider,this._mediaAgent,this._logger,nU(this._config),this._ecsProvider,e,this._oneDsTelemetryLoggers);return t.on("disposed",(()=>{this.callRegistries.splice(this.callRegistries.indexOf(t),1)})),t.on("accountConfigurationReceived",(e=>{0===this._waitForAccountConfiguration.state&&(this._waitForAccountConfiguration.resolve(e),window.clearTimeout(this._waitForAccountConfigurationTimeout)),this._relayManagerFactory.getRelayManager().setDefaultRelayConfig(e.relayConfig),this._relayManagerFactory.getRelayManager().setClientSupportsGenericTokenApi(e.clientSupportsGenericTokenAPI)})),t.on("locationInfoSet",((e,t)=>{this._e911?.setClientInfo(e,t)})),this.callRegistries.push(t),t}initializeMediaProvider(e){const t=(0,$e.assign)({},e);this._mediaAgentProvider=new qx(t,this._ecsProvider,this.platformCallConstraintsProvider),this._deviceManager=new Km(this._mediaAgentProvider.getDeviceManager())}setMidCallTelemetry(e){this._midCallTelemetry=e}getDeviceManager(){return this._deviceManager}async getDeviceManagerAsync(){return this._deviceManager}createDeviceManager(e){return this._deviceManager}getScreenSharingManager(){return this._screenSharingManager}getSetup(){}getEcsProvider(){return this._ecsProvider}async getEcsProviderAsync(){return this._ecsProvider}getCallFeedback(){return null}getAiMdp(){return null}fireIntent(e,t){}getVersion(){return{build:"2024.14.01.23",ovb:"7b433484b6052f263c376357e5f0a7c2fecbb27f"}}getMediaStatus(){return null}getVideoCapabilityLimits(){return null}async setMediaConfig(e){this._mediaAgent.setMediaConfig(e)}async getE911Info(){return this._e911?.getInfo()}setPlatformCallConstraints(e){this.platformCallConstraintsProvider.setConstraints(e)}getPlatformSupportLevel(){return this._platformManager.getPlatformSupportLevel(!!this._mediaAgent)}getLiveStreamClient(){return new Zi(this._ecsProvider.createEcsConfiguration(),this._logger.createChild("LiveStreamClient"),(()=>nU(this._config).tlePlayer))}createVoipCallCoordinator(){}async setLogFileName(e,t,i){throw new Error("not supported")}aggregateDiagnosticLogs(e){return Promise.reject("not supported")}extendBrbFeedback(e,t){return Promise.reject("not supported")}async addOcclusion(e,t,i,n,r,a){}async removeOcclusion(e,t,i,n){}async flushLogs(){throw new Error("not supported")}async getStageCapability(){throw new Error("not supported")}},aU={build(e){const t=e.telemetryContextProvider?.(),i=new Yx(t),n=new nf;return function(e,t,i){if(!Jm.RootToolsManager.isDelegateSet()){const n=new rf(e.telemetryService,t);if(Jm.RootToolsManager.setDelegate(n),n.on("onMidCallTelemetry",(e=>i.send(e))),e.logger){const t=new Qm(e.logger);Jm.LogFactory.instance().addAppender(t)}}e.logger=new we("JS.TsCalling.Pluginless",!0),e.mediaAgentFactoryConfig.logger=new we("JS.TsCalling.MediaAgentUnsafe",!1),e.mediaAgentFactoryConfig.safeLogger=new we("JS.TsCalling.MediaAgent",!0),e.signalingAgentConfig.logger=new we("JS.TsCalling.SignalingAgent",!0)}(e,i,n),rU.build(e,i,n)},buildBaseStack(e){const t=e.telemetryContextProvider?.(),i=new Yx(t);return rU.buildBaseStack(e,i)},getVersion:()=>({build:"2024.14.01.23",ovb:"7b433484b6052f263c376357e5f0a7c2fecbb27f"})};if("object"==typeof r.exports&&"object"==typeof n){r.exports=((e,t,i,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of Object.getOwnPropertyNames(t))Object.prototype.hasOwnProperty.call(e,r)||r===i||Object.defineProperty(e,r,{get:()=>t[r],enumerable:!(n=Object.getOwnPropertyDescriptor(t,r))||n.enumerable});return e})(r.exports,n)}return r.exports}))}));const f={CALL_CLIENT:{INIT_CALL_CLIENT:{message:"Failed to initialize CallClient. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:500,subCode:4e4,resultCategories:["UnexpectedClientError"]},CREATE_CALL_AGENT:{message:"Failed to create CallAgent. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:409,subCode:40001,resultCategories:["UnexpectedClientError"]},CREATE_TEAMS_CALL_AGENT:{message:"Failed to create TeamsCallAgent. Please try again, if issue persists, gather browser console logs, and contact Azure Communication Services support.",code:409,subCode:40002,resultCategories:["UnexpectedClientError"]},RELAY_INFO:{message:"Failed to create a URL object with the ICE server URL provided.",code:400,subCode:40003,resultCategories:["ExpectedError"]},RELAY_UNRECOGNIZED_SCHEMA:{message:"The ICE server url must contain 'turn', 'turns', or 'stun'.",code:400,subCode:40004,resultCategories:["ExpectedError"]},PROXY_SHORT_URL:{message:"Failed setup proxy, the url is too short",code:400,subCode:40005,resultCategories:["ExpectedError"]},PROXY_PROTOCOL:{message:"Failed setup proxy, the protocol is not https or http",code:400,subCode:40006,resultCategories:["ExpectedError"]},SETUP_PROXY:{message:"Failed to create a URL object with the proxy URL provided.",code:400,subCode:40007,resultCategories:["ExpectedError"]},ONE_CALL_AGENT_PER_CALL_CLIENT:{message:"CallClient instance can support only one CallAgent or TeamsCallAgent create new CallClient instance to create new CallAgent or TeamsCallAgent",code:400,subCode:40008,resultCategories:["ExpectedError"]},EMERGENCY_CODE_TOO_LONG:{message:"EmergencyCountryCode is invalid, max length is 10",code:400,subCode:40009,resultCategories:["ExpectedError"]}},CALL_STACK:{BAD_PROTOCOL:{message:"ACS Web Calling SDK must be used through https, file:, or localhost",code:400,subCode:40100,resultCategories:["ExpectedError"]},BASE_STACK_INIT_TIMEOUT:{message:"Failed to create CallAgent, timeout during initialization of the calling base stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40101,resultCategories:["UnexpectedClientError"]},BASE_STACK_INIT_FAILED:{message:"Failed to create CallAgent, failure during initialization of the calling base stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40102,resultCategories:["UnexpectedClientError"]},USER_STACK_NO_BASE_STACK:{message:"Failed to create CallAgent, failure to initialize calling user stack because calling base stack failed to create. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40103,resultCategories:["UnexpectedClientError"]},USER_STACK_INIT_TIMEOUT:{message:"Failed to create CallAgent, timeout during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40104,resultCategories:["UnexpectedClientError"]},USER_STACK_INIT_FAILED:{message:"Failed to create CallAgent, failure during initialization of the calling user stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40105,resultCategories:["UnexpectedClientError"]},PARSE_CONFIG:{message:"Failed to set configurations for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40106,resultCategories:["UnexpectedClientError"]},SET_STACK_CONFIG:{message:"Failed to set user configurations for calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40107,resultCategories:["UnexpectedClientError"]},GET_DM:{message:"Failed to get device manager due to internal call stack undefined. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40108,resultCategories:["UnexpectedClientError"]},SET_STACK_PARAMS:{message:"Failed to set configuration parameters for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40109,resultCategories:["UnexpectedClientError"]},FOUND_UNDEFINED_CONFIGS:{message:"Fetched undefined configurations for the calling stack. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40110,resultCategories:["UnexpectedClientError"]},SIGNALING_SERVICE_CREATE_FAIL:{message:"Failed to connect to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40111,resultCategories:["UnexpectedClientError"]},SIGNALING_INIT_FAIL:{message:"Failed to initialize connection to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40112,resultCategories:["UnexpectedClientError"]},SIGNALING_SERVICE_ALREADY_INITIALIZED:{message:"Already connected to Azure Communication Services infrastructure. Please try again, if issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:40113,resultCategories:["ExpectedError"]},SIGNALING_SERVICE_CREATE_TIMEOUT:{message:"Failed to connect to Azure Communication Services infrastructure, timeout during initialization. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:408,subCode:40114,resultCategories:["UnexpectedClientError"]},SIGNALING_UNINITIALIZED:{message:"Failed to create CallAgent, unable to initialize connection to Azure Communication Services infrastructure. Please try again and check the browser's network requests. If the requests keep failing, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:412,subCode:40115,resultCategories:["UnexpectedClientError"]}},CALL_AGENT:{PROXY_CUSTOM_TURN_FORBIDDEN:{message:"Using proxy or custom TURN for calls involving Teams is disabled",code:403,subCode:40200,resultCategories:["ExpectedError"]},PARSE_ACCESSTOKEN:{message:"Failed to parse AccessToken",code:500,subCode:40201,resultCategories:["UnexpectedClientError"]},CANT_CALL_YOURSELF:{message:"Call to yourself is not supported.",code:400,subCode:40202,resultCategories:["ExpectedError"]},ACS_ALREADY_DISPOSED:{message:"Call Agent is already disposed",code:409,subCode:40203,resultCategories:["ExpectedError"]},CTE_ALREADY_DISPOSED:{message:"Teams Call Agent is already disposed",code:409,subCode:40204,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to CallAgent event, unknown event name.",code:422,subCode:40205,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from CallAgent event, unknown event name.",code:422,subCode:40206,resultCategories:["ExpectedError"]},MESH_DEVICETYPE_V2:{message:"Device type must be msft-acs-mesh-deviceType-v2 to join immersive call",code:400,subCode:40207,resultCategories:["ExpectedError"]},STACK_NOT_INIT:{message:"Failed to start or join call, call stack did not initialize",code:500,subCode:40208,resultCategories:["UnexpectedClientError"]},INVALID_JOIN_LOCATOR:{message:"Invalid join locator specified.",code:400,subCode:40209,resultCategories:["ExpectedError"]},INVALID_MEETING_LINK:{message:"The provided Teams meeting link is invalid.",code:400,subCode:40210,resultCategories:["ExpectedError"]},INVALID_TFL_MEETING_LINK:{message:"The provided Teams For Life meeting link is invalid.",code:400,subCode:40211,resultCategories:["ExpectedError"]},GROUPCALL_THREADID:{message:"Starting a group call must include thread ID in StartTeamsGroupCallOptions.",code:400,subCode:40212,resultCategories:["ExpectedError"]},ONE_TO_ONE_THREADID:{message:"Starting a one to one with thread ID is invalid.",code:400,subCode:40213,resultCategories:["ExpectedError"]},CTE_DISPLAY_NAME:{message:"Display name is not allowed to be set for Teams users.",code:400,subCode:40214,resultCategories:["ExpectedError"]},DISPLAY_NAME_TOO_LONG:{message:"Display name is too long.",code:400,subCode:40215,resultCategories:["ExpectedError"]},INIT_FAIL:{message:"Failed to create CallAgent. Please try again, if issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:40216,resultCategories:["UnexpectedClientError"]},GET_TOKEN_BEFORE_INIT:{message:"Attempted to get AccessToken before initialization",code:422,subCode:40217,resultCategories:["UnexpectedClientError"]},INVALID_PUSH_NOTIFICAITON_DATA:{message:"Invalid push notification data provided. No 'incomingCallContext' key found in the PushNotificatitonData.",code:400,subCode:40218,resultCategories:["ExpectedError"]},PUSH_NOTIFICAITON_FAIL:{message:"Failed to handle push notification",code:500,subCode:40219,resultCategories:["UnexpectedClientError"]},INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS:{message:"Incoming Call push notification payload provided has too many keys. Only 'incomingCallContext' key is expected in the PushNotificatitonData.",code:400,subCode:40220,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED:{message:"Invalid push notification data provided. No 'incomingCallContext' key found in the PushNotificatitonData.",code:400,subCode:40221,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD:{message:"The decoded 'incomingCallContext' data is invalid.",code:400,subCode:40222,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED:{message:"Incoming Call is already being processed",code:400,subCode:40223,resultCategories:["ExpectedError"]},INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS:{message:"Failed to handle Incoming Call push notification",code:500,subCode:40224,resultCategories:["UnexpectedClientError"]},INCOMING_PUSH_NOTIFICATION_CALL_MISSED:{message:"Missed call",code:400,subCode:40225,resultCategories:["ExpectedError"]},USERIDS_MUST_BE_OBJECTS:{message:"AssertIsObject failed. : userIds must be object",code:400,subCode:40226,resultCategories:["ExpectedError"]},USERIDS_CANNOT_BE_NULL:{message:"AssertNotNull failed. : userIds cannot be null",code:400,subCode:40227,resultCategories:["ExpectedError"]},ACS_CALLAGENT_ALREADY_EXSISTS:{message:"Failed to create CallAgent, an instance of CallAgent associated with this identity already exists. Please dispose the existing CallAgent, or create a new one with a different identity.",code:409,subCode:40228,resultCategories:["ExpectedError"]},ACS_CALLAGENT_TOKEN_ONLY:{message:"CallAgent must be created only with ACS token",code:403,subCode:40229,resultCategories:["ExpectedError"]},TEAMS_CALLAGENT_ALREADY_EXSISTS:{message:"Failed to create TeamsCallAgent, an instance of TeamsCallAgent associated with this identity already exists. Please dispose the existing TeamsCallAgent before creating a new one.",code:409,subCode:40230,resultCategories:["ExpectedError"]},TEAMS_CALLAGENT_TOKEN_ONLY:{message:"TeamsCallAgent must be created only with Teams token",code:403,subCode:40231,resultCategories:["ExpectedError"]},FAILED_TO_GET_TOKEN:{message:"Failed to get token",code:409,subCode:40232,resultCategories:["UnexpectedClientError"]},REFRESHED_TOKEN_INVALID_USERID:{message:"Refreshed AccessToken User Id doesnt match initial User Id.",code:400,subCode:40233,resultCategories:["ExpectedError"]},REFRESHED_TOKEN_RETRIES:{message:"Access token is expired and failed to fetch a valid one after retries.",code:400,subCode:40234,resultCategories:["ExpectedError"]},ACCESSTOKEN_EXPIRED:{message:"AccessToken expired",code:401,subCode:40235,resultCategories:["ExpectedError"]},ACTION_BLOCKED:{message:"Action not allowed.",code:403,subCode:40236,resultCategories:["ExpectedError"]},HANGUP_FAILED:{message:"Failed to hangup call",code:500,subCode:40237,resultCategories:["UnexpectedServerError"]}},DEVICE_MANAGER:{GET_MEDIA_STREAM_TRACK:{message:"Failed to get raw device stream track",code:500,subCode:40600,resultCategories:["UnexpectedClientError"]},GET_MEDIA_STREAM_DEVICE_UNAVAILABLE:{message:"Failed to get raw device stream track, make sure there is available device",code:412,subCode:40601,resultCategories:["UnexpectedClientError"]},GET_DM:{message:"Failed to get device manager.",code:500,subCode:40602,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to DeviceManager event, unknown event name.",code:422,subCode:40603,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from DeviceManager event, unknown event name.",code:422,subCode:40604,resultCategories:["ExpectedError"]},ACCESS_DM:{message:"Unable to access device manager",code:500,subCode:40605,resultCategories:["UnexpectedClientError"]},SPEAKER_ENUMERATION_UNSUPPORTED:{message:"Failed to enumerate speakers, it is not supported to enumerate/select speakers on Android Chrome, iOS Safari, nor MacOS Safari.",code:405,subCode:40606,resultCategories:["ExpectedError"]},SELECT_MICROPHONE_TIMEOUT:{message:"Microphone selection timed out.",code:408,subCode:40607,resultCategories:["UnexpectedClientError"]},SELECT_MICROPHONE_FAIL:{message:"There was an issue with selecting the microphone",code:500,subCode:40608,resultCategories:["UnexpectedClientError"]},SELECT_SPEAKER_TIMEOUT:{message:"Speaker selection timed out.",code:408,subCode:40609,resultCategories:["UnexpectedClientError"]},SELECT_SPEAKER_FAIL:{message:"There was an issue with selecting the speaker",code:500,subCode:40610,resultCategories:["UnexpectedClientError"]},SPEAKER_SELECTION_UNSUPPORTED:{message:"This device does not support speaker selection.",code:405,subCode:40611,resultCategories:["ExpectedError"]},ONE_PERMISSION_ATLEAST:{message:"At least one permission must be requested",code:400,subCode:40612,resultCategories:["ExpectedError"]},PERMISSION_NOT_GRANTED_OR_FAILED:{message:"Failed to obtain permission to use microphone and/or camera, it was denied or it failed. Please ensure to allow the permissions in the browser's setttings and in the OS setttings.",code:400,subCode:40613,resultCategories:["ExpectedError"]},ADP_FAIL:{message:"Failed to ask for device permissions Please ensure to allow the permissions in the browser's setttings and in the OS setttings and try again. If issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:40614,resultCategories:["UnexpectedClientError"]},INVALID_DEVICE:{message:"Invalid AudioDeviceInfo object passed in. Ensure it has an Id.",code:400,subCode:40615,resultCategories:["ExpectedError"]},DEVICE_NOT_SELECTABLE:{message:"The device is not selectable",code:400,subCode:40616,resultCategories:["ExpectedError"]}},CALL:{OPERATION_NOT_ALLOWED_DURING_EMERGENCY_CALL:{message:"Attempted invalid operation during Emergency Call.",code:500,subCode:41e3,resultCategories:["ExpectedError"]},OPERATION_FAILED:{message:"{0} failed",code:500,subCode:41001,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED:{message:"Unable to get remote audio stream, getMediaStream returned undefined",code:500,subCode:41002,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR:{message:"Unable to get remote audio stream, getMediaStream returned error",code:500,subCode:41003,resultCategories:["UnexpectedClientError"]},REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED:{message:"Getting raw audio media stream is currently disabled by Azure Communication Services.",code:409,subCode:41004,resultCategories:["ExpectedError"]},ACCEPT_INCOMING_CALL:{message:"Failed to accept the Incoming Call",code:500,subCode:41005,resultCategories:["UnexpectedClientError"]},ACCEPT_NOT_RINGING:{message:"Failed to accept the incoming call, it is not in the Ringing state. Subcscribe to CallAgent's 'incomingCall' event to accept the incoming call.",code:400,subCode:41006,resultCategories:["ExpectedError"]},REJECT_NOT_RINGING:{message:"Failed to reject the incoming call, it is not in the Ringing state. Subcscribe to CallAgent's 'incomingCall' event to reject the incoming call.",code:400,subCode:41007,resultCategories:["ExpectedError"]},LOCAL_AUDIO_GET_MEDIA_STREAM:{message:"Failed to get raw stream from local audio stream",code:500,subCode:41008,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_SET_MEDIA_STREAM:{message:"Failed to set raw input audio stream",code:500,subCode:41009,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_UNSET_MEDIA_STREAM:{message:"Failed to unset raw input audio stream",code:500,subCode:41010,resultCategories:["UnexpectedClientError"]},LOCAL_AUDIO_UNDEFINED_STACK:{message:"Failed to process audio because the calling stack is undefined. Please collect browser console logs and contact Azure Communication Services support.",code:500,subCode:41011,resultCategories:["UnexpectedClientError"]},REMOVE_LOCAL_VIDEO_ON_BAD_UFD:{message:"Removing local video stream due to video fail UFD being raised before call connected. Please ensure to allow video permissions in the browser's setttings and in the OS setttings, and ensure the camera device is not being used by another process.",code:409,subCode:41012,resultCategories:["UnexpectedClientError"]},STOP_AUDIO_ON_BAD_UFD:{message:"Failed to stop audio on microphone device not functioning or capture mute event {0} with value {1}",code:400,subCode:41013,resultCategories:["UnexpectedClientError"]},INSTANTIATE_CALL:{message:"Failed to instantiate the Call",code:500,subCode:41014,resultCategories:["UnexpectedClientError"]},MIC_MUTE:{message:"Failed to mute microphone. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41015,resultCategories:["UnexpectedClientError"]},MIC_UNMUTE:{message:"Failed to unmute microphone. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:400,subCode:41016,resultCategories:["UnexpectedClientError"]},MIC_UNMUTE_AND_STARTAUDIO:{message:"Failed to recover the microphone audio after bad microphone UFD recovered. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:410,subCode:41017,resultCategories:["UnexpectedClientError"]},MUTE_ALL_PARTICIPANTS_DISABLED:{message:"Mute other participants is currently disabled by ACS service.",code:403,subCode:41018,resultCategories:["ExpectedError"]},MUTE_ALL_PARTICIPANTS:{message:"Failed to mute all remote participants",code:500,subCode:41019,resultCategories:["UnexpectedClientError"]},MUTE_INCOMING_AUDIO:{message:"Failed to mute incoming audio",code:500,subCode:41020,resultCategories:["UnexpectedClientError"]},UNMUTE_INCOMING_AUDIO:{message:"Failed to unmute incoming audio",code:500,subCode:41021,resultCategories:["UnexpectedClientError"]},DTMF_TONE:{message:"Failed to send DTMF tone",code:400,subCode:41022,resultCategories:["UnexpectedClientError"]},INVALID_DTMF_TONE:{message:"Invalid value passed to DtfmTone",code:422,subCode:41023,resultCategories:["ExpectedError"]},START_AUDIO_BEFORE_VIDEO:{message:"Failed to start audio before starting video",code:500,subCode:41024,resultCategories:["UnexpectedClientError"]},STREAM_NULL:{message:"Failed to start video, LocalVideoStream instance is invalid or empty. Please pass in a LocalVideoStream instance.",code:400,subCode:41025,resultCategories:["ExpectedError"]},STREAM_IS_NOT_LVS:{message:"Failed to start video, localVideoStream is not an instance of LocalVideoStream",code:400,subCode:41026,resultCategories:["ExpectedError"]},VIDEO_ALREADY_ON:{message:"Failed to start video, video is already started.",code:400,subCode:41027,resultCategories:["ExpectedError"]},VIDEO_SET_MEDIA_STREAM:{message:"Failed to set media stream",code:500,subCode:41028,resultCategories:["UnexpectedClientError"]},START_VIDEO:{message:"Failed to start video",code:500,subCode:41029,resultCategories:["UnexpectedClientError"]},VIDEO_ALREADY_OFF:{message:"Failed to stop video, video is already stopped.",code:400,subCode:41030,resultCategories:["ExpectedError"]},VIDEO_UNDEFINED_STACK:{message:"Failed to start video because the calling stack is undefined. Please gether browser console logs, .HAR files, and contact Aure Communication Services support.",code:500,subCode:41031,resultCategories:["UnexpectedClientError"]},STOP_WRONG_STREAM:{message:"Failed to stop video, invalid argument. LocalVideoStream used as an input is currently not being sent.",code:400,subCode:41032,resultCategories:["ExpectedError"]},HOLD_CALL:{message:"Failed to hold the call. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41033,resultCategories:["UnexpectedClientError"]},RESUME_CALL:{message:"Failed to resume the call.Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41034,resultCategories:["UnexpectedClientError"]},SS_ALREADY_ON:{message:"Failed to start screen share, screen share is already started.",code:400,subCode:41035,resultCategories:["ExpectedError"]},SS_RAW_STREAM_IS_NOT_LVS:{message:"Failed to start raw screen sharing, localVideoStream is not an instance of LocalVideoStream",code:400,subCode:41036,resultCategories:["ExpectedError"]},SS_RAW_STREAM_UNDEFINED:{message:"Unable to get media stream from local video stream for raw media screen sharing. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41037,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_SET:{message:"Failed to set raw media stream for screen sharing. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:422,subCode:41038,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_GET:{message:"Failed to get raw screen sharing stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:422,subCode:41039,resultCategories:["UnexpectedClientError"]},START_SS:{message:"Failed to start screen sharing",code:500,subCode:41040,resultCategories:["UnexpectedClientError"]},SS_ALREADY_OFF:{message:"Failed to stop screen share, screen share is already stopped.",code:400,subCode:41041,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to Call event, unknown event name.",code:422,subCode:41042,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Call event, unknown event name.",code:422,subCode:41043,resultCategories:["ExpectedError"]},ONLY_SINGLE_VIDEO_STREAM:{message:"Only single LocalVideoStream is supported currently",code:400,subCode:41044,resultCategories:["ExpectedError"]},NOT_INSTANCE_OF_LVS:{message:"Stream is not an instance of LocalVideoStream",code:400,subCode:41045,resultCategories:["ExpectedError"]},ONLY_SINGLE_AUDIO_STREAM:{message:"Only single LocalAudioStream is supported currently",code:400,subCode:41046,resultCategories:["ExpectedError"]},NOT_INSTANCE_OF_LAS:{message:"Stream is not an instance of LocalAudioStream",code:400,subCode:41047,resultCategories:["ExpectedError"]},VIDEO_FAILED_TO_START:{message:"Failed to start video during call setup process. Please ensure to allow video permissions in the browser's setttings and in the OS setttings, and ensure the camera device is not being used by another process.",code:410,subCode:41048,resultCategories:["UnexpectedClientError"]},AUDIO_FAILED_TO_START:{message:"Failed to start audio during call setup process. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:400,subCode:41049,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_FORCE_ISAVAILABLE:{message:"Failed to force isAvailable flag to false during large meeting",code:500,subCode:41050,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_DISPOSE_VIEW:{message:"Failed to dispose view in large meeting",code:500,subCode:41051,resultCategories:["UnexpectedClientError"]},ADD_UNKNOWN:{message:"Not able to add unkown participant.",code:400,subCode:41052,resultCategories:["ExpectedError"]},PARTICIPANT_ALREADY_IN_CALL:{message:"{0} is already in the call",code:400,subCode:41053,resultCategories:["ExpectedError"]},PARTICIPANT_NOT_IN_CALL:{message:"Failed to remove the specified participant. The participant is not in the call.",code:400,subCode:41054,resultCategories:["ExpectedError"]},CTE_ADDPARTICIPANT_NO_THREAD_ID:{message:"Add participant failed: thread ID is missing in options.",code:400,subCode:41055,resultCategories:["ExpectedError"]},CTE_VOICE_NOT_ENABLED:{message:"Failed to start or join to the call, Teams Enterprise voice policy is not enabled for this Azure Communication Services resource. Follow the tutorial online to enable it.",code:412,subCode:41056,resultCategories:["ExpectedError"]},SERVER_CALL_ID:{message:"Failed to get server call Id",code:500,subCode:41057,resultCategories:["UnexpectedClientError"]},VOLUME_TRACK:{message:"Failed to get the MediaStream to initialize the Volume indicator. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41058,resultCategories:["UnexpectedClientError"]},VOLUME_INIT:{message:"Failed to setup volume calcualtor using AudioContext, please retry getVolumeindicator on a working audio stream with exponential backoff",code:500,subCode:41059,resultCategories:["UnexpectedClientError"]},VOLUME_EVENT_SUBSCRIBE:{message:"Not able to subscribe to Volume Indicator event, unknown event name.",code:400,subCode:41060,resultCategories:["ExpectedError"]},VOLUME_EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Volume Indicator event, unknown event name.",code:400,subCode:41061,resultCategories:["ExpectedError"]},VOLUME_GET:{message:"Failed to setup volume calculator, please retry after exponential backoff",code:500,subCode:41062,resultCategories:["UnexpectedClientError"]},GET_SERVER_CALL_ID:{message:"Failed to get serverCallId, serverCallId is empty",code:404,subCode:41063,resultCategories:["UnexpectedClientError"]},MEDIA_CONSTRAINTS_DISABLED:{message:"Setting call constraint is currently disabled by ACS service.",code:409,subCode:41064,resultCategories:["ExpectedError"]},SET_CONSTRAINTS_START_OR_ACCEPT:{message:"Error setting call constraints at call setup. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41065,resultCategories:["UnexpectedClientError"]},SET_CONSTRAINTS_MID_CALL:{message:"Error setting call constraints during mid-call",code:500,subCode:41066,resultCategories:["UnexpectedClientError"]},SET_CONSTRAINTS:{message:"Error settting video constraints during call settup or mid-call. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:41067,resultCategories:["UnexpectedClientError"]},ACCEPT_VIDEO_CONSTRAINTS:{message:"Error setting video constraints during call accept",code:500,subCode:41068,resultCategories:["UnexpectedClientError"]},CALLSTART_VIDEO_CONSTRAINTS:{message:"Error setting video constraints during call start",code:500,subCode:41069,resultCategories:["UnexpectedClientError"]},SET_VIDEO_CONSTRAINTS:{message:"Failed to set call constraints during mid call",code:500,subCode:41070,resultCategories:["UnexpectedClientError"]},START_SS_CALL_NOT_CONNECTED:{message:"Failed to start screen share, call is not in Connected state. Subscribe to the Call's 'statteChanged' event to know when the call is connected.",code:412,subCode:41071,resultCategories:["ExpectedError"]},STOP_SS_CALL_NOT_CONNECTED:{message:"Failed to stop screen sharing. Call must be in connected state",code:412,subCode:41072,resultCategories:["ExpectedError"]},ACCESS_RAW_MEDIA_STREAM_DISABLED:{message:"Failed to get or set custom MediaStream, this functionality is currently disabled by Azure Communication Services.",code:412,subCode:41073,resultCategories:["ExpectedError"]},ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC:{message:"The raw media stream function is currently not available",code:500,subCode:41074,resultCategories:["UnexpectedClientError"]},SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA:{message:"Failed to start raw screen sharing, localVideoStream doesn't contain a raw media stream",code:400,subCode:41075,resultCategories:["ExpectedError"]},START_AUDIO_STREAM_FAILED:{message:"Failed to start audio stream",code:500,subCode:41076,resultCategories:["UnexpectedClientError"]},STOP_VIDEO_FAILED:{message:"Failed to stop video",code:500,subCode:41077,resultCategories:["UnexpectedClientError"]},INCOMING_CALL_ALREADY_UNPLACED:{message:"Incoming call is already unplaced",code:400,subCode:41078,resultCategories:["ExpectedError"]},REJECT_CALL_FAILED:{message:"Failed to reject call",code:500,subCode:41079,resultCategories:["UnexpectedServerError"]},START_AUDIO_FAIL_TO_START_LOCAL_DEVICE:{message:"Failed to start local audio device",code:400,subCode:41080,resultCategories:["UnexpectedClientError"]},START_AUDIO_SELECT_VIRTUAL_DEVICE:{message:"Failed to Select Virtual Device.",code:400,subCode:41081,resultCategories:["UnexpectedClientError"]},START_AUDIO_UNSELECT_VIRTUAL_DEVICE:{message:"Failed to Unselect Virtual Device.",code:400,subCode:41082,resultCategories:["UnexpectedClientError"]},START_AUDIO_LAS_NOT_RAW_MEDIA:{message:"Failed to start raw audio, localAudioStream doesn't contain a raw media stream. To start raw audio, the LocalAudioStream passed in, must be constructed with a MediaStream object.",code:400,subCode:41083,resultCategories:["ExpectedError"]},STOP_AUDIO_LAS_NOT_RAW_MEDIA:{message:"Failed to stop raw audio, localAudioStream doesn't contain a raw media stream. To stop raw audio, the current LocalAudioStream in the call must have a MediaStream as the source.",code:400,subCode:41084,resultCategories:["ExpectedError"]},TEAMS_INVALID_THREAD_ID:{message:"Thread ID is invalid.",code:400,subCode:41085,resultCategories:["ExpectedError"]}},LOBBY:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to Lobby event, unknown event name.",code:422,subCode:41800,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Lobby event, unknown event name.",code:422,subCode:41801,resultCategories:["ExpectedError"]},CONV_UNSUPPORTED:{message:"Current conversation type doesn't support lobby admit and reject",code:400,subCode:41802,resultCategories:["ExpectedError"]},ALREADY_IN_MEETING:{message:"Participant is already in the meeting.",code:400,subCode:41803,resultCategories:["ExpectedError"]},NOT_IN_LOBBY:{message:"Participant is not in the lobby.",code:400,subCode:41804,resultCategories:["ExpectedError"]},UNAUTHORIZED_ADMIT_REJECT:{message:"only Organizer, Co-organizer or Presenter can admit/reject participants from lobby",code:403,subCode:41805,resultCategories:["ExpectedError"]},ADMIT_FAILED:{message:"Failed to admit participants in the lobby",code:500,subCode:41806,resultCategories:["UnexpectedServerError"]},EMPTY_PARTICIPANT_LIST:{message:"Participant list is empty",code:400,subCode:41807,resultCategories:["ExpectedError"]},LOBBY_NOT_ENABLED:{message:"Lobby is not enabled for this meeting",code:400,subCode:41808,resultCategories:["ExpectedError"]},REJECT_FAILED:{message:"Failed to reject participants from the lobby",code:500,subCode:41809,resultCategories:["UnexpectedServerError"]}},CTE_MID_TIER_POLICY_SERVICE:{TEAMS_USER_ID_NOT_PROVIDED:{message:"Failed to fetch Teams user policies and settings cannot proceed, because teams user Id was not found in the AccessToken.",code:400,subCode:41900,resultCategories:["ExpectedError"]},FETCH_POLICY:{message:"Error Fetching Teams user policy from ACS MiddleTier Service",code:500,subCode:41901,resultCategories:["UnexpectedServerError"]},DERIVE_EMERGENCY_POLICY:{message:"Unable to derive emergency policy from ACS MiddleTier Service response",code:500,subCode:41902,resultCategories:["UnexpectedServerError"]},TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED:{message:"Unable to fetch Teams calling policy from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41903,resultCategories:["UnexpectedServerError"]},TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED:{message:"Unable to fetch Teams meeting policy from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41904,resultCategories:["UnexpectedServerError"]},TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED:{message:"Unable to fetch feature types from ACS MiddleTier Service response. Please try again, if the issue persists, gather browser console logs, .HAR file, and contact Azure Communication Services support.",code:500,subCode:41905,resultCategories:["UnexpectedServerError"]},CREATETHREAD_FAILED:{message:"Unable to create thread for the Teams User groupcall from ACS MiddleTier Service response",code:500,subCode:41906,resultCategories:["UnexpectedServerError"]},ADD_PARTICIPANTS_TO_THREAD_FAILED:{message:"Unable to add particpant for the thread for Teams groupcall from ACS MiddleTier Service",code:500,subCode:41907,resultCategories:["UnexpectedServerError"]}},REMOTE_PARTICIPANT:{MUTE_PARTICIPANT_DISABLED:{message:"Mute other participants is disabled by ACS service.",code:403,subCode:42e3,resultCategories:["ExpectedError"]},MUTE_PARTICIPANT_FAILED:{message:"Failed to mute specific participant",code:500,subCode:42001,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to RemoteParticipant event, unknown event name.",code:422,subCode:42002,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from RemoteParticipant event, unknown event name.",code:422,subCode:42003,resultCategories:["ExpectedError"]}},LOCAL_VIDEO_STREAM:{SOURCE_UNAVAILABLE:{message:"Failed to start video, video device is being used by another process/application. Stop your camera from being used in the other process/application and try again.",code:412,subCode:43e3,resultCategories:["ExpectedError"]},PERMISSION_DENIED:{message:"Failed to start video, permission was not granted to use selected video device. Ensure video device permissions are allowed in the browser's settings and in the system's setttings.",code:403,subCode:43001,resultCategories:["ExpectedError"]},UNKNOWN:{message:"Failed to start video, unknown error. Please try again. If the issue persists, contact Azure Communication Services support.",code:500,subCode:43002,resultCategories:["UnexpectedClientError"]},WRONG_STREAM_TYPE:{message:"Failed to create local video stream, source was not of type VideoDeviceInfo or MediaStream",code:400,subCode:43003,resultCategories:["ExpectedError"]},SWITCH_SOURCE_WRONG_TYPE:{message:"Failed to switch video device, invalid input. Input must be of a VideoDeviceInfo type.",code:400,subCode:43004,resultCategories:["ExpectedError"]},SWITCH_SAME_SOURCE:{message:"Failed to switch video device, unable to switch to the same video device, it's already selected.",code:400,subCode:43005,resultCategories:["ExpectedError"]},CANT_GET_DEVICE_TYPE:{message:"Unable to get device type",code:500,subCode:43006,resultCategories:["UnexpectedClientError"]},VIDEO_GET_MEDIA_STREAM:{message:"Failed to get raw video stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43007,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM_WRONG_TYPE:{message:"Failed to set media stream source is not MediaStream",code:400,subCode:43008,resultCategories:["ExpectedError"]},SET_MEDIA_STREAM_UNDEFINED_FUNC:{message:"Failed to set raw video stream. Found undefined function. Gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43009,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM:{message:"Failed to set raw video stream. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43010,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalVideoStream event, unknown event name.",code:422,subCode:43011,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalVideoStream event, unknown event name.",code:422,subCode:43012,resultCategories:["ExpectedError"]},DEVICES_NOT_FOUND:{message:"Failed to start video, no video devices found. Ensure video devices are plugged in and enabled in the system settings.",code:412,subCode:43013,resultCategories:["ExpectedError"]},MEDIA_STREAM_REQUEST_ERROR:{message:"Failed to start video, error requesting media stream. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43014,resultCategories:["UnexpectedClientError"]},MEDIA_STREAM_REQUEST_TIMEDOUT:{message:"Failed to start video, media stream request timed out. PLease allow permission on the browser's prompt to access the camera and try again.",code:412,subCode:43015,resultCategories:["ExpectedError"]},PERMISSION_DENIED_BY_SYSTEM:{message:"Failed to start video, permissions denied by system. Ensure video device permissions are allowed in the browser's settings and in the system's setttings.",code:412,subCode:43016,resultCategories:["ExpectedError"]},UNSUPPORTED_STREAM:{message:"Failed to start video, unsupported stream. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43017,resultCategories:["UnexpectedClientError"]},CONSTRAINT_NOT_SATISFIED:{message:"Failed to start video, failed to set constraints. Please try again, if issue persists, contact Azure Communication Services support.",code:412,subCode:43018,resultCategories:["UnexpectedClientError"]},NO_DEVICE_SELECTED:{message:"Failed to start video, no device selected. Please ensure to pass a LocalVideoStream constructed with a VideoDeviceInfo and try again. If issue persists, contact Azure Communication Services support.",code:412,subCode:43019,resultCategories:["UnexpectedClientError"]}},REMOTE_VIDEO_STREAM:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to RemoteVideoStream event, unknown event name.",code:422,subCode:43100,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from RemoteVideoStream event, unknown event name.",code:422,subCode:43101,resultCategories:["ExpectedError"]},GET_RAW_MEDIA_STREAM:{message:"Not able to get media stream",code:500,subCode:43102,resultCategories:["UnexpectedClientError"]},RAWMEDIA_LVS_NOT_AVAILABLE:{message:"The remote video stream is currently not available, subscribe to the stream's isAvailable property to get notified when it is ready to get the raw media stream.",code:400,subCode:43103,resultCategories:["ExpectedError"]},SUBSCRIBE_MEDIA_STREAM_TIMEOUT:{message:"Failed to subscribe to media stream, timeout",code:408,subCode:43104,resultCategories:["UnexpectedClientError"]},GET_TRACK:{message:"Failed to get media stream",code:500,subCode:43105,resultCategories:["UnexpectedClientError"]},TRACK_UNMUTED_TIMEOUT:{message:"Failed to subscribe to media stream, muted",code:408,subCode:43106,resultCategories:["UnexpectedClientError"]},GET_MEDIA_STREAM:{message:"Failed to get raw media stream",code:500,subCode:43107,resultCategories:["UnexpectedClientError"]}},VIEW:{ISAVAILABLE_FALSE:{message:"Failed to render video stream, this stream is not available. Subscribe to the stream's isAvailable property to get notified when the remote participant has their video on and the stream is available for rendering.",code:412,subCode:43200,resultCategories:["ExpectedError"]},START_ALREADY_DISPOSED:{message:"Failed to start stream, already disposed",code:405,subCode:43201,resultCategories:["ExpectedError"]},STREAM_BECAME_UNAVAILABLE:{message:"Failed to render video stream, this stream is not longer available. Remote participant turned their video off.",code:404,subCode:43202,resultCategories:["ExpectedError"]},TIMEOUT:{message:"Failed to render video stream, rendering timed out while waiting for video frames. Please try again, if issue persists, contact Azure Communication Services support.",code:408,subCode:43203,resultCategories:["UnexpectedClientError"]},SUBSCRIBE:{message:"Failed to render video stream, failed to subscribe to video on the Azure Communication Services infrastructure. Please try again, if issue persists, contact Azure Communication Services support.",code:500,subCode:43204,resultCategories:["UnexpectedClientError"]},START:{message:"Failed to start stream, internal error",code:500,subCode:43205,resultCategories:["UnexpectedClientError"]},SCALING_MODE:{message:"Failed to updateScalingMode, failed to update",code:500,subCode:43206,resultCategories:["UnexpectedClientError"]},LARGE_MEETING_VIEW_DISPOSED:{message:"Failed to start stream, disposing stream because participant is not a dominant speaker in the large meeting",code:405,subCode:43207,resultCategories:["ExpectedError"]},REMOTE_VIDEO_STREAM_DISPOSED:{message:"Failed to start stream, disposing stream because remote video stream is disposing",code:405,subCode:43208,resultCategories:["ExpectedError"]},APP_VIEW_DISPOSED:{message:"Failed to render video stream, VideoStreamRenderer was disposed during initialization process.",code:405,subCode:43209,resultCategories:["ExpectedError"]},RENDERER_DISPOSE_ALREADY_DISPOSED:{message:"Failed to dispose VideoStreamRenderer, it is already disposed.",code:400,subCode:43210,resultCategories:["ExpectedError"]},REMOTE_RENDERER_DISPOSE_FAIL:{message:"Failed to dispose remote renderer",code:500,subCode:43211,resultCategories:["UnexpectedClientError"]},VIEW_WRONG_STREAM_TYPE:{message:"Failed to create VideoStreamRendererView, videoStream must be either LocalVideoStream or RemoteVideoStream type",code:400,subCode:43212,resultCategories:["ExpectedError"]},VIEW_ALREADY_DISPOSED:{message:"Failed to dispose, VideoStreamRendererView is disposed",code:400,subCode:43213,resultCategories:["ExpectedError"]},RENDER_FAIL_STREAM_DISPOSED:{message:"Failed to render, stream disposed",code:400,subCode:43214,resultCategories:["ExpectedError"]},SCALING_MODE_DISPOSED:{message:"Failed to updateScalingMode, VideoStreamRendererView is disposed",code:400,subCode:43215,resultCategories:["ExpectedError"]},SCALING_MODE_WRONG_VAL:{message:"Failed to updateScalingMode, wrong scalingMode value",code:400,subCode:43216,resultCategories:["ExpectedError"]},DISPOSE_FAIL:{message:"Failed to dispose view",code:500,subCode:43217,resultCategories:["UnexpectedClientError"]},RENDERER_WRONG_STREAM_TYPE:{message:"Failed to create VideoStreamRenderer, videoStream must be either LocalVideoStream or RemoteVideoStreamCommon type",code:400,subCode:43218,resultCategories:["ExpectedError"]},RENDERER_DISPOSED:{message:"Failed to create view, VideoStreamRenderer is disposed",code:400,subCode:43219,resultCategories:["ExpectedError"]},MAX_NUM_OF_VIEWS_REACHED:{message:"Failed to create view, maximum number of active RemoteVideoStream views has been reached. You can dispose of a previous one in order to create new one.",code:400,subCode:43220,resultCategories:["ExpectedError"]},CREATE_VIEW_FAILED:{message:"Failed to create view",code:500,subCode:43221,resultCategories:["UnexpectedClientError"]},RENDERER_ALREADY_DISPOSED:{message:"Failed to dispose, VideoStreamRendererView is already disposed",code:400,subCode:43222,resultCategories:["ExpectedError"]},UNKNOWN_STREAM_TYPE:{message:"Unknown stream type",code:400,subCode:43223,resultCategories:["ExpectedError"]},LOCAL_RENDERER_DISPOSE_FAIL:{message:"Failed to dispose local renderer",code:500,subCode:43224,resultCategories:["UnexpectedClientError"]}},LOCAL_AUDIO_STREAM:{WRONG_STREAM_TYPE:{message:"Failed to create local audio stream, source is not of type AudioDeviceInfo or MediaStream",code:400,subCode:43600,resultCategories:["ExpectedError"]},SOURCE_WRONG_TYPE:{message:"Failed to create local audio stream, source is not a microphone",code:400,subCode:43601,resultCategories:["ExpectedError"]},GET_MEDIA_STREAM:{message:"Failed to get media stream source is not AudioDeviceInfo or MediaStream",code:500,subCode:43602,resultCategories:["UnexpectedClientError"]},SET_MEDIA_STREAM_WRONG_TYPE:{message:"Failed to switch stream on local audio, source is not of type MediaStream",code:400,subCode:43603,resultCategories:["ExpectedError"]},SWITCH_SOURCE_WRONG_TYPE:{message:"Failed to create local audio stream, source is not a microphone",code:400,subCode:43604,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalAudioStream event, unknown event name.",code:422,subCode:43605,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalAudioStream event, unknown event name.",code:422,subCode:43606,resultCategories:["ExpectedError"]},SWITCH_SAME_SOURCE:{message:"Failed to switch audio device, unable to switch to the same audio device, it's already selected.",code:400,subCode:43607,resultCategories:["ExpectedError"]},UNKNOWN:{message:"Failed to start audio, unknown error. Please try again. If the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:43608,resultCategories:["UnexpectedClientError"]}},REMOTE_AUDIO_STREAM:{},IDENTIFIER:{PARSE_PHONENUMBER:{message:"Unable to parse PhoneNumberIdentifier object",code:422,subCode:44e3,resultCategories:["ExpectedError"]},PARSE_MSFT_TEAMS_USER:{message:"Unable to parse MicrosoftTeamsUserIdentifier object",code:422,subCode:44001,resultCategories:["ExpectedError"]},PARSE_MSFT_TEAMS_APP:{message:"Unable to parse MicrosoftTeamsAppIdentifier object",code:422,subCode:44002,resultCategories:["ExpectedError"]},PARSE_IDENTIFIER:{message:"Unable to parse Identifier object, please check the syntax",code:422,subCode:44003,resultCategories:["ExpectedError"]},INVALID_COMM_USER:{message:"Invalid CommunicationUser identifier specified",code:422,subCode:44004,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_USER_RAWID:{message:"Invalid MicrosoftTeamsUser rawId specified",code:422,subCode:44005,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_USER_USERID:{message:"Invalid MicrosoftTeamsUser microsoftTeamsUserId specified",code:422,subCode:44006,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_APP_RAWID:{message:"Invalid MicrosoftTeamsApp rawId specified",code:422,subCode:44007,resultCategories:["ExpectedError"]},INVALID_MSFT_TEAMS_APP_APPID:{message:"Invalid MicrosoftTeamsApp teamsAppId specified",code:422,subCode:44008,resultCategories:["ExpectedError"]},INVALID_UNKNOWN_IDENTIFIER:{message:"Invalid identifier specified, please specify an id",code:422,subCode:44009,resultCategories:["ExpectedError"]},PARSE_INVALID_IDENTIFIER:{message:"Unable to parse Identifier object",code:422,subCode:44010,resultCategories:["ExpectedError"]},INVALID_IDENTIFIER_ARRAY:{message:"AssertIsArrayOfIdentifiers failed. : userIds must be array of CommunicationIdentifier",code:422,subCode:44011,resultCategories:["ExpectedError"]},NO_CLOUD_PREFIX_FOUND:{message:"No cloud prefix found in identity",code:409,subCode:44012,resultCategories:["ExpectedError"]}},INTERNAL:{ECS_CONFIG_EMPTY:{message:"Config is empty",code:500,subCode:44100,resultCategories:["UnexpectedServerError"]},ECS_CONFIG_MISSING_ACS:{message:"Missing ACS config key",code:500,subCode:44101,resultCategories:["UnexpectedServerError"]},ECS_CONFIG_MERGING_ERROR:{message:"Error while merging config",code:500,subCode:44102,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE_INVALID_CLOUD_TYPE:{message:"Failed to initialize telemetry",code:500,subCode:44103,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE_ALREADY_INITIALIZED:{message:"Failed to initialize telemetry",code:500,subCode:44104,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_INITIALIZE:{message:"Failed to create and initialize telemetry logger for tenant. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:44105,resultCategories:["UnexpectedClientError"]},TELEMETRY_FAILED_TO_FLUSH:{message:"Failed to flush telemetry",code:500,subCode:44106,resultCategories:["UnexpectedClientError"]},TELEMETRY_LOGGER_INIT_FAIL:{message:"Failed to initialize telemetry logger",code:500,subCode:44107,resultCategories:["UnexpectedClientError"]},NO_TOKEN_PROVIDED:{message:"No CommunicationTokenCredential provided",code:401,subCode:44108,resultCategories:["ExpectedError"]},EMPTY_TOKEN:{message:"AccessToken is empty",code:401,subCode:44109,resultCategories:["ExpectedError"]},GET_TOKEN:{message:"Failed to get AccessToken",code:401,subCode:44110,resultCategories:["UnexpectedClientError"]},TOKEN_PAYLOAD_UNDEFINED:{message:"Invalid token",code:401,subCode:44111,resultCategories:["ExpectedError"]},TOKEN_UNDEFINED:{message:"Failed to parse AccessToken",code:401,subCode:44112,resultCategories:["ExpectedError"]},INVALID_TOKEN_SCOPE:{message:"AccessToken does not contain 'voip' or 'voip.join' scope",code:401,subCode:44113,resultCategories:["ExpectedError"]},INVALID_TOKEN_SCOPE_FORMAT:{message:"Wrong AccessToken scope format. Scope is expected to be a string that contains 'voip'",code:401,subCode:44114,resultCategories:["ExpectedError"]},RESOURCE_NOT_FOUND_IN_TOKEN:{message:"AccessToken does not contain ACS resource Id",code:401,subCode:44115,resultCategories:["ExpectedError"]},USERID_NOT_FOUND_IN_TOKEN:{message:"AccessToken does not contain ACS user Id",code:401,subCode:44116,resultCategories:["ExpectedError"]},PARSE_TOKEN_FAIL:{message:"Failed to parse AccessToken",code:401,subCode:44117,resultCategories:["UnexpectedClientError"]},OPERATION_TIMEDOUT:{message:"Operation timed out",code:408,subCode:44118,resultCategories:["UnexpectedClientError"]}},FEATURES:{AUDIO_EFFECTS:{SET_ECHO_CANCELLATION:{message:"Error while trying to start or stop echo cancellation. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45e3,resultCategories:["UnexpectedClientError"]},SET_NOISE_SUPPRESSION:{message:"Error while trying to start or stop noise suppression. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45001,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to AudioEffects event, unknown event name.",code:400,subCode:45002,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from AudioEffects event, unknown event name.",code:400,subCode:45003,resultCategories:["ExpectedError"]},DISABLED:{message:"Setting audio effects is currently disabled by Azure Communication Services.",code:403,subCode:45004,resultCategories:["ExpectedError"]},START_DISPOSED:{message:"Audio effects feature is disposed. Create a new AudioEffects feature instance.",code:400,subCode:45005,resultCategories:["ExpectedError"]},SOURCE_UNSUPPORTED:{message:"Current source is not supported",code:415,subCode:45006,resultCategories:["ExpectedError"]},START_DEVICE_MANAGER:{message:"Failed to get device manager to start effects.",code:500,subCode:45007,resultCategories:["UnexpectedClientError"]},STOP_DISPOSED:{message:"Audio effects feature is disposed. Create a new AudioEffects feature instance.",code:400,subCode:45008,resultCategories:["ExpectedError"]},STOP_DEVICE_MANAGER:{message:"Failed to get device manager to stop effects.",code:500,subCode:45009,resultCategories:["UnexpectedClientError"]},FAILED_TO_GET_DM:{message:"Internal error - DM missing",code:500,subCode:45010,resultCategories:["UnexpectedClientError"]},PROVIDER_UNAVAILABLE:{message:"EffectProvider not available",code:500,subCode:45011,resultCategories:["UnexpectedClientError"]},AEC_PROVIDER_MISSING:{message:"Internal error - stack aec provider missing",code:500,subCode:45012,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT:{message:"Invalid effect provided",code:400,subCode:45013,resultCategories:["ExpectedError"]},INVALID_EFFECT_ECHO:{message:"Invalid or no echo cancellation effect provided",code:400,subCode:45014,resultCategories:["ExpectedError"]},INVALID_EFFECT_NOISE_SUPP:{message:"Invalid or no noise suppression effect provided",code:400,subCode:45015,resultCategories:["ExpectedError"]},UNSUPPORTED_EFFECT:{message:"Unsupported effect specified. Please specify a supported audio effect.",code:415,subCode:45016,resultCategories:["UnexpectedClientError"]},SUPPORT_CHECK_FAILED:{message:"Error while checking support",code:501,subCode:45017,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT_GAINCONTROL:{message:"Invalid or no auto gain control effect provided",code:400,subCode:45018,resultCategories:["ExpectedError"]},SET_AUTO_GAIN_CONTROL:{message:"Error while trying to start or stop auto gain control. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45019,resultCategories:["UnexpectedClientError"]},AUDIO_FLAGS:{message:"Error setting browser audio processing flags",code:500,subCode:45020,resultCategories:["UnexpectedClientError"]},START_FAILED:{message:"Error starting audio effects.",code:500,subCode:45021,resultCategories:["UnexpectedClientError"]},STOP_FAILED:{message:"Error stopping audio effects.",code:500,subCode:45022,resultCategories:["UnexpectedClientError"]},DISPOSE_FAILED:{message:"Error disposing audio effects feature.",code:500,subCode:45023,resultCategories:["UnexpectedClientError"]}},AUDIO_ZONES:{},CALL_SURVEY:{INVALID_SURVEY:{message:"Invalid call survey. Please submit a survey options.",code:400,subCode:45100,resultCategories:["ExpectedError"]},SUBMIT_TIMEOUT:{message:"Failed to submit survery, timedout. Please try again, if issue persists, gather browser console logs and contact Azure Communication Services support.",code:408,subCode:45101,resultCategories:["UnexpectedClientError"]}},CAPABILITIES:{},CAPTIONS:{INITIALIZE:{message:"Failed to initialize Captions.",code:500,subCode:45200,resultCategories:["UnexpectedClientError"]},DISABLED:{message:"Captions feature is currently disabled by Azure Communication services.",code:412,subCode:45201,resultCategories:["ExpectedError"]},SPOKEN_LANG_UNSUPPORTED:{message:"Spoken language requested is not supported.",code:400,subCode:45202,resultCategories:["ExpectedError"]},MEETING_POLICY_DISABLED:{message:"Captions feature is disabled in meeting policy.",code:403,subCode:45203,resultCategories:["ExpectedError"]},CALLING_POLICY_DISABLED:{message:"Captions feature is disabled in calling policy.",code:403,subCode:45204,resultCategories:["ExpectedError"]},START_FAILED:{message:"Could not start captions.",code:500,subCode:45205,resultCategories:["UnexpectedClientError"]},UPDATE_LANGUAGE_NOT_STARTED:{message:"Cannot update spoken language as captions has not started.",code:400,subCode:45206,resultCategories:["ExpectedError"]},SPOKEN_LANG_DISABLED:{message:"Set spoken language is currently disabled by Azure Communication Services.",code:412,subCode:45207,resultCategories:["ExpectedError"]},UPDATE_LANGUAGE_GET_TOKEN:{message:"Unable to update spoken language. Failed to get token.",code:401,subCode:45208,resultCategories:["UnexpectedClientError"]},UPDATE_LANGUAGE_FAILED:{message:"Unable to update spoken language.",code:500,subCode:45209,resultCategories:["UnexpectedClientError"]},UPDATE_CAPTIONS_NOT_STARTED:{message:"Cannot update caption language as captions has not started.",code:400,subCode:45210,resultCategories:["ExpectedError"]},CAPTIONS_LANG_DISABLED:{message:"Set caption language is currently disabled by Azure Communication Services.",code:412,subCode:45211,resultCategories:["ExpectedError"]},CAPTIONS_LANG_TEAMS_LICENSE:{message:"Set caption language failed. Teams premium license is needed to use this feature.",code:401,subCode:45212,resultCategories:["ExpectedError"]},CAPTIONS_LANG_UNSUPPORTED:{message:"Caption language requested is not supported.",code:400,subCode:45213,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_GET_TOKEN:{message:"Null token",code:401,subCode:45214,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_FAILED:{message:"Unable to update caption language.",code:500,subCode:45215,resultCategories:["UnexpectedClientError"]},CTE_POLICY_FETCH_FAIL:{message:"Failed to fetch policy for Teams Captions.",code:500,subCode:45216,resultCategories:["UnexpectedClientError"]},ALREADY_ACTIVE:{message:"Captions already active",code:400,subCode:45217,resultCategories:["ExpectedError"]},STOP_NOT_ACTIVE:{message:"Captions feature is not active.",code:400,subCode:45218,resultCategories:["ExpectedError"]},ALREADY_STARTING:{message:"Operation in progress",code:400,subCode:45219,resultCategories:["ExpectedError"]},SPOKEN_LANGUAGE_ALREADY_SET:{message:"Spoken language already set",code:400,subCode:45220,resultCategories:["ExpectedError"]},UPDATE_CAPTIONS_NOT_ACTIVE:{message:"Unable to update caption language as Captions is not active.",code:400,subCode:45221,resultCategories:["ExpectedError"]},CAPTIONS_LANG_ALREADY_SET:{message:"Caption language already set.",code:400,subCode:45222,resultCategories:["ExpectedError"]},CAPTIONS_STATUS_ALREADY_SET:{message:"Captions status already set.",code:400,subCode:45223,resultCategories:["ExpectedError"]},CAPTIONS_NOT_SUPPORTED:{message:"Captions is not supported.",code:400,subCode:45224,resultCategories:["ExpectedError"]}},COMPOSED_STREAM:{},DATA_CHANNEL:{DISPOSED:{message:"DataChannel has been disposed",code:500,subCode:45300,resultCategories:["UnexpectedClientError"]},SENDER_NOT_READY:{message:"Sender is not ready",code:500,subCode:45301,resultCategories:["UnexpectedClientError"]},NO_AVAILABLE_CHANNEL_ID:{message:"No available channel id",code:500,subCode:45302,resultCategories:["UnexpectedClientError"]},INVALID_CHANNEL_ID:{message:"Invalid channel id",code:400,subCode:45303,resultCategories:["ExpectedError"]},INVALID_BITRATE_IN_KBPS:{message:"Invalid bitrateInKbps",code:400,subCode:45304,resultCategories:["ExpectedError"]},INVALID_PARTICIPANTS:{message:"Invalid participants",code:400,subCode:45305,resultCategories:["ExpectedError"]},TOO_MANY_PARTICIPANTS:{message:"Too many participants",code:400,subCode:45306,resultCategories:["ExpectedError"]},NO_VALID_PARTICIPANT:{message:"No valid participant",code:400,subCode:45307,resultCategories:["ExpectedError"]},MSG_DATA_EMPTY:{message:"Message data is empty",code:400,subCode:45308,resultCategories:["ExpectedError"]},MSG_DATA_TOO_LARGE:{message:"The size of message data is too large",code:400,subCode:45309,resultCategories:["ExpectedError"]},INVALID_MSG_LENGTH:{message:"Invalid message length",code:500,subCode:45310,resultCategories:["UnexpectedClientError"]},BUFFER_FULL:{message:"The buffer is full. Please wait and try again",code:500,subCode:45311,resultCategories:["UnexpectedClientError"]},SENDER_CLOSED:{message:"The sender has been closed",code:400,subCode:45312,resultCategories:["ExpectedError"]},NO_AVAILABLE_RELIABLE_CHANNEL:{message:"Currently there is no available reliable channel",code:500,subCode:45313,resultCategories:["UnexpectedClientError"]},NO_AVAILABLE_UNRELIABLE_CHANNEL:{message:"Currently there is no available unreliable channel",code:500,subCode:45314,resultCategories:["UnexpectedClientError"]},CHANNEL_ALREADY_ALLOCATED:{message:"Unable allocate the channel because a channel with the same channelId has already been allocated",code:500,subCode:45315,resultCategories:["UnexpectedClientError"]},INVALID_BITRATE:{message:"Invalid bitrate",code:400,subCode:45316,resultCategories:["ExpectedError"]},TRAFFIC_LIMITED:{message:"Traffic is limited",code:400,subCode:45317,resultCategories:["ExpectedError"]},SEND_FAIL:{message:"Failed to send message.",code:500,subCode:45318,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to DataChannel event, unknown event name.",code:422,subCode:45319,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_TYPE:{message:"Wrong argument type specified.",code:400,subCode:45320,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_VALUE:{message:"Wrong value specified.",code:400,subCode:45321,resultCategories:["ExpectedError"]},CANT_FIND_CHANNEL_ID:{message:"Cannot find the channelId specified.",code:400,subCode:45322,resultCategories:["ExpectedError"]},FAILED_TO_CREATE_SENDER:{message:"Failed to create the sender.",code:500,subCode:45323,resultCategories:["UnexpectedClientError"]}},DEBUG_INFO:{},DIAGNOSTICS:{INCORRECT_VALUETYPE_MAPPED:{message:"Mapped to an incorrect value type. Please gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45400,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to UserFacingDiagnostics event, unknown event name.",code:422,subCode:45401,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from UserFacingDiagnostics event, unknown event name.",code:422,subCode:45402,resultCategories:["ExpectedError"]},INCORRECT_VALUE_MAPPED:{message:"Failed to map diagnostic quality level. Please gather browser console logs and contact Azure Communication Services support.",code:500,subCode:45403,resultCategories:["UnexpectedClientError"]}},DOMINANT_SPEAKER:{},LIVE_STREAM:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to LiveStream event, unknown event name.",code:422,subCode:45500,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribefrom LiveStream event, unknown event name.",code:422,subCode:45501,resultCategories:["ExpectedError"]},INVALID_AGGREGATION_INTERVAL_RANGE:{message:"Invalid aggregationInterval value range.",code:400,subCode:45502,resultCategories:["ExpectedError"]},INVALID_DATAPOINTS_AGGREGATION_RANGE:{message:"invalid dataPointsPerAggregation value range.",code:400,subCode:45503,resultCategories:["ExpectedError"]},DISPOSED:{message:"MediaStatsCallFeature has been disposed.",code:400,subCode:45504,resultCategories:["ExpectedError"]}},MEDIA_STATS:{INVALID_AGGREGATION_INTERVAL_RANGE:{message:"Invalid aggregationInterval value range.",code:400,subCode:45550,resultCategories:["ExpectedError"]},INVALID_DATAPOINTS_AGGREGATION_RANGE:{message:"invalid dataPointsPerAggregation value range.",code:400,subCode:45551,resultCategories:["ExpectedError"]},DISPOSED:{message:"MediaStatsCallFeature has been disposed.",code:400,subCode:45552,resultCategories:["ExpectedError"]}},OPTIMAL_VIDEO_COUNT:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to OptimalVideoCount event, unknown event name.",code:422,subCode:45600,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from OptimalVideoCount event, unknown event name.",code:422,subCode:45601,resultCategories:["ExpectedError"]}},PPTLIVE:{},PRECALL_DIAGNOSTICS:{SET_DEVICE_FAIL:{message:"Failed to set default microphone or speaker with error",code:412,subCode:45700,resultCategories:["UnexpectedClientError"]},GET_DIAGNOSTICS_INFO:{message:"Unable to return call diagnostic information.",code:500,subCode:45701,resultCategories:["UnexpectedClientError"]},VIDEO_STREAM_TIMEOUT:{message:"Timeout in checking media stream status",code:500,subCode:45702,resultCategories:["UnexpectedClientError"]},GET_CALL_AGENT:{message:"Failed to get existing call agent or create a new one",code:500,subCode:45703,resultCategories:["UnexpectedClientError"]},CONNECT_FAIL:{message:"Test call failed to connect",code:500,subCode:45704,resultCategories:["UnexpectedClientError"]},RENDER_VIDEO:{message:"Call failed to render video.",code:500,subCode:45705,resultCategories:["UnexpectedClientError"]},HANGUP_FAIL:{message:"Test call failed hang up the call",code:500,subCode:45706,resultCategories:["UnexpectedClientError"]},VIDEO_MEDIASTATS:{message:"Failed to get video call media stats",code:500,subCode:45707,resultCategories:["UnexpectedClientError"]},CALL_CONNECT_TIMEOUT:{message:"Call timed out to connect. Please try again, if the issue persists, gather browser console logs and contact Azure Communication Services support.",code:408,subCode:45708,resultCategories:["UnexpectedClientError"]}},RAISE_HAND:{INITIALIZE:{message:"Could not initialize raise hand feature.",code:500,subCode:45750,resultCategories:["UnexpectedClientError"]},RAISE_HAND_PUBLISH_STATE:{message:"Could not change a participant state.",code:500,subCode:45751,resultCategories:["UnexpectedServerError"]},RAISE_HAND_FAIL:{message:"Could not change a participant state.",code:500,subCode:45752,resultCategories:["UnexpectedServerError"]},LOWER_HAND_FAIL:{message:"Could not change a participant state.",code:500,subCode:45753,resultCategories:["UnexpectedServerError"]},LOWER_REMOTEPARTICIPANTS_HANDS_FAIL:{message:"Could not change a participant state.",code:500,subCode:45754,resultCategories:["UnexpectedServerError"]},LOWER_ALL_HANDS_FAIL:{message:"Could not change a participant state.",code:500,subCode:45755,resultCategories:["UnexpectedServerError"]},LOWER_HANDS_EMPTY_PARTICIPANT_LIST:{message:"Lower hands request failed because participant list is empty.",code:400,subCode:45756,resultCategories:["ExpectedError"]},RAISE_HANDS_EMPTY_PARTICIPANT_LIST:{message:"Raise hands request failed because participant list is empty.",code:400,subCode:45757,resultCategories:["ExpectedError"]}},REACTION:{CALL_NOT_CONNECTED:{message:"Call is not connected yet to send reaction",code:400,subCode:45800,resultCategories:["ExpectedError"]},NOT_SUPPORTED_1TO1_CTE:{message:"Reaction send is not supported for 1:1 direct calling with teams identity",code:400,subCode:45801,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE_FAIL_POLICY:{message:"Unable to register listener due to meeting policy",code:403,subCode:45802,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE_FAIL_POLICY:{message:"Unable to deregister listener due to meeting policy",code:403,subCode:45803,resultCategories:["ExpectedError"]},SEND_FAIL_POLICY:{message:"Unable to send reaction due to meeting policy",code:403,subCode:45804,resultCategories:["ExpectedError"]},STATE_SERVICE_CONNECT_FAIL:{message:"Could not create state service proxy web-socket connection",code:500,subCode:45805,resultCategories:["UnexpectedServerError"]},MAP_CREATE_FAIL:{message:"Could not create sync map to exchange reaction",code:500,subCode:45806,resultCategories:["UnexpectedServerError"]},NOT_INIT_YET:{message:"Unable to handle send reaction",code:400,subCode:45807,resultCategories:["ExpectedError"]},SEND_REACTION_FAIL:{message:"Unable to handle send reaction",code:500,subCode:45808,resultCategories:["UnexpectedClientError"]},RECEIVE_REACTION_FAIL:{message:"Unable to parse reaction",code:500,subCode:45809,resultCategories:["UnexpectedClientError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to Reation event, unknown event name.",code:422,subCode:45810,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Reaction event, unknown event name.",code:422,subCode:45811,resultCategories:["ExpectedError"]}},RECORDING:{EVENT_SUBSCRIBE:{message:"Not able to subscribe to Recording event, unknown event name.",code:422,subCode:45850,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from Recording event, unknown event name.",code:422,subCode:45851,resultCategories:["ExpectedError"]},RECORDING_STATUS_ALREADY_SET:{message:"Recording status already set.",code:400,subCode:45852,resultCategories:["ExpectedError"]}},SPOTLIGHT:{ALREADY_SPOTLIGHTED:{message:"Bad request. All participants are already spotlighted",code:400,subCode:45900,resultCategories:["ExpectedError"]},START_SPOTLIGHT_FAILED:{message:"Internal Error. Start spotlight for participants failed",code:500,subCode:45901,resultCategories:["UnexpectedServerError"]},SPOTLIGHT_LIGHT_MAX_REACHED:{message:"Failed to start spotlight. Reached the maximum number of participants that can be Spotlighted.",code:400,subCode:45902,resultCategories:["ExpectedError"]},UNSUPPORTED_ROLE_TYPE:{message:"Failed to spotlight. User does not have a Presenter or Organizer role.",code:403,subCode:45903,resultCategories:["ExpectedError"]},FEATURE_NOT_ENABLED:{message:"Spotlight feature is not enabled",code:400,subCode:45904,resultCategories:["ExpectedError"]},PARTICIPANT_LIST_EMPTY:{message:"StartSpotlight failed. Participant list is empty",code:400,subCode:45905,resultCategories:["ExpectedError"]}},TEAMS_MEETING_AUDIO_CONFERENCING:{ONLY_AVAILABLE_IN_MEETINGS:{message:"Teams meeting audio conferencing feature is only available in meetings",code:400,subCode:45950,resultCategories:["ExpectedError"]},DISABLED:{message:"The Teams meeting audio conferencing details feature is disabled by ACS service.",code:405,subCode:45951,resultCategories:["ExpectedError"]},UNAVAILABLE_BEFORE_JOINING:{message:"Teams meeting audio conferencing details are not available before joining the Teams meeting",code:400,subCode:45952,resultCategories:["ExpectedError"]},UNVAILABLE_IN_LOBBY:{message:"Teams meeting audio conferencing details are not available in Lobby",code:400,subCode:45953,resultCategories:["ExpectedError"]},DETAILS_NOT_CONFIGURED:{message:"Teams meeting audio conferencing details is not configured",code:400,subCode:45954,resultCategories:["UnexpectedClientError"]},GET_DETAILS_FAILED:{message:"Error retrieving Teams meeting audio conferencing details",code:500,subCode:45955,resultCategories:["UnexpectedServerError"]}},TRANSCRIPTION:{TRANSCRIPTION_STATUS_ALREADY_SET:{message:"Transcription status already set.",code:400,subCode:46e3,resultCategories:["ExpectedError"]}},TRANSFER:{TRANSFER_TO_TARGET_FAILED:{message:"Transfer to target failed",code:500,subCode:46050,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_CALL_TYPE:{message:"Transfer is not supported in this call.",code:400,subCode:46051,resultCategories:["ExpectedError"]},TARGET_NOT_RECOGNIZED:{message:"Transfer target is not recognized.",code:400,subCode:46052,resultCategories:["ExpectedError"]},INVALID_TARGET_TYPE:{message:"Invalid target participant type detected.",code:400,subCode:46053,resultCategories:["ExpectedError"]}},UNMIXED_AUDIO:{UNAVAILABLE:{message:"UnmixedAudio is not available.",code:500,subCode:46100,resultCategories:["UnexpectedClientError"]},PENDING_OPERATION:{message:"The operation cannot be done because there is a pending operation",code:400,subCode:46101,resultCategories:["ExpectedError"]},UNSUPPORTED_OPERATION:{message:"The operation is not supported in peer-to-peer call",code:400,subCode:46102,resultCategories:["ExpectedError"]},ENABLED:{message:"Unmixed audio has been enabled",code:400,subCode:46103,resultCategories:["ExpectedError"]},DISABLED:{message:"Unmixed audio has been disabled",code:400,subCode:46104,resultCategories:["ExpectedError"]},DISPOSED:{message:"Unmixed audio has been disposed",code:400,subCode:46105,resultCategories:["ExpectedError"]},EVENT_SUBSCIBE_UNSUBSCRIBE:{message:"Not able to subscribe or unsubscibe to UnmixedAudio event, unknown event name.",code:422,subCode:46106,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_TYPE:{message:"Wrong argument type specified.",code:400,subCode:46107,resultCategories:["ExpectedError"]},WRONG_ARGUMENT_VALUE:{message:"Wrong value specified.",code:400,subCode:46108,resultCategories:["ExpectedError"]},INVALID_STATE:{message:"Invalid state.",code:400,subCode:46109,resultCategories:["ExpectedError"]},UNKNOWN_ERROR:{message:"Unknown error",code:500,subCode:46110,resultCategories:["UnexpectedClientError"]},FAILED_TO_ENABLE:{message:"Failed to enable unmixed audio: AudioContext={0}, UnmixedAudio={1}",code:500,subCode:46111,resultCategories:["UnexpectedClientError"]},FAILED_TO_DISABLE:{message:"Failed to disable unmixed audio: AudioContext={0}, UnmixedAudio={1}",code:500,subCode:46112,resultCategories:["UnexpectedClientError"]},FAILED_TO_INITIALIZE:{message:"Failed to initialize unmixed audio.",code:500,subCode:46113,resultCategories:["UnexpectedClientError"]}},VIDEO_EFFECTS:{DISABLED:{message:"Video effects feature is currently disabled by Azure Communication Services.",code:403,subCode:46150,resultCategories:["ExpectedError"]},START_DISPOSED:{message:"VideoEffects feature is disposed. Create a new VideoEffects Feature instance.",code:400,subCode:46151,resultCategories:["ExpectedError"]},UNSUPPORTED_SOURCE:{message:"Current source is unsupported to use effects",code:415,subCode:46152,resultCategories:["ExpectedError"]},START_DEVICE_MANAGER:{message:"Failed to get device manager to start effects.",code:500,subCode:46153,resultCategories:["UnexpectedClientError"]},PROVIDER_UNAVAILABLE:{message:"EffectProvider not available",code:500,subCode:46154,resultCategories:["UnexpectedClientError"]},WEBCV_PROVIDER_FAILED:{message:"Failed to get WebCV provider.",code:500,subCode:46155,resultCategories:["UnexpectedClientError"]},UNSUPPORTED_EFFECT:{message:"Effect is not supported.",code:501,subCode:46156,resultCategories:["UnexpectedClientError"]},STOP_DISPOSED:{message:"VideoEffects feature is disposed. Create a new VideoEffects Feature instance.",code:400,subCode:46157,resultCategories:["UnexpectedClientError"]},STOP_DEVICE_MANAGER:{message:"Failed to get device manager to stop effects.",code:500,subCode:46158,resultCategories:["UnexpectedClientError"]},INVALID_EFFECT:{message:"Invalid effect provided",code:400,subCode:46159,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to event {event}, unknown event name",code:400,subCode:46160,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe event {event}, unknown event name",code:400,subCode:46161,resultCategories:["ExpectedError"]},EFFECT_PROVIDER_TIMEOUT:{message:"Timed promise; rejected.",code:408,subCode:46162,resultCategories:["UnexpectedClientError"]},SUPPORT_CHECK_FAILED:{message:"Error while checking support",code:501,subCode:46163,resultCategories:["UnexpectedClientError"]},START_FAILED:{message:"Error starting video effects",code:500,subCode:46164,resultCategories:["UnexpectedClientError"]},STOP_FAILED:{message:"Error stopping video effects",code:500,subCode:46165,resultCategories:["UnexpectedClientError"]},DISPOSE_FAILED:{message:"Error disposing video effects feature",code:500,subCode:46166,resultCategories:["UnexpectedClientError"]},EFFECT_NOT_SUPPORTED:{message:"Effect is not supported. The hardware does not support the effect.",code:400,subCode:46167,resultCategories:["UnexpectedClientError"]},EFFECT_NOT_AVAILABLE:{message:"Effect is not available. Try again when the effect is initialized and available",code:500,subCode:46168,resultCategories:["UnexpectedClientError"]},EFFECT_DISABLED_BY_POLICY:{message:"Effect can not be enabled because of Teams Policy",code:403,subCode:46169,resultCategories:["ExpectedError"]},ENABLE_EFFECT_FAILED:{message:"Failed to enable the effect",code:500,subCode:46170,resultCategories:["UnexpectedClientError"]}},LOCAL_RECORDING:{ONLY_AVAILABLE_IN_MEETINGS:{message:"Local Recording feature is only available in meetings",code:400,subCode:46200,resultCategories:["ExpectedError"]},DISABLED:{message:"Local Recording feature is currently disabled by Azure Communication Service.",code:405,subCode:46201,resultCategories:["ExpectedError"]},EVENT_SUBSCRIBE:{message:"Not able to subscribe to LocalRecording event, unknown event name.",code:422,subCode:46202,resultCategories:["ExpectedError"]},EVENT_UNSUBSCRIBE:{message:"Not able to unsubscribe from LocalRecording event, unknown event name.",code:422,subCode:46203,resultCategories:["ExpectedError"]}}}},v=400,S=408,y=412,C=422,_=500,E="19:preview-",T={Date:!0,RegExp:!0,String:!0,Number:!0};class b extends Error{constructor(e){if(super(),this._code=0,this._subCode=0,this._resultCategories=[],this.name="CallingCommunicationError",e.originalError instanceof b)return this._code=e.originalError.code,this._subCode=e.originalError.subCode,this._resultCategories=e.originalError.resultCategories,this.message=e.originalError.message,void(this.stack=e.originalError.stack);this.message=e.defaultError.message,this._code=e.defaultError.code,this._subCode=e.defaultError.subCode,this._resultCategories=e.defaultError.resultCategories,e.originalError instanceof Error&&(this.stack=e.originalError.stack)}get code(){return this._code}get subCode(){return this._subCode}get resultCategories(){return this._resultCategories}}const I=Symbol("loggerKeySymbol");var w,R,A;function P(e){return D(e||"",!1)}function M(e){return D(e||"",!0)}(w=e.CallAgentKind||(e.CallAgentKind={})).CallAgent="CallAgent",w.TeamsCallAgent="TeamsCallAgent",(R=e.CallKind||(e.CallKind={})).Call="Call",R.TeamsCall="TeamsCall",(A=e.IncomingCallKind||(e.IncomingCallKind={})).IncomingCall="IncomingCall",A.TeamsIncomingCall="TeamsIncomingCall";const k=t=>(i,n,r)=>{const a=r.value;return r.value=function(...i){if(this.kind===e.CallKind.TeamsCall&&this.isEmergencyCallInProgress())throw new b({defaultError:f.CALL.OPERATION_NOT_ALLOWED_DURING_EMERGENCY_CALL,defaultErrorMessageArgs:[t]});return a.apply(this,i)},r},D=(e,t)=>t?(t,i,n)=>{const r=n.value;return n.value=async function(...t){let i;const n=+new Date;O(this,e,"started");try{i=await r.apply(this,t),O(this,e,"succeeded",n)}catch(t){const i=new b({defaultError:f.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[e],originalError:t});throw N(this,e,t,n),i}return i},n}:(t,i,n)=>{const r=n.value;return n.value=function(...t){let i;const n=+new Date;O(this,e,"started");try{i=r.apply(this,t),O(this,e,"succeeded",n)}catch(t){const i=new b({defaultError:f.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[e],originalError:t});throw N(this,e,t,n),i}return i},n};function O(e,t,i,n){const r=L(e);if(r){const e=n?`in ${(+new Date-n)/1e3}s`:"";r.info(`op:${t}, ${i} ${e}`)}}function N(e,t,i,n){const r=L(e);try{if(r){const e=n?`in ${(+new Date-n)/1e3}s`:"";r.error(`op:${t} failed, message=${i.message}, code=${i.code}${i.subCode?`, subCode=${i.subCode}`:""} ${e}`),i&&r.error(`op:${t} failed, message=${i.message}, code=${i.code}, subCode=${i.subCode}, resultCategories=${i.resultCategories}, time elapsed=${e}`)}}catch(i){}}function L(e){try{const t=Reflect.getMetadata(I,e);if(t)return e[t]}catch(e){}}function x(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}var F="function",U="object",B="undefined",V="prototype",H="hasOwnProperty",$=Object,G=$[V],j=$.assign,z=$.create,W=$.defineProperty,q=G[H];function K(){return typeof globalThis!==B&&globalThis?globalThis:typeof self!==B&&self?self:typeof window!==B&&window?window:typeof i.g!==B&&i.g?i.g:null}function J(e){throw new TypeError(e)}function Y(e){if(z)return z(e);if(null==e)return{};var t=typeof e;function i(){}return t!==U&&t!==F&&J("Object prototype may only be an Object:"+e),i[V]=e,new i}(K()||{}).Symbol,(K()||{}).Reflect;var Q=j||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])G[H].call(t,r)&&(e[r]=t[r]);return e},Z=function(e,t){return Z=$.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t[H](i)&&(e[i]=t[i])},Z(e,t)};function X(e,t){function i(){this.constructor=e}typeof t!==F&&null!==t&&J("Class extends value "+String(t)+" is not a constructor or null"),Z(e,t),e[V]=null===t?Y(t):(i[V]=t[V],new i)}var ee,te=0,ie=1,ne=2,re=4,ae=5,se="undefined",oe="constructor",le="prototype",ce="function",de="_dynInstFuncs",ue="_isDynProxy",he="_dynClass",pe="_dynInstChk",ge=pe,me="_dfOpts",fe="_unknown_",ve="__proto__",Se="_dyn"+ve,ye="__dynProto$Gbl",Ce="_dynInstProto",_e="useBaseInst",Ee="setInstFuncs",Te=Object,be=Te.getPrototypeOf,Ie=Te.getOwnPropertyNames;var we,Re=function(){var e;return typeof globalThis!==se&&(e=globalThis),e||typeof self===se||(e=self),e||typeof window===se||(e=window),e||typeof i.g===se||(e=i.g),e||{}}(),Ae=Re[ye]||(Re[ye]={o:(ee={},ee[Ee]=!0,ee[_e]=!0,ee),n:1e3});function Pe(e,t){return e&&Te[le].hasOwnProperty.call(e,t)}function Me(e){return e&&(e===Te[le]||e===Array[le])}function ke(e){return Me(e)||e===Function[le]}function De(e){var t;if(e){if(be)return be(e);var i=e[ve]||e[le]||(e[oe]?e[oe][le]:null);t=e[Se]||i,Pe(e,Se)||(delete e[Ce],t=e[Se]=e[Ce]||e[Se],e[Ce]=i)}return t}function Oe(e,t){var i=[];if(Ie)i=Ie(e);else for(var n in e)"string"==typeof n&&Pe(e,n)&&i.push(n);if(i&&i.length>0)for(var r=0;r<i.length;r++)t(i[r])}function Ne(e,t,i){return t!==oe&&typeof e[t]===ce&&(i||Pe(e,t))}function Le(e){throw new TypeError("DynamicProto: "+e)}function xe(e,t){for(var i=e.length-1;i>=0;i--)if(e[i]===t)return!0;return!1}function Fe(e,t,i,n,r){function a(e,t){var i=function(){return(function(e,t,i,n){var r=null;if(e&&Pe(i,he)){var a=e[de]||{};if((r=(a[i[he]]||{})[t])||Le("Missing ["+t+"] "+ce),!r[pe]&&!1!==a[ge]){for(var s=!Pe(e,t),o=De(e),l=[];s&&o&&!ke(o)&&!xe(l,o);){var c=o[t];if(c){s=c===n;break}l.push(o),o=De(o)}try{s&&(e[t]=r),r[pe]=1}catch(e){a[ge]=!1}}}return r}(this,t,e,i)||function(e,t,i){var n=t[e];return n===i&&(n=De(t)[e]),typeof n!==ce&&Le("["+e+"] is not a "+ce),n}(t,e,i)).apply(this,arguments)};return i[ue]=1,i}if(!Me(e)){var s=i[de]=i[de]||{},o=s[t]=s[t]||{};!1!==s[ge]&&(s[ge]=!!r),Oe(i,(function(t){Ne(i,t,!1)&&i[t]!==n[t]&&(o[t]=i[t],delete i[t],(!Pe(e,t)||e[t]&&!e[t][ue])&&(e[t]=a(e,t)))}))}}function Ue(e,t){return Pe(e,le)?e.name||t||fe:((e||{})[oe]||{}).name||t||fe}function Be(e,t,i,n){Pe(e,le)||Le("theClass is an invalid class definition.");var r=e[le];(function(e,t){if(be){for(var i=[],n=De(t);n&&!ke(n)&&!xe(i,n);){if(n===e)return!0;i.push(n),n=De(n)}return!1}return!0})(r,t)||Le("["+Ue(e)+"] not in hierarchy of ["+Ue(t)+"]");var a=null;Pe(r,he)?a=r[he]:(a="_dynCls$"+Ue(e,"_")+"$"+Ae.n,Ae.n++,r[he]=a);var s=Be[me],o=!!s[_e];o&&n&&void 0!==n[_e]&&(o=!!n[_e]);var l=function(e){var t={};return Oe(e,(function(i){!t[i]&&Ne(e,i,!1)&&(t[i]=e[i])})),t}(t);i(t,function(e,t,i,n){function r(e,t,i){var r=t[i];if(r[ue]&&n){var a=e[de]||{};!1!==a[ge]&&(r=(a[t[he]]||{})[i]||r)}return function(){return r.apply(e,arguments)}}var a={};Oe(i,(function(e){a[e]=r(t,i,e)}));for(var s=De(e),o=[];s&&!ke(s)&&!xe(o,s);)Oe(s,(function(e){!a[e]&&Ne(s,e,!be)&&(a[e]=r(t,s,e))})),o.push(s),s=De(s);return a}(r,t,l,o));var c=!!be&&!!s[Ee];c&&n&&(c=!!n[Ee]),Fe(r,a,t,l,!1!==c)}Be[me]=Ae.o,function(e){e[e.CRITICAL=1]="CRITICAL",e[e.WARNING=2]="WARNING"}(we||(we={}));var Ve={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99,InvalidInstrumentationKey:100,CannotParseAiBlobValue:101,InvalidContentBlob:102,TrackPageActionEventFailed:103},He="on",$e="attachEvent",Ge="addEventListener",je="detachEvent",ze="removeEventListener",We=W;function qe(e){return G.toString.call(e)}function Ke(e){return void 0===e||typeof e===B}function Je(e){return null===e||Ke(e)}function Ye(e){return!Je(e)}function Qe(e){return typeof e===U}function Ze(e){return typeof e===F}function Xe(e,t,i,n){void 0===n&&(n=!1);var r=!1;if(!Je(e))try{Je(e[Ge])?Je(e[$e])||(e[$e](He+t,i),r=!0):(e[Ge](t,i,n),r=!0)}catch(e){}return r}function et(e,t,i,n){if(void 0===n&&(n=!1),!Je(e))try{Je(e[ze])?Je(e[je])||e[je](He+t,i):e[ze](t,i,n)}catch(e){}}function tt(e,t){if(e)for(var i in e)q.call(e,i)&&t.call(e,i,e[i])}function it(e,t){var i=!1;if(e&&t){var n=t.length;if(e===t)return!0;if(e.length>=n){for(var r=0;r<n;r++)if(e[r]!==t[r])return!1;i=!0}}return i}function nt(e,t){return!(!e||!t)&&-1!==e.indexOf(t)}function rt(e){return"[object Array]"===qe(e)}function at(e){return"string"==typeof e}function st(e){return"number"==typeof e}function ot(e){return"boolean"==typeof e}function lt(e){if(function(e){return"[object Date]"===qe(e)}(e)){var t=function(e){var t=String(e);return 1===t.length&&(t="0"+t),t};return e.getUTCFullYear()+"-"+t(e.getUTCMonth()+1)+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+String((e.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}}function ct(e,t,i){for(var n=e.length,r=0;r<n&&(!(r in e)||-1!==t.call(i||e,e[r],r,e));r++);}function dt(e,t,i){for(var n=e.length,r=i||0,a=Math.max(r>=0?r:n-Math.abs(r),0);a<n;a++)if(a in e&&e[a]===t)return a;return-1}function ut(e){return"string"!=typeof e?e:e.replace(/^\s+|\s+$/g,"")}var ht=!{toString:null}.propertyIsEnumerable("toString"),pt=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];function gt(e){var t=typeof e;t===F||t===U&&null!==e||J("objKeys called on non-object");var i=[];for(var n in e)e&&q.call(e,n)&&i.push(n);if(ht)for(var r=pt.length,a=0;a<r;a++)e&&q.call(e,pt[a])&&i.push(pt[a]);return i}function mt(e,t,i,n){if(We)try{var r={enumerable:!0,configurable:!0};return i&&(r.get=i),n&&(r.set=n),We(e,t,r),!0}catch(e){}return!1}function ft(){var e=Date;return e.now?e.now():(new e).getTime()}function vt(e){return function(e){return"[object Error]"===qe(e)}(e)?e.name:""}function St(e,t,i,n,r){var a=i;return e&&((a=e[t])===i||r&&!r(a)||n&&!n(i)||(a=i,e[t]=a)),a}function yt(e){return!e}function Ct(e){return!!e}function _t(e){throw new Error(e)}function Et(e){return e&&(e=$(j?j({},e):e)),e}var Tt="window",bt="document",It="navigator",wt="location",Rt="performance",At="JSON",Pt="crypto",Mt="msCrypto",kt="msie",Dt="trident/",Ot=null,Nt=null,Lt=!1;function xt(e){var t=K();return t&&t[e]?t[e]:e===Tt&&Ft()?window:null}function Ft(){return Boolean(typeof window===U&&window)}function Ut(){return Ft()?window:xt(Tt)}function Bt(){return Boolean(typeof document===U&&document)?document:xt(bt)}function Vt(){return Boolean(typeof navigator===U&&navigator)}function Ht(){return Vt()?navigator:xt(It)}function $t(e){if(e&&Lt){var t=xt("__mockLocation");if(t)return t}return typeof location===U&&location?location:xt(wt)}function Gt(){return Boolean(typeof JSON===U&&JSON||null!==xt(At))}function jt(){return Gt()?JSON||xt(At):null}function zt(){var e=Ht();return!(!e||!e.product)&&"ReactNative"===e.product}function Wt(){var e=Ht();if(e&&(e.userAgent!==Nt||null===Ot)){var t=((Nt=e.userAgent)||"").toLowerCase();Ot=nt(t,kt)||nt(t,Dt)}return Ot}function qt(e){var t=Object[V].toString.call(e),i="";return"[object Error]"===t?i="{ stack: '"+e.stack+"', message: '"+e.message+"', name: '"+e.name+"'":Gt()&&(i=jt().stringify(e)),t+i}function Kt(e){return e?'"'+e.replace(/\"/g,"")+'"':""}var Jt=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r.messageId=e,r.message=(i?"AI: ":"AI (Internal): ")+e;var a="";Gt()&&(a=jt().stringify(n));var s=(t?" message:"+Kt(t):"")+(n?" props:"+Kt(a):"");r.message+=s}return e.dataType="MessageData",e}();function Yt(e,t){return(e||{}).logger||new Qt(t)}var Qt=function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i=0,n={};Be(e,this,(function(e){function r(e,i){var n=t[e];return Je(n)?i:n}Je(t)&&(t={}),e.consoleLoggingLevel=function(){return r("loggingLevelConsole",0)},e.telemetryLoggingLevel=function(){return r("loggingLevelTelemetry",1)},e.maxInternalMessageLimit=function(){return r("maxMessageLimit",25)},e.enableDebugExceptions=function(){return r("enableDebugExceptions",!1)},e.throwInternal=function(t,i,r,a,s){void 0===s&&(s=!1);var o=new Jt(i,r,s,a);if(e.enableDebugExceptions())throw o;if(!Ke(o)&&o&&!Ke(o.message)){var l=e.consoleLoggingLevel();if(s){var c=+o.messageId;!n[c]&&l>=we.WARNING&&(e.warnToConsole(o.message),n[c]=!0)}else l>=we.WARNING&&e.warnToConsole(o.message);e.logInternalMessage(t,o)}},e.warnToConsole=function(e){var t=typeof console!==B?console:xt("console");if(t){var i="log";t.warn&&(i="warn"),Ze(t[i])&&t[i](e)}},e.resetInternalMessageCount=function(){i=0,n={}},e.logInternalMessage=function(t,r){if(!(i>=e.maxInternalMessageLimit())){var a=!0,s="AITR_"+r.messageId;if(n[s]?a=!1:n[s]=!0,a&&(t<=e.telemetryLoggingLevel()&&(e.queue.push(r),i++),i===e.maxInternalMessageLimit())){var o="Internal events throttle limit per PageView reached for this app.",l=new Jt(Ve.MessageLimitPerPVExceeded,o,!1);e.queue.push(l),e.warnToConsole(o)}}}}))},Zt="ctx",Xt=function(){function e(t,i,n){var r,a=this,s=!1;a.start=ft(),a.name=t,a.isAsync=n,a.isChildEvt=function(){return!1},Ze(i)&&(s=mt(a,"payload",(function(){return!r&&Ze(i)&&(r=i(),i=null),r}))),a.getCtx=function(t){return t?t===e.ParentContextKey||t===e.ChildrenContextKey?a[t]:(a[Zt]||{})[t]:null},a.setCtx=function(t,i){t&&(t===e.ParentContextKey?(a[t]||(a.isChildEvt=function(){return!0}),a[t]=i):t===e.ChildrenContextKey?a[t]=i:(a[Zt]=a[Zt]||{})[t]=i)},a.complete=function(){var t=0,n=a.getCtx(e.ChildrenContextKey);if(rt(n))for(var r=0;r<n.length;r++){var o=n[r];o&&(t+=o.time)}a.time=ft()-a.start,a.exTime=a.time-t,a.complete=function(){},!s&&Ze(i)&&(a.payload=i())}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),ei=function e(t){this.ctx={},Be(e,this,(function(e){e.create=function(e,t,i){return new Xt(e,t,i)},e.fire=function(e){e&&(e.complete(),t&&t.perfEvent(e))},e.setCtx=function(t,i){t&&((e[Zt]=e[Zt]||{})[t]=i)},e.getCtx=function(t){return(e[Zt]||{})[t]}}))},ti="CoreUtils.doPerf";function ii(e,t,i,n,r){if(e){var a=e;if(a&&Ze(a.getPerfMgr)&&(a=a.getPerfMgr()),a){var s=void 0,o=a.getCtx(ti);try{if(s=a.create(t(),n,r)){if(o&&s.setCtx&&(s.setCtx(Xt.ParentContextKey,o),o.getCtx&&o.setCtx)){var l=o.getCtx(Xt.ChildrenContextKey);l||(l=[],o.setCtx(Xt.ChildrenContextKey,l)),l.push(s)}return a.setCtx(ti,s),i(s)}}catch(e){s&&s.setCtx&&s.setCtx("exception",e)}finally{s&&a.fire(s),a.setCtx(ti,o)}}}return i()}var ni=function(e,t){var i=this,n=null,r=Ze(e.processTelemetry),a=Ze(e.setNextPlugin);i._hasRun=!1,i.getPlugin=function(){return e},i.getNext=function(){return n},i.setNext=function(e){n=e},i.processTelemetry=function(s,o){o||(o=t);var l=e?e.identifier:"TelemetryPluginChain";ii(o?o.core():null,(function(){return l+":processTelemetry"}),(function(){if(e&&r){i._hasRun=!0;try{o.setNext(n),a&&e.setNextPlugin(n),n&&(n._hasRun=!1),e.processTelemetry(s,o)}catch(i){var t=n&&n._hasRun;n&&t||o.diagLog().throwInternal(we.CRITICAL,Ve.PluginException,"Plugin ["+e.identifier+"] failed during processTelemetry - "+i),n&&!t&&n.processTelemetry(s,o)}}else n&&(i._hasRun=!0,n.processTelemetry(s,o))}),(function(){return{item:s}}),!s.sync)}};function ri(e,t){var i=[];if(e&&e.length>0)for(var n=null,r=0;r<e.length;r++){var a=e[r];if(a&&Ze(a.processTelemetry)){var s=new ni(a,t);i.push(s),n&&n.setNext(s),n=s}}return i.length>0?i[0]:null}var ai=function e(t,i,n,r){var a=this,s=null;null!==r&&(t&&Ze(t.getPlugin)?s=function(e,t,i){var n=[],r=!i;if(e)for(;e;){var a=e.getPlugin();(r||a===i)&&(r=!0,n.push(a)),e=e.getNext()}return r||n.push(i),ri(n,t)}(t,a,r||t.getPlugin()):r?s=function(e,t,i){var n=e,r=!1;return i&&e&&(n=[],ct(e,(function(e){(r||e===i)&&(r=!0,n.push(e))}))),i&&!r&&(n||(n=[]),n.push(i)),ri(n,t)}(t,a,r):Ke(r)&&(s=ri(t,a))),a.core=function(){return n},a.diagLog=function(){return Yt(n,i)},a.getCfg=function(){return i},a.getExtCfg=function(e,t){var n;if(void 0===t&&(t={}),i){var r=i.extensionConfig;r&&e&&(n=r[e])}return n||t},a.getConfig=function(e,t,n){var r;void 0===n&&(n=!1);var s=a.getExtCfg(e,null);return s&&!Je(s[t])?r=s[t]:i&&!Je(i[t])&&(r=i[t]),Je(r)?n:r},a.hasNext=function(){return null!=s},a.getNext=function(){return s},a.setNext=function(e){s=e},a.processNext=function(e){var t=s;t&&(s=t.getNext(),t.processTelemetry(e,a))},a.createNew=function(t,r){return void 0===t&&(t=null),new e(t||s,i,n,r)}},si="extensionConfig",oi="getPlugin",li=function(){function e(){var e=this,t=!1,i=null,n=null;e.core=null,e.diagLog=function(t){return e._getTelCtx(t).diagLog()},e.isInitialized=function(){return t},e.setInitialized=function(e){t=e},e.setNextPlugin=function(e){n=e},e.processNext=function(e,t){t?t.processNext(e):n&&Ze(n.processTelemetry)&&n.processTelemetry(e,null)},e._getTelCtx=function(t){void 0===t&&(t=null);var r=t;if(!r){var a=i||new ai(null,{},e.core);r=n&&n[oi]?a.createNew(null,n[oi]):a.createNew(null,n)}return r},e._baseTelInit=function(r,a,s,o){r&&St(r,si,[],null,Je),!o&&a&&(o=a.getProcessTelContext().getNext());var l=n;n&&n[oi]&&(l=n[oi]()),e.core=a,i=new ai(o,r,a,l),t=!0}}return e.prototype.initialize=function(e,t,i,n){this._baseTelInit(e,t,i,n)},e}(),ci="processTelemetry",di="priority",ui="setNextPlugin",hi="isInitialized";function pi(e,t){for(var i=[],n=null,r=e.getNext();r;){var a=r.getPlugin();a&&(n&&Ze(n[ui])&&Ze(a[ci])&&n[ui](a),Ze(a[hi])&&a[hi]()||i.push(a),n=a,r=r.getNext())}ct(i,(function(i){i.initialize(e.getCfg(),e.core(),t,e.getNext())}))}function gi(e){return e.sort((function(e,t){var i=0,n=Ze(t[ci]);return Ze(e[ci])?i=n?e[di]-t[di]:1:n&&(i=-1),i}))}var mi=function(e){function t(){var i,n=e.call(this)||this;function r(e){e&&e.length>0&&(function(e){ct(e,(function(e){e.priority<500&&_t("Channel has invalid priority"+e.identifier)}))}(e=e.sort((function(e,t){return e.priority-t.priority}))),i.push(e))}return n.identifier="ChannelControllerPlugin",n.priority=500,Be(t,n,(function(e,t){e.setNextPlugin=function(e){},e.processTelemetry=function(e,t){i&&ct(i,(function(i){i.length>0&&n._getTelCtx(t).createNew(i).processNext(e)}))},e.getChannelControls=function(){return i},e.initialize=function(n,a,s){e.isInitialized()||(t.initialize(n,a,s),function(e,t){if(i=[],e&&ct(e,(function(e){return r(e)})),t){var n=[];ct(t,(function(e){e.priority>500&&n.push(e)})),r(n)}}((n||{}).channels,s),ct(i,(function(e){return pi(new ai(e,n,a),s)})))}})),n}var i;return X(t,e),t._staticInit=(mt(i=t.prototype,"ChannelControls",i.getChannelControls),void mt(i,"channelQueue",i.getChannelControls)),t}(li),fi="toGMTString",vi="toUTCString",Si="cookie",yi="expires",Ci="enabled",_i="isCookieUseDisabled",Ei="disableCookiesUsage",Ti="_ckMgr",bi="",Ii=null,wi=null,Ri=null,Ai=Bt(),Pi={},Mi={};function ki(e){return!e||e.isEnabled()}function Di(e,t){var i;if(e)i=e.getCookieMgr();else if(t){var n=(t||{}).cookieCfg;i=n[Ti]?n[Ti]:Oi(t)}return i||(i=function(e,t){var i=Oi[Ti]||Mi[Ti];return i||(i=Oi[Ti]=Oi(e,t),Mi[Ti]=i),i}(t,(e||{}).logger)),i}function Oi(e,t){var i=function(e){var t=e.cookieCfg=e.cookieCfg||{};if(St(t,"domain",e.cookieDomain,Ye,Je),St(t,"path",e.cookiePath||"/",null,Je),Je(t[Ci])){var i=void 0;Ke(e[_i])||(i=!e[_i]),Ke(e[Ei])||(i=!e[Ei]),t[Ci]=i}return t}(e||Mi),n=i.path||"/",r=i.domain,a=!1!==i[Ci],s={isEnabled:function(){var e=a&&Ni(t),i=Mi[Ti];return e&&i&&s!==i&&(e=ki(i)),e},setEnabled:function(e){a=!1!==e},set:function(e,t,a,o,l){if(ki(s)){var c={},d=ut(t||bi),u=d.indexOf(";");if(-1!==u&&(d=ut(t.substring(0,u)),c=Li(t.substring(u+1))),St(c,"domain",o||r,Ct,Ke),!Je(a)){var h=Wt();if(Ke(c[yi])){var p=ft()+1e3*a;if(p>0){var g=new Date;g.setTime(p),St(c,yi,xi(g,h?fi:vi)||xi(g,h?fi:vi)||bi,Ct)}}h||St(c,"max-age",bi+a,null,Ke)}var m=$t();m&&"https:"===m.protocol&&(St(c,"secure",null,null,Ke),null===wi&&(wi=!function(e){return!(!at(e)||!nt(e,"CPU iPhone OS 12")&&!nt(e,"iPad; CPU OS 12")&&!(nt(e,"Macintosh; Intel Mac OS X 10_14")&&nt(e,"Version/")&&nt(e,"Safari"))&&(!nt(e,"Macintosh; Intel Mac OS X 10_14")||!function(e,t){if(e&&t){var i=t.length,n=e.length;if(e===t)return!0;if(n>=i){for(var r=n-1,a=i-1;a>=0;a--){if(e[r]!=t[a])return!1;r--}return!0}}return!1}(e,"AppleWebKit/605.1.15 (KHTML, like Gecko)"))&&!nt(e,"Chrome/5")&&!nt(e,"Chrome/6")&&(!nt(e,"UnrealEngine")||nt(e,"Chrome"))&&!nt(e,"UCBrowser/12")&&!nt(e,"UCBrowser/11"))}((Ht()||{}).userAgent)),wi&&St(c,"SameSite","None",null,Ke)),St(c,"path",l||n,null,Ke),(i.setCookie||Bi)(e,Fi(d,c))}},get:function(e){var t=bi;return ki(s)&&(t=(i.getCookie||Ui)(e)),t},del:function(e,t){ki(s)&&s.purge(e,t)},purge:function(e,n){if(Ni(t)){var r=((a={}).path=n||"/",a[yi]="Thu, 01 Jan 1970 00:00:01 GMT",a);Wt()||(r["max-age"]="0"),(i.delCookie||Bi)(e,Fi(bi,r))}var a}};return s[Ti]=s,s}function Ni(e){if(null===Ii){Ii=!1;try{Ii=void 0!==(Ai||{})[Si]}catch(t){e&&e.throwInternal(we.WARNING,Ve.CannotAccessCookie,"Cannot access document.cookie - "+vt(t),{exception:qt(t)})}}return Ii}function Li(e){var t={};return e&&e.length&&ct(ut(e).split(";"),(function(e){if(e=ut(e||bi)){var i=e.indexOf("=");-1===i?t[e]=null:t[ut(e.substring(0,i))]=ut(e.substring(i+1))}})),t}function xi(e,t){return Ze(e[t])?e[t]():null}function Fi(e,t){var i=e||bi;return tt(t,(function(e,t){i+="; "+e+(Je(t)?bi:"="+t)})),i}function Ui(e){var t=bi;if(Ai){var i=Ai[Si]||bi;Ri!==i&&(Pi=Li(i),Ri=i),t=ut(Pi[e]||bi)}return t}function Bi(e,t){Ai&&(Ai[Si]=e+"="+t)}var Vi="_notificationManager",Hi=function e(){var t,i,n,r,a,s=!1;Be(e,this,(function(e){e._extensions=new Array,i=new mi,e.logger=Y({throwInternal:function(e,t,i,n,r){},warnToConsole:function(e){},resetInternalMessageCount:function(){}}),t=[],e.isInitialized=function(){return s},e.initialize=function(t,r,a,o){e.isInitialized()&&_t("Core should not be initialized more than once"),t&&!Je(t.instrumentationKey)||_t("Please provide instrumentation key"),n=o,e[Vi]=o,e.config=t||{},t.extensions=Je(t.extensions)?[]:t.extensions,(function(e,t,i){var n;return e?!(n=e[t])&&Je(n)&&(n=Ke(i)?{}:i,e[t]=n):n=Ke(i)?{}:i,n}(t,si)).NotificationManager=o,a&&(e.logger=a);var l=[];l.push.apply(l,r.concat(t.extensions)),l=gi(l);var c=[],d={};ct(l,(function(e){(Je(e)||Je(e.initialize))&&_t("Extensions must provide callback to initialize");var t=e.priority,n=e.identifier;e&&t&&(Je(d[t])?d[t]=n:a.warnToConsole("Two extensions have same priority #"+t+" - "+d[t]+", "+n)),(!t||t<i.priority)&&c.push(e)})),l.push(i),c.push(i),l=gi(l),e._extensions=l,pi(new ai([i],t,e),l),pi(new ai(c,t,e),l),e._extensions=c,0===e.getTransmissionControls().length&&_t("No channels available"),s=!0,e.releaseQueue()},e.getTransmissionControls=function(){return i.getChannelControls()},e.track=function(i){St(i,"iKey",e.config.instrumentationKey,null,yt),St(i,"time",lt(new Date),null,yt),St(i,"ver","4.0",null,Je),e.isInitialized()?e.getProcessTelContext().processNext(i):t.push(i)},e.getProcessTelContext=function(){var t=e._extensions,n=t;return t&&0!==t.length||(n=[i]),new ai(n,e.config,e)},e.getNotifyMgr=function(){return n||(n=Y({addNotificationListener:function(e){},removeNotificationListener:function(e){},eventsSent:function(e){},eventsDiscarded:function(e,t){},eventsSendRequest:function(e,t){}}),e[Vi]=n),n},e.getCookieMgr=function(){return a||(a=Oi(e.config,e.logger)),a},e.setCookieMgr=function(e){a=e},e.getPerfMgr=function(){return r||e.config&&e.config.enablePerfMgr&&(r=new ei(e.getNotifyMgr())),r},e.setPerfMgr=function(e){r=e},e.eventCnt=function(){return t.length},e.releaseQueue=function(){t.length>0&&(ct(t,(function(t){e.getProcessTelContext().processNext(t)})),t=[])}}))},$i=function e(t){this.listeners=[];var i=!!(t||{}).perfEvtsSendAll;Be(e,this,(function(e){e.addNotificationListener=function(t){e.listeners.push(t)},e.removeNotificationListener=function(t){for(var i=dt(e.listeners,t);i>-1;)e.listeners.splice(i,1),i=dt(e.listeners,t)},e.eventsSent=function(t){ct(e.listeners,(function(e){e&&e.eventsSent&&setTimeout((function(){return e.eventsSent(t)}),0)}))},e.eventsDiscarded=function(t,i){ct(e.listeners,(function(e){e&&e.eventsDiscarded&&setTimeout((function(){return e.eventsDiscarded(t,i)}),0)}))},e.eventsSendRequest=function(t,i){ct(e.listeners,(function(e){if(e&&e.eventsSendRequest)if(i)setTimeout((function(){return e.eventsSendRequest(t,i)}),0);else try{e.eventsSendRequest(t,i)}catch(e){}}))},e.perfEvent=function(t){t&&(!i&&t.isChildEvt()||ct(e.listeners,(function(e){if(e&&e.perfEvent)if(t.isAsync)setTimeout((function(){return e.perfEvent(t)}),0);else try{e.perfEvent(t)}catch(e){}})))}}))},Gi=function(e){function t(){var i=e.call(this)||this;return Be(t,i,(function(e,t){function i(t){var i=e.getNotifyMgr();i&&i.eventsDiscarded([t],ne)}e.initialize=function(e,i,n,r){t.initialize(e,i,n||new Qt(e),r||new $i(e))},e.track=function(n){ii(e.getPerfMgr(),(function(){return"AppInsightsCore:track"}),(function(){null===n&&(i(n),_t("Invalid telemetry item")),function(e){if(Je(e.name))throw i(e),Error("telemetry name required")}(n),t.track(n)}),(function(){return{item:n}}),!n.sync)},e.addNotificationListener=function(t){var i=e.getNotifyMgr();i&&i.addNotificationListener(t)},e.removeNotificationListener=function(t){var i=e.getNotifyMgr();i&&i.removeNotificationListener(t)},e.pollInternalLogs=function(t){var i=e.config.diagnosticLogInterval;return i&&i>0||(i=1e4),setInterval((function(){var i=e.logger?e.logger.queue:[];ct(i,(function(i){var n={name:t||"InternalMessageId: "+i.messageId,iKey:e.config.instrumentationKey,time:lt(new Date),baseType:Jt.dataType,baseData:{message:i.message}};e.track(n)})),i.length=0}),i)}})),i}return X(t,e),t}(Hi),ji=4294967296,zi=4294967295,Wi=!1,qi=123456789,Ki=987654321;function Ji(){try{var e=2147483647&ft();!function(e){e<0&&(e>>>=0),qi=123456789+e&zi,Ki=987654321-e&zi,Wi=!0}((Math.random()*ji^e)+e)}catch(e){}}function Yi(e){var t,i=xt(Pt)||xt(Mt);return i&&i.getRandomValues?t=i.getRandomValues(new Uint32Array(1))[0]&zi:Wt()?(Wi||Ji(),t=function(e){var t=((Ki=36969*(65535&Ki)+(Ki>>16)&zi)<<16)+(65535&(qi=18e3*(65535&qi)+(qi>>16)&zi))>>>0&zi;return e||(t>>>=0),t}()&zi):t=Math.floor(ji*Math.random()|0),e||(t>>>=0),t}function Qi(e,t){var i=!1,n=Ut();n&&(i=Xe(n,e,t),i=Xe(n.body,e,t)||i);var r=Bt();return r&&(i=nn.Attach(r,e,t)||i),i}function Zi(){function e(){return function(e){return e>0?Math.floor(Yi()/zi*(e+1))>>>0:0}(15)}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(tn,(function(t){var i=0|e();return("x"===t?i:3&i|8).toString(16)}))}function Xi(e){void 0===e&&(e=22);for(var t=Yi()>>>0,i=0,n="";n.length<e;)i++,n+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(63&t),t>>>=6,5===i&&(t=(Yi()<<2&4294967295|3&t)>>>0,i=0);return n}var en,tn=/[xy]/g,nn={Attach:Xe,AttachEvent:Xe,Detach:et,DetachEvent:et},rn={NotSet:0,Pii_DistinguishedName:1,Pii_GenericData:2,Pii_IPV4Address:3,Pii_IPv6Address:4,Pii_MailSubject:5,Pii_PhoneNumber:6,Pii_QueryString:7,Pii_SipAddress:8,Pii_SmtpAddress:9,Pii_Identity:10,Pii_Uri:11,Pii_Fqdn:12,Pii_IPV4AddressLegacy:13,CustomerContent_GenericContent:32},an=1,sn=2,on=3,ln=4,cn={Unspecified:0,String:1,Int32:2,UInt32:3,Int64:4,UInt64:5,Double:6,Bool:7,Guid:8,DateTime:9},dn=Q(Q({},Ve),{AuthHandShakeError:501,AuthRedirectFail:502,BrowserCannotReadLocalStorage:503,BrowserCannotWriteLocalStorage:504,BrowserDoesNotSupportLocalStorage:505,CannotParseBiBlobValue:506,CannotParseDataAttribute:507,CVPluginNotAvailable:508,DroppedEvent:509,ErrorParsingAISessionCookie:510,ErrorProvidedChannels:511,FailedToGetCookies:512,FailedToInitializeCorrelationVector:513,FailedToInitializeSDK:514,InvalidContentBlob:515,InvalidCorrelationValue:516,SessionRenewalDateIsZero:517,SendPostOnCompleteFailure:518,PostResponseHandler:519,SDKNotInitialized:520}),un="1DS-Web-JS-3.1.2",hn=((en={})[0]=cn.Unspecified,en[2]=cn.Double,en[1]=cn.String,en[3]=cn.Bool,en[4098]=cn.Double,en[4097]=cn.String,en[4099]=cn.Bool,en),pn=null,gn=(Boolean(Bt()),Boolean(Ut()));function mn(e){return!(""===e||Je(e))}function fn(){return null===pn&&(pn=Vt()&&Boolean(Ht().sendBeacon)),pn}function vn(e,t,i){if(!t&&!mn(t)||"string"!=typeof e)return null;var n=typeof t;if("string"===n||"number"===n||"boolean"===n||rt(t))t={value:t};else if("object"!==n||t.hasOwnProperty("value")){if(Je(t.value)||""===t.value||!at(t.value)&&!st(t.value)&&!ot(t.value)&&!rt(t.value))return null}else t={value:i?JSON.stringify(t):t};if(rt(t.value)&&!function(e){return e.length>0}(t.value))return null;if(!Je(t.kind)){if(rt(t.value)||!function(e){return e===rn.NotSet||e>rn.NotSet&&e<=rn.Pii_IPV4AddressLegacy||e===rn.CustomerContent_GenericContent}(t.kind))return null;t.value=t.value.toString()}return t}function Sn(){if(void 0!==typeof XMLHttpRequest){var e=xt("XMLHttpRequest");if(e){var t=new e;return Boolean(Ke(t.withCredentials)&&void 0!==typeof XDomainRequest)}}}function yn(e,t,i){var n=-1;if(!Ke(e))if(t>0&&(32===t?n=8192:t<=13&&(n=t<<5)),function(e){return e>=0&&e<=9}(i))-1===n&&(n=0),n|=i;else{var r=hn[In(e)]||-1;-1!==n&&-1!==r?n|=r:r===cn.Double&&(n=r)}return n}function Cn(e,t,i){var n;return void 0===i&&(i=!0),e&&(n=e.get(t),i&&n&&decodeURIComponent&&(n=decodeURIComponent(n))),n||""}function _n(e){void 0===e&&(e="D");var t=Zi();return"B"===e?t="{"+t+"}":"P"===e?t="("+t+")":"N"===e&&(t=t.replace(/-/g,"")),t}function En(e,t,i,n,r){var a={},s=!1,o=0,l=arguments.length,c=arguments;for("[object Boolean]"===Object[V].toString.call(c[0])&&(s=c[0],o++);o<l;o++)tt(c[o],(function(e,t){s&&t&&Qe(t)?rt(t)?(a[e]=a[e]||[],ct(t,(function(t,i){t&&Qe(t)?a[e][i]=En(!0,a[e][i],t):a[e][i]=t}))):a[e]=En(!0,a[e],t):a[e]=t}));return a}var Tn=function(){var e=xt(Rt);return e&&e.now?e.now():ft()};function bn(e,t){var i=e;i.timings=i.timings||{},i.timings.processTelemetryStart=i.timings.processTelemetryStart||{},i.timings.processTelemetryStart[t]=Tn()}function In(e){var t=0;if(null!=e){var i=typeof e;"string"===i?t=1:"number"===i?t=2:"boolean"===i?t=3:i===U&&(t=4,rt(e)?(t=4096,e.length>0&&(t|=In(e[0]))):function(e,t){return e&&q.call(e,t)}(e,"value")&&(t=8192|In(e.value)))}return t}var wn="version",Rn="properties",An=function(e){function t(){var i=e.call(this)||this;return i.pluginVersionStringArr=[],i.pluginVersionString="",Be(t,i,(function(e,t){e.initialize=function(i,n,r,a){ii(e,(function(){return"AppInsightsCore.initialize"}),(function(){if(i){i.endpointUrl||(i.endpointUrl="https://browser.events.data.microsoft.com/OneCollector/1.0/");var s=i.propertyStorageOverride;if(s&&(!s.getProperty||!s.setProperty))throw new Error("Invalid property storage override passed.");i.channels&&ct(i.channels,(function(t){t&&ct(t,(function(t){if(t.identifier&&t.version){var i=t.identifier+"="+t.version;e.pluginVersionStringArr.push(i)}}))}))}e.getWParam=function(){return"undefined"!=typeof document?0:-1},n&&ct(n,(function(t){if(t&&t.identifier&&t.version){var i=t.identifier+"="+t.version;e.pluginVersionStringArr.push(i)}})),e.pluginVersionString=e.pluginVersionStringArr.join(";");try{t.initialize(i,n,r,a)}catch(t){e.logger.throwInternal(we.CRITICAL,dn.ErrorProvidedChannels,"Channels must be provided through config.channels only")}e.pollInternalLogs("InternalLog")}),(function(){return{config:i,extensions:n,logger:r,notificationManager:a}}))},e.track=function(i){ii(e,(function(){return"AppInsightsCore.track"}),(function(){var n=i;if(n){n.timings=n.timings||{},n.timings.trackStart=Tn(),function(e){return!!(e&&st(e)&&e>=an&&e<=ln)}(n.latency)||(n.latency=an);var r=n.ext=n.ext||{};r.sdk=r.sdk||{},r.sdk.ver=un;var a=n.baseData=n.baseData||{};a[Rn]||(a[Rn]={});var s=a[Rn];s[wn]||(s[wn]=""),""!==e.pluginVersionString&&(s[wn]=e.pluginVersionString)}t.track(n)}),(function(){return{item:i}}),!i.sync)}})),i}return X(t,e),t}(Gi),Pn="function",Mn="object",kn="undefined",Dn="prototype",On="hasOwnProperty",Nn=Object,Ln=Nn[Dn],xn=Nn.assign,Fn=Nn.create,Un=Nn.defineProperty,Bn=Ln[On];function Vn(){return typeof globalThis!==kn&&globalThis?globalThis:typeof self!==kn&&self?self:typeof window!==kn&&window?window:typeof i.g!==kn&&i.g?i.g:null}function Hn(e){throw new TypeError(e)}(Vn()||{}).Symbol,(Vn()||{}).Reflect;var $n,Gn=xn||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Ln[On].call(t,r)&&(e[r]=t[r]);return e},jn=function(e,t){return jn=Nn.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t[On](i)&&(e[i]=t[i])},jn(e,t)};function zn(e,t){function i(){this.constructor=e}typeof t!==Pn&&null!==t&&Hn("Class extends value "+String(t)+" is not a constructor or null"),jn(e,t),e[Dn]=null===t?function(e){if(Fn)return Fn(e);if(null==e)return{};var t=typeof e;function i(){}return t!==Mn&&t!==Pn&&Hn("Object prototype may only be an Object:"+e),i[Dn]=e,new i}(t):(i[Dn]=t[Dn],new i)}!function(e){e[e.CRITICAL=1]="CRITICAL",e[e.WARNING=2]="WARNING"}($n||($n={}));var Wn={BrowserDoesNotSupportLocalStorage:0,BrowserCannotReadLocalStorage:1,BrowserCannotReadSessionStorage:2,BrowserCannotWriteLocalStorage:3,BrowserCannotWriteSessionStorage:4,BrowserFailedRemovalFromLocalStorage:5,BrowserFailedRemovalFromSessionStorage:6,CannotSendEmptyTelemetry:7,ClientPerformanceMathError:8,ErrorParsingAISessionCookie:9,ErrorPVCalc:10,ExceptionWhileLoggingError:11,FailedAddingTelemetryToBuffer:12,FailedMonitorAjaxAbort:13,FailedMonitorAjaxDur:14,FailedMonitorAjaxOpen:15,FailedMonitorAjaxRSC:16,FailedMonitorAjaxSend:17,FailedMonitorAjaxGetCorrelationHeader:18,FailedToAddHandlerForOnBeforeUnload:19,FailedToSendQueuedTelemetry:20,FailedToReportDataLoss:21,FlushFailed:22,MessageLimitPerPVExceeded:23,MissingRequiredFieldSpecification:24,NavigationTimingNotSupported:25,OnError:26,SessionRenewalDateIsZero:27,SenderNotInitialized:28,StartTrackEventFailed:29,StopTrackEventFailed:30,StartTrackFailed:31,StopTrackFailed:32,TelemetrySampledAndNotSent:33,TrackEventFailed:34,TrackExceptionFailed:35,TrackMetricFailed:36,TrackPVFailed:37,TrackPVFailedCalc:38,TrackTraceFailed:39,TransmissionFailed:40,FailedToSetStorageBuffer:41,FailedToRestoreStorageBuffer:42,InvalidBackendResponse:43,FailedToFixDepricatedValues:44,InvalidDurationValue:45,TelemetryEnvelopeInvalid:46,CreateEnvelopeError:47,CannotSerializeObject:48,CannotSerializeObjectNonSerializable:49,CircularReferenceDetected:50,ClearAuthContextFailed:51,ExceptionTruncated:52,IllegalCharsInName:53,ItemNotInArray:54,MaxAjaxPerPVExceeded:55,MessageTruncated:56,NameTooLong:57,SampleRateOutOfRange:58,SetAuthContextFailed:59,SetAuthContextFailedAccountName:60,StringValueTooLong:61,StartCalledMoreThanOnce:62,StopCalledWithoutStart:63,TelemetryInitializerFailed:64,TrackArgumentsNotSpecified:65,UrlTooLong:66,SessionStorageBufferFull:67,CannotAccessCookie:68,IdTooLong:69,InvalidEvent:70,FailedMonitorAjaxSetRequestHeader:71,SendBrowserInfoOnUserInit:72,PluginException:73,NotificationException:74,SnippetScriptLoadFailure:99,InvalidInstrumentationKey:100,CannotParseAiBlobValue:101,InvalidContentBlob:102,TrackPageActionEventFailed:103},qn=Un;function Kn(e){return void 0===e||typeof e===kn}function Jn(e){return null===e||Kn(e)}function Yn(e){return typeof e===Pn}function Qn(e,t){return!(!e||!t)&&-1!==e.indexOf(t)}function Zn(e){return"[object Array]"===function(e){return Ln.toString.call(e)}(e)}function Xn(e,t,i){for(var n=e.length,r=0;r<n&&(!(r in e)||-1!==t.call(i||e,e[r],r,e));r++);}var er=!{toString:null}.propertyIsEnumerable("toString"),tr=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];function ir(){var e=Date;return e.now?e.now():(new e).getTime()}var nr="window",rr="navigator",ar="performance",sr="JSON",or="crypto",lr="msCrypto",cr="msie",dr="trident/",ur=null,hr=null;function pr(e){var t=Vn();return t&&t[e]?t[e]:e===nr&&gr()?window:null}function gr(){return Boolean(typeof window===Mn&&window)}function mr(){return Boolean(typeof navigator===Mn&&navigator)?navigator:pr(rr)}function fr(){return Boolean(typeof JSON===Mn&&JSON||null!==pr(sr))}function vr(e){return e?'"'+e.replace(/\"/g,"")+'"':""}var Sr=function(){function e(e,t,i,n){void 0===i&&(i=!1);var r=this;r.messageId=e,r.message=(i?"AI: ":"AI (Internal): ")+e;var a="";fr()&&(a=(fr()?JSON||pr(sr):null).stringify(n));var s=(t?" message:"+vr(t):"")+(n?" props:"+vr(a):"");r.message+=s}return e.dataType="MessageData",e}();var yr=function e(t){this.identifier="DiagnosticLogger",this.queue=[];var i=0,n={};Be(e,this,(function(e){function r(e,i){var n=t[e];return Jn(n)?i:n}Jn(t)&&(t={}),e.consoleLoggingLevel=function(){return r("loggingLevelConsole",0)},e.telemetryLoggingLevel=function(){return r("loggingLevelTelemetry",1)},e.maxInternalMessageLimit=function(){return r("maxMessageLimit",25)},e.enableDebugExceptions=function(){return r("enableDebugExceptions",!1)},e.throwInternal=function(t,i,r,a,s){void 0===s&&(s=!1);var o=new Sr(i,r,s,a);if(e.enableDebugExceptions())throw o;if(!Kn(o)&&o&&!Kn(o.message)){var l=e.consoleLoggingLevel();if(s){var c=+o.messageId;!n[c]&&l>=$n.WARNING&&(e.warnToConsole(o.message),n[c]=!0)}else l>=$n.WARNING&&e.warnToConsole(o.message);e.logInternalMessage(t,o)}},e.warnToConsole=function(e){var t=typeof console!==kn?console:pr("console");if(t){var i="log";t.warn&&(i="warn"),Yn(t[i])&&t[i](e)}},e.resetInternalMessageCount=function(){i=0,n={}},e.logInternalMessage=function(t,r){if(!(i>=e.maxInternalMessageLimit())){var a=!0,s="AITR_"+r.messageId;if(n[s]?a=!1:n[s]=!0,a&&(t<=e.telemetryLoggingLevel()&&(e.queue.push(r),i++),i===e.maxInternalMessageLimit())){var o="Internal events throttle limit per PageView reached for this app.",l=new Sr(Wn.MessageLimitPerPVExceeded,o,!1);e.queue.push(l),e.warnToConsole(o)}}}}))},Cr="ctx",_r=function(){function e(t,i,n){var r,a=this,s=!1;a.start=ir(),a.name=t,a.isAsync=n,a.isChildEvt=function(){return!1},Yn(i)&&(s=function(e,t,i,n){if(qn)try{var r={enumerable:!0,configurable:!0};return i&&(r.get=i),n&&(r.set=n),qn(e,t,r),!0}catch(e){}return!1}(a,"payload",(function(){return!r&&Yn(i)&&(r=i(),i=null),r}))),a.getCtx=function(t){return t?t===e.ParentContextKey||t===e.ChildrenContextKey?a[t]:(a[Cr]||{})[t]:null},a.setCtx=function(t,i){t&&(t===e.ParentContextKey?(a[t]||(a.isChildEvt=function(){return!0}),a[t]=i):t===e.ChildrenContextKey?a[t]=i:(a[Cr]=a[Cr]||{})[t]=i)},a.complete=function(){var t=0,n=a.getCtx(e.ChildrenContextKey);if(Zn(n))for(var r=0;r<n.length;r++){var o=n[r];o&&(t+=o.time)}a.time=ir()-a.start,a.exTime=a.time-t,a.complete=function(){},!s&&Yn(i)&&(a.payload=i())}}return e.ParentContextKey="parent",e.ChildrenContextKey="childEvts",e}(),Er="CoreUtils.doPerf";function Tr(e,t,i,n,r){if(e){var a=e;if(a&&Yn(a.getPerfMgr)&&(a=a.getPerfMgr()),a){var s=void 0,o=a.getCtx(Er);try{if(s=a.create(t(),n,r)){if(o&&s.setCtx&&(s.setCtx(_r.ParentContextKey,o),o.getCtx&&o.setCtx)){var l=o.getCtx(_r.ChildrenContextKey);l||(l=[],o.setCtx(_r.ChildrenContextKey,l)),l.push(s)}return a.setCtx(Er,s),i(s)}}catch(e){s&&s.setCtx&&s.setCtx("exception",e)}finally{s&&a.fire(s),a.setCtx(Er,o)}}}return i()}var br=function(e,t){var i=this,n=null,r=Yn(e.processTelemetry),a=Yn(e.setNextPlugin);i._hasRun=!1,i.getPlugin=function(){return e},i.getNext=function(){return n},i.setNext=function(e){n=e},i.processTelemetry=function(s,o){o||(o=t);var l=e?e.identifier:"TelemetryPluginChain";Tr(o?o.core():null,(function(){return l+":processTelemetry"}),(function(){if(e&&r){i._hasRun=!0;try{o.setNext(n),a&&e.setNextPlugin(n),n&&(n._hasRun=!1),e.processTelemetry(s,o)}catch(i){var t=n&&n._hasRun;n&&t||o.diagLog().throwInternal($n.CRITICAL,Wn.PluginException,"Plugin ["+e.identifier+"] failed during processTelemetry - "+i),n&&!t&&n.processTelemetry(s,o)}}else n&&(i._hasRun=!0,n.processTelemetry(s,o))}),(function(){return{item:s}}),!s.sync)}};function Ir(e,t){var i=[];if(e&&e.length>0)for(var n=null,r=0;r<e.length;r++){var a=e[r];if(a&&Yn(a.processTelemetry)){var s=new br(a,t);i.push(s),n&&n.setNext(s),n=s}}return i.length>0?i[0]:null}var wr=function e(t,i,n,r){var a=this,s=null;null!==r&&(t&&Yn(t.getPlugin)?s=function(e,t,i){var n=[],r=!i;if(e)for(;e;){var a=e.getPlugin();(r||a===i)&&(r=!0,n.push(a)),e=e.getNext()}return r||n.push(i),Ir(n,t)}(t,a,r||t.getPlugin()):r?s=function(e,t,i){var n=e,r=!1;return i&&e&&(n=[],Xn(e,(function(e){(r||e===i)&&(r=!0,n.push(e))}))),i&&!r&&(n||(n=[]),n.push(i)),Ir(n,t)}(t,a,r):Kn(r)&&(s=Ir(t,a))),a.core=function(){return n},a.diagLog=function(){return function(e,t){return(e||{}).logger||new yr(t)}(n,i)},a.getCfg=function(){return i},a.getExtCfg=function(e,t){var n;if(void 0===t&&(t={}),i){var r=i.extensionConfig;r&&e&&(n=r[e])}return n||t},a.getConfig=function(e,t,n){var r;void 0===n&&(n=!1);var s=a.getExtCfg(e,null);return s&&!Jn(s[t])?r=s[t]:i&&!Jn(i[t])&&(r=i[t]),Jn(r)?n:r},a.hasNext=function(){return null!=s},a.getNext=function(){return s},a.setNext=function(e){s=e},a.processNext=function(e){var t=s;t&&(s=t.getNext(),t.processTelemetry(e,a))},a.createNew=function(t,r){return void 0===t&&(t=null),new e(t||s,i,n,r)}},Rr="getPlugin",Ar=function(){function e(){var e=this,t=!1,i=null,n=null;e.core=null,e.diagLog=function(t){return e._getTelCtx(t).diagLog()},e.isInitialized=function(){return t},e.setInitialized=function(e){t=e},e.setNextPlugin=function(e){n=e},e.processNext=function(e,t){t?t.processNext(e):n&&Yn(n.processTelemetry)&&n.processTelemetry(e,null)},e._getTelCtx=function(t){void 0===t&&(t=null);var r=t;if(!r){var a=i||new wr(null,{},e.core);r=n&&n[Rr]?a.createNew(null,n[Rr]):a.createNew(null,n)}return r},e._baseTelInit=function(r,a,s,o){r&&function(e,t,i,n,r){var a=i;e&&((a=e[t])===i||r&&!r(a)||n&&!n(i)||(a=i,e[t]=a))}(r,"extensionConfig",[],null,Jn),!o&&a&&(o=a.getProcessTelContext().getNext());var l=n;n&&n[Rr]&&(l=n[Rr]()),e.core=a,i=new wr(o,r,a,l),t=!0}}return e.prototype.initialize=function(e,t,i,n){this._baseTelInit(e,t,i,n)},e}(),Pr=4294967296,Mr=4294967295,kr=!1,Dr=123456789,Or=987654321;function Nr(){try{var e=2147483647&ir();!function(e){e<0&&(e>>>=0),Dr=123456789+e&Mr,Or=987654321-e&Mr,kr=!0}((Math.random()*Pr^e)+e)}catch(e){}}function Lr(e){return e>0?Math.floor(function(e){var t,i=pr(or)||pr(lr);return i&&i.getRandomValues?t=i.getRandomValues(new Uint32Array(1))[0]&Mr:function(){var e=mr();if(e&&(e.userAgent!==hr||null===ur)){var t=((hr=e.userAgent)||"").toLowerCase();ur=Qn(t,cr)||Qn(t,dr)}return ur}()?(kr||Nr(),t=function(e){var t=((Or=36969*(65535&Or)+(Or>>16)&Mr)<<16)+(65535&(Dr=18e3*(65535&Dr)+(Dr>>16)&Mr))>>>0&Mr;return e||(t>>>=0),t}()&Mr):t=Math.floor(Pr*Math.random()|0),e||(t>>>=0),t}()/Mr*(e+1))>>>0:0}function xr(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(Ur,(function(e){var t=0|Lr(15);return("x"===e?t:3&t|8).toString(16)}))}var Fr,Ur=/[xy]/g,Br=0,Vr=1,Hr=6,$r=7,Gr=1,jr=2;function zr(e){if(e){var t=e.indexOf("-");if(t>-1)return e.substring(0,t)}return""}Gn(Gn({},Wn),{AuthHandShakeError:501,AuthRedirectFail:502,BrowserCannotReadLocalStorage:503,BrowserCannotWriteLocalStorage:504,BrowserDoesNotSupportLocalStorage:505,CannotParseBiBlobValue:506,CannotParseDataAttribute:507,CVPluginNotAvailable:508,DroppedEvent:509,ErrorParsingAISessionCookie:510,ErrorProvidedChannels:511,FailedToGetCookies:512,FailedToInitializeCorrelationVector:513,FailedToInitializeSDK:514,InvalidContentBlob:515,InvalidCorrelationValue:516,SessionRenewalDateIsZero:517,SendPostOnCompleteFailure:518,PostResponseHandler:519,SDKNotInitialized:520}),(Fr={})[0]=Br,Fr[2]=Hr,Fr[1]=Vr,Fr[3]=$r,Fr[4098]=Hr,Fr[4097]=Vr,Fr[4099]=$r,Boolean(Boolean(typeof document===Mn&&document)?document:pr("document")),Boolean(gr()?window:pr(nr));var Wr=function(){var e=pr(ar);return e&&e.now?e.now():ir()};var qr=Yn;function Kr(e,t,i){return function(n){e[t]=n,i()}}var Jr=function(){function e(t){var i=0,n=null,r=[];function a(t,a,o,l){r.push((function(){var r;try{(r=1===i?qr(t)?t(n):n:qr(a)?a(n):n)instanceof e?r.then(o,l):2!==i||qr(a)?o(r):l(r)}catch(e){return void l(e)}})),0!==i&&s()}function s(){if(r.length>0){var e=r.slice();r=[],setTimeout((function(){for(var t=0,i=e.length;t<i;++t)try{e[t]()}catch(e){}}),0)}}function o(e){0===i&&(n=e,i=1,s())}function l(e){0===i&&(n=e,i=2,s())}Be(e,this,(function(t){t.then=function(t,i){return new e((function(e,n){a(t,i,e,n)}))},t.catch=function(e){return t.then(null,e)}})),function(){if(!qr(t))throw new TypeError("ESPromise: resolvedFunc argument is not a Function");try{t(o,l)}catch(e){l(e)}}()}return e.resolve=function(t){return t instanceof e?t:t&&qr(t.then)?new e((function(e,i){try{t.then(e,i)}catch(e){i(e)}})):new e((function(e){e(t)}))},e.reject=function(t){return new e((function(e,i){i(t)}))},e.all=function(t){if(t&&t.length)return new e((function(e,i){try{for(var n=[],r=0,a=0;a<t.length;a++){var s=t[a];s&&qr(s.then)?(r++,s.then(Kr(n,a,(function(){0==--r&&e(n)})),i)):n[a]=s}0===r&&setTimeout((function(){e(n)}),0)}catch(e){i(e)}}))},e.race=function(t){return new e((function(e,i){if(t&&t.length)try{for(var n=function(n){var r=t[n];r&&qr(r.then)?r.then(e,i):setTimeout((function(){e(r)}),0)},r=0;r<t.length;r++)n(r)}catch(e){i(e)}}))},e}(),Yr=0,Qr=[],Zr=[],Xr=[];function ea(){return(new Date).getTime()}var ta,ia=function(){function e(t,i){var n=0,r=(t||"<unnamed>")+"."+Yr;function a(e){var t=Vn();t&&t.QUnit&&console&&console.log("ESPromiseScheduler["+r+"] "+e)}function s(e){i&&i.warnToConsole("ESPromiseScheduler["+r+"] "+e)}Yr++,Be(e,this,(function(e){var t=null,i=0;function o(e,t){for(var i=0;i<e.length;i++)if(e[i].id===t)return e.splice(i,1)[0];return null}e.scheduleEvent=function(e,l,c){var d=r+"."+i;i++,l&&(d+="-("+l+")");var u=d+"{"+n+"}";n++;var h={evt:null,tm:ea(),id:u,isRunning:!1,isAborted:!1};return h.evt=t?function(e,t){var i=new Jr((function(i,n){var r=ea()-t.tm,s=t.id;a("["+d+"] is waiting for ["+s+":"+r+" ms] to complete before starting -- ["+Zr.length+"] waiting and ["+Qr.length+"] running"),e.abort=function(t){e.abort=null,o(Zr,d),e.isAborted=!0,n(new Error(t))},t.evt.then((function(t){o(Zr,d),S(e).then(i,n)}),(function(t){o(Zr,d),S(e).then(i,n)}))}));return Zr.push(e),i}(h,t):S(h),(t=h).evt._schId=u,h.evt;function p(e){for(var t=ea(),i=t-6e5,n=e.length,r=0;r<n;){var a=e[r];if(a&&a.tm<i){var o=null;a.abort?(o="Aborting ["+a.id+"] due to Excessive runtime ("+(t-a.tm)+" ms)",a.abort(o)):o="Removing ["+a.id+"] due to Excessive runtime ("+(t-a.tm)+" ms)",s(o),e.splice(r,1),n--}else r++}}function g(e,i){var n=!1,r=o(Qr,e);if(r||(r=o(Xr,e),n=!0),r){r.to&&(clearTimeout(r.to),r.to=null);var l=ea()-r.tm;i?n?s("Timed out event ["+e+"] finally complete -- "+l+" ms"):a("Promise ["+e+"] Complete -- "+l+" ms"):(Xr.push(r),s("Event ["+e+"] Timed out and removed -- "+l+" ms"))}else a("Failed to remove ["+e+"] from running queue");t&&t.id===e&&(t=null),p(Qr),p(Zr),p(Xr)}function m(e,t){return function(i){return g(e,!0),t&&t(i),i}}function f(e,t,i,n){t.then((function(t){return t instanceof Jr?(a("Event ["+e+"] returned a promise -- waiting"),f(e,t,i,n),t):m(e,i)(t)}),m(e,n))}function v(e,t){var i=e.id;return new Jr((function(n,r){a("Event ["+i+"] Starting -- waited for "+(e.wTm||"--")+" ms"),e.isRunning=!0,e.abort=function(t){e.abort=null,e.isAborted=!0,g(i,!1),r(new Error(t))};var s=t(i);s instanceof Jr?(c&&(e.to=setTimeout((function(){g(i,!1),r(new Error("Timed out after ["+c+"] ms"))}),c)),f(i,s,(function(t){a("Event ["+i+"] Resolving after "+(ea()-e.tm)+" ms"),n(t)}),r)):(a("Promise ["+i+"] Auto completed as the start action did not return a promise"),n())}))}function S(t){var i=ea();return t.wTm=i-t.tm,t.tm=i,t.isAborted?Jr.reject(new Error("["+d+"] was aborted")):(Qr.push(t),v(t,e))}}}))}return e.incomplete=function(){return Qr},e.waitingToStart=function(){return Zr},e}();function na(e){return function(e){return"number"==typeof e}(e)&&e>=Gr&&e<=jr}!function(e){e[e.LocalStorage=1]="LocalStorage",e[e.SessionStorage=2]="SessionStorage",e[e.IndexedDb=3]="IndexedDb"}(ta||(ta={}));var ra="AWTEvents";function aa(e){var t=Vn()||{},i=null;try{if(i=t[e]){var n="__storage_test__";i.setItem(n,n),i.removeItem(n)}}catch(e){(function(e,t){var i=!1;return t instanceof DOMException&&(22!==t.code&&"QuotaExceededError"!==t.name&&1014!==t.code&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||e&&0!==e.length&&(i=!0)),i})(i,e)||(i=null)}return i}function sa(e,t){if(e)for(var i=function(e){var t=typeof e;t===Pn||t===Mn&&null!==e||Hn("objKeys called on non-object");var i=[];for(var n in e)e&&Bn.call(e,n)&&i.push(n);if(er)for(var r=tr.length,a=0;a<r;a++)e&&Bn.call(e,tr[a])&&i.push(tr[a]);return i}(e),n=0;n<i.length;n++){var r=i[n];if(!t(e[r],r))break}}function oa(e){var t=!0;return sa(e,(function(e,i){return e&&(t=!1),t})),t}function la(e,t){for(var i=1,n=0,r=function(){var e=[],r=t[i];if(sa(r,(function(t,i){return e.push(i),++n<10})),n>0){for(var a=0;a<e.length;a++)delete r[e[a]];return{value:!0}}i++};i<=e&&n<10;){var a=r();if("object"==typeof a)return a.value}return n>0}var ca=na,da=function e(t,i){Be(e,this,(function(e){var n=null,r=ra,a=null,s=null,o=null,l=5e6,c=null,d=null;function u(e,t){return{key:e,db:t}}function h(e,t){void 0===t&&(t=!0);var i=null;if(n){var r=n.getItem(e);if(r)try{i=JSON.parse(r)}catch(t){n.removeItem(e)}}return t&&!i&&(i={events:{1:{},2:{},3:{}},lastAccessTime:0}),u(e,i)}function p(e,t){void 0===t&&(t=!0);var i=!0,r=e.db;if(r){t&&(r.lastAccessTime=(new Date).getTime());for(var a=1;a<=2;a++)if(!oa(r.events[a])){i=!1;break}}try{if(i)n&&n.removeItem(e.key);else{var s=JSON.stringify(r);if(s.length>l)return!1;n&&n.setItem(e.key,s)}}catch(e){return!1}return!0}function g(e){var t=[],i=h(e,!1),r=i.db;if(r){var a=r.events;try{for(var s=1;s<=2;s++)sa(a[s],(function(e,i){return e&&t.push(e),!0}))}catch(e){}n&&n.removeItem(i.key)}return t}e.id=i,n=aa(t)||null,e.initialize=function(t){if(!n)return!1;var i=t.storageConfig||{};return l=i.maxStorageSizeInBytes>0?i.maxStorageSizeInBytes:l,r=i.storageKey||ra,a=e.id||t.id||xr(),d=r+"."+a,c=r+"Version",s=t.itemCtx.getCfg().instrumentationKey,o=zr(s)||s,function(){if(n){for(var e=n.getItem(c),t=[],i=h(d),a=!1,s=0;s<n.length;s++){var l=n.key(s);if(0===l.indexOf(r)&&l!==c){if("3"!==e){t.push(u(l,null));continue}var g=h(l,!1),m=g.db;if(m){if((new Date).getTime()-m.lastAccessTime>6e5){for(var f=1,v=function(){var e=m.events[f],t=i.db.events[f];sa(e,(function(i,n){return(zr(i.iKey)||i.iKey)===o&&(t[n]=i,delete e[n]),!0})),f++};f<=2;)v();a=!0,t.push(g)}}else t.push(u(l,null))}}for(s=0;s<t.length;s++)p(t[s],!1);a&&p(i),n.setItem(c,"3")}}(),!0},e.supportsSyncRequests=function(){return!0},e.getAllEvents=function(){try{var e=[],t=h(d,!1).db;if(t)for(var i=t.events,n=2;n>=1;n--)sa(i[n],(function(t){return t&&(zr(t.iKey)||t.iKey)===o&&e.push(t),!0}));return Jr.resolve(e)}catch(e){return Jr.reject(e)}},e.addEvent=function(e,t,i){try{var n=h(d);t.id=t.id||xr(),ca(t.persistence)||(t.persistence=1);for(var r=t.persistence,a=t.id,s=n.db.events;;){if(s[r][a]=t,p(n))return Jr.resolve(t);if(delete s[r][a],!la(r,s))return Jr.reject(new Error("Unable to free up event space"))}}catch(e){return Jr.reject(e)}},e.removeEvents=function(e){try{var t=h(d,!1),i=t.db;if(i){var n=i.events;try{for(var r=0;r<e.length;++r){var a=e[r];delete n[a.persistence][a.id]}if(p(t))return Jr.resolve(e)}catch(e){}e=g(t.key)}return Jr.resolve(e)}catch(e){return Jr.reject(e)}},e.clear=function(){try{var e=[],t=h(d,!1),i=t.db;if(i){for(var n=i.events,r=function(t){var i=n[t];sa(i,(function(t){return t&&(zr(t.iKey)||t.iKey)===o&&(delete i[t.id],e.push(t)),!0}))},a=2;a>=1;a--)r(a);p(t)}return Jr.resolve(e)}catch(e){return Jr.reject(e)}},e.teardown=function(){try{var e=h(d,!1),t=e.db;t&&(t.lastAccessTime=0,p(e,!1))}catch(e){}}}))},ua="result",ha="DBError: Unable to open database",pa="Database is not open",ga="DBError: Failed to delete the database",ma=["indexedDB"],fa=Yn,va=function(e){return"string"==typeof e};function Sa(e,t){pr("QUnit")&&console&&console.log("IndexedDbHelper ["+e+"] "+t)}function ya(e,t,i){e&&e.warnToConsole("IndexedDbHelper ["+t+"] "+i)}function Ca(e,t,i,n){return function(r){i(new Error(t)),Sa(e,"["+n+"] event rejected")}}var _a=[];function Ea(e,t){for(var i=null,n=0;n<_a.length;n++)if((i=_a[n]).name===e)return i;return i={name:e,sch:new ia("IndexedDbHelper["+e+"]",t),dbHdl:[],add:function(t){i.dbHdl.push(t),Sa(e,"- dbOpened (add) -- hdls ["+i.dbHdl.length+"]")},remove:function(t){for(var n=i.dbHdl,r=0;r<n.length;r++)if(n[r]===t){n.splice(r,1);break}Sa(e,"- dbClosed (remove) -- hdls ["+i.dbHdl.length+"]")},isOpen:function(){return i.dbHdl.length>0},openHdl:function(){return i.dbHdl.length>0?i.dbHdl[0]:null}},_a.push(i),i}var Ta=function e(t){Be(e,this,(function(e){var i=function(){var e=Vn()||{},t=null;if(e)try{for(var i=0;i<ma.length;i++)if((t=e[ma[i]])&&fa(t.open))return t}catch(e){t=null}return t||null}()||null;function n(e,i){var n=e.db.transaction(i,"readwrite");return n.onabort=function(){ya(t,e.dbName,"txn.onabort")},n.onerror=function(){ya(t,e.dbName,"txn.onerror")},n.oncomplete=function(){Sa(e.dbName,"txn.oncomplete")},{db:e,store:n.objectStore(i),tx:n,tbl:i,openCursor:function(t,n){return a(e,i,t,n)},newTransaction:function(t){return r(e,i,t)}}}function r(e,t,i){if(!e||!e.db)return Jr.reject(new Error(pa));try{var r=i(n(e,t));return r instanceof Jr?r:Jr.resolve(r)}catch(e){return Jr.reject(e)}}function a(e,t,i,r){if(!e||!e.db)return Jr.reject(new Error(pa));var a=null;return i&&va(i)?a=new ba(i):i&&i.isMatch&&(a=i),new Jr((function(i,s){var o=[],l=null,c=null;a&&a.keyRange&&(c=a.keyRange());var d=n(e,t);(l=c?d.store.openCursor(c):d.store.openCursor()).onerror=Ca(d.db.dbName,"DBError: Failed to Open Cursor",s,"openCursor"),l.onsuccess=function(e){var t=e.target[ua];if(t){var n={store:d,cursor:t,continue:function(){t.continue()},done:function(){i(o)}},l=t.value;if(!a||a.isMatch(l))if(r)try{switch(r(n,l,o)){case 2:i(o);break;case 1:break;default:n.continue()}}catch(e){s(e)}else o.push(l),n.continue();else n.continue()}else i(o)}}))}function s(e,t,i,n){return Ea(e).sch.scheduleEvent(i,t,n)}e.isAvailable=function(){return!!i},e.openDb=function(e,n,o,l){return s(e,"openDb",(function(s){return new Jr((function(c,d){var u=!1;function h(t,i,s,o,l){var c={db:i,dbName:e,dbVersion:n,ctx:null,isNew:o,txn:s?s.transaction:null};return l||(c.openStore=function(e,t){return r(c,e,t)},c.openCursor=function(e,t,i){return a(c,e,t,i)}),c}function p(i,n){var r=Ea(e);r.add(i),i.onabort=function(n){ya(t,e,"onabort -- closing the Db"),r.remove(i)},i.onerror=function(n){ya(t,e,"onerror -- closing the Db"),r.remove(i)},i.onclose=function(n){ya(t,e,"onclose -- closing the Db"),r.remove(i)},i.onversionchange=function(n){ya(t,e,"onversionchange -- force closing the Db"),i.close(),r.remove(i)};var a,s=null;r.dbHdl.length>0&&(s=r.dbHdl[0]),a=h(0,s,n,u);try{o(a).then((function(e){c(e)}),d)}catch(e){d(e)}}var g=Ea(e);if(null==i)d(new Error("No available storage factory"));else if(g.isOpen()){var m=h(0,g.openHdl(),null,!1);o(m).then(c,d)}else{var f=i.open(e,n);f.onblocked=function(i){ya(t,e,"Db Open Blocked event ["+s+"] - "+(f.error||"")),d(new Error(ha))},f.onerror=function(i){ya(t,e,"Db Open Error event ["+s+"] - "+(f.error||"")),d(new Error(ha))},f.onupgradeneeded=function(t){Sa(e,"Db Open Create/Upgrade needed event ["+s+"]");try{var i=t.target[ua];if(!i)return void d(new Error(ha));!function(e,t){var i=h(0,e,t,!0,!0);if(l)u=!0,l(i).then((function(){i.txn||(i.txn=t.transaction)}),(function(e){try{t.transaction&&t.transaction.abort()}finally{d(e)}}));else try{t.transaction&&t.transaction.abort()}finally{d(new Error("DBError: Database upgrade required"))}}(i,f)}catch(t){Ca(e,ha,d,s)(t)}},f.onsuccess=function(e){var t=e.target[ua];t?p(t,f):d(new Error(ha))}}}))}))},e.closeDb=function(e){s(e,"closeDb",(function(t){var i=Ea(e),n=i.dbHdl,r=n.length;if(r>0){for(var a=0;a<r;a++)n[a].close();i.dbHdl=[]}return Jr.resolve(1)}))},e.deleteDb=function(e){return null==i?Jr.resolve(!1):s(e,"deleteDb",(function(n){var r=Ea(e),a=r.dbHdl,s=a.length;if(s>0){ya(t,e,"Db is open ["+s+"] force closing");for(var o=0;o<s;o++)a[o].close();r.dbHdl=[]}return new Jr((function(r,a){setTimeout((function(){try{Sa(e,"["+n+"] starting");var s=i.deleteDatabase(e);s.onerror=function(i){ya(t,e,"["+n+"] error!!"),a(new Error(ga))},s.onblocked=function(i){ya(t,e,"["+n+"] blocked!!"),a(new Error(ga))},s.onupgradeneeded=function(i){ya(t,e,"["+n+"] upgrade needed!!"),a(new Error(ga))},s.onsuccess=function(t){Sa(e,"["+n+"] complete"),r(!0)},Sa(e,"["+n+"] started")}catch(i){ya(t,e,"["+n+"] threw - "+i),a(new Error(ga+" - "+i))}}),0)}))}))},e.getDbDetails=function(e){return s(e,"getDbDetails",(function(t){return null!=i&&i.databases?new Jr((function(t,n){i.databases().then((function(i){for(var r=0;r<i.length;r++)if(i[r].name===e)return void t(i[r]);n(new Error("DBError: Database does not exist"))}),n)})):Jr.reject(new Error("DBError: Feature not supported"))}),2e3)}}))},ba=function e(t){var i=[],n=null;Be(e,this,(function(e){e.keyRange=function(){return n},e.parseQuery=function(t){if(i=[],t)for(var r=t.split(";"),a=0;a<r.length;a++){var s=r[a],o=s.indexOf("=");if(-1!==o){var l=s.substring(0,o),c=s.substring(o+1);0===l.indexOf("#")&&(l=l.substring(1),n||(n=IDBKeyRange.bound(c,c+""))),e.startsWith(l,c)}}},e.startsWith=function(e,t){i.push({name:e,value:t,type:0})},e.contains=function(e,t){i.push({name:e,value:t,type:1})},e.isMatch=function(e){if(!i||0===i.length)return!0;if(!e)return!1;for(var t=0;t<i.length;t++){var n=i[t],r=e[n.name];if(r)if(0===n.type){if(0!==r.indexOf(n.value))return!1}else if(1===n.type&&-1===r.indexOf(n.value))return!1}return!0},t&&e.parseQuery(t)}))},Ia=6e5,wa=1008e4,Ra="DBError: Unable to add event",Aa="Evts",Pa="iKey",Ma=na;function ka(){return(new Date).getTime()}function Da(e){return e.openStore(Pa,(function(t){return new Jr((function(i,n){var r={iKey:e.ctx.iKey,tm:ka()},a=t.store.put(r);a.onsuccess=function(e){i(a.result.toString())},a.onerror=function(e){n(new Error(Ra))},a.onerror=function(e,t){return function(i){return t(new Error(e))}}("DBError: Unable to update iKey",n)}))}))}function Oa(e){for(var t=[],i=jr;i>=Gr;i--)for(var n=0;n<e.length;n++){var r=e[n];r&&r.evt.persistence===i&&t.push(r.evt)}return t}function Na(e){return function(t){return e.continue()}}function La(e){var t=e.cursor.delete();return t.onerror=Na(e),t.onsuccess=Na(e),1}function xa(e,t,i){return e.openCursor(Aa,t,(function(e,t,n){return i(t)?(n.push(t),La(e)):0}))}function Fa(e){return e.openCursor(Aa,"#key="+e.ctx.iKeyPrefix(),(function(t,i){var n=i.key;if(0===n.indexOf(e.ctx.iKeyPrefix())&&-1===n.indexOf(e.ctx.evtKeyPrefix())&&function(e,t){var i=e.tm;return ka()-i>t}(i,Ia)){i.key=e.ctx.evtKeyPrefix()+i.id;var r=t.store.store.put(i);return r.onerror=Na(t),r.onsuccess=function(e){try{La(t)}catch(e){t.continue()}},1}return 0}))}function Ua(e){return new Jr((function(t,i){(function(e){return new Jr((function(t,i){var n=!1;e.openCursor(Pa,null,(function(e,t,i){var r=t.tm;return ka()-r<wa?0:(n=!0,2)})).then((function(){if(n){var r={};xa(e,null,(function(e){if(!e||!e.evt||!e.evt.iKey)return!0;var t=e.tm;return ka()-t>wa||(r[e.evt.iKey]=1,!1)})).then((function(){var n=[];e.openCursor(Pa,null,(function(e,t,i){var a=t.tm;return ka()-a<wa||r[t.iKey]?0:(n.push(t),La(e))})).then((function(){t(n)}),i)}),i)}else t([])}),i)}))})(e).then((function(){Fa(e).then(t,t)}),i)}))}var Ba=function e(t){Be(e,this,(function(e){var i=null,n=null,r="Unknown",a=null,s=null,o=null,l=-1,c=0;function d(e){return i.openDb(n,1,(function(t){return new Jr((function(i,n){var l={iKey:r,storageId:a,iKeyPrefix:function(){return s},evtKeyPrefix:function(){return o}};t.ctx=l,Da(t).then((function(){e(t).then(i,n)}),n)}))}),(function(e){return new Jr((function(t,i){(function(e){e.objectStoreNames.contains(Aa)||e.createObjectStore(Aa,{keyPath:"key"}).createIndex("EvntId","key",{unique:!1}),e.objectStoreNames.contains(Pa)||e.createObjectStore(Pa,{keyPath:"iKey"}).createIndex("iKey","iKey",{unique:!0})})(e.db),t()}))}))}function u(e,t,i){return new Jr((function(n,r){function a(t,i){(function(e,t){return new Jr((function(i,n){var r=0,a=e.ctx.evtKeyPrefix();function s(){i(r)}function o(e,t){return new Jr((function(i){var n=e.store.delete(t.key);n.onsuccess=function(e){r++,i()},n.onerror=function(e){i()}}))}e.openCursor(Aa,"#key="+a,(function(e,i,n){return i.evt.persistence<=t&&0===i.key.indexOf(a)&&(function(e,t){for(var i=0;i<e.length;i++)if(t.tm<e[i].tm)return void e.splice(i,0,t);e.push(t)}(n,i),n.length>10&&n.splice(n.length-1,1)),0})).then((function(t){0!==t.length?e.openStore(Aa,(function(e){for(var i=[],n=0;n<t.length;n++)i.push(o(e,t[n]));return Jr.all(i).then(s,s)})):s()}),(function(){i(0)}))}))})(e,t).then((function(e){e>0&&(c-=e),i(e)}),(function(e){i(0)}))}function s(e){n(t.evt)}function o(){e.openStore(Aa,(function(o){var l=o.store.put(t);l.onsuccess=function(r){i&&Da(e).then(s,s),c++,n(t.evt)},l.onerror=function(s){function o(i){0===i&&r(new Error(Ra)),u(e,t,!1).then((function(e){n(t.evt)}),(function(){r(new Error(Ra))}))}i?a(Gr,(function(e){e>0?o(e):t.evt.persistence>=jr?a(jr,(function(e){o(e)})):r(new Error(Ra))})):r(new Error(Ra))}}))}l>0&&c>=l?a(Gr,(function(e){0===e?t.evt.persistence>=jr?a(jr,(function(e){o()})):r(new Error(Ra)):o()})):o()}))}e.id=t,e.initialize=function(t){var c=t.itemCtx.diagLog();if(!(i=new Ta(c)).isAvailable())return i=null,!1;var u=t.itemCtx.getCfg(),h=t.storageConfig||{};return n=h.indexedDbName||"AppInsightEvents.1",r=u.instrumentationKey||r,a=e.id||t.id||xr(),o=(s=r+"::")+a+"::",l=h.maxStorageItems>0?h.maxStorageItems:l,d((function(e){return e.isNew?Jr.resolve(!0):Ua(e)})).then((function(e){}),(function(e){c.warnToConsole("IndexedDbProvider failed to initialize - "+(e||"<unknown>")),i=null})),!0},e.supportsSyncRequests=function(){return!1},e.getAllEvents=function(){return null!=i&&i.isAvailable()?d((function(e){return new Jr((function(t,i){(function(e,t){return e.openCursor(Aa,t,(function(e,t,i){return i.push(t),0}))})(e,"#key="+e.ctx.evtKeyPrefix()).then((function(e){c=e.length,t(Oa(e))}),i)}))})):Jr.resolve([])},e.addEvent=function(e,t,n){return null!=i&&i.isAvailable()?(t.id=t.id||xr(),Ma(t.persistence)||(t.persistence=Gr),d((function(i){var n=e||t.id,r={key:i.ctx.evtKeyPrefix()+n,id:n,evt:t,tm:ka(),v:1};return u(i,r,!0)}))):Jr.resolve(t)},e.removeEvents=function(e){if(null==i||!i.isAvailable())return Jr.resolve([]);var t=[];return new Jr((function(i,n){d((function(i){return i.openCursor(Aa,"#key="+i.ctx.iKey,(function(i,n,r){if(-1!==function(e,t){for(var i=t.length,n=0;n<i;n++)if(e===t[n].id)return n;return-1}(n.id,e)){var a=i.cursor.delete();return a.onerror=Na(i),a.onsuccess=function(){t.push(n.evt),i.continue()},1}return 0}))})).then((function(e){c-=t.length,i(t)}),(function(e){c-=t.length,i(t)}))}))},e.clear=function(){return null!=i&&i.isAvailable()?new Jr((function(e,t){d((function(e){return xa(e,"#key="+e.ctx.evtKeyPrefix(),(function(t){return 0===t.key.indexOf(e.ctx.evtKeyPrefix())}))})).then((function(t){c=0,e(Oa(t))}),t)})):Jr.resolve([])},e.teardown=function(){i&&i.closeDb(n)}}))},Va=na,Ha=function(e){function t(){var i=e.call(this)||this;return i.identifier="LocalStorage",i.priority=1009,i.version="3.1.3",Be(t,i,(function(e,t){var i=!1,n=!1,r=null,a=[];function s(e,t){r||(r=new ia("LocalStorage")),r.scheduleEvent((function(e){return t(e)}),e)}function o(t){Tr(e.core,(function(){return"LocalStorageChannel:_sendStoredEventsToNextPlugin"}),(function(){s("sendToNext",(function(i){return t.provider.getAllEvents().then((function(i){for(var n=0;n<i.length;n++)try{var r=i[n];(zr(r.iKey)||r.iKey)===t.tenantId&&e.processNext(r,t.coreRootCtx.createNew())}catch(e){}}))}))}),(function(){return{iKeyConfig:t}}))}function l(t,i){Tr(e.core,(function(){return"LocalStorageChannel:_removeEvents"}),(function(){s("removeEvents",(function(e){var n=[];return Xn(i,(function(e){(zr(e.iKey)||e.iKey)===t.tenantId&&n.push(e)})),n.length>0?t.provider.removeEvents(n).then((function(e){})).catch((function(e){})):Jr.resolve()}))}),(function(){return{iKeyConfig:t,events:i}}))}function c(e){var t=new Ba;return t.initialize(e)||(t=null),t}function d(e,t){var i=new da(e);return i.initialize(t)||(i=null),i}function u(t,i,n,r){var s=e.identifier,u=t.extensionConfig=t.extensionConfig||[],h=u[s]=u[s]||{};h.providers||(h.providers=[ta.LocalStorage,ta.IndexedDb]);var p=function(t,i,n,r){t&&(t.extensionConfig=t.extensionConfig||[]),!r&&i&&(r=i.getProcessTelContext().getNext());var a=null,s=e._getTelCtx().getNext();return s&&(a=s.getPlugin()),new wr(r,t,i,a)}(t,i,0,r),g={itemCtx:p,storageConfig:h,id:e.id},m=function(e){for(var t=e.storageConfig.providers,i=null,n=0;!i&&n<t.length&&n<5;)switch(t[n++]){case ta.LocalStorage:i=d("localStorage",e);break;case ta.SessionStorage:i=d("sessionStorage",e);break;case ta.IndexedDb:i=c(e)}return i}(g);if(m){var f={iKey:t.instrumentationKey,tenantId:zr(t.instrumentationKey)||t.instrumentationKey,minPersistenceCacheLevel:Gr,coreRootCtx:p,providerContext:g,provider:m};Va(h.minPersistenceLevel||-1)&&(f.minPersistenceCacheLevel=h.minPersistenceLevel),a.push(f),i.addNotificationListener({eventsSent:function(e){l(f,e)},eventsDiscarded:function(e,t){l(f,e)}}),o(f)}}e.initialize=function(e,n,a,s){Tr(n,(function(){return"LocalStorageChannel.initialize"}),(function(){i||(t.initialize(e,n,a),t.setInitialized(!1),i=!0,r=new ia("LocalStorage",n.logger)),u(e,n,0,s)}),(function(){return{coreConfig:e,core:n,extensions:a,pluginChain:s}}))},e.processTelemetry=function(t,i){i=e._getTelCtx(i),function(e,t){var i=e;i.timings=i.timings||{},i.timings.processTelemetryStart=i.timings.processTelemetryStart||{},i.timings.processTelemetryStart[t]=Wr()}(t,e.identifier);var r=null;Xn(a,(function(e){e.iKey===t.iKey&&(r=e)}));var o=n,l=r?r.provider:null,c=t;!c.sync&&l?(c.id=c.id||xr(),na(c.persistence)||(c.persistence=1),function(e,t){return!(t.sync||t.persistence<e.minPersistenceCacheLevel)}(r,c)&&s("processTelemetry",(function(e){return l.addEvent(c.id,c,i)})),o||e.processNext(c,i)):e.processNext(c,i)},e.pause=function(){n=!0},e.resume=function(){Tr(e.core,(function(){return"LocalStorageChannel:resume"}),(function(){n=!1,Xn(a,(function(e){e.provider&&o(e)}))}))},e.teardown=function(){Xn(a,(function(e){var t=e.provider;t&&t.teardown()})),a=[]},e.flush=function(e,t){}})),i}return zn(t,e),t}(Ar),$a="function",Ga="object",ja="undefined",za="prototype",Wa=Object,qa=Wa.create,Ka=null;function Ja(e){void 0===e&&(e=!0);var t=!1===e?null:Ka;return t||(typeof globalThis!==ja&&(t=globalThis),t||typeof self===ja||(t=self),t||typeof window===ja||(t=window),t||typeof i.g===ja||(t=i.g),Ka=t),t}function Ya(e){throw new TypeError(e)}(Ja()||{}).Symbol,(Ja()||{}).Reflect;var Qa=function(e,t){return Qa=Wa.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},Qa(e,t)};function Za(e,t){function i(){this.constructor=e}typeof t!==$a&&null!==t&&Ya("Class extends value "+String(t)+" is not a constructor or null"),Qa(e,t),e[za]=null===t?function(e){if(qa)return qa(e);if(null==e)return{};var t=typeof e;function i(){}return t!==Ga&&t!==$a&&Ya("Object prototype may only be an Object:"+e),i[za]=e,new i}(t):(i[za]=t[za],new i)}var Xa="REAL_TIME",es=function(){function e(t,i){var n=i?[].concat(i):[],r=this;r.iKey=function(){return t},r.count=function(){return n.length},r.events=function(){return n},r.addEvents=function(e,t){return void 0===t&&(t=!0),e&&e.length>0?(n=t?n.concat(e):e.concat(n),e.length):0},r.split=function(i,r){var a=new e(t);if(i<n.length){var s=n.length-i;Je(r)||(s=r<s?r:s),a.addEvents(n.splice(i,s),!0)}return a}}return e.create=function(t,i){return new e(t,i)},e}(),ts=2e6,is=Math.min(ts,65e3),ns="metadata",rs="f",as=/\./,ss=function e(t,i,n,r){var a="data",s="baseData",o=!!r,l=i,c={};Be(e,this,(function(e){function i(e,t){var i=c[e];return void 0===i&&(e.length>=7&&(i=it(e,"ext.metadata")||it(e,"ext.web")),c[e]=i),i}function r(e,t,a,s,c,d,u){tt(e,(function(e,h){var p=null;if(h||mn(h)){var g=a,m=e,f=c,v=t;if(o&&!s&&as.test(e)){var S=e.split("."),y=S.length;if(y>1){f&&(f=f.slice());for(var C=0;C<y-1;C++){var _=S[C];v=v[_]=v[_]||{},g+="."+_,f&&f.push(_)}m=S[y-1]}}if(p=s&&i(g)||!l||!l.handleField(g,m)?vn(m,h,n):l.value(g,m,h,n)){var E=p.value;if(v[m]=E,d&&d(f,m,p),u&&"object"==typeof E&&!rt(E)){var T=f;T&&(T=T.slice()).push(m),r(h,E,g+"."+m,s,T,d,u)}}}}))}e.createPayload=function(e,t,i,n,r){return{apiKeys:[],payloadBlob:"",overflow:null,sizeExceed:[],failedEvts:[],batches:[],numEvents:0,retryCnt:e,isTeardown:t,isSync:i,isBeacon:n,sendReason:r}},e.appendPayload=function(i,n,r){var a=i&&n&&!i.overflow;return a&&ii(t,(function(){return"Serializer:appendPayload"}),(function(){for(var t=n.events(),a=i.payloadBlob,s=i.numEvents,o=!1,l=[],c=[],d=i.isBeacon,u=d?65e3:3984588,h=d?is:ts,p=0,g=0;p<t.length;){var m=t[p];if(m){if(s>=r){i.overflow=n.split(p);break}var f=e.getEventBlob(m);if(f&&f.length<=h){var v=f.length;if(a.length+v>u){i.overflow=n.split(p);break}a&&(a+="\n"),a+=f,++g>20&&(a.substr(0,1),g=0),o=!0,s++}else f?l.push(m):c.push(m),t.splice(p,1),p--}p++}if(l&&l.length>0&&i.sizeExceed.push(es.create(n.iKey(),l)),c&&c.length>0&&i.failedEvts.push(es.create(n.iKey(),c)),o){i.batches.push(n),i.payloadBlob=a,i.numEvents=s;var S=n.iKey();-1===dt(i.apiKeys,S)&&i.apiKeys.push(S)}}),(function(){return{payload:i,theBatch:{iKey:n.iKey(),evts:n.events()},max:r}})),a},e.getEventBlob=function(e){try{return ii(t,(function(){return"Serializer.getEventBlob"}),(function(){var t={};t.name=e.name,t.time=e.time,t.ver=e.ver,t.iKey="o:"+function(e){if(e){var t=e.indexOf("-");if(t>-1)return e.substring(0,t)}return""}(e.iKey);var i={},n=e.ext;n&&(t.ext=i,tt(n,(function(e,t){r(t,i[e]={},"ext."+e,!0,null,null,!0)})));var o=t[a]={};o.baseType=e.baseType;var l=o[s]={};return r(e.baseData,l,s,!1,[s],(function(e,t,n){os(i,e,t,n)}),!0),r(e.data,o,a,!1,[],(function(e,t,n){os(i,e,t,n)}),!0),JSON.stringify(t)}),(function(){return{item:e}}))}catch(e){return null}}}))};function os(e,t,i,n){if(n&&e){var r=yn(n.value,n.kind,n.propertyType);if(r>-1){var a=e[ns];a||(a=e[ns]={f:{}});var s=a[rs];if(s||(s=a[rs]={}),t)for(var o=0;o<t.length;o++){var l=t[o];s[l]||(s[l]={f:{}});var c=s[l][rs];c||(c=s[l][rs]={}),s=c}s=s[i]={},rt(n.value)?s.a={t:r}:s.t=r}}}var ls,cs=function(){function e(){}return e.shouldRetryForStatus=function(e){return!(e>=300&&e<500&&408!==e&&429!==e||501===e||505===e)},e.getMillisToBackoffForRetry=function(e){var t,i=Math.floor(1200*Math.random())+2400;return t=Math.pow(2,e)*i,Math.min(t,6e5)},e}(),ds=function e(){var t={};Be(e,this,(function(e){e.setKillSwitchTenants=function(e,i){if(e&&i)try{var n=function(e){var t=[];return e&&ct(e,(function(e){t.push(ut(e))})),t}(e.split(","));if("this-request-only"===i)return n;for(var r=1e3*parseInt(i,10),a=0;a<n.length;++a)t[n[a]]=ft()+r}catch(e){return[]}return[]},e.isTenantKilled=function(e){var i=t,n=ut(e);return void 0!==i[n]&&i[n]>ft()||(delete i[n],!1)}}))},us=function e(){var t=!0,i=!0,n=!0,r="use-collector-delta",a=!1;Be(e,this,(function(e){e.allowRequestSending=function(){return t},e.firstRequestSent=function(){n&&(n=!1,a||(t=!1))},e.shouldAddClockSkewHeaders=function(){return i},e.getClockSkewHeaderValue=function(){return r},e.setClockSkew=function(e){a||(e?(r=e,i=!0,a=!0):i=!1,t=!0)}}))},hs="POST",ps="Microsoft_ApplicationInsights_BypassAjaxInstrumentation",gs="drop",ms="send",fs="requeue",vs="rspFail",Ss="kill-duration",ys="time-delta-millis",Cs=((ls={})[1]=fs,ls[100]=fs,ls[200]="sent",ls[8004]=gs,ls[8003]=gs,ls);function _s(e){try{return e.responseText}catch(e){}return""}var Es=function e(t,i,n,r){this._responseHandlers=[];var a,s,o,l,c,d="?cors=true&content-type=application/x-json-stream&client-id=NO_AUTH&client-version="+un,u=new ds,h=!1,p=new us,g=!1,m=0,f=!0,v=[],S={},y=[],C=null,_=!1;Be(e,this,(function(e){var E=!0;function T(e){for(var t=0,i=null,n=0;null==i&&n<e.length;)1===(t=e[n])?Sn()?i=b:"undefined"!=typeof XMLHttpRequest&&(i=w):2===t?i=I:g&&3===t&&fn()&&(i=A),n++;return i?{_transport:t,sendPOST:i}:null}function b(e,t,i){var n=new XDomainRequest;n.open(hs,e.urlString),n.onload=function(){var e=_s(n);R(t,200,{},e),$(e)},n.onerror=function(){R(t,400,{})},n.ontimeout=function(){R(t,500,{})},n.onprogress=function(){},i?n.send(e.data):a._setTimeoutOverride((function(){n.send(e.data)}),0)}function I(e,t){var i,n=((i={body:e.data,method:hs})[ps]=!0,i);E&&(n.credentials="include"),e.headers&&gt(e.headers).length>0&&(n.headers=e.headers),fetch(e.urlString,n).then((function(e){var i={},n="";e.headers&&e.headers.forEach((function(e,t){i[t]=e})),e.body&&e.text().then((function(e){n=e})),R(t,e.status,i,n),$(n)})).catch((function(e){R(t,0,{})}))}function w(e,t,i){function n(e,t,i){if(!e[i]&&t&&t.getResponseHeader){var n=t.getResponseHeader(i);n&&(e[i]=ut(n))}return e}function r(e){var t={};return e.getAllResponseHeaders?t=function(e){var t={};return at(e)&&ct(ut(e).split(/[\r\n]+/),(function(e){if(e){var i=e.indexOf(": ");if(-1!==i){var n=ut(e.substring(0,i)).toLowerCase(),r=ut(e.substring(i+1));t[n]=r}else t[ut(e)]=1}})),t}(e.getAllResponseHeaders()):(t=n(t,e,ys),t=n(t,e,Ss),t=n(t,e,"kill-duration-seconds")),t}function a(e,i){R(t,e.status,r(e),i)}var s=new XMLHttpRequest;try{s[ps]=!0}catch(e){}E&&(s.withCredentials=!0),s.open(hs,e.urlString,!i),tt(e.headers,(function(e,t){s.setRequestHeader(e,t)})),s.onload=function(){var e=_s(s);a(s,e),$(e)},s.onerror=function(){a(s)},s.ontimeout=function(){a(s)},s.send(e.data)}function R(e,t,i,n){try{e(t,i,n)}catch(e){a.diagLog().throwInternal(we.WARNING,dn.SendPostOnCompleteFailure,qt(e))}}function A(e,t,i){var n=200,r=e._thePayload;try{var s=Ht();if(!s.sendBeacon(e.urlString,e.data))if(r){var o=[];ct(r.batches,(function(t){if(o&&t&&t.count()>0){for(var i=t.events(),n=0;n<i.length;n++)if(!s.sendBeacon(e.urlString,C.getEventBlob(i[n]))){o.push(t.split(n));break}}else o.push(t.split(0))})),G(o,8003,r.isSync,!0)}else n=0}catch(e){a.diagLog().warnToConsole("Failed to send telemetry using sendBeacon API. Ex:"+e),n=0}finally{R(t,n,{},"")}}function P(){return!h&&m<i}function M(){var e=y;return y=[],e}function k(e,t,i){var n=!1;return e&&e.length>0&&!h&&s&&C&&(n=t||P()&&(i>0||p.allowRequestSending())),n}function D(e){var t={};return e&&ct(e,(function(e,i){t[i]={iKey:e.iKey(),evts:e.events()}})),t}function O(e,i,n,r,o,c){if(e&&0!==e.length)if(h)G(e,1,r);else try{var d=e;ii(l,(function(){return"HttpManager:_sendBatches"}),(function(a){a&&(e=e.slice(0));for(var l=[],d=null,h=Tn(),p=(c||s&&3===s._transport)&&L();k(e,r,i);){var g=e.shift();g&&g.count()>0&&(u.isTenantKilled(g.iKey())?l.push(g):(d=d||C.createPayload(i,n,r,p,o),C.appendPayload(d,g,t)?null!==d.overflow&&(e=[d.overflow].concat(e),d.overflow=null,F(d,h,Tn(),o),h=Tn(),d=null):(F(d,h,Tn(),o),h=Tn(),e=[g].concat(e),d=null)))}d&&F(d,h,Tn(),o),e.length>0&&(y=e.concat(y)),G(l,8004,r)}),(function(){return{batches:D(d),retryCount:i,isTeardown:n,isSynchronous:r,sendReason:o,useSendBeacon:c}}),!r)}catch(e){a.diagLog().throwInternal(we.WARNING,dn.CannotSerializeObject,"Unexpected Exception sending batch: "+qt(e))}}function N(e){var t=d,i="";ct(e.apiKeys,(function(e){i.length>0&&(i+=","),i+=e})),i.length>0&&(t+="&apikey="+i),t+="&upload-time="+ft().toString();var n=function(e){for(var t=0;t<e.batches.length;t++)for(var i=e.batches[t].events(),n=0;n<i.length;n++){var r=(i[n].ext||{}).intweb||{};if(mn(r.msfpc))return encodeURIComponent(r.msfpc)}return""}(e);if(mn(n)&&(t=t+"&ext.intweb.msfpc="+n),p.shouldAddClockSkewHeaders()&&(t+="&time-delta-to-apply-millis="+p.getClockSkewHeaderValue()),l.getWParam){var r=l.getWParam();r>=0&&(t+="&w="+r)}for(var a=0;a<v.length;a++)t+="&"+v[a].name+"="+v[a].value;return t}function L(){return!f&&g&&fn()}function x(e,t,i){e[t]=e[t]||{},e[t][a.identifier]=i}function F(t,i,n,r){if(t&&t.payloadBlob&&t.payloadBlob.length>0){var c=N(t),d=Tn(),u="sendAttempt";ii(l,(function(){return"HttpManager:_doPayloadSend"}),(function(){for(var h=0;h<t.batches.length;h++)for(var g=t.batches[h].events(),v=0;v<g.length;v++){var y=g[v];if(_){var C=y.timings=y.timings||{};x(C,"sendEventStart",d),x(C,"serializationStart",i),x(C,"serializationCompleted",n)}y[u]>0?y[u]++:y[u]=1}G(t.batches,1e3+(r||0),t.isSync,!0);var E={data:t.payloadBlob,urlString:c,headers:En({},S),_thePayload:t,_sendReason:r},T=null,b=!!e.sendHook,I=s;o&&t.isBeacon&&2===t.sendReason&&(I=o),I&&(T=function(i){p.firstRequestSent();var n=function(e,i){U(e,i,t,r)};try{I.sendPOST(i,n,t.isTeardown||t.isSync),e.sendListener&&e.sendListener(E,i,t.isSync||t.isTeardown,t.isBeacon)}catch(e){a.diagLog().warnToConsole("Unexpected exception sending payload. Ex:"+qt(e)),R(n,0,{})}}),ii(l,(function(){return"HttpManager:_doPayloadSend.sender"}),(function(){if(T)if(t.isSync||t.isBeacon||m++,b&&!t.isBeacon&&3!==I._transport){var i={data:E.data,urlString:E.urlString,headers:E.headers},n=!1;ii(l,(function(){return"HttpManager:_doPayloadSend.sendHook"}),(function(){try{e.sendHook(i,(function(e){n=!0,f||e._thePayload||(e._thePayload=e._thePayload||E._thePayload,e._sendReason=e._sendReason||E._sendReason),T(e)}),t.isSync||t.isTeardown)}catch(e){n||T(E)}}))}else T(E)}))}),(function(){return{thePayload:t,serializationStart:i,serializationCompleted:n,sendReason:r}}),t.isSync)}t.sizeExceed&&t.sizeExceed.length>0&&G(t.sizeExceed,8003,t.isSync),t.failedEvts&&t.failedEvts.length>0&&G(t.failedEvts,8002,t.isSync)}function U(e,t,i,r){var a=9e3,s=null,o=!1,l=!1;try{var c=!0;if(typeof e!==B){if(t){p.setClockSkew(t[ys]);var d=t[Ss]||t["kill-duration-seconds"];ct(u.setKillSwitchTenants(t["kill-tokens"],d),(function(e){ct(i.batches,(function(t){if(t.iKey()===e){s=s||[];var n=t.split(0);i.numEvents-=n.count(),s.push(n)}}))}))}if(200===e)return void(a=200);(!cs.shouldRetryForStatus(e)||i.numEvents<=0)&&(c=!1),a=9e3+e%1e3}if(c){a=100;var h=i.retryCnt;i.isSync||i.isBeacon||(h<n?(o=!0,H((function(){i.isSync||i.isBeacon||m--,O(i.batches,h+1,i.isTeardown,i.isSync,5,i.isBeacon)}),!0,cs.getMillisToBackoffForRetry(h))):l=!0)}}finally{o||(p.setClockSkew(),V(i,a,r,l)),G(s,8004,i.isSync)}}function V(t,i,n,r){try{r&&a._backOffTransmission(),200===i&&(r||t.isSync||a._clearBackOff(),function(e){if(_){var t=Tn();ct(e,(function(e){e&&e.count()>0&&function(e,t){_&&ct(e,(function(e){x(e.timings=e.timings||{},"sendEventCompleted",t)}))}(e.events(),t)}))}}(t.batches)),G(t.batches,i,t.isSync,!0)}finally{t.isSync||t.isBeacon||(m--,5!==n&&e.sendQueuedRequests(n,!t.isSync,t.isBeacon))}}function H(e,t,i){t?e():a._setTimeoutOverride(e,i)}function $(t){var i=e._responseHandlers;try{for(var n=0;n<i.length;n++)try{i[n](t)}catch(t){a.diagLog().throwInternal(we.CRITICAL,dn.PostResponseHandler,"Response handler failed: "+t)}if(t){var r=JSON.parse(t);mn(r.webResult)&&mn(r.webResult.msfpc)&&c.set("MSFPC",r.webResult.msfpc,31536e3)}}catch(t){}}function G(e,t,i,n){if(e&&e.length>0&&r){var s=r[function(e){var t=Cs[e];return mn(t)||(t="oth",e>=9e3&&e<=9999?t=vs:e>=8e3&&e<=8999?t=gs:e>=1e3&&e<=1999&&(t=ms)),t}(t)];s&&ii(l,(function(){return"HttpManager:_sendBatchesNotification"}),(function(){H((function(){try{s.call(r,e,t,i)}catch(e){a.diagLog().throwInternal(we.CRITICAL,dn.NotificationException,"send request notification failed: "+e)}}),n||i,0)}),(function(){return{batches:D(e),reason:t,isSync:i,sendSync:n}}),!i)}}e.initialize=function(e,t,i,n,r){r||(r={}),d=e+d,l=t,c=t.getCookieMgr(),_=!l.config.disableEventTimings;var u=!!l.config.enableCompoundKey;a=i;var h=r.valueSanitizer,p=r.stringifyObjects;if(Ke(r.enableCompoundKey)||(u=!!r.enableCompoundKey),g=!zt(),C=new ss(l,h,p,u),o=T([3]),!(s=n)){f=!1;var m=$t();m&&m.protocol&&"file:"===m.protocol.toLowerCase()&&(E=!1);var v=[];v=zt()?[2,1]:[1,2,3];var S=r.transports;S&&(st(S)?v=[S].concat(v):rt(S)&&(v=S.concat(v))),(s=T(v))||a.diagLog().warnToConsole("No available transport to send events")}},e._getDbgPlgTargets=function(){return[s,u,C]},e.addQueryStringParameter=function(e,t){for(var i=0;i<v.length;i++)if(v[i].name===e)return void(v[i].value=t);v.push({name:e,value:t})},e.addHeader=function(e,t){S[e]=t},e.canSendRequest=function(){return P()&&p.allowRequestSending()},e.sendQueuedRequests=function(e,t,i){var n=!Je(t)&&!t;k(y,n,0)&&O(M(),0,!1,n,e||0,!!i)},e.isCompletelyIdle=function(){return!h&&0===m&&0===y.length},e.addBatch=function(e){if(e&&e.count()>0){if(u.isTenantKilled(e.iKey()))return!1;y.push(e)}return!0},e.teardown=function(){y.length>0&&O(M(),0,!0,!0,2,!0)},e.pause=function(){h=!0},e.resume=function(){h=!1,e.sendQueuedRequests(4,!1)},e.sendSynchronousBatch=function(e,t,i){e&&e.count()>0&&O([e],0,!1,!0,t||0,!!i)}}))},Ts=gn?window:void 0,bs="eventsDiscarded",Is="overrideInstrumentationKey",ws=function(e){function t(){var i,n=e.call(this)||this;n.identifier="PostChannel",n.priority=1011,n.version="3.1.2";var r,a,s,o,l,c=!1,d=[],u=null,h=!1,p=0,g=500,m=0,f=1e4,v={},S=Xa,y=null,C=null,_=0,E=0,T={},b=-1,I=!0;return Be(t,n,(function(e,t){function n(e,t){if(e.sendAttempt||(e.sendAttempt=0),e.latency||(e.latency=an),e.ext&&e.ext.trace&&delete e.ext.trace,e.ext&&e.ext.user&&e.ext.user.id&&delete e.ext.user.id,I&&(e.ext=Et(e.ext),e.baseData&&(e.baseData=Et(e.baseData)),e.data&&(e.data=Et(e.data))),e.sync)if(_||h)e.latency=on,e.sync=!1;else if(a)return I&&(e=Et(e)),void a.sendSynchronousBatch(es.create(e.iKey,[e]),3);var i=e.latency,n=m,r=f;i===ln&&(n=p,r=g);var s=!1;if(n<r)s=!N(e,t);else{var o=an,l=20;i===ln&&(o=ln,l=1),s=!0,function(e,t,i,n){for(;i<=t;){var r=D(e,t,!0);if(r&&r.count()>0){var a=r.split(0,n),s=a.count();if(s>0)return i===ln?p-=s:m-=s,$(bs,[a],ae),!0}i++}return L(),!1}(e.iKey,e.latency,o,l)&&(s=!N(e,t))}s&&H(bs,[e],ae)}function w(e,t,i,n){var r=x(e,t,i);return a.sendQueuedRequests(t,i,n),r}function R(){return m>0}function A(){if(b>=0&&x(b,l,!0)&&a.sendQueuedRequests(l,!0,!1),p>0&&!C&&!h){var e=v[S][2];e>=0&&(C=P((function(){C=null,w(ln,1,!0),A()}),e))}var t=v[S][1];!y&&!u&&t>=0&&!h&&(R()?y=P((function(){y=null,w(0===E?on:an,1,!0),E++,E%=2,A()}),t):E=0)}function P(t,i){0===i&&_&&(i=1);var n=1e3;return _&&(n=cs.getMillisToBackoffForRetry(_-1)),e._setTimeoutOverride(t,i*n)}function M(){null!==y&&(e._clearTimeoutOverride(y),y=null,E=0)}function k(t,i){M(),u&&(e._clearTimeoutOverride(u),u=null),h||w(an,t,i,!0)}function D(e,t,i){var n=T[t];n||(n=T[t=an]);var r=n.iKeyMap[e];return!r&&i&&(r=es.create(e),n.batches.push(r),n.iKeyMap[e]=r),r}function O(t,i){a.canSendRequest()&&!_&&(s>0&&m>s&&(i=!0),i&&null==u&&e.flush(t,null,20))}function N(e,t){I&&(e=Et(e));var i=e.latency,n=D(e.iKey,i,!0);return!!n.addEvents([e],t)&&(i!==ln?(m++,t&&0===e.sendAttempt&&O(!e.sync,o>0&&n.count()>=o)):p++,!0)}function L(){for(var e=0,t=0,i=function(i){var n=T[i];n&&n.batches&&ct(n.batches,(function(n){i===ln?e+=n.count():t+=n.count()}))},n=an;n<=ln;n++)i(n);m=t,p=e}function x(t,i,n){var r=!1;return!n||a.canSendRequest()?ii(e.core,(function(){return"PostChannel._queueBatches"}),(function(){for(var e=[],i=ln;i>=t;){var n=T[i];n&&n.batches&&(ct(n.batches,(function(t){a.addBatch(t)?r=r||t&&t.count()>0:e=e.concat(t.events()),i===ln?p-=t.count():m-=t.count()})),n.batches=[],n.iKeyMap={}),i--}e.length>0&&H(bs,e,re),r&&b>=t&&(b=-1,l=0)}),(function(){return{latency:t,sendReason:i}}),n):(b=b>=0?Math.min(b,t):t,l=Math.max(l,i)),r}function F(e,t){w(an,t,!0),U((function(){e&&e(),d.length>0?u=P((function(){return F(d.shift(),t)}),0):(u=null,R()&&A())}))}function U(e){a.isCompletelyIdle()?e():u=P((function(){U(e)}),.25)}function B(){(v={})[Xa]=[2,1,0],v.NEAR_REAL_TIME=[6,3,0],v.BEST_EFFORT=[18,9,0]}function V(t,i){var n=e._notificationManager||{},r=n[t];if(r)try{r.apply(n,i)}catch(i){e.diagLog().throwInternal(we.CRITICAL,dn.NotificationException,t+" notification failed: "+i)}}function H(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t.length>0&&V(e,[t].concat(i))}function $(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t&&t.length>0&&ct(t,(function(t){t&&t.count()>0&&V(e,[t.events()].concat(i))}))}function G(){o=i&&i.disableAutoBatchFlushLimit?0:Math.max(1500,f/6)}B(),T[ln]={batches:[],iKeyMap:{}},T[on]={batches:[],iKeyMap:{}},T[sn]={batches:[],iKeyMap:{}},T[an]={batches:[],iKeyMap:{}},G(),a=new Es(500,2,1,{requeue:function(t,i){var r=[];ct(t,(function(t){t&&t.count()>0&&ct(t.events(),(function(t){t&&(t.sync&&(t.latency=on,t.sync=!1),t.sendAttempt<6?(bn(t,e.identifier),n(t,!1)):r.push(t))}))})),r.length>0&&H(bs,r,ie)},send:function(e,t,i){e&&e.length>0&&V("eventsSendRequest",[t>=1e3&&t<=1999?t-1e3:0,!0!==i])},sent:function(e,t){$("eventsSent",e,t),A()},drop:function(e,t){$(bs,e,t>=8e3&&t<=8999?t-8e3:te)},rspFail:function(e){$(bs,e,ie),A()},oth:function(e,t){$(bs,e,te),A()}}),e._getDbgPlgTargets=function(){return[a]},e.initialize=function(n,o,l){ii(o,(function(){return"PostChannel:initialize"}),(function(){var c=o;t.initialize(n,o,l),e.setInitialized(!1);var d=e._getTelCtx();n.extensionConfig[e.identifier]=n.extensionConfig[e.identifier]||{},i=d.getExtCfg(e.identifier),e._setTimeoutOverride=i.setTimeoutOverride?i.setTimeoutOverride:setTimeout.bind(Ts),e._clearTimeoutOverride=i.clearTimeoutOverride?i.clearTimeoutOverride:clearTimeout.bind(Ts),I=!i.disableOptimizeObj&&!!xt("chrome");var u=c.getWParam;c.getWParam=function(){var e=0;return i.ignoreMc1Ms0CookieProcessing&&(e|=2),e|u()},i.eventsLimitInMem>0&&(f=i.eventsLimitInMem),i.immediateEventLimit>0&&(g=i.immediateEventLimit),i.autoFlushEventsLimit>0&&(s=i.autoFlushEventsLimit),G(),i.httpXHROverride&&i.httpXHROverride.sendPOST&&(r=i.httpXHROverride),mn(n.anonCookieName)&&a.addQueryStringParameter("anoncknm",n.anonCookieName),a.sendHook=i.payloadPreprocessor,a.sendListener=i.payloadListener;var h=i.overrideEndpointUrl?i.overrideEndpointUrl:n.endpointUrl;e._notificationManager=n.extensionConfig.NotificationManager,a.initialize(h,e.core,e,r,i),function(e){var t=Qi("beforeunload",e);t=Qi("unload",e)||t,Qi("pagehide",e)}((function(){k(2,!1)})),e.setInitialized(!0)}),(function(){return{coreConfig:n,core:o,extensions:l}}))},e.processTelemetry=function(t,r){bn(t,e.identifier);var a=(r=e._getTelCtx(r)).getExtCfg(e.identifier),s=!!i.disableTelemetry;a&&(s=s||!!a.disableTelemetry);var o=t;s||c||(i[Is]&&(o.iKey=i[Is]),a&&a[Is]&&(o.iKey=a[Is]),n(o,!0),A()),e.processNext(o,r)},e.setEventQueueLimits=function(e,t){f=e>0?e:1e4,s=t>0?t:0,G();var i=m>e;if(!i&&o>0)for(var n=an;!i&&n<=on;n++){var r=T[n];r&&r.batches&&ct(r.batches,(function(e){e&&e.count()>=o&&(i=!0)}))}O(!0,i)},e.teardown=function(){k(2,!1),c=!0,a.teardown()},e.pause=function(){M(),h=!0,a.pause()},e.resume=function(){h=!1,a.resume(),A()},e.addResponseHandler=function(e){a._responseHandlers.push(e)},e._loadTransmitProfiles=function(e){M(),B(),S=Xa,A(),tt(e,(function(e,t){var i=t.length;if(i>=2){var n=i>2?t[2]:0;if(t.splice(0,i-2),t[1]<0&&(t[0]=-1),t[1]>0&&t[0]>0){var r=t[0]/t[1];t[0]=Math.ceil(r)*t[1]}n>=0&&t[1]>=0&&n>t[1]&&(n=t[1]),t.push(n),v[e]=t}}))},e.flush=function(e,t,i){void 0===e&&(e=!0),h||(M(),i=i||1,e?(x(an,i,e),L(),null==u?u=P((function(){F(t,i)}),0):d.push(t)):(w(an,i,!1),null!=t&&t()))},e.setMsaAuthTicket=function(e){a.addHeader("AuthMsaDeviceTicket",e)},e.hasEvents=R,e._setTransmitProfile=function(e){S!==e&&void 0!==v[e]&&(M(),S=e,A())},e._backOffTransmission=function(){_<4&&(_++,M(),A())},e._clearBackOff=function(){_&&(_=0,M(),A())}})),n}return Za(t,e),t}(li),Rs=["AX","EX","SF","CS","CF","CT","CU","DC","DF","H5","HL","WS","WP"];function As(e,t){void 0===t&&(t=Rs);var i=null;if(e)for(var n=e.split(","),r=0;r<n.length;r++)Ps(n[r],t)&&(i?i+=","+n[r]:i=n[r]);return i}function Ps(e,t){if(void 0===t&&(t=Rs),!e||e.length<4)return!1;for(var i=!1,n=e.substring(0,3).toString().toUpperCase(),r=0;r<t.length;r++)if(t[r]+":"===n&&e.length<=256){i=!0;break}return i}var Ms=function(){function e(e,t){this.core=t,this.appExpId=null,this.flightIdNameSpaces=Rs.slice(0),this.expIdCookieName="Treatments",this._cookieMgr=Di(t),this._propertiesConfig=e;var i=Bt();if(i){var n=i.documentElement;i&&(this.locale=n.lang)}this.env=e.env?e.env:this._getMetaDataFromDOM("awa-").env}return e.prototype.getExpId=function(){return this._propertiesConfig.expId?this._readExpIdFromCoreData(this._propertiesConfig.expId):this._readExpIdFromCookie()},e.prototype._getMetaDataFromDOM=function(e){var t,i={},n=Bt();if(n){t=n&&n.querySelectorAll("meta");for(var r=0;r<t.length;r++){var a=t[r];a.name&&0===a.name.toLowerCase().indexOf(e)&&(i[a.name.replace(e,"")]=a.content)}}return i},e.prototype._setAppExpId=function(e){e!==this.appExpId&&(this.appExpId=As(e,this.flightIdNameSpaces))},e.prototype._getAppExpId=function(){return this.appExpId},e.prototype._readExpIdFromCookie=function(){var e=Cn(this._cookieMgr,this.expIdCookieName);return this._setAppExpId(e),this._getAppExpId()},e.prototype._readExpIdFromCoreData=function(e){return this._setAppExpId(e),this._getAppExpId()},e.validateAppExpId=As,e._staticInit=void mt(e.prototype,"expId",e.prototype.getExpId),e}(),ks=function(){},Ds=function(){function e(t,i,n){this.core=n;var r=this._cookieMgr=Di(n,t);if(r&&r.isEnabled()){var a=Cn(r,"MUID");if(a&&this.setLocalId("t:"+a),i.enableApplicationInsightsUser){var s=Cn(r,e.userCookieName);if(s){var o=s.split(e.cookieSeparator);o.length>0&&(this.id=o[0])}if(!this.id){this.id=Xi(t&&!Ke(t.idLength)?t.idLength:22);var l=lt(new Date);this.accountAcquisitionDate=l;var c=[this.id,l],d=i.cookieDomain?i.cookieDomain:void 0;r.set(e.userCookieName,c.join(e.cookieSeparator),31536e3,d)}}}if("undefined"!=typeof navigator){var u=navigator;this.locale=u.userLanguage||u.language}}return e.prototype.getLocalId=function(){if(this._customLocalId)return this._customLocalId;var e=Cn(this._cookieMgr,"MUID");e&&this.setLocalId("t:"+e)},e.prototype.setLocalId=function(e){this._customLocalId=e},e.cookieSeparator="|",e.userCookieName="ai_user",e._staticInit=void mt(e.prototype,"localId",e.prototype.getLocalId,e.prototype.setLocalId),e}(),Os="MSIE",Ns="Chrome",Ls="Firefox",xs="Safari",Fs="Edge",Us="Electron",Bs="SkypeShell",Vs="PhantomJS",Hs="Opera",$s="([\\d,.]+)",Gs="Unknown",js="Edg/",zs=function(){function e(e,t){this._cookieMgr=Di(t),this._propertiesConfig=e;var i=$t();if(i){var n=i.hostname;n&&(this.domain="file:"===i.protocol?"local":n)}var r="undefined"!=typeof navigator?navigator.userAgent:"";if(e.userAgent&&(r=e.userAgent),e.populateBrowserInfo){if(r){var a=this._getBrowserName(r);this.browser=a,this.browserVer=this._getBrowserVersion(r,a)}var s=this._getScreenResolution();this.screenRes=s.w+"X"+s.h}}return e.prototype.getUserConsent=function(){return this._propertiesConfig.userConsented||!!Cn(this._cookieMgr,this._propertiesConfig.userConsentCookieName||"MSCC")},e.prototype.getUserConsentDetails=function(){try{if(this._propertiesConfig.callback&&this._propertiesConfig.callback.userConsentDetails){var e=this._propertiesConfig.callback.userConsentDetails();if(e)return JSON.stringify({Required:!!e.Required&&e.Required,Analytics:!!e.Analytics&&e.Analytics,SocialMedia:!!e.SocialMedia&&e.SocialMedia,Advertising:!!e.Advertising&&e.Advertising})}}catch(e){}return null},e.prototype._getBrowserName=function(e){return this._userAgentContainsString("OPR/",e)?Hs:this._userAgentContainsString(Vs,e)?Vs:this._userAgentContainsString(Fs,e)||this._userAgentContainsString(js,e)?Fs:this._userAgentContainsString(Us,e)?Us:this._userAgentContainsString(Ns,e)?Ns:this._userAgentContainsString("Trident",e)?Os:this._userAgentContainsString(Ls,e)?Ls:this._userAgentContainsString(xs,e)?xs:this._userAgentContainsString(Bs,e)?Bs:Gs},e.prototype._userAgentContainsString=function(e,t){return t.indexOf(e)>-1},e.prototype._getBrowserVersion=function(e,t){return t===Os?this._getIeVersion(e):this._getOtherVersion(t,e)},e.prototype._getIeVersion=function(e){var t=e.match(new RegExp(Os+" "+$s));if(t)return t[1];var i=e.match(new RegExp("rv:"+$s));return i?i[1]:void 0},e.prototype._getOtherVersion=function(e,t){e===xs?e="Version":e===Fs&&this._userAgentContainsString(js,t)&&(e="Edg");var i=t.match(new RegExp(e+"/"+$s));return i?i[1]:Gs},e.prototype._getScreenResolution=function(){var e={h:0,w:0},t=Ut();return t&&t.screen&&(e.h=screen.height,e.w=screen.width),e},e._staticInit=void mt(e.prototype,"userConsent",e.prototype.getUserConsent),e}(),Ws="Windows",qs="Mac OS X",Ks="Android",Js="iOS",Ys=/(windows|win32)/i,Qs=/ arm;/i,Zs=/windows\sphone\s\d+\.\d+/i,Xs=/(macintosh|mac os x)/i,eo=/(ipad|iphone|ipod)(?=.*like mac os x)/i,to=/(linux|joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)/i,io=/android/i,no=/CrOS/i,ro={5.1:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1","10.0":"10"},ao="([\\d,_,.]+)",so="Unknown",oo=function(){function e(e){var t="undefined"!=typeof navigator?navigator.userAgent:"";if(e.userAgent&&(t=e.userAgent),t&&e.populateOperatingSystemInfo){var i=this._getOsName(t.toLowerCase());this.name=i,this.ver=this._getOsVersion(t,i)}}return e.prototype._getOsName=function(e){return e.match(Zs)?"Windows Phone":e.match(Qs)?"Windows RT":e.match(Ys)?Ws:e.match(eo)?Js:e.match(io)?Ks:e.match(to)?"Linux":e.match(no)?"Chrome OS":-1!==e.indexOf("x11")?"Unix":-1!==e.indexOf("blackberry")?"BlackBerry":-1!==e.indexOf("symbian")?"Symbian":-1!==e.indexOf("nokia")?"Nokia":e.match(Xs)?qs:so},e.prototype._getOsVersion=function(e,t){return t===Ws?this._getGenericOsVersion(e,"Windows NT"):t===Ks?this._getGenericOsVersion(e,t):t===qs?this._getMacOsxVersion(e):t===Js?this._getIosVersion(e):so},e.prototype._getGenericOsVersion=function(e,t){var i=e.match(new RegExp(t+" ([\\d,.]+)"));return i?ro[i[1]]?ro[i[1]]:i[1]:so},e.prototype._getMacOsxVersion=function(e){var t=e.match(new RegExp(qs+" "+ao));if(t){var i=t[1].replace(/_/g,".");if(i){var n=this._getDelimiter(i);return n?i.split(n)[0]:i}}return so},e.prototype._getIosVersion=function(e){var t=e.match(new RegExp("OS "+ao));if(t){var i=t[1].replace(/_/g,".");if(i){var n=this._getDelimiter(i);return n?i.split(n)[0]:i}}return so},e.prototype._getDelimiter=function(e){return e.indexOf(".")>-1?".":e.indexOf("_")>-1?"_":null},e}(),lo=function(){function e(e,t){this.core=t,e.serviceName&&(this.serviceName=e.serviceName),this._cookieMgr=Di(t)}return e.prototype.getMsfpc=function(){return Cn(this._cookieMgr,"MSFPC")},e.prototype.getAnid=function(){return Cn(this._cookieMgr,"ANON").slice(0,34)},e._staticInit=(mt(e.prototype,"msfpc",e.prototype.getMsfpc),void mt(e.prototype,"anid",e.prototype.getAnid)),e}(),co=function(e){this.popSample=100,this.eventFlags=0,e.hashIdentifiers&&(this.eventFlags=1048576|this.eventFlags),e.dropIdentifiers&&(this.eventFlags=2097152|this.eventFlags)},uo=function(){var e=(new Date).getTimezoneOffset(),t=e%60,i=(e-t)/60,n="+";i>0&&(n="-"),i=Math.abs(i),t=Math.abs(t),this.tz=n+(i<10?"0"+i:i.toString())+":"+(t<10?"0"+t:t.toString())},ho=function(){},po=function(){function e(){}return e.prototype.setId=function(e){this.customId=e},e.prototype.getId=function(){return at(this.customId)?this.customId:this.automaticId},e._staticInit=void mt(e.prototype,"id",e.prototype.getId,e.prototype.setId),e}(),go=function(e,t,i,n){if(e.enableApplicationInsightsTrace){this.traceId=t||function(){for(var e,t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],i="",n=0;n<4;n++)i+=t[15&(e=Yi())]+t[e>>4&15]+t[e>>8&15]+t[e>>12&15]+t[e>>16&15]+t[e>>20&15]+t[e>>24&15]+t[e>>28&15];var r=t[8+(3&Yi())|0];return i.substr(0,8)+i.substr(9,4)+"4"+i.substr(13,3)+r+i.substr(16,3)+i.substr(19,12)}(),this.parentId=i,this.name=n;var r=$t();r&&r.pathname&&(this.name=r.pathname)}},mo=function(){function e(){}return e.id="id",e.ver="ver",e.appName="name",e.locale="locale",e.expId="expId",e.env="env",e}(),fo=function(){function e(){}return e.domain="domain",e.browser="browser",e.browserVer="browserVer",e.screenRes="screenRes",e.userConsent="userConsent",e.consentDetails="consentDetails",e}(),vo=function(){function e(){}return e.locale="locale",e.localId="localId",e.id="id",e}(),So=function(){function e(){}return e.osName="name",e.ver="ver",e}(),yo=function(){function e(){}return e.ver="ver",e.seq="seq",e.installId="installId",e.epoch="epoch",e}(),Co=function(){function e(){}return e.msfpc="msfpc",e.anid="anid",e.serviceName="serviceName",e}(),_o=function(){function e(){}return e.popSample="popSample",e.eventFlags="eventFlags",e}(),Eo=function(){function e(){}return e.tz="tz",e}(),To=function(){function e(){}return e.sessionId="sesId",e}(),bo=function(){function e(){}return e.localId="localId",e.deviceClass="deviceClass",e.make="make",e.model="model",e}(),Io=function(){function e(){}return e.role="role",e.roleInstance="roleInstance",e.roleVer="roleVer",e}(),wo=function(){function e(){}return e.traceId="traceID",e.traceName="name",e.parentId="parentID",e}(),Ro=function(){function e(){}return e.UserExt="user",e.DeviceExt="device",e.TraceExt="trace",e.WebExt="web",e.AppExt="app",e.OSExt="os",e.SdkExt="sdk",e.IntWebExt="intweb",e.UtcExt="utc",e.LocExt="loc",e.CloudExt="cloud",e}(),Ao="MicrosoftApplicationsTelemetryDeviceId";var Po,Mo,ko=function(){function e(e,t){this._sequenceId=0;var i=e.propertyStorageOverride;this.seq=this._sequenceId,this.epoch=Yi(!1).toString();var n=Di(t,e);if(n.isEnabled()||i){var r=function(e,t,i){return t?t.getProperty(i)||"":Cn(e,i)}(n,i,Ao);r||(r=Zi()),function(e,t,i,n){t?t.setProperty(i,n):e.set(i,n,31536e3)}(n,i,Ao,r),this.installId=r}else n.purge(Ao)}return e.prototype.getSequenceId=function(){return++this._sequenceId},e}();function Do(){return void 0===Po&&(Po=!!No(Mo.LocalStorage)),Po}function Oo(){return Do()?No(Mo.LocalStorage):null}function No(e){var t,i,n=null;try{var r=K();if(!r)return null;i=new Date,(n=e===Mo.LocalStorage?r.localStorage:r.sessionStorage)&&Ze(n.setItem)&&(n.setItem(i,i),t=n.getItem(i)!==i,n.removeItem(i),t&&(n=null))}catch(e){n=null}return n}!function(e){e[e.LocalStorage=0]="LocalStorage",e[e.SessionStorage=1]="SessionStorage"}(Mo||(Mo={}));var Lo=function(){function e(t,i){var n,r,a=Yt(t),s=Di(t);Be(e,this,(function(t){var o=function(e){return{sessionRenewalMs:e.sessionRenewalMs&&function(){return e.sessionRenewalMs},sessionExpirationMs:e.sessionExpirationMs&&function(){return e.sessionExpirationMs},cookieDomain:e.cookieDomain&&function(){return e.cookieDomain},namePrefix:e.namePrefix&&function(){return e.namePrefix},sessionAsGuid:function(){return e.sessionAsGuid},idLength:function(){return e.idLength?e.idLength:22}}}(i);function l(){var e=function(e){return Ni(null)?Cn(Di(null),e):""}(r());if(e&&Ze(e.split))c(e);else{var i=function(e,t){var i=Oo();if(null!==i)try{return i.getItem(t)}catch(t){Po=!1,e.throwInternal(we.CRITICAL,dn.BrowserCannotReadLocalStorage,"Browser failed read of local storage. "+t)}return null}(a,r());i&&c(i)}t.automaticSession.getId()||d()}function c(e){var i=t.automaticSession,n=e.split("|");n.length>0&&i.setId(n[0]);try{if(n.length>1){var r=+n[1];i.acquisitionDate=+new Date(r),i.acquisitionDate=i.acquisitionDate>0?i.acquisitionDate:0}if(n.length>2){var s=+n[2];i.renewalDate=+new Date(s),i.renewalDate=i.renewalDate>0?i.renewalDate:0}}catch(e){a.throwInternal(we.CRITICAL,dn.ErrorParsingAISessionCookie,"Error parsing ai_session cookie, session will be reset: "+e)}0===i.renewalDate&&a.throwInternal(we.WARNING,dn.SessionRenewalDateIsZero,"AI session renewal date is 0, session will be reset.")}function d(){var e=t.automaticSession,i=(new Date).getTime(),n=t.config.sessionAsGuid();!Ke(n)&&n?ot(n)?e.setId(_n()):e.setId(_n(n)):e.setId(Xi(o&&o.idLength?o.idLength():22)),e.acquisitionDate=i,e.renewalDate=i,u(e.getId(),e.acquisitionDate,e.renewalDate),Do()||a.throwInternal(we.WARNING,dn.BrowserDoesNotSupportLocalStorage,"Browser does not support local storage. Session durations will be inaccurate.")}function u(e,i,a){var o=i+t.config.sessionExpirationMs(),l=a+t.config.sessionRenewalMs(),c=new Date,d=[e,i,a];o<l?c.setTime(o):c.setTime(l);var u=t.config.cookieDomain?t.config.cookieDomain():null;s.set(r(),d.join("|")+";expires="+c.toUTCString(),null,u),n=(new Date).getTime()}function h(e,t,i){!function(e,t,i){var n=Oo();if(null!==n)try{return n.setItem(t,i),!0}catch(t){Po=!1,e.throwInternal(we.CRITICAL,dn.BrowserCannotWriteLocalStorage,"Browser failed write to local storage. "+t)}}(a,r(),[e,t,i].join("|"))}Ze(i.sessionExpirationMs)||(o.sessionExpirationMs=function(){return e.acquisitionSpan}),Ze(i.sessionRenewalMs)||(o.sessionRenewalMs=function(){return e.renewalSpan}),t.config=o,r=function(){return t.config.namePrefix&&t.config.namePrefix()?e.cookieNameConst+t.config.namePrefix():e.cookieNameConst},t.automaticSession=new po,t.update=function(){t.automaticSession.getId()||l();var i=t.automaticSession,r=t.config,a=(new Date).getTime(),s=a-i.acquisitionDate>r.sessionExpirationMs(),o=a-i.renewalDate>r.sessionRenewalMs();s||o?d():(!n||a-n>e.cookieUpdateInterval)&&(i.renewalDate=a,u(i.getId(),i.acquisitionDate,i.renewalDate))},t.backup=function(){var e=t.automaticSession;h(e.getId(),e.acquisitionDate,e.renewalDate)}}))}return e.acquisitionSpan=864e5,e.renewalSpan=18e5,e.cookieUpdateInterval=6e4,e.cookieNameConst="ai_session",e}(),xo=at,Fo=function(){function e(e,t,i){this.app=new Ms(t,i),this.cloud=new ks,this.user=new Ds(e,t,i),this.os=new oo(t),this.web=new zs(t,i),this.sdk=new ko(e,i),this.intWeb=new lo(t,i),this.utc=new co(t),this.loc=new uo,this.device=new ho,this.telemetryTrace=new go(t),this.sessionManager=new Lo(i,t),this.session=new po}return e.prototype.getSessionId=function(){var e=this.session;if(e&&xo(e.customId))return e.customId;var t=this.sessionManager;t.update();var i=t.automaticSession;if(i){var n=i.getId();n&&xo(n)&&(e.automaticId=n)}return e.automaticId},e.prototype.applyApplicationContext=function(e){var t=this.app;xo(t.id)&&(e.ext[Ro.AppExt][mo.id]=t.id),xo(t.ver)&&(e.ext[Ro.AppExt][mo.ver]=t.ver),xo(t.name)&&(e.ext[Ro.AppExt][mo.appName]=t.name),xo(t.locale)&&(e.ext[Ro.AppExt][mo.locale]=t.locale);var i=t.getExpId();xo(i)&&(e.ext[Ro.AppExt][mo.expId]=i),xo(t.env)&&(e.ext[Ro.AppExt][mo.env]=t.env)},e.prototype.applyUserContext=function(e){var t=this.user,i=t.getLocalId();xo(i)&&(e.ext[Ro.UserExt][vo.localId]=i),xo(t.locale)&&(e.ext[Ro.UserExt][vo.locale]=t.locale),xo(t.id)&&(e.ext[Ro.UserExt][vo.id]=t.id)},e.prototype.applyWebContext=function(e){var t=this.web;xo(t.domain)&&(e.ext[Ro.WebExt][fo.domain]=t.domain),xo(t.browser)&&(e.ext[Ro.WebExt][fo.browser]=t.browser),xo(t.browserVer)&&(e.ext[Ro.WebExt][fo.browserVer]=t.browserVer),xo(t.screenRes)&&(e.ext[Ro.WebExt][fo.screenRes]=t.screenRes),e.ext[Ro.WebExt][fo.userConsent]=t.getUserConsent(),e.ext[Ro.WebExt][fo.consentDetails]=t.getUserConsentDetails()},e.prototype.applyOsContext=function(e){var t=this.os;xo(t.name)&&(e.ext[Ro.OSExt][So.osName]=t.name),xo(t.ver)&&(e.ext[Ro.OSExt][So.ver]=t.ver)},e.prototype.applySdkContext=function(e){var t=this.sdk;e.ext[Ro.SdkExt][yo.seq]=t.getSequenceId(),e.ext[Ro.SdkExt][yo.epoch]=t.epoch,xo(t.installId)&&(e.ext[Ro.SdkExt][yo.installId]=t.installId)},e.prototype.applyIntWebContext=function(e){var t=this.intWeb,i=t.getMsfpc();xo(i)&&(e.ext[Ro.IntWebExt][Co.msfpc]=i);var n=t.getAnid();xo(n)&&(e.ext[Ro.IntWebExt][Co.anid]=n),xo(t.serviceName)&&(e.ext[Ro.IntWebExt][Co.serviceName]=t.serviceName)},e.prototype.applyUtcContext=function(e){var t=this.utc;e.ext[Ro.UtcExt][_o.popSample]=t.popSample,t.eventFlags>0&&(e.ext[Ro.UtcExt][_o.eventFlags]=t.eventFlags)},e.prototype.applyLocContext=function(e){e.ext[Ro.LocExt][Eo.tz]=this.loc.tz},e.prototype.applySessionContext=function(e){e.ext[Ro.AppExt][To.sessionId]=this.getSessionId()},e.prototype.applyDeviceContext=function(e){var t=this.device;xo(t.localId)&&(e.ext[Ro.DeviceExt][bo.localId]=t.localId),xo(t.make)&&(e.ext[Ro.DeviceExt][bo.make]=t.make),xo(t.model)&&(e.ext[Ro.DeviceExt][bo.model]=t.model),xo(t.deviceClass)&&(e.ext[Ro.DeviceExt][bo.deviceClass]=t.deviceClass)},e.prototype.applyCloudContext=function(e){var t=this.cloud;xo(t.role)&&(e.ext[Ro.CloudExt][Io.role]=t.role),xo(t.roleInstance)&&(e.ext[Ro.CloudExt][Io.roleInstance]=t.roleInstance),xo(t.roleVer)&&(e.ext[Ro.CloudExt][Io.roleVer]=t.roleVer)},e.prototype.applyAITraceContext=function(e){var t=this.telemetryTrace;xo(t.traceId)&&(e.ext[Ro.TraceExt][wo.traceId]=t.traceId),xo(t.name)&&(e.ext[Ro.TraceExt][wo.traceName]=t.name),xo(t.parentId)&&(e.ext[Ro.TraceExt][wo.parentId]=t.parentId)},e}(),Uo=function(e){function t(){var i,n=e.call(this)||this;n.identifier="SystemPropertiesCollector",n.priority=3,n.version="3.1.2";var r={};return Be(t,n,(function(t,a){t.initialize=function(r,a,s){e.prototype.initialize.call(n,r,a,s),i=new Fo(r,t._getTelCtx().getExtCfg(t.identifier),a)},t.processTelemetry=function(e,n){bn(e,t.identifier),n=t._getTelCtx(n);var a=e.ext=e.ext?e.ext:{};e.data=e.data?e.data:{},a[Ro.AppExt]=a[Ro.AppExt]||{},a[Ro.UserExt]=a[Ro.UserExt]||{},a[Ro.WebExt]=a[Ro.WebExt]||{},a[Ro.OSExt]=a[Ro.OSExt]||{},a[Ro.SdkExt]=a[Ro.SdkExt]||{},a[Ro.IntWebExt]=a[Ro.IntWebExt]||{},a[Ro.UtcExt]=a[Ro.UtcExt]||{},a[Ro.LocExt]=a[Ro.LocExt]||{},a[Ro.DeviceExt]=a[Ro.DeviceExt]||{},a[Ro.TraceExt]=a[Ro.TraceExt]||{},a[Ro.CloudExt]=a[Ro.CloudExt]||{},i.applyApplicationContext(e),i.applyUserContext(e),i.applyWebContext(e),i.applyOsContext(e),i.applySdkContext(e),i.applyIntWebContext(e),i.applyUtcContext(e),i.applyLocContext(e),i.applySessionContext(e),i.applyDeviceContext(e),i.applyAITraceContext(e),i.applyCloudContext(e),ct(gt(a),(function(e){0===gt(a[e]).length&&delete a[e]})),function(e,t){e&&tt(e,(function(e,i){t[e]||(t[e]=i)}))}(r,e.data),t.processNext(e,n)},t.getPropertiesContext=function(){return i},t.setProperty=function(e,t){r[e]=t}})),n}return Za(t,e),t}(li);const Bo="https://ic3.events.data.microsoft.com/OneCollector/1.0/",Vo="https://eu-ic3.events.data.microsoft.com/OneCollector/1.0/",Ho="https://tb.events.data.microsoft.com/OneCollector/1.0/",$o="https://pf.events.data.microsoft.com/OneCollector/1.0/",Go="https://collector.azure.eaglex.ic.gov/OneCollector/1.0/",jo="https://collector.azure.microsoft.scloud/OneCollector/1.0/",zo="https://teams.events.data.microsoft.com/OneCollector/1.0",Wo="https://eu-teams.events.data.microsoft.com/OneCollector/1.0";var qo,Ko;!function(e){e.Public="Public",e.GccHigh="GCCHigh",e.Dod="DoD",e.AirGap08="AirGap08",e.AirGap09="AirGap09"}(qo||(qo={})),function(e){e.OrgId="orgid",e.Acs="acs",e.Spool="spool",e.GccHigh="gcch",e.GccHighAcs="gcch-acs",e.Dod="dod",e.DodAcs="dod-acs",e.AirGap08="ag08",e.AirGap08Acs="ag08-acs",e.AirGap09="ag09",e.AirGap09Acs="ag09-acs"}(Ko||(Ko={}));var Jo;!function(e){e.Public_ConversationServiceUrl_EUDB="https://api.flightproxy.skype.com/api/v2/cpconv",e.Public_TrouterServiceUrl_EUDB="https://go-eu.trouter.communication.microsoft.com/v4/a",e.Public_RegistrarServiceUrl_EUDB="https://emea.prod.registrar.skype.com/v3/registrations",e.Public_MdnTrapServiceUrl_EUDB="https://edge.skype.com/trap",e.Public_MdnTrapServiceTokenUrl_EUDB="https://edge.skype.com/trap/tokens",e.Public_MdnTrapRelaySkypeFqdns_EUDB="eu.relay.skype.com",e.Public_MdnTrapRelayTurnFqdns_EUDB="eu.relay.skype.com",e.Public_MdnTrapRelayTurnUrl_EUDB="",e.Enterprise_ConversationServiceUrl_EUDB="https://api.flightproxy.teams.microsoft.com/api/v2/epconv",e.Enterprise_TrouterServiceUrl_EUDB="https://go-eu.trouter.teams.microsoft.com/v4/a",e.Enterprise_RegistrarServiceUrl_EUDB="https://teams.microsoft.com/registrar/prod/v3/registrations",e.Enterprise_MdnTrapServiceUrl_EUDB="https://teams.microsoft.com/trap",e.Enterprise_MdnTrapServiceTokenUrl_EUDB="https://teams.microsoft.com/trap/tokens",e.Enterprise_MdnTrapRelaySkypeFqdns_EUDB="euaz.relay.teams.microsoft.com",e.Enterprise_MdnTrapRelayTurnFqdns_EUDB="euaz.relay.teams.microsoft.com",e.Enterprise_MdnTrapRelayTurnUrl_EUDB=""}(Jo||(Jo={}));const Yo={Public_ConversationServiceUrl:"https://api.flightproxy.skype.com/api/v2/cpconv",Public_TrouterServiceUrl:"https://go.trouter.communication.microsoft.com/v4/a",Public_RegistrarServiceUrl:"https://prod.registrar.skype.com/v3/registrations",Public_MdnTrapServiceUrl:"https://edge.skype.com/trap",Public_MdnTrapServiceTokenUrl:"https://edge.skype.com/trap/tokens",Public_MdnTrapRelaySkypeFqdns:"worldaz.tr.skype.com",Public_MdnTrapRelayTurnFqdns:"turn.azure.com",Public_MdnTrapRelayTurnUrl:"",GccHigh_ConversationServiceUrl:"https://api.cc.gov.teams.microsoft.us/conv/",GccHigh_TrouterServiceUrl:"https://go.trouter.gov.teams.microsoft.us/v4/a",GccHigh_RegistrarServiceUrl:"https://registrar.gov.teams.microsoft.us/v3/registrations",GccHigh_MdnTrapServiceUrl:"https://trap.gov.teams.microsoft.us",GccHigh_MdnTrapServiceTokenUrl:"https://trap.gov.teams.microsoft.us/tokens",GccHigh_MdnTrapRelaySkypeFqdns:"tr.gov.teams.microsoft.us",GccHigh_MdnTrapRelayTurnFqdns:"turn.gov.teams.microsoft.us",GccHigh_MdnTrapRelayTurnUrl:"https://turn.gov.teams.microsoft.us/relay",Dod_ConversationServiceUrl:"https://api.cc.dod.teams.microsoft.us/conv/",Dod_TrouterServiceUrl:"https://go.trouter.dod.teams.microsoft.us/v4/a",Dod_RegistrarServiceUrl:"https://registrar.dod.teams.microsoft.us/v3/registrations",Dod_MdnTrapServiceUrl:"https://trap.dod.teams.microsoft.us",Dod_MdnTrapServiceTokenUrl:"https://trap.dod.teams.microsoft.us/tokens",Dod_MdnTrapRelaySkypeFqdns:"tr.dod.teams.microsoft.us",Dod_MdnTrapRelayTurnFqdns:"turn.dod.teams.microsoft.us",Dod_MdnTrapRelayTurnUrl:"https://turn.dod.teams.microsoft.us/relay",AirGap08_ConversationServiceUrl:"https://api.cc.skype.com/conv/",AirGap08_TrouterServiceUrl:"https://go.trouter.teams.eaglex.ic.gov/v4/a",AirGap08_RegistrarServiceUrl:"https://api.registrar.teams.eaglex.ic.gov/v3/registrations",AirGap09_ConversationServiceUrl:"https://api.cc.skype.com/conv/",AirGap09_TrouterServiceUrl:"https://go.trouter.teams.microsoft.scloud/v4/a",AirGap09_RegistrarServiceUrl:"https://api.registrar.teams.microsoft.scloud/v3/registrations",Enterprise_ConversationServiceUrl:"https://api.flightproxy.teams.microsoft.com/api/v2/epconv",Enterprise_TrouterServiceUrl:"https://go.trouter.teams.microsoft.com/v4/a",Enterprise_RegistrarServiceUrl:"https://teams.microsoft.com/registrar/prod/v3/registrations",Enterprise_MdnTrapServiceUrl:"https://teams.microsoft.com/trap",Enterprise_MdnTrapServiceTokenUrl:"https://teams.microsoft.com/trap/tokens",Enterprise_MdnTrapRelaySkypeFqdns:"worldaz.relay.teams.microsoft.com",Enterprise_MdnTrapRelayTurnFqdns:"worldaz.relay.teams.microsoft.com",Enterprise_MdnTrapRelayTurnUrl:"",Public_EcsServer_Url:"https://ecs.communication.microsoft.com",GccHigh_EcsServer_Url:"https://config.ecs.gov.teams.microsoft.us",Dod_EcsServer_Url:"https://config.ecs.dod.teams.microsoft.us",AirGap08_EcsServer_Url:"https://config.ecs.teams.eaglex.ic.go",AirGap09_EcsServer_Url:"https://config.ecs.teams.microsoft.scloud",Enterprise_Ecs_ServerUrl:"https://config.teams.microsoft.com"},Qo="https://global.mtgw.prod.communication.microsoft.com/",Zo="acsmt/v1/useraggregatepolicysettings/",Xo="acsmt/v2/useraggregatepolicysettings/",el="acsmt/v2/threads/",tl="acsmt/v2/addParticipantsToThread/";var il;!function(e){e.Consumer="consumer",e.Enterprise="enterprise"}(il||(il={}));const nl=["europe","france","germany","norway","switzerland","sweden"],rl=["emea","fr","de","se"],al=Array.from(new Set(nl.concat(["qatar","uae","africa","uk"]))),sl=["asiapacific","india","japan","korea","australia"],ol=["unitedstates","brazil","canada"];var ll,cl;!function(e){e.EU="EU",e.RoW="RoW"}(ll||(ll={})),function(e){e.APAC="APAC",e.NOAM="NOAM",e.EMEA="EMEA",e.UNKNOWN=""}(cl||(cl={}));const dl={AUDIO:{JITTER:{GOOD:30,AVERAGE:75},RTT:{GOOD:200,AVERAGE:350},PACKETS_LOSS_PERCENTAGE:{GOOD:3,AVERAGE:6}},VIDEO:{JITTER:{GOOD:20,AVERAGE:75},RTT:{GOOD:200,AVERAGE:350},PACKETS_LOSS_PERCENTAGE:{GOOD:3,AVERAGE:6}},BANDWIDTH:{GOOD:1500,AVERAGE:500},CALL:{DURATION_IN_SEC:30,GROUP_ID:x(),AGGREGATION:{INTERVAL:1e3,DATAPOINTS:1},VIDEO_SIZE:{heigth:720,width:1280},MEDIASTREAM_TIMEOUT_IN_SEC:15,CONNECT_TIMEOUT_IN_SEC:10}};var ul;!function(e){e.AcsOrganizerRole="acsorganizer",e.AcsPresenterRole="acspresenter",e.AcsAttendeeRole="acsattendee",e.AcsConsumerRole="acsconsumer",e.TeamsOrganizer="organizer",e.TeamsAttendee="attendee",e.TeamsPresenter="presenter",e.TeamsCoorganizer="coorganizer"}(ul||(ul={}));const hl="4cf9ed87f7dc4e148f77855cd1f2fdca-61fb83a7-6672-4264-806f-7aded29f9b49-7618",pl="53fdaa090eb946b5a1d6cbdeb4f2ef66-bcbf6380-2590-41cc-ae60-9e467cd51835-7413",gl="1cae5691997646c98b01d15beddae7a3-ce16e198-bc32-420f-ac64-42bb916111af-6865",ml="28:8133db4c-c049-4346-9edd-273f164a9227",fl="28:b1902c3e-b9f7-4650-9b23-5772bd429747",vl="ACS-Public",Sl=["en-us"],yl="setLanguage",Cl="transcription",_l=["scheduledMeeting","adhocMeeting"],El="0.0",Tl=!0,bl=Symbol("global_telemetry_logger"),Il=Symbol("global_call_client_index"),wl="orgid",Rl="gcch",Al="8:",Pl="28:",Ml="4:",kl=":",Dl="Unknown",Ol=Al+(wl+kl),Nl="8:dod:",Ll=Al+(Rl+kl),xl="8:teamsvisitor:",Fl="8:acs:",Ul="8:spool:",Bl="8:dod-acs:",Vl="8:gcch-acs:",Hl=Pl+(wl+kl),$l=Pl+(Rl+kl),Gl=Pl+"dod:",jl={audioBitrate:{aggregation_needed:!1,raw_data_reduction:!0},videoBitrate:{aggregation_needed:!1,raw_data_reduction:!0},downloadBitrate:{aggregation_needed:!0,multiplier:8,integer:!0,calculation_method:"rate"},bufferLengthInMs:{aggregation_needed:!0},mediaDelayInMs:{aggregation_needed:!0,is_internal:!0},videoHeight:{aggregation_needed:!1,raw_data_reduction:!0},videoWidth:{aggregation_needed:!1,raw_data_reduction:!0},playerHeight:{aggregation_needed:!1,raw_data_reduction:!0,is_internal:!0},playerWidth:{aggregation_needed:!1,raw_data_reduction:!0,is_internal:!0},currentPlayPosition:{aggregation_needed:!1,raw_data_reduction:!0}};var zl,Wl;!function(e){e.GroupCall="joinGroupId",e.GroupChatCall="joinThreadId",e.TeamsCoordinates="joinMeetingCoordinates",e.TeamsMeetingId="joinMeetingId",e.TeamsMeetingLink="joinMeetingLink",e.RoomCall="joinRoom",e.Unknown="Unknown"}(zl||(zl={})),function(e){e.Organizer="Organizer",e.Coorganizer="Co-organizer",e.Attendee="Attendee",e.Presenter="Presenter",e.Consumer="Consumer",e.Unknown="Unknown"}(Wl||(Wl={}));const ql={"msft-acs-room-deviceType":"room","msft-acs-3proom-deviceType":"3proom","msft-acs-mesh-deviceType":"mesh","msft-acs-mesh-deviceType-v2":"meshV2"};var Kl,Jl;!function(e){e.onlyUsedProxy="onlyUsedProxy",e.onlyUsedNonMsftTurn="onlyUsedNonMsftTurn",e.usedProxyAndNonMsftTurn="usedProxyAndNonMsftTurn",e.noCustomProxyAndTurnUsed="noCustomProxyAndTurnUsed"}(Kl||(Kl={})),function(e){e.RoleRestricted="RoleRestricted",e.FeatureNotSupported="FeatureNotSupported",e.ClientRestricted="ClientRestricted",e.MeetingRestricted="MeetingRestricted",e.UserPolicyRestricted="UserPolicyRestricted",e.NotInitialized="NotInitialized",e.Capable="Capable",e.NotCapable="NotCapable",e.CapabilityNotApplicableForTheCallType="CapabilityNotApplicableForTheCallType"}(Jl||(Jl={}));const Yl="roomsRoleBasedCapabilities",Ql="teamsRoleBasedCapabilities",Zl=/^(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]?)$/,Xl=/(\:[0-9]{1,6})(?=$|\/|\?)/;var ec,tc;!function(e){e.TeamsProMgmt="TeamsProMgmt"}(ec||(ec={})),function(e){e.Disabled="Disabled",e.DisabledUserOverride="DisabledUserOverride"}(tc||(tc={}));const ic="ScreenSharing";var nc;function rc(e){const t=n.getIdentifierKind(e);switch(t.kind){case nc.communicationUser:return t.communicationUserId;case nc.phoneNumber:if(t.rawId)return`${t.rawId}`;if(t.phoneNumber)return`${Ml}${t.phoneNumber}`;throw new b({defaultError:f.IDENTIFIER.PARSE_PHONENUMBER});case nc.microsoftTeamsUser:if(t.rawId)return t.rawId;if(t.microsoftTeamsUserId){if(t.isAnonymous)return`${xl}${t.microsoftTeamsUserId}`;if("public"===t.cloud)return`${Ol}${t.microsoftTeamsUserId}`;if("dod"===t.cloud)return`${Nl}${t.microsoftTeamsUserId}`;if("gcch"===t.cloud)return`${Ll}${t.microsoftTeamsUserId}`;if(!t.cloud)return`${Ol}${t.microsoftTeamsUserId}`}throw new b({defaultError:f.IDENTIFIER.PARSE_MSFT_TEAMS_USER});case nc.microsoftTeamsApp:if(t.rawId)return t.rawId;if(t.teamsAppId){if("public"===t.cloud)return`${Hl}${t.teamsAppId}`;if("dod"===t.cloud)return`${Gl}${t.teamsAppId}`;if("gcch"===t.cloud)return`${$l}${t.teamsAppId}`;if(!t.cloud)return`${Hl}${t.teamsAppId}`}throw new b({defaultError:f.IDENTIFIER.PARSE_MSFT_TEAMS_APP});case"unknown":return t.id;default:throw new b({defaultError:f.IDENTIFIER.PARSE_IDENTIFIER})}}function ac(e){return e.startsWith(Ol)?{kind:nc.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(8),isAnonymous:!1,cloud:"public"}:e.startsWith(Nl)?{kind:nc.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(6),isAnonymous:!1,cloud:"dod"}:e.startsWith(Ll)?{kind:nc.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(7),isAnonymous:!1,cloud:"gcch"}:e.startsWith(xl)?{kind:nc.microsoftTeamsUser,rawId:e,microsoftTeamsUserId:e.substring(15),isAnonymous:!0}:e.startsWith(Ml)?{kind:nc.phoneNumber,rawId:e,phoneNumber:e.substring(2)}:e.startsWith(Fl)||e.startsWith(Ul)||e.startsWith(Vl)||e.startsWith(Bl)?{kind:nc.communicationUser,communicationUserId:e}:e.startsWith(Hl)?{kind:nc.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(9),cloud:"public"}:e.startsWith($l)?{kind:nc.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(8),cloud:"gcch"}:e.startsWith(Gl)?{kind:nc.microsoftTeamsApp,rawId:e,teamsAppId:e.substring(7),cloud:"dod"}:{kind:nc.unknown,id:e}}function sc(e){return!!e.startsWith(Pl)}function oc(e){const t=n.getIdentifierKind(e);switch(t.kind){case nc.communicationUser:if(!(t.communicationUserId.startsWith(Fl)||t.communicationUserId.startsWith(Ul)||t.communicationUserId.startsWith(Vl)||t.communicationUserId.startsWith(Bl)))throw new b({defaultError:f.IDENTIFIER.INVALID_COMM_USER});return t;case"phoneNumber":return t;case nc.microsoftTeamsUser:if(t.rawId&&!t.rawId.startsWith(Ol)&&!t.rawId.startsWith(Nl)&&!t.rawId.startsWith(Ll)&&!t.rawId.startsWith(xl))throw new b({defaultError:f.IDENTIFIER.INVALID_MSFT_TEAMS_USER_RAWID});if(!t.microsoftTeamsUserId)throw new b({defaultError:f.IDENTIFIER.INVALID_MSFT_TEAMS_USER_USERID});return t;case nc.microsoftTeamsApp:if(t.rawId&&!t.rawId.startsWith(Pl))throw new b({defaultError:f.IDENTIFIER.INVALID_MSFT_TEAMS_APP_RAWID});if(!t.teamsAppId)throw new b({defaultError:f.IDENTIFIER.INVALID_MSFT_TEAMS_APP_APPID});return t;case nc.unknown:if(!t.id)throw new b({defaultError:f.IDENTIFIER.INVALID_UNKNOWN_IDENTIFIER});return t;default:throw new b({defaultError:f.IDENTIFIER.PARSE_INVALID_IDENTIFIER})}}!function(e){e.communicationUser="communicationUser",e.microsoftTeamsUser="microsoftTeamsUser",e.microsoftTeamsApp="microsoftTeamsApp",e.phoneNumber="phoneNumber",e.unknown="unknown",e.group="group"}(nc||(nc={}));const lc="1.24.1.2_beta",cc="1.24.1-beta.2";function dc(){const e="ACS_CLIENT_INTERNAL_SZK_VERSION".replace("Z","D");return lc===e?"1.0.0.0":lc}function uc(){const e="ACS_CLIENT_SZK_VERSION".replace("Z","D");return cc===e?"1.0.0.0":cc}function hc(e,t){if(Array.isArray(e))return t.slice()}function pc(e){return Array.isArray(e)&&0!==e.length}function gc(e){return null==e||void 0===e}function mc(e,t){return void 0!==e?e:t}function fc(e){try{return JSON.stringify(e,null,2)}catch(t){return`failed to stringify obj ${e}`}}let vc,Sc={telemetry:{callStatsFlushTimeout:6e3,discardedTelemetryRetryTimeout:5e3,discardedEventsBufferMaxLength:1e3,discardedEventsMaxRetries:3,telemetryFlushTimeout:2e3,allowedEvents:[],blockedEvents:["acs_calling_feature_usage","acs_calling_call_client_init"],limit:{outSideCall:{enabled:!1,deltaTimeInMs:15e3,includedEvents:[],excludedEvents:[]},rates:[]},telemetryBeforeUnload:!1,gzipTelemetryPayload:!0,localStorageEnable:!1,mediaStatsConfig:{enabled:!0,throttleTelemetry:1,aggregationInterval:10,dataPointsPerAggregation:6,metricsProperties:{},dataToSend:{raw:!1,min:!0,max:!0,sum:!0,count:!0}},liveStreamStatsConfig:{enabled:!1,fetchInterval:1,aggregationInterval:10,dataPointsPerAggregation:6,pollingMethod:"interval",additionalStats:{},dataToSend:{raw:!1,min:!0,max:!0,sum:!0,count:!0}},reportSdkUaToService:!1,reportEnvToService:!1,sendNetworkChangedTelemetry:!1,deviceChangedEvents:{enabled:!1,piiSafeWordsMode:"merge",piiSafeWords:["airpod","bluetooth","hands-free","stereo","wireless","citrix hdx","remote audio","vmware","built-in","integrated","internal","teams","high definition","facetime","macbook","smartaudio","front","rear","back","iphone","ipad","display","displayport","dp","hdmi","amd","nvidia","intel","analog","digital","dock","line( in| out)?","s/pdif","external","thunderbolt\\d*","usb","panoramic","desktop","capture","cable","cam","virtual","manycam","snap camera","obs","vb-audio","vaio","effect","sink","source","default","test"]},maxExistingReportedParticipants:25},mediaStats:{blockMetrics:{},transformMetrics:{},fetchInterval:1,aggregationInterval:10,dataPointsPerAggregation:6,pollingMethod:"interval",timerThrottlingFilter:{enabled:!1,delayRatio:0,filterRange:{"audio.send":{bitrate:{min:0,max:535500},packetsPerSecond:{min:0,max:200},packetsLostPerSecond:{min:0,max:200}},"audio.receive":{bitrate:{min:0,max:535500},packetsPerSecond:{min:0,max:200},packetsLostPerSecond:{min:0,max:200}},"video.send":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateInput:{min:0,max:66},frameRateEncoded:{min:0,max:66},frameRateSent:{min:0,max:66}},"video.receive":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateOutput:{min:0,max:66},frameRateDecoded:{min:0,max:66},frameRateReceived:{min:0,max:66}},"screenShare.send":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateInput:{min:0,max:33},frameRateEncoded:{min:0,max:33},frameRateSent:{min:0,max:33}},"screenShare.receive":{bitrate:{min:0,max:8e6},packetsPerSecond:{min:0,max:1e3},packetsLostPerSecond:{min:0,max:1e3},frameRateOutput:{min:0,max:33},frameRateDecoded:{min:0,max:33},frameRateReceived:{min:0,max:33}}}}},debugInfo:{broadcastChannelName:"acs_broadcast_channel",tabsBroadcastDelay:5e3,tabsUpdateDelay:500,enableLogDump:!1,maxLogDumpLength:500,includeList:[],excludeList:[]},volumeIndicator:{fftSize:512,minDecibels:-127,maxDecibels:0,smoothingConstant:.4,microphoneVolumeSampleIntervalMs:200,normalisedMaxVolume:100,maxAvailableVolume:255},telemetryEvents:{eventNameToPriority:{eventName:["acs_calling_call_stats"],priority:[ln]}},rendering:{remoteVideo:{createViewTimeout:6e3,createViewUnsubscribeTimeout:2500,debounceTimeout:1500,createViewSendMediaStats:!0,createViewSendMediaStatsMaxLength:120,createViewSendMediaStatsInitialMaxLength:1,createViewFailureNetworkUfdCheckWindowInMs:2e3,forceCheckIfVideoWasAttachedToDom:!0,checkIfVideoAttachedToDom_poll:!0,checkIfVideoAttachedToDom_intervalTime:5e3,checkIfVideoAttachedToDom_intervalMaxTries:12,checkIfVideoAttachedToDom_timeout:2e4,createViewSenderStatsDuration:6e4,registeredViewIdsMaxLength:0,getMediaStreamTimeout:6e3,largeMeeting:{handleVideoRendering:!0,participantCountThreshold:100,dominantSpeakersWithVideoOn_topCount:4}}},captions:{acsBotMri:ml,teamsBotMri:fl,clientInfo:vl,availableLanguages:Sl,enabled:!0,acs:{botMri:ml,clientInfo:{ring:vl},spokenLanguages:{enabled:!0,languages:Sl}},teams:{botMri:fl,clientInfo:{ring:"Teams-Public"},spokenLanguages:{enabled:!0,languages:Sl},captionLanguages:{enabled:!1,languages:["en"]}}},audioEffects:{enableAudioEffects:!1,maxStringLengthForTelemetry:250},videoEffects:{enableVideoEffects:!1,effectInitTimeThresholdInMs:2e4,fpsWarningThreshold:5,waitTimeToInitiateFpsChecksInMs:2e4,fpsCheckIntervalTimeInMs:3e3},calling:{enableMuteOthers:!0,enableSmePassFakeConversation:!1,doNotWaitForTrouter:!1,hangUpCallOnPageHide:!1,maxNumberOfTokenFetchRetries:10,deviceSelectionTimeoutInMs:3e3,deviceNotFunctioningMuted:!0,muteUnmuteOnMicrophoneNotFunctioning:!1,unmuteDelayForMicrophoneNotFunctioningInMs:0,preventStopAudio:!1,preventFakeMute:!1,osAutoRecoverAudio:!1,deviceCaptureMuteRecover:!1,allowMuteOnBadUfd:!0,preventStopVideo:!0,mediaMetricsDeviceEventsEnabled:!1,allowAccessRawMediaStream:!1,applyViewLimit:!1,deviceCaptureMutedVideo:!0,removeLvsCheckOnCallStartAndCallAccept:!1,removeLocalAudioStreamCheckOnCallStartAndCallAccept:!1,constraints:{enabled:!1,maxOutgoingResolution:0,maxOutgoingFrameRate:0,maxOutgoingVideoBitrate:0},supportLiveStreaming:!1,liveStreamingBotIds:["28:f4693563-c70b-4e4d-bda6-01792aa21440","28:e32c9418-a835-4eb1-bfb9-733fa74dd6e8"],composedStreamBotIds:["28:5f2511f1-6da9-41d9-80d9-af7da23a2c27","28:accb0009-8d12-4cfe-969c-39b204e3ed0c"],setDeviceType:!1,devicePermissions:{splitAskAudioVideo:!1,timeoutInBetween:0,getCurrentState:!0},applicationSettingsUrls:{Public_ConversationServiceUrl:Yo.Public_ConversationServiceUrl,Public_TrouterServiceUrl:Yo.Public_TrouterServiceUrl,Public_RegistrarServiceUrl:Yo.Public_RegistrarServiceUrl,Public_MdnTrapServiceUrl:Yo.Public_MdnTrapServiceUrl,Public_MdnTrapServiceTokenUrl:Yo.Public_MdnTrapServiceTokenUrl,Public_MdnTrapRelaySkypeFqdns:Yo.Public_MdnTrapRelaySkypeFqdns,Public_MdnTrapRelayTurnFqdns:Yo.Public_MdnTrapRelayTurnFqdns,Public_MdnTrapRelayTurnUrl:Yo.Public_MdnTrapRelayTurnUrl,GccHigh_ConversationServiceUrl:Yo.GccHigh_ConversationServiceUrl,GccHigh_TrouterServiceUrl:Yo.GccHigh_TrouterServiceUrl,GccHigh_RegistrarServiceUrl:Yo.GccHigh_RegistrarServiceUrl,GccHigh_MdnTrapServiceUrl:Yo.GccHigh_MdnTrapServiceUrl,GccHigh_MdnTrapServiceTokenUrl:Yo.GccHigh_MdnTrapServiceTokenUrl,GccHigh_MdnTrapRelaySkypeFqdns:Yo.GccHigh_MdnTrapRelaySkypeFqdns,GccHigh_MdnTrapRelayTurnFqdns:Yo.GccHigh_MdnTrapRelayTurnFqdns,GccHigh_MdnTrapRelayTurnUrl:Yo.GccHigh_MdnTrapRelayTurnUrl,Dod_ConversationServiceUrl:Yo.Dod_ConversationServiceUrl,Dod_TrouterServiceUrl:Yo.Dod_TrouterServiceUrl,Dod_RegistrarServiceUrl:Yo.Dod_RegistrarServiceUrl,Dod_MdnTrapServiceUrl:Yo.Dod_MdnTrapServiceUrl,Dod_MdnTrapServiceTokenUrl:Yo.Dod_MdnTrapServiceTokenUrl,Dod_MdnTrapRelaySkypeFqdns:Yo.Dod_MdnTrapRelaySkypeFqdns,Dod_MdnTrapRelayTurnFqdns:Yo.Dod_MdnTrapRelayTurnFqdns,Dod_MdnTrapRelayTurnUrl:Yo.Dod_MdnTrapRelayTurnUrl,AirGap08_ConversationServiceUrl:Yo.AirGap08_ConversationServiceUrl,AirGap08_TrouterServiceUrl:Yo.AirGap08_TrouterServiceUrl,AirGap08_RegistrarServiceUrl:Yo.AirGap08_RegistrarServiceUrl,AirGap09_ConversationServiceUrl:Yo.AirGap09_ConversationServiceUrl,AirGap09_TrouterServiceUrl:Yo.AirGap09_TrouterServiceUrl,AirGap09_RegistrarServiceUrl:Yo.AirGap09_RegistrarServiceUrl,Enterprise_ConversationServiceUrl:Yo.Enterprise_ConversationServiceUrl,Enterprise_TrouterServiceUrl:Yo.Enterprise_TrouterServiceUrl,Enterprise_RegistrarServiceUrl:Yo.Enterprise_RegistrarServiceUrl,Enterprise_MdnTrapServiceUrl:Yo.Enterprise_MdnTrapServiceUrl,Enterprise_MdnTrapServiceTokenUrl:Yo.Enterprise_MdnTrapServiceTokenUrl,Enterprise_MdnTrapRelaySkypeFqdns:Yo.Enterprise_MdnTrapRelaySkypeFqdns,Enterprise_MdnTrapRelayTurnFqdns:Yo.Enterprise_MdnTrapRelayTurnFqdns,Enterprise_MdnTrapRelayTurnUrl:Yo.Enterprise_MdnTrapRelayTurnUrl},applicationSettingsEudbUrls:{Public_ConversationServiceUrl_EUDB:Jo.Public_ConversationServiceUrl_EUDB,Public_TrouterServiceUrl_EUDB:Jo.Public_TrouterServiceUrl_EUDB,Public_RegistrarServiceUrl_EUDB:Jo.Public_RegistrarServiceUrl_EUDB,Public_MdnTrapServiceUrl_EUDB:Jo.Public_MdnTrapServiceUrl_EUDB,Public_MdnTrapServiceTokenUrl_EUDB:Jo.Public_MdnTrapServiceTokenUrl_EUDB,Public_MdnTrapRelaySkypeFqdns_EUDB:Jo.Public_MdnTrapRelaySkypeFqdns_EUDB,Public_MdnTrapRelayTurnFqdns_EUDB:Jo.Public_MdnTrapRelayTurnFqdns_EUDB,Public_MdnTrapRelayTurnUrl_EUDB:Jo.Public_MdnTrapRelayTurnUrl_EUDB,Enterprise_ConversationServiceUrl_EUDB:Jo.Enterprise_ConversationServiceUrl_EUDB,Enterprise_TrouterServiceUrl_EUDB:Jo.Enterprise_TrouterServiceUrl_EUDB,Enterprise_RegistrarServiceUrl_EUDB:Jo.Enterprise_RegistrarServiceUrl_EUDB,Enterprise_MdnTrapServiceUrl_EUDB:Jo.Enterprise_MdnTrapServiceUrl_EUDB,Enterprise_MdnTrapServiceTokenUrl_EUDB:Jo.Enterprise_MdnTrapServiceTokenUrl_EUDB,Enterprise_MdnTrapRelaySkypeFqdns_EUDB:Jo.Enterprise_MdnTrapRelaySkypeFqdns_EUDB,Enterprise_MdnTrapRelayTurnFqdns_EUDB:Jo.Enterprise_MdnTrapRelayTurnFqdns_EUDB,Enterprise_MdnTrapRelayTurnUrl_EUDB:Jo.Enterprise_MdnTrapRelayTurnUrl_EUDB},maxDisplayNameLength:256,callDiagnostics:dl,eudb:{isEnabled:!0,countries:nl,regions:rl,defaultDataLocationEurope:!1,EmeaTenants:al,ApacTenants:sl,NoamTenants:ol,acsCompliantEvents:{},isRgnClaimEnabledForACS:!0,sendRegionToNgc:!0},tfl:{isEnabled:!1,hosts:["teams.live.com"]},lobbyAdmitAndReject:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},localRecording:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},enableCustomTurnUsage:!1,allowProxyForTeamsCalls:!1,allowCustomTurnForTeamsCalls:!1,spotlight:{enabled:!0,maxSpotlightParticipants:7,supportedRoles:["presenter","organizer","coorganizer"],meetingTypes:["scheduledMeeting"]},teamsMeetingAudioConferencing:{enabled:!0,supportedConversationTypes:["scheduledMeeting","adHocMeeting"]},transfer:{autoAccept:!0},reaction:{enabled:!0,telemetryEventAggregationIntervalInSecond:3,enableStateServiceConsoleLogs:!0,StateServiceProxySettings:{batchedRequestsEnabled:!1,websocketAliveTimeAfterLoseFocusInMS:3e4,pingTimeoutInMs:2e4,pongTimeoutInMs:5e3,maxSessionRetries:2,offlineMessageCacheEnabled:!0,maxOfflineMessageCacheLength:64,maxOfflineMessageCacheTimeInMs:2e4,autoRoutingEnabled:!0}},pptlive:{enabled:!0,wdParams:{wdModernSlideShowInTeams:!0,wdPresenterViewInTeams:!1,wdForceModernSlideShowInTeams:!1,isMovePrivateViewingToPPTEnabled:!0},appSettings:{takeFocusOnBoot:!0,enableAdvanceOnClick:!1,enableAdvanceOnTap:!1},stateServiceProxySettings:{batchedRequestsEnabled:!1,maxRoundtripRaw:300,pingTimeoutInMs:15e3,pongTimeoutInMs:15e3,retryIntervalsInMs:[1e3,2e3,4e3],verbose:!1,websocketAliveTimeAfterLoseFocusInMS:3e4,autoRoutingEnabled:!0,useServiceGeneratedClientId:!0,offlineMessageCacheEnabled:!0,maxOfflineMessageCacheTimeInMs:2e4,maxOfflineMessageCacheLength:64,allowReconnectOnSendMessage:!0},enableStateServiceInPreviewerFeatures:'["Ink","Media","Nav","NavSync","PresUrl","PresUrlBoot"]',featureGates:'{"ModernSlideShowAllowListForFileType":"pptx;ppsx;potx;pptm;ppsm;pot;ppt;odp;pps"}'},blacklistedBots:[],musicOnHoldEnabled:!0},dataChannel:{maxReceiveBufferSize:2097152,receiveTimeoutInMs:12e4,maxSendBandwidth:5e5,maxBroadcastPacketRate:80,defaultBitrate:32e3,maxMessageSize:32768,enableBroadcastLimitOnReliableChannel:!1,dataIdConfigs:[]},unmixedAudio:{maxStreamSize:7,operationTimeoutInMs:1e4,skipProviderStateCheck:!1},roles:{acsOrganizer:ul.AcsOrganizerRole,acsPresenter:ul.AcsPresenterRole,acsAttendee:ul.AcsAttendeeRole,acsConsumer:ul.AcsConsumerRole,teamsAttendee:ul.TeamsAttendee,teamsOrganizer:ul.TeamsOrganizer,teamsPresenter:ul.TeamsPresenter,teamsCoorganizer:ul.TeamsCoorganizer},roomsRoleBasedCapabilities:{presenter:_c("roomJoin","Presenter"),attendee:_c("roomJoin","Attendee"),consumer:_c("roomJoin","Consumer")},teamsRoleBasedCapabilities:{organizer:_c("teamsMeetingJoin","Organizer"),coorganizer:_c("teamsMeetingJoin","Co-organizer"),presenter:_c("teamsMeetingJoin","Presenter"),attendee:_c("teamsMeetingJoin","Attendee")},environments:{android:{chrome:{minVersion:El,isSupportedOnSdkVersion:Tl},edgeanaheim:{minVersion:El,isSupportedOnSdkVersion:Tl}},ios:{safari:{minVersion:El,isSupportedOnSdkVersion:Tl},chrome:{minVersion:El,isSupportedOnSdkVersion:!uc().includes("stable")},applewebview:{minVersion:El,isSupportedOnSdkVersion:Tl}},mac:{chrome:{minVersion:El,isSupportedOnSdkVersion:Tl},safari:{minVersion:El,isSupportedOnSdkVersion:Tl},edgeanaheim:{minVersion:El,isSupportedOnSdkVersion:Tl},firefox:{minVersion:El,isSupportedOnSdkVersion:!uc().includes("stable")}},windows:{chrome:{minVersion:El,isSupportedOnSdkVersion:Tl},chromium:{minVersion:El,isSupportedOnSdkVersion:Tl},edgeanaheim:{minVersion:El,isSupportedOnSdkVersion:Tl},firefox:{minVersion:El,isSupportedOnSdkVersion:!uc().includes("stable")}},linux:{chrome:{minVersion:El,isSupportedOnSdkVersion:Tl},firefox:{minVersion:El,isSupportedOnSdkVersion:!uc().includes("stable")}}},MiddleTier:{enabled:!1,maxRetry:3,baseServiceUrl:Qo,policyUrlSuffix:Zo,policyUrlSuffixV2:Xo,userPolicySettingsApi:!1,serverManagedThreadIdApiConfiguration:{allowServerThreadCreation:!0,decoupleChatThreadFromCalls:!0,createThreadSuffix:el,addParticipantSuffix:tl}},PowerPointStateServiceUrl:{public:{amer:"https://usc.pptservicescast.officeapps.live.com",apac:"https://apac.pptservicescast.officeapps.live.com",emea:"https://emea.pptservicescast.officeapps.live.com",uk:"https://ukc.pptservicescast.officeapps.live.com",eu:"https://euc.pptservicescast.officeapps.live.com",in:"https://inc.pptservicescast.officeapps.live.com",au:"https://auc.pptservicescast.officeapps.live.com",ca:"https://canc.pptservicescast.officeapps.live.com",fr:"https://fr.pptservicescast.officeapps.live.com",jp:"https://jpc.pptservicescast.officeapps.live.com",ae:"https://ae.pptservicescast.officeapps.live.com",kr:"https://krc.pptservicescast.officeapps.live.com",sg:"https://sg.pptservicescast.officeapps.live.com",za:"https://za.pptservicescast.officeapps.live.com",de:"https://de.pptservicescast.officeapps.live.com",ch:"https://ch.pptservicescast.officeapps.live.com",no:"https://no.pptservicescast.officeapps.live.com",br:"https://pptservicescast.officeapps.live.com",se:"https://se.pptservicescast.officeapps.live.com",qa:"https://qa.pptservicescast.officeapps.live.com",gallatin:"https://pptservicescast.osi.microsoftonline.cn",pl:"https://pl.pptservicescast.officeapps.live.com",it:"https://euc.pptservicescast.officeapps.live.com",il:"https://pptservicescast.officeapps.live.com",mx:"https://pptservicescast.officeapps.live.com"},gcc:"https://pptservicescast.gcc.osi.office365.us",gcch:"https://pptservicescast.osi.office365.us",dod:"https://pptservicescast.osi.apps.mil",ag08:"https://pptservicescast.osi.eaglex.ic.gov",ag09:"https://pptservicescast.osi.microsoft.scloud"}};function yc(){return Sc}function Cc(){return vc}function _c(e,t){let i={turnVideoOn:!0,unmuteMic:!0,shareScreen:!0,removeParticipant:!0,hangUpForEveryOne:!0,addCommunicationUser:!0,addTeamsUser:!0,addPhoneNumber:!0,manageLobby:!0,spotlightParticipant:!0,removeParticipantsSpotlight:!0,blurBackground:!0,startLiveCaptions:!0,stopLiveCaptions:!0,raiseHand:!0,pstnDialOut:!0,muteOthers:!0,useReactions:!0,viewAttendeeNames:!0};if("teamsMeetingJoin"==e){if("Presenter"==t||"Co-organizer"==t||"Organizer"==t)return{...i};if("Attendee"==t){let e={...i};return e.removeParticipant=!1,e.manageLobby=!1,e.spotlightParticipant=!1,e.removeParticipantsSpotlight=!1,e.shareScreen=!1,e.muteOthers=!1,e}}if("roomJoin"==e){let e={...i};if(e.removeParticipant=!1,e.hangUpForEveryOne=!1,e.addCommunicationUser=!1,e.addTeamsUser=!1,e.manageLobby=!1,e.spotlightParticipant=!1,e.removeParticipantsSpotlight=!1,e.blurBackground=!1,e.startLiveCaptions=!1,e.stopLiveCaptions=!1,e.raiseHand=!1,"Presenter"==t)return{...e};if("Attendee"==t){let t={...e};return t.shareScreen=!1,t.muteOthers=!1,t.addPhoneNumber=!1,t.pstnDialOut=!1,t}if("Consumer"==t){let t={...e};return t.turnVideoOn=!1,t.unmuteMic=!1,t.shareScreen=!1,t.muteOthers=!1,t.addPhoneNumber=!1,t.pstnDialOut=!1,t}}return i}const Ec=["response","responseText","responseURL","status","state","statusText","timeout","withCredentials","stack","message","name","error","piiSafe","phase","code","participantId","phrase","subCode","reason"];function Tc(e){switch(e){case"Crop":return 1;case"Fit":return 2;default:return 0}}function bc(e){return e.toString===Object.prototype.toString?JSON.stringify(e):e.toString()}function Ic(e,t){try{return"string"==typeof e?new Blob([e]).size:e.byteLength}catch(e){return t.error(e),0}}function wc(e){let t={};return e.forEach(((e,i)=>{t[i]=e})),Object.freeze(t)}function Rc(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)},dispose:()=>{i&&(t("disposed"),i=!1)}}}function Ac(e,t="Timed promise; rejected."){let i,n,r,a=!0;const s=()=>{window.clearTimeout(r)};let o=new Promise(((e,t)=>{i=t=>{s(),a=!1,e(t)},n=e=>{s(),a=!1,t(e)}}));return{timerStart:()=>{r=window.setTimeout((()=>{n(new b({defaultError:f.FEATURES.VIDEO_EFFECTS.EFFECT_PROVIDER_TIMEOUT}))}),e)},timerStop:s,deferredPromise:{promise:o,resolve:i,reject:n,isPending:()=>a,dispose:()=>{n("disposed")}}}}function Pc(e,t){if(null==e)throw new b({defaultError:t})}function Mc(e,t){if("object"!=typeof e)throw new b({defaultError:t})}function kc(e){let[,t]=e?.split(".");if(void 0===t)throw new b({defaultError:f.INTERNAL.TOKEN_PAYLOAD_UNDEFINED});return t=t.replace(/-/g,"+").replace(/_/g,"/"),JSON.parse(decodeURIComponent(escape(atob(t))))}function Dc(e,t){throw t.error(`CallingCommunicationError: Message={${e.message},Code={${e.code}}, SubCode={${e.subCode}}, ResultCategories={${e.resultCategories}}`),new b({defaultError:e})}function Oc(){}function Nc(e,t){const i=function(e){return xc(e)?yc().calling.eudb.regions:yc().calling.eudb.countries}(e);return!!t&&!!i.find((e=>e===t))}function Lc(e,t){return yc().calling.eudb.isEnabled&&Nc(e,t||"")}function xc(e){return yc().calling.eudb.isRgnClaimEnabledForACS||!!e&&e===il.Enterprise||!1}async function Fc(e,t,i){let n;try{if(!e)throw new b({defaultError:f.INTERNAL.NO_TOKEN_PROVIDED});try{n=(await e.getToken(i))?.token}catch(e){throw new b("The token returned from the tokenRefresher is expired."===e.message?{defaultError:f.CALL_AGENT.ACCESSTOKEN_EXPIRED}:{defaultError:f.INTERNAL.GET_TOKEN})}if(!n)throw new b({defaultError:f.INTERNAL.EMPTY_TOKEN})}catch(e){throw new b({defaultError:f.INTERNAL.GET_TOKEN,originalError:e})}try{let e=kc(n);if(!e)throw new b({defaultError:f.INTERNAL.TOKEN_UNDEFINED});if("string"!=typeof e.acsScope)throw new b({defaultError:f.INTERNAL.INVALID_TOKEN_SCOPE_FORMAT});if(!e.acsScope.split(",").find((e=>"voip"===e||"voip.join"===e)))throw new b({defaultError:f.INTERNAL.INVALID_TOKEN_SCOPE});const i=e.resourceId,r=ac(`8:${e.skypeid}`);if(!i&&"microsoftTeamsUser"!==r?.kind)throw new b({defaultError:f.INTERNAL.RESOURCE_NOT_FOUND_IN_TOKEN});let a=e.skypeid;if(!a)throw new b({defaultError:f.INTERNAL.USERID_NOT_FOUND_IN_TOKEN});const s=function(e){const t=e.substring(0,e.indexOf(":"));if(!t)throw new b({defaultError:f.IDENTIFIER.NO_CLOUD_PREFIX_FOUND});switch(t){case Ko.OrgId:case Ko.Acs:case Ko.Spool:return qo.Public;case Ko.GccHigh:case Ko.GccHighAcs:return qo.GccHigh;case Ko.Dod:case Ko.DodAcs:return qo.Dod;case Ko.AirGap08:case Ko.AirGap08Acs:return qo.AirGap08;case Ko.AirGap09:case Ko.AirGap09Acs:return qo.AirGap09;default:return qo.Public}}(a),o=!!e.tid,l=!!e.rgn;return{jwtToken:n,acsResourceId:i,identityMri:a,cloudType:s,isCte:o,region:(o||t?e.rgn:e.resourceLocation)||"",rgnClaimExists:l,exp:1e3*e.exp}}catch(e){throw new b({defaultError:f.INTERNAL.PARSE_TOKEN_FAIL,originalError:e})}}function Uc(e,t=!1){if(void 0===e)return"void";if(e instanceof Error)return e.toString();if(e instanceof String||e instanceof Number||e instanceof Boolean)return e.toString();try{return e.stack&&(e.stack=(e=>{try{return e.split("\n")[0]}catch(e){return"invalid stack"}})(e.stack)),(t?JSON.stringify(e):JSON.stringify(e,Ec,4)).replace(/(\r\n\t|\n|\r\t|\s)/gm,"")}catch(t){return`failed to get error information:${e&&"function"==typeof e.toString&&e.toString()} ${e&&e.response&&JSON.stringify(e.response)}`}}function Bc(e,t){return t.info("permission state to boolean",e),"granted"===e}function Vc(e,t,i=[]){let n=[];try{const r=Array.isArray(e);for(const a in e){const s=e[a],o=r?+a:a;if(!(a in t)){n.push({type:"REMOVE",path:[o],oldValue:e[a]});continue}const l=t[a],c="object"==typeof s&&"object"==typeof l;if(s&&l&&c&&!T[Object.getPrototypeOf(s).constructor.name]&&!i.includes(s)){const e=Vc(s,l);n.push.apply(n,e.map((e=>(e.path.unshift(o),e))))}else s===l||c&&(isNaN(s)?s+""==l+"":+s==+l)||n.push({path:[o],type:"CHANGE",value:l,oldValue:s})}const a=Array.isArray(t);for(const i in t)i in e||n.push({type:"CREATE",path:[a?+i:i],value:t[i]})}catch(e){}return n}function Hc(e,t){const i={[e.roles.acsOrganizer.toLowerCase()]:Wl.Organizer,[e.roles.teamsOrganizer.toLowerCase()]:Wl.Organizer,[e.roles.acsPresenter.toLowerCase()]:Wl.Presenter,[e.roles.teamsPresenter.toLowerCase()]:Wl.Presenter,[e.roles.acsAttendee.toLowerCase()]:Wl.Attendee,[e.roles.teamsAttendee.toLowerCase()]:Wl.Attendee,[e.roles.acsConsumer.toLowerCase()]:Wl.Consumer,[e.roles.teamsCoorganizer.toLowerCase()]:Wl.Coorganizer};return t&&i[t.toString().toLowerCase()]?i[t.toString().toLowerCase()]:Wl.Unknown}function $c(e,t,i,n,r){if(i||n&&"microsoftTeamsUser"===n.kind||r&&function(e){return!!(e.meetingId||e.meetingLink||e.messageId||e.organizerId||e.tenantId||e.threadId)}(r)){const i=yc().calling.allowProxyForTeamsCalls,n=e.proxyInUse,r=yc().calling.allowCustomTurnForTeamsCalls,a=t.customRelayManagerInUse;if(n&&!i)return!1;if(a&&!r)return!1}return!0}function Gc(e){return!!e.find((e=>"microsoftTeamsUser"===n.getIdentifierKind(e).kind))}var jc=s((function(e,t){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;t.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},t.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var n={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),r);else for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){var t,i,n,r,a,s;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(s=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)a=e[t],s.set(a,r),r+=a.length;return s}},r={arraySet:function(e,t,i,n,r){for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){return[].concat.apply([],e)}};t.setTyped=function(e){e?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,n)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,r))},t.setTyped(i)})),zc=0,Wc=1;function qc(e){for(var t=e.length;--t>=0;)e[t]=0}var Kc=0,Jc=29,Yc=256,Qc=Yc+1+Jc,Zc=30,Xc=19,ed=2*Qc+1,td=15,id=16,nd=7,rd=256,ad=16,sd=17,od=18,ld=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],cd=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],dd=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ud=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],hd=new Array(2*(Qc+2));qc(hd);var pd=new Array(2*Zc);qc(pd);var gd=new Array(512);qc(gd);var md=new Array(256);qc(md);var fd=new Array(Jc);qc(fd);var vd,Sd,yd,Cd=new Array(Zc);function _d(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}function Ed(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Td(e){return e<256?gd[e]:gd[256+(e>>>7)]}function bd(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Id(e,t,i){e.bi_valid>id-i?(e.bi_buf|=t<<e.bi_valid&65535,bd(e,e.bi_buf),e.bi_buf=t>>id-e.bi_valid,e.bi_valid+=i-id):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function wd(e,t,i){Id(e,i[2*t],i[2*t+1])}function Rd(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function Ad(e,t,i){var n,r,a=new Array(td+1),s=0;for(n=1;n<=td;n++)a[n]=s=s+i[n-1]<<1;for(r=0;r<=t;r++){var o=e[2*r+1];0!==o&&(e[2*r]=Rd(a[o]++,o))}}function Pd(e){var t;for(t=0;t<Qc;t++)e.dyn_ltree[2*t]=0;for(t=0;t<Zc;t++)e.dyn_dtree[2*t]=0;for(t=0;t<Xc;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*rd]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Md(e){e.bi_valid>8?bd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function kd(e,t,i,n){var r=2*t,a=2*i;return e[r]<e[a]||e[r]===e[a]&&n[t]<=n[i]}function Dd(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&kd(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!kd(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function Od(e,t,i){var n,r,a,s,o=0;if(0!==e.last_lit)do{n=e.pending_buf[e.d_buf+2*o]<<8|e.pending_buf[e.d_buf+2*o+1],r=e.pending_buf[e.l_buf+o],o++,0===n?wd(e,r,t):(wd(e,(a=md[r])+Yc+1,t),0!==(s=ld[a])&&Id(e,r-=fd[a],s),wd(e,a=Td(--n),i),0!==(s=cd[a])&&Id(e,n-=Cd[a],s))}while(o<e.last_lit);wd(e,rd,t)}function Nd(e,t){var i,n,r,a=t.dyn_tree,s=t.stat_desc.static_tree,o=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=ed,i=0;i<l;i++)0!==a[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):a[2*i+1]=0;for(;e.heap_len<2;)a[2*(r=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[r]=0,e.opt_len--,o&&(e.static_len-=s[2*r+1]);for(t.max_code=c,i=e.heap_len>>1;i>=1;i--)Dd(e,a,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Dd(e,a,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,a[2*r]=a[2*i]+a[2*n],e.depth[r]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,a[2*i+1]=a[2*n+1]=r,e.heap[1]=r++,Dd(e,a,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,r,a,s,o,l=t.dyn_tree,c=t.max_code,d=t.stat_desc.static_tree,u=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,g=t.stat_desc.max_length,m=0;for(a=0;a<=td;a++)e.bl_count[a]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<ed;i++)(a=l[2*l[2*(n=e.heap[i])+1]+1]+1)>g&&(a=g,m++),l[2*n+1]=a,n>c||(e.bl_count[a]++,s=0,n>=p&&(s=h[n-p]),o=l[2*n],e.opt_len+=o*(a+s),u&&(e.static_len+=o*(d[2*n+1]+s)));if(0!==m){do{for(a=g-1;0===e.bl_count[a];)a--;e.bl_count[a]--,e.bl_count[a+1]+=2,e.bl_count[g]--,m-=2}while(m>0);for(a=g;0!==a;a--)for(n=e.bl_count[a];0!==n;)(r=e.heap[--i])>c||(l[2*r+1]!==a&&(e.opt_len+=(a-l[2*r+1])*l[2*r],l[2*r+1]=a),n--)}}(e,t),Ad(a,c,e.bl_count)}function Ld(e,t,i){var n,r,a=-1,s=t[1],o=0,l=7,c=4;for(0===s&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=s,s=t[2*(n+1)+1],++o<l&&r===s||(o<c?e.bl_tree[2*r]+=o:0!==r?(r!==a&&e.bl_tree[2*r]++,e.bl_tree[2*ad]++):o<=10?e.bl_tree[2*sd]++:e.bl_tree[2*od]++,o=0,a=r,0===s?(l=138,c=3):r===s?(l=6,c=3):(l=7,c=4))}function xd(e,t,i){var n,r,a=-1,s=t[1],o=0,l=7,c=4;for(0===s&&(l=138,c=3),n=0;n<=i;n++)if(r=s,s=t[2*(n+1)+1],!(++o<l&&r===s)){if(o<c)do{wd(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==a&&(wd(e,r,e.bl_tree),o--),wd(e,ad,e.bl_tree),Id(e,o-3,2)):o<=10?(wd(e,sd,e.bl_tree),Id(e,o-3,3)):(wd(e,od,e.bl_tree),Id(e,o-11,7));o=0,a=r,0===s?(l=138,c=3):r===s?(l=6,c=3):(l=7,c=4)}}qc(Cd);var Fd=!1;function Ud(e,t,i,n){Id(e,(Kc<<1)+(n?1:0),3),function(e,t,i,n){Md(e),n&&(bd(e,i),bd(e,~i)),jc.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}(e,t,i,!0)}var Bd={_tr_init:function(e){Fd||(function(){var e,t,i,n,r,a=new Array(td+1);for(i=0,n=0;n<Jc-1;n++)for(fd[n]=i,e=0;e<1<<ld[n];e++)md[i++]=n;for(md[i-1]=n,r=0,n=0;n<16;n++)for(Cd[n]=r,e=0;e<1<<cd[n];e++)gd[r++]=n;for(r>>=7;n<Zc;n++)for(Cd[n]=r<<7,e=0;e<1<<cd[n]-7;e++)gd[256+r++]=n;for(t=0;t<=td;t++)a[t]=0;for(e=0;e<=143;)hd[2*e+1]=8,e++,a[8]++;for(;e<=255;)hd[2*e+1]=9,e++,a[9]++;for(;e<=279;)hd[2*e+1]=7,e++,a[7]++;for(;e<=287;)hd[2*e+1]=8,e++,a[8]++;for(Ad(hd,Qc+1,a),e=0;e<Zc;e++)pd[2*e+1]=5,pd[2*e]=Rd(e,5);vd=new _d(hd,ld,Yc+1,Qc,td),Sd=new _d(pd,cd,0,Zc,td),yd=new _d(new Array(0),dd,0,Xc,nd)}(),Fd=!0),e.l_desc=new Ed(e.dyn_ltree,vd),e.d_desc=new Ed(e.dyn_dtree,Sd),e.bl_desc=new Ed(e.bl_tree,yd),e.bi_buf=0,e.bi_valid=0,Pd(e)},_tr_stored_block:Ud,_tr_flush_block:function(e,t,i,n){var r,a,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return zc;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return Wc;for(t=32;t<Yc;t++)if(0!==e.dyn_ltree[2*t])return Wc;return zc}(e)),Nd(e,e.l_desc),Nd(e,e.d_desc),s=function(e){var t;for(Ld(e,e.dyn_ltree,e.l_desc.max_code),Ld(e,e.dyn_dtree,e.d_desc.max_code),Nd(e,e.bl_desc),t=Xc-1;t>=3&&0===e.bl_tree[2*ud[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=r&&(r=a)):r=a=i+5,i+4<=r&&-1!==t?Ud(e,t,i,n):4===e.strategy||a===r?(Id(e,2+(n?1:0),3),Od(e,hd,pd)):(Id(e,4+(n?1:0),3),function(e,t,i,n){var r;for(Id(e,t-257,5),Id(e,i-1,5),Id(e,n-4,4),r=0;r<n;r++)Id(e,e.bl_tree[2*ud[r]+1],3);xd(e,e.dyn_ltree,t-1),xd(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),Od(e,e.dyn_ltree,e.dyn_dtree)),Pd(e),n&&Md(e)},_tr_tally:function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(md[i]+Yc+1)]++,e.dyn_dtree[2*Td(t)]++),e.last_lit===e.lit_bufsize-1},_tr_align:function(e){Id(e,2,3),wd(e,rd,hd),function(e){16===e.bi_valid?(bd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}};var Vd=function(e,t,i,n){for(var r=65535&e,a=e>>>16&65535,s=0;0!==i;){i-=s=i>2e3?2e3:i;do{a=a+(r=r+t[n++]|0)|0}while(--s);r%=65521,a%=65521}return r|a<<16};var Hd=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();var $d,Gd=function(e,t,i,n){var r=Hd,a=n+i;e^=-1;for(var s=n;s<a;s++)e=e>>>8^r[255&(e^t[s])];return~e},jd={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},zd=0,Wd=4,qd=0,Kd=-2,Jd=-1,Yd=4,Qd=2,Zd=8,Xd=9,eu=286,tu=30,iu=19,nu=2*eu+1,ru=15,au=3,su=258,ou=su+au+1,lu=42,cu=103,du=113,uu=666,hu=1,pu=2,gu=3,mu=4;function fu(e,t){return e.msg=jd[t],t}function vu(e){return(e<<1)-(e>4?9:0)}function Su(e){for(var t=e.length;--t>=0;)e[t]=0}function yu(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(jc.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function Cu(e,t){Bd._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,yu(e.strm)}function _u(e,t){e.pending_buf[e.pending++]=t}function Eu(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Tu(e,t,i,n){var r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,jc.arraySet(t,e.input,e.next_in,r,i),1===e.state.wrap?e.adler=Vd(e.adler,t,r,i):2===e.state.wrap&&(e.adler=Gd(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)}function bu(e,t){var i,n,r=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match,l=e.strstart>e.w_size-ou?e.strstart-(e.w_size-ou):0,c=e.window,d=e.w_mask,u=e.prev,h=e.strstart+su,p=c[a+s-1],g=c[a+s];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(c[(i=t)+s]===g&&c[i+s-1]===p&&c[i]===c[a]&&c[++i]===c[a+1]){a+=2,i++;do{}while(c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&a<h);if(n=su-(h-a),a=h-su,n>s){if(e.match_start=t,s=n,n>=o)break;p=c[a+s-1],g=c[a+s]}}}while((t=u[t&d])>l&&0!=--r);return s<=e.lookahead?s:e.lookahead}function Iu(e){var t,i,n,r,a,s=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=s+(s-ou)){jc.arraySet(e.window,e.window,s,s,0),e.match_start-=s,e.strstart-=s,e.block_start-=s,t=i=e.hash_size;do{n=e.head[--t],e.head[t]=n>=s?n-s:0}while(--i);t=i=s;do{n=e.prev[--t],e.prev[t]=n>=s?n-s:0}while(--i);r+=s}if(0===e.strm.avail_in)break;if(i=Tu(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=i,e.lookahead+e.insert>=au)for(a=e.strstart-e.insert,e.ins_h=e.window[a],e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[a+au-1])&e.hash_mask,e.prev[a&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=a,a++,e.insert--,!(e.lookahead+e.insert<au)););}while(e.lookahead<ou&&0!==e.strm.avail_in)}function wu(e,t){for(var i,n;;){if(e.lookahead<ou){if(Iu(e),e.lookahead<ou&&t===zd)return hu;if(0===e.lookahead)break}if(i=0,e.lookahead>=au&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+au-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-ou&&(e.match_length=bu(e,i)),e.match_length>=au)if(n=Bd._tr_tally(e,e.strstart-e.match_start,e.match_length-au),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=au){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+au-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=Bd._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Cu(e,!1),0===e.strm.avail_out))return hu}return e.insert=e.strstart<au-1?e.strstart:au-1,t===Wd?(Cu(e,!0),0===e.strm.avail_out?gu:mu):e.last_lit&&(Cu(e,!1),0===e.strm.avail_out)?hu:pu}function Ru(e,t){for(var i,n,r;;){if(e.lookahead<ou){if(Iu(e),e.lookahead<ou&&t===zd)return hu;if(0===e.lookahead)break}if(i=0,e.lookahead>=au&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+au-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=au-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-ou&&(e.match_length=bu(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===au&&e.strstart-e.match_start>4096)&&(e.match_length=au-1)),e.prev_length>=au&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-au,n=Bd._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-au),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+au-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=au-1,e.strstart++,n&&(Cu(e,!1),0===e.strm.avail_out))return hu}else if(e.match_available){if((n=Bd._tr_tally(e,0,e.window[e.strstart-1]))&&Cu(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return hu}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Bd._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<au-1?e.strstart:au-1,t===Wd?(Cu(e,!0),0===e.strm.avail_out?gu:mu):e.last_lit&&(Cu(e,!1),0===e.strm.avail_out)?hu:pu}function Au(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}function Pu(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Zd,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new jc.Buf16(2*nu),this.dyn_dtree=new jc.Buf16(2*(2*tu+1)),this.bl_tree=new jc.Buf16(2*(2*iu+1)),Su(this.dyn_ltree),Su(this.dyn_dtree),Su(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new jc.Buf16(ru+1),this.heap=new jc.Buf16(2*eu+1),Su(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new jc.Buf16(2*eu+1),Su(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Mu(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=Qd,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?lu:du,e.adler=2===t.wrap?0:1,t.last_flush=zd,Bd._tr_init(t),qd):fu(e,Kd)}function ku(e){var t=Mu(e);return t===qd&&function(e){e.window_size=2*e.w_size,Su(e.head),e.max_lazy_match=$d[e.level].max_lazy,e.good_match=$d[e.level].good_length,e.nice_match=$d[e.level].nice_length,e.max_chain_length=$d[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=au-1,e.match_available=0,e.ins_h=0}(e.state),t}function Du(e,t,i,n,r,a){if(!e)return Kd;var s=1;if(t===Jd&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>Xd||i!==Zd||n<8||n>15||t<0||t>9||a<0||a>Yd)return fu(e,Kd);8===n&&(n=9);var o=new Pu;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+au-1)/au),o.window=new jc.Buf8(2*o.w_size),o.head=new jc.Buf16(o.hash_size),o.prev=new jc.Buf16(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new jc.Buf8(o.pending_buf_size),o.d_buf=o.lit_bufsize>>1,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=a,o.method=i,ku(e)}$d=[new Au(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Iu(e),0===e.lookahead&&t===zd)return hu;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,Cu(e,!1),0===e.strm.avail_out))return hu;if(e.strstart-e.block_start>=e.w_size-ou&&(Cu(e,!1),0===e.strm.avail_out))return hu}return e.insert=0,t===Wd?(Cu(e,!0),0===e.strm.avail_out?gu:mu):(e.strstart>e.block_start&&(Cu(e,!1),e.strm.avail_out),hu)})),new Au(4,4,8,4,wu),new Au(4,5,16,8,wu),new Au(4,6,32,32,wu),new Au(4,4,16,16,Ru),new Au(8,16,32,32,Ru),new Au(8,16,128,128,Ru),new Au(8,32,128,256,Ru),new Au(32,128,258,1024,Ru),new Au(32,258,258,4096,Ru)];var Ou={deflateInit:function(e,t){return Du(e,t,Zd,15,8,0)},deflateInit2:Du,deflateReset:ku,deflateResetKeep:Mu,deflateSetHeader:function(e,t){return e&&e.state?2!==e.state.wrap?Kd:(e.state.gzhead=t,qd):Kd},deflate:function(e,t){var i,n,r,a;if(!e||!e.state||t>5||t<0)return e?fu(e,Kd):Kd;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||n.status===uu&&t!==Wd)return fu(e,0===e.avail_out?-5:Kd);if(n.strm=e,i=n.last_flush,n.last_flush=t,n.status===lu)if(2===n.wrap)e.adler=0,_u(n,31),_u(n,139),_u(n,8),n.gzhead?(_u(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),_u(n,255&n.gzhead.time),_u(n,n.gzhead.time>>8&255),_u(n,n.gzhead.time>>16&255),_u(n,n.gzhead.time>>24&255),_u(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),_u(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(_u(n,255&n.gzhead.extra.length),_u(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=Gd(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(_u(n,0),_u(n,0),_u(n,0),_u(n,0),_u(n,0),_u(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),_u(n,3),n.status=du);else{var s=Zd+(n.w_bits-8<<4)<<8;s|=(n.strategy>=2||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(s|=32),s+=31-s%31,n.status=du,Eu(n,s),0!==n.strstart&&(Eu(n,e.adler>>>16),Eu(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),yu(e),r=n.pending,n.pending!==n.pending_buf_size));)_u(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),yu(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,_u(n,a)}while(0!==a);n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),0===a&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),yu(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}a=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,_u(n,a)}while(0!==a);n.gzhead.hcrc&&n.pending>r&&(e.adler=Gd(e.adler,n.pending_buf,n.pending-r,r)),0===a&&(n.status=cu)}else n.status=cu;if(n.status===cu&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&yu(e),n.pending+2<=n.pending_buf_size&&(_u(n,255&e.adler),_u(n,e.adler>>8&255),e.adler=0,n.status=du)):n.status=du),0!==n.pending){if(yu(e),0===e.avail_out)return n.last_flush=-1,qd}else if(0===e.avail_in&&vu(t)<=vu(i)&&t!==Wd)return fu(e,-5);if(n.status===uu&&0!==e.avail_in)return fu(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==zd&&n.status!==uu){var o=2===n.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(Iu(e),0===e.lookahead)){if(t===zd)return hu;break}if(e.match_length=0,i=Bd._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Cu(e,!1),0===e.strm.avail_out))return hu}return e.insert=0,t===Wd?(Cu(e,!0),0===e.strm.avail_out?gu:mu):e.last_lit&&(Cu(e,!1),0===e.strm.avail_out)?hu:pu}(n,t):3===n.strategy?function(e,t){for(var i,n,r,a,s=e.window;;){if(e.lookahead<=su){if(Iu(e),e.lookahead<=su&&t===zd)return hu;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=au&&e.strstart>0&&(n=s[r=e.strstart-1])===s[++r]&&n===s[++r]&&n===s[++r]){a=e.strstart+su;do{}while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<a);e.match_length=su-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=au?(i=Bd._tr_tally(e,1,e.match_length-au),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Bd._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Cu(e,!1),0===e.strm.avail_out))return hu}return e.insert=0,t===Wd?(Cu(e,!0),0===e.strm.avail_out?gu:mu):e.last_lit&&(Cu(e,!1),0===e.strm.avail_out)?hu:pu}(n,t):$d[n.level].func(n,t);if(o!==gu&&o!==mu||(n.status=uu),o===hu||o===gu)return 0===e.avail_out&&(n.last_flush=-1),qd;if(o===pu&&(1===t?Bd._tr_align(n):5!==t&&(Bd._tr_stored_block(n,0,0,!1),3===t&&(Su(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),yu(e),0===e.avail_out))return n.last_flush=-1,qd}return t!==Wd?qd:n.wrap<=0?1:(2===n.wrap?(_u(n,255&e.adler),_u(n,e.adler>>8&255),_u(n,e.adler>>16&255),_u(n,e.adler>>24&255),_u(n,255&e.total_in),_u(n,e.total_in>>8&255),_u(n,e.total_in>>16&255),_u(n,e.total_in>>24&255)):(Eu(n,e.adler>>>16),Eu(n,65535&e.adler)),yu(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?qd:1)},deflateEnd:function(e){var t;return e&&e.state?(t=e.state.status)!==lu&&69!==t&&73!==t&&91!==t&&t!==cu&&t!==du&&t!==uu?fu(e,Kd):(e.state=null,t===du?fu(e,-3):qd):Kd},deflateSetDictionary:function(e,t){var i,n,r,a,s,o,l,c,d=t.length;if(!e||!e.state)return Kd;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==lu||i.lookahead)return Kd;for(1===a&&(e.adler=Vd(e.adler,t,d,0)),i.wrap=0,d>=i.w_size&&(0===a&&(Su(i.head),i.strstart=0,i.block_start=0,i.insert=0),c=new jc.Buf8(i.w_size),jc.arraySet(c,t,d-i.w_size,i.w_size,0),t=c,d=i.w_size),s=e.avail_in,o=e.next_in,l=e.input,e.avail_in=d,e.next_in=0,e.input=t,Iu(i);i.lookahead>=au;){n=i.strstart,r=i.lookahead-(au-1);do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+au-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++}while(--r);i.strstart=n,i.lookahead=au-1,Iu(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=au-1,i.match_available=0,e.next_in=o,e.input=l,e.avail_in=s,i.wrap=a,qd},deflateInfo:"pako deflate (from Nodeca project)"},Nu=!0,Lu=!0;try{String.fromCharCode.apply(null,[0])}catch(e){Nu=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){Lu=!1}for(var xu=new jc.Buf8(256),Fu=0;Fu<256;Fu++)xu[Fu]=Fu>=252?6:Fu>=248?5:Fu>=240?4:Fu>=224?3:Fu>=192?2:1;xu[254]=xu[254]=1;function Uu(e,t){if(t<65537&&(e.subarray&&Lu||!e.subarray&&Nu))return String.fromCharCode.apply(null,jc.shrinkBuf(e,t));for(var i="",n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i}var Bu={string2buf:function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<s&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new jc.Buf8(o),a=0,r=0;a<o;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<s&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|63&i):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|63&i):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|63&i);return t},buf2binstring:function(e){return Uu(e,e.length)},binstring2buf:function(e){for(var t=new jc.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t},buf2string:function(e,t){var i,n,r,a,s=t||e.length,o=new Array(2*s);for(n=0,i=0;i<s;)if((r=e[i++])<128)o[n++]=r;else if((a=xu[r])>4)o[n++]=65533,i+=a-1;else{for(r&=2===a?31:3===a?15:7;a>1&&i<s;)r=r<<6|63&e[i++],a--;a>1?o[n++]=65533:r<65536?o[n++]=r:(r-=65536,o[n++]=55296|r>>10&1023,o[n++]=56320|1023&r)}return Uu(o,n)},utf8border:function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+xu[e[i]]>t?i:t}};var Vu=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},Hu=Object.prototype.toString,$u=0,Gu=-1,ju=0,zu=8;function Wu(e){if(!(this instanceof Wu))return new Wu(e);this.options=jc.assign({level:Gu,method:zu,chunkSize:16384,windowBits:15,memLevel:8,strategy:ju,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Vu,this.strm.avail_out=0;var i=Ou.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==$u)throw new Error(jd[i]);if(t.header&&Ou.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(n="string"==typeof t.dictionary?Bu.string2buf(t.dictionary):"[object ArrayBuffer]"===Hu.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=Ou.deflateSetDictionary(this.strm,n))!==$u)throw new Error(jd[i]);this._dict_set=!0}}function qu(e,t){var i=new Wu(t);if(i.push(e,!0),i.err)throw i.msg;return i.result}Wu.prototype.push=function(e,t){var i,n,r=this.strm,a=this.options.chunkSize;if(this.ended)return!1;n=t===~~t?t:!0===t?4:0,"string"==typeof e?r.input=Bu.string2buf(e):"[object ArrayBuffer]"===Hu.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(0===r.avail_out&&(r.output=new jc.Buf8(a),r.next_out=0,r.avail_out=a),1!==(i=Ou.deflate(r,n))&&i!==$u)return this.onEnd(i),this.ended=!0,!1;0!==r.avail_out&&(0!==r.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(Bu.buf2binstring(jc.shrinkBuf(r.output,r.next_out))):this.onData(jc.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||0===r.avail_out)&&1!==i);return 4===n?(i=Ou.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===$u):2!==n||(this.onEnd($u),r.avail_out=0,!0)},Wu.prototype.onData=function(e){this.chunks.push(e)},Wu.prototype.onEnd=function(e){e===$u&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=jc.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Ku={Deflate:Wu,deflate:qu,deflateRaw:function(e,t){return(t=t||{}).raw=!0,qu(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,qu(e,t)}},Ju=function(e,t){var i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S,y,C,_,E,T,b,I,w;i=e.state,n=e.next_in,I=e.input,r=n+(e.avail_in-5),a=e.next_out,w=e.output,s=a-(t-e.avail_out),o=a+(e.avail_out-257),l=i.dmax,c=i.wsize,d=i.whave,u=i.wnext,h=i.window,p=i.hold,g=i.bits,m=i.lencode,f=i.distcode,v=(1<<i.lenbits)-1,S=(1<<i.distbits)-1;e:do{g<15&&(p+=I[n++]<<g,g+=8,p+=I[n++]<<g,g+=8),y=m[p&v];t:for(;;){if(p>>>=C=y>>>24,g-=C,0==(C=y>>>16&255))w[a++]=65535&y;else{if(!(16&C)){if(!(64&C)){y=m[(65535&y)+(p&(1<<C)-1)];continue t}if(32&C){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}_=65535&y,(C&=15)&&(g<C&&(p+=I[n++]<<g,g+=8),_+=p&(1<<C)-1,p>>>=C,g-=C),g<15&&(p+=I[n++]<<g,g+=8,p+=I[n++]<<g,g+=8),y=f[p&S];i:for(;;){if(p>>>=C=y>>>24,g-=C,!(16&(C=y>>>16&255))){if(!(64&C)){y=f[(65535&y)+(p&(1<<C)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(E=65535&y,g<(C&=15)&&(p+=I[n++]<<g,(g+=8)<C&&(p+=I[n++]<<g,g+=8)),(E+=p&(1<<C)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=C,g-=C,E>(C=a-s)){if((C=E-C)>d&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(T=0,b=h,0===u){if(T+=c-C,C<_){_-=C;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}}else if(u<C){if(T+=c+u-C,(C-=u)<_){_-=C;do{w[a++]=h[T++]}while(--C);if(T=0,u<_){_-=C=u;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}}}else if(T+=u-C,C<_){_-=C;do{w[a++]=h[T++]}while(--C);T=a-E,b=w}for(;_>2;)w[a++]=b[T++],w[a++]=b[T++],w[a++]=b[T++],_-=3;_&&(w[a++]=b[T++],_>1&&(w[a++]=b[T++]))}else{T=a-E;do{w[a++]=w[T++],w[a++]=w[T++],w[a++]=w[T++],_-=3}while(_>2);_&&(w[a++]=w[T++],_>1&&(w[a++]=w[T++]))}break}}break}}while(n<r&&a<o);n-=_=g>>3,p&=(1<<(g-=_<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<r?r-n+5:5-(n-r),e.avail_out=a<o?o-a+257:257-(a-o),i.hold=p,i.bits=g},Yu=15,Qu=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],Zu=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Xu=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],eh=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64],th=function(e,t,i,n,r,a,s,o){var l,c,d,u,h,p,g,m,f,v=o.bits,S=0,y=0,C=0,_=0,E=0,T=0,b=0,I=0,w=0,R=0,A=null,P=0,M=new jc.Buf16(16),k=new jc.Buf16(16),D=null,O=0;for(S=0;S<=Yu;S++)M[S]=0;for(y=0;y<n;y++)M[t[i+y]]++;for(E=v,_=Yu;_>=1&&0===M[_];_--);if(E>_&&(E=_),0===_)return r[a++]=20971520,r[a++]=20971520,o.bits=1,0;for(C=1;C<_&&0===M[C];C++);for(E<C&&(E=C),I=1,S=1;S<=Yu;S++)if(I<<=1,(I-=M[S])<0)return-1;if(I>0&&(0===e||1!==_))return-1;for(k[1]=0,S=1;S<Yu;S++)k[S+1]=k[S]+M[S];for(y=0;y<n;y++)0!==t[i+y]&&(s[k[t[i+y]]++]=y);if(0===e?(A=D=s,p=19):1===e?(A=Qu,P-=257,D=Zu,O-=257,p=256):(A=Xu,D=eh,p=-1),R=0,y=0,S=C,h=a,T=E,b=0,d=-1,u=(w=1<<E)-1,1===e&&w>852||2===e&&w>592)return 1;for(;;){g=S-b,s[y]<p?(m=0,f=s[y]):s[y]>p?(m=D[O+s[y]],f=A[P+s[y]]):(m=96,f=0),l=1<<S-b,C=c=1<<T;do{r[h+(R>>b)+(c-=l)]=g<<24|m<<16|f}while(0!==c);for(l=1<<S-1;R&l;)l>>=1;if(0!==l?(R&=l-1,R+=l):R=0,y++,0==--M[S]){if(S===_)break;S=t[i+s[y]]}if(S>E&&(R&u)!==d){for(0===b&&(b=E),h+=C,I=1<<(T=S-b);T+b<_&&!((I-=M[T+b])<=0);)T++,I<<=1;if(w+=1<<T,1===e&&w>852||2===e&&w>592)return 1;r[d=R&u]=E<<24|T<<16|h-a}}return 0!==R&&(r[h+R]=S-b<<24|64<<16),o.bits=E,0},ih=1,nh=2,rh=0,ah=-2,sh=1,oh=12,lh=30,ch=852,dh=592;function uh(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function hh(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new jc.Buf16(320),this.work=new jc.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function ph(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=sh,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new jc.Buf32(ch),t.distcode=t.distdyn=new jc.Buf32(dh),t.sane=1,t.back=-1,rh):ah}function gh(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,ph(e)):ah}function mh(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?ah:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,gh(e))):ah}function fh(e,t){var i,n;return e?(n=new hh,e.state=n,n.window=null,(i=mh(e,t))!==rh&&(e.state=null),i):ah}var vh,Sh,yh=!0;function Ch(e){if(yh){var t;for(vh=new jc.Buf32(512),Sh=new jc.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(th(ih,e.lens,0,288,vh,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;th(nh,e.lens,0,32,Sh,0,e.work,{bits:5}),yh=!1}e.lencode=vh,e.lenbits=9,e.distcode=Sh,e.distbits=5}function _h(e,t,i,n){var r,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new jc.Buf8(a.wsize)),n>=a.wsize?(jc.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((r=a.wsize-a.wnext)>n&&(r=n),jc.arraySet(a.window,t,i-n,r,a.wnext),(n-=r)?(jc.arraySet(a.window,t,i-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=r))),0}var Eh={inflateReset:gh,inflateReset2:mh,inflateResetKeep:ph,inflateInit:function(e){return fh(e,15)},inflateInit2:fh,inflate:function(e,t){var i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S,y,C,_,E,T,b,I,w=0,R=new jc.Buf8(4),A=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return ah;(i=e.state).mode===oh&&(i.mode=13),s=e.next_out,r=e.output,l=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,u=o,h=l,T=rh;e:for(;;)switch(i.mode){case sh:if(0===i.wrap){i.mode=13;break}for(;d<16;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(2&i.wrap&&35615===c){i.check=0,R[0]=255&c,R[1]=c>>>8&255,i.check=Gd(i.check,R,2,0),c=0,d=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&c)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=lh;break}if(8!=(15&c)){e.msg="unknown compression method",i.mode=lh;break}if(d-=4,E=8+(15&(c>>>=4)),0===i.wbits)i.wbits=E;else if(E>i.wbits){e.msg="invalid window size",i.mode=lh;break}i.dmax=1<<E,e.adler=i.check=1,i.mode=512&c?10:oh,c=0,d=0;break;case 2:for(;d<16;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(i.flags=c,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=lh;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=lh;break}i.head&&(i.head.text=c>>8&1),512&i.flags&&(R[0]=255&c,R[1]=c>>>8&255,i.check=Gd(i.check,R,2,0)),c=0,d=0,i.mode=3;case 3:for(;d<32;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.head&&(i.head.time=c),512&i.flags&&(R[0]=255&c,R[1]=c>>>8&255,R[2]=c>>>16&255,R[3]=c>>>24&255,i.check=Gd(i.check,R,4,0)),c=0,d=0,i.mode=4;case 4:for(;d<16;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.head&&(i.head.xflags=255&c,i.head.os=c>>8),512&i.flags&&(R[0]=255&c,R[1]=c>>>8&255,i.check=Gd(i.check,R,2,0)),c=0,d=0,i.mode=5;case 5:if(1024&i.flags){for(;d<16;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.length=c,i.head&&(i.head.extra_len=c),512&i.flags&&(R[0]=255&c,R[1]=c>>>8&255,i.check=Gd(i.check,R,2,0)),c=0,d=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((p=i.length)>o&&(p=o),p&&(i.head&&(E=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),jc.arraySet(i.head.extra,n,a,p,E)),512&i.flags&&(i.check=Gd(i.check,n,p,a)),o-=p,a+=p,i.length-=p),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===o)break e;p=0;do{E=n[a+p++],i.head&&E&&i.length<65536&&(i.head.name+=String.fromCharCode(E))}while(E&&p<o);if(512&i.flags&&(i.check=Gd(i.check,n,p,a)),o-=p,a+=p,E)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===o)break e;p=0;do{E=n[a+p++],i.head&&E&&i.length<65536&&(i.head.comment+=String.fromCharCode(E))}while(E&&p<o);if(512&i.flags&&(i.check=Gd(i.check,n,p,a)),o-=p,a+=p,E)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;d<16;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(c!==(65535&i.check)){e.msg="header crc mismatch",i.mode=lh;break}c=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=oh;break;case 10:for(;d<32;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}e.adler=i.check=uh(c),c=0,d=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,2;e.adler=i.check=1,i.mode=oh;case oh:if(5===t||6===t)break e;case 13:if(i.last){c>>>=7&d,d-=7&d,i.mode=27;break}for(;d<3;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}switch(i.last=1&c,d-=1,3&(c>>>=1)){case 0:i.mode=14;break;case 1:if(Ch(i),i.mode=20,6===t){c>>>=2,d-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=lh}c>>>=2,d-=2;break;case 14:for(c>>>=7&d,d-=7&d;d<32;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if((65535&c)!=(c>>>16^65535)){e.msg="invalid stored block lengths",i.mode=lh;break}if(i.length=65535&c,c=0,d=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(p=i.length){if(p>o&&(p=o),p>l&&(p=l),0===p)break e;jc.arraySet(r,n,a,p,s),o-=p,a+=p,l-=p,s+=p,i.length-=p;break}i.mode=oh;break;case 17:for(;d<14;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(i.nlen=257+(31&c),c>>>=5,d-=5,i.ndist=1+(31&c),c>>>=5,d-=5,i.ncode=4+(15&c),c>>>=4,d-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=lh;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;d<3;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.lens[A[i.have++]]=7&c,c>>>=3,d-=3}for(;i.have<19;)i.lens[A[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,b={bits:i.lenbits},T=th(0,i.lens,0,19,i.lencode,0,i.work,b),i.lenbits=b.bits,T){e.msg="invalid code lengths set",i.mode=lh;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;v=(w=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(S<16)c>>>=f,d-=f,i.lens[i.have++]=S;else{if(16===S){for(I=f+2;d<I;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(c>>>=f,d-=f,0===i.have){e.msg="invalid bit length repeat",i.mode=lh;break}E=i.lens[i.have-1],p=3+(3&c),c>>>=2,d-=2}else if(17===S){for(I=f+3;d<I;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}d-=f,E=0,p=3+(7&(c>>>=f)),c>>>=3,d-=3}else{for(I=f+7;d<I;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}d-=f,E=0,p=11+(127&(c>>>=f)),c>>>=7,d-=7}if(i.have+p>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=lh;break}for(;p--;)i.lens[i.have++]=E}}if(i.mode===lh)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=lh;break}if(i.lenbits=9,b={bits:i.lenbits},T=th(ih,i.lens,0,i.nlen,i.lencode,0,i.work,b),i.lenbits=b.bits,T){e.msg="invalid literal/lengths set",i.mode=lh;break}if(i.distbits=6,i.distcode=i.distdyn,b={bits:i.distbits},T=th(nh,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,b),i.distbits=b.bits,T){e.msg="invalid distances set",i.mode=lh;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(o>=6&&l>=258){e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,Ju(e,h),s=e.next_out,r=e.output,l=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,i.mode===oh&&(i.back=-1);break}for(i.back=0;v=(w=i.lencode[c&(1<<i.lenbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(v&&!(240&v)){for(y=f,C=v,_=S;v=(w=i.lencode[_+((c&(1<<y+C)-1)>>y)])>>>16&255,S=65535&w,!(y+(f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}c>>>=y,d-=y,i.back+=y}if(c>>>=f,d-=f,i.back+=f,i.length=S,0===v){i.mode=26;break}if(32&v){i.back=-1,i.mode=oh;break}if(64&v){e.msg="invalid literal/length code",i.mode=lh;break}i.extra=15&v,i.mode=22;case 22:if(i.extra){for(I=i.extra;d<I;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.length+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;v=(w=i.distcode[c&(1<<i.distbits)-1])>>>16&255,S=65535&w,!((f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(!(240&v)){for(y=f,C=v,_=S;v=(w=i.distcode[_+((c&(1<<y+C)-1)>>y)])>>>16&255,S=65535&w,!(y+(f=w>>>24)<=d);){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}c>>>=y,d-=y,i.back+=y}if(c>>>=f,d-=f,i.back+=f,64&v){e.msg="invalid distance code",i.mode=lh;break}i.offset=S,i.extra=15&v,i.mode=24;case 24:if(i.extra){for(I=i.extra;d<I;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}i.offset+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=lh;break}i.mode=25;case 25:if(0===l)break e;if(p=h-l,i.offset>p){if((p=i.offset-p)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=lh;break}p>i.wnext?(p-=i.wnext,g=i.wsize-p):g=i.wnext-p,p>i.length&&(p=i.length),m=i.window}else m=r,g=s-i.offset,p=i.length;p>l&&(p=l),l-=p,i.length-=p;do{r[s++]=m[g++]}while(--p);0===i.length&&(i.mode=21);break;case 26:if(0===l)break e;r[s++]=i.length,l--,i.mode=21;break;case 27:if(i.wrap){for(;d<32;){if(0===o)break e;o--,c|=n[a++]<<d,d+=8}if(h-=l,e.total_out+=h,i.total+=h,h&&(e.adler=i.check=i.flags?Gd(i.check,r,h,s-h):Vd(i.check,r,h,s-h)),h=l,(i.flags?c:uh(c))!==i.check){e.msg="incorrect data check",i.mode=lh;break}c=0,d=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;d<32;){if(0===o)break e;o--,c+=n[a++]<<d,d+=8}if(c!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=lh;break}c=0,d=0}i.mode=29;case 29:T=1;break e;case lh:T=-3;break e;case 31:return-4;default:return ah}return e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,(i.wsize||h!==e.avail_out&&i.mode<lh&&(i.mode<27||4!==t))&&_h(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,i.total+=h,i.wrap&&h&&(e.adler=i.check=i.flags?Gd(i.check,r,h,e.next_out-h):Vd(i.check,r,h,e.next_out-h)),e.data_type=i.bits+(i.last?64:0)+(i.mode===oh?128:0)+(20===i.mode||15===i.mode?256:0),(0===u&&0===h||4===t)&&T===rh&&(T=-5),T},inflateEnd:function(e){if(!e||!e.state)return ah;var t=e.state;return t.window&&(t.window=null),e.state=null,rh},inflateGetHeader:function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?(i.head=t,t.done=!1,rh):ah},inflateSetDictionary:function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?ah:11===i.mode&&Vd(1,t,n,0)!==i.check?-3:_h(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,rh):ah},inflateInfo:"pako inflate (from Nodeca project)"},Th={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var bh=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},Ih=Object.prototype.toString;function wh(e){if(!(this instanceof wh))return new wh(e);this.options=jc.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Vu,this.strm.avail_out=0;var i=Eh.inflateInit2(this.strm,t.windowBits);if(i!==Th.Z_OK)throw new Error(jd[i]);this.header=new bh,Eh.inflateGetHeader(this.strm,this.header)}function Rh(e,t){var i=new wh(t);if(i.push(e,!0),i.err)throw i.msg;return i.result}wh.prototype.push=function(e,t){var i,n,r,a,s,o,l=this.strm,c=this.options.chunkSize,d=this.options.dictionary,u=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?Th.Z_FINISH:Th.Z_NO_FLUSH,"string"==typeof e?l.input=Bu.binstring2buf(e):"[object ArrayBuffer]"===Ih.call(e)?l.input=new Uint8Array(e):l.input=e,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new jc.Buf8(c),l.next_out=0,l.avail_out=c),(i=Eh.inflate(l,Th.Z_NO_FLUSH))===Th.Z_NEED_DICT&&d&&(o="string"==typeof d?Bu.string2buf(d):"[object ArrayBuffer]"===Ih.call(d)?new Uint8Array(d):d,i=Eh.inflateSetDictionary(this.strm,o)),i===Th.Z_BUF_ERROR&&!0===u&&(i=Th.Z_OK,u=!1),i!==Th.Z_STREAM_END&&i!==Th.Z_OK)return this.onEnd(i),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&i!==Th.Z_STREAM_END&&(0!==l.avail_in||n!==Th.Z_FINISH&&n!==Th.Z_SYNC_FLUSH)||("string"===this.options.to?(r=Bu.utf8border(l.output,l.next_out),a=l.next_out-r,s=Bu.buf2string(l.output,r),l.next_out=a,l.avail_out=c-a,a&&jc.arraySet(l.output,l.output,r,a,0),this.onData(s)):this.onData(jc.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(u=!0)}while((l.avail_in>0||0===l.avail_out)&&i!==Th.Z_STREAM_END);return i===Th.Z_STREAM_END&&(n=Th.Z_FINISH),n===Th.Z_FINISH?(i=Eh.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Th.Z_OK):n!==Th.Z_SYNC_FLUSH||(this.onEnd(Th.Z_OK),l.avail_out=0,!0)},wh.prototype.onData=function(e){this.chunks.push(e)},wh.prototype.onEnd=function(e){e===Th.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=jc.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Ah={Inflate:wh,inflate:Rh,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Rh(e,t)},ungzip:Rh},Ph={};(0,jc.assign)(Ph,Ku,Ah,Th);var Mh=Ph;function kh(){let e,t,i=!0;return{isPending:()=>i,promise:new Promise(((i,n)=>{e=i,t=n})),resolve:t=>{i&&(e(t),i=!1)},reject:e=>{i&&(t(e),i=!1)}}}function Dh(e){return new Promise((t=>Oh(t,e)))}function Oh(e,t){return globalThis.setTimeout(e,t)}function Nh(e){globalThis.clearTimeout(e)}function Lh(e,t){const i=kh();let n;try{n=e()}catch(e){return Promise.reject(i.reject(e))}if(t<0)return n.finally((()=>{i.resolve(n)})),i.promise;const r=Oh((()=>{i.isPending()&&i.reject(new b({defaultError:f.INTERNAL.OPERATION_TIMEDOUT}))}),t);return n.catch((e=>{Nh(r),i.isPending()&&i.reject(e)})).finally((()=>{Nh(r),i.isPending()&&i.resolve(n)})),i.promise}var xh=function(e,t){var i=e.toString(),n=t.toString();return i>n?1:i<n?-1:0};function Fh(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function Uh(e,t,i){return t&&Fh(e.prototype,t),i&&Fh(e,i),e}var Bh=function(){function e(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).comparator,i=void 0===t?xh:t;(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,e),function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(this,"comparator",void 0),this.comparator=i}return Uh(e,null,[{key:"from",value:function(e,t){throw new Error("not implemented")}}]),Uh(e,[{key:"clear",value:function(){throw new Error("not implemented")}},{key:"toArray",value:function(){throw new Error("not implemented")}},{key:"push",value:function(e){throw new Error("not implemented")}},{key:"enqueue",value:function(e){return this.push(e)}},{key:"top",value:function(){throw new Error("not implemented")}},{key:"peek",value:function(){return this.top()}},{key:"pop",value:function(){throw new Error("not implemented")}},{key:"dequeue",value:function(){return this.pop()}},{key:"merge",value:function(e){throw new Error("not implemented")}},{key:"isEmpty",value:function(){throw new Error("not implemented")}},{key:"length",get:function(){throw new Error("not implemented")}}]),e}();function Vh(e){return Vh="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Vh(e)}function Hh(e){return function(e){if(Array.isArray(e)){for(var t=0,i=new Array(e.length);t<e.length;t++)i[t]=e[t];return i}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function $h(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function Gh(e){return Gh=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},Gh(e)}function jh(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function zh(e,t){return zh=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},zh(e,t)}function Wh(e,t,i){var n=function(e,t,i){var n=2*t,r=2*t+1,a=t;return n<e.length&&i(e[a],e[n])<0&&(a=n),r<e.length&&i(e[a],e[r])<0&&(a=r),a}(e,t,i);if(n!==t){var r=e[t];e[t]=e[n],e[n]=r,Wh(e,n,i)}}function qh(e){for(var t=Math.floor(e.collection.length/2)-1;t>=0;--t)Wh(e.collection,t,e.comparator)}var Kh,Jh,Yh,Qh,Zh,Xh,ep,tp=function(e){function t(){var e,i;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return function(e,t,i){t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}(jh(i=function(e,t){return!t||"object"!==Vh(t)&&"function"!=typeof t?jh(e):t}(this,(e=Gh(t)).call.apply(e,[this].concat(r)))),"collection",[]),i}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&zh(e,t)}(t,e),function(e,t,i){t&&$h(e.prototype,t),i&&$h(e,i)}(t,[{key:"clear",value:function(){this.collection.length=0}},{key:"toArray",value:function(){return Hh(this.collection).sort(this.comparator)}},{key:"top",value:function(){if(0===this.length)throw new Error("invalid operation: top() called for empty BinaryHeap");return this.collection[0]}},{key:"pop",value:function(){if(0===this.length)throw new Error("invalid operation: pop() called for empty BinaryHeap");var e=this.collection[0];return this.collection.length>1?(this.collection[0]=this.collection.pop(),Wh(this.collection,0,this.comparator)):this.collection.pop(),e}},{key:"push",value:function(e){this.collection.push(e);for(var t=this.collection,i=t.length-1,n=Math.floor(i/2);i>0&&this.comparator(t[n],t[i])<0;i=n,n=Math.floor(n/2)){var r=t[i];t[i]=t[n],t[n]=r}}},{key:"merge",value:function(e){this.collection=e instanceof t?this.collection.concat(e.collection):this.collection.concat(e.toArray()),qh(this),e.clear()}},{key:"isEmpty",value:function(){return!this.collection.length}},{key:"length",get:function(){return this.collection.length}}],[{key:"from",value:function(e){var i=new t(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{});return i.collection=Array.from(e),qh(i),i}}]),t}(Bh),ip=tp;class np{constructor(e,t){this._tenantId=e,this.listeners=[],this._logger=t.createChild(`TelemetryLogger[${e}]`);const i=this._tenantId;t.log(`Notification Manager Notification Manager logger initialized for tenant ${i}`),this._discardedEventsBufferPQ=new ip({comparator:(e,t)=>t.latency-e.latency})}addNotificationListener(e){this.listeners.find((t=>t===e))||this.listeners.push(e)}removeNotificationListener(e){this.listeners=this.listeners.filter((t=>t!==e))}eventsSent(e){const t=JSON.stringify(e);this._logger.log(`Notification Manager sent telemetry events ${t}`),this.listeners.forEach((t=>t.eventsSent&&t.eventsSent(e)))}eventsDiscarded(e,t){this._logger.log(`Notification Manager discarded telemetry events ${JSON.stringify(e)}, reason ${t} adding to retry buffer`),e.forEach((e=>{e.latency=e.latency||an;const t=e;(t.sendAttempt||0)<=yc().telemetry.discardedEventsMaxRetries?this._discardedEventsBufferPQ.push(t):this._logger.log(`Notification Manager dropping event due to too many retries ${JSON.stringify(e)}`)}));const i=yc().telemetry.discardedEventsBufferMaxLength;for(;this._discardedEventsBufferPQ.length>i;)this._logger.log(` dropping event from retry buffer ${this._discardedEventsBufferPQ.dequeue()} due to overflow`);this.listeners.forEach((i=>i.eventsDiscarded&&i.eventsDiscarded(e,t)))}getDiscardedEvents(){const e=[],t=this._discardedEventsBufferPQ.length;for(let i=0;i<t;i++)e.push(this._discardedEventsBufferPQ.dequeue());return e}}class rp{constructor(e,t,i,n){this._telemetryLoggers=new Map,this._eventsBufferMap=new Map,this._initialized=!1,this.sdkDiagnosticInformation="",this._telemetryRateLimit=new Map,this._mediaEventsReportedForTheCall={},this._logger=e.createChild("TelemetryLogManager"),this.sdkDiagnosticInformation=t,this._sdkInternaVersion=dc(),this._acsProxy=i,this._acsCustomRelayManager=n,yc().telemetry.limit.rates.forEach((e=>{this._telemetryRateLimit.set(e.eventName,{...e,windowStartTime:Date.now(),eventCount:0})}))}getTelemetryLoggers(){return this._telemetryLoggers}getEventsBufferMap(){return this._eventsBufferMap}isInitialized(){return this._initialized}getCloudType(){return this._caConfigBag?.cloudType}getAcsResourceId(){return this._caConfigBag?.acsResourceId}getClientId(){return this._caConfigBag?.clientId}initialize(e){if(!e.cloudType)throw this._logger.error("Failed to initialize telemetry loggers, invalid cloud type provided."),new b({defaultError:f.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE_INVALID_CLOUD_TYPE});if(this._initialized)throw this._logger.error("Failed to initialize telemetry loggers, telemetry log manager is already initialized."),new b({defaultError:f.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE_ALREADY_INITIALIZED});this._telemetryLoggers.forEach(((t,i)=>{try{t.initialize(e),this._logger.log(`Initialized and flushed buffered telemetry logger for ${i}`)}catch(e){this._logger.warn(`Failed to initialize and flush buffered telemetry logger for ${i}`),this._telemetryLoggers.delete(i)}})),this._initialized=!0,this._caConfigBag=e,this._logger.log(`Telemetry log manager has been initialized for Call Client: ${this._caConfigBag.clientId}`)}clearTelemetryLoggers(){const e=this._telemetryLoggers.size;return this._telemetryLoggers=new Map,this._caConfigBag=void 0,this._initialized=!1,e}getMediaEventReportedPromise(e){if(!this._mediaEventsReportedForTheCall[e]){const t=Rc();t.promise.catch(Oc),this._mediaEventsReportedForTheCall[e]=t}return this._mediaEventsReportedForTheCall[e].promise}_reportMediaEventForTheCall(e){if(this._mediaEventsReportedForTheCall[e])this._mediaEventsReportedForTheCall[e].resolve();else{const t=Rc();t.promise.catch(Oc),t.resolve(),this._mediaEventsReportedForTheCall[e]=t}}_getEventDataWithoutPii(e){const t={};if(e.properties)for(const i of Object.keys(e.properties)){const n=e.properties[i];t[i]={value:n?.value??n,kind:n?.piiKind??0}}return t}sendEvent(e,t){try{if(this._logger.debug(`sending event=${e.name}`),this.checkIfEventIsBlocked(e.name)||this.shouldLimitSendingTelemetry(e.name)||this.isRateLimitExceeded(e.name))return void this._logger.debug(`event=${e.name} is blocked`);const i={name:e.name,data:e.properties};i?.name in dp&&(i.data=this._getEventDataWithoutPii(e)),void 0===i.data&&(i.data={}),i?.name===dp.mdsc_webrtc_session&&this._reportMediaEventForTheCall(i?.data?.CorrelationId),void 0!==typeof e.priority?i.latency=e.priority:i.latency=an;const n=yc().telemetryEvents.eventNameToPriority.eventName.indexOf(e.name);-1!==n&&(i.latency=yc().telemetryEvents.eventNameToPriority.priority[n]),i.data.sdkVersion=this._sdkInternaVersion,i.data.platformId="3617";const r=`3617/${this._sdkInternaVersion}`;i.data.uiVersion=r,i.data.ui_version=r,i.data.Platform_Uiversion=r,i.data.userAgent=`${this.sdkDiagnosticInformation} ${navigator.userAgent}`,i.data.clientTimestamp=+new Date,i.data.customProxyAndRelayUsage=this.getCustomProxyAndRelayTag();const a=e.tenant;let s=this._eventsBufferMap.get(a);s||(s=this._eventsBufferMap.set(a,[]).get(a));let o=this._telemetryLoggers.get(a);if(o||(o=new ap(a,this._logger,s,this._acsProxy),this._telemetryLoggers.set(a,o),this._logger.log(`Created telemetry logger for ${a}`)),this._initialized){if(!o.isInitialized())try{o.initialize(this._caConfigBag),this._logger.log(`Created and initialized telemetry logger for ${a}`)}catch(e){throw this._telemetryLoggers.delete(a),s?.push(i),this._logger.error(`Failed to create and initialize telemetry logger for ${a}`),new b({defaultError:f.INTERNAL.TELEMETRY_FAILED_TO_INITIALIZE,defaultErrorMessageArgs:[a]})}t&&o.getAppInsightsCore()?.addNotificationListener(t),o.sendEvent(i)}else s?.push(i)}catch(t){this._logger.warn(`Failed to send event ${e?.name}`)}}async flushAllEvents(e){if(this._logger.debug(`flushing events: ${this._telemetryLoggers.size}`),-1!==yc().telemetry.telemetryFlushTimeout){const t=(t,i)=>{try{const n=Rc();n.promise.catch(Oc);const r=Lh((async()=>(i===gl&&await this.getMediaEventReportedPromise(e),n.promise)),yc().telemetry.telemetryFlushTimeout);return t.flushEvents((()=>{this._logger.debug("events flushed"),n.resolve()})),r.then(Oc)}catch(e){throw new b({defaultError:f.INTERNAL.TELEMETRY_FAILED_TO_FLUSH})}},i=[];return this._telemetryLoggers.forEach(((e,n)=>{i.push(t(e,n).catch((()=>{this._logger.warn("Failed to flush telemetry")})))})),Promise.all(i)}this._telemetryLoggers.forEach((e=>{try{e.flushEvents()}catch(e){this._logger.warn("Failed to flush telemetry")}}))}checkIfEventIsBlocked(e){if(Array.isArray(yc()?.telemetry?.blockedEvents)){const t=yc()?.telemetry?.blockedEvents;return Array.isArray(t)&&t?.indexOf(e)>-1||!1}return!1}shouldLimitSendingTelemetry(e){return yc().telemetry.limit.outSideCall.enabled&&(0===yc().telemetry.limit.outSideCall.includedEvents.length||yc().telemetry.limit.outSideCall.includedEvents.includes(e))&&!yc().telemetry.limit.outSideCall.excludedEvents.includes(e)&&rp.callEndTimestamp!==Number.MAX_SAFE_INTEGER&&rp.callEndTimestamp+yc().telemetry.limit.outSideCall.deltaTimeInMs-Date.now()<0}isRateLimitExceeded(e){const t=this._telemetryRateLimit.get(e);if(t){const i=Date.now();if(i-t.windowStartTime>t.windowSizeInMs&&(t.windowStartTime=i,t.eventCount=0),t.eventCount++,t.eventCount>t.maxEventPerWindow)return this._logger.info(`Telemetry event ${e} is rate limited`),!0}return!1}getCustomProxyAndRelayTag(){const e=this._acsProxy?.proxyInUse??!1,t=this._acsCustomRelayManager?.hasRelayConfig??!1;return e&&t?Kl.usedProxyAndNonMsftTurn:e?Kl.onlyUsedProxy:t?Kl.onlyUsedNonMsftTurn:Kl.noCustomProxyAndTurnUsed}}rp.telemetryPayloadBytesOriginal=0,rp.telemetryPayloadBytesCompressed=0,rp.callEndTimestamp=0;class ap{constructor(e,t,i,n){this._tenantId=e,this._eventsBuffer=i,this._initialized=!1,this._networkOnline=!0,this._telemetryRetryIntervalRunning=!1,this._logger=t.createChild(`TelemetryLogger[${e}]`),this._acsProxy=n,window.addEventListener("online",(e=>{this._networkOnline=e.detail,this._networkOnline&&this._initialized&&!this._telemetryRetryIntervalRunning&&(this._logger.log("browser network back online starting telemetry send retry"),this.scheduleDiscardedTelemetryRetry())}))}initialize(e){if(this._initialized)this._logger.warn(`Telemetry logger for tenant: ${this._tenantId}, already initialized`);else try{const t=new Uo;this._appInsightsCore=new An,this._postChannel=new ws;const i={instrumentationKey:this._tenantId,extensions:[this._postChannel,t],disableCookiesUsage:!0},n={populateBrowserInfo:!0,populateOperatingSystemInfo:!0};void 0===i.extensionConfig&&(i.extensionConfig={}),i.extensionConfig[t.identifier]=n;const r={overrideEndpointUrl:this.getAriaCollectorUrl(e),payloadPreprocessor:yc().telemetry.gzipTelemetryPayload?(e,t)=>{this.gzipPayload(e,t)}:void 0};if(i.extensionConfig[this._postChannel.identifier]=r,Object.keys(yc().calling?.eudb?.acsCompliantEvents).length>0&&(sp={...sp,...yc().calling.eudb.acsCompliantEvents}),yc().telemetry.localStorageEnable){const e=new Ha;i.extensions?.push(e);const t={storageKey:"WebSdkTelemetry"};i.extensionConfig[e.identifier]=t}this._NotificationManager=new np(this._tenantId,this._logger),this._appInsightsCore.initialize(i,[],void 0,this._NotificationManager),this._caConfigBag=e,this.scheduleDiscardedTelemetryRetry(),this._initialized=!0,this._eventsBuffer.forEach((e=>{this.sendEvent(e)})),this._eventsBuffer.splice(0,this._eventsBuffer.length)}catch(e){throw this._logger.error(`Failed to initialize telemetry logger for tenant: ${this._tenantId}`),new b({defaultError:f.INTERNAL.TELEMETRY_LOGGER_INIT_FAIL})}}getCloudType(){return this._caConfigBag?.cloudType}getAcsResourceId(){return this._caConfigBag?.acsResourceId}getClientId(){return this._caConfigBag?.clientId}isInitialized(){return this._initialized}getAppInsightsCore(){return this._appInsightsCore}sendEvent(e){this._initialized&&(e?.name in sp&&this.appendEudbComplianceRegionToEvent(e),e?.data&&(e.data.clientId=this._caConfigBag?.clientId||"",0===e?.name?.indexOf("mdsc_webrtc")?e.data.metrics_AcsResourceId=this._caConfigBag?.acsResourceId||"":e.data.AcsResourceId=this._caConfigBag?.acsResourceId||"",e.data.cloudType=this._caConfigBag?.cloudType||"",e.data.identityType=this._caConfigBag?.identityType||""),this.sendAppInsightsCoreEvent(e))}scheduleDiscardedTelemetryRetry(){const e=yc().telemetry.discardedTelemetryRetryTimeout;let t=setInterval((async()=>{this._networkOnline?(this._NotificationManager?.getDiscardedEvents().forEach((e=>{this.sendEvent(e)})),this._telemetryRetryIntervalRunning=!0):(this._logger.log("browser lost network access stopping telemetry send retry"),clearInterval(t),this._telemetryRetryIntervalRunning=!1)}),e)}sendAppInsightsCoreEvent(e){this._appInsightsCore?.track(e)}flushEvents(e){this._initialized&&this._postChannel&&this._postChannel.flush(!1,e)}getAriaCollectorUrl(e){const t=Lc(e.identityType,e.region);let i;if(e.identityType===il.Enterprise)i=t?Wo:zo;else switch(e.cloudType){case qo.Public:i=t?Vo:Bo;break;case qo.GccHigh:i=Ho;break;case qo.Dod:i=$o;break;case qo.AirGap08:i=Go;break;case qo.AirGap09:i=jo;break;default:i=Bo}return this._acsProxy?this._acsProxy.proxyfyUrl(i):i}gzipPayload(e,t){try{rp.telemetryPayloadBytesOriginal+=Ic(e.data,this._logger),e.data=Mh.gzip(e.data),e.urlString+="&content-encoding=gzip",rp.telemetryPayloadBytesCompressed+=Ic(e.data,this._logger)}catch(e){this._logger.warn("Failed to gzip with pako: ",e)}t(e)}getRegion(e){if(this._caConfigBag&&xc(this._caConfigBag.identityType))switch(e){case"emea":case"de":return cl.EMEA;case"apac":return cl.APAC;case"noam":case"amer":return cl.NOAM;default:return this._logger.log(`Unable to map region \`${e}\`, to EudbTenantRegion`),cl.UNKNOWN}return e&&al.includes(e)?cl.EMEA:e&&sl.includes(e)?cl.APAC:e&&ol.includes(e)?cl.NOAM:(this._logger.log(`Unable to map region \`${e}\`, to EudbTenantRegion`),cl.UNKNOWN)}appendEudbComplianceRegionToEvent(e){let t=this.getTenantComplianceRegion();const i=this.getRegion(this._caConfigBag?.region);if(e.data){let n={};n[op]=t,n[cp]=i,e.data[lp]=n}}getTenantComplianceRegion(){return this._caConfigBag&&Lc(this._caConfigBag.identityType,this._caConfigBag.region)?ll.EU:ll.RoW}}!function(e){e.remote_view="remote_view",e.remote_stream="remote_stream",e.network_quality="network_quality",e.video_device_issue="video_device_issue",e.other_diagnostic="other_diagnostic",e.logger_event="logger_event",e.number_of_participants="number_of_participants",e.media_metrics_device_events="media_metrics_device_events",e.sdk_active_in_another_tab="sdk_active_in_another_tab",e.network_changed="network_changed"}(Kh||(Kh={})),function(e){e.acs_calling_call_attempt="acs_calling_call_attempt",e.acs_calling_call_connected="acs_calling_call_connected",e.acs_calling_call_failed="acs_calling_call_failed",e.acs_calling_call_accept_attempt="acs_calling_call_accept_attempt",e.acs_calling_call_accept_connected="acs_calling_call_accept_connected",e.acs_calling_call_accept_failed="acs_calling_call_accept_failed",e.acs_calling_call_reject_attempt="acs_calling_call_reject_attempt",e.acs_calling_call_reject_success="acs_calling_call_reject_success",e.acs_calling_call_reject_failed="acs_calling_call_reject_failed",e.acs_calling_call_hangup_attempt="acs_calling_call_hangup_attempt",e.acs_calling_call_hangup_success="acs_calling_call_hangup_success",e.acs_calling_call_hangup_failure="acs_calling_call_hangup_failure",e.acs_calling_call_progress="acs_calling_call_progress",e.acs_calling_stack_init="acs_calling_stack_init",e.acs_calling_get_device_manager="acs_calling_get_device_manager",e.acs_calling_config_fetched_attempt="acs_calling_config_fetched_attempt",e.acs_calling_config_fetched_success="acs_calling_config_fetched_success",e.acs_calling_config_fetched_failure="acs_calling_config_fetched_failure",e.acs_calling_signaling_init="acs_calling_signaling_init",e.acs_calling_call_agent="acs_calling_call_agent",e.acs_calling_call_agent_init_attempt="acs_calling_call_agent_init_attempt",e.acs_calling_call_agent_init_success="acs_calling_call_agent_init_success",e.acs_calling_call_agent_init_failure="acs_calling_call_agent_init_failure",e.acs_calling_create_view_attempt="acs_calling_create_view_attempt",e.acs_calling_create_view_success="acs_calling_create_view_success",e.acs_calling_create_view_failure="acs_calling_create_view_failure",e.acs_calling_dispose_view_attempt="acs_calling_dispose_view_attempt",e.acs_calling_dispose_view_success="acs_calling_dispose_view_success",e.acs_calling_dispose_view_failure="acs_calling_dispose_view_failure",e.acs_calling_start_video_attempt="acs_calling_start_video_attempt",e.acs_calling_start_video_success="acs_calling_start_video_success",e.acs_calling_start_video_failure="acs_calling_start_video_failure",e.acs_calling_stop_video_on_ufd_attempt="acs_calling_stop_video_on_ufd_attempt",e.acs_calling_stop_video_attempt="acs_calling_stop_video_attempt",e.acs_calling_stop_video_success="acs_calling_stop_video_success",e.acs_calling_stop_video_failure="acs_calling_stop_video_failure",e.acs_calling_call_hold_and_resume="acs_calling_call_hold_and_resume",e.acs_calling_start_screen_share="acs_calling_start_screen_share",e.acs_calling_stop_screen_share="acs_calling_stop_screen_share",e.acs_calling_audio_stream_volume="acs_calling_audio_stream_volume",e.acs_calling_call_stats="acs_calling_call_stats",e.acs_calling_participant_added_or_removed="acs_calling_participant_added_or_removed",e.acs_calling_adp_attempt="acs_calling_adp_attempt",e.acs_calling_adp_success="acs_calling_adp_success",e.acs_calling_adp_failure="acs_calling_adp_failure",e.acs_calling_client_operations="acs_calling_client_operations",e.acs_calling_device_permission_changed="acs_calling_device_permission_changed",e.acs_calling_local_audio_source_changed="acs_calling_local_audio_source_changed",e.acs_calling_start_audio_stream_track="acs_calling_start_audio_stream_track",e.acs_calling_stop_audio_stream_track="acs_calling_stop_audio_stream_track",e.acs_calling_get_remote_audio_stream_track="acs_calling_get_remote_audio_stream_track",e.acs_calling_get_raw_device_media_stream="acs_calling_get_raw_device_media_stream",e.acs_calling_media_stream="acs_calling_media_stream",e.acs_calling_page_hidden="acs_calling_page_hidden",e.acs_calling_orientation_changed="acs_calling_orientation_changed",e.acs_calling_token_expiration_changed="acs_calling_token_expiration_changed",e.acs_calling_token_expiration_changed_failure="acs_calling_token_expiration_changed_failure",e.acs_calling_token_expired="acs_calling_token_expired",e.acs_calling_token_has_no_data_location="acs_calling_token_has_no_data_location",e.acs_calling_mute_on_ufd_attempt="acs_calling_mute_on_ufd_attempt",e.acs_calling_mute_attempt="acs_calling_mute_attempt",e.acs_calling_mute_success="acs_calling_mute_success",e.acs_calling_mute_failure="acs_calling_mute_failure",e.acs_calling_unmute_attempt="acs_calling_unmute_attempt",e.acs_calling_unmute_success="acs_calling_unmute_success",e.acs_calling_unmute_failure="acs_calling_unmute_failure",e.acs_calling_start_audio_attempt="acs_calling_start_audio_attempt",e.acs_calling_start_audio_success="acs_calling_start_audio_success",e.acs_calling_start_audio_failure="acs_calling_start_audio_failure",e.acs_calling_unmute_speaker_attempt="acs_calling_unmute_speaker_attempt",e.acs_calling_unmute_speaker_success="acs_calling_unmute_speaker_success",e.acs_calling_unmute_speaker_failure="acs_calling_unmute_speaker_failure",e.acs_calling_stop_audio_attempt="acs_calling_stop_audio_attempt",e.acs_calling_stop_audio_success="acs_calling_stop_audio_success",e.acs_calling_stop_audio_failure="acs_calling_stop_audio_failure",e.acs_calling_prevent_stop_audio="acs_calling_prevent_stop_audio",e.acs_calling_captions="acs_calling_captions",e.acs_calling_mid_call_media_stats="acs_calling_mid_call_media_stats",e.acs_calling_mid_call_new_media_stats="acs_calling_mid_call_new_media_stats",e.acs_calling_mid_call_raw_media_stats="acs_calling_mid_call_raw_media_stats",e.acs_calling_datachannel="acs_calling_datachannel",e.acs_calling_datachannel_stats="acs_calling_datachannel_stats",e.acs_calling_unmixed_audio="acs_calling_unmixed_audio",e.acs_calling_livestream_stats="acs_calling_livestream_stats",e.acs_calling_livestream_raw_stats="acs_calling_livestream_raw_stats",e.acs_calling_survey="acs_calling_survey",e.acs_calling_switch_video_source_attempt="acs_calling_switch_video_source_attempt",e.acs_calling_switch_video_source_success="acs_calling_switch_video_source_success",e.acs_calling_switch_video_source_failure="acs_calling_switch_video_source_failure",e.acs_calling_diagnostics_attempt="acs_calling_diagnostics_attempt",e.acs_calling_diagnostics_result="acs_calling_diagnostics_result",e.acs_calling_feature_usage="acs_calling_feature_usage",e.acs_calling_middletier_gateway_fetch_policy="acs_calling_middletier_gateway_fetch_policy",e.acs_calling_middletier_gateway_emergency_content="acs_calling_middletier_gateway_emergency_content",e.acs_calling_middletier_gateway_fetch_user_policies_for_captions="acs_calling_middletier_gateway_fetch_user_policies_for_captions",e.acs_calling_middletier_gateway_api="acs_calling_middletier_gateway_api",e.acs_calling_call_client_init="acs_calling_call_client_init",e.acs_calling_tab_events="acs_calling_tab_events",e.acs_calling_lobby_events="acs_calling_lobby_events",e.acs_calling_handle_push_notification="acs_calling_handle_push_notification"}(Jh||(Jh={})),function(e){e.attempt="attempt",e.success="success",e.failure="failure",e.getter="getter",e.setter="setter",e.subscribe="subscribe",e.unsubscribe="unsubscribe",e.initialize="initialize",e.event="event"}(Yh||(Yh={})),function(e){e.lobbyAdmit="lobbyAdmit",e.lobbyAdmitAll="lobbyAdmitAll",e.lobbyReject="lobbyReject"}(Qh||(Qh={})),function(e){e.MuteMicrophone="MuteMicrophone",e.MuteAllRemoteParticipants="MuteAllRemoteParticipants",e.MuteSpecificParticipant="MuteSpecificParticipant",e.UnmuteMicrophone="UnmuteMicrophone",e.MuteIncomingAudio="MuteIncomingAudio",e.UnmuteIncomingAudio="UnmuteIncomingAudio"}(Zh||(Zh={})),function(e){e.Expected="expected",e.Unexpected="unexpected",e.Unknown="unknown"}(Xh||(Xh={})),function(e){e.CaptionsKindChanged="CaptionsKindChanged",e.FirstCaptionReceived="FirstCaptionReceived",e.FirstCaptionParsingError="FirstCaptionParsingError",e.InitializeCaptions="InitializeCaptions",e.LanguageChanged="LanguageChanged",e.SetSpokenLanguage="SetSpokenLanguage",e.SetCaptionLanguage="SetCaptionLanguage",e.SpokenLanguageChanged="SpokenLanguageChanged",e.StartCaptions="StartCaptions",e.StopCaptions="StopCaptions",e.UpdateIsActive="UpdateIsActive"}(ep||(ep={}));let sp={...Jh,skypecosi_concore_web_csa_conversation_callmodality:"skypecosi_concore_web_csa_conversation_callmodality",skypecosi_concore_web_pluginless_modality_session:"skypecosi_concore_web_pluginless_modality_session",skypecosi_concore_web_pluginless_call_session:"skypecosi_concore_web_pluginless_call_session",skypecosi_concore_web_csa_conversation_httprequest:"skypecosi_concore_web_csa_conversation_httprequest"};const op="tenantComplianceRegion",lp="acsCompliancePayload",cp="tenantRegion";var dp,up,hp,pp,gp,mp,fp,vp,Sp,yp,Cp,_p,Ep,Tp,bp,Ip,wp,Rp,Ap,Pp,Mp,kp,Dp;function Op(e){try{const t=new URL(e),i=t.pathname.split("/"),n=decodeURIComponent(i[3]),r=i[4],a=JSON.parse(decodeURIComponent(t.search.replace("?context=","")));return{threadId:n,messageId:r,organizerId:a.Oid,tenantId:a.Tid}}catch(e){throw new b({defaultError:f.CALL_AGENT.INVALID_MEETING_LINK,originalError:e})}}!function(e){e.mdsc_webrtc_session="mdsc_webrtc_session",e.mdsc_webrtc_session_initial="mdsc_webrtc_session_initial"}(dp||(dp={})),function(e){e.Outgoing="Outgoing",e.Incoming="Incoming",e.TransferOutgoing="TransferOutgoing"}(up||(up={})),function(e){e.CreateCallAgent="CreateCallAgent",e.CreateTeamsCallAgent="CreateTeamsCallAgent",e.GetDeviceManager="GetDeviceManager",e.GetEnvironmentInfo="GetEnvironmentInfo",e.GetSDKVersion="GetSDKVersion",e.Feature="Feature"}(hp||(hp={})),function(e){e.StartCall="StartCall",e.Join="Join",e.HandlePushNotification="HandlePushNotification",e.Initialize="Initialize",e.Dispose="Dispose",e.CreateCall="CreateCall",e.Feature="Feature"}(pp||(pp={})),function(e){e.Call="Call",e.StartCall="StartCall",e.CallGroup="CallGroup",e.JoinGroup="JoinGroup",e.Accept="Accept",e.Reject="Reject",e.Mute="Mute",e.Unmute="Unmute",e.MuteAllRemoteParticipants="MuteAllRemoteParticipants",e.MuteIncomingAudio="MuteIncomingAudio",e.UnmuteIncomingAudio="UnmuteIncomingAudio",e.SendDtmf="SendDtmf",e.HangUp="HangUp",e.StartVideo="StartVideo",e.startAudio="startAudio",e.StopVideo="StopVideo",e.AddParticipant="AddParticipant",e.RemoveParticipant="RemoveParticipant",e.LobbyAdmitParticipant="LobbyAdmitParticipant",e.LobbyRejectParticipant="LobbyRejectParticipant",e.LobbyAdmitAll="LobbyAdmitAll",e.Hold="Hold",e.Resume="Resume",e.StartScreenShare="StartScreenShare",e.StopScreenShare="StopScreenShare",e.Transfer="Transfer",e.BindToCall="BindToCall",e.Feature="Feature",e.SetConstraints="SetConstraints"}(gp||(gp={})),function(e){e.Mute="Mute"}(mp||(mp={})),function(e){e.GetServerCallId="GetServerCallId"}(fp||(fp={})),function(e){e.CreateStackBase="CreateStackBase",e.GetDeviceManager="GetDeviceManager",e.InitializeStackForUser="InitializeStackForUser",e.InitializeEcsBase="InitializeEcsBase",e.InitializeEcsForUser="InitializeEcsForUser",e.Dispose="Dispose"}(vp||(vp={})),function(e){e.GetDeviceManager="GetDeviceManager",e.GetCameras="GetCameras",e.GetMicrophones="GetMicrophones",e.GetSpeakers="GetSpeakers",e.GetCamera="GetCamera",e.SelectCamera="SelectCamera",e.GetSelectedMicrophone="GetSelectedMicrophone",e.SelectMicrophone="SelectMicrophone",e.GetSelectedSpeaker="GetSelectedSpeaker",e.SelectSpeaker="SelectSpeaker",e.RenderPreviewVideo="RenderPreviewVideo",e.AskDevicePermission="AskDevicePermission"}(Sp||(Sp={})),function(e){e.Dispose="Dispose",e.UpdateScalingMode="UpdateScalingMode",e.Render="Render",e.RenderRemoteStream="RenderRemoteStream",e.RenderLocalStream="RenderLocalStream"}(yp||(yp={})),function(e){e.Dispose="Dispose",e.CreateView="CreateView"}(Cp||(Cp={})),function(e){e.SwitchSource="SwitchSource",e.Render="Render",e.GetMediaStream="GetMediaStream",e.SetMediaStream="SetMediaStream",e.SwitchVideo="SwitchVideo",e.Feature="Feature"}(_p||(_p={})),function(e){e.SwitchSource="SwitchSource",e.GetMediaStream="GetMediaStream",e.SetMediaStream="SetMediaStream",e.Feature="Feature"}(Ep||(Ep={})),function(e){e.SetScalingMode="SetScalingMode",e.Start="Start",e.Stop="Stop",e.SwitchDevice="SwitchDevice",e.Dispose="Dispose"}(Tp||(Tp={})),function(e){e.Render="Render",e.GetMediaStream="GetMediaStream"}(bp||(bp={})),function(e){e.Start="Start",e.Resume="Resume",e.Pause="Pause",e.SetScalingMode="SetScalingMode",e.Dispose="Dispose"}(Ip||(Ip={})),function(e){e.Start="Start",e.Resume="Resume",e.Pause="Pause",e.SetScalingMode="SetScalingMode",e.Dispose="Dispose",e.SetSourceObject="SetSourceObject"}(wp||(wp={})),function(e){e.SourceUnavailableError="SourceUnavailableError",e.permissionDeniedError="permissionDeniedError",e.PermissionDeniedError="PermissionDeniedError",e.DevicesNotFoundError="DevicesNotFoundError",e.MediaStreamRequestError="MediaStreamRequestError",e.PermissionsDeniedBySystem="PermissionsDeniedBySystem",e.UnknownFailureForVideoOperation="UnknownFailureForVideoOperation",e.noDeviceSelected="noDeviceSelected",e.NoDeviceSelected="NoDeviceSelected",e.MediaStreamRequestTimedout="MediaStreamRequestTimedout",e.UnsupportedStream="UnsupportedStream",e.ConstraintNotSatisfiedError="ConstraintNotSatisfiedError"}(Rp||(Rp={})),function(e){e.BrowserNotSupported="BrowserNotSupported",e.IncompatibleVersions="IncompatibleVersions"}(Ap||(Ap={})),function(e){e.P2P="P2P",e.Multiparty="Multiparty",e.Unknown="Unknown"}(Pp||(Pp={})),function(e){e.GroupJoin="groupJoin",e.RoomJoin="roomJoin",e.TeamsMeetingJoin="teamsMeetingJoin",e.TransferToParticipant="transferToParticipant",e.TransferToCall="transferToCall",e.NoContext=""}(Mp||(Mp={})),function(e){e.Enabled="Enabled",e.UserOverride="UserOverride",e.Disabled="Disabled"}(kp||(kp={})),function(e){e.Standard="standard",e.MusicOnHold="musicOnHold"}(Dp||(Dp={}));var Np,Lp,xp,Fp,Up,Bp,Vp=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Hp{get threadId(){return this._threadId}get participantId(){return this._tsCall.participantId}constructor(e){this._tsCall=e,this._threadId=this._tsCall.threadId}setThreadId(e){this._threadId=e}initialize(e,t,i){this._logger=t,this._eventEmitter=e,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall)))}async getServerCallId(){const e=JSON.parse(await this._tsCall.getJoinBlob()),t=e?.conversationUrl;if(!t)throw new b({defaultError:f.CALL.GET_SERVER_CALL_ID});return function(e){let t=btoa(e).replace(/=/g,"");t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_");for(const e of t)if(e.match(/[^A-Za-z0-9-_]/))throw new b({defaultError:f.CALL.SERVER_CALL_ID});return t}(t)}threadIdChanged(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit("threadIdChanged"))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners()}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([M(fp.GetServerCallId),Vp("design:type",Function),Vp("design:paramtypes",[]),Vp("design:returntype",Promise)],Hp.prototype,"getServerCallId",null);class $p extends Hp{get groupId(){return this._groupId}get roomId(){return this._roomId}get callScenario(){const e=this._tsCall.callType;return 1!==e&&2!==e?Pp.Unknown:1===e?Pp.P2P:Pp.Multiparty}get direction(){return this._config?.isIncoming?up.Incoming:up.Outgoing}get initiatorKind(){return ac(this._tsCall.callerMri?this._tsCall.callerMri:"").kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?"TeamsMeetingJoinLink":this._tsCall.transferorMri?"Transferee":1===this._tsCall.participants.length?ac(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>ac(e.id).kind)).toString()}get transferorKind(){return this._tsCall.transferorMri?ac(this._tsCall.transferorMri||"").kind:""}get context(){if(this._tsCall.groupId)return Mp.GroupJoin;if(this._config?.roomId||this._roomId)return Mp.RoomJoin;if(this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||this._tsCall.threadId)return Mp.TeamsMeetingJoin;if("unknown"!==this.transferorKind){if("transfer"===this._tsCall.incomingCallType)return Mp.TransferToParticipant;if("replaces"===this._tsCall.incomingCallType)return Mp.TransferToCall}return Mp.NoContext}constructor(e,t={}){super(e);const i=this._tsCall.groupId;this._groupId=!i||i.startsWith("19:")||i.startsWith("99:")?void 0:i,this._roomId=t.roomId,this._config=t.config}}!function(e){e.AudioRaw="AudioRaw",e.VideoRaw="VideoRaw",e.ScreenSharingRaw="ScreenSharingRaw",e.VideoRawOrScreenSharingRaw="VideoRawOrScreenSharingRaw",e.Audio="Audio",e.Video="Video"}(Np||(Np={})),function(e){e.Local="Local",e.Remote="Remote"}(Lp||(Lp={})),function(e){e.getMediaStream="getMediaStream",e.setMediaStream="setMediaStream",e.startEffects="startEffects",e.stopEffects="stopEffects",e.isSupported="isSupported",e.subscribe="subscribe",e.fpsWarningThresholdReached="fpsWarningThresholdReached",e.timeForEffectsWarningReached="timeForEffectsWarningReached",e.effectsError="effectsError",e.switchSource="switchSource",e.render="render"}(xp||(xp={})),function(e){e.stun="stun",e.turn="turn",e.turns="turns"}(Fp||(Fp={})),function(e){e.tcp="tcp",e.tls="tls",e.udp="udp"}(Up||(Up={})),function(e){e.Public_App="Public_App",e.Internal_LargeMeetingVideoRendering="Internal_LargeMeetingVideoRendering",e.Internal_RemoteVideoStreamDisposed="Internal_RemoteVideoStreamDisposed"}(Bp||(Bp={}));var Gp,jp="object"==typeof Reflect?Reflect:null,zp=jp&&"function"==typeof jp.apply?jp.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};Gp=jp&&"function"==typeof jp.ownKeys?jp.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var Wp=Number.isNaN||function(e){return e!=e};function qp(){qp.init.call(this)}var Kp=qp,Jp=function(e,t){return new Promise((function(i,n){function r(){void 0!==a&&e.removeListener("error",a),i([].slice.call(arguments))}var a;"error"!==t&&(a=function(i){e.removeListener(t,r),n(i)},e.once("error",a)),e.once(t,r)}))};qp.EventEmitter=qp,qp.prototype._events=void 0,qp.prototype._eventsCount=0,qp.prototype._maxListeners=void 0;var Yp,Qp,Zp=10;function Xp(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function eg(e){return void 0===e._maxListeners?qp.defaultMaxListeners:e._maxListeners}function tg(e,t,i,n){var r,a,s;if(Xp(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),s=a[t]),void 0===s)s=a[t]=i,++e._eventsCount;else if("function"==typeof s?s=a[t]=n?[i,s]:[s,i]:n?s.unshift(i):s.push(i),(r=eg(e))>0&&s.length>r&&!s.warned){s.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=s.length,function(e){console&&console.warn&&console.warn(e)}(o)}return e}function ig(){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 ng(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=ig.bind(n);return r.listener=i,n.wrapFn=r,r}function rg(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):sg(r,r.length)}function ag(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function sg(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}Object.defineProperty(qp,"defaultMaxListeners",{enumerable:!0,get:function(){return Zp},set:function(e){if("number"!=typeof e||e<0||Wp(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Zp=e}}),qp.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},qp.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||Wp(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},qp.prototype.getMaxListeners=function(){return eg(this)},qp.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var n="error"===e,r=this._events;if(void 0!==r)n=n&&void 0===r.error;else if(!n)return!1;if(n){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var o=r[e];if(void 0===o)return!1;if("function"==typeof o)zp(o,this,t);else{var l=o.length,c=sg(o,l);for(i=0;i<l;++i)zp(c[i],this,t)}return!0},qp.prototype.addListener=function(e,t){return tg(this,e,t,!1)},qp.prototype.on=qp.prototype.addListener,qp.prototype.prependListener=function(e,t){return tg(this,e,t,!0)},qp.prototype.once=function(e,t){return Xp(t),this.on(e,ng(this,e,t)),this},qp.prototype.prependOnceListener=function(e,t){return Xp(t),this.prependListener(e,ng(this,e,t)),this},qp.prototype.removeListener=function(e,t){var i,n,r,a,s;if(Xp(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){s=i[a].listener,r=a;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},qp.prototype.off=qp.prototype.removeListener,qp.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,a=Object.keys(i);for(n=0;n<a.length;++n)"removeListener"!==(r=a[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[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},qp.prototype.listeners=function(e){return rg(this,e,!0)},qp.prototype.rawListeners=function(e){return rg(this,e,!1)},qp.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):ag.call(e,t)},qp.prototype.listenerCount=ag,qp.prototype.eventNames=function(){return this._eventsCount>0?Gp(this._events):[]},Kp.once=Jp;class og{constructor(e){this.disposed=!1,this.callAgent=e.callAgent,this.callClient=e.callClient,this.eventEmitter=new Kp.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class lg{constructor(e){this.disposed=!1,this.callClient=e.callClient,this.eventEmitter=new Kp.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class cg{constructor(e){this.disposed=!1,this.call=e.call,this.callAgent=e.callAgent,this.callInfo=e.callInfo,this.eventEmitter=new Kp.EventEmitter}dispose(){this.disposed||(this.eventEmitter.removeAllListeners(),this.disposed=!0)}}class dg{constructor(e){this.disposed=!1,this.streamInstance=e.streamInstance,this.eventEmitter=new Kp.EventEmitter}}class ug{constructor(e){this.disposed=!1,this.streamInstance=e.streamInstance,this.eventEmitter=new Kp.EventEmitter}}!function(e){e[e.CallClientFeature=0]="CallClientFeature",e[e.CallAgentFeature=1]="CallAgentFeature",e[e.CallFeature=2]="CallFeature"}(Yp||(Yp={}));class hg extends cg{}class pg extends og{}class gg extends lg{}class mg extends dg{}class fg extends ug{}!function(e){e.Transfer="Transfer",e.StartCaptions="StartCaptions",e.StopCaptions="StopCaptions",e.SetSpokenLanguage="SetSpokenLanguage",e.SetCaptionLanguage="SetCaptionLanguage",e.getMediaStatsCollector="getMediaStatsCollector",e.disposeAllCollectors="disposeAllCollectors"}(Qp||(Qp={}));class vg{constructor(e,t,i){this._logger=e,this._featureCtorContext=t,this._featureInitContext=i,this._apiObjInstances=new Map}getApiObjectInstance(e){if(!this._apiObjInstances.has(e)){const t=new e(this._featureCtorContext);return(t instanceof hg||t instanceof pg||t instanceof gg||t instanceof mg||t instanceof fg)&&t.initialize(this._featureInitContext,this._logger),this._apiObjInstances.set(e,t),t}return this._apiObjInstances.get(e)}dispose(){for(const[,e]of this._apiObjInstances)e.dispose()}}const Sg={commandUrl:"",processingModes:{closedCaptions:{state:"Inactive"},realTimeTranscript:{state:"Inactive"}},spokenLanguage:""};var yg,Cg;!function(e){e.Acs="acs",e.Teams="teams",e.Unknown="unknown"}(yg||(yg={})),function(e){e.Captions="captions",e.TeamsCaptions="teams_captions"}(Cg||(Cg={}));class _g{constructor(e){this._eventEmitter=e,this._captionsModeKey="closedCaptions",this._transcriptModeKey="realTimeTranscript",this._transcriptionDataId=3,this._isCaptionsBot=e=>e.id===this._captionsBotMri,this._getBotMetadata=e=>e?.endpoints?.endpointDetails[0]?.endpointMetadata??void 0,this._getBotDataMediaStreamSourceId=e=>{if(e?.endpoints?.endpointDetails[0]?.mediaStreams){let t=e?.endpoints?.endpointDetails[0]?.mediaStreams;if(t.length>0)for(let e in t)if("data"===t[e].type)return t[e].sourceId}},this._isCaptionsEnabled=e=>"Active"===e?.processingModes?.[this._captionsModeKey]?.state,this._isTranscriptionEnabled=e=>"Active"===e?.processingModes?.[this._transcriptModeKey]?.state,this._copyBotMetaData=e=>{const t=this._getBotMetadata(e)||Sg;return JSON.parse(JSON.stringify(t))},this._isSpokenLanguageChanged=e=>e?.spokenLanguage===this._acsMetadata?.spokenLanguage}dispose(){this._acsMetadata=void 0}}function Eg(e,t={activationEvent:"OnFeatureAccess"}){return{get callApiCtor(){return e},activationOptions:t,isCallFeature:!0}}function Tg(e,t={activationEvent:"OnFeatureAccess"}){return{get callClientApiCtor(){return e},activationOptions:t,isCallClientFeature:!0}}function bg(e,t,i){try{const i={correlationId:e.correlationId||"",callId:e.callId,localParticipantId:e.localParticipantId,featureName:e.featureName,featureType:e.featureType,initializationType:e.initializationType,featureDetails:e.featureDetails,additionalDetails:e.additionalDetails||{}};t.sendEvent({name:Jh.acs_calling_feature_usage,tenant:hl,properties:i})}catch(t){i.debug(`Unable to send ${e.featureName} feature usage telemtery`)}}function Ig(e,t,i){try{const i={featureName:e.featureName,featureType:e.featureType,initializationType:e.initializationType,featureDetails:e.featureDetails};t.sendEvent({name:Jh.acs_calling_feature_usage,tenant:hl,properties:i})}catch(t){i.debug(`Unable to send ${e.featureName} feature usage telemetry`)}}const wg={0:"",1:"Success",2:"NoNgcEndpoint",3:"NetworkError",4:"MediaDroppedError",5:"BadRequest",6:"CallEstablishmentTimeout",7:"CallSetupError",8:"NoPermission",9:"Missed",10:"Declined",11:"Busy",12:"Cancelled",13:"Dropped",14:"PstnInsufficientFunds",15:"PstnSkypeoutAccountBlocked",16:"PstnCouldNotConnectToSkypeProxy",17:"PstnBlockedByUs",18:"PstnBlockedRegulatoryIndia",19:"PstnInvalidNumber",20:"PstnNumberForbidden",21:"PstnCallTerminated",22:"PstnNumberUnavailable",23:"PstnEmergencyCallDenied",24:"CallNotFound",25:"LocalError",26:"NotAcceptableHere",27:"CallForwarded",28:"CallForwardedToVoicemail",29:"SkypeTokenError",30:"CallAccepted",31:"LocalHttpStackError",32:"UnknownError",33:"PstnNoSubscriptionCover",34:"SessionNotFound",35:"SessionTimedOut",36:"PstnCreditExpired",37:"PstnCreditExpiredButEnough",38:"RetargetNotSupported",39:"EnterprisePstnInternalError",40:"EnterprisePstnUnavailable",41:"EnterprisePstnForbidden",42:"EnterprisePstnInvalidNumber",43:"EnterprisePstnMiscError",44:"Kicked",45:"NetworkRequestTimeoutError",46:"CallDoesNotExist",47:"MediaSetupFailure",48:"ServiceUnavailable",49:"SignalingError",50:"ConversationEstablishmentFailed",51:"TemporarilyUnavailable",52:"CannotConnectToNetworkError",53:"MediaRelayWhiteListingIssue",54:"NoSignalingFromPeer",55:"DeniedInLobby",56:"TimedOutInLobby",57:"CallFailedConflict",58:"DevicePermissionDenied",59:"ConfParticipantCountLimitReached",60:"ActionNotAllowed",61:"Abandoned",62:"ForbiddenDueToPolicy",63:"InsufficientCapabilitiesForCallee",64:"UserBlocked",65:"AccessDenied",66:"AnonymousJoinDisabledByPolicy",67:"NoLobbyForBroadcastJoin",68:"NotAllowedDueToInformationBarrier",69:"BroadcastLimitReached",70:"TeamParkPolicyDisabled",71:"B2bJoinDisabledByPolicy",72:"LocationBasedRoutingError",73:"ConfLobbyParticipantCountLimitReached",74:"DowngradeToStreamingClient",75:"CallRedirected",76:"CallIsEndToEndEncrypted",77:"Suspended"},Rg=e=>"number"==typeof e&&wg[e]||"UnknownError",Ag={0:"",1:"AddingFailed",2:"NoResponse",3:"Declined",4:"NotReachable",5:"Blocked",6:"NotFriendOrAuthorized",7:"CallLimitReached",8:"CallNotFound",9:"NetworkError",10:"MediaDroppedError",11:"OtherError",12:"PstnInsufficientFunds",13:"PstnSkypeoutAccountBlocked",14:"PstnCouldNotConnectToSkypeProxy",15:"PstnBlockedByUs",16:"PstnBlockedRegulatoryIndia",17:"PstnInvalidNumber",18:"PstnNumberForbidden",19:"Busy",20:"PstnCallTerminated",21:"PstnNumberUnavailable",22:"PstnEmergencyCallDenied",23:"Cancelled",24:"Dropped",25:"PstnNoSubscriptionCover",26:"PstnCreditExpired",27:"PstnCreditExpiredButEnough",28:"EnterprisePstnInternalError",29:"EnterprisePstnUnavailable",30:"EnterprisePstnForbidden",31:"EnterprisePstnInvalidNumber",32:"EnterprisePstnMiscError",33:"Kicked",34:"NetworkRequestTimeoutError",35:"CallDoesNotExist",36:"MediaSetupFailure",37:"ServiceUnavailable",38:"SignalingError",39:"ConversationEstablishmentFailed",40:"TemporarilyUnavailable",41:"CannotConnectToNetworkError",42:"NoSignalingFromPeer",43:"ParticipantDoesNotExist",44:"DeniedInLobby",45:"TimedOutInLobby",46:"ConfParticipantCountLimitReached",47:"Abandoned",48:"ActionNotAllowed",49:"ForbiddenDueToPolicy",50:"InsufficientCapabilitiesForCallee",51:"AccessDenied",52:"NoPermission",53:"AnonymousJoinDisabledByPolicy",54:"NoLobbyForBroadcastJoin",55:"NotAllowedDueToInformationBarrier",56:"BroadcastLimitReached",57:"B2bJoinDisabledByPolicy",58:"LocationBasedRoutingError",59:"ConfLobbyParticipantCountLimitReached",60:"LobbyUserLeft"},Pg=e=>"number"==typeof e&&Ag[e]||"UnknownError",Mg={0:"None",1:"Incoming Call",2:"Connecting",3:"Connected",4:"LocalHold",5:"RemoteHold",10:"InLobby",9:"EarlyMedia",6:"Disconnecting",7:"Disconnected",8:"Unknown",11:"Unknown",12:"Unknown",13:"Unknown",14:"Unknown",15:"Unknown"},kg={0:"None",1:"RealTime",2:"Streaming"};function Dg(e,t){let i=0,n=0,r=Dl,a=[];return e.tsCall&&(i=e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.callControllerCode||0,n=e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.callControllerSubCode||0,a=e.tsCall.callEndDiagnosticsInfo&&e.tsCall.callEndDiagnosticsInfo.resultCategories||["Success"]),r=Rg(t||e.tsCall?.terminatedReason||0),e.logger.error(`Call end reason=${r}, code=${i}, subCode=${n}, resultCategories=${a.toString()}`),{callEndReason:{message:r,code:i,subCode:n,resultCategories:a},callingCommunicationError:new b({defaultError:{message:r,code:i,subCode:n,resultCategories:a}})}}function Og(e,t,i){let n=0,r=0,a=Dl,s=[];if(t?.callEndDiagnosticsInfo)a=Pg(i||t.stateReason||0),n=t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.callControllerCode||0,r=t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.callControllerSubCode||0,s=t.callEndDiagnosticsInfo&&t.callEndDiagnosticsInfo.resultCategories||[];else{let t=Dg(e,i);n=t.callEndReason.code,r=t.callEndReason.subCode||0,s=t.callEndReason.resultCategories,a=t.callEndReason.message}return e.logger[0===n?"info":"error"](`Participant call end reason=${a}, code=${n}, subCode=${r}, resultCategories=${s.toString()}`),{callEndReason:{message:a,code:n,subCode:r,resultCategories:s},callingCommunicationError:new b({defaultError:{message:a,code:n,subCode:r,resultCategories:s}})}}function Ng(e,t){let i;switch(t?.type?t.type:Rp.UnknownFailureForVideoOperation){case Rp.DevicesNotFoundError:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.DEVICES_NOT_FOUND});break;case Rp.MediaStreamRequestError:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_ERROR});break;case Rp.MediaStreamRequestTimedout:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.MEDIA_STREAM_REQUEST_TIMEDOUT});break;case Rp.PermissionsDeniedBySystem:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.PERMISSION_DENIED_BY_SYSTEM});break;case Rp.UnsupportedStream:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.UNSUPPORTED_STREAM});break;case Rp.ConstraintNotSatisfiedError:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.CONSTRAINT_NOT_SATISFIED});break;case Rp.noDeviceSelected:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.NO_DEVICE_SELECTED});break;case Rp.SourceUnavailableError:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.SOURCE_UNAVAILABLE});break;case Rp.PermissionDeniedError:case Rp.permissionDeniedError:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.PERMISSION_DENIED});break;default:i=new b({defaultError:f.LOCAL_VIDEO_STREAM.UNKNOWN})}return i}function Lg(e,t){return new b({defaultError:{message:t.message,code:e?.response?.status||t.code,subCode:t.subCode,resultCategories:t.resultCategories},originalError:e})}function xg(e){return{communicationServicesError:{message:e.message||"Unknown error",code:void 0===e.code?_:e.code,subCode:e.subCode||0,resultCategories:void 0===e.resultCategories||0===e.resultCategories.length?["UnexpectedClientError"]:e.resultCategories}}}function Fg(e){return{callEndReason:{message:e.message,code:void 0===e.code?_:e.code,subCode:e.subCode||0,resultCategories:void 0===e.resultCategories||0===e.resultCategories.length?["UnexpectedClientError"]:e.resultCategories}}}var Ug=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Bg=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const Vg=Date.UTC(1900,0,1);class Hg{constructor(e,t){this._eventEmitter=t,this._impl=e}async startCaptions(e){await this._impl.startCaptions(e)}async stopCaptions(){await this._impl.stopCaptions()}async setSpokenLanguage(e){await this._impl.setSpokenLanguage(e)}get supportedSpokenLanguages(){return this._impl.supportedSpokenLanguages}get isCaptionsFeatureActive(){return this._impl.isCaptionsFeatureActive}get activeSpokenLanguage(){return this._impl.activeSpokenLanguage}get kind(){return this._impl.kind}}class $g extends Hg{constructor(e,t){super(e,t)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}}class Gg extends Hg{constructor(e,t){super(e,t)}get supportedCaptionLanguages(){return this._impl.supportedCaptionLanguages}get activeCaptionLanguage(){return this._impl.activeCaptionLanguage}async setCaptionLanguage(e){await this._impl.setCaptionLanguage(e)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}}class jg extends _g{constructor(e,t,i,n){super(e),this._botParticipantId="",this._isCteUser=!1,this._isCaptionsActive=!1,this._firstTimeActive=!1,this._ecsCaptionsEnabled=!1,this._ecsSpokenLanguagesEnabled=!1,this._ecsSpokenLanguages=[],this._ecsCaptionLanguagesEnabled=!1,this._ecsCaptionLanguages=[],this._ecsAmtPolicyUrlSuffix="",this._hasReportedCaptionParseFailure=!1,this._hasReceivedFirstCaption=!1,this._currentLanguage="",this._currentCaptionLanguage="",this._participantSequenceIdMap={},this._addParticipantPromise=null,this._dataChannelHandler={onStarted:async(e,t)=>{},onStopped:async e=>{},onDataReceived:async(e,t,i)=>{let n;try{n=JSON.parse(t.toString())}catch(e){try{if(void 0===this._textDecoder)throw new Error("TextDecoder undefined.");n=JSON.parse(this._textDecoder.decode(t))}catch(e){return this._logger.error("Failed to parse Captions result",e),void(this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(ep.FirstCaptionParsingError,Yh.failure,"",0,Xh.Unexpected,"Could not decode data packet.")))}}if(n){let e=[];n.textTracks?e=n.textTracks:n.recognitionResults&&(e=n.recognitionResults),e.forEach((e=>{try{const[t,n]=e.id.split("/");let r=parseInt(n,10);if(this._participantSequenceIdMap[e.userId]&&this._botParticipantId==t&&this._participantSequenceIdMap[e.userId]>r)return;this._botParticipantId=t,this._participantSequenceIdMap[e.userId]=r;const a=this._tsCall.participants.find((t=>t.id===e.userId))?.displayName||(this._internalCallAgent.getUserMri()===e.userId?this._internalCallAgent?.displayName:void 0),s={resultType:e.isFinal?"Final":"Partial",captionText:e.text,spokenText:e.originalText??e.text,timestamp:new Date(new Date(e.timestampAudioSent/1e4).getTime()+Vg),speaker:{identifier:ac(e.userId),displayName:a},spokenLanguage:e.spokenLanguage,captionLanguage:e.trackLanguage};if(this._currentLanguage!=e.spokenLanguage&&(this._currentLanguage=e.spokenLanguage,this._eventEmitter.emit("SpokenLanguageChanged")),!this.isCaptionsFeatureActive||this._mediaStreamSourceId!==i)return;this._hasReceivedFirstCaption||(this._hasReceivedFirstCaption=!0,this._sendCaptionsEvent(ep.FirstCaptionReceived,Yh.success,"",0)),this._eventEmitter.emit("CaptionsReceived",s)}catch(e){this._logger.error("Failed to parse Captions result",e),this._hasReportedCaptionParseFailure||(this._hasReportedCaptionParseFailure=!0,this._sendCaptionsEvent(ep.FirstCaptionParsingError,Yh.failure,"",0,Xh.Unexpected,"Error thrown during incoming caption result mapping."))}}))}}},this._handleBotRemoved=e=>{this._acsMetadata&&this._isCaptionsBot(e)&&(this.isCaptionsFeatureActive&&(this._isCaptionsActive=!1,this._eventEmitter.emit("CaptionsActiveChanged")),this._acsMetadata=void 0,this._firstTimeActive=!1)},this._telemetryStartTime=Date.now()}get isCaptionsFeatureActive(){return!!this._acsMetadata&&this._isCaptionsEnabled(this._acsMetadata)&&this._isCaptionsActive}get supportedSpokenLanguages(){return this._ecsSpokenLanguages}get supportedCaptionLanguages(){return this._ecsCaptionLanguages}get captions(){return this._captions}get kind(){return this._name===Cg.TeamsCaptions?"TeamsCaptions":"Captions"}get activeSpokenLanguage(){return this._currentLanguage}get activeCaptionLanguage(){return this._currentCaptionLanguage}get isTeamsConversationType(){return _l.indexOf(this._tsCall.conversationType)>-1}get isTeamsUserInCall(){for(let e of this._tsCall.participants)if("microsoftTeamsUser"===ac(e.id).kind)return!0;return!1}get isTeamsCallKind(){return this._call.kind===e.CallKind.TeamsCall}get isTeamsCaptionsBotInCall(){for(let e of this._tsCall.participants)if(e.id===yc().captions.teams.botMri)return!0;return!1}updateParticipantTranscriptionPrefsMetadata(e){let t;for(let e in this._tsCall.endpoints?.endpointDetails)if(this._tsCall.endpoints?.endpointDetails[e].participantId===this._tsCall.participantId){t=this._tsCall.endpoints?.endpointDetails[e];break}const i=t?.endpointMetadata??{transcriptionPrefs:{}};e?i.transcriptionPrefs?.closedCaptions?i.transcriptionPrefs.closedCaptions=e:i.transcriptionPrefs={closedCaptions:e}:i.transcriptionPrefs?.closedCaptions&&delete i.transcriptionPrefs.closedCaptions,this._tsCall.updateEndpointMetadata(JSON.stringify(i))}initialize(e,t,i,n,r,a,s,o){this._logger=a.createChild((()=>`CaptionsFeature::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._call=t,this._internalCallAgent=i,this._httpRequestHelper=n,this._telemetryLogManager=r,this._telemetryStartTime=s,this._isCteUser=i.isCteUser(),this._ecsCaptionsEnabled=yc().captions.enabled,this._name=this.isTeamsConversationType||this._isCteUser||this.isTeamsUserInCall||this.isTeamsCaptionsBotInCall||this.isTeamsCallKind?Cg.TeamsCaptions:Cg.Captions,this.updateCaptionsData(this._name),this._sendCaptionsEvent(ep.InitializeCaptions,Yh.initialize,o,this._telemetryStartTime),this._initializationPromise=new Promise(((e,t)=>{this._initializeAsync(o).then((t=>e())).catch((e=>t(e)))}))}async _initializeAsync(e){try{this._textDecoder=new TextDecoder,this._tsCall.on("participantAdded",(async t=>{if(this._captions&&"Captions"===this._captions.kind&&"microsoftTeamsUser"===ac(t.id).kind){if(this._captionsBotMri)try{await this._tsCall.removeParticipant(this._captionsBotMri)}catch(i){const n=new b({defaultError:{message:Pg(i),code:t.callEndDiagnosticsInfo?.callControllerCode||0,subCode:t.callEndDiagnosticsInfo?.callControllerSubCode||0,resultCategories:t.callEndDiagnosticsInfo?.resultCategories||["UnexpectedClientError"]},originalError:i});this._sendCaptionsEvent(ep.CaptionsKindChanged,Yh.failure,e,this._telemetryStartTime,Xh.Unexpected,n.message,n.code,n.subCode,xg(n))}this.updateCaptionsData(Cg.TeamsCaptions),this._isCaptionsActive&&(this._currentLanguage&&this._ecsSpokenLanguages.includes(this._currentLanguage)?await this._captions.startCaptions({spokenLanguage:this._currentLanguage}):await this._captions.startCaptions()),this._eventEmitter.emit("CaptionsKindChanged"),this._sendCaptionsEvent(ep.CaptionsKindChanged,Yh.success,e,this._telemetryStartTime)}})),this._tsCall.on("participantAdded",(async e=>{this._isCaptionsBot(e)&&(this._acsMetadata||(this._acsMetadata=this._copyBotMetaData(e),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(e),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._transcriptionDataId,this._dataChannelHandler)))})),this._tsCall.on("participantRemoved",(async e=>{this._isCaptionsBot(e)&&this._handleBotRemoved(e)})),this._tsCall.on("participantUpdated",(async e=>{this._getBotMetadata(e)&&this._isCaptionsBot(e)&&this._acsMetadata&&(this._acsMetadata=this._copyBotMetaData(e),this._mediaStreamSourceId=this._getBotDataMediaStreamSourceId(e),!this._firstTimeActive&&this.isCaptionsFeatureActive&&(this._firstTimeActive=!0,this._eventEmitter.emit("CaptionsActiveChanged")))}));const t=this._tsCall.participants.find((e=>e.id===this._captionsBotMri));t&&(this._acsMetadata=this._copyBotMetaData(t),this._mediaStreamSourceId=t.getSourceIdForMediaType(3),await this._tsCall.startDataChannel(),await this._tsCall.dataChannelAdapter.addHandler(this._transcriptionDataId,this._dataChannelHandler))}catch(t){const i=new b({defaultError:f.FEATURES.CAPTIONS.INITIALIZE});throw this._sendCaptionsEvent(ep.InitializeCaptions,Yh.failure,e,this._telemetryStartTime,Xh.Unexpected,i.message,i.code,i.subCode,xg(i)),this._logger.error(i.message),i}}updateCaptionsData(e){e===Cg.Captions?(this._name=Cg.Captions,this._captionsBotMri=yc().captions.acs.botMri,this._clientInfo=yc().captions.acs.clientInfo.ring,this._ecsSpokenLanguagesEnabled=yc().captions.teams.spokenLanguages.enabled,this._ecsSpokenLanguages=yc().captions.teams.spokenLanguages.languages,this._captions=new $g(this,this._eventEmitter)):e===Cg.TeamsCaptions&&(this._name=Cg.TeamsCaptions,this._captionsBotMri=yc().captions.teams.botMri,this._clientInfo=yc().captions.teams.clientInfo.ring,this._ecsSpokenLanguagesEnabled=yc().captions.teams.spokenLanguages.enabled,this._ecsSpokenLanguages=yc().captions.teams.spokenLanguages.languages,this._ecsCaptionLanguagesEnabled=yc().captions.teams.captionLanguages.enabled,this._ecsCaptionLanguages=yc().captions.teams.captionLanguages.languages,this._ecsAmtPolicyUrlSuffix=yc().MiddleTier.policyUrlSuffixV2,this._captions=new Gg(this,this._eventEmitter))}async startCaptions(e){this._telemetryStartTime=+Date.now();const t=x(),i=e?.spokenLanguage||"en-us";if(this._sendFeatureUsage("startCaptions",Yh.attempt),this._sendCaptionsEvent(ep.StartCaptions,Yh.attempt,t,0),this._addParticipantPromise){const e=new b({defaultError:f.FEATURES.CAPTIONS.ALREADY_STARTING});return this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),void this._sendFeatureUsage("startCaptions",Yh.failure)}if(await this._initializationPromise,!this._ecsCaptionsEnabled){const e=new b({defaultError:f.FEATURES.CAPTIONS.DISABLED});return this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("startCaptions",Yh.failure),void this._logger.error("Feature is not enabled.")}if(!this._ecsSpokenLanguages.includes(i)){const e=new b({defaultError:f.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),this._logger.error("Spoken language requested is not supported."),e}if(this._name===Cg.TeamsCaptions&&(this._mtPolicy=this._internalCallAgent.mtPolicyService,this._isCteUser)){try{this._mtPolicy.initialize({localParticipant:this._internalCallAgent.getUserMri(),skypeToken:await this._internalCallAgent.tokenProvider(),telemetryLogManager:this._telemetryLogManager}),await this._mtPolicy.fetchUserPoliciesFromAcsMiddleTier(this._tsCall.callId,this._tsCall.participantId,{policyUrlSuffix:this._ecsAmtPolicyUrlSuffix,userPolicies:["TeamsCallingPolicy","TeamsMeetingPolicy"],userProperties:["FeatureTypes","PoliciesMetadata"]}),this._mtCaptionsPolicyResult=JSON.parse(this._mtPolicy.getTeamsUserCaptionsPoliciesData())}catch(e){const i=new b({defaultError:f.FEATURES.CAPTIONS.CTE_POLICY_FETCH_FAIL,originalError:e});this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,i.message,i.code,i.subCode,xg(i)),this._logger.error("Unable to fetch policies")}if(this._mtCaptionsPolicyResult)if(this.isTeamsConversationType){if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForMeeting){const e=new b({defaultError:f.FEATURES.CAPTIONS.MEETING_POLICY_DISABLED});throw this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("startCaptions",Yh.failure),this._logger.error(e.message),e}}else if(!this._mtCaptionsPolicyResult?.isLiveCaptionsEnabledForCalling){const e=new b({defaultError:f.FEATURES.CAPTIONS.CALLING_POLICY_DISABLED});throw this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("startCaptions",Yh.failure),this._logger.error(e.message),e}}if(this._acsMetadata){if(this._isCaptionsEnabled(this._acsMetadata))if(this._isCaptionsActive){const e=new b({defaultError:f.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("startCaptions",Yh.failure)}else this._isCaptionsActive=!0,"Captions"===this._captions.kind&&this.updateParticipantTranscriptionPrefsMetadata(!0),this._sendCaptionsEvent(ep.StartCaptions,Yh.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",Yh.success),this._eventEmitter.emit("CaptionsActiveChanged");else if("Captions"===this._captions.kind)if(this._isCaptionsActive){const e=new b({defaultError:f.FEATURES.CAPTIONS.ALREADY_ACTIVE});this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("startCaptions",Yh.failure)}else this._isCaptionsActive=!0,this.updateParticipantTranscriptionPrefsMetadata(!0),this._sendCaptionsEvent(ep.StartCaptions,Yh.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",Yh.success),this._eventEmitter.emit("CaptionsActiveChanged")}else try{const e={participantInvitationData:{botData:{clientInfo:this._clientInfo,consumerType:"ACS",initiatorUserToken:this._name===Cg.TeamsCaptions?"":await this._internalCallAgent.tokenProvider(),spokenLanguage:i,mode:Cl,transcriptionModes:[this._captionsModeKey]}}};this._addParticipantPromise=this._tsCall.addParticipant(this._captionsBotMri,e),await this._addParticipantPromise,this._addParticipantPromise=null,this._currentLanguage!==i&&(this._currentLanguage=i,this._eventEmitter.emit("SpokenLanguageChanged")),this._isCaptionsActive=!0,"Captions"===this._captions.kind&&this.updateParticipantTranscriptionPrefsMetadata(!0),this._sendCaptionsEvent(ep.StartCaptions,Yh.success,t,this._telemetryStartTime),this._sendFeatureUsage("startCaptions",Yh.success)}catch(e){this._addParticipantPromise=null;const i=new b({defaultError:f.FEATURES.CAPTIONS.START_FAILED});throw this._sendCaptionsEvent(ep.StartCaptions,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,i.message,i.code,i.subCode,xg(i)),this._sendFeatureUsage("startCaptions",Yh.failure),this._logger.error(i.message),i}}async stopCaptions(){this._telemetryStartTime=+Date.now();const e=x();if(this._sendFeatureUsage("stopCaptions",Yh.attempt),this._sendCaptionsEvent(ep.StopCaptions,Yh.attempt,e,0),this.isCaptionsFeatureActive)this._isCaptionsActive=!1,this._sendCaptionsEvent(ep.StopCaptions,Yh.success,e,this._telemetryStartTime),this._sendFeatureUsage("stopCaptions",Yh.success),this._eventEmitter.emit("CaptionsActiveChanged"),"Captions"===this._captions.kind&&this.updateParticipantTranscriptionPrefsMetadata();else{const t=new b({defaultError:f.FEATURES.CAPTIONS.STOP_NOT_ACTIVE});this._sendCaptionsEvent(ep.StopCaptions,Yh.failure,e,this._telemetryStartTime,Xh.Expected,t.message,t.code,t.subCode,xg(t)),this._logger.warn(t.message)}this._isCaptionsActive=!1}async setSpokenLanguage(e){this._telemetryStartTime=+Date.now();const t=x();if(this._sendFeatureUsage("setSpokenLanguage",Yh.attempt),this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.attempt,t,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),this._logger.error(e.message),e}if(!this._isCaptionsActive){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_LANGUAGE_NOT_STARTED});return this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),void this._logger.warn(e.message)}if(!this._ecsSpokenLanguagesEnabled){const e=new b({defaultError:f.FEATURES.CAPTIONS.SPOKEN_LANG_DISABLED});return this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),void this._logger.error(e.message)}if(e==this._currentLanguage){const e=new b({defaultError:f.FEATURES.CAPTIONS.SPOKEN_LANGUAGE_ALREADY_SET});return this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),void this._sendFeatureUsage("setSpokenLanguage",Yh.failure)}if(!this._ecsSpokenLanguages.includes(e)){const e=new b({defaultError:f.FEATURES.CAPTIONS.SPOKEN_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),this._logger.error(e.message),e}try{const i=await this._internalCallAgent.tokenProvider();if(!i){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_LANGUAGE_GET_TOKEN});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,e.message,e.code,e.subCode,xg(e)),e}await this._sendSetLanguageRequest(e,"",i,this._acsMetadata.commandUrl),this._currentLanguage!==e&&(this._currentLanguage=e,this._eventEmitter.emit("SpokenLanguageChanged")),this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.success,t,this._telemetryStartTime),this._sendFeatureUsage("setSpokenLanguage",Yh.success)}catch(e){const i=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_LANGUAGE_FAILED,originalError:e});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,i.message,i.code,i.subCode,xg(i)),this._sendFeatureUsage("setSpokenLanguage",Yh.failure),this._logger.error(i.message),i}}async setCaptionLanguage(e){this._telemetryStartTime=+Date.now();const t=x();if(this._sendFeatureUsage("setCaptionLanguage",Yh.attempt),this._sendCaptionsEvent(ep.SetCaptionLanguage,Yh.attempt,t,0),await this._initializationPromise,!this._acsMetadata?.commandUrl){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_STARTED});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),this._logger.error(e.message),e}if(!this._isCaptionsActive){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_CAPTIONS_NOT_ACTIVE});return this._sendCaptionsEvent(ep.SetCaptionLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),void this._logger.warn(e.message)}if(!this._ecsCaptionLanguagesEnabled){const e=new b({defaultError:f.FEATURES.CAPTIONS.CAPTIONS_LANG_DISABLED});return this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),void this._logger.error(e.message)}if(this._isTranslatedCaptionsAllowed||this._tsCall.meetingDetails?.meetingCapability&&this._tsCall.meetingDetails.meetingCapability.allowTranslatedCaptions&&(this._isTranslatedCaptionsAllowed=this._tsCall.meetingDetails.meetingCapability.allowTranslatedCaptions),!(this.isTeamsConversationType&&this._isTranslatedCaptionsAllowed||this._mtCaptionsPolicyResult?.isTeamsProMgmtSkuAvailable)){const e=new b({defaultError:f.FEATURES.CAPTIONS.CAPTIONS_LANG_TEAMS_LICENSE});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),this._logger.error(e.message),e}if(e==this._currentCaptionLanguage){const e=new b({defaultError:f.FEATURES.CAPTIONS.CAPTIONS_LANG_ALREADY_SET});return this._sendCaptionsEvent(ep.SetCaptionLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),void this._sendFeatureUsage("setCaptionLanguage",Yh.failure)}if(!this._ecsCaptionLanguages.includes(e)){const e=new b({defaultError:f.FEATURES.CAPTIONS.CAPTIONS_LANG_UNSUPPORTED});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Expected,e.message,e.code,e.subCode,xg(e)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),this._logger.error(e.message),e}try{const i=await this._internalCallAgent.tokenProvider();if(!i){const e=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_CAPTIONS_GET_TOKEN});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,e.message,e.code,e.subCode,xg(e)),e}await this._sendSetLanguageRequest("",e,i,this._acsMetadata.commandUrl),this._currentCaptionLanguage!==e&&(this._currentCaptionLanguage=e,this._eventEmitter.emit("CaptionLanguageChanged")),this._sendCaptionsEvent(ep.SetCaptionLanguage,Yh.success,t,this._telemetryStartTime),this._sendFeatureUsage("setCaptionLanguage",Yh.success)}catch(e){const i=new b({defaultError:f.FEATURES.CAPTIONS.UPDATE_CAPTIONS_FAILED,originalError:e});throw this._sendCaptionsEvent(ep.SetSpokenLanguage,Yh.failure,t,this._telemetryStartTime,Xh.Unexpected,i.message,i.code,i.subCode,xg(i)),this._sendFeatureUsage("setCaptionLanguage",Yh.failure),this._logger.error(i.message),i}}dispose(){this._acsMetadata=void 0,this._textDecoder=void 0}_sendCaptionsEvent(e,t,i,n,r,a,s,o,l){let c={eventName:Jh.acs_calling_captions,callId:this._call.id,correlationId:i,isExpected:r??"",localParticipantId:this._call.tsCall.participantId,featureType:this._name,featureDetails:{step:e},kindOfEvent:t,timestampInfo:n?{deltaTimeInMs:+Date.now()-n}:"",additionalDetails:{failureReason:a,code:s,subCode:o,...l}};try{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_captions,tenant:hl,properties:c})}catch(e){this._logger.debug(`Unable to send ${this._name} feature usage telemtery`)}}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this._name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}async _sendSetLanguageRequest(e,t,i,n){const r=e?{type:yl,spokenLanguage:e}:{type:yl,subtitleLanguages:[t]},a={timestamp:(new Date).toISOString(),participantMri:this._internalCallAgent.getUserMri(),participantLegId:this._tsCall.participantId,action:yl,mode:Cl,actionParameters:r},s={headers:{"X-Microsoft-Skype-Chain-ID":this._tsCall.callId,Authorization:`Bearer ${i}`,"x-skypetoken":i},withCredentials:!0};return this._httpRequestHelper.sendRequestWithRetry("post",n,a,s,3)}}Ug([M(Qp.StartCaptions),Bg("design:type",Function),Bg("design:paramtypes",[Object]),Bg("design:returntype",Promise)],jg.prototype,"startCaptions",null),Ug([M(Qp.StopCaptions),Bg("design:type",Function),Bg("design:paramtypes",[]),Bg("design:returntype",Promise)],jg.prototype,"stopCaptions",null),Ug([M(Qp.SetSpokenLanguage),Bg("design:type",Function),Bg("design:paramtypes",[String]),Bg("design:returntype",Promise)],jg.prototype,"setSpokenLanguage",null),Ug([M(Qp.SetCaptionLanguage),Bg("design:type",Function),Bg("design:paramtypes",[String]),Bg("design:returntype",Promise)],jg.prototype,"setCaptionLanguage",null);class zg{constructor(e){this.typeRankComparator=(e,t)=>void 0===e.publishedState?-1:void 0===t.publishedState?1:e.publishedState.typeRank-t.publishedState.typeRank,this._eventEmitter=e,this._currentRaiseHandStates=new Map}initialize(e,t,i,n){this._logger=n.createChild((()=>`RaiseHandFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._telemetryLogManager=i,this._internalCallAgent=t,this._sendFeatureUsage("initialize",Yh.initialize);try{let e=e=>new Map(this.getPublishedState(e).sort(this.typeRankComparator).map((e=>[e.id,e])));this._tsCall.on("publishedStatesChanged",(async t=>{let i=e(t),n=this._currentRaiseHandStates;this._currentRaiseHandStates=i,this._currentRaiseHandStates.forEach(((e,t)=>{n.has(t)||this._eventEmitter.emit("raisedHandEvent",{identifier:ac(t)})})),n.forEach(((e,t)=>{this._currentRaiseHandStates.has(t)||this._eventEmitter.emit("loweredHandEvent",{identifier:ac(t)})}))})),this._tsCall.publishedStates&&(this._currentRaiseHandStates=e(this._tsCall.publishedStates)),this._sendFeatureUsage("initialize",Yh.success)}catch(e){throw this._logger.error("Could not initialize raise hand feature.",e),this._sendFeatureUsage("initialize",Yh.failure),new b({defaultError:f.FEATURES.RAISE_HAND.INITIALIZE,originalError:e})}}async raiseHand(){this._sendFeatureUsage("raiseHand",Yh.attempt);try{if(void 0!==this.getLocalRaiseHandState())return void this._sendFeatureUsage("raiseHand",Yh.failure);const e={level:"user",type:"raiseHands",content:"{}"};if(!await this._tsCall.publishState(e,m.generateCauseId()))throw new b({defaultError:f.FEATURES.RAISE_HAND.RAISE_HAND_PUBLISH_STATE});this._sendFeatureUsage("raiseHand",Yh.success)}catch(e){throw this._logger.error("Could not change a participant state. Code: ",e?.response?.status),this._sendFeatureUsage("raiseHand",Yh.failure),Lg(e,f.FEATURES.RAISE_HAND.RAISE_HAND_FAIL)}}async lowerHand(){this._sendFeatureUsage("lowerHand",Yh.attempt);try{const e=this.getLocalRaiseHandState();if(void 0===e)return void this._sendFeatureUsage("lowerHand",Yh.failure);const t={stateIds:[e]};await this._tsCall.removeState(t,m.generateCauseId()),this._sendFeatureUsage("lowerHand",Yh.success)}catch(e){throw this._logger.error("Could not change a participant state. Code: ",e?.response?.status),this._sendFeatureUsage("lowerHand",Yh.failure),Lg(e,f.FEATURES.RAISE_HAND.LOWER_HAND_FAIL)}}async lowerHands(e){this._sendFeatureUsage("lowerHands",Yh.attempt);try{if(0===e.length)return void this._sendFeatureUsage("lowerHands",Yh.failure);if(0===this._currentRaiseHandStates.size)return void this._sendFeatureUsage("lowerHands",Yh.failure);const t=e.map((e=>rc(e))),i=this.findStateIdsForParticipantIds(t);await this._tsCall.removeState({stateIds:i},m.generateCauseId()),this._sendFeatureUsage("lowerHands",Yh.success)}catch(e){throw this._logger.error("Could not change a participant state.",e),this._sendFeatureUsage("lowerHands",Yh.failure),Lg(e,f.FEATURES.RAISE_HAND.LOWER_REMOTEPARTICIPANTS_HANDS_FAIL)}}async lowerAllHands(){this._sendFeatureUsage("lowerAllHands",Yh.attempt);try{await this._tsCall.removeStatesForEveryone({type:"raiseHands"},m.generateCauseId()),this._sendFeatureUsage("lowerAllHands",Yh.success)}catch(e){throw this._logger.error("Could not change a participant state.",e),this._sendFeatureUsage("lowerAllHands",Yh.failure),Lg(e,f.FEATURES.RAISE_HAND.LOWER_ALL_HANDS_FAIL)}}get raisedHands(){return 0===this._currentRaiseHandStates.size?[]:Array.from(this._currentRaiseHandStates.keys()).map(((e,t)=>({identifier:ac(e),order:t+1})))}getLocalRaiseHandState(){const e=this.findStateIdsForParticipantIds([this._internalCallAgent.getUserMri()]);if(e&&e.length>0)return e[0]}findStateIdsForParticipantIds(e){return e&&0!==this._currentRaiseHandStates.size?Array.from(this._currentRaiseHandStates.entries()).filter((t=>e.includes(t[0]))).map((e=>e[1]?.publishedState?.stateId)).filter((e=>!!e)):[]}getPublishedState(e){return e.typeStates.filter((e=>"raiseHands"===e.type)).map((e=>e.participantStates)).flat()}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}var Wg;!function(e){e.turnVideoOn="turnVideoOn",e.unmuteMic="unmuteMic",e.shareScreen="shareScreen",e.removeParticipant="removeParticipant",e.hangUpForEveryOne="hangUpForEveryOne",e.addCommunicationUser="addCommunicationUser",e.addTeamsUser="addTeamsUser",e.addPhoneNumber="addPhoneNumber",e.manageLobby="manageLobby",e.spotlightParticipant="spotlightParticipant",e.removeParticipantsSpotlight="removeParticipantsSpotlight",e.blurBackground="blurBackground",e.startLiveCaptions="startLiveCaptions",e.stopLiveCaptions="stopLiveCaptions",e.raiseHand="raiseHand",e.pstnDialOut="pstnDialOut",e.muteOthers="muteOthers",e.useReactions="useReactions",e.viewAttendeeNames="viewAttendeeNames"}(Wg||(Wg={}));class qg{constructor(e){this._logger=e,this._ecsConfig=yc()}getResolvedCapabilitiesBasedOnRole(e,t){let i={...t},n=e.toLocaleLowerCase();return n!==Wl.Attendee.toLocaleLowerCase()&&n!==Wl.Presenter.toLocaleLowerCase()&&n!==Wl.Consumer.toLocaleLowerCase()&&n!==Wl.Organizer.toLocaleLowerCase()||(this._ecsConfig[Yl][n][Wg.turnVideoOn]?i.turnVideoOn={isPresent:this._ecsConfig[Yl][n][Wg.turnVideoOn],reason:Jl.Capable}:i.turnVideoOn={isPresent:this._ecsConfig[Yl][n][Wg.turnVideoOn],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.unmuteMic]?i.unmuteMic={isPresent:this._ecsConfig[Yl][n][Wg.unmuteMic],reason:Jl.Capable}:i.unmuteMic={isPresent:this._ecsConfig[Yl][n][Wg.unmuteMic],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.shareScreen]?i.shareScreen={isPresent:this._ecsConfig[Yl][n][Wg.shareScreen],reason:Jl.Capable}:i.shareScreen={isPresent:this._ecsConfig[Yl][n][Wg.shareScreen],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.removeParticipant]?i.removeParticipant={isPresent:this._ecsConfig[Yl][n][Wg.removeParticipant],reason:Jl.Capable}:i.removeParticipant={isPresent:this._ecsConfig[Yl][n][Wg.removeParticipant],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.muteOthers]?i.muteOthers={isPresent:this._ecsConfig[Yl][n][Wg.muteOthers],reason:Jl.Capable}:i.muteOthers={isPresent:this._ecsConfig[Yl][n][Wg.muteOthers],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.pstnDialOut]?i.pstnDialOut={isPresent:this._ecsConfig[Yl][n][Wg.pstnDialOut],reason:Jl.Capable}:i.pstnDialOut={isPresent:this._ecsConfig[Yl][n][Wg.pstnDialOut],reason:Jl.RoleRestricted},this._ecsConfig[Yl][n][Wg.addPhoneNumber]?i.addPhoneNumber={isPresent:this._ecsConfig[Yl][n][Wg.addPhoneNumber],reason:Jl.Capable}:i.addPhoneNumber={isPresent:this._ecsConfig[Yl][n][Wg.addPhoneNumber],reason:Jl.RoleRestricted}),i.removeParticipant={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.hangUpForEveryOne={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.addCommunicationUser={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.addTeamsUser={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.manageLobby={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.spotlightParticipant={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.removeParticipantsSpotlight={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.blurBackground={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.startLiveCaptions={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.stopLiveCaptions={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.raiseHand={isPresent:!1,reason:Jl.CapabilityNotApplicableForTheCallType},i.useReactions={isPresent:!0,reason:Jl.Capable},i.viewAttendeeNames={isPresent:!0,reason:Jl.Capable},this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on role change to ${e}`),i}}class Kg{constructor(e){this._logger=e,this._ecsConfig=yc()}getResolvedCapabilitiesBasedOnRole(e,t){let i={...t},n=e.toLocaleLowerCase();return n!==Wl.Attendee.toLocaleLowerCase()&&n!==Wl.Presenter.toLocaleLowerCase()&&n!==Wl.Consumer.toLocaleLowerCase()&&n!==Wl.Organizer.toLocaleLowerCase()&&n!==Wl.Coorganizer.toLocaleLowerCase()||(n=n.replace("-",""),t.turnVideoOn.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.turnVideoOn]?i.turnVideoOn={isPresent:!0,reason:Jl.Capable}:i.turnVideoOn={isPresent:!1,reason:Jl.RoleRestricted}),t.unmuteMic.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.unmuteMic]?i.unmuteMic={isPresent:!0,reason:Jl.Capable}:i.unmuteMic={isPresent:!1,reason:Jl.RoleRestricted}),t.shareScreen.reason!=Jl.UserPolicyRestricted&&(this._ecsConfig[Ql][n][Wg.shareScreen]?i.shareScreen={isPresent:!0,reason:Jl.Capable}:i.shareScreen={isPresent:!1,reason:Jl.RoleRestricted}),this._ecsConfig[Ql][n][Wg.removeParticipant]?i.removeParticipant={isPresent:!0,reason:Jl.Capable}:i.removeParticipant={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.hangUpForEveryOne]?i.hangUpForEveryOne={isPresent:!0,reason:Jl.Capable}:i.hangUpForEveryOne={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.addCommunicationUser]?i.addCommunicationUser={isPresent:!0,reason:Jl.Capable}:i.addCommunicationUser={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.addTeamsUser]?i.addTeamsUser={isPresent:!0,reason:Jl.Capable}:i.addTeamsUser={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.addPhoneNumber]?i.addPhoneNumber={isPresent:!0,reason:Jl.Capable}:i.addPhoneNumber={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.manageLobby]?i.manageLobby={isPresent:!0,reason:Jl.Capable}:i.manageLobby={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.spotlightParticipant]?i.spotlightParticipant={isPresent:!0,reason:Jl.Capable}:i.spotlightParticipant={isPresent:!1,reason:Jl.RoleRestricted},this._ecsConfig[Ql][n][Wg.removeParticipantsSpotlight]?i.removeParticipantsSpotlight={isPresent:!0,reason:Jl.Capable}:i.removeParticipantsSpotlight={isPresent:!1,reason:Jl.RoleRestricted},t.blurBackground.reason!=Jl.UserPolicyRestricted&&(this._ecsConfig[Ql][n][Wg.blurBackground]?i.blurBackground={isPresent:!0,reason:Jl.Capable}:i.blurBackground={isPresent:!1,reason:Jl.RoleRestricted}),t.startLiveCaptions.reason!=Jl.UserPolicyRestricted&&(this._ecsConfig[Ql][n][Wg.startLiveCaptions]?i.startLiveCaptions={isPresent:!0,reason:Jl.Capable}:i.startLiveCaptions={isPresent:!1,reason:Jl.RoleRestricted}),t.stopLiveCaptions.reason!=Jl.UserPolicyRestricted&&(this._ecsConfig[Ql][n][Wg.stopLiveCaptions]?i.stopLiveCaptions={isPresent:!0,reason:Jl.Capable}:i.stopLiveCaptions={isPresent:!1,reason:Jl.RoleRestricted}),t.raiseHand.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.raiseHand]?i.raiseHand={isPresent:!0,reason:Jl.Capable}:i.raiseHand={isPresent:!1,reason:Jl.RoleRestricted}),t.pstnDialOut.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.pstnDialOut]?i.pstnDialOut={isPresent:!0,reason:Jl.Capable}:i.pstnDialOut={isPresent:!1,reason:Jl.RoleRestricted}),t.muteOthers.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.muteOthers]?i.muteOthers={isPresent:!0,reason:Jl.Capable}:i.muteOthers={isPresent:!1,reason:Jl.RoleRestricted}),t.useReactions.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.useReactions]?i.useReactions={isPresent:!0,reason:Jl.Capable}:i.useReactions={isPresent:!1,reason:Jl.RoleRestricted}),t.viewAttendeeNames.reason!=Jl.MeetingRestricted&&(this._ecsConfig[Ql][n][Wg.viewAttendeeNames]?i.viewAttendeeNames={isPresent:!0,reason:Jl.Capable}:i.viewAttendeeNames={isPresent:!1,reason:Jl.RoleRestricted})),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on role change to ${e}`),i}getResolvedCapabilitiesBasedOnMeetingCapabilities(e,t){let i={...t};return null!=e.attendeeRestrictions&&("DisableVideo"!=e.attendeeRestrictions&&"DisableAv"!=e.attendeeRestrictions?i.turnVideoOn={isPresent:!0,reason:Jl.Capable}:i.turnVideoOn={isPresent:!1,reason:Jl.MeetingRestricted}),null!=e.attendeeRestrictions&&("DisableAv"!=e.attendeeRestrictions?i.unmuteMic={isPresent:!0,reason:Jl.Capable}:i.unmuteMic={isPresent:!1,reason:Jl.MeetingRestricted}),null!=e.allowRaiseHands&&(e.allowRaiseHands?i.raiseHand={isPresent:!0,reason:Jl.Capable}:i.raiseHand={isPresent:!1,reason:Jl.MeetingRestricted}),null!=e.allowPstnConferencing&&(e.allowPstnConferencing?i.pstnDialOut={isPresent:!0,reason:Jl.Capable}:i.pstnDialOut={isPresent:!1,reason:Jl.MeetingRestricted}),null!=e.allowTeamsMeetingReactions&&(e.allowTeamsMeetingReactions?i.useReactions={isPresent:!0,reason:Jl.Capable}:i.useReactions={isPresent:!1,reason:Jl.MeetingRestricted}),null!=e.maskIdentitiesForRole&&(e.maskIdentitiesForRole?i.viewAttendeeNames={isPresent:!1,reason:Jl.MeetingRestricted}:i.viewAttendeeNames={isPresent:!0,reason:Jl.Capable}),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on meeting details change to ${e}`),i}getResolvedCapabilitiesBasedOnUserPolicy(e,t){let i={...t};return null!=e.teamsMeetingPolicy?.screenSharingMode&&("Disabled"==e.teamsMeetingPolicy?.screenSharingMode?i.shareScreen={isPresent:!1,reason:Jl.UserPolicyRestricted}:i.shareScreen={isPresent:!0,reason:Jl.Capable}),null!=e.teamsMeetingPolicy?.liveCaptionsEnabledType&&("Disabled"==e.teamsMeetingPolicy?.liveCaptionsEnabledType?i.startLiveCaptions={isPresent:!1,reason:Jl.UserPolicyRestricted}:i.startLiveCaptions={isPresent:!0,reason:Jl.Capable}),null!=e.teamsMeetingPolicy?.liveCaptionsEnabledType&&("Disabled"==e.teamsMeetingPolicy?.liveCaptionsEnabledType?i.stopLiveCaptions={isPresent:!1,reason:Jl.UserPolicyRestricted}:i.stopLiveCaptions={isPresent:!0,reason:Jl.Capable}),null!=e.teamsMeetingPolicy?.videoFiltersMode&&("NoFilters"==e.teamsMeetingPolicy?.videoFiltersMode?i.blurBackground={isPresent:!1,reason:Jl.UserPolicyRestricted}:i.blurBackground={isPresent:!0,reason:Jl.Capable}),this._logger.log(`Capabilities resolved to : ${JSON.stringify(i)} on user policy update to ${e}`),i}}class Jg{constructor(e,t,i,n,r,a){this._eventEmitter=e,this._logger=t,this._callInfo=n,this._tsCall=a,this._call=i,this._callAgent=r,this._capabilities=this.initializeCapabilities(),("roomJoin"==this._callInfo.context||"teamsMeetingJoin"==this._callInfo.context)&&this.doInitialCapabilityResolutionBasedOnRole(),"teamsMeetingJoin"==this._callInfo.context&&this.doInitialCapabilityResolutionBasedOnUserPolicy(),"teamsMeetingJoin"==this._callInfo.context&&this.doInitialCapabilityResolutionBasedOnMeetingCapabilities()}initializeCapabilities(){return this._logger.info("initializing capabilities"),"roomJoin"!=this._callInfo.context&&"teamsMeetingJoin"!=this._callInfo.context?{turnVideoOn:{isPresent:!1,reason:Jl.FeatureNotSupported},unmuteMic:{isPresent:!1,reason:Jl.FeatureNotSupported},shareScreen:{isPresent:!1,reason:Jl.FeatureNotSupported},removeParticipant:{isPresent:!1,reason:Jl.FeatureNotSupported},hangUpForEveryOne:{isPresent:!1,reason:Jl.FeatureNotSupported},addCommunicationUser:{isPresent:!1,reason:Jl.FeatureNotSupported},addTeamsUser:{isPresent:!1,reason:Jl.FeatureNotSupported},addPhoneNumber:{isPresent:!1,reason:Jl.FeatureNotSupported},manageLobby:{isPresent:!1,reason:Jl.FeatureNotSupported},spotlightParticipant:{isPresent:!1,reason:Jl.FeatureNotSupported},removeParticipantsSpotlight:{isPresent:!1,reason:Jl.FeatureNotSupported},blurBackground:{isPresent:!1,reason:Jl.FeatureNotSupported},startLiveCaptions:{isPresent:!1,reason:Jl.FeatureNotSupported},stopLiveCaptions:{isPresent:!1,reason:Jl.FeatureNotSupported},raiseHand:{isPresent:!1,reason:Jl.FeatureNotSupported},pstnDialOut:{isPresent:!1,reason:Jl.FeatureNotSupported},muteOthers:{isPresent:!1,reason:Jl.FeatureNotSupported},useReactions:{isPresent:!1,reason:Jl.FeatureNotSupported},viewAttendeeNames:{isPresent:!1,reason:Jl.FeatureNotSupported}}:{turnVideoOn:{isPresent:!1,reason:Jl.NotInitialized},unmuteMic:{isPresent:!1,reason:Jl.NotInitialized},shareScreen:{isPresent:!1,reason:Jl.NotInitialized},removeParticipant:{isPresent:!1,reason:Jl.NotInitialized},hangUpForEveryOne:{isPresent:!1,reason:Jl.NotInitialized},addCommunicationUser:{isPresent:!1,reason:Jl.NotInitialized},addTeamsUser:{isPresent:!1,reason:Jl.NotInitialized},addPhoneNumber:{isPresent:!1,reason:Jl.NotInitialized},manageLobby:{isPresent:!1,reason:Jl.NotInitialized},spotlightParticipant:{isPresent:!1,reason:Jl.NotInitialized},removeParticipantsSpotlight:{isPresent:!1,reason:Jl.NotInitialized},blurBackground:{isPresent:!1,reason:Jl.NotInitialized},startLiveCaptions:{isPresent:!1,reason:Jl.NotInitialized},stopLiveCaptions:{isPresent:!1,reason:Jl.NotInitialized},raiseHand:{isPresent:!1,reason:Jl.NotInitialized},pstnDialOut:{isPresent:!1,reason:Jl.NotInitialized},muteOthers:{isPresent:!1,reason:Jl.NotInitialized},useReactions:{isPresent:!1,reason:Jl.NotInitialized},viewAttendeeNames:{isPresent:!1,reason:Jl.NotInitialized}}}doInitialCapabilityResolutionBasedOnRole(){this.resolveCapabilitiesBasedOnRole()}doInitialCapabilityResolutionBasedOnUserPolicy(){this.getCapabilityResolver()instanceof Kg&&"roomJoin"!=this._callInfo.context&&this.resolveCapabilitiesBasedOnUserPolicy()}doInitialCapabilityResolutionBasedOnMeetingCapabilities(){this.resolveCapabilitiesBasedOnMeetingCapabilities()}getCapabilityResolver(){return this._callInfo.context?.match("roomJoin")?new qg(this._logger):(this._callInfo.context?.match("teamsMeetingJoin"),new Kg(this._logger))}getCapabilities(){return this._capabilities}resolveCapabilitiesBasedOnRole(){if("roomJoin"!=this._callInfo.context&&"teamsMeetingJoin"!=this._callInfo.context)return;let e=this._call.role;e==Wl.Unknown&&(e="roomJoin"==this._callInfo.context?Wl.Consumer:Wl.Attendee);let t=this.getCapabilityResolver();if(t){let i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnRole(e,this._capabilities),!g.isEqual(i,this._capabilities)){const t=this.getChangedCapabilitiesInfo(i,this._capabilities,"RoleChanged");this._logger.info(`Capabilities has changed based on role update to ${e}, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(t)}`),this._eventEmitter.emit("capabilitiesChanged",t)}}}resolveCapabilitiesBasedOnMeetingCapabilities(){if("teamsMeetingJoin"!=this._callInfo.context)return;let e={};e={...this._tsCall.meetingDetails?.capabilities,...this._tsCall.meetingDetails?.meetingCapability};let t=this.getCapabilityResolver();if(t&&t){const i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnMeetingCapabilities(e,this._capabilities),!g.isEqual(i,this._capabilities)){const e=this.getChangedCapabilitiesInfo(i,this._capabilities,"MeetingOptionOrOrganizerPolicyChanged");this._logger.info(`Capabilities has changed due to meeting capabilities, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}resolveCapabilitiesBasedOnUserPolicy(){if("teamsMeetingJoin"!=this._callInfo.context)return;let e=this._callAgent.getUserPolicy(),t=this.getCapabilityResolver();if(t&&t&&e){let i=JSON.parse(JSON.stringify(this._capabilities));if(this._capabilities=t.getResolvedCapabilitiesBasedOnUserPolicy(e,this._capabilities),!g.isEqual(i,this._capabilities)){const e=this.getChangedCapabilitiesInfo(i,this._capabilities,"UserPolicyChanged");this._logger.info(`Capabilities has changed due to user policy, emitting capabilities changed event with capabilitiesChangeInfo: ${JSON.stringify(e)}`),this._eventEmitter.emit("capabilitiesChanged",e)}}}getChangedCapabilitiesInfo(e,t,i){let n={},r={};return Object.keys(e).forEach((i=>{e[i].isPresent!=t[i].isPresent&&(n[i]=e[i],r[i]=t[i])})),{oldValue:n,newValue:r,reason:i}}}class Yg{constructor(e){this._eventEmitter=e}get capabilities(){return this._capabilityResolver.getCapabilities()}initialize(e,t,i,n,r,a){this._logger=a.createChild((()=>`CapabilitiesFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._call=i,this._callInfo=n,this._internalCallAgent=t,this._timeToInitialize=new Date,this._capabilityResolver=new Jg(this._eventEmitter,this._logger,this._call,this._callInfo,this._internalCallAgent,this._tsCall),this._call.on("roleChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnRole();let e=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after role set is "+e)})),this._call.onMeetingCapabilitiesChanged("meetingCapabilitiesChanged",(()=>{this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities();let e=((new Date).getTime()-this._timeToInitialize.getTime())/1e3;this._logger.info("Time difference to initialize after meeting set up is"+e)}))}}var Qg,Zg,Xg=function(e){var t=typeof e;if("string"===t||"number"===t)return function(e,t){var i="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";t=t||62;var n,r=[],a="",s=e<0?"-":"";for(e=Math.abs(e);e>=t;)n=e%t,e=Math.floor(e/t),r.push(i[n]);e>0&&r.push(i[e]);for(var o=r.length-1;o>=0;o--)a+=r[o];return s+a}(function(e){var t=0;if(0==e.length)return t;for(var i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t&=t;return t}(String(e)),61).replace("-","Z");throw new Error("Unexpected input type")};!function(e){e.ping="ping",e.pong="pong"}(Qg||(Qg={}));class em{get diagnosticInformation(){return this._sdkDiagnosticInformation}get logDump(){return this._logger.log("Log dump requested"),this._logger.dumpAllLogs()}get AcsResourceId(){return this._callAgent?.getAcsResourceId()}get lastLocalParticipantId(){return this._lastLocalParticipantId}get localParticipantIdMap(){return this._localParticipantIdMap}get incommingCallIdMap(){return this._incommingCallIdMap}get clientId(){return this._callAgent?.getClientId()}constructor(){this._localParticipantIdMap={},this._incommingCallIdMap={}}initialize(e,t){this._logger=t,this._callAgent=e?.callClient?.callAgent,this._sdkDiagnosticInformation=e?.callClient.sdkDiagnosticInformation,this._logger.info("waiting for call agent to be created");e?.callClient.on("callAgentCreated",(()=>{this._callAgent=e?.callClient.callAgent,this.subscribeToCallAgentEvents()}))}dispose(){}subscribeToCallAgentEvents(){try{this._callAgent?.on("callsUpdated",(e=>{[...e.added,...e.removed].forEach((e=>{this.updateLocalParticipantIdMap(e),e.on("idChanged",(()=>{this.updateLocalParticipantIdMap(e)}))}))})),this._callAgent?.on("incomingCall",(e=>{let t=e.incomingCall;t.on("callEnded",(e=>{try{this._incommingCallIdMap[t.id]=JSON.stringify(e.callEndReason)}catch(e){this._incommingCallIdMap[t.id]="callEnd reason unknown"}}));try{this._incommingCallIdMap[t.id]=JSON.stringify(e.incomingCall.callerInfo.identifier?.kind)}catch(e){this._incommingCallIdMap[t.id]="identifier kind unknown"}}))}catch(e){this._logger.info("failed to subscribe to call agent events, due to non initialized call agent")}}updateLocalParticipantIdMap(e){try{let t=this._localParticipantIdMap[e.tsCall.participantId]?.callIds.filter((t=>t!==e.tsCall.callId)).concat([e.tsCall.callId])??[e.tsCall.callId],i=[],n=[],r=e.callEndReason?JSON.stringify(e.callEndReason):e.state,a=e.state;this._localParticipantIdMap[e.tsCall.participantId]?.callEndReasons?(this._localParticipantIdMap[e.tsCall.participantId].callEndReasons.slice(-1)[0]!==r?(this._localParticipantIdMap[e.tsCall.participantId].callEndReasons.push(r),i=this._localParticipantIdMap[e.tsCall.participantId].callEndReasons):i=this._localParticipantIdMap[e.tsCall.participantId].callEndReasons,this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.slice(-1)[0]!==a?(this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.push(a),n=this._localParticipantIdMap[e.tsCall.participantId].stateTransitions):n=this._localParticipantIdMap[e.tsCall.participantId].stateTransitions):(i=[r],n=[e.state]),this._localParticipantIdMap[e.tsCall.participantId]={callIds:t,callEndReasons:i,stateTransitions:n},this._logger.info(`localParticipantIdMap: ${JSON.stringify(this._localParticipantIdMap)}`),e.on("stateChanged",(()=>{"Connected"===e.state&&(this._lastLocalParticipantId=e.tsCall.participantId,this._logger.info(`last patricipant id: ${this._lastLocalParticipantId}`)),this._localParticipantIdMap[e.tsCall.participantId].stateTransitions.slice(-1)[0]!==e.state&&this.localParticipantIdMap[e.tsCall.participantId].stateTransitions.push(e.state)}))}catch(e){this._logger.error(`exception occured while updating localParticipantId map: ${e}`)}}}class tm{get isCallClientActiveInAnotherTab(){return this._isCallClientActiveInAnotherTab}get isAnotherCallClientActiveInSameTab(){return this._isAnotherCallClientActiveInSameTab}constructor(e){this._eventEmitter=e,this._tabGroupId=tm.tabId,this._isCallClientActiveInAnotherTab=!1,this._isAnotherCallClientActiveInSameTab=!1,this._areThereMultipleTabs=null,this._manyCallClientInSameTab=null,this._isTabFirstLoadFlag=!0,this._intervalId=void 0,this._timeoutId=void 0,this._channel=new BroadcastChannel(yc().debugInfo.broadcastChannelName)}initialize(e,t,i){this._callClient=e,this._logger=t,this._telemetryLogManager=i;const n=yc().debugInfo.tabsBroadcastDelay,r=yc().debugInfo.tabsUpdateDelay;this.tabsCheck(),this._channel.postMessage({action:Qg.ping,tabId:tm.tabId,groupId:this._tabGroupId}),this._timeoutId=setTimeout((()=>{this._areThereMultipleTabs&&(this._isCallClientActiveInAnotherTab=this._areThereMultipleTabs),this._manyCallClientInSameTab&&(this._isAnotherCallClientActiveInSameTab=this._manyCallClientInSameTab),this.sendTabUpdateEvent(),this._isTabFirstLoadFlag=!1}),10),this._intervalId=setInterval((()=>{this._areThereMultipleTabs=null,this._manyCallClientInSameTab=null,this._channel.postMessage({action:Qg.ping,tabId:tm.tabId,groupId:this._tabGroupId}),setTimeout((()=>{null===this._areThereMultipleTabs&&(this._areThereMultipleTabs=!1),null===this._manyCallClientInSameTab&&(this._manyCallClientInSameTab=!1),this.tabsUpdate()}),r)}),n)}tabsCheck(){this._channel.addEventListener("message",(e=>{e.data?.action!==Qg.ping&&e.data?.action!==Qg.pong||(e.data?.action===Qg.ping&&(tm.tabId===e.data.tabId?this._manyCallClientInSameTab=!0:tm.tabId!==e.data.tabId&&(this._areThereMultipleTabs=!0),this._channel.postMessage({action:Qg.pong,tabId:tm.tabId,groupId:this._tabGroupId})),e.data?.action===Qg.pong&&(tm.tabId===e.data.tabId?this._manyCallClientInSameTab=!0:tm.tabId!==e.data.tabId&&(this._areThereMultipleTabs=!0),this._tabGroupId!==e.data.groupId&&(this._tabGroupId=e.data.groupId)),this.tabsUpdate())}))}sendTabUpdateToCallEvent(){this._callClient.callAgent?._calls?.forEach((e=>e?.stats?.recordEvent({name:Kh.sdk_active_in_another_tab,callId:e.id,localParticipantId:e.tsCall.participantId,data:{tabId:tm.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab}})))}sendTabUpdateEvent(){const e={tabId:tm.tabId,tabGroupId:this._tabGroupId,isCallClientActiveInAnotherTab:this._isCallClientActiveInAnotherTab,isAnotherCallClientActiveInSameTab:this._isAnotherCallClientActiveInSameTab};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_tab_events,tenant:hl,properties:e})}tabsUpdate(){this._isTabFirstLoadFlag||null===this._manyCallClientInSameTab||null===this._areThereMultipleTabs||this._isCallClientActiveInAnotherTab===this._areThereMultipleTabs&&this._isAnotherCallClientActiveInSameTab===this._manyCallClientInSameTab||(this._isAnotherCallClientActiveInSameTab!==this._manyCallClientInSameTab&&(this._logger.log(`isAnotherCallClientActiveInSameTab changed from ${this._isAnotherCallClientActiveInSameTab} to ${this._manyCallClientInSameTab}`),this._isAnotherCallClientActiveInSameTab=this._manyCallClientInSameTab,this._eventEmitter.emit("isAnotherCallClientActiveInSameTabChanged")),this._isCallClientActiveInAnotherTab!==this._areThereMultipleTabs&&(this._logger.log(`isCallClientActiveInAnotherTab changed from ${this._isCallClientActiveInAnotherTab} to ${this._areThereMultipleTabs}`),this._isCallClientActiveInAnotherTab=this._areThereMultipleTabs,this._eventEmitter.emit("isCallClientActiveInAnotherTabChanged")),this.sendTabUpdateEvent(),this.sendTabUpdateToCallEvent())}dispose(){this._channel.close(),void 0!==this._timeoutId&&clearTimeout(this._timeoutId),void 0!==this._intervalId&&clearInterval(this._intervalId)}}tm.tabId=x(),(Zg=e.DiagnosticQuality||(e.DiagnosticQuality={}))[Zg.Good=1]="Good",Zg[Zg.Poor=2]="Poor",Zg[Zg.Bad=3]="Bad";const im="networkReconnect",nm="networkReceiveQuality",rm="networkSendQuality",am="networkRelaysNotReachable",sm="noNetwork",om="noSpeakerDevicesEnumerated",lm="noMicrophoneDevicesEnumerated",cm="microphoneNotFunctioning",dm="microphoneMuteUnexpectedly",um="cameraStoppedUnexpectedly",hm="capturerStoppedUnexpectedly",pm="speakingWhileMicrophoneIsMuted",gm="cameraFreeze",mm="cameraStartFailed",fm="capturerStartFailed",vm="cameraStartTimedOut",Sm="screenshareRecordingDisabled",ym="microphonePermissionDenied",Cm="cameraPermissionDenied";class _m{get network(){return this._network}get media(){return this._media}constructor(){}initialize(e,t){this._network=new Tm(e,t),this._media=new bm(e,t)}dispose(){}}class Em{constructor(t,i){this.logger=i,this._tsUfdUnknownValue=0,this.tsQualityToAcsQualityMap={1:e.DiagnosticQuality.Good,2:e.DiagnosticQuality.Poor,3:e.DiagnosticQuality.Bad},this.tssQualityToAcsBooleanMap={3:!0,1:!1},this._tsCall=t.tsCall,this.eventEmitter=new Kp.EventEmitter,this._tsCall.on("callQualityChanged",(t=>{try{const i=this.mapTSQualityEventType(t.type,t.mediaType);if(i){if(t.value===this._tsUfdUnknownValue)return;const n=i,r=this.mapTSQualityLevel(i,t.value);let a;if("number"!=typeof r||r!==e.DiagnosticQuality.Good&&r!==e.DiagnosticQuality.Poor&&r!==e.DiagnosticQuality.Bad){if("boolean"!=typeof r)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.INCORRECT_VALUETYPE_MAPPED,defaultErrorMessageArgs:[typeof r,r,n]});a="DiagnosticFlag"}else a="DiagnosticQuality";let s={diagnostic:n,value:r,valueType:a};this.logger.log(`Call diagnostic changed, diagnostic='${s.diagnostic}', value='${s.value}'`);const o="DiagnosticFlag"===s.valueType&&!0===s.value,l="DiagnosticQuality"===s.valueType&&(s.value===e.DiagnosticQuality.Bad||s.value===e.DiagnosticQuality.Poor);(o||l)&&this.logger.warn(`Call diagnostic error raised!, diagnostic='${s.diagnostic}', value='${s.value}', value type='${s.valueType}'`),this.eventEmitter.emit("diagnosticChanged",s)}}catch(e){this.logger.error(`${e?.message})`)}}))}}class Tm extends Em{constructor(e,t){super(e,t.createChild((()=>`[UserFacingDiagnosticsFeature:NetworkDiagnostics:Call(id='${e.tsCall.callId}', state='${e.tsCall.state}')]`))),this.latestNetworkDiagnostics=new Map}on(e,t){if("diagnosticChanged"!==e)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("diagnosticChanged"!==e&&"diagnosticFlagChanged"!==e)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getLatest(){try{return wc(this.latestNetworkDiagnostics)}catch(e){return this.logger.error("Failed to get latest network diagnostics"),{}}}mapTSQualityEventType(e){return{5:im,2:nm,1:rm,32:am,37:sm}[e]}mapTSQualityLevel(e,t){let i,n;switch(e){case im:case nm:case rm:n="DiagnosticQuality",i=this.tsQualityToAcsQualityMap[t];break;case am:case sm:n="DiagnosticFlag",i=this.tssQualityToAcsBooleanMap[t]}if(void 0===i)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.INCORRECT_VALUE_MAPPED,defaultErrorMessageArgs:[t,e]});return this.latestNetworkDiagnostics.set(e,{value:i,valueType:n}),i}}class bm extends Em{constructor(e,t){super(e,t.createChild((()=>`[UserFacingDiagnosticsFeature:MediaDiagnostics:Call(id='${e.tsCall.callId}', state='${e.tsCall.state}')]`))),this.latestMediaDiagnostics=new Map}on(e,t){if("diagnosticChanged"!==e)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("diagnosticChanged"!==e&&"diagnosticFlagChanged"!==e)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getLatest(){try{return wc(this.latestMediaDiagnostics)}catch(e){return this.logger.error("Failed to get latest media diagnostics"),{}}}mapTSQualityEventType(e,t){const i={44:om,43:lm,9:cm,25:dm,27:pm,45:gm,33:mm,34:vm,55:Sm,26:ym,47:Cm};return this.overrideQualityEventsForMediaType(i[e],t)}overrideQualityEventsForMediaType(e,t){if(e===dm)switch(t){case 1:return um;case 2:return hm}return e===mm&&2===t?fm:e}mapTSQualityLevel(e,t){let i,n;switch(e){case om:case lm:case cm:case dm:case pm:case gm:case mm:case vm:case Sm:case ym:case Cm:case um:case hm:case fm:n="DiagnosticFlag",i=this.tssQualityToAcsBooleanMap[t]}if(void 0===i)throw new b({defaultError:f.FEATURES.DIAGNOSTICS.INCORRECT_VALUE_MAPPED,defaultErrorMessageArgs:[t,e]});return this.latestMediaDiagnostics.set(e,{value:i,valueType:n}),i}}class Im{constructor(e){this._eventEmitter=e,this.localDominantList=[]}initialize(e,t,i,n,r=!1){this._logger=n.createChild((()=>`DominantSpeakersFeature${r?"Internal":""}::Call(id='${e.callId}')`)),this._tsCall=e,this.localDominantList=this._tsCall.dominantSpeakerInfo?.speakerList||[],this._tsCallChangedListener=this._tsCall.changed((()=>{let e=!1;if(this.localDominantList.length!=this._tsCall.dominantSpeakerInfo.speakerList.length)e=!0;else for(let t in this._tsCall.dominantSpeakerInfo.speakerList)if(this._tsCall.dominantSpeakerInfo.speakerList[t]!==this.localDominantList[t]){e=!0;break}e&&(this._logger.info("Dominant speakers list change detected"),this.localDominantList=this._tsCall.dominantSpeakerInfo.speakerList,this._eventEmitter.emit("dominantSpeakersChanged"))}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get dominantSpeakers(){let e=Array();return this._tsCall.dominantSpeakerInfo.speakerList.map((t=>{e.push(ac(t))})),{speakersList:e,timestamp:this._tsCall.dominantSpeakerInfo.timestamp||new Date}}dispose(){this._eventEmitter.removeAllListeners(),this._tsCallChangedListener?.dispose()}}class wm extends Kp.EventEmitter{constructor(e,t){super(),this._options={enableLogOn:!0,enableLogOff:!0,enableLogOnce:!0,enableLogEmit:!0},this._logger=e.createChild("CallingEventEmitter"),t&&(this._options=t)}on(e,t){return!1!==this._options.enableLogOn&&this._logger.info(`event:subscribe to ${e.toString()}`),super.on(e,t)}once(e,t){return!1!==this._options.enableLogOnce&&this._logger.info(`event:subscribe once to ${e.toString()}`),super.once(e,t)}off(e,t){return!1!==this._options.enableLogOff&&this._logger.info(`event:unsubscribed ${e.toString()}`),super.off(e,t)}emit(e,...t){try{return!1!==this._options.enableLogEmit&&this._logger.info(`event:emit ${e.toString()}`),super.emit(e,...t)}catch(t){return this._logger.warn(`Application threw an error while it handled the ${e.toString()} event`),!1}}}function Rm(){return{audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{}}}function Am(e){let t=e.length>0?e[0]:0;return e.forEach((e=>{e>t&&(t=e)})),t}function Pm(e){let t=e.length>0?e[0]:0;return e.forEach((e=>{e<t&&(t=e)})),t}function Mm(e){let t=0,i=0;return e.forEach((e=>{const n=e-i,r=t+n;i=r-t-n,t=r})),t}const km=Rm;class Dm{constructor(e){this._metricsProperties=e,this._originalValues={},this._aggregateValues={},this._events=[],this._currentValues={}}addStats(e,t){const i=this._metricsProperties[e];if(void 0!==i&&!0!==i.skip){if(i.events){const n=i.output_key??e;t!==this._currentValues[n]&&(this._currentValues[n]=t,this._events.push({name:n,value:t,timestamp:Date.now()}))}else{let i=this._originalValues[e];void 0===i&&(i={raw:[],beginTime:Date.now()},this._originalValues[e]=i),i.raw.push(t)}return t}}aggregate(){for(const[e,t]of Object.entries(this._originalValues)){const i=this._metricsProperties[e],n=i.output_key??e;let r=this._aggregateValues[n];void 0===r&&(r={raw:[],timestamp:new Date(t.beginTime)},i.aggregable&&(r.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[n]=r);const a=t.raw;let s=a;if(i.aggregable&&r.aggregation){const e=a.filter((e=>"number"==typeof e&&!isNaN(e)));r.aggregation.count.push(e.length),r.aggregation.sum.push(Mm(e)),r.aggregation.max.push(Am(e)),r.aggregation.min.push(Pm(e)),s=e}i.raw_data_reduction&&s.length>0&&(r.reduced=r.reduced||[],r.reduced.push(s[s.length-1])),s.forEach((e=>r.raw.push(e)))}this._originalValues={}}popAggregates(){const e=this._aggregateValues;return this._aggregateValues={},e}popEvents(){const e=this._events;return this._events=[],e}}class Om{constructor(e,t){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=km(),this._isActive=!1,t.aggregationInterval<1)throw new Error("invalid aggregationInterval value range");if(t.dataPointsPerAggregation<1)throw new Error("invalid dataPointsPerAggregation value range");this._metricsProperties=t.metricsPropertics,this._logger=e.createChild("TelemetryCollector"),this._eventEmitter=new wm(this._logger,{enableLogEmit:!1}),this._callStateChanged=kh(),this._aggregationInterval=t.aggregationInterval,this._dataPointsPerAggregation=t.dataPointsPerAggregation,this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}onReport(e){this._processMediaStatsReport(e)}onAdded(e){this._isActive!==e&&(this._isActive=e,this._callStateChanged.resolve(e))}onRemoved(){this.dispose()}pause(){this._isActive&&(this._isActive=!1,this._callStateChanged.resolve(!1))}resume(){this._isActive||(this._isActive=!0,this._callStateChanged.resolve(!0))}stop(){this.dispose()}_processMediaStatsReport(e){try{const t=[[e.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send,"send"],[e.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive,"recv"],[e.video.send,this._calculators.video.send,this._metricsProperties.video.send,"send"],[e.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive,"recv"],[e.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send,"send"],[e.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive,"recv"],[e.dataChannel,this._calculators.dataChannel,this._metricsProperties.dataChannel,""],[e.transports,this._calculators.transports,this._metricsProperties.transports,""]];for(const[i,n,r,a]of t){const t=[],s=Object.keys(n);Object.keys(i).forEach((s=>{const o=i[s],l=o.id;t.push(l),void 0===n[l]&&(n[l]=new Dm(r));const c=(e,t)=>n[l].addStats(e,t);if(Object.keys(o).forEach((e=>c(e,o[e]))),"send"==a||"recv"==a){const t=o.transportId;if(void 0!==t){const i=e.transports[t];void 0!==i.rtt&&c("pairRttInMs",i.rttInMs),void 0!==i.availableIncomingBitrate&&"recv"==a&&c("availableBitrate",i.availableIncomingBitrate),void 0!==i.availableOutgoingBitrate&&"send"==a&&c("availableBitrate",i.availableOutgoingBitrate)}}})),s.filter((e=>!t.includes(e))).forEach((e=>{delete n[e]}))}}catch(e){this._logger.error(e)}}async _run(){let e=0;const t=()=>{if(0===e)return;const t={audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{}},i=[[t.audio.send,this._calculators.audio.send],[t.audio.receive,this._calculators.audio.receive],[t.video.send,this._calculators.video.send],[t.video.receive,this._calculators.video.receive],[t.screenShare.send,this._calculators.screenShare.send],[t.screenShare.receive,this._calculators.screenShare.receive],[t.dataChannel,this._calculators.dataChannel],[t.transports,this._calculators.transports]];for(const[e,t]of i)for(const[i,n]of Object.entries(t))e[i]={id:i,...n.popAggregates(),events:n.popEvents()};this._eventEmitter.emit("data",t),e=0};let i=1e3*this._aggregationInterval;for(;!this._disposed;){const n=[this._calculators.audio.send,this._calculators.audio.receive,this._calculators.video.send,this._calculators.video.receive,this._calculators.screenShare.send,this._calculators.screenShare.receive,this._calculators.dataChannel];if(this._isActive){i>0&&await Lh((()=>this._callStateChanged.promise),i).catch((e=>{}));const r=Date.now();for(const e of n)for(const[,t]of Object.entries(e))t.aggregate();e++,e===this._dataPointsPerAggregation&&t();const a=Date.now();i=r+1e3*this._aggregationInterval-a}else t(),this._calculators=km(),await this._callStateChanged.promise.catch((e=>{})),i=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=kh())}t()}}function Nm(e){const t=[];return e.sort(((e,t)=>e.id>t.id?1:e.id<t.id?-1:0)),e.forEach((e=>{const i=/^([^.]+)\.?([^.]+)?$/.exec(e.id);if(i&&i[2]){e.id=g.toString(i[2]);const n=g.toString(i[1]);if(t.length>0&&t[t.length-1].id===n){const i=t[t.length-1].altLayouts??[];i.push(e),t[t.length-1].altLayouts=i}else t.push(e)}else t.push(e)})),t}class Lm{constructor(e,t){if(this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=km(),this._isActive=!1,t.aggregationInterval<1)throw new b({defaultError:f.FEATURES.MEDIA_STATS.INVALID_AGGREGATION_INTERVAL_RANGE});if(t.dataPointsPerAggregation<1)throw new b({defaultError:f.FEATURES.MEDIA_STATS.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._metricsProperties=t.metricsPropertics,this._logger=e.createChild("MediaStatsCollector"),this._eventEmitter=new wm(this._logger,{enableLogEmit:!1}),this._callStateChanged=kh(),this._aggregationInterval=t.aggregationInterval,this._dataPointsPerAggregation=t.dataPointsPerAggregation,this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._disposed||(this._disposed=!0,this._callStateChanged.resolve(!1),this._eventEmitter.removeAllListeners(),this._mediaStatsSource?.removeSink(this))}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}onReport(e){this._processMediaStatsReport(e)}onAdded(e){this._isActive!==e&&(this._isActive=e,this._callStateChanged.resolve(e))}onRemoved(){this.dispose()}pause(){this._isActive&&(this._isActive=!1,this._callStateChanged.resolve(!1))}resume(){this._isActive||(this._isActive=!0,this._callStateChanged.resolve(!0))}stop(){this.dispose()}_processMediaStatsReport(e){const t={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};try{const i=[[e.audio.send,t.audio.send,this._calculators.audio.send,this._metricsProperties.audio.send],[e.audio.receive,t.audio.receive,this._calculators.audio.receive,this._metricsProperties.audio.receive],[e.video.send,t.video.send,this._calculators.video.send,this._metricsProperties.video.send],[e.video.receive,t.video.receive,this._calculators.video.receive,this._metricsProperties.video.receive],[e.screenShare.send,t.screenShare.send,this._calculators.screenShare.send,this._metricsProperties.screenShare.send],[e.screenShare.receive,t.screenShare.receive,this._calculators.screenShare.receive,this._metricsProperties.screenShare.receive],[e.transports,t.transports,this._calculators.transports,this._metricsProperties.transports]];let n=!1;for(const[e,t,r,a]of i){const i=[],s=Object.keys(r);Object.keys(e).forEach((s=>{const o=e[s];let l=o.id;o.groupId&&(l=`${o.groupId}.${l}`,n=!0);const c={id:l};i.push(l),void 0===r[l]&&(r[l]=new Dm(a)),Object.keys(o).forEach((e=>{const t=a[e];if(t&&!0!==t.skip){const i=r[l].addStats(e,o[e]),n=t.output_key??e;c[n]=i}})),t.push(c)})),s.filter((e=>!i.includes(e))).forEach((e=>{delete r[e]}))}n&&(t.video.send=Nm(t.video.send),t.screenShare.send=Nm(t.screenShare.send))}catch(e){this._logger.error(e)}this._eventEmitter.emit("sampleReported",t)}async _run(){let e=0;const t=()=>{if(0===e)return;const t={audio:{send:[],receive:[]},video:{send:[],receive:[]},screenShare:{send:[],receive:[]},transports:[]};for(const[e,i]of Object.entries(this._calculators.audio.send))t.audio.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.audio.receive))t.audio.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.video.send))t.video.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.video.receive))t.video.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.screenShare.send))t.screenShare.send.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.screenShare.receive))t.screenShare.receive.push({id:e,...i.popAggregates()});for(const[e,i]of Object.entries(this._calculators.transports))t.transports.push({id:e,...i.popAggregates()});t.video.send=Nm(t.video.send),t.screenShare.send=Nm(t.screenShare.send),this._eventEmitter.emit("summaryReported",t),e=0};let i=1e3*this._aggregationInterval;for(;!this._disposed;){const n=[this._calculators.audio.send,this._calculators.audio.receive,this._calculators.video.send,this._calculators.video.receive,this._calculators.screenShare.send,this._calculators.screenShare.receive,this._calculators.transports];if(this._isActive){i>0&&await Lh((()=>this._callStateChanged.promise),i).catch((e=>{}));const r=Date.now();for(const e of n)for(const[,t]of Object.entries(e))t.aggregate();e++,e===this._dataPointsPerAggregation&&t();const a=Date.now();i=r+1e3*this._aggregationInterval-a}else t(),this._calculators=km(),await this._callStateChanged.promise.catch((e=>{})),i=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=kh())}t()}}class xm{constructor(){this._eventEmitter=new Kp.EventEmitter,this._getCurrentTime=globalThis.performance&&"function"==typeof globalThis.performance.now?()=>globalThis.performance.now():()=>Date.now()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners()}}class Fm extends xm{constructor(e){super(),this._intervalInMs=e,this._handle=0}start(){this._handle||(this._handle=globalThis.setInterval((()=>{this._eventEmitter.emit("tick")}),this._intervalInMs))}stop(){this._handle&&(globalThis.clearInterval(this._handle),this._handle=0)}dispose(){this.stop(),super.dispose()}}class Um extends xm{constructor(e){super(),this._intervalInMs=e,this._callQueue=Promise.resolve(),this._state={isRunning:!1}}start(){if(this._state.isRunning)return;const e={isRunning:!0};this._state=e;const t=async()=>{for(;e.isRunning;){const e=this._getCurrentTime();this._eventEmitter.emit("tick");const t=this._getCurrentTime()-e;t<this._intervalInMs&&await Dh(this._intervalInMs-t)}};this._callQueue=this._callQueue.then((()=>t())).catch((()=>{}))}stop(){this._state.isRunning&&(this._state.isRunning=!1)}dispose(){this._state.isRunning=!1,super.dispose()}}class Bm{static createTicker(e,t){if("interval"===e)return new Fm(t);if("timeout"===e)return new Um(t);throw new Error(`Invalid tickerType: ${e}`)}}class Vm{constructor(e,t,i,n){this._tsCall=e,this._logger=t,this._dataEventRefCount=0,this._lastFetchTime=0,this._timerDelayRatio=0,this._pendingStats=!1,this._fetchInterval=i,this._eventEmitter=new wm(this._logger,{enableLogEmit:!1});const r=1e3*i;this._ticker=Bm.createTicker(n,r),this._ticker.on("tick",(()=>{const e=Date.now();this._lastFetchTime>0&&(this._timerDelayRatio=(e-this._lastFetchTime)/r),this._lastFetchTime=e,this._dataEventRefCount>0&&!1===this._pendingStats&&(this._pendingStats=!0,this.getStats().then((e=>{e&&this._eventEmitter.emit("data",e)})).catch((e=>{this._logger.error(e)})).finally((()=>{this._pendingStats=!1})))}));const a=()=>{[10,3].includes(this._tsCall.state)?this._start():this._stop()};this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{a()})),a()}dispose(){this._callStateChangedHandle.dispose(),this._ticker.dispose()}get fetchInterval(){return this._fetchInterval}get timerDelayRatio(){return this._timerDelayRatio}_start(){this._lastFetchTime=0,this._timerDelayRatio=0,this._ticker.start()}_stop(){this._ticker.stop()}on(e,t){this._dataEventRefCount++,this._eventEmitter.on(e,t)}off(e,t){this._dataEventRefCount--,this._eventEmitter.off(e,t)}}class Hm extends Vm{constructor(e,t,i){super(e,t.createChild("MediaStatsPoller"),i.fetchInterval,i.pollingMethod)}async getStats(){return{report:this._tsCall.getMediaSessionStats(),delayRatio:this.timerDelayRatio}}}var $m;!function(e){e[e.Running=0]="Running",e[e.Paused=1]="Paused",e[e.Stopped=2]="Stopped"}($m||($m={}));class Gm{constructor(){this._sinks=[],this._transformers=[],this._state=$m.Running}_setTransformers(e){this._transformers=e.slice()}addSink(e){e.source=this,this._sinks.push(e),e.onAdded(this._state===$m.Running)}removeSink(e){e.source===this&&(g.pull(this._sinks,e),e.source=void 0,e.onRemoved())}removeAllSinks(){const e=this._sinks;this._sinks=[],e.forEach((e=>{e.source=void 0,e.onRemoved()}))}send(e){if(this._state!==$m.Running)return;let t=e;this._transformers.length&&(t=this._transformers.reduce(((e,t)=>t.transform(e)),e)),this._sinks.forEach((e=>e.onReport(t)))}pause(){this._state===$m.Running&&(this._state=$m.Paused,this._sinks.forEach((e=>e.pause())))}resume(){this._state===$m.Paused&&(this._state=$m.Running,this._sinks.forEach((e=>e.resume())))}stop(){this._state!==$m.Stopped&&this._sinks.forEach((e=>e.stop()))}}class jm extends Gm{constructor(e){super(),this._setTransformers(e)}onReport(e){if(void 0===e.report)return;const t={audio:{send:{},receive:{}},video:{send:{},receive:{}},screenShare:{send:{},receive:{}},dataChannel:{},transports:{}};t.metadata=t.metadata??{},t.metadata.delayRatio=e.delayRatio;const i=[[e.report.audio.send,t.audio.send],[e.report.audio.recv,t.audio.receive],[e.report.video.send,t.video.send],[e.report.video.recv,t.video.receive],[e.report.screenShare.send,t.screenShare.send],[e.report.screenShare.recv,t.screenShare.receive],[e.report.data,t.dataChannel],[e.report.transports,t.transports]],n=e=>{const t={};return Object.entries(e).forEach((e=>{const i=e[0],n=e[1];"altLayouts"!==i&&null!=n&&(t[i]=n)})),t};i.forEach((e=>{const t=e[0];if(void 0!==t){const i=e[1];t.forEach((e=>{const t=g.toString(e.id);i[t]=n(e),void 0!==e.altLayouts&&e.altLayouts.forEach((e=>{const r=e.id,a=n(e);a.groupId=t,i[r]=a}))}))}})),this.send(t)}}class zm extends Gm{constructor(e){super(),this._setTransformers(e)}onAdded(e){}onRemoved(){}onReport(e){this.send(e)}get source(){return this._mediaStatsSource}set source(e){this._mediaStatsSource=e}}class Wm{constructor(e){this._tsCall=e,this._activeParticipantMris=new Set,this._sourceIdToParticipantInfo=new Map,this._listenerHandles=[],this._config=yc(),this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._activeParticipantMris.has(e.id)&&this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._activeParticipantMris.delete(e.id),this._removeMapping(e)}))),this._tsCall.participants?.forEach((e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))}_updateMapping(e){const t=e.id,i=[],n=this._config.calling.composedStreamBotIds;e.endpoints?.endpointDetails?.forEach((e=>{e.mediaStreams?.forEach((r=>{i.push(r.sourceId),this._sourceIdToParticipantInfo.set(r.sourceId,{mri:t,participantId:e.participantId,isComposedStream:n.includes(t)})}))}))}_removeMapping(e){e.endpoints?.endpointDetails?.forEach((e=>{e.mediaStreams?.forEach((e=>{this._sourceIdToParticipantInfo.delete(e.sourceId)}))}))}findParticipantInfo(e){let t=this._sourceIdToParticipantInfo.get(e);if(void 0===t&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const e=this._tsCall.participants[0],i=e.endpoints?.endpointDetails[0];t={mri:e.id,participantId:i?.participantId??"",isComposedStream:!1}}return t}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._sourceIdToParticipantInfo.clear(),this._listenerHandles.forEach((e=>e.dispose()))}}class qm{constructor(e,t,i,n){this._tsCall=e,this._call=t,this._telemetryLogManager=i,this._config=n,this._participantMappingManager=new Wm(this._tsCall)}dispose(){this._participantMappingManager.dispose()}log(e){const t=this._config.telemetry.mediaStatsConfig;[{type:"audio",direction:"send",value:e.audio.send},{type:"audio",direction:"recv",value:e.audio.receive},{type:"video",direction:"send",value:e.video.send},{type:"video",direction:"recv",value:e.video.receive},{type:"screen",direction:"send",value:e.screenShare.send},{type:"screen",direction:"recv",value:e.screenShare.receive},{type:"data",direction:"",value:e.dataChannel},{type:"transport",direction:"",value:e.transports}].forEach((e=>{const i=Object.values(e.value);i.forEach((n=>{const r={id:n.id},a={id:n.id};Object.keys(n).forEach((e=>{const i=e;if("id"===e)return;if("events"===e){const e=n[i];return void(e.length>0&&(r.events=JSON.stringify(e)))}const s=n[i];if(t.dataToSend.raw){const e={};s?.timestamp&&(e.timestamp=s?.timestamp),t.dataToSend.raw&&(e.raw=s?.raw),a[i]=e}const o={};void 0!==s.aggregation?(s.timestamp&&(o.timestamp=s.timestamp),t.dataToSend.min&&(o.min=s.aggregation.min),t.dataToSend.max&&(o.max=s.aggregation.max),t.dataToSend.sum&&(o.sum=s.aggregation.sum),t.dataToSend.count&&(o.count=s.aggregation.count)):(s.timestamp&&(o.timestamp=s.timestamp),s.reduced?o.raw=s.reduced:s.raw&&(o.raw=s.raw)),r[i]=o}));let s="",o="";if(("video"===e.type||"screen"===e.type)&&"recv"===e.direction){const e=n;if(void 0!==e.streamId&&e.streamId.raw?.length){const t=e.streamId.raw[0],i=this._participantMappingManager.findParticipantInfo(t);s=i?.participantId??"",o=i?.isComposedStream?"ComposedVideoStream":"RemoteVideoStream"}}if(Object.keys(r).length>1){const t={mediaType:e.type,mediaDirection:e.direction,stats:r,callId:this._tsCall.callId,remoteParticipantId:s,localParticipantId:this._tsCall.participantId,videoStreamKind:o,streamCount:i.length,appliedFrameHeightMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.frameHeight?.max,appliedBitrateMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.bitrate?.max,appliedFrameRateMaxSentConstraint:this._call.mediaConstraintsManager.currentVideoConstraints?.send?.frameRate?.max,audioEffectsProcessorStats:this._call.audioEffectsProcessorStats??void 0};this._sendMidCallNewMediaStats(t)}if(t.dataToSend.raw&&Object.keys(a).length>1){const t={mediaType:e.type,mediaDirection:e.direction,stats:a,callId:this._tsCall.callId,remoteParticipantId:s,localParticipantId:this._tsCall.participantId,videoStreamKind:o,streamCount:i.length};this._sendMidCallRawMediaStats(t)}}))}))}_sendMidCallNewMediaStats(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_mid_call_new_media_stats,tenant:hl,properties:e})}_sendMidCallRawMediaStats(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_mid_call_raw_media_stats,tenant:hl,properties:e})}}function Km(e){return{transform:t=>([[t.audio.send,e.audio.send],[t.audio.receive,e.audio.receive],[t.video.send,e.video.send],[t.video.receive,e.video.receive],[t.screenShare.send,e.screenShare.send],[t.screenShare.receive,e.screenShare.receive],[t.dataChannel,e.dataChannel],[t.transports,e.transports]].forEach((e=>{const t=e[0],i=e[1];g.forEach(i,((e,i)=>{!0!==e.disabled&&g.forEach(t,(t=>{let n=t[e.source];void 0!==n&&(void 0!==e.multiplier&&"number"==typeof n&&(n*=e.multiplier),e.integer&&(n=g.toInteger(n)),t[i]=n)}))}))})),t)}}function Jm(e){const t=["audio.send","audio.receive","video.send","video.receive","screenShare.send","screenShare.receive","dataChannel","transports"];return{transform:i=>(g.forEach(t,(t=>{const n=g.get(i,t),r=g.get(e,t,[]);g.forEach(n,(e=>{r.forEach((t=>{"id"!==t&&delete e[t]}))}))})),i)}}const Ym={codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},frameRateInput:{aggregable:!0},frameWidthInput:{aggregable:!0},frameHeightInput:{aggregable:!0},framesEncoded:{},frameRateEncoded:{aggregable:!0},framesSent:{},frameRateSent:{aggregable:!0},frameWidthSent:{aggregable:!0},frameHeightSent:{aggregable:!0},keyFramesEncoded:{},transportId:{}},Qm={codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},streamId:{},jitterBufferDelayInMs:{aggregable:!0},frameRateDecoded:{aggregable:!0},frameRateReceived:{aggregable:!0},frameWidthReceived:{aggregable:!0},frameHeightReceived:{aggregable:!0},longestFreezeDurationInMs:{},totalFreezeDurationInMs:{},framesReceived:{},framesDropped:{},framesDecoded:{},keyFramesDecoded:{},transportId:{}},Zm={audio:{send:{codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},audioInputLevel:{aggregable:!0},transportId:{}},receive:{codecName:{},bitrate:{aggregable:!0},jitterInMs:{aggregable:!0},packets:{},packetsPerSecond:{aggregable:!0},packetsLost:{},packetsLostPerSecond:{aggregable:!0},rttInMs:{aggregable:!0},jitterBufferDelayInMs:{aggregable:!0},audioOutputLevel:{aggregable:!0},healedRatio:{aggregable:!0},transportId:{}}},video:{send:Ym,receive:Qm},screenShare:{send:Ym,receive:Qm},dataChannel:{incomingBitrate:{aggregable:!0},outgoingBitrate:{aggregable:!0},messagesSentPerSecond:{aggregable:!0},messagesReceivedPerSecond:{aggregable:!0}},transports:{rttInMs:{aggregable:!0},availableIncomingBitrate:{aggregable:!0},availableOutgoingBitrate:{aggregable:!0}}},Xm={codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},framesEncoded:{raw_data_reduction:!0},framesSent:{raw_data_reduction:!0},keyFramesEncoded:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0},groupId:{raw_data_reduction:!0}},ef={codecName:{raw_data_reduction:!0},streamId:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},jitterBufferDelayInMs:{output_key:"jitterBufferInMs"},longestFreezeDurationInMs:{skip:!0},totalFreezeDurationInMs:{raw_data_reduction:!0},framesReceived:{raw_data_reduction:!0},framesDropped:{raw_data_reduction:!0},framesDecoded:{raw_data_reduction:!0},keyFramesDecoded:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}},tf={audio:{send:{codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}},receive:{codecName:{raw_data_reduction:!0},packets:{raw_data_reduction:!0},packetsLost:{raw_data_reduction:!0},jitterBufferDelayInMs:{output_key:"jitterBufferInMs"},pairRttInMs:{aggregable:!0},availableBitrate:{aggregable:!0},transportId:{skip:!0}}},video:{send:Xm,receive:ef},screenShare:{send:Xm,receive:ef},dataChannel:{state:{raw_data_reduction:!0},dataChannelIdentifier:{raw_data_reduction:!0},messagesSent:{raw_data_reduction:!0},bytesSent:{raw_data_reduction:!0},messagesReceived:{raw_data_reduction:!0},bytesReceived:{raw_data_reduction:!0}},transports:{candidateType:{events:!0},relayProtocol:{events:!0}}},nf={multiplier:1e3,integer:!0,source:"jitter"},rf={multiplier:1e3,integer:!0,source:"rtt"},af={integer:!0,source:"jitterBufferMs"},sf={jitterInMs:nf,rttInMs:rf},of={jitterInMs:nf,rttInMs:rf,jitterBufferDelayInMs:af,streamId:{source:"msi"},longestFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"longestFreezeDuration"},totalFreezeDurationInMs:{multiplier:1e3,integer:!0,source:"totalFreezeDuration"}},lf={audio:{send:{jitterInMs:nf,rttInMs:rf,audioInputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}},receive:{jitterInMs:nf,rttInMs:rf,jitterBufferDelayInMs:af,audioOutputLevel:{multiplier:65536,integer:!0,source:"audioLevel"}}},video:{send:sf,receive:of},screenShare:{send:sf,receive:of},dataChannel:{incomingBitrate:{source:"recvBitrate"},outgoingBitrate:{source:"sendBitrate"}},transports:{rttInMs:rf}};class cf{constructor(e,t,i,n){this._tsCall=e,this._call=t,this._logger=i,this._disposed=!1;const r=yc();this._config=r.mediaStats,this._statsPoller=new Hm(this._tsCall,this._logger,this._config);const a=[Km(g.merge(g.cloneDeep(lf),this._config.transformMetrics))];this._config.timerThrottlingFilter.enabled&&a.push(function(e,t){return{transform:i=>{const n=i.metadata?.delayRatio,r=e>0&&void 0!==n&&n>e;return g.forEach(t,((e,t)=>{const n=g.get(i,t);g.forEach(n,(t=>{g.forEach(e,((e,i)=>{if(r)delete t[i];else{const n=t[i];(void 0!==e.max&&n>e.max||void 0!==e.min&&n<e.min||g.isNaN(n))&&delete t[i]}}))}))})),i}}}(this._config.timerThrottlingFilter.delayRatio,this._config.timerThrottlingFilter.filterRange)),this._mediaStatsSourceNode=new jm(a);const s=[3,10];this._isCallActive=s.includes(this._tsCall.state),this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{const e=s.includes(this._tsCall.state);this._isCallActive!==e&&(this._isCallActive=e,e?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause())}));const o=this._config.blockMetrics;if(Object.keys(o).length>0){const e=new zm([{transform:e=>g.cloneDeep(e)},Jm(o)]);this._mediaStatsSourceNode.addSink(e),this._collectorsSourceNode=e}else this._collectorsSourceNode=this._mediaStatsSourceNode;const l=r.telemetry.mediaStatsConfig;if(l.enabled){const e=new qm(this._tsCall,this._call,n,r),t=g.merge(g.cloneDeep(Zm),tf,l.metricsProperties),i=new Om(this._logger,{aggregationInterval:l.aggregationInterval,dataPointsPerAggregation:l.dataPointsPerAggregation,metricsPropertics:t});i.on("data",(t=>e.log(t))),this._mediaStatsSourceNode.addSink(i)}this._isCallActive?this._mediaStatsSourceNode.resume():this._mediaStatsSourceNode.pause(),this._dataEventListener=e=>{this._mediaStatsSourceNode.onReport(e)},this._statsPoller.on("data",this._dataEventListener)}createCollector(e){if(this._disposed)throw new b({defaultError:f.FEATURES.MEDIA_STATS.DISPOSED});const t=this._config,i=new Lm(this._logger,{aggregationInterval:e?.aggregationInterval??t.aggregationInterval,dataPointsPerAggregation:e?.dataPointsPerAggregation??t.dataPointsPerAggregation,metricsPropertics:Zm});return this._collectorsSourceNode.addSink(i),i}dispose(){this._disposed||(this._disposed=!0,this._statsPoller.off("data",this._dataEventListener),this._mediaStatsSourceNode.stop(),this._callStateChangedHandle.dispose())}}class df extends hg{constructor(e){super(e)}get name(){return this._sendFeatureUsage("name",Yh.getter),"MediaStats"}createCollector(e){this._sendFeatureUsage("createCollector",Yh.attempt);const t=this._statsManager.createCollector(e);return this._sendFeatureUsage("creaetCollector",Yh.success),t}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._statsManager=new cf(e.tsCall,this._call,this._logger,this._telemetryLogManager),this._sendFeatureUsage("initialize",Yh.initialize)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"MediaStats",featureType:"Call",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._statsManager.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}var uf,hf;(uf=e.RecordingState||(e.RecordingState={}))[uf.None=0]="None",uf[uf.Started=1]="Started",uf[uf.Paused=2]="Paused",uf[uf.Ended=3]="Ended";class pf{constructor(e){this._eventEmitter=e,this._recordingBots=new Map,this._recordingBotChangedSubs=new WeakMap,this._recordingInitiatorMap=new Map,this._isRecordingActive=!1,this._updateIsCallRecorded=e=>this._isRecordingActive!==e&&(this._isRecordingActive=e,this._logger.info(`Updating isCallRecorded to ${e}`),!0),this._handleRecordingBotAdded=e=>{const t=()=>{let t,i=!1,n=!1;if(this._hasRecordingState(e)){if(this._recordingBots.has(e.id)){let i=this._getRecordingBotEndpoint(e);if(t=this._recordingBots.get(e.id),i&&t){t.endpoint=i;let e=i.userId?this._recordingInitiatorMap.get(i.userId):void 0;n=t.recordingInfo?.update(i,e)??!1}}else t=this._getRecordingBotInfo(e),t&&(this._logger.info("Adding recording bot"),this._recordingBots.set(e.id,t),i=!0);this._sendEvents(n?[t]:void 0,i?[t]:void 0,void 0,this._updateIsCallRecorded(this._isRecordingEnabled()))}};t(),this._recordingBotChangedSubs.set(e,e.changed(t))},this._handleRecordingBotRemoved=e=>{let t=this._recordingBots.get(e.id);this._recordingBots.delete(e.id),this._recordingBotChangedSubs.get(e)?.dispose(),this._recordingBotChangedSubs.delete(e),this._logger.info(`Updating recordingState to ${t?.endpoint?.state}`),t?.recordingInfo?.dispose(),this._sendEvents([t],void 0,[t],this._updateIsCallRecorded(this._isRecordingEnabled()))},this._sendEvents=(e,t,i,n)=>{e&&e.forEach((e=>e?.recordingInfo?.sendRecordingStateChanged()));let r=!!t&&t.length>0,a=!!i&&i.length>0;(r||a)&&this._eventEmitter.emit("recordingsUpdated",{added:this._getRecordingInfos(t),removed:this._getRecordingInfos(i)}),n&&this._eventEmitter.emit("isRecordingActiveChanged")},this._hasRecordingState=e=>e?.endpoints?.endpointDetails?.some((e=>!!e?.endpointMetadata?.__platform?.recording?.compliance?.state||!!e?.endpointMetadata?.processingModes?.recording?.state))??!1,this._getRecordingInfos=e=>{if(e)return e.map((e=>e?.recordingInfo)).filter((e=>!!e))},this._isRecordingEnabled=()=>{let e=!1;try{this._recordingBots.forEach((t=>{e||(e="Active"===t?.endpoint?.state)}))}catch(e){this._logger.info("Unable to read recording state: ",e)}return e},this._getRecordingInfoImpl=e=>{if(null==e)return;if("Active"!==e.state&&"Inactive"!==e.state)return;let t;return void 0!==e.userId&&(t=this._recordingInitiatorMap.get(e.userId)),new gf(e.state,this._eventEmitter,t)},this._getRecordingBotInfo=e=>{let t=this._getRecordingBotEndpoint(e);return t?{endpoint:t,recordingInfo:this._getRecordingInfoImpl(t)}:void 0},this._getRecordingBotEndpoint=e=>{let t=e.endpoints?.endpointDetails.map((e=>{let t=e?.endpointMetadata?.__platform?.recording?.compliance?.state,i=e?.endpointMetadata?.__platform?.recording?.compliance?.userId,n=e?.endpointMetadata?.processingModes?.recording?.state,r=e?.endpointMetadata?.processingModes?.recording?.userId;if(t||n)return{state:t??n,userId:i??r}})).filter((e=>null!=e));if(t&&0!=t.length)return t.length>1&&this._logger.log(`Unexpected: multiple recording endpoints: ${t?.map((e=>e?.state??"undefined")).join(", ")}`),t[0]}}get isRecordingActive(){return this._isRecordingActive}get recordings(){return Array.from(this._recordingBots.values()).map((e=>e?.recordingInfo)).filter((e=>!!e))}initialize(e,t,i){this._logger=i.createChild((()=>`RecordingFeature::Call(id='${e.callId}', state='${e.state}')`)),e.on("callStateChanged",(async()=>{3===e.state&&this._initInitiatorMap(e)})),e.on("participantAdded",(async e=>{sc(e.id)?this._handleRecordingBotAdded(e):void 0===e||this._recordingInitiatorMap.has(e.id)||this._recordingInitiatorMap.set(e.id,e.displayName)})),e.on("participantRemoved",(async e=>{sc(e.id)?this._handleRecordingBotRemoved(e):void 0!==e&&this._recordingInitiatorMap.has(e.id)&&this._recordingInitiatorMap.delete(e.id)})),e.on("participantUpdated",(async e=>{void 0!==e&&this._recordingInitiatorMap.has(e.id)&&this._recordingInitiatorMap.set(e.id,e.displayName)}))}dispose(){let e=this._updateIsCallRecorded(!1),t=Array.from(this._recordingBots.values());t.forEach((e=>e?.recordingInfo?.dispose())),this._sendEvents(void 0,void 0,t,e)}_initInitiatorMap(e){const{participants:t}=e;[...t].forEach((e=>{sc(e.id)||this._recordingInitiatorMap.set(e.id,e.displayName)}))}}class gf{constructor(e,t,i){this.state=this.getRecordingState(e),this._eventEmitter=t,this.displayName=i}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}update(e,t){if(null==e)return!1;let i=this.getRecordingState(e.state);return i!=this.state&&(this.state=i,void 0!==t&&(this.displayName=t),!0)}dispose(){this.state=e.RecordingState.Ended}sendRecordingStateChanged(){this._eventEmitter.emit("recordingStateChanged")}getRecordingState(t){let i=e.RecordingState.None;switch(t?.toLocaleLowerCase()){case"active":i=e.RecordingState.Started;break;case"inactive":i=e.RecordingState.Paused;break;default:i=e.RecordingState.None}return i}}(hf=e.LocalRecordingState||(e.LocalRecordingState={}))[hf.None=0]="None",hf[hf.Started=1]="Started",hf[hf.Ended=2]="Ended";const mf="active",ff="inactive";class vf{constructor(e){this._eventEmitter=e,this._localRecordingInitiators=new Map,this._sendEvents=(e,t,i)=>{let n=!!e&&e.length>0,r=!!t&&t.length>0;(n||r)&&this._eventEmitter.emit("localRecordingsUpdated",{added:e,removed:t}),i&&this._eventEmitter.emit("isLocalRecordingActiveChanged")},this._isEnabled=yc().calling.localRecording.enabled,this._supportedConversationTypes=yc().calling.localRecording.supportedConversationTypes}get isRecordingActive(){return this._localRecordingInitiators.size>0}get recordings(){return Array.from(this._localRecordingInitiators.values())}initialize(e,t,i){if(this._logger=i.createChild((()=>`LocalRecordingFeature::Call(id='${e.callId}', state='${e.state}')`)),!this._isEnabled){const e="Local Recording feature is is disabled",t=new b({defaultError:f.FEATURES.LOCAL_RECORDING.DISABLED});throw this._logger.error(e),t}e.on("callStateChanged",(async()=>{if(3===e.state){if(!this._supportedConversationTypes.includes(e.conversationType)){const e="Local Recording feature is only available in meetings",t=new b({defaultError:f.FEATURES.LOCAL_RECORDING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(e),t}this.initLocalRecordingStatus(e)}})),e.on("participantUpdated",(t=>this._onParticipantUpdatedEvent(e,t,t.endpoints?.endpointDetails)))}dispose(){let e=this._localRecordingInitiators.size>0,t=Array.from(this._localRecordingInitiators.values());t.forEach((e=>e?.dispose())),e&&(e=0==this._localRecordingInitiators.size),this._sendEvents(void 0,t,e)}hasOngoingLocalRecording(e){return e?.some((e=>(e.propertyBag?.localRecording?.value?.state||"")===mf))||!1}initLocalRecordingStatus(e){const{participants:t}=e,i=[...t];this._localRecordingInitiators=new Map(i.filter((e=>this.hasOngoingLocalRecording(e.endpoints?.endpointDetails))).map((e=>[e.id,this._getLocalRecordingInfo(e)])))}_onParticipantUpdatedEvent(e,t,i){t?sc(t.id)||(this.hasOngoingLocalRecording(i)?this._tryAddLocalRecordingInitiator(e,t):this._tryRemoveLocalRecordingInitiator(e,t)):this._logger.error(`Empty participant, skip update event processing. CallId: ${e.callId}`)}_tryAddLocalRecordingInitiator(e,t){const{callId:i}=e;if(!this._localRecordingInitiators.has(t.id)){this._logger.info(`Add local recording participant: ${t.id}, callId: ${i}`);let e=this._getLocalRecordingInfo(t);this._localRecordingInitiators.set(t.id,e),this._sendEvents([e],void 0,1==this._localRecordingInitiators.size)}}_tryRemoveLocalRecordingInitiator(e,t){const{callId:i}=e;if(this._localRecordingInitiators.has(t.id)){this._logger.info(`Remove local recording participant: ${t.id}, callId: ${i}`);let e=this._localRecordingInitiators.get(t.id);e.update(ff),this._localRecordingInitiators.delete(t.id),this._sendEvents(void 0,[e],0==this._localRecordingInitiators.size)}}_getLocalRecordingInfo(e){let t=e.displayName;return new Sf(mf,t)}}class Sf{constructor(e,t){this.state=this.getRecordingState(e),this.displayName=t}update(e){let t=this.getRecordingState(e);return t!=this.state&&(this.state=t,!0)}dispose(){this.state=e.LocalRecordingState.Ended}getRecordingState(t){let i=e.LocalRecordingState.None;switch(t?.toLocaleLowerCase()){case"active":i=e.LocalRecordingState.Started;break;case"inactive":i=e.LocalRecordingState.Ended;break;default:i=e.LocalRecordingState.None}return i}}class yf{constructor(e){this._eventEmitter=e,this._botChangedSubs=new Map,this._isTranscriptionActive=!1,this._updateIsTranscriptionActive=e=>{this._isTranscriptionActive!==e&&(this._isTranscriptionActive=e,this._logger.info(`Updating isTranscriptionActive to ${e}`),this._eventEmitter.emit("isTranscriptionActiveChanged"))},this._isCallingApplication=e=>sc(e.id),this._handleBotRemoved=e=>{this._botChangedSubs.get(e)?.dispose(),this._botChangedSubs.delete(e),this._checkIfAbotIsTranscribing()},this._handleBotAdded=e=>{this._botChangedSubs.set(e,e.changed(this._checkIfAbotIsTranscribing)),this._checkIfAbotIsTranscribing()},this._checkIfAbotIsTranscribing=()=>{try{Array.from(this._botChangedSubs.keys()).find((e=>e.endpoints?.endpointDetails?.find((e=>"Active"===e?.endpointMetadata?.processingModes?.realTimeTranscript?.state))))?this._updateIsTranscriptionActive(!0):this._updateIsTranscriptionActive(!1)}catch(e){this._logger.warn("Unable to read transcription state: ",e)}}}get isTranscriptionActive(){return this._isTranscriptionActive}initialize(e,t,i){this._logger=i.createChild((()=>`TranscriptionFeature::Call(id='${e.callId}', state='${e.state}')`)),e.on("participantAdded",(e=>{this._isCallingApplication(e)&&this._handleBotAdded(e)})),e.participants.forEach((e=>{this._isCallingApplication(e)&&this._handleBotAdded(e)})),e.on("participantRemoved",(e=>{this._isCallingApplication(e)&&this._handleBotRemoved(e)}))}dispose(){this._updateIsTranscriptionActive(!1),this._botChangedSubs.forEach(((e,t)=>e.dispose())),this._botChangedSubs.clear()}}class Cf{get state(){return this._state}get error(){return this._error}constructor(e,t,i=!0){return this._eventEmitter=new Kp.EventEmitter,this._lastTsTransferState=0,this._getTransferEndReason=(e,t=0)=>{let i=t,n=0,r=e||"Unknown";this._tsCall&&(i=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo.callControllerCode||t,n=this._tsCall.transferDiagnosticsInfo&&this._tsCall.transferDiagnosticsInfo?.callControllerSubCode||0,r=Rg(this._tsCall.terminatedReason));const a={code:i,subCode:n};return this._logger[0===i?"info":"error"](`Transfer end reason=${r}, code=${i}, subCode=${n}`),a},this._state="None",this._logger=t.createChild((()=>"Transfer")),this._logger.log("created"),this._tsCall=e,i?4!==e.state?(this._logger.error("Transfer end reason= call must be on hold before transfer"),this._error={code:y},void this.setTransferState(4)):(this._lastTsTransferState=this._tsCall.transferState,this.setTransferState(this._tsCall.transferState),void this._tsCall.changed((()=>{this._tsCall.transferState!==this._lastTsTransferState&&(this._logger.log(`tsCall transfer state changed=${this._tsCall.transferState}`),this._lastTsTransferState=this._tsCall.transferState,this.setTransferState(this._tsCall.transferState))}))):(this._logger.error("Transfer end reason= call was not found with this callId"),this._error={code:y},void this.setTransferState(4))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}setTransferState(e){let t,i;const n={0:"None",1:"Transferring",2:"Transferring",3:"Transferred",4:"Failed"};n[e]?(t=n[e],"Failed"===t&&(i=this._getTransferEndReason(),this._error=i),this._logger.log(`Mapped ts transfer state:[${e}] to [${t}]`),this._setTransferState(t)):this._logger.warn(`unable to map tsCall state=[${e}] to transfer state`)}_setTransferState(e){e!==this._state&&(this._logger.log(`transfer state changed [${this._state}]=>[${this.state}]`),this._state=e,this._eventEmitter.emit("stateChanged"))}}var _f=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Ef{constructor(e){this._eventEmitter=e,this._autoAccept=yc().calling.transfer.autoAccept}initialize(e,t,i,n){this._logger=n.createChild((()=>`TransferFeature::Call(id='${e.callId}', state='${e.state}')`)),this._telemetryLogManager=i,this._tsCall=e,this._callAgent=t,e.on("transferRequested",(e=>{const t=this.getTransferRequestPayload(e);if(this._autoAccept){const e=t.accept();this._eventEmitter.emit("transferAccepted",{targetCall:e})}}))}transfer(e,t){let i="safe";if(e.targetCallId&&(i="consultative"),this._sendFeatureUsage(i,Yh.attempt),!this.isTransferable(this._tsCall))throw this._sendFeatureUsage(i,Yh.failure),new b({defaultError:f.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});try{let n;switch(i){case"safe":return n=this.transferToParticipant(e.targetParticipant,t),this._sendFeatureUsage(i,Yh.success),n;case"consultative":return n=this.transferToCall(e.targetCallId,t),this._sendFeatureUsage(i,Yh.success),n}}catch(e){if(this._sendFeatureUsage(i,Yh.failure),e instanceof b)throw e}throw this._sendFeatureUsage(i,Yh.failure),new b({defaultError:f.FEATURES.TRANSFER.TARGET_NOT_RECOGNIZED})}getTransferRequestPayload(e){const t=ac(e.transferContext.targetMri);if("communicationUser"===t.kind||"phoneNumber"===t.kind||"microsoftTeamsUser"===t.kind||"unknown"===t.kind||"microsoftTeamsApp"===t.kind){let t=!1;const i={accept:()=>{let i;try{if(i=this._callAgent.createTransferTargetCall(e.transferContext),t)return this._logger.info("Transfer accept was called when transfer action is already in progress."),i;t=!0;const n={threadId:"",messageId:void 0,transferContext:e.transferContext,mediaPeerType:0};i.startCallInternal(void 0,!1,void 0,n).catch((i=>{t=!1,e.onCompleted(7),this._logger.error("Transfer to target failed at call start")}));const r=()=>{if(t)switch(i.state){case"Connected":t=!1,e.onCompleted(1),this._logger.info("Transfer Completed"),i.off("stateChanged",(()=>{}));break;case"Disconnected":t=!1,e.onCompleted(7),this._logger.info(`Transfer call disconnected. \n                                            code = ${i.callEndReason?.code} \n                                            subcode = ${i.callEndReason?.subCode} \n                                            message = ${i.callEndReason?.message} \n                                            result categories = ${i.callEndReason?.resultCategories}`),i.off("stateChanged",(()=>{}))}};return i.on("stateChanged",r),i}catch(i){throw t=!1,e.onCompleted(7),this._logger.error("Transfer to target failed at call create"),new b({defaultError:f.FEATURES.TRANSFER.TRANSFER_TO_TARGET_FAILED,originalError:i})}}};return i}throw new b({defaultError:f.FEATURES.TRANSFER.INVALID_TARGET_TYPE,defaultErrorMessageArgs:[t]})}isTransferable(e){return 1===e.callType||e.participants.filter((e=>!sc(e.id))).length<=2}transferToParticipant(e,t){let i=rc(e);return 4===this._tsCall.state&&this._tsCall.callSafeTransfer(i,void 0,t),new Cf(this._tsCall,this._logger)}transferToCall(e,t){const i=this._callAgent.getCallByCallId(e);if(i&&!this.isTransferable(i))throw new b({defaultError:f.FEATURES.TRANSFER.UNSUPPORTED_CALL_TYPE});return i&&4===this._tsCall.state&&this._tsCall.callConsultativeTransfer(i,void 0,void 0,t),new Cf(this._tsCall,this._logger,!!i)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([P(Qp.Transfer),_f("design:type",Function),_f("design:paramtypes",[Object,Object]),_f("design:returntype",Object)],Ef.prototype,"transfer",null);class Tf{constructor(e,t,i,n){this._name=e,this._id=t,this._deviceType=i,this._deviceManager=n}get name(){return this._name}setName(e){this._name=e}get id(){return this._id}setId(e){this._id=e}get deviceType(){return this._deviceType}setDeviceType(e){this._deviceType=e}get deviceManager(){return this._deviceManager}}function bf(e,t){Reflect.defineMetadata(I,t,e)}function If(e){if(this._capacity=Rf(e),this._length=0,this._front=0,wf(e)){for(var t=e.length,i=0;i<t;++i)this[i]=e[i];this._length=t}}If.prototype.toArray=function(){for(var e=this._length,t=new Array(e),i=this._front,n=this._capacity,r=0;r<e;++r)t[r]=this[i+r&n-1];return t},If.prototype.push=function(e){var t=arguments.length,i=this._length;if(t>1){var n=this._capacity;if(i+t>n){for(var r=0;r<t;++r)this._checkCapacity(i+1),this[a=this._front+i&this._capacity-1]=arguments[r],i++,this._length=i;return i}var a=this._front;for(r=0;r<t;++r)this[a+i&n-1]=arguments[r],a++;return this._length=i+t,i+t}return 0===t?i:(this._checkCapacity(i+1),this[r=this._front+i&this._capacity-1]=e,this._length=i+1,i+1)},If.prototype.pop=function(){var e=this._length;if(0!==e){var t=this._front+e-1&this._capacity-1,i=this[t];return this[t]=void 0,this._length=e-1,i}},If.prototype.shift=function(){var e=this._length;if(0!==e){var t=this._front,i=this[t];return this[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,i}},If.prototype.unshift=function(e){var t=this._length,i=arguments.length;if(i>1){if(t+i>(r=this._capacity)){for(var n=i-1;n>=0;n--){this._checkCapacity(t+1);var r=this._capacity;this[s=(this._front-1&r-1^r)-r]=arguments[n],t++,this._length=t,this._front=s}return t}var a=this._front;for(n=i-1;n>=0;n--){var s;this[s=(a-1&r-1^r)-r]=arguments[n],a=s}return this._front=a,this._length=t+i,t+i}return 0===i?t:(this._checkCapacity(t+1),r=this._capacity,this[n=(this._front-1&r-1^r)-r]=e,this._length=t+1,this._front=n,t+1)},If.prototype.peekBack=function(){var e=this._length;if(0!==e)return this[this._front+e-1&this._capacity-1]},If.prototype.peekFront=function(){if(0!==this._length)return this[this._front]},If.prototype.get=function(e){var t=e;if(t===(0|t)){var i=this._length;if(t<0&&(t+=i),!(t<0||t>=i))return this[this._front+t&this._capacity-1]}},If.prototype.isEmpty=function(){return 0===this._length},If.prototype.clear=function(){for(var e=this._length,t=this._front,i=this._capacity,n=0;n<e;++n)this[t+n&i-1]=void 0;this._length=0,this._front=0},If.prototype.toString=function(){return this.toArray().toString()},If.prototype.valueOf=If.prototype.toString,If.prototype.removeFront=If.prototype.shift,If.prototype.removeBack=If.prototype.pop,If.prototype.insertFront=If.prototype.unshift,If.prototype.insertBack=If.prototype.push,If.prototype.enqueue=If.prototype.push,If.prototype.dequeue=If.prototype.shift,If.prototype.toJSON=If.prototype.toArray,Object.defineProperty(If.prototype,"length",{get:function(){return this._length},set:function(){throw new RangeError("")}}),If.prototype._checkCapacity=function(e){this._capacity<e&&this._resizeTo(Rf(1.5*this._capacity+16))},If.prototype._resizeTo=function(e){var t=this._capacity;this._capacity=e;var i=this._front,n=this._length;i+n>t&&function(e,t,i,n,r){for(var a=0;a<r;++a)i[a+n]=e[a+t],e[a+t]=void 0}(this,0,this,t,i+n&t-1)};var wf=Array.isArray;function Rf(e){if("number"!=typeof e){if(!wf(e))return 16;e=e.length}return function(e){return e>>>=0,e-=1,e|=e>>1,e|=e>>2,e|=e>>4,1+((e|=e>>8)|e>>16)}(Math.min(Math.max(16,e),1073741824))}var Af=If;class Pf{static overrideDefaultLogDump(){if(Pf.logDump.isEmpty())Pf.logDump=new Af(yc()?.debugInfo?.maxLogDumpLength);else{let e=new Af(yc()?.debugInfo?.maxLogDumpLength);for(;Pf.logDump.length>0;){const t=Pf.logDump.shift();t&&e.push(t)}Pf.logDump=e}}constructor(e,t=[],i=Pf.defaultLogRedirect){this._azureLogger=e,this._namespace=t,this._logRedirectCallback=i}createChild(e){return new Pf(this._azureLogger,[...this._namespace,"string"==typeof e?()=>e:e])}createFnLogger(e,t,...i){return this.createChild(this.getPrefix(e,t)+i.join(""))}log(...e){const t=this.getMessage(e);this._azureLogger.verbose(t),this._logRedirectCallback(`log:${t}`)}debug(...e){const t=this.getMessage(e);this._azureLogger.verbose(t),this._logRedirectCallback(`debug:${t}`)}info(...e){const t=this.getMessage(e);this._azureLogger.info(t),this._logRedirectCallback(`info:${t}`)}warn(...e){const t=this.getMessage(e);this._azureLogger.warning(t),this._logRedirectCallback(`warn:${t}`)}error(...e){const t=this.getMessage(e);this._azureLogger.error(this.getMessage(e)),this._logRedirectCallback(`error::${t}`)}getMessage(...e){return`${(new Date).toISOString()} ${this.getNamespace()} ${e.join(" ")}`}getNamespace(){return this._namespace.map((e=>e())).join(":")}getPrefix(e,t){let i="";return t&&(i+=t),e&&(i+=e),i}redirectLog(e){this._logRedirectCallback=t=>{Pf.defaultLogRedirect(t),e(t)}}dumpAllLogs(){return[...Pf.logDump.toArray()]}}Pf.logDump=new Af(500),Pf.defaultLogRedirect=e=>{if(yc()?.debugInfo?.enableLogDump){const t=()=>{Pf.logDump.length>yc()?.debugInfo?.maxLogDumpLength&&Pf.logDump.shift()};if(yc()?.debugInfo?.includeList.some((t=>g.includes(e,t))))return Pf.logDump.push(e),void t();if(!yc()?.debugInfo?.excludeList.some((t=>g.includes(e,t))))return Pf.logDump.push(e),void t()}};class Mf{constructor(e){this._telemetryLogManager=e}sendMediaStreamEvent(e){this._telemetryLogManager?.sendEvent({name:Jh.acs_calling_media_stream,tenant:hl,properties:{correlationId:e.correlationId,mediaType:e.mediaType,operation:e.operation,timestampInfo:e.timestampInfo,streamType:e.streamType||Lp.Local,additionalDetails:e.additionalDetails||"",kindOfEvent:e.kindOfEvent||"",callId:e.callId||"",localPaticipantId:e.localParticipantId||""}})}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([bf,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type",Object)],Mf.prototype,"logger",void 0);var kf,Df=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Of=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Nf{constructor(e){if(this._disposed=!1,this._call=new Set,this._canStartEffects=!1,this.kind="LocalVideoStream",this._renderers=[],this._disposeRenderer=e=>{this.logger.log("disposing renderer");try{e.dispose(),this.logger.log("renderer disposed")}catch(e){this.logger.log("failed to dispose renderer")}},!(e instanceof Tf||e instanceof MediaStream))throw new b({defaultError:f.LOCAL_VIDEO_STREAM.WRONG_STREAM_TYPE});const i=t.createClientLogger("ACS-calling");this.logger=new Pf(i,[()=>`LocalVideoStream:${e.id}`]),this.logger.info("created"),this._eventEmitter=new wm(this.logger),this.setSource(e,!0),this._localStreamTelemetryEventSender=new Mf(this._telemetryLogManager)}on(e,t){if("videoSourceChanged"!==e)throw new b({defaultError:f.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("videoSourceChanged"!==e)throw new b({defaultError:f.LOCAL_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get source(){return this._source}get mediaStreamType(){return this._mediaStreamType}get telemetryLogManager(){return this._telemetryLogManager}get callStackWebCVProvider(){return this.source?.deviceManager?.callStackWebCvProvider??null}get callStackEffectsStatusManager(){return this.source?.deviceManager?.callStackVideoEffectsStatusManager??null}get canStartEffects(){return this._canStartEffects}async switchSource(e){this.logger.createFnLogger(_p.SwitchSource);const t=+new Date,i=x(),n={timestampInfo:{attemptTimestamp:t},correlationId:i,operation:xp.switchSource,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",kindOfEvent:Yh.attempt,mediaType:Np.Video,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),!(e instanceof Tf)){const e=new b({defaultError:f.LOCAL_VIDEO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.switchSource,additionalDetails:{failureReason:e.message,code:C,...xg(e)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,mediaType:Np.Video,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}if(this._source===e){const e=new b({defaultError:f.LOCAL_VIDEO_STREAM.SWITCH_SAME_SOURCE}),n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.switchSource,additionalDetails:{failureReason:e.message,code:e.code,...xg(e)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,mediaType:Np.Video,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}try{"RawMedia"===this._mediaStreamType&&Array.from(this._call.values()).some((e=>e.localVideoStream===this))&&e.deviceManager.getTsDeviceManager().unsetRawMediaStream?.(1),e.deviceManager.getTsDeviceManager().selectDevices({camera:e.id}),this.setSource(e);const n={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:Np.Video,operation:xp.switchSource,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n)}catch(e){const n=Ng(0,e),r={correlationId:i,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.switchSource,additionalDetails:{failureReason:n.message,code:C,...xg(n)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,mediaType:Np.Video,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}dispose(){this.logger.log("Disposing LocalVideoStream."),this._disposed?this.logger.log("already disposed"):(this.disposeRawStream(),this._renderers.forEach((e=>this._disposeRenderer(e))),this._renderers=[],this._disposed=!0)}async getMediaStream(){const e=x();let t=+new Date;const i={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",timestampInfo:{attemptTimestamp:t},operation:xp.getMediaStream,kindOfEvent:Yh.attempt,mediaType:Np.VideoRaw,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const i={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:Np.VideoRaw,operation:xp.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),new MediaStream(this._mediaStreamSource.clone())}try{let i;if("ScreenSharing"===this._source.deviceType?i=2:"UsbCamera"!==this._source.deviceType&&"CaptureAdapter"!==this._source.deviceType&&"Virtual"!==this._source.deviceType||(i=1),!i)throw new b({defaultError:f.LOCAL_VIDEO_STREAM.CANT_GET_DEVICE_TYPE});this._rawStream||(this._rawStream=this.source.deviceManager.getRawDeviceMediaStream(i));const n={correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",mediaType:Np.VideoRaw,operation:xp.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n);const r=await(this._rawStream?.getMediaStream());return new MediaStream(r.clone())}catch(i){let n;n="ScreenSharing"===this._source.deviceType?new b({defaultError:f.CALL.SS_RAW_STREAM_GET,originalError:i}):new b({defaultError:f.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:i});const r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.getMediaStream,additionalDetails:{failureReason:n.message,code:n.code,...xg(n)},kindOfEvent:Yh.failure,mediaType:Np.VideoRaw,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}async setMediaStream(e){const t=x();let i,n=+new Date,r=!1,a=!1,s=Np.VideoRawOrScreenSharingRaw;for(let e of this._call){const t=e;if(t.localScreenSharingStream===this||t.localVideoStream===this){i=t.deviceManager,a=!0,t.localVideoStream===this?(r=!0,s=Np.VideoRaw):t.localScreenSharingStream===this&&(r=!1,s=Np.ScreenSharingRaw);break}}const o={timestampInfo:{attemptTimestamp:n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.setMediaStream,kindOfEvent:Yh.attempt,mediaType:s,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(o),!(e instanceof MediaStream)){const e=new b({defaultError:f.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),i={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.setMediaStream,additionalDetails:{failureReason:e.message,code:e.code,...xg(e)},kindOfEvent:Yh.failure,mediaType:s,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),e}if(this.setSource(e),yc()?.calling?.allowAccessRawMediaStream)try{if(a){const t=i?.getTsDeviceManager();if(!t?.setRawMediaStream)throw new b({defaultError:f.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM_UNDEFINED_FUNC});r?t.setRawMediaStream(e,1):t.setRawMediaStream(e,2)}this._renderers.forEach((t=>{t.setSourceObject(e)}));const o={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.setMediaStream,kindOfEvent:Yh.success,mediaType:s,streamType:Lp.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(o)}catch(e){const i=new b({defaultError:f.LOCAL_VIDEO_STREAM.SET_MEDIA_STREAM,originalError:e}),r={correlationId:t,callId:this.getCall()?.id||"",localParticipantId:this.getLocalParticipantId()||"",operation:xp.setMediaStream,additionalDetails:{failureReason:i.message,code:i.code,...xg(i)},timestampInfo:{deltaTimeInMs:+new Date-n},kindOfEvent:Yh.failure,mediaType:s,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),i}}addCall(e){this._call.add(e)}removeCall(e){this._call.delete(e)}feature(e){return this._extensibleApi||(this._extensibleApi=new vg(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(e.videoStreamApiCtor)}registerRenderer(e){this._renderers.push(e)}unregisterRenderer(e){const t=this._renderers.indexOf(e);-1!==t&&this._renderers.splice(t,1)}getStreamMetadata(){let e,t,i=this.getCall();this._source instanceof Tf?(e=this.source.deviceManager,t=this.source.deviceType):this._mediaStreamSource instanceof MediaStream&&i&&(e=i.deviceManager);let n=-1;return i&&("Video"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&i.localVideoStream===this?n=i.tsCall.mediaStreams[0][0]?.id||-1:("ScreenSharing"===this._mediaStreamType||"RawMedia"===this.mediaStreamType&&i.localScreenSharingStream===this)&&(n=i.tsCall.mediaStreams[1][0]?.id||-1)),{source:"local",sourceId:n,streamType:this.mediaStreamType,deviceType:t||"",callId:i?.id||"",localParticipantId:i?.tsCall.participantId||"",deviceManagerPermissionState:e?JSON.stringify({cameraPermission:e.getVideoDevicePermission(),microphonePermission:e.getAudioDevicePermission()}):"",acsResourceId:e?.getAcsResourceId()||"",clientId:e?.getClientId()||""}}getLocalParticipantId(){let e="";const t=this.getCall();return t&&(e=t.tsCall.participantId),e}getCall(){for(const e of this._call)if(e.localVideoStreams.includes(this))return e}setSource(e,t=!1){if(e instanceof Tf)this._telemetryLogManager=e.deviceManager.telemetryLogManager,this._source=e,this._mediaStreamType="ScreenSharing"===e.deviceType?"ScreenSharing":"Video",this._mediaStreamSource=void 0,this._rawStream=void 0,this._canStartEffects=!0;else{try{1===globalThis[Il]&&(this._telemetryLogManager=globalThis[bl])}catch(e){this.logger.error("Failed to retrive telemetry logger for localVideoStream")}this._source={name:"CustomMediaStream",id:x(),deviceType:"Virtual"},this._mediaStreamSource=e,this._mediaStreamType="RawMedia",this._canStartEffects=!1}t||this._eventEmitter.emit("videoSourceChanged",{source:this})}subscribeToRawStreamChangedIfNeeded(){this._source instanceof Tf&&!this._videoSourceChangedSub&&(this._videoSourceChangedSub=this._rawStream?.changed((()=>{this._eventEmitter.emit("videoSourceChanged",{source:this})})))}disposeRawStream(){this._rawStream&&this._rawStream.dispose(),this._videoSourceChangedSub?.dispose(),this._videoSourceChangedSub=void 0}}Df([bf,Of("design:type",Object)],Nf.prototype,"logger",void 0),Df([M(_p.SwitchSource),Of("design:type",Function),Of("design:paramtypes",[Object]),Of("design:returntype",Promise)],Nf.prototype,"switchSource",null),Df([M(_p.GetMediaStream),Of("design:type",Function),Of("design:paramtypes",[]),Of("design:returntype",Promise)],Nf.prototype,"getMediaStream",null),Df([M(_p.SetMediaStream),Of("design:type",Function),Of("design:paramtypes",[MediaStream]),Of("design:returntype",Promise)],Nf.prototype,"setMediaStream",null),Df([P(_p.Feature),Of("design:type",Function),Of("design:paramtypes",[Object]),Of("design:returntype","function"==typeof(kf="undefined"!=typeof TFeature&&TFeature)?kf:Object)],Nf.prototype,"feature",null);class Lf{constructor(e,t,i,n,r){this._name=e,this._id=t,this._isSystemDefault=i,this._deviceType=n,this._deviceManager=r}get name(){return this._name}setName(e){this._name=e}get id(){return this._id}setId(e){this._id=e}get isSystemDefault(){return this._isSystemDefault}setIsSystemDefault(e){this._isSystemDefault=e}get deviceType(){return this._deviceType}setDeviceType(e){this._deviceType=e}get deviceManager(){return this._deviceManager}}class xf{constructor(e,t,i,n,r){this._workQueue=Promise.resolve(),this.logger=e.createChild("volume indicator"),this._eventEmitter=new wm(this.logger,{enableLogEmit:!1}),this._isInitialized=!1,this._level=0,this._streamType=t,this._callId=n,this._localParticipantId=r,this._telemetryLogManager=i}get isInitialized(){return this._isInitialized}initialize(e){if(void 0===e)throw this.logger.error("failed to getMediaStreamTrack"),new b({defaultError:f.CALL.VOLUME_TRACK});const t=x(),i=+new Date;try{this.sendVolumeEvent({eventName:Jh.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),this.bindToAudioStreamVolume(e),this.sendVolumeEvent({eventName:Jh.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:""})}catch(e){const n=new b({defaultError:f.CALL.VOLUME_INIT,originalError:e});throw this.logger.error(n.message),this.sendVolumeEvent({eventName:Jh.acs_calling_audio_stream_volume,correlationId:t,callId:this._callId||"",localParticipantId:this._localParticipantId||"",streamType:this._streamType,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...xg(n)}}),n}}bindToAudioStreamVolume(e){let[t,i]=this.setupVolumeCalculator(e);this._level=t();let n=setInterval((()=>{let e=t();e!==this._level&&(this._level=e,this._eventEmitter.emit("levelChanged"))}),yc()?.volumeIndicator?.microphoneVolumeSampleIntervalMs);this._volumeCallBackInterval=n,this._audioContext=i}setupVolumeCalculator(e){const t=new MediaStream(e),i=new AudioContext,n=i.createMediaStreamSource(t),r=i.createAnalyser();n.connect(r),r.fftSize=yc().volumeIndicator.fftSize,r.minDecibels=yc().volumeIndicator.minDecibels,r.maxDecibels=yc().volumeIndicator.maxDecibels,r.smoothingTimeConstant=yc().volumeIndicator.smoothingConstant;const a=new Uint8Array(r.frequencyBinCount);return[()=>{try{r.getByteFrequencyData(a);let e=0;for(const t of a)e+=t;return e/a.length*yc().volumeIndicator.normalisedMaxVolume/yc().volumeIndicator.maxAvailableVolume}catch(e){return this.logger.error("error in calculating audio stream volume"),0}},i]}dispose(){this._isInitialized=!1,this._level=0,this._eventEmitter.removeAllListeners();try{this._audioContext?.close().catch((e=>{this.logger.error("unable to close AudioContext")}))}catch(e){this.logger.error("unable to close MicrophoneAudioContext")}this._volumeCallBackInterval&&clearInterval(this._volumeCallBackInterval)}on(e,t){if("levelChanged"!==e)throw new b({defaultError:f.CALL.VOLUME_EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("levelChanged"!==e)throw new b({defaultError:f.CALL.VOLUME_EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get level(){return this._level}getVolumeIndicator(e){const t=()=>{if(!this.isInitialized)try{this.initialize(e),this._isInitialized=!0}catch(e){const t=new b({defaultError:f.CALL.VOLUME_GET,originalError:e});throw this.logger.error(t.message),t}return this},i=this._workQueue.then((()=>t()));return this._workQueue=i.then(Oc,Oc),i}sendVolumeEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send screen share telemetry")}}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([bf,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type",Object)],xf.prototype,"logger",void 0);var Ff,Uf,Bf,Vf=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Hf=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class $f{constructor(e){this.canStartEffects=!1;const i=t.createClientLogger("ACS-calling");if(this.logger=new Pf(i,[()=>`LocalAudioStream for default device with source: ${!!e}`]),this._eventEmitter=new wm(this.logger),this._disposed=!1,!(e instanceof Lf||e instanceof MediaStream))throw new b({defaultError:f.LOCAL_AUDIO_STREAM.WRONG_STREAM_TYPE});if(e instanceof Lf&&"Microphone"!==e.deviceType)throw new b({defaultError:f.LOCAL_AUDIO_STREAM.SOURCE_WRONG_TYPE});this.setSource(e,!0),this._localStreamTelemetryEventSender=new Mf(this._telemetryLogManager),this._volumeIndicator=new xf(this.logger,"LocalAudioStream",this._telemetryLogManager),this.logger.info("created")}on(e,t){if("audioSourceChanged"!==e)throw new b({defaultError:f.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("audioSourceChanged"!==e)throw new b({defaultError:f.LOCAL_AUDIO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}feature(e){return this._extensibleApi||(this._extensibleApi=new vg(this.logger,{streamInstance:this},{streamInstance:this,telemetryLogManager:this.telemetryLogManager})),this._extensibleApi.getApiObjectInstance(e.audioStreamApiCtor)}get mediaStreamType(){return this._mediaStreamType}get source(){return this._source}get telemetryLogManager(){return this._telemetryLogManager}get callStackWasmVqeProvider(){return this.source?.deviceManager?.callStackWasmVqeProvider??null}get callStackEffectsStatusManager(){return this.source?.deviceManager?.callStackAudioEffectsStatusManager??null}async getMediaStream(){const e=x(),t=+new Date,i={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:xp.getMediaStream,kindOfEvent:Yh.attempt,mediaType:Np.AudioRaw,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this.subscribeToRawStreamChangedIfNeeded(),this._mediaStreamSource){const i={correlationId:e,mediaType:Np.AudioRaw,operation:xp.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(i),this._mediaStreamSource}if(this._source instanceof Lf)try{this._rawStream=this._source.deviceManager.getRawDeviceMediaStream(0);const i=await(this._rawStream?.getMediaStream()),n={correlationId:e,mediaType:Np.AudioRaw,operation:xp.getMediaStream,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),i}catch(n){const i=new b({defaultError:f.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM,originalError:n}),r={correlationId:e,operation:xp.getMediaStream,additionalDetails:{failureReason:i.message,code:i.code,...xg(i)},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,mediaType:Np.AudioRaw,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),i}const n=new b({defaultError:f.LOCAL_AUDIO_STREAM.GET_MEDIA_STREAM}),r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:xp.getMediaStream,additionalDetails:{failureReason:n.message,code:C,...xg(n)},kindOfEvent:Yh.failure,mediaType:Np.AudioRaw,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}async setMediaStream(e){const t=x();let i=+new Date;const n={timestampInfo:{attemptTimestamp:i},correlationId:t,operation:xp.setMediaStream,kindOfEvent:Yh.attempt,mediaType:Np.AudioRaw,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),!(e instanceof MediaStream)){const e=new b({defaultError:f.LOCAL_AUDIO_STREAM.SET_MEDIA_STREAM_WRONG_TYPE}),n={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:t,operation:xp.setMediaStream,additionalDetails:{failureReason:e.message,code:e.code,...xg(e)},kindOfEvent:Yh.failure,mediaType:Np.AudioRaw,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}this._mediaStreamSource=new MediaStream(e.getAudioTracks()),this.setSource(this._mediaStreamSource),this._volumeIndicator.dispose();const r={correlationId:t,mediaType:Np.AudioRaw,operation:xp.setMediaStream,timestampInfo:{deltaTimeInMs:+new Date-i},streamType:Lp.Local,kindOfEvent:Yh.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r)}async switchSource(e){const t=+new Date,i=x(),n={timestampInfo:{attemptTimestamp:t},correlationId:i,operation:xp.switchSource,kindOfEvent:Yh.attempt,mediaType:Np.Audio,streamType:Lp.Local};if(this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e instanceof Lf&&"Microphone"!==e.deviceType){const e=new b({defaultError:f.LOCAL_AUDIO_STREAM.SWITCH_SOURCE_WRONG_TYPE}),n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:xp.switchSource,additionalDetails:{failureReason:e.message,code:e.code,...xg(e)},kindOfEvent:Yh.failure,mediaType:Np.Audio,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}if(this._source===e){const e=new b({defaultError:f.LOCAL_AUDIO_STREAM.SWITCH_SAME_SOURCE}),n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:xp.switchSource,additionalDetails:{failureReason:e.message,code:e.code,...xg(e)},kindOfEvent:Yh.failure,mediaType:Np.Audio,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),e}try{this._source.deviceManager.selectMicrophone(e),this.setSource(e),this._volumeIndicator.dispose();const n={correlationId:i,mediaType:Np.Audio,operation:xp.switchSource,timestampInfo:{deltaTimeInMs:+new Date-t},streamType:Lp.Local,kindOfEvent:Yh.success};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n)}catch(e){const n=new b({defaultError:f.LOCAL_AUDIO_STREAM.UNKNOWN,originalError:e}),r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:i,operation:xp.switchSource,additionalDetails:{failureReason:n.message,code:n.code,...xg(n)},kindOfEvent:Yh.failure,mediaType:Np.Audio,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),n}}dispose(){this.logger.log("LocalAudioStream disposing"),this._disposed?this.logger.log("Already disposed"):(this._disposed=!0,this.disposeRawStream(),this._volumeIndicator.dispose(),this._eventEmitter.removeAllListeners(),this.logger.log("LocalAudioStream disposed"))}async getVolume(){return this._volumeIndicator.isInitialized?this._volumeIndicator:this._volumeIndicator.getVolumeIndicator(await this.getMediaStream())}subscribeToRawStreamChangedIfNeeded(){this._source instanceof Lf&&!this._audioSourceChangedSub&&(this._audioSourceChangedSub=this._rawStream?.changed((()=>{this._eventEmitter.emit("audioSourceChanged",{source:this}),this._volumeIndicator.dispose()})))}disposeRawStream(){this._audioSourceChangedSub?.dispose(),this._rawStream?.dispose(),this._audioSourceChangedSub=void 0}getStreamMetadata(){const e=this.source.deviceManager;return{source:"local",streamType:this.mediaStreamType,deviceType:this.source.deviceType,deviceManagerPermissionState:JSON.stringify({cameraPermission:e.getVideoDevicePermission(),microphonePermission:e.getAudioDevicePermission()}),acsResourceId:e.getAcsResourceId()||"",clientId:e.getClientId()}}setSource(e,t=!1){if(e instanceof Lf)this._telemetryLogManager=e.deviceManager.telemetryLogManager,this._source=e,this._mediaStreamType="Audio",this._mediaStreamSource=void 0,this._rawStream=void 0,this.canStartEffects=!0;else{try{1===globalThis[Il]&&(this._telemetryLogManager=globalThis[bl])}catch(e){this.logger.error("Failed to retrive telemetry logger for localAudioStream")}this._source={name:"CustomMediaStream",id:x(),deviceType:"Virtual",isSystemDefault:!1},this._mediaStreamSource=e,this._mediaStreamType="RawMedia",this.canStartEffects=!1}t||this._eventEmitter.emit("audioSourceChanged",{source:this})}}Vf([bf,Hf("design:type",Object)],$f.prototype,"logger",void 0),Vf([P(Ep.Feature),Hf("design:type",Function),Hf("design:paramtypes",[Object]),Hf("design:returntype","function"==typeof(Ff="undefined"!=typeof TFeature&&TFeature)?Ff:Object)],$f.prototype,"feature",null),Vf([M(Ep.GetMediaStream),Hf("design:type",Function),Hf("design:paramtypes",[]),Hf("design:returntype",Promise)],$f.prototype,"getMediaStream",null),Vf([M(Ep.SetMediaStream),Hf("design:type",Function),Hf("design:paramtypes",[MediaStream]),Hf("design:returntype",Promise)],$f.prototype,"setMediaStream",null),Vf([M(Ep.SwitchSource),Hf("design:type",Function),Hf("design:paramtypes",[Object]),Hf("design:returntype",Promise)],$f.prototype,"switchSource",null),function(e){e[e.JITTER=0]="JITTER",e[e.RTT=1]="RTT",e[e.PACKETS_LOSS=2]="PACKETS_LOSS",e[e.BIT_RATE=3]="BIT_RATE",e[e.BANDWIDTH=4]="BANDWIDTH"}(Uf||(Uf={})),function(e){e[e.AUDIO=0]="AUDIO",e[e.VIDEO=1]="VIDEO"}(Bf||(Bf={}));const Gf="Unknown";var jf,zf;function Wf(e){return e?.count.length&&e?.count[0]?function(e,t,i=100){return Math.round((e/t+Number.EPSILON)*i)/i}(e.sum[0],e.count[0]):NaN}function qf(e){return e?.count.length&&e?.count[0]?e.sum[0]:NaN}!function(e){e.Supported="Supported",e.NotSupported="NotSupported",e.Unknown="Unknown"}(jf||(jf={})),function(e){e.CompleteTest="CompleteTest",e.StartTest="StartTest",e.DeviceAccess="DeviceAccess",e.DeviceEnumerations="DeviceEnumerations",e.InCallDiagnostics="InCallDiagnostics",e.BrowserSupport="BrowserSupport"}(zf||(zf={}));class Kf{constructor(){this._printableObjectAll=!0,this._completeTestInfo={name:"",succeeded:!0},this._diagnosticsTestRunIds=[],this._callMediaStatistics=Rc(),this._inCallDiagnostics={connected:!1,diagnostics:{audio:{jitter:Gf,packetLoss:Gf,rtt:Gf},video:{jitter:Gf,packetLoss:Gf,rtt:Gf}},bandWidth:Gf},this._diagnosticsMediaTelemetry={jitter:{audio:{inbound:0,outbound:0},video:{inbound:0,outbound:0}},rtt:{audio:0,video:0},packets:{audioSent:0,audioSentLost:0,audioReceived:0,audioReceivedLost:0,videoSent:0,videoSentLost:0,videoReceived:0,videoReceivedLost:0},bandWidth:0},this._isCreatingNewCallAgent=!1}intialize(e,t,i,n){this._internalCallClient=t,this._mainCallClient=e,this._logger=i,this._telemetryLogManager=n}async getDevices(e,t){let i=[];try{switch(t){case"Speaker":i=await e.getSpeakers();break;case"Microphone":i=await e.getMicrophones();break;default:i=await e.getCameras()}}catch(e){this._logger.warn("Failed to get speakers")}return i}async startTest(e,t){this._sendFeatureUsage("startTest",Yh.attempt),this._currentTestRunId=x(),this._diagnosticsTestRunIds.push(this._currentTestRunId),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.CompleteTest}}),this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.StartTest}});try{this._internalDeviceManager=await this._internalCallClient.getDeviceManager();const e=this._internalCallClient.callAgent,t=await this._mainCallClient.getDeviceManager();e?.tsStack?.getDeviceManager().selectDevices({speaker:t.selectedSpeaker?.id,microphone:t.selectedMicrophone?.id});const i=await this._internalCallClient.getDeviceManager(),n={mic:(await this.getDevices(i,"Microphone")).length,speaker:(await this.getDevices(i,"Speaker")).length};this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.StartTest,!0,`Device selection successful. Result: ${Uc(n,this._printableObjectAll)}`)})}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.SET_DEVICE_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.StartTest,!1,"Device selection failed."),additionalDetails:{...xg(t)}}),this._logger.warn(e),this._sendFeatureUsage("startTest",Yh.failure),t}try{return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.StartTest,!0,"StartTest succeeded")}),this._sendFeatureUsage("startTest",Yh.success),t?{deviceAccess:t.deviceAccess?this.deviceAccess():void 0,deviceEnumeration:t.deviceEnumeration?this.deviceEnumeration():void 0,inCallDiagnostics:t.inCallDiagnostics?this.getInCallDiagnostics(e):void 0,browserSupport:t.browserSupport?this.getBrowserSupport():void 0,callMediaStatistics:t.callMediaStatistics?this.getcallMediaStatistics():void 0,id:this._currentTestRunId}:{deviceAccess:this.deviceAccess(),deviceEnumeration:this.deviceEnumeration(),inCallDiagnostics:this.getInCallDiagnostics(e),browserSupport:this.getBrowserSupport(),callMediaStatistics:this.getcallMediaStatistics(),id:this._currentTestRunId}}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.GET_DIAGNOSTICS_INFO,originalError:e});throw this._logger.error(t.message),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.StartTest,!1,"StartTest failed."),additionalDetails:{...xg(t)}}),this._sendFeatureUsage("startTest",Yh.failure),t}}async getBrowserSupport(){let e;this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.BrowserSupport}});try{const t=await this._mainCallClient.getEnvironmentInfoInternal();e={browser:t.isSupportedBrowser?jf.Supported:jf.NotSupported,os:t.isSupportedPlatform?jf.Supported:jf.NotSupported},this.updateTestInfo(zf.BrowserSupport,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Browser support successful. Result: ${Uc(e,this._printableObjectAll)}`,name:zf.BrowserSupport}})}catch(t){e={browser:jf.Unknown,os:jf.Unknown},this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.BrowserSupport,!1,`Browser support failed. Error: ${Uc(t)}`)}),this._logger.error(`Browser support failed: ${t}`)}return new Promise((t=>t(e)))}async renderHiddenVideoElement(e,t){let i,n=e.tsCall,r=n.mediaStreams;try{await new Promise(((e,t)=>{i=n.changed((()=>{void 0!==r[0]&&r[0].length>0&&r[0][0].isAvailable&&(e(),i?.dispose(),this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call mediaStreams successful.",name:zf.InCallDiagnostics}}))})),setTimeout((()=>{this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,"Call mediaStreams failed. Error: Timeout")}),t(new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_STREAM_TIMEOUT}))}),1e3*this._diagnosticsEcsConfig.CALL.MEDIASTREAM_TIMEOUT_IN_SEC)}));let a=n.mediaStreams[0][0],s=document.getElementById("_hiddenSelfRemoteStream");s&&s.remove(),s=document.createElement("div"),s.id="_hiddenSelfRemoteStream",s.style.position="relative",s.style.height="0px",s.style.width="0px";const o=document.createElement("div");o.style.position="absolute",o.style.height=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.heigth+"px",o.style.width=this._diagnosticsEcsConfig.CALL.VIDEO_SIZE.width+"px",o.style.bottom="0px",o.style.left="-2000px",s.appendChild(o),document.getElementsByTagName("body")[0].appendChild(s),this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Video element rendering successful. CallId: ${e.id}, localParticipantId: ${t}`,name:zf.InCallDiagnostics}}),await a.start(o)}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,`Call mediaStreams failed. Error: ${Uc(e)}`)}),this._logger.warn("Failed to render hidden video element")}}sineWaveAudioStream(){const e=new window.AudioContext,t=e.createMediaStreamDestination(),i=e.createOscillator();i.type="sine",i.frequency.value=500,i.connect(t),i.start();const{stream:n}=t;return new $f(n)}async receiveAndPlayCallAudio(e,t){try{const i=new window.AudioContext,n=new MediaStream;i.createMediaStreamSource(n).connect(i.destination),this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call mediaStreams audio track succeeded. CallId: ${e.id}, localParticipantId: ${t}`,name:zf.InCallDiagnostics}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,`Call mediaStreams audio track failed. Error: ${Uc(e)}`)}),this._logger.warn("Failed to send audio to call.")}}async getcallMediaStatistics(){return this._callMediaStatistics.promise}setEcsConfig(){this._diagnosticsEcsConfig=yc()?.calling?.callDiagnostics}async getInCallDiagnostics(e){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.InCallDiagnostics}}),this.setEcsConfig();const t={groupId:this._diagnosticsEcsConfig.CALL.GROUP_ID},i=await this.getDevices(this._internalDeviceManager,"Camera");let n,r="";0!==i.length&&(n=[new Nf(i[0])]);const a={videoOptions:{localVideoStreams:n},audioOptions:{muted:!1,localAudioStreams:[this.sineWaveAudioStream()]}};let s;try{s=await(this._mainCallClient.callAgent?.getExistingCallAgentWithToken(e)),s?this._internalCallClient.setCallAgent(s):(this._isCreatingNewCallAgent=!0,await this._internalCallClient.createCallAgent(e)),this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Create CallAgent successful.",name:zf.InCallDiagnostics}})}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.GET_CALL_AGENT,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,t.message),additionalDetails:{...xg(t)}}),this._logger.error(t.message),t}const o=this._internalCallClient.callAgent?.join(t,a);if(o){try{await this.waitCallConnected(o),r=o.tsCall.participantId,this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:"Call connected successfully",name:zf.InCallDiagnostics}})}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.CONNECT_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,t.message),additionalDetails:{...xg(t)}}),this._logger.error(t.message),t}try{this.updateTestInfo(zf.InCallDiagnostics,!0),await this.renderHiddenVideoElement(o,r)}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.RENDER_VIDEO,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,t.message),additionalDetails:{...xg(t)}}),t}this.receiveAndPlayCallAudio(o,r);const t=o.feature(Eg(df,{activationEvent:"OnExtendedObjectConstructor"}));this._callMediaStatistics.resolve(t),t.createCollector({aggregationInterval:this._diagnosticsEcsConfig.CALL.AGGREGATION.INTERVAL,dataPointsPerAggregation:this._diagnosticsEcsConfig.CALL.AGGREGATION.DATAPOINTS}).on("summaryReported",(e=>this.gatherCallStatistics(e)));try{await Dh(1e3*this._diagnosticsEcsConfig.CALL.DURATION_IN_SEC),await o.hangUp({forEveryone:!0}),this.updateTestInfo(zf.InCallDiagnostics,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Call hangup successful. Result: ${Uc(this._inCallDiagnostics,this._printableObjectAll)}`,name:zf.InCallDiagnostics}})}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.HANGUP_FAIL,originalError:e});throw this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.InCallDiagnostics,!1,t.message),additionalDetails:{...xg(t)}}),this._logger.error(t.message),t}this.dispose()}return this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:this._completeTestInfo.succeeded,result:this._completeTestInfo.result||"InCallDiagnostics succeeded.",name:zf.CompleteTest}}),this._inCallDiagnostics}async waitCallConnected(e){await new Promise((async(t,i)=>{e.on("stateChanged",(()=>{"Connected"==e.state&&(this._inCallDiagnostics.connected=!0,t()),"Disconnected"==e.state&&i("Call disconnected")}));const n=this._diagnosticsEcsConfig.CALL.CONNECT_TIMEOUT_IN_SEC;await Dh(1e3*n),i(new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.CALL_CONNECT_TIMEOUT,defaultErrorMessageArgs:[n]}))}))}qualityGrade(e,t,i){return e<=t?"Good":e>=i?"Bad":"Average"}bandwidthQualityGrade(e,t,i){return e>=t?"Good":e<=i?"Bad":"Average"}getQualityGradeForMetric(e,t,i){switch(e){case Uf.JITTER:return i===Bf.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.JITTER.GOOD,this._diagnosticsEcsConfig.AUDIO.JITTER.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.JITTER.GOOD,this._diagnosticsEcsConfig.VIDEO.JITTER.AVERAGE);case Uf.RTT:return i===Bf.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.RTT.GOOD,this._diagnosticsEcsConfig.AUDIO.RTT.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.RTT.GOOD,this._diagnosticsEcsConfig.VIDEO.RTT.AVERAGE);case Uf.PACKETS_LOSS:return i===Bf.AUDIO?this.qualityGrade(t,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.AUDIO.PACKETS_LOSS_PERCENTAGE.AVERAGE):this.qualityGrade(t,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.GOOD,this._diagnosticsEcsConfig.VIDEO.PACKETS_LOSS_PERCENTAGE.AVERAGE);case Uf.BANDWIDTH:return this.bandwidthQualityGrade(t,this._diagnosticsEcsConfig.BANDWIDTH.GOOD,this._diagnosticsEcsConfig.BANDWIDTH.AVERAGE);default:return Gf}}gatherCallStatistics(e){try{const t=e.audio.receive.length?e.audio.receive[0]:void 0,i=e.audio.send.length?e.audio.send[0]:void 0,n=e.video.receive.length?e.video.receive[0]:void 0,r=e.video.send.length?e.video.send[0]:void 0,a=e.transports.length?e.transports[0]:void 0;this._diagnosticsMediaTelemetry.jitter.audio.inbound=Wf(t?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.audio.outbound=Wf(i?.jitterInMs?.aggregation);const s=Math.max(this._diagnosticsMediaTelemetry.jitter.audio?.inbound,this._diagnosticsMediaTelemetry.jitter.audio?.outbound);this._inCallDiagnostics.diagnostics.audio.jitter=this.getQualityGradeForMetric(Uf.JITTER,s,Bf.AUDIO),this._diagnosticsMediaTelemetry.rtt.audio=Wf(i?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.audio.rtt=this.getQualityGradeForMetric(Uf.JITTER,this._diagnosticsMediaTelemetry.rtt.audio,Bf.AUDIO),this._diagnosticsMediaTelemetry.packets.audioSent=qf(i?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioSentLost=qf(i?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceived=qf(t?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.audioReceivedLost=qf(t?.packetsLostPerSecond?.aggregation);const o=this._diagnosticsMediaTelemetry.packets.audioSent-this._diagnosticsMediaTelemetry.packets.audioSentLost,l=this._diagnosticsMediaTelemetry.packets.audioReceived-this._diagnosticsMediaTelemetry.packets.audioReceivedLost,c=Math.max(o,l)/this._diagnosticsMediaTelemetry.packets.audioSent*100;this._inCallDiagnostics.diagnostics.audio.packetLoss=this.getQualityGradeForMetric(Uf.PACKETS_LOSS,c,Bf.AUDIO),this._diagnosticsMediaTelemetry.jitter.video.inbound=Wf(n?.jitterInMs?.aggregation),this._diagnosticsMediaTelemetry.jitter.video.outbound=Wf(r?.jitterInMs?.aggregation);const d=Math.max(this._diagnosticsMediaTelemetry.jitter.video.inbound,this._diagnosticsMediaTelemetry.jitter.video.outbound);this._inCallDiagnostics.diagnostics.video.jitter=this.getQualityGradeForMetric(Uf.JITTER,d,Bf.VIDEO),this._diagnosticsMediaTelemetry.rtt.video=Wf(r?.rttInMs?.aggregation),this._inCallDiagnostics.diagnostics.video.rtt=this.getQualityGradeForMetric(Uf.RTT,this._diagnosticsMediaTelemetry.rtt.video,Bf.VIDEO),this._diagnosticsMediaTelemetry.packets.videoSent=qf(r?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoSentLost=qf(r?.packetsLostPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceived=qf(n?.packetsPerSecond?.aggregation),this._diagnosticsMediaTelemetry.packets.videoReceivedLost=qf(n?.packetsLostPerSecond?.aggregation);const u=this._diagnosticsMediaTelemetry.packets.videoSent-this._diagnosticsMediaTelemetry.packets.videoSentLost,h=this._diagnosticsMediaTelemetry.packets.videoReceived-this._diagnosticsMediaTelemetry.packets.videoReceivedLost,p=Math.max(u,h)/this._diagnosticsMediaTelemetry.packets.videoSent*100;this._inCallDiagnostics.diagnostics.video.packetLoss=this.getQualityGradeForMetric(Uf.PACKETS_LOSS,p,Bf.VIDEO),this._diagnosticsMediaTelemetry.bandWidth=Wf(a?.availableOutgoingBitrate?.aggregation),this._inCallDiagnostics.bandWidth=this.getQualityGradeForMetric(Uf.BANDWIDTH,this._diagnosticsMediaTelemetry.bandWidth,Bf.AUDIO)}catch(e){const t=new b({defaultError:f.FEATURES.PRECALL_DIAGNOSTICS.VIDEO_MEDIASTATS,originalError:e});this._logger.error("Failed to get audio call media stats:",t.message),this._callMediaStatistics.reject(t)}}async deviceAccess(){this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.DeviceAccess}});const e=this._internalDeviceManager.askDevicePermission({audio:!0,video:!0});try{const t=await e;this.updateTestInfo(zf.DeviceAccess,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Access successful. Result: ${Uc(t,this._printableObjectAll)}`,name:zf.DeviceAccess}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.DeviceAccess,!1,"Device Access failed.")})}return e}async deviceEnumeration(){const e={microphone:Gf,camera:Gf,speaker:Gf};this.telemetryLogAttemptEvents({diagnosticsTestRunId:this._currentTestRunId,testAttemptDetails:{name:zf.DeviceEnumerations}});try{const t=0!==(await this.getDevices(this._internalDeviceManager,"Microphone")).length,i=0!==(await this.getDevices(this._internalDeviceManager,"Camera")).length,n=0!==(await this.getDevices(this._internalDeviceManager,"Speaker")).length;e.microphone=t?"Available":"NotAvailable",e.camera=i?"Available":"NotAvailable",e.speaker=n?"Available":"NotAvailable",this.updateTestInfo(zf.DeviceEnumerations,!0),this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:{succeeded:!0,result:`Device Enumeration successful. Result: ${Uc(e,this._printableObjectAll)}`,name:zf.DeviceEnumerations}})}catch(e){this.telemetryLogResultEvents({diagnosticsTestRunId:this._currentTestRunId,testResultDetails:this.updateTestInfo(zf.DeviceEnumerations,!1,"Device Enumeration failed.")}),this._logger.error(`Couldn't find mic, camera, or speaker: ${e}`)}return e}telemetryLogAttemptEvents(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_diagnostics_attempt,tenant:hl,properties:{name:e.testAttemptDetails.name,diagnosticsTestRunId:e.diagnosticsTestRunId}})}telemetryLogResultEvents(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_diagnostics_result,tenant:hl,properties:{name:e.testResultDetails.name,diagnosticsTestRunId:e.diagnosticsTestRunId,succeeded:e.testResultDetails.succeeded,result:e.testResultDetails.result,additionalDetails:e.additionalDetails||{}}})}updateTestInfo(e,t,i){return this._completeTestInfo.succeeded&&(this._completeTestInfo={succeeded:t,name:e,result:i}),{succeeded:t,name:e,result:i||""}}_sendFeatureUsage(e,t){Ig({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._isCreatingNewCallAgent&&this._internalCallClient.callAgent?.dispose()}}class Jf{constructor(e,t){this._debounce=void 0,this._updateFunction=e,this._timeout=t}debounce(){this._debounce?(clearTimeout(this._debounce),this._debounce=setTimeout((()=>{this._updateFunction(),this._debounce=void 0}),this._timeout)):(this._updateFunction(),this._debounce=setTimeout((()=>{this._debounce=void 0}),this._timeout))}flush(){this._debounce&&(clearTimeout(this._debounce),this._debounce=void 0,this._updateFunction())}}class Yf{constructor(e,t,i,n,r,a){this._isReceiving=!1,this._mediaStreamType="Video",this._renderers=[],this._disposed=!1,this._size={height:0,width:0},this._setType=e=>{0===e.type?this._mediaStreamType="Video":1===e.type?this._mediaStreamType="ScreenSharing":2===e.type&&(this._mediaStreamType="LiveStream")},this._disposeRenderer=e=>{this.logger.log("disposing renderer");try{e.dispose(Bp.Internal_RemoteVideoStreamDisposed),this.logger.log("renderer disposed")}catch(e){this.logger.log("failed to dispose renderer")}},this.tsStream=e,this._setType(this.tsStream),this.logger=t.createChild((()=>`Stream:{id=${this.tsStream.id}}:{type=${this._mediaStreamType}}`)),this.telemetryLogManager=r,this.kind=a,this._eventEmitter=new wm(this.logger),this.call=i,this._tsParticipantId=n,this.sendRemoteVideoStreamTelemetry(),this._debounceSize=this.createDebounceSize(),this._debounceIsReceiving=new Jf((()=>{const e=this._renderers?.filter((e=>!!e?.isRendering)).length>0;this._isReceiving!==e&&(this._isReceiving=e,this.logger.info(`isReceiving changed to ${this._isReceiving}`),this._eventEmitter.emit("isReceivingChanged"),this.sendRemoteVideoStreamTelemetry())}),yc().rendering.remoteVideo.debounceTimeout),this._registeredViewIdsMaxLength=yc().rendering.remoteVideo.registeredViewIdsMaxLength,this.logger.info("created")}on(e,t){if("sizeChanged"!==e&&"isReceivingChanged"!==e)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("sizeChanged"!==e&&"isReceivingChanged"!==e)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get id(){return this.tsStream.id}get isReceiving(){return this._isReceiving}get tsParticipantId(){return this._tsParticipantId}get remoteParticipantId(){return this.tsStream.participantId??""}get mediaStreamType(){return this._mediaStreamType}get size(){return{height:this._size.height,width:this._size.width}}updateSize(){this._debounceSize.debounce()}updateIsReceiving(){this._debounceIsReceiving.debounce()}flushIsReceiving(){this._debounceIsReceiving.flush()}registerRenderer(e){this._renderers.push(e),this.logger.info(`Renderer registered, view id: ${e.viewId}`)}unregisterRenderer(e){const t=this._renderers.indexOf(e);-1!==t&&(this._renderers.splice(t,1),this.logger.info(`Renderer un-registered, view id: ${e.viewId}`))}dispose(){this.logger.log("dispose"),this._disposed?this.logger.log("already disposed"):(this._disposed=!0,this._streamChangedHandler&&this._streamChangedHandler.dispose(),this._renderers.forEach((e=>this._disposeRenderer(e))),this._renderers=[],this._eventEmitter.removeAllListeners())}getRegisteredViewIds(){let e=this._renderers.map((e=>e.viewId));return this._registeredViewIdsMaxLength&&(e=e.slice(0,this._registeredViewIdsMaxLength)),e.join(", ")}sendRemoteVideoStreamTelemetry(){this.call.stats.recordEvent({name:Kh.remote_stream,callId:this.call.id,localParticipantId:this.call.tsCall.participantId,data:{...this.getStreamMetadata()}})}createDebounceSize(){return new Jf((()=>{let e={height:0,width:0};this._renderers?.forEach((t=>{t?.isRendering&&t.size.height>e.height&&t.size.width>e.width&&(e.height=t.size.height,e.width=t.size.width)}),yc().rendering.remoteVideo.debounceTimeout),this._size.height===e.height&&this._size.width===e.width||(this._size.height=e.height,this._size.width=e.width,this.logger.info(`stream size changed to { height: ${this._size.height}, width: ${this._size.width} }`),this._eventEmitter.emit("sizeChanged"),this.sendRemoteVideoStreamTelemetry())}),yc().rendering.remoteVideo.debounceTimeout)}}class Qf{constructor(e){this._statsInfo=e,this._originalValues={},this._aggregateValues={}}isDiffMethod(e){return"diff"==e||"last2"==e||"rate"===e}addStats(e,t){const i=this._statsInfo[e];let n=this._originalValues[e];if(void 0===n&&(n={raw:[],calc:[],lastTime:Date.now(),beginTime:Date.now()},this._originalValues[e]=n),this.isDiffMethod(i.calculation_method)){n.raw.push(t);const e=Date.now(),r=n.lastTime;n.lastTime=e,n.raw.length>1?(t=n.raw[n.raw.length-1]-n.raw[n.raw.length-2],"rate"===i.calculation_method&&(t=t/(e-r)*1e3),void 0!==i.multiplier&&(t*=i.multiplier),!0===i.integer&&(t|=0),n.calc.push(t)):"rate"===i.calculation_method&&(t=0)}else void 0!==i.multiplier&&"number"==typeof t&&(t*=i.multiplier),!0===i.integer&&(t|=0),n.raw.push(t);return t}aggregate(){const e={};for(const[t,i]of Object.entries(this._originalValues)){const n=this._statsInfo[t];if(void 0===n||!1===n.show)continue;this.isDiffMethod(n.calculation_method)&&i.raw.length>0&&(e[t]={raw:[i.raw[i.raw.length-1]],calc:[],lastTime:i.lastTime,beginTime:0});let r=this._aggregateValues[t];void 0===r&&(r={raw:[],timestamp:new Date(i.beginTime)},n.aggregation_needed&&(r.aggregation={count:[],sum:[],max:[],min:[]}),this._aggregateValues[t]=r);const a=i.calc?.length?i.calc:i.raw;let s=a;if(n.aggregation_needed&&r.aggregation){const e=a.filter((e=>"number"==typeof e&&!isNaN(e)));r.aggregation.count.push(e.length),r.aggregation.sum.push(Mm(e)),r.aggregation.max.push(Am(e)),r.aggregation.min.push(Pm(e)),s=e}n.raw_data_reduction&&s.length>0&&(r.reduced=r.reduced||[],r.reduced.push(s[s.length-1])),s.forEach((e=>r.raw.push(e)))}this._originalValues=e}popAggregates(){const e={};for(const[t,i]of Object.entries(this._aggregateValues))e[this._statsInfo[t].name??t]=i;return this._aggregateValues={},e}}class Zf{constructor(e,t,i){if(this._tsCall=e,this._aggregationInterval=0,this._dataPointsPerAggregation=0,this._disposed=!1,this._calculators=new Map,i.aggregationInterval<1)throw new b({defaultError:f.FEATURES.LIVE_STREAM.INVALID_AGGREGATION_INTERVAL_RANGE});if(i.dataPointsPerAggregation<1)throw new b({defaultError:f.FEATURES.LIVE_STREAM.INVALID_DATAPOINTS_AGGREGATION_RANGE});this._logger=t.createChild("LiveStreamStatsCollector"),this._eventEmitter=new wm(this._logger,{enableLogEmit:!1}),this._callStateChanged=kh(),this._statsPoller=i.statsPoller,this._statsInfo=i.statsInfo,this._aggregationInterval=i.aggregationInterval,this._dataPointsPerAggregation=i.dataPointsPerAggregation,this._isInternal=i.isInternal,this._dataEventListener=e=>{void 0!==e&&this._processData(e)},this._statsPoller.on("data",this._dataEventListener);const n=[3,10];let r=n.includes(this._tsCall.state);this._callStateChangedHandle=this._tsCall.on("callStateChanged",(()=>{r!==n.includes(this._tsCall.state)&&(r=!r,this._callStateChanged.resolve(r))})),this._run()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._disposed||(this._disposed=!0,this._callStateChangedHandle.dispose(),this._callStateChanged.resolve(!1),this._statsPoller.off("data",this._dataEventListener),this._eventEmitter.emit("dispose"),this._eventEmitter.removeAllListeners())}_processData(e){const t={},i=Object.keys(e);0!==i.length&&(i.forEach((i=>{const n=e[i],r={};let a=this._calculators.get(i);a||(a=new Qf(this._statsInfo),this._calculators.set(i,a));for(const[e,t]of Object.entries(n)){const i=this._statsInfo[e];if(i&&!1!==i.show&&(this._isInternal||!i.is_internal)){const n=a.addStats(e,t);r[i.name??e]=n}}t[i]=r})),Object.keys(t).length>0&&this._eventEmitter.emit("sampleReported",t))}async _run(){let e=0;const t=e=>(Object.keys(e).forEach((t=>{e[t].reduced&&!this._isInternal&&delete e[t].reduced})),e),i=()=>{if(0===this._calculators.size||0===e)return;const i=[],n={};this._calculators.forEach(((e,r)=>{const a=t(e.popAggregates());0===Object.keys(a).length?i.push(r):(a.reduced&&!this._isInternal&&delete a.reduced,n[r]=a)}));try{this._eventEmitter.emit("summaryReported",n)}catch(e){this._logger.error(`summary event: ${e}`)}i.forEach((e=>{this._calculators.delete(e)})),e=0},n=[3,10];let r=1e3*this._aggregationInterval;for(;!this._disposed;){if(n.includes(this._tsCall.state)){r>0&&await Lh((()=>this._callStateChanged.promise),r).catch((e=>{}));const t=Date.now();this._calculators.size>0&&(this._calculators.forEach((e=>{e.aggregate()})),e++,e===this._dataPointsPerAggregation&&i());const n=Date.now();r=t+1e3*this._aggregationInterval-n}else i(),this._calculators.clear(),await this._callStateChanged.promise.catch((e=>{})),r=1e3*this._aggregationInterval;this._callStateChanged.isPending()||(this._callStateChanged=kh())}i()}}class Xf extends Vm{constructor(e,t,i,n){super(e,t.createChild("LiveStreamStatsPoller"),i.fetchInterval,i.pollingMethod),this._liveStreams=n}async getStats(){const e={};return this._liveStreams.forEach(((t,i)=>{try{const i=t.tsStream.getStats();if(i){const t=i.id.toString(),n={id:t};"number"==typeof i.player_downloadBitrate&&(n.videoBitrate=i.player_downloadBitrate),"number"==typeof i.player_audioDownloadBitrate&&(n.audioBitrate=i.player_audioDownloadBitrate),"number"==typeof i.player_totalDownloadedBytes&&(n.downloadBitrate=i.player_totalDownloadedBytes,n.totalDownloadBytes=i.player_totalDownloadedBytes),"number"==typeof i.player_videoBufferLength&&(n.bufferLengthInMs=Math.round(1e3*i.player_videoBufferLength)),void 0!==i.player_mediaHeight&&(n.videoHeight=i.player_mediaHeight),void 0!==i.player_mediaWidth&&(n.videoWidth=i.player_mediaWidth),void 0!==i.player_playerHeight&&(n.playerHeight=i.player_playerHeight),void 0!==i.player_playerWidth&&(n.playerWidth=i.player_playerWidth),"number"==typeof i.player_mediaDelay&&(n.mediaDelayInMs=Math.round(1e3*i.player_mediaDelay)),"number"==typeof i.player_currentPlayPosition&&(n.currentPlayPosition=Math.round(1e3*i.player_currentPlayPosition)/1e3),e[t]=n}}catch(e){this._logger.error(`fetch live stream stats failed: ${e}`)}})),Object.keys(e).length>0?e:void 0}}class ev{constructor(e,t,i){this._tsCall=e,this._telemetryLogManager=t,this._config=i}log(e){Object.entries(e).forEach((([e,t])=>{const i={id:e},n={id:e};if(Object.entries(t).forEach((([e,t])=>{const r=e,a={};if(this._config.dataToSend.raw){const e={};t?.timestamp&&(e.timestamp=t.timestamp),t?.raw&&(e.raw=t?.raw),void 0===e.raw&&delete n[r],n[r]=e}void 0!==t?.aggregation?(t?.timestamp&&(a.timestamp=t?.timestamp),this._config.dataToSend.min&&(a.min=t?.aggregation.min),this._config.dataToSend.max&&(a.max=t?.aggregation.max),this._config.dataToSend.sum&&(a.sum=t?.aggregation.sum),this._config.dataToSend.count&&(a.count=t?.aggregation.count),t?.aggregation.sum&&t?.aggregation.count&&(a.average=Mm(t?.aggregation.sum)/Mm(t?.aggregation.count))):(t?.timestamp&&(a.timestamp=t.timestamp),t?.reduced?a.raw=t?.reduced:void 0!==t?.raw&&(a.raw=t?.raw)),i[r]=a})),Object.keys(i).length>1){const e={stats:i,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamStatsEvent(e)}if(this._config.dataToSend.raw&&Object.keys(n).length>1){const e={stats:n,callId:this._tsCall.callId||"",localParticipantId:this._tsCall.participantId||""};this._sendLiveStreamRawStatsEvent(e)}}))}_sendLiveStreamStatsEvent(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_livestream_stats,tenant:hl,properties:e})}_sendLiveStreamRawStatsEvent(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_livestream_raw_stats,tenant:hl,properties:e})}}class tv{constructor(e,t,i,n){this._tsCall=e,this._logger=t,this._collectors=[],this._disposed=!1,this._externalStatsInfo={};const r=yc().telemetry.liveStreamStatsConfig;this._config=r,this._statsPoller=new Xf(this._tsCall,this._logger,r,n);const a={...jl,...r.additionalStats};if(Object.entries(a).filter((([,e])=>!e.is_internal)).forEach((([e,t])=>{this._externalStatsInfo[e]=t})),r.enabled){const e=new Zf(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:r.aggregationInterval,dataPointsPerAggregation:r.dataPointsPerAggregation,statsInfo:a,isInternal:!0}),t=new ev(this._tsCall,i,r);e.on("summaryReported",(e=>{t.log(e)})),this._collectors.push(e)}}createStatsCollector(e){if(this._disposed)throw new b({defaultError:f.FEATURES.LIVE_STREAM.DISPOSED});const t=this._config,i=new Zf(this._tsCall,this._logger,{statsPoller:this._statsPoller,aggregationInterval:e?.aggregationInterval??t.aggregationInterval,dataPointsPerAggregation:e?.dataPointsPerAggregation??t.dataPointsPerAggregation,statsInfo:this._externalStatsInfo,isInternal:!1});return i.on("dispose",(()=>{this._collectors=this._collectors.filter((e=>e!==i))})),this._collectors.push(i),i}dispose(){this._disposed||(this._disposed=!0,this._collectors.forEach((e=>{e.dispose()})))}}class iv{constructor(e,t){this._featureName=e,this._targetBotIds=t,this._streamIdToStreamMap=new Map}initialize(e,t,i,n,r){this._logger=r.createChild((()=>`${this._featureName}::Call(id='${e.callId}')`)),this._telemetryLogManager=n,this._call=i,this._tsCall=e,this.observeBotParticipantsAlreadyInCall(),this._tsCall.on("participantAdded",(async e=>{this.observeBotParticipantJustJoinedCall(e)})),this._tsCall.on("participantRemoved",(async e=>{this.removeStreamOfTheBotJustRemovedFromCall(e)}))}disposeAllBotStreams(){this._streamIdToStreamMap.forEach((e=>e.dispose())),this._streamIdToStreamMap.clear()}observeBotParticipantsAlreadyInCall(){this._tsCall.participants.forEach((e=>{this.isExpectedBotParticipant(e)&&(this._logger.info(`${this._featureName} Bot already in the call`),this.observeBotParticipant(e))}))}observeBotParticipantJustJoinedCall(e){this.isExpectedBotParticipant(e)&&(this._logger.info(`${this._featureName} Bot added`),this.observeBotParticipant(e))}removeStreamOfTheBotJustRemovedFromCall(e){if(this.isExpectedBotParticipant(e)){this._logger.info(`${this._featureName} Bot removed`);const t=[];this.removeAllStreams(e,t),this.checkVideoStreamAddedOrRemoved([],t)}}observeBotParticipant(e){e.changed((()=>{this._logger.info(`${this._featureName} Bot - changed event triggered. state: ${e.state}`),this._mapStreams(e)})),this._logger.info(`Composition Bot state: ${e.state}`),this._mapStreams(e)}_mapStreams(e){const t=[],i=[],n=n=>{if(e)if(pc(e.streams&&e.streams[n])){let r=e.streams[n];this._logger.log(`Stream Type: ${n}`),r.forEach((i=>{if(void 0===i.id&&(i.id=-1),!this._streamIdToStreamMap.get(i.id)){const n=this.createConcreteVideoStream(i,e.id);this._logger.log(`${this._featureName} stream created, type==${n.mediaStreamType} id=${i.id}`),t.push(n)}})),this._streamIdToStreamMap.forEach((t=>{t.tsParticipantId!==e.id||r.some((e=>e.id===t.id))||i.push(t)}))}else this.removeAllStreams(e,i)};this.getStreamTypes().forEach((e=>n(e))),this.checkVideoStreamAddedOrRemoved(t,i)}removeAllStreams(e,t){this._streamIdToStreamMap.forEach((i=>{i.tsParticipantId===e.id&&t.push(i)}))}checkVideoStreamAddedOrRemoved(e,t){if(e.length>0||t.length>0){const i=e=>{this._streamIdToStreamMap.set(e.id,e)},n=e=>{const t=this._streamIdToStreamMap.get(e.id);t&&(this._logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._streamIdToStreamMap.delete(e.id),t.dispose())};e.forEach(i),t.forEach(n),this.emitVideoStreamsUpdatedEvent({added:e,removed:t})}}isExpectedBotParticipant(e){return this._targetBotIds.includes(e.id)}}class nv extends iv{constructor(e,t){super(t,yc().calling.liveStreamingBotIds),this._eventEmitter=e}initialize(e,t,i,n,r){super.initialize(e,t,i,n,r),this._statsManager=new tv(e,r,n,this._streamIdToStreamMap),this._tsCall.participantCounts&&null!=this._tsCall.participantCounts.streamingClients&&(this._participantCount=this._tsCall.participantCounts.streamingClients),this._tsCall.on("participantCountsUpdated",(()=>{if(this._tsCall.participantCounts&&this._participantCount!==this._tsCall.participantCounts.streamingClients){const e=this._participantCount;this._participantCount=this._tsCall.participantCounts.streamingClients,this._logger.log(`tsCall participantCount changed from ${e} to ${this._participantCount}`),this._eventEmitter.emit("participantCountChanged")}}))}dispose(){super.disposeAllBotStreams(),this._statsManager.dispose()}createStatsCollector(e){return this._statsManager.createStatsCollector(e)}get liveStreams(){return[...this._streamIdToStreamMap.values()].map((e=>e))}get streamingClientCount(){return this._participantCount??0}createConcreteVideoStream(e,t){return new rv(e,this._logger,this._call,this._callAgent,t,this._telemetryLogManager)}getStreamTypes(){return[2]}emitVideoStreamsUpdatedEvent(e){return this._eventEmitter.emit("liveStreamsUpdated",e)}}class rv extends Yf{constructor(e,t,i,n,r,a){super(e,t,i,r,a,"LiveVideoStream")}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this.getRegisteredViewIds(),height:this._size.height,width:this._size.width,isDisposed:this._disposed}}}class av extends iv{constructor(e,t){super(t,yc().calling.composedStreamBotIds),this._eventEmitter=e}initialize(e,t,i,n,r){super.initialize(e,t,i,n,r)}dispose(){super.disposeAllBotStreams()}get composedStreams(){return[...this._streamIdToStreamMap.values()].map((e=>e))}createConcreteVideoStream(e,t){return new sv(e,this._logger,this._call,this._callAgent,t,this._telemetryLogManager)}getStreamTypes(){return[0]}emitVideoStreamsUpdatedEvent(e){return this._eventEmitter.emit("composedStreamsUpdated",e)}}class sv extends Yf{constructor(e,t,i,n,r,a){super(e,t,i,r,a,"ComposedVideoStream")}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this.getRegisteredViewIds(),height:this._size.height,width:this._size.width,isDisposed:this._disposed}}}class ov{constructor(e,t){this._logger=e,this._environmentInfo=t,this._videoEffectsEnabled=!1,this._audioEffectsEnabled=!1,this._videoEffectsSupported=!1,this._audioEffectsSupported=!1,this._config=yc(),this._mediaConfig=Cc(),this._videoEffectsEnabled=!(!this._mediaConfig?.enableVideoEffects||!this._config?.videoEffects?.enableVideoEffects),this._audioEffectsEnabled=!!this._config?.audioEffects?.enableAudioEffects,this._videoEffectsEnabled&&(this._videoEffectsSupported=this._mediaConfig?.webcv?.useWasmEffects?this._isWasmVideoEffectSupported():this._isWebgl2EffectSupported())}async videoEffectsSupported(){if(this._videoEffectsEnabled){const e=this._mediaConfig?.webcv?.useWasmEffects?this._isWasmVideoEffectSupported():this._isWebgl2EffectSupported();this._videoEffectsSupported=e&&this._isCurrentEnvironmentSDKSupported()}else this._logger.info("Video effects are disabled."),this._videoEffectsSupported=!1;return this._videoEffectsSupported}async audioEffectsSupported(e){return this._audioEffectsEnabled?this._audioEffectsSupported=this._isBrowserEffect(e)?this._isBrowserEffectSupported(e):await this._isWasmAudioEffectSupported():(this._logger.info("Audio effects are disabled."),this._audioEffectsSupported=!1),this._audioEffectsSupported}_isBrowserEffect(e){if("string"==typeof e)switch(e){case"BrowserEchoCancellation":case"BrowserNoiseSuppression":case"BrowserAutoGainControl":return!0;default:return!1}return!1}_isBrowserEffectSupported(e){const t=window.navigator?.mediaDevices?.getSupportedConstraints?.();if(t)switch(e){case"BrowserEchoCancellation":return!!t.echoCancellation;case"BrowserNoiseSuppression":return!!t.noiseSuppression;case"BrowserAutoGainControl":return!!t.autoGainControl;default:return!1}return!1}_isCurrentEnvironmentSDKSupported(){return!!(this._environmentInfo.isSupportedBrowser&&this._environmentInfo.isSupportedBrowserVersion&&this._environmentInfo.isSupportedEnvironment&&this._environmentInfo.isSupportedPlatform)}_isWasmVideoEffectSupported(){return this._mediaConfig?.webcv?.useWasmEffects?!!window.MediaStreamTrackProcessor||(this._logger.info("WASM effects disabled, insertable streams are not supported"),!1):(this._logger.info("WASM effects disabled by WebCV feature flag"),!1)}_isWebgl2EffectSupported(){return this._isCurrentRendererSupported()&&this._isWebGL2Supported()}_isCurrentRendererSupported(){const e=this._mediaConfig?.webcv?.webGLUnsupportedRenderers??[];let t=!1;try{const i=document.createElement("canvas").getContext("webgl"),n=i?.getExtension("WEBGL_debug_renderer_info"),r=n&&i?.getParameter(n.UNMASKED_RENDERER_WEBGL);return r&&!e.some((e=>e===r))?t=!0:this._logger.info(`Unsupported renderer: ${bc(r)}`),t}catch(e){return this._logger.warn(`Error trying to check compatibility: ${JSON.stringify(e)}`),!1}}_isWebGL2Supported(){try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return this._logger.info("WebGL2 context is not supported"),!1;const t=e.getSupportedExtensions(),i=this._mediaConfig?.webcv?.webGLRequiredExtensions.filter((e=>!t?.includes(e)));if(i.length>0)return this._logger.info(`Unsupported WebGL2 extensions: ${bc(i)}`),!1}catch(e){return this._logger.error(`isWebGL2Supported: ${bc(e)}`),!1}return!0}async _isWasmAudioEffectSupported(){return window.AudioWorkletNode?!!window.WebAssembly||(this._logger.info("WebAssembly is not supported"),!1):(this._logger.info("AudioWorkletNode is not supported"),!1)}}const lv=[{acsEffect:"Off",tsCallingEffect:0},{acsEffect:"BackgroundBlur",tsCallingEffect:1},{acsEffect:"BackgroundReplacement",tsCallingEffect:16}];class cv{constructor(e){this._tsCall=e,this._activeParticipantMris=new Set,this._participantMriToSourceId=new Map,this._sourceIdToParticipantMri=new Map,this._sourceIdToParticipantId=new Map,this._listenerHandles=[],this._eventEmitter=new Kp.EventEmitter,this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e),this._eventEmitter.emit("participantAdded",e.id)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._activeParticipantMris.has(e.id)&&this._updateMapping(e)&&this._eventEmitter.emit("participantUpdated",e.id)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._activeParticipantMris.delete(e.id),this._removeMapping(e),this._eventEmitter.emit("participantRemoved",e.id)}))),this._tsCall.participants.forEach((e=>{this._activeParticipantMris.add(e.id),this._updateMapping(e)}))}_updateMapping(e){const t=e.id,i=[];e.endpoints?.endpointDetails?.forEach((e=>{const t=e.mediaStreams?.find((e=>"data"===e.type));t&&(i.push(t.sourceId),this._sourceIdToParticipantId.set(t.sourceId,e.participantId))}));const n=this._participantMriToSourceId.get(t);return i.sort(),!g.isEqual(i,n)&&(this._participantMriToSourceId.set(t,i),i.forEach((e=>{this._sourceIdToParticipantMri.set(e,t)})),!0)}_removeMapping(e){const t=e.id,i=this._participantMriToSourceId.get(t)||[];this._participantMriToSourceId.delete(t),i.forEach((e=>{this._sourceIdToParticipantMri.delete(e),this._sourceIdToParticipantId.delete(e)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}findParticipantMri(e){let t=this._sourceIdToParticipantMri.get(e);return void 0===t&&this.isP2P()&&this._tsCall.participants.length&&(t=this._tsCall.participants[0].id),t}findParticipantId(e){let t=this._sourceIdToParticipantId.get(e);if(void 0===t&&this.isP2P()&&this._tsCall.participants.length&&this._tsCall.participants[0].endpoints?.endpointDetails.length){const e=this._tsCall.participants[0].endpoints?.endpointDetails[0];t=e.participantId}return t}findSourceIds(e){return this._participantMriToSourceId.get(e)??[]}isP2P(){return 1===this._tsCall.callType}dispose(){this._activeParticipantMris.clear(),this._participantMriToSourceId.clear(),this._sourceIdToParticipantMri.clear(),this._sourceIdToParticipantId.clear(),this._listenerHandles.forEach((e=>e.dispose())),this._eventEmitter.removeAllListeners()}}const dv=2147483648,uv=65535,hv=1024,pv=4294967295;function gv(e,t){return new b({defaultError:f.FEATURES.DATA_CHANNEL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[t,e]})}function mv(e,t){return new b({defaultError:f.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_TYPE,defaultErrorMessageArgs:[e,t]})}function fv(e,t){return new b({defaultError:f.FEATURES.DATA_CHANNEL.WRONG_ARGUMENT_VALUE,defaultErrorMessageArgs:[e,t]})}function vv(){return new b({defaultError:f.FEATURES.DATA_CHANNEL.NO_AVAILABLE_CHANNEL_ID})}function Sv(){return new b({defaultError:f.FEATURES.DATA_CHANNEL.INVALID_CHANNEL_ID})}function yv(){return new b({defaultError:f.FEATURES.DATA_CHANNEL.TOO_MANY_PARTICIPANTS})}function Cv(){return new b({defaultError:f.FEATURES.DATA_CHANNEL.NO_AVAILABLE_UNRELIABLE_CHANNEL})}function _v(){return new b({defaultError:f.FEATURES.DATA_CHANNEL.TRAFFIC_LIMITED})}function Ev(e){return e?.message??"Unknown"}function Tv(e,t,i){const n=i.value;return i.value=function(...e){try{return n?.apply(this,e)}catch(e){throw this?._logger?.error(`${t}: ${Ev(e)}`),e}},i}class bv{constructor(){this._firstByte=0,this._channelVersion=0,this._channelId=0,this._sequenceNumber=0}static parse(e){if(e.length<bv.headerLength)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.INVALID_MSG_LENGTH});const t=new DataView(e.buffer),i=t.getUint8(0),n=t.getUint8(1),r=t.getUint16(2),a=t.getUint32(4),s=e.slice(bv.headerLength),o=new bv;return o._firstByte=i,o._channelVersion=n,o._channelId=r,o._sequenceNumber=a,o._data=s,o._serializedData=e,o}static create(e,t,i,n){const r=new bv,a=new Uint8Array(bv.headerLength+n.length),s=new DataView(a.buffer);return t&=255,e&=65535,i>>>=0,s.setUint8(0,0),s.setUint8(1,t),s.setUint16(2,e),s.setUint32(4,i),a.set(n,bv.headerLength),r._channelVersion=t,r._channelId=e,r._sequenceNumber=i,r._data=n,r._serializedData=a,r}get channelId(){return this._channelId}set channelId(e){this._channelId=e}get channelVersion(){return this._channelVersion}get sequenceNumber(){return this._sequenceNumber}get data(){return this._data}get serializedData(){return this._serializedData}isInternal(){return!!(128&this._firstByte)}isEmpty(){return 0===this._data.length}}var Iv;bv.headerLength=8,(Iv=e.DataChannelState||(e.DataChannelState={}))[Iv.Initializing=0]="Initializing",Iv[Iv.Initialized=1]="Initialized",Iv[Iv.Started=2]="Started",Iv[Iv.Stopped=3]="Stopped",Iv[Iv.Destroyed=4]="Destroyed";class wv{constructor(t,i){this._eventEmitter=new Kp.EventEmitter,this._state=e.DataChannelState.Initializing,this._tsCall=t,this._dataId=i}async initialize(){const t={onStarted:async(t,i,n)=>{this._dataSendFunction=i,this._getStats=n,this._state=e.DataChannelState.Started,this._eventEmitter.emit("stateChanged",this._state)},onStopped:async t=>{this._dataSendFunction=void 0,this._getStats=void 0,this._state=e.DataChannelState.Stopped,this._eventEmitter.emit("stateChanged",this._state)},onDataReceived:async(e,t,i)=>{const n={sourceId:i,data:t};this._eventEmitter.emit("message",n)}};await(this._tsCall.dataChannelAdapter?.addHandler(this._dataId,t)),this._state<e.DataChannelState.Initialized&&(this._state=e.DataChannelState.Initialized)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}send(e,t){return this._dataSendFunction?this._dataSendFunction(e,t):Promise.reject(new b({defaultError:f.FEATURES.DATA_CHANNEL.SENDER_NOT_READY}))}getStats(){return this._getStats?this._getStats():Promise.resolve({bufferSize:0,remainingBytes:0,remainingPackets:0})}get state(){return this._state}dispose(){if(this._state===e.DataChannelState.Destroyed)return;const t=this._state;this._state=e.DataChannelState.Destroyed,this._dataSendFunction=void 0,this._getStats=void 0,t!==e.DataChannelState.Initializing&&this._tsCall.dataChannelAdapter?.removeHandler(this._dataId).catch(Oc),this._eventEmitter.emit("stateChanged",this._state),this._eventEmitter.removeAllListeners()}}class Rv{constructor(e,t,i){const n=e.dataId;this._logger=i.createChild(`DataChannelProcessor(${n})`),this._eventEmitter=new wm(this._logger,{enableLogOn:!1,enableLogOff:!1,enableLogOnce:!1,enableLogEmit:!1}),this._bufferFullErrorMessage=`dataId ${n} send queue is full`,this._dataChannelAdapter=new wv(t,n),this._dataChannelAdapter.on("message",(e=>{try{const t=e.sourceId,i=bv.parse(e.data),n={sourceId:t,message:i};i.isInternal()?this._eventEmitter.emit("internalMessage",n):this._eventEmitter.emit("message",n)}catch(e){this._logger.error(`process message error: ${Ev(e)}`)}}))}async initialize(){await this._dataChannelAdapter.initialize()}async send(e){try{if(void 0===e.recipients)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.NO_VALID_PARTICIPANT});if(e.recipients.length>64)throw yv();await this._dataChannelAdapter.send(e.data,e.recipients)}catch(e){throw e?.message===this._bufferFullErrorMessage?new b({defaultError:f.FEATURES.DATA_CHANNEL.BUFFER_FULL}):new b({defaultError:f.FEATURES.DATA_CHANNEL.SEND_FAIL,originalError:e})}}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._dataChannelAdapter.dispose()}}class Av{constructor(e){this._sourceIds=[],this._participantMappingManager=e,this._participantMapping=new Map,e.on("participantAdded",(e=>{if(this._participantMapping.has(e)){const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t),this._updateSourceIds()}})),e.on("participantUpdated",(e=>{if(this._participantMapping.has(e)){const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t),this._updateSourceIds()}})),e.on("participantRemoved",(e=>{this._participantMapping.has(e)&&(this._participantMapping.set(e,[]),this._updateSourceIds())}))}get sourceIds(){if(this._participantMappingManager.isP2P()||!(this._participantMapping.size>0)||0!==this._sourceIds.length)return this._sourceIds}setParticipants(e){const t=[];e.forEach((e=>{oc(e),t.push(rc(e))})),this._participantMapping.clear(),t.forEach((e=>{const t=this._participantMappingManager.findSourceIds(e);this._participantMapping.set(e,t)})),this._updateSourceIds()}_updateSourceIds(){this._sourceIds=Array.from(this._participantMapping.values()).flat()}}var Pv,Mv=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},kv=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};!function(e){e[e.Open=0]="Open",e[e.Closed=1]="Closed",e[e.Destroyed=2]="Destroyed"}(Pv||(Pv={}));class Dv{constructor(e,t,i,n,r,a){this._state=Pv.Open;const s=yc().dataChannel;this._eventEmitter=new Kp.EventEmitter,this._channelId=e,this._channelVersion=t,this._sequenceNumber=Math.floor(Math.random()*(pv+1)),this._recipientsManager=new Av(n),this._dataChannelMonitor=r,this._sendMessageFunction=i,this._maxMessageSize=s.maxMessageSize,this._logger=a.createChild(`DataChannelSender(${e},${t})`),this._logger.info("opened")}get channelId(){return this._channelId}get maxMessageSize(){return this._maxMessageSize}setParticipants(e){if(!Array.isArray(e))throw mv("participants","CommunicationIdentifier[]");if(e.length>64)throw yv();this._recipientsManager.setParticipants(e),this._logger.info(`participant size: ${e.length}`)}async sendMessage(e){if(this._dataChannelMonitor.updateAttemptStats(e.length),!(e instanceof Uint8Array))throw mv("data","Uint8Array");if(this._state===Pv.Closed)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.SENDER_CLOSED});if(0===e.length)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.MSG_DATA_EMPTY});if(e.length>this._maxMessageSize)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.MSG_DATA_TOO_LARGE});const t=this._recipientsManager.sourceIds;await this._sendMessage(e,t),this._dataChannelMonitor.updateCommitStats(e.length)}close(){this._state<Pv.Closed&&(this._sendMessage(new Uint8Array,[]).catch(Oc),this._state=Pv.Closed,this._eventEmitter.emit("close"),this._logger.info("closed"),this._dataChannelMonitor.close())}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this.close(),this._state!==Pv.Destroyed&&(this._eventEmitter.removeAllListeners(),this._state=Pv.Destroyed,this._logger.info("disposed"))}get channelVersion(){return this._channelVersion}get state(){return this._state}async _sendMessage(e,t){const i=bv.create(this._channelId,this._channelVersion,this._sequenceNumber,e);this._sequenceNumber=(this._sequenceNumber+1)%(pv+1);const n={channelId:this._channelId,channelVersion:this._channelVersion,recipients:t,data:i.serializedData};await this._sendMessageFunction(n)}}Mv([Tv,kv("design:type",Function),kv("design:paramtypes",[Array]),kv("design:returntype",void 0)],Dv.prototype,"setParticipants",null),Mv([function(e,t,i){const n=i.value;return i.value=async function(...e){try{return await(n?.apply(this,e))}catch(e){throw this?._logger?.error(`${t}: ${Ev(e)}`),e}},i},kv("design:type",Function),kv("design:paramtypes",[Uint8Array]),kv("design:returntype",Promise)],Dv.prototype,"sendMessage",null),Mv([Tv,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Dv.prototype,"close",null),Mv([Tv,kv("design:type",Function),kv("design:paramtypes",[]),kv("design:returntype",void 0)],Dv.prototype,"dispose",null);class Ov{constructor(e){this.value=e,this.next=void 0}}class Nv{constructor(){this.length=0,this.front=void 0,this.rear=void 0}enqueue(e){const t=new Ov(e);this.front?(this.rear.next=t,this.rear=t):(this.front=t,this.rear=t),this.length++}dequeue(){if(!this.front)return;const e=this.front;return this.front===this.rear?(this.front=void 0,this.rear=void 0):this.front=this.front.next,this.length--,e.value}peek(){return this.front?.value}size(){return this.length}back(){return this.rear?.value}isEmpty(){return 0===length}clear(){this.front=void 0,this.rear=void 0,this.length=0}}var Lv,xv=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Fv=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};!function(e){e[e.Open=0]="Open",e[e.Closed=1]="Closed",e[e.Destroyed=2]="Destroyed"}(Lv||(Lv={}));class Uv{constructor(e,t,i,n,r,a){this._receiveBuffers=new Nv,this._remainingBytes=0,this._state=Lv.Open,this._channelVersion=0;const s=yc().dataChannel;this._logger=a.createChild(`DataChannelReceiver(${e},${n},${i})`),this._eventEmitter=new wm(this._logger,{enableLogEmit:!1}),this._maxBufferSize=s.maxReceiveBufferSize,this._dataChannelMonitor=r,this._channelId=e,this._senderParticipantIdentifier=ac(t),this._channelVersion=n,this._lastMessageTimestamp=Date.now(),this._logger.info("created.")}get channelId(){return this._channelId}get senderParticipantIdentifier(){return this._senderParticipantIdentifier}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}readMessage(){const e=this._receiveBuffers.dequeue();return e?.data&&(this._remainingBytes-=e.data.length),e}dispose(){this._state!==Lv.Destroyed&&(this.close(),this._state=Lv.Destroyed,this._receiveBuffers.clear(),this._eventEmitter.removeAllListeners())}close(){this._state===Lv.Open&&(this._state=Lv.Closed,this._eventEmitter.emit("close"),this._dataChannelMonitor.close())}get channelVersion(){return this._channelVersion}get lastMessageTimestamp(){return this._lastMessageTimestamp}get state(){return this._state}appendMessage(e){if(this._dataChannelMonitor.updateAttemptStats(e.data.length),this._state!==Lv.Open)return;if(0===e.data.length)return void this.close();if(this._lastMessageTimestamp=Date.now(),this._remainingBytes+e.data.length>this._maxBufferSize)return;const t={sequenceNumber:e.sequenceNumber,data:e.data};this._receiveBuffers.enqueue(t),this._remainingBytes+=e.data.length,this._eventEmitter.emit("messageReady"),this._dataChannelMonitor.updateCommitStats(e.data.length)}}xv([Tv,Fv("design:type",Function),Fv("design:paramtypes",[]),Fv("design:returntype",Object)],Uv.prototype,"readMessage",null),xv([Tv,Fv("design:type",Function),Fv("design:paramtypes",[bv]),Fv("design:returntype",void 0)],Uv.prototype,"appendMessage",null);class Bv{constructor(e,t,i){this._timeoutHandle=0;const n=yc().dataChannel;this._eventEmitter=new Kp.EventEmitter,this._participantMappingManager=e,this._dataChannelMonitor=t,this._logger=i,this._receivers=new Map,this._lastestVersion=new Map,this._receiveTimeoutInMs=n.receiveTimeoutInMs}_checkTimeoutReceivers(){Array.from(this._receivers.keys()).forEach((e=>{const t=this._receivers.get(e);void 0!==t&&Date.now()-t.lastMessageTimestamp>=this._receiveTimeoutInMs&&t.close()})),this._receivers.size>0&&(this._timeoutHandle=window.setTimeout((()=>{this._timeoutHandle=0,this._checkTimeoutReceivers(),Math.ceil(this._receiveTimeoutInMs/2)})))}appendMessage(e){const t=`${e.sourceId},${e.message.channelId}`,i=`${e.sourceId},${e.message.channelId},${e.message.channelVersion}`;let n=this._lastestVersion.get(t),r=this._receivers.get(i);const a=e.message;if(void 0===r){if(void 0!==n&&-1===function(e,t){if(e===t)return 0;if(-1===t)return 1;const i=e-t;return i>0?i<127.5?1:-1:-i>127.5?1:-1}(a.channelVersion,n))return;if(this._lastestVersion.set(t,a.channelVersion),a.isEmpty())return;if(0===this._eventEmitter.listenerCount("dataChannelReceiverCreated"))return;const s=this._participantMappingManager.findParticipantMri(e.sourceId)??"",o=this._participantMappingManager.findParticipantId(e.sourceId)??"",l=this._dataChannelMonitor.createReceiverMonitor(a.channelId,a.channelVersion,o);if(""===s)return void this._logger.info(`Unable to find corresponding sender mri, ignoring the message. channelId:${a.channelId}, sourceId:${e.sourceId}`);this._logger.info(`channelId:${a.channelId} message from ${o}, sourceId:${e.sourceId}, channelVersion:${a.channelVersion}`),r=new Uv(a.channelId,s,e.sourceId,a.channelVersion,l,this._logger),r.on("close",(()=>{this._receivers.delete(i)})),this._receivers.set(i,r),this._eventEmitter.emit("dataChannelReceiverCreated",r),0===this._timeoutHandle&&this._checkTimeoutReceivers()}r.appendMessage(a),a.isEmpty()&&this._receivers.delete(i)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){window.clearTimeout(this._timeoutHandle),this._timeoutHandle=0,this._receivers.forEach(((e,t)=>{e.dispose()})),this._lastestVersion.clear(),this._receivers.clear(),this._eventEmitter.removeAllListeners()}}const Vv=64512;class Hv{constructor(e){this._channelIdsInUse=e}findAvailableChannelId(){if(this._channelIdsInUse.size>=Vv)throw vv();let e;for(;(e=Math.floor(Math.random()*Vv)+hv)&&this._channelIdsInUse.has(e););return e}}class $v{constructor(e){this._availableChannelIds=[],this._channelIdsInUse=e,this._initArray()}findAvailableChannelId(){if(0===this._availableChannelIds.length){if(this._channelIdsInUse.size>=Vv)throw vv();this._initArray()}return this._availableChannelIds.pop()}_initArray(){const e=Array.from(this._channelIdsInUse,(e=>e)).sort();let t=0,i=0;for(;t<=uv&&i<e.length;)t<e[i]?(this._availableChannelIds.push(t),t++):(t>e[i]||t++,i++);for(;t<=uv;)this._availableChannelIds.push(t),t++;this._availableChannelIds=g.shuffle(this._availableChannelIds)}}class Gv{constructor(){this._channelIdsInUse=new Set,this._highWaterMark=Math.ceil(.8*Vv),this._lowWaterMark=Math.floor(.4*Vv),this._strategy=new Hv(this._channelIdsInUse)}addChannelId(e){e>=hv&&e<=uv&&(this._channelIdsInUse.add(e),this._channelIdsInUse.size>=this._highWaterMark&&this._strategy instanceof Hv&&(this._strategy=new $v(this._channelIdsInUse)))}removeChannelId(e){this._channelIdsInUse.delete(e),this._channelIdsInUse.size<this._lowWaterMark&&this._strategy instanceof $v&&(this._strategy=new Hv(this._channelIdsInUse))}findAvailableChannelId(){return this._strategy.findAvailableChannelId()}}class jv{constructor(e){this._dataIds=[],this._channelIds=new Map,e.forEach((e=>{this._dataIds.push({dataId:e.dataId,bandwidth:e.bandwidth,allocatedBandwidth:0})}))}allocate(e){const t=g.maxBy(this._dataIds,(t=>1-(t.allocatedBandwidth+e.bitrate)/t.bandwidth));if(void 0===t)throw new b({defaultError:f.FEATURES.DATA_CHANNEL.NO_AVAILABLE_RELIABLE_CHANNEL});return t.allocatedBandwidth+=e.bitrate,this._channelIds.set(e.channelId,{dataId:t.dataId,allocatedBandwidth:e.bitrate}),t.dataId}deallocate(e){const t=this._channelIds.get(e);if(void 0!==t){const i=this._dataIds.find((e=>e.dataId===t.dataId));void 0!==i&&(i.allocatedBandwidth-=t.allocatedBandwidth),this._channelIds.delete(e)}}getDataIds(e){const t=this._channelIds.get(e);return void 0!==t?[t.dataId]:[]}}class zv{getDataIds(e){throw Cv()}getAllSum(){return 0}}class Wv{constructor(e){this._acsDataIdConfigs=[],this._bandwidthList=[],this._acsDataIdConfigs=e,e.forEach((e=>{this._bandwidthList.push(e.bandwidth/1e3)})),this._allSum=g.sumBy(e,(e=>e.bandwidth))}getDataIds(e){let t=[];const i=Math.ceil(e/1e3);if(i>=this._allSum)t=this._acsDataIdConfigs.map((e=>e.dataId));else{const e=this._bandwidthList[0]-1;let n=0;i&e&&(n=this._bandwidthList.findIndex((e=>!(e&i))),-1!==n&&(t.push(this._acsDataIdConfigs[n].dataId),n++));for(let e=n;e<this._bandwidthList.length;e++)this._bandwidthList[e]&i&&t.push(this._acsDataIdConfigs[e].dataId)}return t}getAllSum(){return this._allSum}}class qv{constructor(e){this._bandwidthMap=new Map,this._bandwidthMap.set(0,[]),function(e){const t=[[]];return e.forEach((e=>{const i=[];t.forEach((t=>{i.push([...t,e])})),t.push(...i)})),t}(e).forEach((e=>{const t=g.sumBy(e,(e=>e.bandwidth)),i=this._bandwidthMap.get(t);(void 0===i||e.length<i.length)&&this._bandwidthMap.set(t,e.map((e=>e.dataId)))})),this._bandwidthList=Array.from(this._bandwidthMap.keys()).sort(((e,t)=>e-t))}getDataIds(e){const t=g.sortedIndex(this._bandwidthList,e),i=this._bandwidthList[t]??this._bandwidthList[this._bandwidthList.length-1];return this._bandwidthMap.get(i)||[]}getAllSum(){return g.last(this._bandwidthList)||0}}class Kv{constructor(e){(e=g.sortBy(e,(e=>e.bandwidth))).length?function(e){if(e.find((e=>!Number.isInteger(Math.log2(e)))))return!1;for(let t=1;t<e.length;t++)if(e[t]!==2*e[t-1])return!1;return!0}(e.map((e=>e.bandwidth/1e3)))?this._dataIdSelectionStrategy=new Wv(e):this._dataIdSelectionStrategy=new qv(e):this._dataIdSelectionStrategy=new zv}getDataIds(e){return this._dataIdSelectionStrategy.getDataIds(e)}getAllSum(){return this._dataIdSelectionStrategy.getAllSum()}}class Jv{constructor(e){this._totalNormalPriorityBandwidth=0,this._totalHighPriorityBandwidth=0,this._configs=new Map,this._currentNormalPriorityDataIds=[],this._currentHighPriorityDataIds=[],this._normalPriorityTable=new Kv(e.filter((e=>"normal"===e.priority))),this._highPriorityTable=new Kv(e.filter((e=>"high"===e.priority)))}allocate(e){this._configs.set(e.channelId,e),"Normal"===e.priority?this._totalNormalPriorityBandwidth+=e.bitrate:"High"===e.priority&&(this._totalHighPriorityBandwidth+=e.bitrate),this._updateDataIds()}deallocate(e){const t=this._configs.get(e);void 0!==t&&(this._configs.delete(e),"Normal"===t.priority?this._totalNormalPriorityBandwidth-=t.bitrate:"High"===t.priority&&(this._totalHighPriorityBandwidth-=t.bitrate),this._updateDataIds())}getDataIds(e){const t=this._configs.get(e);if(void 0!==t){if("Normal"===t.priority)return this._currentNormalPriorityDataIds;if("High"===t.priority)return this._currentHighPriorityDataIds}return[]}_updateDataIds(){const e=this._highPriorityTable.getAllSum(),t=this._totalHighPriorityBandwidth-e;if(t>0){const e=this._totalNormalPriorityBandwidth+t;this._currentNormalPriorityDataIds=this._normalPriorityTable.getDataIds(e),this._currentHighPriorityDataIds=this._highPriorityTable.getDataIds(this._totalHighPriorityBandwidth).concat(this._currentNormalPriorityDataIds)}else this._currentNormalPriorityDataIds=this._normalPriorityTable.getDataIds(this._totalNormalPriorityBandwidth),this._currentHighPriorityDataIds=this._highPriorityTable.getDataIds(this._totalHighPriorityBandwidth)}}class Yv{constructor(e){const t=e.filter((e=>"reliable"===e.category)),i=e.filter((e=>"unicast"===e.category)),n=e.filter((e=>"broadcast"===e.category));this._reliableDataIdManager=new jv(t),this._unicastDataIdManager=new Jv(i),this._broadcastDataIdManager=new Jv(n),this._configs=new Map}allocate(e){let t=-1;if(this._configs.has(e.channelId))throw new b({defaultError:f.FEATURES.DATA_CHANNEL.CHANNEL_ALREADY_ALLOCATED});try{"Durable"===e.reliability?t=this._reliableDataIdManager.allocate(e):(this._unicastDataIdManager.allocate(e),this._broadcastDataIdManager.allocate(e)),this._configs.set(e.channelId,e)}catch(t){throw"Durable"===e.reliability?this._reliableDataIdManager.deallocate(e.channelId):(this._unicastDataIdManager.deallocate(e.channelId),this._broadcastDataIdManager.deallocate(e.channelId)),t}return t}deallocate(e){const t=this._configs.get(e);void 0!==t&&("Durable"===t.reliability?this._reliableDataIdManager.deallocate(e):(this._unicastDataIdManager.deallocate(e),this._broadcastDataIdManager.deallocate(e)),this._configs.delete(e))}getDataIdToSend(e,t,i){const n=this._configs.get(e);if(void 0!==n)return"Durable"===n.reliability?this._reliableDataIdManager.getDataIds(e):i?this._broadcastDataIdManager.getDataIds(e):this._unicastDataIdManager.getDataIds(e);throw function(e){return new b({defaultError:f.FEATURES.DATA_CHANNEL.CANT_FIND_CHANNEL_ID,defaultErrorMessageArgs:[e]})}(e)}}class Qv{constructor(e){this._attemptCount=0,this._attemptBytes=0,this._commitCount=0,this._commitBytes=0,this._dataChannelTelemetryLogger=e,this._openTime=new Date,this._closeTime=this._openTime}updateAttemptStats(e){this._attemptCount++,this._attemptBytes+=e}updateCommitStats(e){this._commitCount++,this._commitBytes+=e}close(){this._closeTime=new Date}}class Zv extends Qv{constructor(e,t,i,n){super(n),this._channelId=e,this._channelVersion=t,this._correlationId=i}close(){super.close();const e={direction:"send",channelId:this._channelId,channelVersion:this._channelVersion,openTime:this._openTime,closeTime:this._closeTime,attemptCount:this._attemptCount,attemptBytes:this._attemptBytes,commitCount:this._commitCount,commitBytes:this._commitBytes,correlationId:this._correlationId};this._dataChannelTelemetryLogger.sendStatsEvent(e)}}class Xv extends Qv{constructor(e,t,i,n){super(n),this._channelId=e,this._channelVersion=t,this._remoteParticipantId=i}close(){super.close();const e={direction:"recv",channelId:this._channelId,channelVersion:this._channelVersion,openTime:this._openTime,closeTime:this._closeTime,attemptCount:this._attemptCount,attemptBytes:this._attemptBytes,commitCount:this._commitCount,commitBytes:this._commitBytes,remoteParticipantId:this._remoteParticipantId};this._dataChannelTelemetryLogger.sendStatsEvent(e)}}class eS{constructor(e){this._dataChannelTelemetryLogger=e}createSenderMonitor(e,t,i){return new Zv(e,t,i,this._dataChannelTelemetryLogger)}createReceiverMonitor(e,t,i){return new Xv(e,t,i,this._dataChannelTelemetryLogger)}}class tS{constructor(e){this._timeBucket=0,this._maxPacketRate=0,this._packetCount=0,this._maxPacketRate=e}canSend(e){let t=Math.ceil(e/1200);const i=window.performance.now();return Math.floor(i/1e3)==this._timeBucket&&(t+=this._packetCount),t<=this._maxPacketRate}update(e){let t=Math.ceil(e/1200);const i=window.performance.now(),n=Math.floor(i/1e3);n!==this._timeBucket&&(this._timeBucket=n,this._packetCount=0),this._packetCount+=t}}class iS{constructor(e){this._endTime=0,this._maxDataRate=0,this._maxDataRate=e/8}canSend(e){if(0===this._maxDataRate)return!0;const t=window.performance.now(),i=(this._endTime-t)/1e3;return!(i>0)||i+e/this._maxDataRate<=1}update(e){const t=window.performance.now(),i=this._maxDataRate?e/this._maxDataRate*1e3:0;this._endTime<t?this._endTime=t+i:this._endTime+=i}changeBitrate(e){this._maxDataRate=e/8}}class nS{constructor(){this._totalBytes=0,this._lastUpdateTime=window.performance.now(),this._lastUpdateBytes=0,this._currentBitrate=0}getBitrate(){return this._currentBitrate}update(e){this._totalBytes+=e}calculateBitrate(){const e=window.performance.now();e-this._lastUpdateTime>0&&(this._currentBitrate=8*(this._totalBytes-this._lastUpdateBytes)/(e-this._lastUpdateTime)),this._lastUpdateTime=e,this._lastUpdateBytes=this._totalBytes}}class rS{constructor(e,t){this._availableBytes=0,this._reducedBytes=0,this._lastUpdateTime=window.performance.now(),this._packetRateLimiter=new tS(t),this._receiveBitrate=new nS,this._bitrateTimer=window.setInterval((()=>{this._receiveBitrate.calculateBitrate();const t=window.performance.now(),i=(t-this._lastUpdateTime)/1e3;this._availableBytes=e/8*i,this._reducedBytes=.8*this._receiveBitrate.getBitrate()/8*i,this._lastUpdateTime=t}),1e3)}canSend(e,t){return t?!!this._packetRateLimiter.canSend(e)&&this._availableBytes-this._reducedBytes>=e:this._availableBytes>=e}updateSendBytes(e,t){t&&this._packetRateLimiter.update(e),this._availableBytes-=e}updateReceiveBytes(e){this._receiveBitrate.update(e)}dispose(){window.clearInterval(this._bitrateTimer)}}var aS,sS;!function(e){e[e.Initializing=0]="Initializing",e[e.Initialized=1]="Initialized",e[e.Destroyed=2]="Destroyed"}(aS||(aS={}));class oS{constructor(e,t,i){this._state=aS.Initializing,this._initializedDefer=kh();const n=yc();this._logger=t,this._tsCall=e,this._dataChannelTelemtryLogger=i,this._participantMappingManager=new cv(e),this._dataChannelMonitor=new eS(i),this._senders=new Map,this._receiversManager=new Bv(this._participantMappingManager,this._dataChannelMonitor,t),this._processors=new Map,this._channelVersions=new Map,this._randomChannelIdManager=new Gv,this._dataIds=new Map,n.dataChannel.dataIdConfigs.forEach((e=>{const t=this._dataIds.get(e.dataId)??[];t.push(e.raw?{dataId:e.dataId,raw:e.raw}:{dataId:e.dataId,raw:e.raw,bandwidth:e.bandwidth??0,priority:e.priority??"normal",category:e.category??"reliable"}),this._dataIds.set(e.dataId,t)})),this._rateLimiters=new Map,this._sendTrafficLimiter=new rS(n.dataChannel.maxSendBandwidth,n.dataChannel.maxBroadcastPacketRate),this._enableBroadcastLimitOnReliableChannel=n.dataChannel.enableBroadcastLimitOnReliableChannel}async initialize(){const e=async e=>{const t=new Rv(e,this._tsCall,this._logger);return t.on("message",(t=>{const i=t.message;e.raw?i.channelId=e.dataId+dv:this._sendTrafficLimiter.updateReceiveBytes(i.data.length);try{this._receiversManager.appendMessage(t)}catch(t){this._logger.error(`Failed to appendMessage on dataId ${e.dataId}: ${Ev(t)}`)}})),await t.initialize(),t},t=[],i=new Map,n=Array.from(this._dataIds.keys());for(let r=0;r<n.length;r++){const a=n[r],s=this._dataIds.get(a)[0];try{const t=await e(s);i.set(a,t)}catch(i){t.push(a),this._dataIds.delete(a)}}const r=g.flatten(Array.from(this._dataIds.values())).filter((e=>!e.raw));this._dataIdMappingManager=new Yv(r),this._state===aS.Initializing?(this._processors=i,r.forEach((e=>{this._rateLimiters.has(e.dataId)||this._rateLimiters.set(e.dataId,new iS(e.bandwidth))})),t.length&&this._dataChannelTelemtryLogger.sendCreateProcessorEvent({kindOfEvent:"failure",dataIds:t}),this._state=aS.Initialized,this._initializedDefer.resolve()):i.forEach((e=>{e.dispose()}))}createSender(e,t){let i=e.channelId,n=!1;if(i>=dv){if(!0!==this._dataIds.get(i-dv)?.[0].raw)throw Sv();n=!0}else{if(i<0||i>uv)throw Sv();0===i&&(i=this._randomChannelIdManager.findAvailableChannelId())}this._senders.get(i)?.close();const r=function(e){return 255===e?0:e+1}(this._channelVersions.get(i)??-1);let a=i>=dv?i-dv:-1,s=!1;-1===a&&this._state===aS.Initialized&&(a=this._dataIdMappingManager.allocate({channelId:i,reliability:e.reliability,priority:e.priority,bitrate:1e3*e.bitrateInKbps}),s=!0);const o=this._dataChannelMonitor.createSenderMonitor(i,r,t),l=new Dv(i,r,(async t=>{const r=t.data.length;if(-1===a&&!s){if(8===r)return;await this._initializedDefer.promise,s||(a=this._dataIdMappingManager.allocate({channelId:i,reliability:e.reliability,priority:e.priority,bitrate:1e3*e.bitrateInKbps}),s=!0)}const o=0===t.recipients?.length&&!this._participantMappingManager.isP2P();if(-1!==a)if(this._enableBroadcastLimitOnReliableChannel&&o&&!n){if(!this._sendTrafficLimiter.canSend(r,o))throw _v();const e=this._processors.get(a);await(e?.send(t)),this._sendTrafficLimiter.updateSendBytes(r,o)}else{const e=this._processors.get(a);await(e?.send(t))}else{const n=this._dataIdMappingManager.getDataIdToSend(i,r,o);try{const i=!this._sendTrafficLimiter.canSend(r,o);if(i&&"High"!==e.priority)throw _v();if(0===n.length)throw Cv();for(let e=0;e<n.length;e++)try{const a=n[e],s=this._dataIds.get(a)[0];if(i&&"normal"===s.priority)continue;const l=this._rateLimiters.get(a);if(l?.canSend(r)??1){const e=this._processors.get(a);return await(e?.send(t)),l?.update(r),void this._sendTrafficLimiter.updateSendBytes(r,o)}}catch(e){}throw _v()}catch(e){this._logger.error(`Failed to send channelId ${i} message: ${Ev(e)}`)}}}),this._participantMappingManager,o,this._logger);return l.on("close",(()=>{s&&this._dataIdMappingManager.deallocate(i),this._randomChannelIdManager.removeChannelId(i),this._senders.delete(i),setTimeout((()=>l.dispose()),0)})),void 0!==e.participants&&l.setParticipants(e.participants),this._senders.set(i,l),this._randomChannelIdManager.addChannelId(i),this._channelVersions.set(i,r),l}on(e,t){"dataChannelReceiverCreated"===e&&this._receiversManager.on("dataChannelReceiverCreated",t)}off(e,t){"dataChannelReceiverCreated"===e&&this._receiversManager.off("dataChannelReceiverCreated",t)}dispose(){this._state!==aS.Destroyed&&(this._state=aS.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(new b({defaultError:f.FEATURES.DATA_CHANNEL.DISPOSED})),this._senders.forEach((e=>{e.dispose()})),this._receiversManager.dispose(),this._processors.forEach((e=>{e.dispose()})),this._sendTrafficLimiter.dispose(),this._participantMappingManager.dispose())}}class lS{constructor(e,t){this._tsCall=e,this._telemetryLogManager=t}sendStatsEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,...e};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_datachannel_stats,tenant:hl,properties:t})}sendCreateSenderEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createSender",...e};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_datachannel,tenant:hl,properties:t})}sendCreateProcessorEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,operation:"createProcessor",...e};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_datachannel,tenant:hl,properties:t})}}class cS{constructor(e){this.typeRankComparator=(e,t)=>void 0===e.publishedState?-1:void 0===t.publishedState?1:e.publishedState.typeRank-t.publishedState.typeRank,this._eventEmitter=e,this._currentSpotlightStates=new Map;const t=yc().calling.spotlight;this._maxSpotlightStateSupported=t.maxSpotlightParticipants,this._supportedUserRoles=t.supportedRoles,this._meetingTypes=t.meetingTypes}initialize(e,t,i,n){this._logger=n.createChild((()=>`SpotlightFeature::Call(id='${e.callId}')`)),this._tsCall=e,this._telemetryLogManager=i,this._internalCallAgent=t;const r="initialize";this._sendFeatureUsage(r,Yh.initialize);try{let e=e=>new Map(this.getPublishedState(e).sort(this.typeRankComparator).map(((e,t)=>[e.id,{spotlightStateId:e.publishedState?.stateId,index:t+1}])));this._tsCall.on("publishedStatesChanged",(async t=>{let i=e(t),n=[];i.forEach(((e,t)=>{this._currentSpotlightStates.has(t)||n.push({identifier:ac(t),order:e?.index})}));let r=[];this._currentSpotlightStates.forEach(((e,t)=>{i.has(t)||r.push({identifier:ac(t)})})),this._currentSpotlightStates=i,(n.length||r.length)&&this._eventEmitter.emit("spotlightChanged",{added:n,removed:r})})),this._tsCall.publishedStates&&(this._currentSpotlightStates=e(this._tsCall.publishedStates)),this._sendFeatureUsage(r,Yh.success)}catch(e){this.handleSpotlightFailure(r,e)}}async startSpotlight(e){const t="startSpotlight";try{this._sendFeatureUsage(t,Yh.attempt);let i=this.getIdentifiersMri(e).filter((e=>!this._currentSpotlightStates.has(e)));if(!i.length)throw new b({defaultError:f.FEATURES.SPOTLIGHT.ALREADY_SPOTLIGHTED});this.validateStartSpotlightConditions(i);const n={level:"user",type:"spotlight",content:"{}",participantIds:i};if(!await this._tsCall.publishState(n,m.generateCauseId()))throw new b({defaultError:f.FEATURES.SPOTLIGHT.START_SPOTLIGHT_FAILED});this._sendFeatureUsage(t,Yh.success)}catch(e){this.handleSpotlightFailure(t,e)}}async stopSpotlight(e){const t="stopSpotlight";this._tsCall.publishedStates||this._logger.warn(`${t}: no participants is currently Spotlighted`);try{this._sendFeatureUsage(t,Yh.attempt);let i=this.getIdentifiersMri(e);this.validateStopSpotlightConditions(i);const n=this.findStateIdsForParticipantIds(i);await this._tsCall.removeState({stateIds:n},m.generateCauseId()),this._sendFeatureUsage(t,Yh.success)}catch(e){this.handleSpotlightFailure(t,e)}}async stopAllSpotlight(){const e="stopAllSpotlight";try{this._sendFeatureUsage(e,Yh.attempt),this.validateStopSpotlightConditions([]),await this._tsCall.removeStatesForEveryone({type:"spotlight"},m.generateCauseId()),this._sendFeatureUsage(e,Yh.success)}catch(t){this.handleSpotlightFailure(e,t)}}get spotlightedParticipants(){return this._tsCall.publishedStates?Array.from(this._currentSpotlightStates.keys()).map((e=>({identifier:ac(e),order:this._currentSpotlightStates.get(e)?.index}))):[]}get maxSpotlightStateSupported(){return this._maxSpotlightStateSupported}findStateIdsForParticipantIds(e){return e.length&&this._tsCall.publishedStates?e.map((e=>this._currentSpotlightStates.get(e)?.spotlightStateId||"")).filter((e=>e.length)):[]}getPublishedState(e){return e.typeStates.filter((e=>"spotlight"===e.type)).map((e=>e.participantStates)).flat()}isUserRoleEligible(){const e=this._tsCall.advancedMeetingRole;return!!e&&!!this._supportedUserRoles.find((t=>t===e))}isRoleBasedConversationType(){const e=this._tsCall.conversationType;return!!e&&!!this._meetingTypes.find((t=>t===e))}getIdentifiersMri(e){return e&&e?.length?e.map((e=>rc(e))):[this._internalCallAgent.getUserMri()]}validateStartSpotlightConditions(e){if(this.spotlightedParticipants.length+e.length>this._maxSpotlightStateSupported)throw new b({defaultError:f.FEATURES.SPOTLIGHT.SPOTLIGHT_LIGHT_MAX_REACHED,defaultErrorMessageArgs:[this._maxSpotlightStateSupported]});if(this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new b({defaultError:f.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Start",this._tsCall.conversationType]})}validateStopSpotlightConditions(e){if((1!==e.length||e[0]!==this._internalCallAgent.getUserMri())&&this.isRoleBasedConversationType()&&!this.isUserRoleEligible())throw new b({defaultError:f.FEATURES.SPOTLIGHT.UNSUPPORTED_ROLE_TYPE,defaultErrorMessageArgs:["Stop",this._tsCall.conversationType]})}handleSpotlightFailure(e,t){throw this._logger.error(JSON.stringify(t)),this._sendFeatureUsage(e,Yh.failure,t),t}_sendFeatureUsage(e,t,i){let n=i?{code:i?.code||_,subCode:i?.subCode||0,failureReason:i?.message||"",...xg(i)}:void 0;bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Spotlight",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}class dS{initialize(e,t,i,n,r){this._tsCall=e,this._telemetryLogManager=n,this._logger=r}async submitSurvey(e){const t=+new Date,i=x();this.sendEndOfCallEvent("attempt",i);const n=this.validateSurvey(e);if(n){const e=new b({defaultError:f.FEATURES.CALL_SURVEY.INVALID_SURVEY,defaultErrorMessageArgs:[n]});throw this.sendEndOfCallEvent("failure",i,t,{failureReason:n,code:v,...xg(e),isExpected:!0}),e}return new Promise(((n,r)=>{const a=this.createCallSurveyInternal(e);this.registerNotificationEventListener(a,i,t,n,r),this.sendEndOfCallEvent("success",i,t,void 0,a)}))}registerNotificationEventListener(e,t,i,n,r){const a={id:t,callId:e.callId,localParticipantId:e.localParticipantId,overallRating:e.overallRating,audioRating:e.audioRating,videoRating:e.videoRating,screenshareRating:e.screenshareRating};dS.NOTIFICATION_LISTENER.eventsSent=e=>{e.find((e=>e.name===Jh.acs_calling_survey&&e.data?.correlationId===t&&"success"===e.data?.kindOfEvent))&&n(a)},dS.NOTIFICATION_LISTENER.eventsDiscarded=(e,n)=>{if(e.find((e=>e.name===Jh.acs_calling_survey&&e.data?.correlationId===t&&"success"===e.data?.kindOfEvent))){const e=new b({defaultError:f.FEATURES.CALL_SURVEY.SUBMIT_TIMEOUT});this.sendEndOfCallEvent("failure",t,i,{failureReason:e.message,code:e.code,...xg(e)}),r(e)}}}sendEndOfCallEvent(e,t,i,n,r){try{const a={eventName:Jh.acs_calling_survey,callId:this._tsCall?.callId,localParticipantId:this._tsCall?.participantId,correlationId:t,kindOfEvent:e,timestampInfo:{deltaTimeInMs:0},additionalDetails:n};if(i){const e=+new Date;a.timestampInfo.deltaTimeInMs=e-i}"success"===e&&r?(a.overallRating=r.overallRating,a.audioRating=r.audioRating,a.videoRating=r.videoRating,a.screenshareRating=r.screenshareRating,this._telemetryLogManager.sendEvent({name:Jh.acs_calling_survey,tenant:hl,priority:ln,properties:a},dS.NOTIFICATION_LISTENER)):this._telemetryLogManager.sendEvent({name:a.eventName,tenant:hl,properties:a})}catch(e){this._logger.debug("Unable to send call survey telemetry")}}createCallSurveyInternal(e){let t={callId:this._tsCall?.callId,localParticipantId:this._tsCall?.participantId};return e&&(t.overallRating=e.overallRating,t.audioRating=e.audioRating,t.videoRating=e.videoRating,t.screenshareRating=e.screenshareRating),t}validateSurvey(e){let t="";return t=this.validateOverallRating(e.overallRating),t+=this.validateAudioRating(e.audioRating),t+=this.validateVideoRating(e.videoRating),t+=this.validateScreenshareRating(e.screenshareRating),""!==t||e.overallRating||e.audioRating||e.videoRating||e.screenshareRating||(t="At least one survey rating is required."),""===t&&(t=this.validateCallSurveyTypes(e)),t.trim()}validateOverallRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(dS.OVERALL_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("overallRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("overallRating.scale",e)):t=this.defaultRatingScaleMessage(dS.OVERALL_RATING_SCORE),t}validateAudioRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(dS.AUDIO_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("audioRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("audioRating.scale",e)):t=this.defaultRatingScaleMessage(dS.AUDIO_RATING_SCORE),t}validateVideoRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(dS.VIDEO_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("videoRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("videoRating.scale",e)):t=this.defaultRatingScaleMessage(dS.VIDEO_RATING_SCORE),t}validateScreenshareRating(e){if(!e)return"";let t="";return this.isValidFiveStarRating(e)?e.scale&&!this.isRatingValueMatchesRatingScale(e.score,e.scale)?t=this.ratingOutOfRangeMessage(dS.SCREEN_SHARE_RATING_SCORE,e):e.scale&&!this.isValidQualityThreshold(e.scale)?t=this.thresholdOutOfRangeMessage("screenshareRating.scale.lowScoreThreshold",e):e.scale&&!this.isValidRatingScale(e.scale)&&(t=this.ratingScaleOutOfRangeMessage("screenshareRating.scale",e)):t=this.defaultRatingScaleMessage(dS.SCREEN_SHARE_RATING_SCORE),t}validateCallSurveyTypes(e){let t="";return e.overallRating&&(t=this.valueShouldBeNumber(dS.OVERALL_RATING_SCORE,e.overallRating.score),e.overallRating.issues&&(this.isArray(e.overallRating.issues)?e.overallRating.issues.some((e=>dS.OVERALL_ISSUES[e]!==e))&&(t+="overallRating.issues array should be of type OverallIssue. "):t+="overallRating.issues should be of type Array<OverallIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("overallRating.scale",e.overallRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("overallRating",e.overallRating)),e.audioRating&&(t+=this.valueShouldBeNumber(dS.AUDIO_RATING_SCORE,e.audioRating.score),e.audioRating.issues&&(this.isArray(e.audioRating.issues)?e.audioRating.issues.some((e=>dS.AUDIO_ISSUES[e]!==e))&&(t+="audioRating.issues array should be of type AudioIssue. "):t+="audioRating.issues should be of type Array<AudioIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("audioRating.scale",e.audioRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("audioRating",e.audioRating)),e.videoRating&&(t+=this.valueShouldBeNumber(dS.VIDEO_RATING_SCORE,e.videoRating.score),e.videoRating.issues&&(this.isArray(e.videoRating.issues)?e.videoRating.issues.some((e=>dS.VIDEO_ISSUES[e]!==e))&&(t+="videoRating.issues array should be of type VideoIssue. "):t+="videoRating.issues should be of type Array<VideoIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("videoRating.scale",e.videoRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("videoRating",e.videoRating)),e.screenshareRating&&(t+=this.valueShouldBeNumber(dS.SCREEN_SHARE_RATING_SCORE,e.screenshareRating.score),e.screenshareRating.issues&&(this.isArray(e.screenshareRating.issues)?e.screenshareRating.issues.some((e=>dS.SCREENSHARE_ISSUES[e]!==e))&&(t+="screenshareRating.issues array should be of type ScreenshareIssue. "):t+="screenshareRating.issues should be of type Array<ScreenshareIssue>. "),t+=this.ratingScaleShouldNotHaveUnexpectedProperties("screenshareRating.scale",e.screenshareRating.scale),t+=this.ratingShouldNotHaveUnexpectedProperties("screenshareRating",e.screenshareRating)),t}isNumber(e){return null!==e&&"number"==typeof e}isArray(e){return null!==e&&Array.isArray(e)}isValidFiveStarRating(e){return null==e||void 0!==e.scale||e.score>=1&&e.score<=5}isRatingValueMatchesRatingScale(e,t){return e>=t.lowerBound&&e<=t.upperBound}isValidQualityThreshold(e){return e.lowScoreThreshold>=e.lowerBound&&e.lowScoreThreshold<=e.upperBound}isValidRatingScale(e){return e.lowerBound>=0&&e.upperBound<=100}valueShouldBeNumber(e,t){return this.isNumber(t)?"":`${e} should be of type number. `}ratingScaleShouldNotHaveUnexpectedProperties(e,t){let i="";if(!t)return i;for(let n in t)void 0===dS.RATING_SCALE_KEYS[n]&&(i+=`${e} should not have ${n}. `);return i}ratingShouldNotHaveUnexpectedProperties(e,t){let i="";if(!t)return i;for(let n in t)void 0===dS.CALL_RATING_KEYS[n]&&(i+=`${e} should not have ${n}. `);return i}defaultRatingScaleMessage(e){return`In default scale ${e} should be 1 to 5. `}ratingOutOfRangeMessage(e,t){return`${e}: ${t.score} should be between ${t.scale?.lowerBound} and ${t.scale?.upperBound}. `}thresholdOutOfRangeMessage(e,t){return`${e}: ${t.scale?.lowScoreThreshold} should be between ${t.scale?.lowerBound} and ${t.scale?.upperBound}. `}ratingScaleOutOfRangeMessage(e,t){return`${e} lowerBound: ${t.scale?.lowerBound} and upperBound: ${t.scale?.upperBound} should be between 0 and 100. `}}dS.OVERALL_RATING_SCORE="overallRating.score",dS.AUDIO_RATING_SCORE="audioRating.score",dS.VIDEO_RATING_SCORE="videoRating.score",dS.SCREEN_SHARE_RATING_SCORE="screenshareRating.score",dS.NOTIFICATION_LISTENER={},dS.OVERALL_ISSUES={CallCannotInvite:"CallCannotInvite",CallCannotJoin:"CallCannotJoin",CallEndedUnexpectedly:"CallEndedUnexpectedly",HadToRejoin:"HadToRejoin",OtherIssues:"OtherIssues"},dS.AUDIO_ISSUES={AudioInterruption:"AudioInterruption",AudioNoise:"AudioNoise",AudioStoppedUnexpectedly:"AudioStoppedUnexpectedly",DistortedSpeech:"DistortedSpeech",Echo:"Echo",LowVolume:"LowVolume",NoLocalAudio:"NoLocalAudio",NoRemoteAudio:"NoRemoteAudio",OtherIssues:"OtherIssues"},dS.VIDEO_ISSUES={AudioVideoOutOfSync:"AudioVideoOutOfSync",DarkVideoReceived:"DarkVideoReceived",Freezes:"Freezes",LowQuality:"LowQuality",NoVideoReceived:"NoVideoReceived",NoVideoSent:"NoVideoSent",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},dS.SCREENSHARE_ISSUES={CannotPresent:"CannotPresent",Freezes:"Freezes",LargeDelay:"LargeDelay",LowQuality:"LowQuality",NoContentLocal:"NoContentLocal",NoContentRemote:"NoContentRemote",OtherIssues:"OtherIssues",StoppedUnexpectedly:"StoppedUnexpectedly"},dS.CALL_RATING_KEYS={score:"score",issues:"issues",scale:"scale"},dS.RATING_SCALE_KEYS={lowerBound:"lowerBound",upperBound:"upperBound",lowScoreThreshold:"lowScoreThreshold"};class uS{constructor(e,t){this._eventEmitter=e,this._featureName=t}initialize(e,t,i,n,r){this._logger=r.createChild((()=>`${this._featureName}::Call(id='${e.callId}')`)),this._tsCall=e,this._tsCall.changed((()=>{this._logger.log("tsCall changed"),this.updateMeetingGroupDetails()}))}updateAudioZone(e){const t="updateAudioZone_"+x();return this._logger.log(`updateAudioZone toGroup=${e}, causeId=${t}`),this._tsCall.updateMeetingGroups(t,{scope:4,toGroup:e})}dispose(){this._meetingGroupDetails=void 0}get meetingGroupDetails(){return this._meetingGroupDetails}updateMeetingGroupDetails(){const e=this._tsCall.meetingGroupDetails;g.isEqual(e,this._meetingGroupDetails)||(this._meetingGroupDetails=e,this._eventEmitter.emit("meetingGroupDetailsChanged"))}}class hS{constructor(e,t,i){this._featureName=e,this._eventEmitter=t,this._optimalVideoCount=i}initialize(e,t,i,n,r){this._tsCall=e,this._logger=r,this._logger?.createChild((()=>`${this._featureName}::Call(id='${this._tsCall?.callId}')`)),this._tsCall.changed((()=>this.ovcChanged(e)))}ovcChanged(e){e?.optimalVideoCount&&e.optimalVideoCount!==this._optimalVideoCount&&(this._logger.log(`tsCall optimalVideoCount changed from ${this._optimalVideoCount} to ${e?.optimalVideoCount}`),this._eventEmitter.emit("optimalVideoCountChanged"))}}class pS{constructor(e,t){this._effectsStatusManager=e,this._logger=t,this._currentActiveBrowserEffects={},this._updateCurrentActive()}async setBrowserAudioEffects(e,t,i){try{this._updateCurrentActive(t);const n={autoGainControl:void 0!==i.autoGainControl?i.autoGainControl:this._currentActiveBrowserEffects.autoGainControl,echoCancellation:void 0!==i.echoCancellation?i.echoCancellation:this._currentActiveBrowserEffects.echoCancellation,noiseSuppression:void 0!==i.noiseSuppression?i.noiseSuppression:this._currentActiveBrowserEffects.noiseSuppression},r=this._calculateFlags(n);this._logger.info(`Setting browser audio processing flags to ${r}`),await e.setAudioProcessingFlags(r)}catch(e){throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.AUDIO_FLAGS,originalError:e})}}_updateCurrentActive(e){const t=e??this._effectsStatusManager.getActiveEffects();this._currentActiveBrowserEffects={},"BrowserAutoGainControl"===t?.autoGainControl?.[0]&&(this._currentActiveBrowserEffects.autoGainControl=!0),"BrowserEchoCancellation"===t?.echoCancellation?.[0]&&(this._currentActiveBrowserEffects.echoCancellation=!0),"BrowserNoiseSuppression"===t?.noiseSuppression?.[0]&&(this._currentActiveBrowserEffects.noiseSuppression=!0)}_calculateFlags(e){let t=0;return e.autoGainControl&&(t+=1),e.echoCancellation&&(t+=2),e.noiseSuppression&&(t+=4),t}}function gS(e,t){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.EVENT_SUBSCIBE_UNSUBSCRIBE,defaultErrorMessageArgs:[t,e]})}function mS(){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.UNAVAILABLE})}function fS(e){return g.isString(e)?e:e?.message??"Unknown"}function vS(e){throw e instanceof b?e:new b({defaultError:f.FEATURES.UNMIXED_AUDIO.UNKNOWN_ERROR})}function SS(){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.PENDING_OPERATION})}function yS(){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.UNSUPPORTED_OPERATION})}function CS(e){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.INVALID_STATE,defaultErrorMessageArgs:[e]})}function _S(e){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.FAILED_TO_INITIALIZE,originalError:e})}class ES{constructor(e){this._tsCall=e,this._sourceIdMapping=new Map,this._participantIdMapping=new Map,this._listenerHandles=[],this._listenerHandles.push(this._tsCall.on("participantAdded",(e=>{this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantUpdated",(e=>{this._updateMapping(e)}))),this._listenerHandles.push(this._tsCall.on("participantRemoved",(e=>{this._removeMapping(e)}))),this._tsCall.participants.forEach((e=>{this._updateMapping(e)}))}_updateMapping(e){e.endpoints?.endpointDetails?.forEach((t=>{const i=t.mediaStreams?.find((e=>"audio"===e.type));if(i){const n={sourceId:i.sourceId,participantId:t.participantId,mri:e.id};this._sourceIdMapping.set(i.sourceId,n),this._participantIdMapping.set(t.participantId,n)}}))}_removeMapping(e){e.endpoints?.endpointDetails?.forEach((e=>{const t=e.mediaStreams?.find((e=>"audio"===e.type));t&&(this._sourceIdMapping.delete(t.sourceId),this._participantIdMapping.delete(e.participantId))}))}findParticipantInfoBySourceId(e){return this._sourceIdMapping.get(e)}findParticipantInfoByParticipantId(e){return this._participantIdMapping.get(e)}dispose(){this._sourceIdMapping.clear(),this._participantIdMapping.clear(),this._listenerHandles.forEach((e=>e.dispose()))}}class TS{constructor(e,t){this._tsCall=e,this._telemetryLogManager=t}sendActionEvent(e){const t={callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,...e};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_unmixed_audio,tenant:hl,properties:t})}}class bS{constructor(e,t){this._unmixedAudioTelemetryLogger=e,this._action=t,this._correlationId=x()}logAttempt(){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"attempt",correlationId:this._correlationId})}logSuccess(){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"success",correlationId:this._correlationId})}logFailure(e,t){this._unmixedAudioTelemetryLogger.sendActionEvent({action:this._action,kindOfEvent:"failure",correlationId:this._correlationId,failureReason:e.message,...t,additionalDetails:{...xg(e)}})}}class IS{constructor(e,t){this._waitTimeoutInMs=e,this._expectedState=t,this._result=Rc(),this._wait=Lh((()=>this._result.promise),this._waitTimeoutInMs)}updateState(e){this._result.isPending()&&(e===this._expectedState?this._result.resolve():this._result.reject(new Error(`Unexpected active state: ${e}`)))}get waitState(){return this._expectedState}async wait(){await this._wait}cancel(){this._result.isPending()&&this._result.reject(new Error("Operation cancelled"))}}class wS{constructor(e,t){this._logger=e.createChild(`AudioContext:${t}`);const i=new AudioContext,n=()=>{this._logger.info(`The AudioContext:${t} state changed to ${i.state}`),"closed"===i.state&&i.removeEventListener("statechange",n)};i.addEventListener("statechange",n),this._audioContext=i}async resume(e=0){if("closed"===this._audioContext.state)throw CS(this._audioContext.state);if("running"===this._audioContext.state)return;const t=new IS(e,!0);return this._audioContext.resume().then((()=>{t.updateState(!0),this._logger.info("resumed")})).catch((e=>{this._logger.info(`Failed to resume: ${fS(e)}`),t.updateState(!1)})),t.wait()}async close(){"closed"!==this._audioContext.state&&await this._audioContext.close().then((()=>{this._logger.info("closed")})).catch((e=>{this._logger.info(`Failed to close: ${fS(e)}`)}))}get state(){return this._audioContext.state}get value(){return this._audioContext}}function RS(e){switch(e){case sS.Uninitialized:return"Uninitialized";case sS.Initializing:return"Initializing";case sS.Initialized:return"Initialized";case sS.Destroyed:return"Destroyed";case sS.Aborted:return"Aborted"}}!function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized",e[e.Destroyed=3]="Destroyed",e[e.Aborted=4]="Aborted"}(sS||(sS={}));class AS{constructor(e,t,i,n){this._state=sS.Uninitialized,this._listenerHandles=[],this._audioContextSeq=0,this._activeStatePromises=new Set,this._lastestSpatialAudioRequest="none",this._pendingOperation=!1,this._initializedDefer=Rc();try{this._tsCall=e,this._logger=t.createChild("UnmixedAudioManager"),this._eventEmitter=new wm(this._logger,{enableLogEmit:!1}),this._unmixedAudioTelemetryLogger=i,this._participantManager=new ES(e),this._destinationStreamInfoMap=new Map,this._destinationStreamInfoList=new Array(n.maxStreamSize),this._sourceStreamInfoList=new Array(n.maxStreamSize),this._maxStreamSize=n.maxStreamSize,this._operationTimeoutInMs=n.operationTimeoutInMs,this._skipProviderStateCheck=n.skipProviderStateCheck}catch(e){throw this._state=sS.Aborted,t.info(`Failed to create UnmixedAudioManager: ${fS(e)}`),_S(e)}}async initialize(){if(this._state!==sS.Uninitialized)throw CS(RS(this._state));this._initializedDefer.isPending()||(this._initializedDefer=Rc());const e=new bS(this._unmixedAudioTelemetryLogger,"initialize");this._state=sS.Initializing;try{if(e.logAttempt(),!this._tsCall.getUnmixedAudioProvider)throw mS();if(this._tsUnmixedAudioProvider=this._tsUnmixedAudioProvider??await this._tsCall.getUnmixedAudioProvider(),!this._tsUnmixedAudioProvider)throw mS();this._audioContext=this._audioContext??new wS(this._logger,this._audioContextSeq++),0===this._listenerHandles.length&&(this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onStreamSourcesUpdated",(e=>{this._state===sS.Initialized&&this._onStreamSourcesUpdatedHandler(e)}))),this._listenerHandles.push(this._tsUnmixedAudioProvider.on("onActiveStateChanged",(()=>{if(this._state!==sS.Initialized)return;const e=this._tsUnmixedAudioProvider?.active??!1;this._logger.info(`activeStateChanged to ${e}`),this._activeStatePromises.forEach((t=>{t.updateState(e)})),this._activeStatePromises.clear()})))),e.logSuccess(),this._logger.info(`Initialized with maxStreamSize ${this._maxStreamSize}. The AudioContext state is ${this._getAudioContextState()}.`),this._state=sS.Initialized,this._initializedDefer.resolve()}catch(t){this._state=sS.Uninitialized;const i=fS(t);this._logger.info(`Failed to initialize: ${i}`);const n=_S(t);e.logFailure(n),this._initializedDefer.reject(n)}return this._initializedDefer.promise}async enableUnmixedAudio(){const e=new bS(this._unmixedAudioTelemetryLogger,"enable");try{if(![sS.Uninitialized,sS.Initializing,sS.Initialized].includes(this._state))throw CS(RS(this._state));if(1===this._tsCall.callType)throw yS();if(this._pendingOperation)throw SS();if("enable"===this._lastestSpatialAudioRequest&&!this._skipProviderStateCheck&&"active"===this._getUnmixedAudioProviderState()&&"running"===this._getAudioContextState())throw new b({defaultError:f.FEATURES.UNMIXED_AUDIO.ENABLED});let t;this._pendingOperation=!0,e.logAttempt(),this._state===sS.Uninitialized?await this.initialize():this._state===sS.Initializing&&await this._initializedDefer.promise,void 0!==this._audioContext&&"closed"!==this._getAudioContextState()||(this._cleaupAudioNodes(),this._audioContext=new wS(this._logger,this._audioContextSeq++)),"active"!==this._getUnmixedAudioProviderState()&&(t=new IS(this._operationTimeoutInMs,!0),this._activeStatePromises.add(t));const i=[["resume AudioContext","running"===this._getAudioContextState()?void 0:this._audioContext.resume(this._operationTimeoutInMs)],["enable spatial audio config",this._enableSpatialAudio(!0)],["wait for the unmixed audio active state to change to true",t?.wait()]];await this._runTasks(i),this._pendingOperation=!1,e.logSuccess(),this._logger.info(`UnmixedAudio is enabled. The AudioContext state is ${this._getAudioContextState()}.`)}catch(t){const i=this._getAudioContextState(),n=this._getUnmixedAudioProviderState(),r=fS(t);this._logger.info(`Failed to enable unmixed audio: ${r}. AudioContext=${i}, UnmixedAudio=${n}`);const a={audioContextState:i,unmixedAudioState:n},s=function(e,t){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.FAILED_TO_ENABLE,defaultErrorMessageArgs:[t.audioContextState||"undefined",t.unmixedAudioState||"undefined"],originalError:e})}(t,a);!1===this._pendingOperation&&vS(s),e.logFailure(s,a),this._pendingOperation=!1,vS(s)}}async disableUnmixedAudio(){const e=new bS(this._unmixedAudioTelemetryLogger,"disable");try{if(![sS.Initializing,sS.Initialized].includes(this._state))throw CS(RS(this._state));if(1===this._tsCall.callType)throw yS();if(this._pendingOperation)throw SS();if("disable"===this._lastestSpatialAudioRequest&&"active"!==this._getUnmixedAudioProviderState())throw new b({defaultError:f.FEATURES.UNMIXED_AUDIO.DISABLED});let t;this._pendingOperation=!0,e.logAttempt(),this._state===sS.Initializing&&await this._initializedDefer.promise,"inactive"!==this._getUnmixedAudioProviderState()&&(t=new IS(this._operationTimeoutInMs,!1),this._activeStatePromises.add(t));const i=[["disable spatial audio config",this._enableSpatialAudio(!1)],["wait for the unmixed audio active state to change to false",t?.wait()]];await this._runTasks(i),this._pendingOperation=!1,e.logSuccess(),this._logger.info("UnmixedAudio is disabled")}catch(t){const i=this._getAudioContextState(),n=this._getUnmixedAudioProviderState(),r=fS(t);this._logger.info(`Failed to disable unmixed audio: ${r}. AudioContext=${i}, UnmixedAudio=${n}`);const a={audioContextState:i,unmixedAudioState:n},s=function(e,t){return new b({defaultError:f.FEATURES.UNMIXED_AUDIO.FAILED_TO_DISABLE,defaultErrorMessageArgs:[t.audioContextState||"undefined",t.unmixedAudioState||"undefined"],originalError:e})}(t,a);!1===this._pendingOperation&&vS(s),e.logFailure(s,a),this._pendingOperation=!1,vS(s)}}get isUnmixedAudioActive(){return this._state===sS.Initialized&&"active"===this._getUnmixedAudioProviderState()&&"running"===this._getAudioContextState()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._state!==sS.Destroyed&&(this._state=sS.Destroyed,this._initializedDefer.isPending()&&this._initializedDefer.reject(new b({defaultError:f.FEATURES.UNMIXED_AUDIO.DISPOSED})),this._listenerHandles.forEach((e=>e.dispose())),this._cleaupAudioNodes(),this._participantManager.dispose(),this._audioContext?.close(),this._activeStatePromises.forEach((e=>{e.cancel()})),this._activeStatePromises.clear(),this._eventEmitter.removeAllListeners())}_getAudioContextState(){return this._audioContext?.state??"unavailable"}_getUnmixedAudioProviderState(){return this._tsUnmixedAudioProvider?this._tsUnmixedAudioProvider.active?"active":"inactive":"unavailable"}_cleaupAudioNodes(){this._sourceStreamInfoList.forEach(((e,t)=>{const i=this._destinationStreamInfoList[t];void 0!==e&&void 0!==i&&e.audioNode.disconnect(i.audioNode),this._sourceStreamInfoList[t]=void 0,this._destinationStreamInfoList[t]=void 0})),this._destinationStreamInfoMap.clear()}_onStreamSourcesUpdatedHandler(e){const t=this._audioContext?.value;if(void 0===t||"running"!==t.state)return;const i=[];for(let n=0;n<this._maxStreamSize;n++){const r=n<e.length?e[n]:0,a=r?this._participantManager.findParticipantInfoBySourceId(r):void 0;let s=this._destinationStreamInfoList[n],o=this._sourceStreamInfoList[n];if(void 0===a)void 0!==s&&void 0!==o&&(o.audioNode.disconnect(s.audioNode),this._destinationStreamInfoList[n]=void 0);else{const e=this._tsUnmixedAudioProvider?.streams[n]??void 0;if(void 0!==o&&o.mediaStream!==e&&(void 0!==s&&o.audioNode.disconnect(s.audioNode),o=void 0,this._sourceStreamInfoList[n]=void 0),!e)continue;let r=!1;void 0!==o&&void 0!==s&&a.participantId!==s.participantId&&(o.audioNode.disconnect(s.audioNode),s=void 0,this._destinationStreamInfoList[n]=void 0),void 0===s&&(s=this._destinationStreamInfoMap.get(a.participantId),void 0===s&&(s={participantId:a.participantId,identifier:ac(a.mri),audioNode:t.createMediaStreamDestination()},this._destinationStreamInfoMap.set(a.participantId,s)),this._destinationStreamInfoList[n]=s,r=!0),void 0===o&&(o={mediaStream:e,audioNode:t.createMediaStreamSource(e)},this._sourceStreamInfoList[n]=o,r=!0),r&&o.audioNode.connect(s.audioNode),i.push({id:a.sourceId,stream:s.audioNode.stream,participantId:a.participantId,identifier:s.identifier})}}this._eventEmitter.emit("participantSpeaking",{speakers:i})}async _enableSpatialAudio(e){await this._tsCall.setAudioMidcallConfigJson({enableSpatialAudio:e}),this._lastestSpatialAudioRequest=e?"enable":"disable"}async _runTasks(e){let t;if((await Promise.allSettled(e.map((e=>e[1])))).forEach(((i,n)=>{"rejected"===i.status&&(this._logger.info(`Failed to ${e[n][0]}: ${fS(i.reason)}}`),t=i)})),void 0!==t)throw t.reason}}class PS{constructor(){this._isEnabled=yc().calling.teamsMeetingAudioConferencing.enabled,this._supportedConversationTypes=yc().calling.teamsMeetingAudioConferencing.supportedConversationTypes}initialize(e,t,i,n){this._logger=n.createChild((()=>`teamsMeetingAudioConferencing::Call(id='${e.callId}')`)),this._tsCall=e,this._telemetryLogManager=i,this._internalCallAgent=t;const r="initialize";if(this.sendFeatureUsage(r,Yh.initialize),!this.isSupportedConversationType()){const e=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});throw this._logger.error(e.message),this.sendFeatureUsage(r,Yh.failure,e),e}this.sendFeatureUsage(r,Yh.success)}getTeamsMeetingAudioConferencingDetails(){const e="getTeamsMeetingAudioConferencingDetails";if(this.sendFeatureUsage(e,Yh.attempt),!this._isEnabled){const t=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.DISABLED});return this._logger.error(t.message),this.sendFeatureUsage(e,Yh.failure,t),Promise.reject(t)}if(!this.isSupportedConversationType()){const t=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.ONLY_AVAILABLE_IN_MEETINGS});return this._logger.error(t.message),this.sendFeatureUsage(e,Yh.failure,t),Promise.reject(t)}let t;if(3!==this._tsCall.state)return t=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNAVAILABLE_BEFORE_JOINING}),10===this._tsCall.state&&(t=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.UNVAILABLE_IN_LOBBY})),this.sendFeatureUsage(e,Yh.failure,t),this._logger.error(t.message),Promise.reject(t);let i={phoneConferenceId:"",phoneNumbers:[]};try{const t=this._tsCall?.meetingDetails?.pstnDetails?.acpMcuInfo?.settings,n=this._tsCall?.meetingDetails?.pstnDetails?.meetingInvitePhoneNumbers;if(!t&&!n)throw new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.DETAILS_NOT_CONFIGURED});return i={phoneConferenceId:t?.participantPasscode||"",phoneNumbers:n?.map((e=>({cityName:e?.cityName,countryName:e?.countryName,tollPhoneNumber:e?.isTollFree?null:ac(Ml+e.number),tollFreeNumber:e?.isTollFree?ac(Ml+e.number):null})))||[]},this._logger.info("Teams meeting audio conferencing details was retrieved successfully"),this.sendFeatureUsage(e,Yh.success),Promise.resolve(i)}catch(t){const i=new b({defaultError:f.FEATURES.TEAMS_MEETING_AUDIO_CONFERENCING.GET_DETAILS_FAILED,originalError:t});throw this.sendFeatureUsage(e,Yh.failure,i),i}}isSupportedConversationType(){const e=this._tsCall.conversationType;let t=this._supportedConversationTypes.find((t=>t===e));return this._logger.info(`TeamsMeetingAudioConferencingDetails::ConversationType = \n            ${e}. ConversationType is supported = ${t}`),t}sendFeatureUsage(e,t,i){let n=i?{code:i?.code||_,subCode:i?.subCode||0,failureReason:i?.message||"",...xg(i)}:void 0;bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"TeamsMeetingAudioConferencing",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}}var MS,kS=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.TraceLevel=void 0,function(e){e[e.Error=10]="Error",e[e.Warning=15]="Warning",e[e.Info=50]="Info"}(t.TraceLevel||(t.TraceLevel={}))})),DS=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MessageTrackingOption=t.ConnectionState=t.ServiceGeneratedClientIdName=t.SystemCommandsStateName=t.ConfigurationName=t.SystemSessionStateName=t.StateSubscriptionsName=void 0,t.StateSubscriptionsName="ConfigStateSubscriptions",t.SystemSessionStateName="systemSessionState",t.ConfigurationName="config",t.SystemCommandsStateName="systemCommands",t.ServiceGeneratedClientIdName="serviceGeneratedClientId",function(e){e[e.Disconnected=0]="Disconnected",e[e.Connected=1]="Connected",e[e.Connecting=2]="Connecting"}(t.ConnectionState||(t.ConnectionState={})),function(e){e[e.All=0]="All",e[e.Last=1]="Last",e[e.None=2]="None"}(t.MessageTrackingOption||(t.MessageTrackingOption={}))})),OS=function(e,t){return function(){for(var i=new Array(arguments.length),n=0;n<i.length;n++)i[n]=arguments[n];return e.apply(t,i)}},NS=Object.prototype.toString,LS=(MS=Object.create(null),function(e){var t=NS.call(e);return MS[t]||(MS[t]=t.slice(8,-1).toLowerCase())});function xS(e){return e=e.toLowerCase(),function(t){return LS(t)===e}}function FS(e){return Array.isArray(e)}function US(e){return void 0===e}var BS=xS("ArrayBuffer");function VS(e){return null!==e&&"object"==typeof e}function HS(e){if("object"!==LS(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var $S=xS("Date"),GS=xS("File"),jS=xS("Blob"),zS=xS("FileList");function WS(e){return"[object Function]"===NS.call(e)}var qS=xS("URLSearchParams");function KS(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),FS(e))for(var i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.call(null,e[r],r,e)}var JS,YS=(JS="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return JS&&e instanceof JS}),QS={isArray:FS,isArrayBuffer:BS,isBuffer:function(e){return null!==e&&!US(e)&&null!==e.constructor&&!US(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||NS.call(e)===t||WS(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&BS(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:VS,isPlainObject:HS,isUndefined:US,isDate:$S,isFile:GS,isBlob:jS,isFunction:WS,isStream:function(e){return VS(e)&&WS(e.pipe)},isURLSearchParams:qS,isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:KS,merge:function e(){var t={};function i(i,n){HS(t[n])&&HS(i)?t[n]=e(t[n],i):HS(i)?t[n]=e({},i):FS(i)?t[n]=i.slice():t[n]=i}for(var n=0,r=arguments.length;n<r;n++)KS(arguments[n],i);return t},extend:function(e,t,i){return KS(t,(function(t,n){e[n]=i&&"function"==typeof t?OS(t,i):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,i,n){e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,i&&Object.assign(e.prototype,i)},toFlatObject:function(e,t,i){var n,r,a,s={};t=t||{};do{for(r=(n=Object.getOwnPropertyNames(e)).length;r-- >0;)s[a=n[r]]||(t[a]=e[a],s[a]=!0);e=Object.getPrototypeOf(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:LS,kindOfTest:xS,endsWith:function(e,t,i){e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;var n=e.indexOf(t,i);return-1!==n&&n===i},toArray:function(e){if(!e)return null;var t=e.length;if(US(t))return null;for(var i=new Array(t);t-- >0;)i[t]=e[t];return i},isTypedArray:YS,isFileList:zS};function ZS(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var XS=function(e,t,i){if(!t)return e;var n;if(i)n=i(t);else if(QS.isURLSearchParams(t))n=t.toString();else{var r=[];QS.forEach(t,(function(e,t){null!=e&&(QS.isArray(e)?t+="[]":e=[e],QS.forEach(e,(function(e){QS.isDate(e)?e=e.toISOString():QS.isObject(e)&&(e=JSON.stringify(e)),r.push(ZS(t)+"="+ZS(e))})))})),n=r.join("&")}if(n){var a=e.indexOf("#");-1!==a&&(e=e.slice(0,a)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e};function ey(){this.handlers=[]}ey.prototype.use=function(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1},ey.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},ey.prototype.forEach=function(e){QS.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var ty=ey,iy=function(e,t){QS.forEach(e,(function(i,n){n!==t&&n.toUpperCase()===t.toUpperCase()&&(e[t]=i,delete e[n])}))};function ny(e,t,i,n,r){Error.call(this),this.message=e,this.name="AxiosError",t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r)}QS.inherits(ny,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:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var ry=ny.prototype,ay={};["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"].forEach((function(e){ay[e]={value:e}})),Object.defineProperties(ny,ay),Object.defineProperty(ry,"isAxiosError",{value:!0}),ny.from=function(e,t,i,n,r,a){var s=Object.create(ry);return QS.toFlatObject(e,s,(function(e){return e!==Error.prototype})),ny.call(s,e.message,t,i,n,r),s.name=e.name,a&&Object.assign(s,a),s};var sy=ny,oy={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var ly=function(e,t){t=t||new FormData;var i=[];function n(e){return null===e?"":QS.isDate(e)?e.toISOString():QS.isArrayBuffer(e)||QS.isTypedArray(e)?"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}return function e(r,a){if(QS.isPlainObject(r)||QS.isArray(r)){if(-1!==i.indexOf(r))throw Error("Circular reference detected in "+a);i.push(r),QS.forEach(r,(function(i,r){if(!QS.isUndefined(i)){var s,o=a?a+"."+r:r;if(i&&!a&&"object"==typeof i)if(QS.endsWith(r,"{}"))i=JSON.stringify(i);else if(QS.endsWith(r,"[]")&&(s=QS.toArray(i)))return void s.forEach((function(e){!QS.isUndefined(e)&&t.append(o,n(e))}));e(i,o)}})),i.pop()}else t.append(a,n(r))}(e),t},cy=QS.isStandardBrowserEnv()?{write:function(e,t,i,n,r,a){var s=[];s.push(e+"="+encodeURIComponent(t)),QS.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),QS.isString(n)&&s.push("path="+n),QS.isString(r)&&s.push("domain="+r),!0===a&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},dy=function(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t},uy=["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"],hy=QS.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");function n(e){var n=e;return t&&(i.setAttribute("href",n),n=i.href),i.setAttribute("href",n),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}return e=n(window.location.href),function(t){var i=QS.isString(t)?n(t):t;return i.protocol===e.protocol&&i.host===e.host}}():function(){return!0};function py(e){sy.call(this,null==e?"canceled":e,sy.ERR_CANCELED),this.name="CanceledError"}QS.inherits(py,sy,{__CANCEL__:!0});var gy=py,my=function(e){return new Promise((function(t,i){var n,r=e.data,a=e.headers,s=e.responseType;function o(){e.cancelToken&&e.cancelToken.unsubscribe(n),e.signal&&e.signal.removeEventListener("abort",n)}QS.isFormData(r)&&QS.isStandardBrowserEnv()&&delete a["Content-Type"];var l=new XMLHttpRequest;if(e.auth){var c=e.auth.username||"",d=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";a.Authorization="Basic "+btoa(c+":"+d)}var u=dy(e.baseURL,e.url);function h(){if(l){var n="getAllResponseHeaders"in l?function(e){var t,i,n,r={};return e?(QS.forEach(e.split("\n"),(function(e){if(n=e.indexOf(":"),t=QS.trim(e.substr(0,n)).toLowerCase(),i=QS.trim(e.substr(n+1)),t){if(r[t]&&uy.indexOf(t)>=0)return;r[t]="set-cookie"===t?(r[t]?r[t]:[]).concat([i]):r[t]?r[t]+", "+i:i}})),r):r}(l.getAllResponseHeaders()):null;(function(e,t,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new sy("Request failed with status code "+i.status,[sy.ERR_BAD_REQUEST,sy.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)})((function(e){t(e),o()}),(function(e){i(e),o()}),{data:s&&"text"!==s&&"json"!==s?l.response:l.responseText,status:l.status,statusText:l.statusText,headers:n,config:e,request:l}),l=null}}if(l.open(e.method.toUpperCase(),XS(u,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,"onloadend"in l?l.onloadend=h:l.onreadystatechange=function(){l&&4===l.readyState&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))&&setTimeout(h)},l.onabort=function(){l&&(i(new sy("Request aborted",sy.ECONNABORTED,e,l)),l=null)},l.onerror=function(){i(new sy("Network Error",sy.ERR_NETWORK,e,l,l)),l=null},l.ontimeout=function(){var t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",n=e.transitional||oy;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new sy(t,n.clarifyTimeoutError?sy.ETIMEDOUT:sy.ECONNABORTED,e,l)),l=null},QS.isStandardBrowserEnv()){var p=(e.withCredentials||hy(u))&&e.xsrfCookieName?cy.read(e.xsrfCookieName):void 0;p&&(a[e.xsrfHeaderName]=p)}"setRequestHeader"in l&&QS.forEach(a,(function(e,t){void 0===r&&"content-type"===t.toLowerCase()?delete a[t]:l.setRequestHeader(t,e)})),QS.isUndefined(e.withCredentials)||(l.withCredentials=!!e.withCredentials),s&&"json"!==s&&(l.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),(e.cancelToken||e.signal)&&(n=function(e){l&&(i(!e||e&&e.type?new gy:e),l.abort(),l=null)},e.cancelToken&&e.cancelToken.subscribe(n),e.signal&&(e.signal.aborted?n():e.signal.addEventListener("abort",n))),r||(r=null);var g=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(u);g&&-1===["http","https","file"].indexOf(g)?i(new sy("Unsupported protocol "+g+":",sy.ERR_BAD_REQUEST,e)):l.send(r)}))},fy={"Content-Type":"application/x-www-form-urlencoded"};function vy(e,t){!QS.isUndefined(e)&&QS.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var Sy={transitional:oy,adapter:function(){var e;return("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(e=my),e}(),transformRequest:[function(e,t){if(iy(t,"Accept"),iy(t,"Content-Type"),QS.isFormData(e)||QS.isArrayBuffer(e)||QS.isBuffer(e)||QS.isStream(e)||QS.isFile(e)||QS.isBlob(e))return e;if(QS.isArrayBufferView(e))return e.buffer;if(QS.isURLSearchParams(e))return vy(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString();var i,n=QS.isObject(e),r=t&&t["Content-Type"];if((i=QS.isFileList(e))||n&&"multipart/form-data"===r){var a=this.env&&this.env.FormData;return ly(i?{"files[]":e}:e,a&&new a)}return n||"application/json"===r?(vy(t,"application/json"),function(e,t,i){if(QS.isString(e))try{return(t||JSON.parse)(e),QS.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional||Sy.transitional,i=t&&t.silentJSONParsing,n=t&&t.forcedJSONParsing,r=!i&&"json"===this.responseType;if(r||n&&QS.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(r){if("SyntaxError"===e.name)throw sy.from(e,sy.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:null},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};QS.forEach(["delete","get","head"],(function(e){Sy.headers[e]={}})),QS.forEach(["post","put","patch"],(function(e){Sy.headers[e]=QS.merge(fy)}));var yy=Sy,Cy=function(e,t,i){var n=this||yy;return QS.forEach(i,(function(i){e=i.call(n,e,t)})),e},_y=function(e){return!(!e||!e.__CANCEL__)};function Ey(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new gy}var Ty=function(e){return Ey(e),e.headers=e.headers||{},e.data=Cy.call(e,e.data,e.headers,e.transformRequest),e.headers=QS.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),QS.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||yy.adapter)(e).then((function(t){return Ey(e),t.data=Cy.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return _y(t)||(Ey(e),t&&t.response&&(t.response.data=Cy.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},by=function(e,t){t=t||{};var i={};function n(e,t){return QS.isPlainObject(e)&&QS.isPlainObject(t)?QS.merge(e,t):QS.isPlainObject(t)?QS.merge({},t):QS.isArray(t)?t.slice():t}function r(i){return QS.isUndefined(t[i])?QS.isUndefined(e[i])?void 0:n(void 0,e[i]):n(e[i],t[i])}function a(e){if(!QS.isUndefined(t[e]))return n(void 0,t[e])}function s(i){return QS.isUndefined(t[i])?QS.isUndefined(e[i])?void 0:n(void 0,e[i]):n(void 0,t[i])}function o(i){return i in t?n(e[i],t[i]):i in e?n(void 0,e[i]):void 0}var l={url:a,method:a,data:a,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:o};return QS.forEach(Object.keys(e).concat(Object.keys(t)),(function(e){var t=l[e]||r,n=t(e);QS.isUndefined(n)&&t!==o||(i[e]=n)})),i},Iy="0.27.2",wy=Iy,Ry={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Ry[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));var Ay={};Ry.transitional=function(e,t,i){function n(e,t){return"[Axios v"+wy+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return function(i,r,a){if(!1===e)throw new sy(n(r," has been removed"+(t?" in "+t:"")),sy.ERR_DEPRECATED);return t&&!Ay[r]&&(Ay[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,a)}};var Py={assertOptions:function(e,t,i){if("object"!=typeof e)throw new sy("options must be an object",sy.ERR_BAD_OPTION_VALUE);for(var n=Object.keys(e),r=n.length;r-- >0;){var a=n[r],s=t[a];if(s){var o=e[a],l=void 0===o||s(o,a,e);if(!0!==l)throw new sy("option "+a+" must be "+l,sy.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new sy("Unknown option "+a,sy.ERR_BAD_OPTION)}},validators:Ry},My=Py.validators;function ky(e){this.defaults=e,this.interceptors={request:new ty,response:new ty}}ky.prototype.request=function(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},(t=by(this.defaults,t)).method?t.method=t.method.toLowerCase():this.defaults.method?t.method=this.defaults.method.toLowerCase():t.method="get";var i=t.transitional;void 0!==i&&Py.assertOptions(i,{silentJSONParsing:My.transitional(My.boolean),forcedJSONParsing:My.transitional(My.boolean),clarifyTimeoutError:My.transitional(My.boolean)},!1);var n=[],r=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(r=r&&e.synchronous,n.unshift(e.fulfilled,e.rejected))}));var a,s=[];if(this.interceptors.response.forEach((function(e){s.push(e.fulfilled,e.rejected)})),!r){var o=[Ty,void 0];for(Array.prototype.unshift.apply(o,n),o=o.concat(s),a=Promise.resolve(t);o.length;)a=a.then(o.shift(),o.shift());return a}for(var l=t;n.length;){var c=n.shift(),d=n.shift();try{l=c(l)}catch(e){d(e);break}}try{a=Ty(l)}catch(e){return Promise.reject(e)}for(;s.length;)a=a.then(s.shift(),s.shift());return a},ky.prototype.getUri=function(e){e=by(this.defaults,e);var t=dy(e.baseURL,e.url);return XS(t,e.params,e.paramsSerializer)},QS.forEach(["delete","get","head","options"],(function(e){ky.prototype[e]=function(t,i){return this.request(by(i||{},{method:e,url:t,data:(i||{}).data}))}})),QS.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,r){return this.request(by(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}ky.prototype[e]=t(),ky.prototype[e+"Form"]=t(!0)}));var Dy=ky;function Oy(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var i=this;this.promise.then((function(e){if(i._listeners){var t,n=i._listeners.length;for(t=0;t<n;t++)i._listeners[t](e);i._listeners=null}})),this.promise.then=function(e){var t,n=new Promise((function(e){i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e){i.reason||(i.reason=new gy(e),t(i.reason))}))}Oy.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},Oy.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},Oy.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},Oy.source=function(){var e;return{token:new Oy((function(t){e=t})),cancel:e}};var Ny=Oy;var Ly=function e(t){var i=new Dy(t),n=OS(Dy.prototype.request,i);return QS.extend(n,Dy.prototype,i),QS.extend(n,i),n.create=function(i){return e(by(t,i))},n}(yy);Ly.Axios=Dy,Ly.CanceledError=gy,Ly.CancelToken=Ny,Ly.isCancel=_y,Ly.VERSION=Iy,Ly.toFormData=ly,Ly.AxiosError=sy,Ly.Cancel=Ly.CanceledError,Ly.all=function(e){return Promise.all(e)},Ly.spread=function(e){return function(t){return e.apply(null,t)}},Ly.isAxiosError=function(e){return QS.isObject(e)&&!0===e.isAxiosError};var xy=Ly,Fy=Ly;xy.default=Fy;for(var Uy=xy,By=s((function(e){var t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(t){var i=new Uint8Array(16);e.exports=function(){return t(i),i}}else{var n=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)!(3&t)&&(e=4294967296*Math.random()),n[t]=e>>>((3&t)<<3)&255;return n}}})),Vy=[],Hy=0;Hy<256;++Hy)Vy[Hy]=(Hy+256).toString(16).substr(1);var $y,Gy,jy=function(e,t){var i=t||0,n=Vy;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")},zy=0,Wy=0;var qy=function(e,t,i){var n=t&&i||0,r=t||[],a=(e=e||{}).node||$y,s=void 0!==e.clockseq?e.clockseq:Gy;if(null==a||null==s){var o=By();null==a&&(a=$y=[1|o[0],o[1],o[2],o[3],o[4],o[5]]),null==s&&(s=Gy=16383&(o[6]<<8|o[7]))}var l=void 0!==e.msecs?e.msecs:(new Date).getTime(),c=void 0!==e.nsecs?e.nsecs:Wy+1,d=l-zy+(c-Wy)/1e4;if(d<0&&void 0===e.clockseq&&(s=s+1&16383),(d<0||l>zy)&&void 0===e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");zy=l,Wy=c,Gy=s;var u=(1e4*(268435455&(l+=122192928e5))+c)%4294967296;r[n++]=u>>>24&255,r[n++]=u>>>16&255,r[n++]=u>>>8&255,r[n++]=255&u;var h=l/4294967296*1e4&268435455;r[n++]=h>>>8&255,r[n++]=255&h,r[n++]=h>>>24&15|16,r[n++]=h>>>16&255,r[n++]=s>>>8|128,r[n++]=255&s;for(var p=0;p<6;++p)r[n+p]=a[p];return t||jy(r)};var Ky=function(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||By)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||jy(r)},Jy=Ky;Jy.v1=qy,Jy.v4=Ky;var Yy=Jy,Qy=s((function(e,t){var i=a&&a.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.errorToString=void 0,t.errorToString=function(e,t){if(void 0===t&&(t=!0),null==e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,r(n(t)))}catch(e){return"Stringifying error failed"}};var n=function(e){return void 0===e&&(e=!1),function(t,n){return n instanceof Error?i({name:n.name,message:n.message,stack:e?[]:("string"==typeof n.stack?n.stack:"").split("\n").map((function(e){return e.trim()})).filter((function(e){return!!e}))},n):n}},r=function(e){var t=new WeakSet;return function(i,n){if("object"==typeof n&&null!==n){if(t.has(n))return;t.add(n)}return e(i,n)}}})),Zy=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.EvictingQueue=void 0;var i=function(){function e(e){this.maxSize=e,this._store=[]}return Object.defineProperty(e.prototype,"store",{get:function(){return this._store},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._store.length},enumerable:!1,configurable:!0}),e.prototype.enqueue=function(e){this._store.length>=this.maxSize&&this._store.shift(),this._store.push(e)},e.prototype.dequeue=function(){return this._store.shift()},e.prototype.clear=function(){this._store=[]},e.prototype.forEach=function(e){this._store.forEach(e)},e}();t.EvictingQueue=i})),Xy=s((function(e,t){var i=a&&a.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},n=a&&a.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(e){return function(t){return l([e,t])}}function l(a){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleSyncCell=void 0;var r=function(){function e(e,t,i,n,r){this.m_id=e,this.m_sender=t,this.m_shouldEmitEventForAllMessages=i,this.aggregation=r,this.m_events=new Kp.EventEmitter,this.m_emitUnacknowledgedEventFor=null!=n?n:DS.MessageTrackingOption.None}return e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.off=function(e,t){return this.m_events.off(e,t),this},e.prototype.removeAllListeners=function(e){return this.m_events.removeAllListeners(e),this},e.prototype.id=function(){return this.m_id},e.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},e.prototype.getAsync=function(){return i(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.m_value]}))}))},e.prototype.setAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return this.m_value=e,t={messageId:Yy.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"set",value:JSON.stringify(this.m_value)},this.m_sender.sendStateMessage(t),[2]}))}))},e.prototype.delete=function(){this.m_value=void 0;var e={messageId:Yy.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"cell",operation:"delete",value:""};this.m_sender.sendStateMessage(e)},e.prototype.handleStateMessage=function(e){switch(e.operation){case"set":return void((JSON.stringify(this.m_value)!==e.value||this.m_shouldEmitEventForAllMessages)&&(this.m_value=JSON.parse(e.value),this.m_events.emit("valueChanged",this.m_value,e)));case"delete":return this.m_value=void 0,void this.m_events.emit("valueDeleted",this.m_value,e);default:return}},e.prototype.handleUnacknowledgedMessage=function(e){this.m_events.emit("valueUnacknowledged",e)},e.prototype.beginAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.beginAggregatedStateUpdating()},e.prototype.endAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.endAggregatedStateUpdating()},e}();t.SimpleSyncCell=r})),eC=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.isPrefixDeleteMessage=void 0,t.isPrefixDeleteMessage=function(e){return"delete"===e.operation&&"prefix"===e.value}})),tC=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleSyncMap=void 0;var i=function(){function e(e,t,i,n,r){this.m_id=e,this.m_sender=t,this.m_shouldEmitEventForAllMessages=i,this.aggregation=r,this.m_events=new Kp.EventEmitter,this.m_map=new Map,this.m_emitUnacknowledgedEventFor=null!=n?n:DS.MessageTrackingOption.None}return e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.off=function(e,t){return this.m_events.off(e,t),this},e.prototype.removeAllListeners=function(e){return this.m_events.removeAllListeners(e),this},e.prototype.id=function(){return this.m_id},e.prototype.messageTrackingOption=function(){return this.m_emitUnacknowledgedEventFor},e.prototype.get=function(e){return this.m_map.get(e)},e.prototype.set=function(e,t){this.m_map.set(e,t);var i={messageId:Yy.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"set",property:e,value:JSON.stringify(t)};this.m_sender.sendStateMessage(i)},e.prototype.delete=function(e){var t={messageId:Yy.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:e,value:""};this.performLocalDelete(t),this.m_sender.sendStateMessage(t)},e.prototype.deleteWithPrefix=function(e){var t={messageId:Yy.v4(),senderId:this.m_sender.senderId(),objectId:this.m_id,type:"map",operation:"delete",property:e,value:"prefix"};this.performLocalDelete(t),this.m_sender.sendStateMessage(t)},e.prototype.forEach=function(e){this.m_map.forEach(e)},e.prototype.handleStateMessage=function(e){switch(e.operation){case"set":return void this.handleSet(e);case"delete":return void this.handleDelete(e);default:return}},e.prototype.handleSet=function(e){if(!e.property)throw new Error("property is missing for a map.");(JSON.stringify(this.m_map.get(e.property))!==e.value||this.m_shouldEmitEventForAllMessages)&&(this.m_map.set(e.property,JSON.parse(e.value)),this.m_events.emit("valueChanged",e.property,e))},e.prototype.handleDelete=function(e){this.performLocalDelete(e),eC.isPrefixDeleteMessage(e)?this.m_events.emit("valuesDeletedWithPrefix",e.property,e):this.m_events.emit("valueDeleted",e.property||"",e)},e.prototype.handleUnacknowledgedMessage=function(e){this.m_events.emit("valueUnacknowledged",e)},e.prototype.beginAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.beginAggregatedStateUpdating()},e.prototype.endAggregatedStateUpdating=function(){var e;null===(e=this.aggregation)||void 0===e||e.endAggregatedStateUpdating()},e.prototype.performLocalDelete=function(e){var t=this;if(e.property){var i=e.property;eC.isPrefixDeleteMessage(e)?this.m_map.forEach((function(e,n){n.startsWith(i)&&t.m_map.delete(n)})):this.m_map.delete(e.property)}else this.m_map.clear()},e}();t.SimpleSyncMap=i})),iC=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleServicePerformanceTelemetry=t.SimpleServiceTelemetry=void 0;var i=function(){function e(e,t,i){this.backendService="SimpleService",this.clientId=e,this.sessionId=t,this.wsReconnectCount=0,this.wsState=DS.ConnectionState[DS.ConnectionState.Disconnected],this.maxRoundtripRaw=i||0,this.roundtripTelemetry=new n,this.messageHandleTelemetry=new n,this.offlineCacheTelemetry={cachedCount:0,resentCount:0,expiredCount:0,rejectedCount:0},this.maxRoundtripRaw>0&&(this.roundtripRaw=[]),this.messagePendingAckCount=0,this.unacknowledgedMessagesCount=0,this.messageRequested={},this.messageReceived={},this.messageAcknowledged={}}return e.prototype.addRoundtripLatency=function(e){this.roundtripRaw&&this.roundtripRaw.length<this.maxRoundtripRaw&&this.roundtripRaw.push(e),this.roundtripTelemetry.addLatency(e)},e.prototype.addMessageHandleLatency=function(e){this.messageHandleTelemetry.addLatency(e)},e.prototype.incrementAcknowledgedCount=function(e){this.incrementMessageCount(this.messageAcknowledged,e)},e.prototype.incrementRequestedCount=function(e){this.incrementMessageCount(this.messageRequested,e)},e.prototype.incrementReceivedCount=function(e){this.incrementMessageCount(this.messageReceived,e)},e.prototype.incrementMessageCount=function(e,t){var i=e[t],n=void 0===i?1:i+1;e[t]=n},e}();t.SimpleServiceTelemetry=i;var n=function(){function e(){this.count=0,this.minValue=0,this.maxValue=0,this.avgValue=0}return e.prototype.addLatency=function(e){this.count+=1,this.avgValue=this.avgValue+(e-this.avgValue)/this.count,this.minValue=this.count>1?Math.min(e,this.minValue):e,this.maxValue=Math.max(this.maxValue,e)},e}();t.SimpleServicePerformanceTelemetry=n})),nC=s((function(e,t){var i=a&&a.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},n=a&&a.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(e){return function(t){return l([e,t])}}function l(a){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.StateServiceWebSocketConnection=void 0;var r=function(){function e(e,t){var r=this;this.onopen=null,this.onclose=null,this.onerror=null,this.onmessage=null,this.onlog=null,this.ws=new WebSocket(e),this.settings=t,this.ws.onopen=function(e){return i(r,void 0,void 0,(function(){return n(this,(function(t){switch(t.label){case 0:return this.onopen&&this.onopen(e),[4,this.sendSetupMessages()];case 1:return t.sent(),[2]}}))}))},this.ws.onclose=function(e){r.onclose&&r.onclose(e)},this.ws.onerror=function(e){r.onerror&&r.onerror(e)},this.ws.onmessage=function(e){r.onmessage&&r.onmessage(e)}}return e.CreateAsync=function(t,r){return i(this,void 0,void 0,(function(){return n(this,(function(i){return[2,new e(t,r)]}))}))},Object.defineProperty(e.prototype,"name",{get:function(){return"WebSocket"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"readyState",{get:function(){return this.ws.readyState},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isOpen",{get:function(){return this.ws.readyState===WebSocket.OPEN},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"shouldSendPings",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.close=function(){this.ws.close()},e.prototype.send=function(e){this.ws.send(e)},e.prototype.sendSetupMessages=function(){return i(this,void 0,void 0,(function(){var e,t,i,r,a,s,o=this;return n(this,(function(n){switch(n.label){case 0:return(t=this.settings.getAuthTokenAsync)?[4,this.settings.getAuthTokenAsync()]:[3,2];case 1:t=n.sent(),n.label=2;case 2:return e=t,i=this.settings,r=i.metadata,a=i.subscriptions,s={authToken:e,metadata:r,subscriptions:a},this.settings.createSetupMessage(s).forEach((function(e){return o.send(e)})),[2]}}))}))},e}();t.StateServiceWebSocketConnection=r})),rC=s((function(e,t){var i=a&&a.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},n=a&&a.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(e){return function(t){return l([e,t])}}function l(a){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},r=a&&a.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},s=a&&a.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SimpleStateServiceProxy=void 0;var o=s(Uy),l=[2e3,2e3,3e3,3e3,5e3],c=function(){function e(e,t,i,n,r,a){var s;this.m_events=new Kp.EventEmitter,this.m_clientId="",this.m_connectionState=DS.ConnectionState.Disconnected,this.m_handlers=new Map,this.m_connection=null,this.m_clientIds=new Set,this.m_initTimeoutDurationInMS=0,this.m_retryAttempts=0,this.m_sessionRetryAttempts=0,this.m_maxSessionRetries=0,this.m_outboundMessageInfo=new Map,this.m_initPromise={promise:null,resolve:null,reject:null},this.m_messageBuffer=[],this.m_batchWaitTimeMS=20,this.m_batchMessageTypeName="list",this.m_closeConnectionTimer=null,this.m_lastCloseCode=0,this.m_lastCloseReason="",this.m_offlineMessageCache=[],this.m_unacknowledgedMessages=new Map,this.m_sessionId=e,this.m_logger=n,this.m_connectionAliveTimeAfterLoseFocusInMS=r.websocketAliveTimeAfterLoseFocusInMS,this.m_useServiceGeneratedClientId=r.useServiceGeneratedClientId||!1,this.m_wsUrl=i+"?docId="+this.m_sessionId+"&clientType="+t,r.correlationId&&(this.m_wsUrl+="&cid="+r.correlationId),r.isAutomation&&(this.m_wsUrl+="&automation=true"),r.autoRoutingEnabled&&(this.m_wsUrl+="&routing=true"),this.m_useServiceGeneratedClientId||(this.m_clientId=r.customClientId||Yy.v4(),this.m_wsUrl+="&clientId="+this.m_clientId),this.m_deltasBaseUrl=i.replace("wss://","https://").replace("ws://","http://"),this.setupSystemClientsCell(),this.setUpSystemCommandsCell(),this.setupServiceGeneratedClientIdCell(),this.m_useServiceGeneratedClientId&&(this.m_clientIdEvictingQueue=new Zy.EvictingQueue(20)),this.m_telemetry=new iC.SimpleServiceTelemetry(this.m_clientId,this.m_sessionId,r.maxRoundtripRaw),this.m_verbose=r.verbose||!1,this.m_batchedRequestsEnabled=r.batchedRequestsEnabled,this.m_initTimeoutDurationInMS=r.initTimeoutDurationInMs||0,this.m_pingTimeoutInMs=r.pingTimeoutInMs,this.m_pongTimeoutInMs=r.pongTimeoutInMs,this.m_user=a,this.m_metadata=r.metadata,this.m_retryIntervalsInMs=r.retryIntervalsInMs||l,this.m_maxSessionRetries=r.maxSessionRetries,this.m_offlineMessageCacheEnabled=r.offlineMessageCacheEnabled,this.m_maxOfflineMessageCacheTimeInMs=r.maxOfflineMessageCacheTimeInMs,this.m_maxOfflineMessageCacheLength=r.maxOfflineMessageCacheLength,this.m_allowReconnectOnMessageSend=r.allowReconnectOnSendMessage||!1,this.m_unacknowledgedMaxTimeInMs=null!==(s=r.unacknowledgeMessageTimeoutInMs)&&void 0!==s?s:0,this.m_subscriptions=r.subscriptions,this.m_connectionSettings={getAuthTokenAsync:this.getAuthToken.bind(this),createSetupMessage:this.createSetupMessage.bind(this),metadata:this.m_metadata,subscriptions:this.m_subscriptions}}return Object.defineProperty(e.prototype,"lastCloseReason",{get:function(){return this.m_lastCloseReason},enumerable:!1,configurable:!0}),e.prototype.senderId=function(){return this.m_clientId},e.prototype.countOfOutboundMessagesNotRoundTrippedYet=function(){return this.m_outboundMessageInfo.size},e.prototype.canRetry=function(){return this.m_connectionState===DS.ConnectionState.Disconnected&&4321!==this.m_lastCloseCode},e.prototype.getServiceTelemetry=function(){return this.m_telemetry.wsState=DS.ConnectionState[this.getConnectionState()],this.m_telemetry.messagePendingAckCount=this.m_outboundMessageInfo.size,this.m_telemetry},e.prototype.activeClientCount=function(){return this.m_clientIds.size},e.prototype.activeClientIds=function(){return this.m_clientIds},e.prototype.clientId=function(){return this.m_clientId},e.prototype.getConnectionState=function(){return this.m_connectionState},e.prototype.on=function(e,t){return this.m_events.on(e,t),this},e.prototype.connectAsync=function(){return i(this,void 0,void 0,(function(){var e=this;return n(this,(function(t){return this.m_initPromise.promise=new Promise((function(t,i){e.m_initPromise.resolve=t,e.m_initPromise.reject=i})),this.setConnectionState(DS.ConnectionState.Connecting),[2,new Promise((function(t,r){return i(e,void 0,void 0,(function(){var e,i=this;return n(this,(function(n){switch(n.label){case 0:return e=this,[4,nC.StateServiceWebSocketConnection.CreateAsync(this.m_wsUrl,this.m_connectionSettings)];case 1:return e.m_connection=n.sent(),this.m_connection.onopen=function(){i.handleConnectionOpen(),i.startInitTimeoutTimerWithRetry(i.m_initTimeoutDurationInMS,i.m_initPromise.reject),t()},this.m_connection.onerror=function(e){var n;i.m_logger.sendTraceTag(590213388,kS.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(n=i.m_connection)||void 0===n?void 0:n.name)+" onerror. {sessionId: "+i.m_sessionId+", ClientId: "+i.m_clientId+", Error: "+JSON.stringify(e)+"}"),i.retryConnection((function(e){var t,n="failed to reconnect after "+(null===(t=i.m_connection)||void 0===t?void 0:t.name)+" error: "+Qy.errorToString(e);i.m_logger.sendTraceTag(579463185,kS.TraceLevel.Error,n),r(n)}),!1,(function(){return t()}))},this.m_connection.onlog=function(e){var t;i.m_logger.sendTraceTag(556909603,e.detail.level,"SimpleStateServiceProxy::log - "+(null===(t=i.m_connection)||void 0===t?void 0:t.name)+" {sessionId: "+i.m_sessionId+", ClientId: "+i.m_clientId+", Message: "+e.detail.message+"}")},this.m_connection.onclose=function(e){var n,a;i.m_logger.sendTraceTag(590213389,kS.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(n=i.m_connection)||void 0===n?void 0:n.name)+" onclose. {sessionId: "+i.m_sessionId+", ClientId: "+i.m_clientId+", Code: "+e.code+", Reason: "+e.reason+"}"),i.m_lastCloseCode=e.code,i.m_lastCloseReason=e.reason,4321!==e.code?i.retryConnection((function(e){var t="failed to reconnect after service side disconnect: "+Qy.errorToString(e);i.m_logger.sendTraceTag(579463186,kS.TraceLevel.Error,t),r(t)}),!1,(function(){return t()})):(i.setConnectionState(DS.ConnectionState.Disconnected),i.m_logger.sendTraceTag(588009741,kS.TraceLevel.Error,"SimpleStateServiceProxy::connect - "+(null===(a=i.m_connection)||void 0===a?void 0:a.name)+" onclose. Not retryable close code. {sessionId: "+i.m_sessionId+", ClientId: "+i.m_clientId+"}"))},this.m_connection.onmessage=function(e){var t;try{i.handleConnectionMessage(e)}catch(e){i.m_logger.sendTraceTag(590213390,kS.TraceLevel.Error,"SimpleStateServiceProxy::onmessage - "+(null===(t=i.m_connection)||void 0===t?void 0:t.name)+" error. {sessionId: "+i.m_sessionId+", ClientId: "+i.m_clientId+", Error: "+Qy.errorToString(e)+"}")}},[2]}}))}))}))]}))}))},e.prototype.close=function(){var e;this.m_logger.sendTraceTag(590213400,kS.TraceLevel.Info,"SimpleStateServiceProxy::close. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.closeAndClearConnection(),this.m_retryTimer&&(clearTimeout(this.m_retryTimer),this.m_retryTimer=null),this.m_unacknowledgedMessages.clear(),this.clearPingPongTimer(),this.clearOfflineMessageCacheTimer(),this.clearInitTimeoutTimer(),this.clearUnacknowledgedTimer(),null===(e=this.m_clientIdEvictingQueue)||void 0===e||e.clear(),0!==this.countOfOutboundMessagesNotRoundTrippedYet()&&(this.m_events.emit("messageFailedToRoundTripOnClose",this.m_outboundMessageInfo.size),this.m_outboundMessageInfo.clear())},e.prototype.sendStateMessage=function(e){this.sendStateMessageImpl(e)},e.prototype.createMapAsync=function(e,t,r,a){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){return i=new tC.SimpleSyncMap(e,this,t,r,a),this.m_handlers.set(e,i),[2,i]}))}))},e.prototype.getMapAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return(t=this.m_handlers.get(e))?[2,t]:[2,null]}))}))},e.prototype.waitMapAsync=function(e,t,r,a){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return[4,this.m_initPromise.promise];case 1:return n.sent(),[4,this.getMapAsync(e)];case 2:return(i=n.sent())?[3,4]:[4,this.createMapAsync(e,t,r,a)];case 3:i=n.sent(),n.label=4;case 4:return[2,i]}}))}))},e.prototype.createCellAsync=function(e,t,r,a){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){return i=new Xy.SimpleSyncCell(e,this,t,r,a),this.m_handlers.set(e,i),[2,i]}))}))},e.prototype.getCellAsync=function(e){return i(this,void 0,void 0,(function(){var t;return n(this,(function(i){return(t=this.m_handlers.get(e))?[2,t]:[2,null]}))}))},e.prototype.waitCellAsync=function(e,t,r,a){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return this.m_logger.sendTraceTag(520161040,kS.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - awaiting initPromise "+e),[4,this.m_initPromise.promise];case 1:return n.sent(),this.m_logger.sendTraceTag(520161039,kS.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - getCellAsync "+e),[4,this.getCellAsync(e)];case 2:return(i=n.sent())?[3,4]:(this.m_logger.sendTraceTag(520161038,kS.TraceLevel.Info,"SimpleStateServiceProxy::waitCellAsync - createCellAsync "+e),[4,this.createCellAsync(e,t,r,a)]);case 3:i=n.sent(),n.label=4;case 4:return[2,i]}}))}))},e.prototype.onFocusChanged=function(e){var t=this;e?(window.clearTimeout(this.m_closeConnectionTimer),this.m_connection||(this.m_logger.sendTraceTag(590213392,kS.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - retryConnection due to getting focus again. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.retryConnection((function(e){t.m_logger.sendTraceTag(579463187,kS.TraceLevel.Error,"failed to reconnect after regaining focus: "+Qy.errorToString(e))}),!0))):this.m_closeConnectionTimer=window.setTimeout((function(){var e;t.m_connection&&(t.m_logger.sendTraceTag(590213391,kS.TraceLevel.Info,"SimpleStateServiceProxy::onFocusChanged - "+(null===(e=t.m_connection)||void 0===e?void 0:e.name)+" close due to losing focus. {sessionId: "+t.m_sessionId+", ClientId: "+t.m_clientId+"}"),t.m_connection.onclose=function(){},t.m_connection.close(),t.m_connection=null)}),this.m_connectionAliveTimeAfterLoseFocusInMS)},e.prototype.getHistoryAsync=function(e,t){return i(this,void 0,void 0,(function(){var i,r;return n(this,(function(n){switch(n.label){case 0:return(i=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),i.searchParams.append("docId",this.m_sessionId),i.searchParams.append("cid",this.m_clientId),i.searchParams.append("objectId",e),t&&i.searchParams.append("property",t),[4,o.default.get(i.toString())];case 1:return(r=n.sent().data).forEach((function(e){return e.value=JSON.parse(e.value)})),[2,r]}}))}))},e.prototype.getHistoryWithPaginationAsync=function(e,t,r){return i(this,void 0,void 0,(function(){var i,a;return n(this,(function(n){switch(n.label){case 0:return(i=new URL(this.m_deltasBaseUrl)).searchParams.append("action","deltas"),i.searchParams.append("docId",this.m_sessionId),i.searchParams.append("cid",this.m_clientId),i.searchParams.append("objectId",e),i.searchParams.append("pagination","true"),r&&i.searchParams.append("cursor",r),t&&i.searchParams.append("property",t),[4,o.default.get(i.toString())];case 1:return(a=n.sent().data).messages.forEach((function(e){return e.value=JSON.parse(e.value)})),[2,a]}}))}))},e.prototype.setupSystemClientsCell=function(){var e=this;this.m_clientsCell=new Xy.SimpleSyncCell("systemClients",this),this.m_handlers.set(this.m_clientsCell.id(),this.m_clientsCell),this.m_clientsCell.on("valueChanged",(function(t){e.m_clientIds=new Set(t),e.m_events.emit("activeClientCountChanged")}))},e.prototype.setUpSystemCommandsCell=function(){var e=this;this.m_systemCommandsCell=new Xy.SimpleSyncCell(DS.SystemCommandsStateName,this),this.m_handlers.set(this.m_systemCommandsCell.id(),this.m_systemCommandsCell),this.m_systemCommandsCell.on("valueChanged",(function(t){return i(e,void 0,void 0,(function(){var e,i,r;return n(this,(function(n){switch(n.label){case 0:return"refreshToken"===t?[3,1]:[3,6];case 1:if(!this.m_user||!this.m_user.getForceRefreshedTokenAsync)return[3,5];n.label=2;case 2:return n.trys.push([2,4,,5]),[4,this.m_user.getForceRefreshedTokenAsync()];case 3:return e=n.sent(),i={},e&&(i.authorization=e.token,i.authProvider=e.authProvider,i.mri=e.mri||"",i.huid=e.hashedUserEmail||""),this.sendConfigMessage(i),[3,5];case 4:return r=n.sent(),this.m_logger.sendTraceTag(574107847,kS.TraceLevel.Error,"Error getting force refreshed auth token: "+Qy.errorToString(r)),[3,5];case 5:return[3,7];case 6:return this.m_logger.sendTraceTag(574107848,kS.TraceLevel.Error,"Unknown system command cell value: "+t),[3,7];case 7:return[2]}}))}))}))},e.prototype.setupServiceGeneratedClientIdCell=function(){var e=this;this.m_serviceGeneratedClientIdCell=new Xy.SimpleSyncCell(DS.ServiceGeneratedClientIdName,this),this.m_handlers.set(this.m_serviceGeneratedClientIdCell.id(),this.m_serviceGeneratedClientIdCell),this.m_serviceGeneratedClientIdCell.on("valueChanged",(function(t){e.m_logger.sendTraceTag(520161037,kS.TraceLevel.Info,"SimpleStateServiceProxy::serviceGeneratedClientId changed to "+t+"}"),e.setClientId(t,!0),e.processClientIdQueue(),e.m_useServiceGeneratedClientId&&(e.processOfflineMessageCache(!0),e.clearOfflineMessageCacheTimer())})),this.m_logger.sendTraceTag(509743689,kS.TraceLevel.Info,"SimpleStateServiceProxy::setupServiceGeneratedClientIdCell completed.")},e.prototype.handleConnectionOpen=function(){var e;this.m_logger.sendTraceTag(590213387,kS.TraceLevel.Info,"SimpleStateServiceProxy::connect - "+(null===(e=this.m_connection)||void 0===e?void 0:e.name)+" onopen. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.m_retryAttempts=0,this.setConnectionState(DS.ConnectionState.Connected),this.startPingTimer(),this.m_useServiceGeneratedClientId||(this.processOfflineMessageCache(!1),this.clearOfflineMessageCacheTimer())},e.prototype.setConnectionState=function(e){this.m_connectionState!==e&&(this.m_connectionState=e,e===DS.ConnectionState.Disconnected&&this.m_useServiceGeneratedClientId&&this.setClientId("",!1),this.m_events.emit("connectionStateChanged"))},e.prototype.setClientId=function(e,t){this.m_clientId!==e&&(this.m_clientId=e,t&&this.m_events.emit("clientIdChanged"))},e.prototype.processClientIdQueue=function(){var e=this;this.m_clientIdEvictingQueue&&this.m_clientIdEvictingQueue.forEach((function(t){t.senderId=e.m_clientId,e.sendConnectionMessage(t,!0)}))},e.prototype.sendGetInitialSystemStateMessages=function(){try{var e={messageId:Yy.v4(),senderId:this.senderId(),objectId:DS.SystemSessionStateName,type:"",operation:"get",value:""};this.sendStateMessage(e);var t={messageId:Yy.v4(),senderId:this.senderId(),objectId:DS.ServiceGeneratedClientIdName,type:"",operation:"get",value:""};this.sendStateMessage(t),this.m_logger.sendTraceTag(509141838,kS.TraceLevel.Info,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - sent messages.")}catch(e){this.m_logger.sendTraceTag(509141837,kS.TraceLevel.Error,"SimpleStateServiceProxy::sendGetInitialSystemStateMessages - caught error "+e)}},e.prototype.createSetupMessage=function(e){var t=e.authToken,i=e.metadata,n=e.subscriptions,r=[];if(t||i){var a={};t&&(a.authorization=t.token,a.authProvider=t.authProvider,a.mri=t.mri||"",a.huid=t.hashedUserEmail||""),i&&(a.metadata=JSON.stringify(i));var s={messageId:Yy.v4(),senderId:this.senderId(),objectId:DS.ConfigurationName,type:"",operation:"",value:JSON.stringify(a)};r.push(JSON.stringify(s))}return n&&(s={messageId:Yy.v4(),senderId:this.senderId(),objectId:DS.StateSubscriptionsName,type:"",operation:"",value:JSON.stringify(n)},r.push(JSON.stringify(s))),r},e.prototype.sendConfigMessage=function(e){var t={messageId:Yy.v4(),senderId:this.senderId(),objectId:DS.ConfigurationName,type:"",operation:"",value:JSON.stringify(e)};this.sendStateMessage(t)},e.prototype.retryConnection=function(e,t,r){var a=this;if(this.clearPingPongTimer(),this.clearInitTimeoutTimer(),this.m_retryAttempts>=this.m_retryIntervalsInMs.length||this.m_sessionRetryAttempts>=this.m_maxSessionRetries)return this.setConnectionState(DS.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213393,kS.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection reached max retry attempts. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),void(e&&e(new Error("reached max retry attempts")));if(this.setConnectionState(DS.ConnectionState.Connecting),t||this.m_connection&&!this.m_retryTimer){var s=this.m_retryIntervalsInMs[this.m_retryAttempts];this.m_retryAttempts+=1,this.m_sessionRetryAttempts+=1,this.m_telemetry.wsReconnectCount+=1,this.closeAndClearConnection(),this.m_retryTimer=setTimeout((function(){return i(a,void 0,void 0,(function(){var t;return n(this,(function(i){switch(i.label){case 0:this.m_logger.sendTraceTag(590213395,kS.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}"),this.m_retryTimer=null,i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.connectAsync()];case 2:return i.sent(),r&&r(),[3,4];case 3:return t=i.sent(),this.setConnectionState(DS.ConnectionState.Disconnected),this.m_logger.sendTraceTag(590213396,kS.TraceLevel.Error,"SimpleStateServiceProxy::retryConnection failed. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}, "+Qy.errorToString(t)),this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&e(t),[3,4];case 4:return[2]}}))}))}),s)}else this.m_logger.sendTraceTag(590213394,kS.TraceLevel.Info,"SimpleStateServiceProxy::retryConnection skipped. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", NullConnection: "+(null===this.m_connection)+", NullRetryTimer: "+(null===this.m_retryTimer)+"}")},e.prototype.startPingTimer=function(){var e=this;this.m_connection&&this.m_connection.shouldSendPings&&(this.m_pingTimeoutInMs<=0||this.m_pongTimeoutInMs<=0||(this.clearPingPongTimer(),this.m_pingTimer=setTimeout((function(){return i(e,void 0,void 0,(function(){return n(this,(function(e){return this.sendPingMessage(),this.m_pingTimer=null,[2]}))}))}),this.m_pingTimeoutInMs)))},e.prototype.sendPingMessage=function(){var e=this;this.m_connection&&(this.m_connection.isOpen?(this.m_verbose&&this.m_logger.sendTraceTag(559952470,kS.TraceLevel.Info,"SimpleStateServiceProxy::sendPingMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", __ping__"),this.m_connection.send("__ping__"),this.clearPongTimer(),this.m_pongTimer=setTimeout((function(){return i(e,void 0,void 0,(function(){var e=this;return n(this,(function(t){return this.retryConnection((function(t){e.m_logger.sendTraceTag(579463188,kS.TraceLevel.Error,"failed to reconnect after missing ping: "+Qy.errorToString(t))}),!1),this.m_pongTimer=null,[2]}))}))}),this.m_pongTimeoutInMs)):(this.retryConnection((function(t){e.m_logger.sendTraceTag(579463189,kS.TraceLevel.Error,"failed to reconnect after closed connection: "+Qy.errorToString(t))}),!1),this.clearPongTimer()))},e.prototype.clearPingPongTimer=function(){this.clearPingTimer(),this.clearPongTimer()},e.prototype.clearPingTimer=function(){this.m_pingTimer&&(clearTimeout(this.m_pingTimer),this.m_pingTimer=null)},e.prototype.clearPongTimer=function(){this.m_pongTimer&&(clearTimeout(this.m_pongTimer),this.m_pongTimer=null)},e.prototype.handleConnectionMessage=function(e){if("string"==typeof e.data){if(this.startPingTimer(),"__pong__"===e.data)return void(this.m_verbose&&this.m_logger.sendTraceTag(559952471,kS.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", __pong__"));var t=Date.now();try{var i=JSON.parse(e.data);Array.isArray(i)&&i.length>0?this.handleAggregatedStateMessages(i):this.handleStateMessage(i),this.m_telemetry.addMessageHandleLatency(Date.now()-t),i.objectId===DS.SystemSessionStateName?(this.m_logger.sendTraceTag(520161036,kS.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - systemSessionState - initPromise resolved."),this.m_initPromise.resolve(),this.clearInitTimeoutTimer()):i.objectId===DS.ServiceGeneratedClientIdName&&this.m_logger.sendTraceTag(509743688,kS.TraceLevel.Info,"SimpleStateServiceProxy::handleConnectionMessage - serviceGeneratedClientId received.")}catch(e){this.m_logger.sendTraceTag(578102302,kS.TraceLevel.Error,"handleConnectionMessage: "+Qy.errorToString(e))}}else this.m_logger.sendTraceTag(590213397,kS.TraceLevel.Error,"SimpleStateServiceProxy::handleConnectionMessage - Unknown data type. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Type: "+typeof e.data+"}")},e.prototype.handleAggregatedStateMessages=function(e){var t,i,n=this;if(e&&0!==e.length){var a=e.map((function(e){return JSON.parse(e)})),s={};a.forEach((function(e){return s[e.objectId]=1+(s[e.objectId]||0)})),Object.keys(s).forEach((function(e){if(s[e]>1){var t=n.m_handlers.get(e);t&&t.beginAggregatedStateUpdating&&t.beginAggregatedStateUpdating()}}));try{for(var o=r(a),l=o.next();!l.done;l=o.next()){var c=l.value;this.handleStateMessage(c)}}catch(e){t={error:e}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(t)throw t.error}}Object.keys(s).forEach((function(e){if(s[e]>1){var t=n.m_handlers.get(e);t&&t.endAggregatedStateUpdating&&t.endAggregatedStateUpdating()}}))}},e.prototype.handleStateMessage=function(e){var t=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213398,kS.TraceLevel.Info,"SimpleStateServiceProxy::handleStateMessage. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+e.objectId+", MessageId: "+e.messageId+"}"),"list"===e.type)JSON.parse(e.value).forEach((function(e){t.handleStateMessage(e)}));else{if(this.m_user&&this.m_user.validateMessage&&!this.m_user.validateMessage(e))return void this.m_logger.sendTraceTag(588009742,kS.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage rejected message: {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+e.objectId+", MessageId: "+e.messageId+"}");var i=this.getHandlerForMessage(e);if(e.senderId===this.senderId()&&(this.acknowledgeMessage(e,i),this.m_telemetry.incrementAcknowledgedCount(e.objectId)),this.measureMessageRoundTripLatency(e),this.m_telemetry.incrementReceivedCount(e.objectId),i)return void i.handleStateMessage(e)}},e.prototype.getAuthToken=function(){return i(this,void 0,void 0,(function(){var e,t;return n(this,(function(i){switch(i.label){case 0:if(!this.m_user||!this.m_user.getAuthTokenAsync)return[3,4];i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.m_user.getAuthTokenAsync()];case 2:return e=i.sent(),[3,4];case 3:return t=i.sent(),this.m_logger.sendTraceTag(578102469,kS.TraceLevel.Error,"Error getting auth token: "+Qy.errorToString(t)),[3,4];case 4:return[2,e]}}))}))},e.prototype.getHandlerForMessage=function(e){var t=this.m_handlers.get(e.objectId);return t||("cell"===e.type?t=new Xy.SimpleSyncCell(e.objectId,this):"map"===e.type?t=new tC.SimpleSyncMap(e.objectId,this):this.m_logger.sendTraceTag(559204164,kS.TraceLevel.Error,"SimpleStateServiceProxy::handleStateMessage - Unknown message type. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Type: "+e.type+"}"),t&&this.m_handlers.set(e.objectId,t),t)},e.prototype.sendStateMessageImpl=function(e){var t,i=this;if(this.m_verbose&&this.m_logger.sendTraceTag(590213403,kS.TraceLevel.Info,"SimpleStateServiceProxy::sendStateMessageImpl. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+e.objectId+", MessageId: "+e.messageId+"}"),e.objectId!==DS.StateSubscriptionsName&&e.objectId!==DS.ConfigurationName){if(this.m_outboundMessageInfo.set(e.messageId,Date.now()),this.m_telemetry.incrementRequestedCount(e.objectId),this.m_unacknowledgedMaxTimeInMs>0){var n=null===(t=this.getHandlerForMessage(e))||void 0===t?void 0:t.messageTrackingOption();if(n&&n!==DS.MessageTrackingOption.None){var r=this.getUnacknowledgedMessagesMapKey(e,n);this.m_unacknowledgedMessages.set(r,{message:e,timestamp:Date.now()}),this.startUnacknowledgeMessageTimer()}}if(this.m_useServiceGeneratedClientId&&this.m_clientIdEvictingQueue&&!this.m_clientId&&"get"!==e.operation)return this.m_logger.sendTraceTag(508348254,kS.TraceLevel.Info,"SimpleStateServiceProxy::enqueueMessage "+JSON.stringify(e)),void this.m_clientIdEvictingQueue.enqueue(e)}this.m_user&&this.m_user.patchMessage&&this.m_user.patchMessage(e),this.m_batchedRequestsEnabled?(this.m_messageBuffer.push(e),this.m_processBufferTimer||(this.m_processBufferTimer=setTimeout((function(){i.processMessageBuffer()}),this.m_batchWaitTimeMS))):this.sendConnectionMessage(e,!0)},e.prototype.createListMessage=function(e){if(0!==e.length)return 1===e.length?e[0]:{value:JSON.stringify(e),type:this.m_batchMessageTypeName,operation:"",messageId:Yy.v4(),objectId:"batch",senderId:this.senderId()}},e.prototype.processMessageBuffer=function(){var e=this.m_messageBuffer.length,t=this.m_messageBuffer.splice(0,e),i=this.createListMessage(t);this.m_processBufferTimer&&clearTimeout(this.m_processBufferTimer),this.m_processBufferTimer=null,i&&this.sendConnectionMessage(i,!0)},e.prototype.processOfflineMessageCache=function(e){var t=this;this.m_offlineMessageCacheEnabled&&(this.m_offlineMessageCache.forEach((function(i){e&&(i.message.senderId=t.m_clientId),t.sendConnectionMessage(i.message,!1),t.m_telemetry.offlineCacheTelemetry.resentCount+=1})),this.m_offlineMessageCache=[])},e.prototype.purgeOfflineMessageCache=function(){var e=this;if(this.m_offlineMessageCacheEnabled&&this.m_maxOfflineMessageCacheTimeInMs){var t=Date.now(),i=this.m_offlineMessageCache.filter((function(i){return e.m_maxOfflineMessageCacheTimeInMs&&i.timestamp+e.m_maxOfflineMessageCacheTimeInMs>=t}));this.m_telemetry.offlineCacheTelemetry.expiredCount+=this.m_offlineMessageCache.length-i.length,this.m_offlineMessageCache=i,0===this.m_offlineMessageCache.length&&this.clearOfflineMessageCacheTimer()}},e.prototype.clearOfflineMessageCacheTimer=function(){this.m_offlineMessageCacheEnabled&&this.m_offlineMessageCacheTimer&&(clearInterval(this.m_offlineMessageCacheTimer),this.m_offlineMessageCacheTimer=null)},e.prototype.getUnacknowledgedMessagesMapKey=function(e,t){return t===DS.MessageTrackingOption.None?"":t===DS.MessageTrackingOption.All?e.messageId:e.objectId},e.prototype.startUnacknowledgeMessageTimer=function(){var e=this;this.m_unacknowledgedMaxTimeInMs>0&&!this.m_unacknowledgedTimer&&(this.m_unacknowledgedTimer=setInterval((function(){e.notifyUnacknowledgedMessages(),e.m_unacknowledgedMessages.size<=0&&e.clearUnacknowledgedTimer()}),this.m_unacknowledgedMaxTimeInMs/2))},e.prototype.acknowledgeMessage=function(e,t){if(e.senderId===this.senderId()&&t&&!(this.m_unacknowledgedMessages.size<=0)){var i=this.getUnacknowledgedMessagesMapKey(e,t.messageTrackingOption()),n=this.m_unacknowledgedMessages.get(i);n&&e.messageId===n.message.messageId&&this.m_unacknowledgedMessages.delete(i)}},e.prototype.notifyUnacknowledgedMessages=function(){var e=this,t=Date.now();this.m_unacknowledgedMessages.forEach((function(i,n){if(i.timestamp+e.m_unacknowledgedMaxTimeInMs<t){var r=e.getHandlerForMessage(i.message);null==r||r.handleUnacknowledgedMessage(i.message),e.m_unacknowledgedMessages.delete(n),e.m_telemetry.unacknowledgedMessagesCount+=1}}))},e.prototype.clearUnacknowledgedTimer=function(){this.m_unacknowledgedTimer&&(clearInterval(this.m_unacknowledgedTimer),this.m_unacknowledgedTimer=null)},e.prototype.startInitTimeoutTimerWithRetry=function(e,t){var i=this;this.startInitTimeoutTimer(e,(function(){i.m_logger.sendTraceTag(509141836,kS.TraceLevel.Error,"SimpleStateServiceProxy::startInitTimeoutTimer - failed to init after "+e+" ms; requesting get messages and retrying"),i.sendGetInitialSystemStateMessages(),i.startInitTimeoutTimer(e,t)}))},e.prototype.startInitTimeoutTimer=function(e,t){e>0&&(this.clearInitTimeoutTimer(),this.m_initTimeoutTimer=setTimeout((function(){t("Initialization timed out after "+e+" ms")}),e))},e.prototype.clearInitTimeoutTimer=function(){this.m_initTimeoutTimer&&clearTimeout(this.m_initTimeoutTimer)},e.prototype.sendConnectionMessage=function(e,t){var i,n,r=this;if(this.m_allowReconnectOnMessageSend&&this.m_connectionState===DS.ConnectionState.Disconnected&&(this.updateRetryAttempts(),this.retryConnection((function(e){r.m_logger.sendTraceTag(559428289,kS.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - failed to reconnect with error: "+Qy.errorToString(e)+" ")}),!1)),this.m_offlineMessageCacheEnabled&&t){if(!this.m_connection||this.m_connectionState!==DS.ConnectionState.Connected)return!this.m_maxOfflineMessageCacheLength||this.m_offlineMessageCache.length>=this.m_maxOfflineMessageCacheLength?(this.m_telemetry.offlineCacheTelemetry.rejectedCount+=1,void this.m_logger.sendTraceTag(570807006,kS.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - Dropping message because offline cache is full. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Status: "+(null===(i=this.m_connection)||void 0===i?void 0:i.readyState)+"}")):(!this.m_offlineMessageCacheTimer&&this.m_maxOfflineMessageCacheTimeInMs&&(this.m_offlineMessageCacheTimer=setInterval((function(){r.purgeOfflineMessageCache()}),this.m_maxOfflineMessageCacheTimeInMs/2)),this.m_offlineMessageCache.push({message:e,timestamp:Date.now()}),void(this.m_telemetry.offlineCacheTelemetry.cachedCount+=1))}else{if(!this.m_connection)return void this.m_logger.sendTraceTag(590213401,kS.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - connection is not set. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+"}");if(!this.m_connection.isOpen)return void this.m_logger.sendTraceTag(590213402,kS.TraceLevel.Error,"SimpleStateServiceProxy::sendConnectionMessage - "+this.m_connection.name+" status is not open. {sessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", Status: "+this.m_connection.readyState+"}")}null===(n=this.m_connection)||void 0===n||n.send(JSON.stringify(e))},e.prototype.closeAndClearConnection=function(){if(this.m_connection){if(this.m_connection.onclose=function(){},this.m_connection.isOpen)this.m_connection.close();else{var e=this.m_connection;e.onopen=function(){return e.close()}}this.m_connection=null}},e.prototype.updateRetryAttempts=function(){this.m_retryAttempts>=this.m_retryIntervalsInMs.length&&(this.m_retryAttempts=0),this.m_sessionRetryAttempts>=this.m_maxSessionRetries&&(this.m_sessionRetryAttempts=0)},e.prototype.measureMessageRoundTripLatency=function(e){if(e.senderId===this.senderId())try{var t=this.m_outboundMessageInfo.get(e.messageId);if(void 0!==t){this.m_outboundMessageInfo.delete(e.messageId);var i=Date.now()-t;this.m_events.emit("messageRoundTripped",{clientId:this.m_clientId,sessionId:this.m_sessionId,messageId:e.messageId,objectId:e.objectId,operation:e.operation,latencyInMs:i}),this.m_telemetry.addRoundtripLatency(i)}else this.m_verbose&&this.m_logger.sendTraceTag(590213404,kS.TraceLevel.Info,"SimpleStateServiceProxy::measureMessageRoundTripLatency. Failed to find outbound message info for {SessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", ObjectId: "+e.objectId+", MessageId: "+e.messageId+"}")}catch(t){this.m_logger.sendTraceTag(590213405,kS.TraceLevel.Error,"SimpleStateServiceProxy::measureMessageRoundTripLatency - Exception thrown error. {SessionId: "+this.m_sessionId+", ClientId: "+this.m_clientId+", MessageId: "+e.messageId+", Error: "+t.message+"}")}},e}();t.SimpleStateServiceProxy=c})),aC=s((function(e,t){var i=a&&a.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},n=a&&a.__generator||function(e,t){var i,n,r,a,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(e){return function(t){return l([e,t])}}function l(a){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createStateServiceProxyAsync=void 0,t.createStateServiceProxyAsync=function(e,t,r,a,s,o){return i(this,void 0,void 0,(function(){var i;return n(this,(function(n){switch(n.label){case 0:return[4,(i=new rC.SimpleStateServiceProxy(e,t,r,a,s,o)).connectAsync()];case 1:return n.sent(),[2,i]}}))}))}})),sC=s((function(e,t){var i=a&&a.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[i]}})}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),n=a&&a.__exportStar||function(e,t){for(var n in e)"default"===n||t.hasOwnProperty(n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),n(kS,t),n(DS,t),n(aC,t)}));class oC{constructor(e){this.enableConsoleLog=yc().calling.reaction.enableStateServiceConsoleLogs,this._logger=e}sendTraceTag(e,t,i){this.enableConsoleLog&&this._logger.info(`Tag: ${e}, Leve: ${t}, Message: ${i}`)}}class lC{constructor(e){this._wsUrl="",this.name="Reaction",this.capabilityChangeHandler=e=>{e.newValue.useReactions&&(this._participantCapability=this._call.getParticipantCapabilities().useReactions,this._logger.log(`participant capabilitity to useReactions feature is ${this._participantCapability}`))},this._eventEmitter=e,this._participantCapability={isPresent:!0,reason:"Capable"},this._isReactionFeatureEnabled=yc().calling.reaction.enabled}initialize(e,t,i,n,r,a){void 0===this._proxy||this._proxy?.getConnectionState()===sC.ConnectionState.Disconnected?(this._logger=r.createChild((()=>`ReactionImplOverStateService::Call(id='${this._tsCall.callId}')`)),this._internalCallAgent=t,this._tsCall=e,this._call=i,this._callInfo=a,this._docId=this._tsCall.callId,this._wsUrl=this.getEndpointUrl(),this._telemetryLogManager=n,this._sendAttempOrFailureFeatureUsage("initialize",Yh.attempt),this.start()):r.info("State Service Proxy already has an active connection."),"teamsMeetingJoin"==this._callInfo.context&&(this._participantCapability=this._call.getParticipantCapabilities().useReactions,this._logger.log(`participant capabilitity to useReactions feature is ${this._participantCapability}`),this._call.onParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler),this._logger.log("participant capabilities change event listener registered"))}async start(){const e=yc().calling.reaction.StateServiceProxySettings,t={getAuthTokenAsync:this.getAuthToken.bind(this)};try{this._proxy=await sC.createStateServiceProxyAsync(this._docId,"ACSWeb",this._wsUrl,new oC(this._logger),e,t)}catch(e){return this._logger.error("Could not create state service proxy",e),void this._sendAttempOrFailureFeatureUsage("initialize",Yh.failure,new b({defaultError:f.FEATURES.REACTION.STATE_SERVICE_CONNECT_FAIL,originalError:e}))}try{this._reactionsMap=await this._proxy.createMapAsync("reactions",!0)}catch(e){return this._logger.error("Could not create state service proxy reaction map",e),void this._sendAttempOrFailureFeatureUsage("initialize",Yh.failure,new b({defaultError:f.FEATURES.REACTION.MAP_CREATE_FAIL,originalError:e}))}this._sendSuccessFeatureUsage("initialize",Yh.success),this._reactionsMap?.on("valueChanged",this.onReactionsReceived.bind(this))}async getAuthToken(){const e={token:await this._internalCallAgent.tokenProvider(),authProvider:"SKYPE",mri:this._internalCallAgent.getUserMri()};return Promise.resolve(e)}async sendReaction(e,t){if(!this._isReactionFeatureEnabled||!this._participantCapability.isPresent){const e=new b({defaultError:f.FEATURES.REACTION.SEND_FAIL_POLICY});throw this._sendAttempOrFailureFeatureUsage("sendReaction",Yh.failure,e,t),e}if(!this._reactionsMap){this._logger.error("Reaction Map has not yet been initialized.");const e=new b({defaultError:f.FEATURES.REACTION.NOT_INIT_YET});throw this._sendAttempOrFailureFeatureUsage("sendReaction",Yh.failure,e,t),e}try{return this._reactionsMap?.set(this._internalCallAgent.getUserMri(),{name:e.reactionType}),void this._sendSuccessFeatureUsage("sendReaction",Yh.success,t,e.reactionType)}catch(e){this._logger.error("Unable to send reaction",e);const i=new b({defaultError:f.FEATURES.REACTION.SEND_REACTION_FAIL,originalError:e});throw this._sendAttempOrFailureFeatureUsage("sendReaction",Yh.failure,i,t),i}}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async onReactionsReceived(e){if(3===this._tsCall.state&&this._participantCapability.isPresent){const t=x();this._sendAttempOrFailureFeatureUsage("receiveReaction",Yh.attempt,void 0,t);try{const i={reactionType:(await(this._reactionsMap?.get(e))).name};this._eventEmitter.emit("reaction",{identifier:e,reactionMessage:i}),this._sendSuccessFeatureUsage("receiveReaction",Yh.success,t,i.reactionType)}catch(e){this._logger.error("Unable to parse reaction",e);let i=new b({defaultError:f.FEATURES.REACTION.RECEIVE_REACTION_FAIL,originalError:e});this._sendAttempOrFailureFeatureUsage("receiveReaction",Yh.failure,i,t)}}}dispose(){void 0!==this._telemetryLogManager&&(this._proxy?.getConnectionState()===sC.ConnectionState.Connected?(this._reactionsMap?.removeAllListeners("valueChanged"),this._proxy.close(),this._sendSuccessFeatureUsage("dispose",Yh.success),this._call.offParticipantCapabilitiesChanged("capabilitiesChanged",this.capabilityChangeHandler)):this._sendSuccessFeatureUsage("dispose",Yh.failure))}_sendAttempOrFailureFeatureUsage(e,t,i,n){let r=i?{code:i?.code||_,subCode:i?.subCode||0,failureReason:i?.message||"",...xg(i)}:void 0;bg({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}_sendSuccessFeatureUsage(e,t,i,n){let r;r="initialize"===e||"dispose"==e?void 0:{reactionConstraint:{reactionType:n}},bg({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}getEndpointUrl(){const e=this._internalCallAgent._caConfigBag,t=e&&Lc(e.identityType,e.region);var i=yc().PowerPointStateServiceUrl.public.amer;switch(e?.cloudType){case qo.Public:t&&(i=yc().PowerPointStateServiceUrl.public.eu);break;case qo.GccHigh:i=yc().PowerPointStateServiceUrl.gcch;break;case qo.AirGap08:i=yc().PowerPointStateServiceUrl.ag08;break;case qo.AirGap09:i=yc().PowerPointStateServiceUrl.ag09;break;case qo.Dod:i=yc().PowerPointStateServiceUrl.dod;break;default:i=yc().PowerPointStateServiceUrl.public.amer}return`wss://${new URL(i).hostname}/StateServiceHandler.ashx`}}class cC{get contentSharingSession(){return this._contentSharingSession}constructor(e){this._contentSharingSession=e}getFileDetails(){if(this.contentSharingSession)return JSON.parse(atob(this.contentSharingSession.contentSharingIdentity))}}const dC="azure_communication_calling_pptLive";class uC{constructor(e){this._isActive=!1,this._isInitializingPPTLive=!1,this._updateIsActive=e=>this._isActive!==e&&(this._isActive=e,this._logger.info(`Updating isActive to ${e}`),!0),this._eventEmitter=e,this._target=document.createElement("div"),this._target.id=dC,this._target.style.width="100%",this._target.style.height="100%"}initialize(e,t,i,n){this._logger=n.createChild((()=>`PPTLive::Call(id='${e.callId}')`)),this._tsCall=e,this._internalCallAgent=t,this._telemetryLogManager=i,this._tsCall.on("contentSharingChanged",(()=>{this._checkContentSharingSession(this._tsCall.contentSharingSessions)})),this._tsCall.on("callStateChanged",(()=>{this._updatePPTLive(this._tsCall.state)}))}get isActive(){return this._isActive}get target(){return this._target}get activePresenterId(){return this._activePresenterId}_checkContentSharingSession(e){if(this._contentSharing&&0===e.length)this._updateIsActive(!1),this._contentSharing=void 0,this._target.innerHTML="",this._isInitializingPPTLive=!1,this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("endedPPTLive",Yh.success);else if(!this._contentSharing&&0!==e.length){if(!yc().calling.pptlive.enabled)return;this._contentSharing=new cC(e[0]),this._updatePPTLive(this._tsCall.state),this._sendFeatureUsage("startedPPTLive",Yh.attempt,this._contentSharing?.contentSharingSession?.contentSharingGuid)}}async _updatePPTLive(e){this._fileDetails=this._contentSharing?.getFileDetails(),this._fileDetails&&"ppt"===this._fileDetails.type&&3===e&&await this._startPPTLive(this._target)}_updateActivePresenter(){this._tsCall.participants.forEach((e=>{const t=ac(e.id);2===e.contentSharingRole&&(this._activePresenterId=t)}))}_sendFeatureUsage(e,t,i){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"PPTLive",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:{pptLiveConstraint:{contentId:i}}},this._telemetryLogManager,this._logger)}_observeDivMount(){const e=new MutationObserver((async t=>{if(this._isActive){if(!this._isInitializingPPTLive)for(const i of t)for(let t=0;t<i.addedNodes.length;t++){const n=i.addedNodes[t];if(n.nodeType===Node.ELEMENT_NODE&&n.matches(`#${dC}`)){await this._startPPTLive(this._target),e.disconnect();break}}}else e.disconnect()}));e.observe(document.body,{childList:!0,subtree:!0})}_initViewerWithExperiment(e,t,i,n,r,a,s,o,l,c,d,u,h,p,g){const m=window.Microsoft,f=yc().calling.pptlive,v={Container:e,SessionInformation:{DocumentClickTime:new Date,HostInitTime:new Date,UiLocale:u,DataLocale:u,IsPresenter:!1,WdParams:{wdModernSlideShowInTeams:f.wdParams.wdModernSlideShowInTeams,wdPresenterViewInTeams:f.wdParams.wdPresenterViewInTeams,wdForceModernSlideShowInTeams:f.wdParams.wdForceModernSlideShowInTeams,isMovePrivateViewingToPPTEnabled:f.wdParams.isMovePrivateViewingToPPTEnabled},PptFeatureGates:f.featureGates,ParticipantId:o,EnableStateServiceInPreviewerFeatures:JSON.parse(f.enableStateServiceInPreviewerFeatures),StateServiceSettings:{stateServiceProxySettings:f.stateServiceProxySettings,regionalEndpointUrl:this._getEndpointUrl(),authEnabled:!1,rosterCheckEnabled:!1,stateServiceUser:{getAuthTokenAsync:!1,getForceRefreshedTokenAsync:!1}},ContentId:h,EndpointId:s,CallId:p,HostName:"ACSWeb",HostSessionId:l},WopiPrecheckInfo:{FileName:n,FileGetUrl:a,FileSize:r,CustomFontCatalogUrl:g,BundleInfo:{MajorVersion:i,Url:c},CreateNewInfo:null},ApplicationCustomSettings:{TakeFocusOnBoot:f.appSettings.takeFocusOnBoot,EnableAdvanceOnClick:f.appSettings.enableAdvanceOnClick,EnableAdvanceOnTap:f.appSettings.enableAdvanceOnTap},Diagnostics:{entryPoint:"null"},FnOnInitializeSuccess:e=>{e.GoToSlide(t,[],""),this._isInitializingPPTLive=!1,this._observeDivMount(),this._sendFeatureUsage("startedPPTLive",Yh.success,this._contentSharing?.contentSharingSession?.contentSharingGuid)},FnOnInitializeFailure:e=>{this._isInitializingPPTLive=!1;var t="Category: "+e.Category+"\nMessage: "+e.Message+"\nExtraInfo: "+e.ExtraInfo;this._sendFeatureUsage("startedPPTLive",Yh.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid),this._logger.error(t)}};d&&(v.ApplicationCustomSettings.EnableWacFallback=!1,v.ApplicationUrl=d),m.Office.PowerPoint.Bootstrap.Prefetch(),m.Office.PowerPoint.Bootstrap.InitializeWopiPending(v),this._updateActivePresenter(),this._updateIsActive(!0),this._eventEmitter.emit("isActiveChanged"),this._sendFeatureUsage("startedPPTLive",Yh.initialize,this._contentSharing?.contentSharingSession?.contentSharingGuid)}async _startPPTLive(e){this._fileDetails?.bootstrapperUrl&&(this._isInitializingPPTLive=!0,e.innerHTML="",await this._loadDynamicModule(this._fileDetails.bootstrapperUrl).then((()=>{this._fileDetails&&this._initViewerWithExperiment(e,Number(this._contentSharing?.contentSharingSession?.contentSharingState),this._fileDetails.majorVersion,this._fileDetails.name,this._fileDetails.fileSize,this._fileDetails.fileGetUrl,this._tsCall.endpointId,this._tsCall.participantId,x(),this._fileDetails.contentBundleUrl,this._fileDetails.wacUrl,navigator.language,this._fileDetails.id,this._tsCall.callId,this._fileDetails.customFontCatalogUrl)})).catch((()=>{this._sendFeatureUsage("startedPPTLive",Yh.failure,this._contentSharing?.contentSharingSession?.contentSharingGuid)})))}_getEndpointUrl(){const e=this._internalCallAgent._caConfigBag,t=e&&Lc(e.identityType,e.region);let i=yc().PowerPointStateServiceUrl.public.amer;switch(e?.cloudType){case qo.Public:t&&(i=yc().PowerPointStateServiceUrl.public.eu);break;case qo.GccHigh:i=yc().PowerPointStateServiceUrl.gcch;break;case qo.AirGap08:i=yc().PowerPointStateServiceUrl.ag08;break;case qo.AirGap09:i=yc().PowerPointStateServiceUrl.ag09;break;case qo.Dod:i=yc().PowerPointStateServiceUrl.dod;break;default:i=yc().PowerPointStateServiceUrl.public.amer}return i}async _loadDynamicModule(e){return new Function(`return (async () => await import('${e}'))()`)()}}const hC={Recording:Eg(class extends hg{constructor(e){super(e),this._impl=new pf(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"Recording"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",Yh.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",Yh.getter),this._impl.recordings}on(e,t){if("isRecordingActiveChanged"!==e&&"recordingsUpdated"!==e)throw new b({defaultError:f.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("isRecordingActiveChanged"!==e&&"recordingsUpdated"!==e)throw new b({defaultError:f.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Recording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),Transfer:Eg(class extends hg{constructor(e){super(e),this._impl=new Ef(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"Transfer"}transfer(e,t){return this._impl.transfer(e,t)}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}on(e,t){this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transfer",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),Transcription:Eg(class extends hg{constructor(e){super(e),this._impl=new yf(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"Transcription"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}get isTranscriptionActive(){return this._sendFeatureUsage("isTranscriptionActive",Yh.getter),this._impl.isTranscriptionActive}on(e,t){this._sendFeatureUsage("isTranscriptionActiveChanged",Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage("isTranscriptionActiveChanged",Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Transcription",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),Captions:Eg(class extends hg{constructor(e){super(e),this._impl=new jg(this.eventEmitter)}initialize(e,t){const i=x();this._impl.initialize(e.tsCall,e.call,e.callAgent,e.callAgent.getHttpRequestHelper(),e.telemetryLogManager,t,this._telemetryStartTime,i),this._logger=t,this._telemetryStartTime=+Date.now(),this._telemetryLogManager=e.telemetryLogManager,this._call=e.call}get name(){return this._sendFeatureUsage("name",Yh.getter),this._captionsTelemetryType.toString()}get _captionsTelemetryType(){return"TeamsCaptions"===this._impl.kind?Cg.TeamsCaptions:Cg.Captions}get captions(){return this._impl.captions}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:this._captionsTelemetryType,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),RaiseHand:Eg(class extends hg{constructor(e){super(e),this._impl=new zg(this.eventEmitter)}get name(){return"RaiseHand"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)}async raiseHand(){return this._impl.raiseHand()}async lowerHand(){return this._impl.lowerHand()}async lowerHands(e){return this._impl.lowerHands(e)}lowerAllHands(){return this._impl.lowerAllHands()}getRaisedHands(){return this._sendFeatureUsage("getRaisedHands",Yh.getter),this._impl.raisedHands}on(e,t){this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"RaiseHand",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),LocalRecording:Eg(class extends hg{constructor(e){super(e),this._impl=new vf(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"LocalRecording"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}get isRecordingActive(){return this._sendFeatureUsage("isRecordingActive",Yh.getter),this._impl.isRecordingActive}get recordings(){return this._sendFeatureUsage("recordings",Yh.getter),this._impl.recordings}on(e,t){if("isLocalRecordingActiveChanged"!==e&&"localRecordingsUpdated"!==e)throw new b({defaultError:f.FEATURES.RECORDING.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("isLocalRecordingActiveChanged"!==e&&"localRecordingsUpdated"!==e)throw new b({defaultError:f.FEATURES.RECORDING.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t,i){let n=i?{code:i?.code||_,subCode:i?.subCode||0,failureReason:i?.message||""}:void 0;bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"LocalRecording",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:n},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),Reaction:Eg(class extends hg{constructor(e){super(e),this._impl=new lC(this.eventEmitter),this._isReactionFeatureEnabled=yc().calling.reaction.enabled,this._callInfo=e.callInfo}get name(){return"Reaction"}initialize(e,t){this._tsCall=e.tsCall,this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._logger.info(`Meeting Reaction feature enable flag: ${this._isReactionFeatureEnabled}`),this._isReactionFeatureEnabled&&3===e.tsCall.state?this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t,this._callInfo):e.tsCall.on("callStateChanged",(()=>{this._isReactionFeatureEnabled&&3===e.tsCall.state?this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t,this._callInfo):this._logger.warn("Calls to reaction APIs will perform no action or return default values where applicable")}))}async sendReaction(e){let t=x();if(this._sendFeatureUsage("sendReaction",Yh.attempt,void 0,t),3!=this._tsCall.state||1===this._tsCall.callType){const e=new b({defaultError:3!=this._tsCall.state?f.FEATURES.REACTION.CALL_NOT_CONNECTED:f.FEATURES.REACTION.NOT_SUPPORTED_1TO1_CTE});throw this._sendFeatureUsage("sendReaction",Yh.failure,e,t),e}await this._impl.sendReaction(e,t)}on(e,t){if("reaction"!==e)throw new b({defaultError:f.FEATURES.REACTION.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});if(!this._isReactionFeatureEnabled){const e=new b({defaultError:f.FEATURES.REACTION.EVENT_SUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",Yh.failure,e),e}this._sendFeatureUsage("receiveReaction",Yh.subscribe),this._impl.on(e,t)}off(e,t){if("reaction"!==e)throw new b({defaultError:f.FEATURES.REACTION.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});if(!this._isReactionFeatureEnabled){const e=new b({defaultError:f.FEATURES.REACTION.EVENT_UNSUBSCRIBE_FAIL_POLICY});throw this._sendFeatureUsage("receiveReaction",Yh.failure,e),e}this._sendFeatureUsage("receiveReaction",Yh.unsubscribe),this._impl.off(e,t)}dispose(){this.disposed||(this._impl.dispose(),super.dispose())}_sendFeatureUsage(e,t,i,n){let r=i?{code:i?.code||_,subCode:i?.subCode||0,failureReason:i?.message||"",...xg(i)}:void 0;bg({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t},additionalDetails:r},this._telemetryLogManager,this._logger)}}),Spotlight:Eg(class extends hg{constructor(e){super(e),this._impl=new cS(this.eventEmitter),this._isSpotlightFeatureEnabled=yc().calling.spotlight.enabled}get name(){return"Spotlight"}initialize(e,t){this._logger=t,this._logger.info(`Spotlight feature enable flag: ${this._isSpotlightFeatureEnabled}`),this._isSpotlightFeatureEnabled?(this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)):this._logger.warn("Calls to spotlight APIs will perform no action or return default values where applicable")}async startSpotlight(e){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(e)&&await this._impl.startSpotlight(e)}async stopSpotlight(e){this._isSpotlightFeatureEnabled&&this.validateIdentifierParam(e)&&await this._impl.stopSpotlight(e)}async stopAllSpotlight(){this._isSpotlightFeatureEnabled&&await this._impl.stopAllSpotlight()}getSpotlightedParticipants(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("getSpotlightedParticipants",Yh.getter),this._impl.spotlightedParticipants):[]}get maxParticipantsToSpotlight(){return this._isSpotlightFeatureEnabled?(this._sendFeatureUsage("maxSpotlightSupportedState",Yh.getter),this._impl.maxSpotlightStateSupported):0}on(e,t){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t))}off(e,t){this._isSpotlightFeatureEnabled&&(this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t))}validateIdentifierParam(e=[]){try{return e.forEach((e=>oc(e))),!0}catch(e){return!1}}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:this.name,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),PPTLive:Eg(class extends hg{constructor(e){super(e),this._impl=new uC(this.eventEmitter)}on(e,t){this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}get isActive(){return this._impl.isActive}get target(){return this._impl.target}get activePresenterId(){return this._impl.activePresenterId}get name(){return"PPTLive"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:e,featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),Capabilities:Eg(class extends hg{constructor(e){super(e),this._callInfo=e.callInfo,this._impl=new Yg(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"Capabilities"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._tsCall=e.tsCall,this._impl.initialize(e.tsCall,e.callAgent,e.call,this._callInfo,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}get capabilities(){return this._sendFeatureUsage("getCapabilities",Yh.getter),this._impl.capabilities}on(e,t){this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"Capabilities",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this.disposed||super.dispose()}}),DominantSpeakers:Eg(class extends hg{constructor(e){super(e),this._impl=new Im(this.eventEmitter)}get name(){return this._sendFeatureUsage("name",Yh.getter),"DominantSpeakers"}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t),this._sendFeatureUsage("initialize",Yh.initialize)}get dominantSpeakers(){return this._sendFeatureUsage("dominantSpeakers",Yh.getter),this._impl.dominantSpeakers}on(e,t){this._sendFeatureUsage("dominantSpeakersChanged",Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){this._sendFeatureUsage("dominantSpeakersChanged",Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"DominantSpeakers",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),LiveStream:Eg(class extends hg{constructor(e){super(e),this._impl=new nv(this.eventEmitter,this.name)}get name(){return"LiveStream"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}dispose(){this._impl.dispose(),super.dispose()}get liveStreams(){return this._impl.liveStreams}get participantCount(){return this._impl.streamingClientCount}on(e,t){if("liveStreamsUpdated"!==e&&"participantCountChanged"!==e)throw new b({defaultError:f.FEATURES.LIVE_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("liveStreamsUpdated"!==e&&"participantCount"!==e)throw new b({defaultError:f.FEATURES.LIVE_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}createStatsCollector(e){return this._impl.createStatsCollector(e)}}),ComposedStream:Eg(class extends hg{constructor(e){super(e),this._impl=new av(this.eventEmitter,this.name)}get name(){return"ComposedStream"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}dispose(){this._impl.dispose(),super.dispose()}get composedStreams(){return this._impl.composedStreams}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}),CallSurvey:Eg(class extends hg{constructor(e){super(e),this._impl=new dS}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}get name(){return"CallSurvey"}dispose(){super.dispose()}submitSurvey(e){return this._impl.submitSurvey(e)}}),UserFacingDiagnostics:Eg(class extends hg{constructor(e){super(e),this._impl=new _m}get name(){return this._sendFeatureUsage("name",Yh.getter),"Diagnostics"}get network(){return this._sendFeatureUsage("network",Yh.getter),this._impl.network}get media(){return this._sendFeatureUsage("media",Yh.getter),this._impl.media}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call,this._impl.initialize(e,t),this._sendFeatureUsage("initialize",Yh.initialize)}_sendFeatureUsage(e,t){bg({callId:this._call.id,localParticipantId:this._call.tsCall.participantId,featureName:"Diagnostics",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),MediaStats:Eg(df,{activationEvent:"OnExtendedObjectConstructor"}),DebugInfo:Tg(class extends gg{constructor(e){super(e),this._impl=new em;try{uc().includes("stable")||(this._browserTabInfoImpl=new tm(this.eventEmitter))}catch(t){e.callClient.logger.error("Feature to detect multiple tabs is not supported on the current environment.")}}get name(){return this._sendFeatureUsage("name",Yh.getter),"DebugInfo"}get lastLocalParticipantId(){return this._sendFeatureUsage("lastLocalParticipantId",Yh.getter),this._impl.lastLocalParticipantId}get logs(){return this._impl.logDump}get localParticipantIdMap(){return this._impl.localParticipantIdMap}get incommingCallIdMap(){return this._impl.incommingCallIdMap}get lastCallId(){if(this._sendFeatureUsage("lastCallId",Yh.getter),this.lastLocalParticipantId)return this._impl.localParticipantIdMap[this.lastLocalParticipantId].callIds.slice(-1)[0]}get diagnosticInformation(){return this._impl.diagnosticInformation}get sdkVersion(){return uc()}get acsResourceId(){return this._impl.AcsResourceId}get clientId(){return this._impl.clientId}dumpDebugInfoAsJSONString(){try{return JSON.stringify(this.toZip())}catch(e){return`JSON.stringify threw: ${e}`}}toZip(){return{clientId:this.clientId,lastLocalParticipantId:this.lastLocalParticipantId,localParticipantIdMap:this.localParticipantIdMap,incommingCallMap:this.incommingCallIdMap,AcsResourceId:this.acsResourceId,diagnosticInformation:this.diagnosticInformation,sdkVersion:this.sdkVersion,logs:this.logs}}dumpDebugInfo(){this._sendFeatureUsage("dumpDebugInfo",Yh.attempt);try{const e=Mh.deflate(this.dumpDebugInfoAsJSONString(),{to:"string"}),t=Xg(e);return this._sendFeatureUsage("dumpDebugInfo",Yh.success),{dump:e,dumpId:`${x()}-${t}`}}catch(e){const t=`failed to deflate, error: ${e}`;return this.logger.error(t),this._sendFeatureUsage("dumpDebugInfo",Yh.failure),{dump:Mh.deflate(t,{to:"string"}),dumpId:x()}}}initialize(e,t){this._impl.initialize(e,t),this.logger=t,this._telemetryLogManager=e.telemetryLogManager,this._callClient=e.callClient,this._browserTabInfoImpl&&this._browserTabInfoImpl.initialize(e.callClient,t,e.telemetryLogManager),this._sendFeatureUsage("initialize",Yh.initialize)}async getEnvironmentInfo(){return this._sendFeatureUsage("getEnvironmentInfo",Yh.getter),await this._callClient.getEnvironmentInfoInternal()}get isAnotherCallClientActiveInSameTab(){return this._sendFeatureUsage("isAnotherCallClientActiveInSameTab",Yh.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isAnotherCallClientActiveInSameTab}get isCallClientActiveInAnotherTab(){return this._sendFeatureUsage("isCallClientActiveInAnotherTab",Yh.getter),!!this._browserTabInfoImpl&&this._browserTabInfoImpl.isCallClientActiveInAnotherTab}on(e,t){"isCallClientActiveInAnotherTabChanged"!==e&&"isAnotherCallClientActiveInSameTabChanged"!==e&&this.logger.error(`Not able to subscribe to event ${e}, unknown event name`),this._sendFeatureUsage(e,Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){"isCallClientActiveInAnotherTabChanged"!==e&&"isAnotherCallClientActiveInSameTabChanged"!==e&&this.logger.error(`Not able to unsubscribe to event ${e}, unknown event name`),this._sendFeatureUsage(e,Yh.unsubscribe),this.eventEmitter.off(e,t)}_sendFeatureUsage(e,t){Ig({featureName:"DebugInfo",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this.logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}},{activationEvent:"OnExtendedObjectConstructor"}),PreCallDiagnostics:Tg(class extends gg{constructor(e){super(e),this._impl=new Kf}initialize(e,t){const i=e.callClient;this._logger=t;const n=i.createInstance({diagnostics:{tags:["diagnostics"]}});this._telemetryLogManager=n.telemetryLogManager,this._impl.intialize(i,n,t,this._telemetryLogManager),this._sendFeatureUsage("initialize",Yh.initialize)}get name(){return this._sendFeatureUsage("name",Yh.getter),"PreCallDiagnostics"}startTest(e,t){return this._impl.startTest(e,t)}_sendFeatureUsage(e,t){Ig({featureName:"PreCallDiagnostics",featureType:"CallClient",initializationType:"OnExtendedObjectConstructor",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}dispose(){this._sendFeatureUsage("dispose",Yh.attempt),this.disposed?this._sendFeatureUsage("dispose",Yh.failure):(this._impl.dispose(),super.dispose(),this._sendFeatureUsage("dispose",Yh.success))}}),VideoEffects:function(e,t={activationEvent:"OnFeatureAccess"}){return{get videoStreamApiCtor(){return e},activationOptions:t,isVideoStreamFeature:!0}}(class extends mg{constructor(){super(...arguments),this._effect=null,this._fpsWarningEventIntervalIds=[],this._fpsWarningEventTimeoutIds=[],this._tsCallingEffectCapability=0,this._tsCallingSupportedEffects=[{acsEffect:"Off",tsCallingEffect:0}],this._activeEffects=[],this.configUpdatedCallback=async e=>{const t=this._internalDeviceManager.getTsDeviceManager();if("BackgroundReplacement"===e){const e=(this._effect?._internalHandle?.effectConfig).backgroundImageUrl;e&&await t.setBackgroundImageAsync("",e)}},this.processingErrorCallback=async e=>{const t=x();this.eventEmitter.emit("effectsError",e);const i=this.getEffectNameForTelemetry(this._effect?.name),n=this.getUsageDetailsForTelemetry("Internal handle error",i);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.effectsError,kindOfEvent:Yh.failure,additionalDetails:{failureReason:e.message,code:e.code,...xg(e),usageDetails:n}}),await this.stopEffects()},this.effectStatusChangedCallback=(e,t)=>{if(t.length>0){const e=this._effect?.name?[this._effect.name]:t;this.eventEmitter.emit("effectsStarted",e)}else{const t=this._effect?.name?[this._effect.name]:e;this.eventEmitter.emit("effectsStopped",t)}}}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this.updateEffectStatusManager()}get name(){return"VideoEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"fpsWarningThresholdReached"!==e&&"timeForEffectsWarningReached"!==e)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t);const i=x();this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:i,operation:xp.subscribe,additionalDetails:{usageDetails:`Subscribed to ${e}`}})}off(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"fpsWarningThresholdReached"!==e&&"timeForEffectsWarningReached"!==e)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}async isSupported(e){const t=x(),i=+new Date,n=this.getEffectNameForTelemetry(e?.name),r=this.getUsageDetailsForTelemetry("",n);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,kindOfEvent:Yh.attempt,additionalDetails:{usageDetails:r}});try{const n=this.getEffectInternalCast(e);if(this.disposed)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const r=this._internalDeviceManager.getEnvironmentInfoInternal();this._supportChecker||(this._supportChecker=new ov(this._logger,r));const a=await this._supportChecker.videoEffectsSupported();this._logger.info(`Support check for ${n.name} resulted in: ${a}`);const s=this.getUsageDetailsForTelemetry("",n.name);return this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.success,additionalDetails:{usageDetails:s}}),a}catch(n){const r=new b({defaultError:f.FEATURES.VIDEO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:n});this._logger.error(r.message);const a=this.getEffectNameForTelemetry(e?.name),s=this.getUsageDetailsForTelemetry("",a);throw this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.failure,additionalDetails:{failureReason:r.message,code:r.code,...xg(r),usageDetails:s}}),r}}async startEffects(e){const t=x(),i=+new Date,n=this.getEffectNameForTelemetry(e?.name),r=this.getUsageDetailsForTelemetry("",n);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,kindOfEvent:Yh.attempt,additionalDetails:{usageDetails:r}});try{if(!yc().videoEffects.enableVideoEffects)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.DISABLED});if(this.disposed)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_SOURCE});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this.updateEffectStatusManager(),this.subscribeToStreamInstanceEvents();const n=window.performance.now();if(this._effect=this.getEffectInternalCast(e),!await this.isSupported(e))throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});const r=this._internalDeviceManager.getTsDeviceManager();if(!r)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.START_DEVICE_MANAGER});this.setConfigForEffects(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();const a=await this._effect._internalHandle.getEffectProvider();if(!a)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.PROVIDER_UNAVAILABLE});const s=await a.getVideoEffectProvider(),o=this.streamInstance.callStackWebCVProvider;if(!o)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.WEBCV_PROVIDER_FAILED});o.videoEffectProviderDeferredPromise.resolve(s),0===this._tsCallingEffectCapability&&(this._tsCallingEffectCapability=await(r?.getDeviceEffectsCapabilityAsync(""))),this._tsCallingSupportedEffects=this.getTsCallingSupportedEffects();const l=this._tsCallingSupportedEffects.find((e=>e.acsEffect===this._effect?.name));if(!l)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await(r?.setDeviceEffectsAsync("",l.tsCallingEffect)),this._effectsStatusManager.setActiveEffects([this._effect.name]),this._logger.info(`Video effects started: ${this._effect.name}`);const c=window.performance.now();this.handleEffectsInitTimeEvent(n,c),this.handleFpsWarningEvent();const d=this.getUsageDetailsForTelemetry("",this._effect.name);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.success,additionalDetails:{usageDetails:d}})}catch(n){const r=new b({defaultError:f.FEATURES.VIDEO_EFFECTS.START_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r),this.clearFpsCheckInterval();const a=this.getEffectNameForTelemetry(e?.name),s=this.getUsageDetailsForTelemetry("",a);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.failure,additionalDetails:{failureReason:r.message,code:r.code,...xg(r),usageDetails:s}})}}async stopEffects(){const e=x(),t=+new Date;this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:e,operation:xp.stopEffects,kindOfEvent:Yh.attempt});try{if(this.clearFpsCheckInterval(),this.disposed)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const i=this._internalDeviceManager.getTsDeviceManager();if(!i)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.STOP_DEVICE_MANAGER});this.updateEffectStatusManager();const n=this._tsCallingSupportedEffects.find((e=>"Off"===e.acsEffect));if(!n)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.UNSUPPORTED_EFFECT});await i.setDeviceEffectsAsync("",n.tsCallingEffect),this._effectsStatusManager?.setActiveEffects([]);const r=this.getEffectNameForTelemetry(this._effect?.name);this._logger.info(`Video effects stopped: ${r}`),this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:e,operation:xp.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.success})}catch(i){const n=new b({defaultError:f.FEATURES.VIDEO_EFFECTS.STOP_FAILED,originalError:i});this._logger?.error(n.message),this.eventEmitter.emit("effectsError",n),this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:e,operation:xp.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,additionalDetails:{failureReason:n.message,code:n.code,...xg(n)}})}}async dispose(){try{if(this.disposed)return void this._logger.info("VideoEffects feature already disposed");this._effect&&(await this.stopEffects(),this._effect._internalHandle.dispose(),this._effect=null),this.eventEmitter.removeAllListeners(),this._effectsStatusManager?.off("statusChanged",this.effectStatusChangedCallback),this.disposed=!0,this._logger.info("VideoEffects feature disposed")}catch(e){const t=new b({defaultError:f.FEATURES.VIDEO_EFFECTS.DISPOSE_FAILED,originalError:e});this._logger?.error(t.message),this.eventEmitter.emit("effectsError",t)}}getEffectInternalCast(e){if("BackgroundBlur"===e?.name&&this.isValidEffectInstance(e))return e;if("BackgroundReplacement"===e?.name&&this.isValidEffectInstance(e))return e;throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(e){let t;return("BackgroundBlur"===e.name&&void 0!==e._internalHandle||"BackgroundReplacement"===e.name&&void 0!==e._internalHandle)&&(t=e,this.hasValidInternalHandle(t._internalHandle))}hasValidInternalHandle(e){return void 0!==e.effectConfig&&void 0!==e.getEffectProvider&&void 0!==e.dispose&&void 0!==e.getStats&&void 0!==e.setConfig}getTsCallingSupportedEffects(){const e=[];return Object.values(lv).forEach((t=>{(this._tsCallingEffectCapability&t.tsCallingEffect)===t.tsCallingEffect&&e.push(t)})),e}subscribeToEffectEvents(){this._effect&&this._internalDeviceManager?(this._effect._internalHandle.on("configUpdated",this.configUpdatedCallback),this._effect._internalHandle.on("processingError",this.processingErrorCallback)):this._logger.debug("No effect instance found.")}disposeEffectEventSubscriptions(){this._effect?(this._effect._internalHandle.off("configUpdated",this.configUpdatedCallback),this._effect._internalHandle.off("processingError",this.processingErrorCallback)):this._logger.debug("No effect instance found.")}subscribeToStreamInstanceEvents(){this.streamInstance.on("videoSourceChanged",(async e=>{e.source&&"Video"!==e.source.mediaStreamType&&await this.stopEffects()}))}handleEffectsInitTimeEvent(e,t){if(!this._effect)return void this._logger.debug("No effect active");const i=x(),n=t-e,r=this._effect._internalHandle.effectConfig.effectInitTimeThresholdInMs;if(this._logger.info(`Time for effects to start: ${n}ms`),r&&n>r){this.eventEmitter.emit("timeForEffectsWarningReached",this._effect.name);const e=this.getUsageDetailsForTelemetry(`Threshold value: ${r}ms`,this._effect.name);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:i,operation:xp.timeForEffectsWarningReached,additionalDetails:{usageDetails:e}})}}handleFpsWarningEvent(){if(!this._effect)return void this._logger.debug("No effect active");this.clearFpsCheckInterval();const e=yc(),t=x(),i=e.videoEffects.waitTimeToInitiateFpsChecksInMs,n=e.videoEffects.fpsCheckIntervalTimeInMs;this._fpsWarningThresholdValue=this._effect._internalHandle.effectConfig.fpsWarningThreshold??e.videoEffects.fpsWarningThreshold;const r=window.setTimeout((()=>{const e=window.setInterval((()=>{const i=this._effect?._internalHandle.getStats(),n=i?.processor.fpsAvg;if(this._logger.info(`Effects avg fps check interval poll. Current Avg - ${n}`),n&&n<this._fpsWarningThresholdValue){this.eventEmitter.emit("fpsWarningThresholdReached",this._effect?.name),window.clearInterval(e),this._logger.info(`Effects fps warning threshold hit at ${n}fps`);const i=this.getUsageDetailsForTelemetry(`Fps reported: ${n}, Fps warning threshold value: ${this._fpsWarningThresholdValue}`,this._effect?.name);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.fpsWarningThresholdReached,additionalDetails:{usageDetails:i}})}}),n);this._fpsWarningEventIntervalIds.push(e)}),i);this._fpsWarningEventTimeoutIds.push(r)}setConfigForEffects(){if(!this._effect)return void this._logger.debug("No effect active");const e=this._effect._internalHandle.configProvider.config.videoEffects??this._effect._internalHandle.configProvider.config,t=Cc(),i=yc();if(t?.enableVideoEffects&&i?.videoEffects?.enableVideoEffects&&(e.enableVideoEffects=t.enableVideoEffects&&i.videoEffects.enableVideoEffects),e.effectConfig={...e.effectConfig,effectInitTimeThresholdInMs:i.videoEffects.effectInitTimeThresholdInMs,fpsWarningThreshold:i.videoEffects.fpsWarningThreshold},t.webcv){const i=t.webcv;e.webcvConfig={...e.webcvConfig,...i}}this._effect._internalHandle.setConfig(e),this._logger.info(`Config for effects set: ${bc(e)}`)}sendFeatureUsageTelemetry(e){if(this._telemetryLogManager)try{const t={correlationId:e.correlationId,mediaType:Np.VideoRaw,streamType:Lp.Local,operation:e.operation,timestampInfo:e.timestampInfo||{},kindOfEvent:e.kindOfEvent||"",additionalDetails:e.additionalDetails||""};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:t})}catch(t){this._logger.debug(`Unable to send ${e.operation} telemetry`)}else this._logger.debug("Telemetry error. Instance is undefined.")}getEffectNameForTelemetry(e){let t="UNKNOWN";return e?t="string"==typeof e?e:JSON.stringify(e):this._effect?.name?t=this._effect.name:this._activeEffects?.[0]&&(t=JSON.stringify(this._activeEffects[0])),t}getUsageDetailsForTelemetry(e,t=""){return`${t?`[${t}] `:""}${e}`}clearFpsCheckInterval(){this._fpsWarningEventIntervalIds.forEach((e=>{window.clearInterval(e)})),this._fpsWarningEventTimeoutIds.forEach((e=>{window.clearTimeout(e)})),this._fpsWarningEventIntervalIds=[],this._fpsWarningEventTimeoutIds=[]}updateEffectStatusManager(){this.streamInstance.canStartEffects?(this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this._effectsStatusManager||(this._effectsStatusManager=this._internalDeviceManager.callStackVideoEffectsStatusManager,this._effectsStatusManager.on("statusChanged",this.effectStatusChangedCallback)),this._activeEffects=this._effectsStatusManager.getActiveEffects()):this._logger.warn("Cannot update status manager, current source is not supported.")}}),AudioEffects:function(e,t={activationEvent:"OnFeatureAccess"}){return{get audioStreamApiCtor(){return e},activationOptions:t,isVideoStreamFeature:!0}}(class extends fg{constructor(){super(...arguments),this._wasmVqeInitialized=!1,this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this._currentEffects={},this._previousTsWasmEffectType=0,this._currentTsWasmEffectType=0,this._stringForUnknownInput="UNKNOWN",this._audioEffectsProcessorStats=null,this.effectStatusChangedCallback=(e,t,i)=>{"start"===i&&this.eventEmitter.emit("effectsStarted",t),"stop"===i&&this.eventEmitter.emit("effectsStopped",t)},this.configUpdatedCallback=async e=>{this._logger?.info("configUpdated callback, no-op.")},this.processingErrorCallback=async e=>{const t=x();this._logger?.info("processingError callback"),this.eventEmitter.emit("effectsError",e);const i=this.getEffectsNameForTelemetry(this.activeEffects),n=this.getUsageDetailsForTelemetry("Internal handle error",i);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.stopEffects,kindOfEvent:Yh.failure,additionalDetails:{failureReason:e.message,...xg(e),usageDetails:n}}),await this.stopEffects({echoCancellation:!0,noiseSuppression:!0})},this.subscribeToStatUpdates=async()=>{let e=null;for(let t of Object.values(this._currentEffects))t&&"object"==typeof t&&(e=t);if(!e)return;const t=await e._internalHandle.getEffectProvider(),i=await(t?.getAudioEffectProvider());let n=null;i&&(this._audioEffectProviderSub=i?.on?.("onMetricsUpdated",(()=>{try{n=i?.getStats&&i.getStats(),n&&(this._audioEffectsProcessorStats={activeAudioEffects:JSON.stringify(this.activeEffects),audioEffectsSpeechProcessingStats:{localAudioInputSpeechRMS_dBFS:n?.speechLevels?.nearEndInputRMS_dBFS,localAudioOutputSpeechRMS_dBFS:n?.speechLevels?.nearEndOutputRMS_dBFS,localAudioInputNoiseRMS_dBFS:n?.noiseLevels?.nearEndInputRMS_dBFS,localAudioOutputNoiseRMS_dBFS:n?.noiseLevels?.nearEndOutputRMS_dBFS,remoteAudioInputSpeechRMS_dBFS:n?.speechLevels?.farEndInputRMS_dBFS,remoteAudioOutputSpeechRMS_dBFS:n?.speechLevels?.farEndOutputRMS_dBFS},rawStats:JSON.stringify(n)}),this.eventEmitter.emit("effectsProcessorStatsUpdated",this._audioEffectsProcessorStats)}catch(e){this._logger?.warn(`Could not emit audio effect processor stat event: ${e}`)}})),this._logger?.info("Subscribed to audioEffectsProvider stat updates"))},this.unsubscribeFromStatUpdates=()=>{let e=null;for(let t of Object.values(this._currentEffects))t&&"object"==typeof t&&(e=t);e?this._logger?.info("There is a wasm audio effect still active, skipping stat unsubscribe"):this._audioEffectProviderSub?.dispose&&(this._audioEffectProviderSub.dispose(),this._audioEffectProviderSub=()=>{},this._audioEffectsProcessorStats=null,this._logger?.info("Unsubscribed from audioEffectsProvider stat updates"))}}initialize(e,t){this._logger=t,this._telemetryLogManager=e.telemetryLogManager,this.updateAudioEffectsStatusManager()}get name(){return"AudioEffects"}get activeEffects(){return this._effectsStatusManager?.getActiveEffects?.()??this._activeEffects}on(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"effectsProcessorStatsUpdated"!==e)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("effectsStarted"!==e&&"effectsStopped"!==e&&"effectsError"!==e&&"effectsProcessorStatsUpdated"!==e)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}async isSupported(e){const t=x(),i=+new Date,n=this.getUsageDetailsForTelemetry("",this.getEffectsNameForTelemetry(e));this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,kindOfEvent:Yh.attempt,additionalDetails:{usageDetails:n}});try{if(this.disposed)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const n=this._internalDeviceManager.getEnvironmentInfoInternal();this._supportChecker||(this._supportChecker=new ov(this._logger,n));let r=!1;if("object"==typeof e){const t=this.getEffectInternalCast(e);r=await this._supportChecker.audioEffectsSupported(t),this._logger?.info(`Support check for ${t.name} resulted in: ${r}`)}else"string"==typeof e&&(r=await this._supportChecker.audioEffectsSupported(e),this._logger?.info(`Support check for ${e} resulted in: ${r}`));const a=this.getEffectsNameForTelemetry(e),s=this.getUsageDetailsForTelemetry("",a);return this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.success,additionalDetails:{usageDetails:s}}),r}catch(n){const r=new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SUPPORT_CHECK_FAILED,originalError:n});this._logger?.error(r.message);const a=this.getEffectsNameForTelemetry(e),s=this.getUsageDetailsForTelemetry("",a);throw this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.isSupported,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.failure,additionalDetails:{failureReason:r.message,code:r.code,...xg(r),usageDetails:s}}),r}}async startEffects(e){const t=x(),i=+new Date,n=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(e)));this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,kindOfEvent:Yh.attempt,additionalDetails:{usageDetails:n}});try{const n=yc();if(!n?.audioEffects?.enableAudioEffects)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.DISABLED});if(this.disposed)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.START_DISPOSED});if(!this.streamInstance.canStartEffects)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SOURCE_UNSUPPORTED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const r=this._internalDeviceManager.getTsDeviceManager();if(!r)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.START_DEVICE_MANAGER});this.updateAudioEffectsStatusManager(),this.subscribeToStreamInstanceEvents(),this.disposeEffectEventSubscriptions(),this.subscribeToEffectEvents();let a=this.activeEffects;e?.autoGainControl&&(a=await this.startStopAutoGainControl(r,a,!0,e.autoGainControl)),e?.echoCancellation&&(a=await this.startStopEchoCancellation(r,a,!0,e.echoCancellation)),e?.noiseSuppression&&(a=await this.startStopNoiseSuppression(r,a,!0,e.noiseSuppression)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&await r.setAudioEffectsAsync("",this._currentTsWasmEffectType),this._effectsStatusManager?.setActiveEffects(a,"start"),await this.subscribeToStatUpdates();const s=JSON.stringify(a),o=this.getUsageDetailsForTelemetry("",s);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.success,additionalDetails:{usageDetails:o}})}catch(n){const r=new b({defaultError:f.FEATURES.AUDIO_EFFECTS.START_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r);const a=JSON.stringify(this.getEffectsConfigForTelemetry(e)),s=this.getUsageDetailsForTelemetry("",a);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.startEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.failure,additionalDetails:{failureReason:r.message,code:r.code,...xg(r),usageDetails:s}})}}async stopEffects(e){const t=x(),i=+new Date,n=this.getUsageDetailsForTelemetry("",JSON.stringify(this.getEffectsConfigForTelemetry(e)));this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.stopEffects,kindOfEvent:Yh.attempt,additionalDetails:{usageDetails:n}});try{if(this.disposed)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.STOP_DISPOSED});this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager);const n=this._internalDeviceManager.getTsDeviceManager();if(!n)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.STOP_DEVICE_MANAGER});this.updateAudioEffectsStatusManager();let r=this.activeEffects;e?.autoGainControl&&(r=await this.startStopAutoGainControl(n,r,!1)),e?.echoCancellation&&(r=await this.startStopEchoCancellation(n,r,!1)),e?.noiseSuppression&&(r=await this.startStopNoiseSuppression(n,r,!1)),this._currentTsWasmEffectType!==this._previousTsWasmEffectType&&await n.setAudioEffectsAsync("",this._currentTsWasmEffectType),this._effectsStatusManager?.setActiveEffects(r,"stop"),this.unsubscribeFromStatUpdates();const a=JSON.stringify(r),s=this.getUsageDetailsForTelemetry("",a);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.success,additionalDetails:{usageDetails:s}})}catch(n){const r=new b({defaultError:f.FEATURES.AUDIO_EFFECTS.STOP_FAILED,originalError:n});this._logger?.error(r.message),this.eventEmitter.emit("effectsError",r);const a=JSON.stringify(this.getEffectsConfigForTelemetry(e)),s=this.getUsageDetailsForTelemetry("",a);this.sendFeatureUsageTelemetry({eventName:Jh.acs_calling_media_stream,correlationId:t,operation:xp.stopEffects,timestampInfo:{deltaTimeInMs:+new Date-i},kindOfEvent:Yh.failure,additionalDetails:{failureReason:r.message,code:r.code,...xg(r),usageDetails:s}})}}async dispose(){try{if(this.disposed)return void this._logger?.info("AudioEffects feature already disposed");await this.stopEffects({echoCancellation:!0,noiseSuppression:!0}),this._currentEffects={},this.eventEmitter.removeAllListeners(),this._effectsStatusManager?.off("statusChanged",this.effectStatusChangedCallback),this.disposed=!0,this._logger?.info("AudioEffects feature disposed")}catch(e){const t=new b({defaultError:f.FEATURES.AUDIO_EFFECTS.DISPOSE_FAILED,originalError:e});this._logger?.error(t.message),this.eventEmitter.emit("effectsError",t)}}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}updateAudioEffectsStatusManager(){this.streamInstance.canStartEffects?(this._internalDeviceManager||(this._internalDeviceManager=this.streamInstance.source.deviceManager),this._effectsStatusManager||(this._effectsStatusManager=this._internalDeviceManager.callStackAudioEffectsStatusManager,this._effectsStatusManager.on("statusChanged",this.effectStatusChangedCallback)),this._activeEffects=this._effectsStatusManager.getActiveEffects(),this._browserAudioEffectsManager=new pS(this._effectsStatusManager,this._logger)):this._logger?.warn("Cannot update status manager, current source is not supported.")}async initializeWasmVqeInStack(e){if(this._wasmVqeInitialized)return void this._logger?.info("WasmVqe initialized already");if(!this._internalDeviceManager)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.FAILED_TO_GET_DM});const t=await e._internalHandle.getEffectProvider();if(!t)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.PROVIDER_UNAVAILABLE});const i=await t.getAudioEffectProvider(),n=this.streamInstance.callStackWasmVqeProvider;if(!n)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.AEC_PROVIDER_MISSING});n.providerValue=i,this._wasmVqeInitialized=!0}getEffectInternalCast(e){if("EchoCancellation"===e?.name&&this.isValidEffectInstance(e))return e;if("NoiseSuppression"===e?.name&&this.isValidEffectInstance(e))return e;if("DeepNoiseSuppression"===e?.name&&this.isValidEffectInstance(e))return e;throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT})}isValidEffectInstance(e){let t;return("EchoCancellation"===e.name&&e._internalHandle||"NoiseSuppression"===e.name&&e._internalHandle||!("DeepNoiseSuppression"!==e.name||!e._internalHandle))&&(t=e,this.hasValidInternalHandle(t._internalHandle))}hasValidInternalHandle(e){return!!(e.getEffectProvider&&e.dispose&&e.setConfig&&e.handleProcessingError)}updateCurrentTsWasmAudioEffectType(e,t,i){const n=i??this._effectsStatusManager?.getActiveEffects();let r=!!n?.echoCancellation?.includes("EchoCancellation"),a=!!n?.noiseSuppression?.includes("NoiseSuppression"),s=!!n?.noiseSuppression?.includes("DeepNoiseSuppression");switch(e){case"EchoCancellation":r=t;break;case"NoiseSuppression":a=t;break;case"DeepNoiseSuppression":s=t}this._previousTsWasmEffectType=this._currentTsWasmEffectType,this._currentTsWasmEffectType=r&&a?8:r&&s?16:r?4:a?1:s?2:0}subscribeToStreamInstanceEvents(){this.streamInstance.on("audioSourceChanged",(async e=>{e.source&&"Audio"!==e.source.mediaStreamType&&await this.stopEffects({echoCancellation:!0,noiseSuppression:!0})}))}subscribeToEffectEvents(){"object"==typeof this._currentEffects.echoCancellation&&(this._currentEffects.echoCancellation?._internalHandle.on("configUpdated",this.configUpdatedCallback),this._currentEffects.echoCancellation?._internalHandle.on("processingError",this.processingErrorCallback)),"object"==typeof this._currentEffects.noiseSuppression&&(this._currentEffects.noiseSuppression?._internalHandle.on("configUpdated",this.configUpdatedCallback),this._currentEffects.noiseSuppression?._internalHandle.on("processingError",this.processingErrorCallback))}disposeEffectEventSubscriptions(){"object"==typeof this._currentEffects.echoCancellation&&(this._currentEffects.echoCancellation?._internalHandle.off("configUpdated",this.configUpdatedCallback),this._currentEffects.echoCancellation?._internalHandle.off("processingError",this.processingErrorCallback)),"object"==typeof this._currentEffects.noiseSuppression&&(this._currentEffects.noiseSuppression?._internalHandle.off("configUpdated",this.configUpdatedCallback),this._currentEffects.noiseSuppression?._internalHandle.off("processingError",this.processingErrorCallback))}setConfigForEffects(e){const t=e._internalHandle.configProvider.config.audioEffects,i=Cc(),n=yc();i?.wasmvqe?.enableVqe&&n?.audioEffects?.enableAudioEffects&&(t.enableAudioEffects=i?.wasmvqe?.enableVqe&&n.audioEffects.enableAudioEffects),e._internalHandle.setConfig(t),this._logger?.info(`Config for audio effects set: ${bc(t)}`)}async startStopAutoGainControl(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("BrowserAutoGainControl"!==n)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_GAINCONTROL});return await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{autoGainControl:!0})),this._logger?.info("Browser auto gain control started"),this._currentEffects.autoGainControl=n,t.autoGainControl=[n],t}switch(t?.autoGainControl?.[0]??""){case"":case"BrowserAutoGainControl":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{autoGainControl:!1})),this._logger?.info("Browser auto gain control stopped")}return t.autoGainControl=[],this._currentEffects.autoGainControl=void 0,t}catch(e){throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SET_AUTO_GAIN_CONTROL,defaultErrorMessageArgs:[i],originalError:e})}}async startStopEchoCancellation(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("string"==typeof n&&"BrowserEchoCancellation"===n)await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{echoCancellation:!0})),this._logger?.info("Browser echo cancellation started"),this._currentEffects.echoCancellation=n,t.echoCancellation=[n];else{if("object"!=typeof n)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_ECHO});this._currentEffects.echoCancellation=this.getEffectInternalCast(n),this.setConfigForEffects(this._currentEffects.echoCancellation),await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.echoCancellation.name,!0,t),t.echoCancellation=[this._currentEffects.echoCancellation.name]}return t}switch(t?.echoCancellation?.[0]??""){case"":case"BrowserEchoCancellation":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{echoCancellation:!1})),this._logger?.info("Browser echo cancellation stopped");break;case"EchoCancellation":await this.initializeWasmVqeInStack(this._currentEffects.echoCancellation),this.updateCurrentTsWasmAudioEffectType("EchoCancellation",!1,t)}return t.echoCancellation=[],this._currentEffects.echoCancellation=void 0,t}catch(e){throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SET_ECHO_CANCELLATION,defaultErrorMessageArgs:[i],originalError:e})}}async startStopNoiseSuppression(e,t,i,n){try{if(i&&n){if(!await this.isSupported(n)){const e=this.getEffectsNameForTelemetry(n);throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.UNSUPPORTED_EFFECT,defaultErrorMessageArgs:[JSON.stringify(e)]})}if("string"==typeof n&&"BrowserNoiseSuppression"===n)await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{noiseSuppression:!0})),this._logger?.info("Browser noise cancellation started"),t.noiseSuppression=[n],this._currentEffects.noiseSuppression=n;else{if("object"!=typeof n)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.INVALID_EFFECT_NOISE_SUPP});this._currentEffects.noiseSuppression=this.getEffectInternalCast(n),this.setConfigForEffects(this._currentEffects.noiseSuppression),await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType(this._currentEffects.noiseSuppression.name,!0,t),t.noiseSuppression=[this._currentEffects.noiseSuppression.name]}return t}switch(t?.noiseSuppression?.[0]??""){case"":case"BrowserNoiseSuppression":await(this._browserAudioEffectsManager?.setBrowserAudioEffects(e,t,{noiseSuppression:!1})),this._logger?.info("Browser noise suppression stopped");break;case"NoiseSuppression":await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("NoiseSuppression",!1,t);break;case"DeepNoiseSuppression":await this.initializeWasmVqeInStack(this._currentEffects.noiseSuppression),this.updateCurrentTsWasmAudioEffectType("DeepNoiseSuppression",!1,t)}return t.noiseSuppression=[],this._currentEffects.noiseSuppression=void 0,t}catch(e){throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.SET_NOISE_SUPPRESSION,defaultErrorMessageArgs:[i],originalError:e})}}sendFeatureUsageTelemetry(e){if(this._telemetryLogManager)try{const t={correlationId:e.correlationId,mediaType:Np.AudioRaw,streamType:Lp.Local,operation:e.operation,timestampInfo:e.timestampInfo||{},kindOfEvent:e.kindOfEvent||"",additionalDetails:e.additionalDetails||""};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:t})}catch(t){this._logger?.debug(`Unable to send ${e.operation} telemetry`)}else this._logger?.debug("Telemetry error. Instance is undefined.")}getEffectsConfigForTelemetry(e){let t=!1;"boolean"!=typeof e?.autoGainControl&&"boolean"!=typeof e?.echoCancellation&&"boolean"!=typeof e?.noiseSuppression||(t=!0);let i={};return i=t?{autoGainControl:e?.autoGainControl&&"boolean"==typeof e?.autoGainControl?e?.autoGainControl:void 0,echoCancellation:e?.echoCancellation&&"boolean"==typeof e?.echoCancellation?e?.echoCancellation:void 0,noiseSuppression:e?.noiseSuppression&&"boolean"==typeof e?.noiseSuppression?e?.noiseSuppression:void 0}:{autoGainControl:this.getEffectsNameForTelemetry(e?.autoGainControl),echoCancellation:this.getEffectsNameForTelemetry(e?.echoCancellation),noiseSuppression:this.getEffectsNameForTelemetry(e?.noiseSuppression)},Object.keys(i).forEach((e=>{""!==i[e]&&void 0!==i[e]||delete i[e]})),i}getEffectsNameForTelemetry(e){return e?"string"==typeof e?this.truncateToMax(e):e?.name&&"string"==typeof e?.name?this.truncateToMax(e.name):(this._logger?.warn("Invalid effect object found"),this._stringForUnknownInput):""}getUsageDetailsForTelemetry(e,t){const i=`${t?`[${t}]`:""}:${e??""}`;return this.truncateToMax(i)}truncateToMax(e){const t=yc().audioEffects.maxStringLengthForTelemetry;return this._logger?.info("Truncating audio effects info for telemetry"),e.length>t?e.substring(0,t-2)+"..":e}}),DataChannel:Eg(class extends hg{constructor(e){super(e)}createDataChannelSender(e){const t=x(),i=yc();try{if(void 0!==e.bitrateInKbps&&"number"!=typeof e.bitrateInKbps)throw mv("bitrateInKbps","number");if(void 0!==e.channelId&&"number"!=typeof e.channelId)throw mv("channelId","number");if(void 0!==e.participants&&!Array.isArray(e.participants))throw mv("participants","CommunicationIdentifier[]");if(void 0!==e.priority&&-1===["High","Normal"].indexOf(e.priority))throw fv("priority","High,Normal");if(void 0!==e.reliability&&-1===["Durable","Lossy"].indexOf(e.reliability))throw fv("reliability","Durable,Lossy");const n={bitrateInKbps:Math.ceil(e.bitrateInKbps??i.dataChannel.defaultBitrate/1e3),channelId:e.channelId??0,participants:e.participants??[],priority:e.priority??"Normal",reliability:e.reliability??"Durable"};this._logger.info(`createDataChannelSender: ${function(e){const t=[];return void 0!==e.bitrateInKbps&&t.push(`bitrateInKbps=${e.bitrateInKbps}`),void 0!==e.channelId&&t.push(`channelId=${e.channelId}`),void 0!==e.participants&&t.push(`participants size=${e.participants.length}`),void 0!==e.priority&&t.push(`priority=${e.priority}`),void 0!==e.reliability&&t.push(`reliability=${e.reliability}`),t.join(",")}(e)}`),this._sendFeatureUsage("createDataChannelSender",Yh.attempt),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"attempt",correlationId:t,senderOptions:{channelId:e.channelId,bitrateInKbps:e.bitrateInKbps,participantsSize:e.participants?.length,priority:e.priority,reliability:e.reliability}});const r=this._dataChannelManager.createSender(n,t);return this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"success",correlationId:t,senderOptions:{channelId:r.channelId,bitrateInKbps:n.bitrateInKbps,participantsSize:n.participants?.length,priority:n.priority,reliability:n.reliability}}),this._logger.info(`The sender is created. channel id=${r.channelId}`),this._sendFeatureUsage("createDataChannelSender",Yh.success),r}catch(e){const i=new b({defaultError:f.FEATURES.DATA_CHANNEL.FAILED_TO_CREATE_SENDER,originalError:e});throw this._logger.info(`Failed to create the sender: ${i.message}`),this._sendFeatureUsage("createDataChannelSender",Yh.failure),this._dataChannelTelemetryLogger.sendCreateSenderEvent({kindOfEvent:"failure",correlationId:t,failureReason:i.message,additionalDetails:{...xg(i)}}),i}}async createDataChannelAdapter(e){const t=new wv(this._tsCall,e);return await t.initialize(),t}initialize(e,t){this._tsCall=e.tsCall,this._logger=t.createChild("DataChannelCallFeature"),this._telemetryLogManager=e.telemetryLogManager,this._dataChannelTelemetryLogger=new lS(this._tsCall,this._telemetryLogManager);const i=new oS(this._tsCall,this._logger,this._dataChannelTelemetryLogger);this._dataChannelManager=i,this._dataChannelManager.initialize().then((()=>{this._sendFeatureUsage("initialize",Yh.initialize)})).catch((e=>{this._logger.error(`initialize:${Ev(e)}`)}))}get name(){return this._sendFeatureUsage("name",Yh.getter),"DataChannel"}dispose(){this.disposed||(this._dataChannelManager?.dispose(),super.dispose())}on(e,t){if("dataChannelReceiverCreated"!==e)throw gv(e,"subscribe");this._sendFeatureUsage(e,Yh.subscribe),"dataChannelReceiverCreated"===e&&this._dataChannelManager?.on("dataChannelReceiverCreated",t)}off(e,t){if("dataChannelReceiverCreated"!==e)throw gv(e,"unsubscribe");this._sendFeatureUsage(e,Yh.unsubscribe),"dataChannelReceiverCreated"===e&&this._dataChannelManager?.off("dataChannelReceiverCreated",t)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"DataChannel",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),OptimalVideoCount:Eg(class extends hg{_sendOVCTelemetryEvent(e){if(!this._telemetryLogManager)return;const t={callId:this._call?.id||"",localParticipantId:this._tsCall?.participantId||"",featureName:"OptimalVideoCount",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{step:e}};this._telemetryLogManager.sendEvent({name:Jh.acs_calling_feature_usage,tenant:hl,properties:t})}get optimalVideoCount(){return this._sendOVCTelemetryEvent(Yh.getter),this._tsCall?.optimalVideoCount?this._tsCall.optimalVideoCount:1}constructor(e){super(e),this.name="OptimalVideoCount",this._impl=new hS(this.name,this.eventEmitter,this.optimalVideoCount)}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t),this._tsCall=e.tsCall,this._telemetryLogManager=e.telemetryLogManager,this._call=e.call}on(e,t){if("optimalVideoCountChanged"!==e)throw new b({defaultError:f.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendOVCTelemetryEvent(Yh.subscribe),this.eventEmitter.on(e,t)}off(e,t){if("optimalVideoCountChanged"!==e)throw new b({defaultError:f.FEATURES.OPTIMAL_VIDEO_COUNT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._sendOVCTelemetryEvent(Yh.unsubscribe),this.eventEmitter.off(e,t)}}),UnmixedAudio:Eg(class extends hg{constructor(e){super(e)}initialize(e,t){const i=yc().unmixedAudio;this._tsCall=e.tsCall,this._logger=t.createChild("UnmixedAudioCallFeature"),this._telemetryLogManager=e.telemetryLogManager;const n=new TS(this._tsCall,this._telemetryLogManager);this._unmixedAudioManager=new AS(this._tsCall,this._logger,n,i),this._unmixedAudioManager.initialize().then((()=>{this._sendFeatureUsage("initialize",Yh.initialize)})).catch((e=>{}))}get name(){return this._sendFeatureUsage("name",Yh.getter),"UnmixedAudio"}dispose(){this.disposed||(this._unmixedAudioManager.dispose(),super.dispose())}enableUnmixedAudio(){return this._unmixedAudioManager.enableUnmixedAudio()}disableUnmixedAudio(){return this._unmixedAudioManager.disableUnmixedAudio()}get isUnmixedAudioActive(){return this._unmixedAudioManager.isUnmixedAudioActive}on(e,t){if("participantSpeaking"!==e)throw gS(e,"subscribe");this._sendFeatureUsage(e,Yh.subscribe),this._unmixedAudioManager.on(e,t)}off(e,t){if("participantSpeaking"!==e)throw gS(e,"unsubscribe");this._sendFeatureUsage(e,Yh.unsubscribe),this._unmixedAudioManager.off(e,t)}_sendFeatureUsage(e,t){bg({callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"UnmixedAudio",featureType:"Call",initializationType:"OnFeatureAccess",featureDetails:{name:e,step:t}},this._telemetryLogManager,this._logger)}}),AudioZones:Eg(class extends hg{constructor(e){super(e),this._impl=new uS(this.eventEmitter,this.name)}get name(){return"AudioZones"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.call,e.telemetryLogManager,t)}updateAudioZone(e){return this._impl.updateAudioZone(e)}dispose(){this._impl.dispose(),super.dispose()}get meetingGroupDetails(){return this._impl.meetingGroupDetails}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}}),TeamsMeetingAudioConferencing:Eg(class extends hg{constructor(e){super(e),this._impl=new PS}get name(){return"TeamsMeetingAudioConferencing"}initialize(e,t){this._impl.initialize(e.tsCall,e.callAgent,e.telemetryLogManager,t)}async getTeamsMeetingAudioConferencingDetails(){return this._impl.getTeamsMeetingAudioConferencingDetails()}dispose(){this.disposed||super.dispose()}})};function pC(e){switch(e){case Yp.CallClientFeature:return Object.entries(hC).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case Yp.CallAgentFeature:return Object.entries(hC).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case Yp.CallFeature:return Object.entries(hC).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]))}}class gC{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild("CallStats"),this._telemetryLogManager=t}recordEvent(e){try{if(yc()?.telemetry?.callStatsFlushTimeout<0)return;if(yc()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;const t={...e,timestamp:+new Date};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemtryFlush()}catch(e){this._logger.debug("Failed to record call stats")}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),0!==this._eventBag.length)try{const e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_call_stats,tenant:hl,properties:{...e[t]}})})),this.resetEventBag()}catch(e){this._logger.debug("Failed to send call stats")}}scheduleTelemtryFlush(){this._callStatSendTimeout||(this._callStatSendTimeout=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),yc().telemetry.callStatsFlushTimeout))}}class mC{constructor(e){this._volumeIndicator=e,this._eventEmitter=new Kp}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on("levelChanged",(()=>{this._eventEmitter.emit("levelChanged")}))))}dispose(){this._eventEmitter.removeAllListeners()}}class fC{constructor(e,i,n,r){this._workQueue=Promise.resolve();const a=t.createClientLogger("ACS-calling");this.logger=new Pf(a,[()=>"RemoteAudioStream for media stream"]),this._source=e,this._disposed=!1,this._volumeIndicator=new xf(this.logger,"RemoteAudioStream",i,n,r),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await(this._volumeProxy?.setSource(await this._source.getMediaStream()))})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.message??"unknown error"}`)})))})),this.logger.info("created")}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log("dispose"),this._disposed?this.logger.log("already disposed"):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){const e=new mC(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(Oc),await t,this._volumeProxy=e}return this._volumeProxy}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([bf,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type",Object)],fC.prototype,"logger",void 0);var vC=s((function(e,t){!function(i,n){var r="function",a="undefined",s="object",o="string",l="model",c="name",d="type",u="vendor",h="version",p="architecture",g="console",m="mobile",f="tablet",v="smarttv",S="wearable",y="embedded",C="Amazon",_="Apple",E="ASUS",T="BlackBerry",b="Browser",I="Chrome",w="Firefox",R="Google",A="Huawei",P="LG",M="Microsoft",k="Motorola",D="Opera",O="Samsung",N="Sharp",L="Sony",x="Xiaomi",F="Zebra",U="Facebook",B=function(e){for(var t={},i=0;i<e.length;i++)t[e[i].toUpperCase()]=e[i];return t},V=function(e,t){return typeof e===o&&-1!==H(t).indexOf(H(e))},H=function(e){return e.toLowerCase()},$=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===a?e:e.substring(0,350)},G=function(e,t){for(var i,a,o,l,c,d,u=0;u<t.length&&!c;){var h=t[u],p=t[u+1];for(i=a=0;i<h.length&&!c;)if(c=h[i++].exec(e))for(o=0;o<p.length;o++)d=c[++a],typeof(l=p[o])===s&&l.length>0?2===l.length?typeof l[1]==r?this[l[0]]=l[1].call(this,d):this[l[0]]=l[1]:3===l.length?typeof l[1]!==r||l[1].exec&&l[1].test?this[l[0]]=d?d.replace(l[1],l[2]):n:this[l[0]]=d?l[1].call(this,d,l[2]):n:4===l.length&&(this[l[0]]=d?l[3].call(this,d.replace(l[1],l[2])):n):this[l]=d||n;u+=2}},j=function(e,t){for(var i in t)if(typeof t[i]===s&&t[i].length>0){for(var r=0;r<t[i].length;r++)if(V(t[i][r],e))return"?"===i?n:i}else if(V(t[i],e))return"?"===i?n:i;return e},z={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},W={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[h,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[h,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,h],[/opios[\/ ]+([\w\.]+)/i],[h,[c,D+" Mini"]],[/\bopr\/([\w\.]+)/i],[h,[c,D]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[c,h],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[h,[c,"UC"+b]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[h,[c,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[h,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[h,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[h,[c,"IE"]],[/yabrowser\/([\w\.]+)/i],[h,[c,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+b],h],[/\bfocus\/([\w\.]+)/i],[h,[c,w+" Focus"]],[/\bopt\/([\w\.]+)/i],[h,[c,D+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[h,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[h,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[h,[c,D+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[h,[c,"MIUI "+b]],[/fxios\/([-\w\.]+)/i],[h,[c,w]],[/\bqihu|(qi?ho?o?|360)browser/i],[[c,"360 "+b]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1 "+b],h],[/(comodo_dragon)\/([\w\.]+)/i],[[c,/_/g," "],h],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[c,h],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,U],h],[/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[c,h],[/\bgsa\/([\w\.]+) .*safari\//i],[h,[c,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[h,[c,I+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,I+" WebView"],h],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[h,[c,"Android "+b]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,h],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[h,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[h,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[h,j,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,h],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],h],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[h,[c,w+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[c,h],[/(cobalt)\/([\w\.]+)/i],[c,[h,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[p,"amd64"]],[/(ia32(?=;))/i],[[p,H]],[/((?:i[346]|x)86)[;\)]/i],[[p,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[p,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[p,"armhf"]],[/windows (ce|mobile); ppc;/i],[[p,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[p,/ower/,"",H]],[/(sun4\w)[;\)]/i],[[p,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[p,H]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[u,O],[d,f]],[/\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[l,[u,O],[d,m]],[/\((ip(?:hone|od)[\w ]*);/i],[l,[u,_],[d,m]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[u,_],[d,f]],[/(macintosh);/i],[l,[u,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[u,A],[d,f]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[u,A],[d,m]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[l,/_/g," "],[u,x],[d,m]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[u,x],[d,f]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[u,"OPPO"],[d,m]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[u,"Vivo"],[d,m]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[l,[u,"Realme"],[d,m]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[u,k],[d,m]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[u,k],[d,f]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[u,P],[d,f]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[u,P],[d,m]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[u,"Lenovo"],[d,f]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[u,"Nokia"],[d,m]],[/(pixel c)\b/i],[l,[u,R],[d,f]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[u,R],[d,m]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[u,L],[d,m]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[u,L],[d,f]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[u,"OnePlus"],[d,m]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[u,C],[d,f]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[u,C],[d,m]],[/(playbook);[-\w\),; ]+(rim)/i],[l,u,[d,f]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[u,T],[d,m]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[u,E],[d,f]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[u,E],[d,m]],[/(nexus 9)/i],[l,[u,"HTC"],[d,f]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic|sony(?!-bra))[-_ ]?([-\w]*)/i],[u,[l,/_/g," "],[d,m]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[u,"Acer"],[d,f]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[u,"Meizu"],[d,m]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[u,N],[d,m]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,l,[d,m]],[/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,l,[d,f]],[/(surface duo)/i],[l,[u,M],[d,f]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[u,"Fairphone"],[d,m]],[/(u304aa)/i],[l,[u,"AT&T"],[d,m]],[/\bsie-(\w*)/i],[l,[u,"Siemens"],[d,m]],[/\b(rct\w+) b/i],[l,[u,"RCA"],[d,f]],[/\b(venue[\d ]{2,7}) b/i],[l,[u,"Dell"],[d,f]],[/\b(q(?:mv|ta)\w+) b/i],[l,[u,"Verizon"],[d,f]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[u,"Barnes & Noble"],[d,f]],[/\b(tm\d{3}\w+) b/i],[l,[u,"NuVision"],[d,f]],[/\b(k88) b/i],[l,[u,"ZTE"],[d,f]],[/\b(nx\d{3}j) b/i],[l,[u,"ZTE"],[d,m]],[/\b(gen\d{3}) b.+49h/i],[l,[u,"Swiss"],[d,m]],[/\b(zur\d{3}) b/i],[l,[u,"Swiss"],[d,f]],[/\b((zeki)?tb.*\b) b/i],[l,[u,"Zeki"],[d,f]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],l,[d,f]],[/\b(ns-?\w{0,9}) b/i],[l,[u,"Insignia"],[d,f]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[u,"NextBook"],[d,f]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],l,[d,m]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],l,[d,m]],[/\b(ph-1) /i],[l,[u,"Essential"],[d,m]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[u,"Envizen"],[d,f]],[/\b(trio[-\w\. ]+) b/i],[l,[u,"MachSpeed"],[d,f]],[/\btu_(1491) b/i],[l,[u,"Rotor"],[d,f]],[/(shield[\w ]+) b/i],[l,[u,"Nvidia"],[d,f]],[/(sprint) (\w+)/i],[u,l,[d,m]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[u,M],[d,m]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[u,F],[d,f]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[u,F],[d,m]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,l,[d,g]],[/droid.+; (shield) bui/i],[l,[u,"Nvidia"],[d,g]],[/(playstation [345portablevi]+)/i],[l,[u,L],[d,g]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[u,M],[d,g]],[/smart-tv.+(samsung)/i],[u,[d,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[u,O],[d,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,P],[d,v]],[/(apple) ?tv/i],[u,[l,_+" TV"],[d,v]],[/crkey/i],[[l,I+"cast"],[u,R],[d,v]],[/droid.+aft(\w)( bui|\))/i],[l,[u,C],[d,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[u,N],[d,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[u,L],[d,v]],[/(mitv-\w{5}) bui/i],[l,[u,x],[d,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w ]*; *(\w[^;]*);([^;]*)/i],[[u,$],[l,$],[d,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,v]],[/((pebble))app/i],[u,l,[d,S]],[/droid.+; (glass) \d/i],[l,[u,R],[d,S]],[/droid.+; (wt63?0{2,3})\)/i],[l,[u,F],[d,S]],[/(quest( 2)?)/i],[l,[u,U],[d,S]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[d,y]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[l,[d,m]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[d,f]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,f]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,m]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[h,[c,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[h,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[c,h],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[h,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,h],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[c,[h,j,z]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[c,"Windows"],[h,j,z]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[h,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,"Mac OS"],[h,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[h,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,h],[/\(bb(10);/i],[h,[c,T]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[h,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[h,[c,w+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[h,[c,"webOS"]],[/crkey\/([\d\.]+)/i],[h,[c,I+"cast"]],[/(cros) [\w]+ ([\w\.]+\w)/i],[[c,"Chromium OS"],h],[/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,h],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],h],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[c,h]]},q=function(e,t){if(typeof e===s&&(t=e,e=n),!(this instanceof q))return new q(e,t).getResult();var r=e||(typeof i!==a&&i.navigator&&i.navigator.userAgent?i.navigator.userAgent:""),g=t?function(e,t){var i={};for(var n in e)t[n]&&t[n].length%2==0?i[n]=t[n].concat(e[n]):i[n]=e[n];return i}(W,t):W;return this.getBrowser=function(){var e={};return e[c]=n,e[h]=n,G.call(e,r,g.browser),e.major=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:n}(e.version),e},this.getCPU=function(){var e={};return e[p]=n,G.call(e,r,g.cpu),e},this.getDevice=function(){var e={};return e[u]=n,e[l]=n,e[d]=n,G.call(e,r,g.device),e},this.getEngine=function(){var e={};return e[c]=n,e[h]=n,G.call(e,r,g.engine),e},this.getOS=function(){var e={};return e[c]=n,e[h]=n,G.call(e,r,g.os),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return r},this.setUA=function(e){return r=typeof e===o&&e.length>350?$(e,350):e,this},this.setUA(r),this};q.VERSION="1.0.33",q.BROWSER=B([c,h,"major"]),q.CPU=B([p]),q.DEVICE=B([l,u,d,g,m,v,f,S,y]),q.ENGINE=q.OS=B([c,h]),e.exports&&(t=e.exports=q),t.UAParser=q;var K=typeof i!==a&&(i.jQuery||i.Zepto);if(K&&!K.ua){var J=new q;K.ua=J.getResult(),K.ua.get=function(){return J.getUA()},K.ua.set=function(e){J.setUA(e);var t=J.getResult();for(var i in t)K.ua[i]=t[i]}}}("object"==typeof window?window:a)}));const SC=[{name:"edge",engine:"Edge",key:"Edge"},{name:"edgeanaheim",engine:"Chromium",key:"Edg"},{name:"chromium",engine:"Chromium",key:"Chromium"},{name:"opera",engine:"Chromium",key:"OPR"},{name:"yandexbrowser",engine:"Chromium",key:"YaBrowser"},{name:"electron",engine:"Chromium",key:"Electron"},{name:"chrome",engine:"Chromium",key:"Chrome"},{name:"firefox",engine:"Firefox",key:"Firefox"},{name:"safari",engine:"Safari",key:"Safari"},{name:"applewebview",engine:"Safari",key:"Mac OS X"},{name:"ie",engine:"MSIE",key:"Trident"}],yC="0.0",CC="unknown";function _C(e){return/iPhone|iPad|iPod|Android|Mobi/i.test(e)?"Mobile":"Desktop"}let EC=new vC.UAParser;function TC(){return EC||(EC=new vC.UAParser),EC.getResult()}function bC(){const e=TC().ua;return-1!==e.indexOf("Edge")?"edge":-1!==e.indexOf("Electron")?"electron":-1!==e.indexOf("Chrome")?"chrome":-1!==e.indexOf("Firefox")?"firefox":-1!==e.indexOf("Safari")?"safari":-1!==e.indexOf("Mac OS X")?"applewebview":-1!==e.indexOf("Trident")?"ie":"unknown"}function IC(e,t){const i=t.find((({name:t})=>t===e));if(!i)return CC;let n=i.engine;return n=function(e,t){const i=AC();return"chrome"===e&&"ios"===i&&(t="Safari"),t}(e,n),n}function wC(){const e=TC();return"WebKit"===e.browser.name&&-1!==e.ua.indexOf("Mac OS X")?e.os.version??yC:void 0!==e.browser.version?e.browser.version:yC}function RC(){const e=TC(),t=e.ua,i=function(e,t){const i=t.find((({key:t})=>e.includes(t)));if(!i)return CC;let n=i.name;return n=function(e,t){return"edge"!==e&&"edgeanaheim"!==e||((t.includes("Edg/")||t.includes("EdgA/")||t.includes("EdgiOS/"))&&(e="edgeanaheim"),t.includes("Edge/")&&(e="edge")),e}(n,TC().ua),n}(e.browser.name,SC);return{name:i,engine:IC(i,SC),version:wC(),formFactor:_C(t)}}function AC(){const e=TC().ua;return/windows phone/i.test(e)?"windowsphone":/windows /i.test(e)?"windows":/macintosh/i.test(e)?"mac":/(ipod|iphone|ipad)/i.test(e)?"ios":function(e){const t=!/like android/i.test(e),i=/android/i.test(e);return t&&i}(e)?"android":/(web|hpw)[o0]s/i.test(e)?"webos":/tizen/i.test(e)?"tizen":/headlesschrome(?:\/([\w\.]+)| )/i.test(e)?"headlesschrome":/linux/i.test(e)?"linux":/CrOS/.test(e)?"chrome":"other"}function PC(){const e=TC();return void 0!==e.os.version?e.os.version:yC}function MC(e){return/^\d+$/.test(e)}function kC(e,i){e=e.replace(/,/g,".").trim(),i=i.replace(/,/g,".").trim();let n=e.split("."),r=i.split(".");try{if(!n.every(MC)||!r.every(MC))return-2;for(;n.length<r.length;)n.push("0");for(;r.length<n.length;)r.push("0");let e=n.map(Number),t=r.map(Number);for(var a=0;a<e.length;a++)if(e[a]!==t[a]){if(e[a]>t[a])return 1;if(e[a]<t[a])return-1}}catch(e){t.AzureLogger.log(`Error in browser check version support: ${e}`)}return 0}function DC(e){let t=yc()?.environments;return!!t.hasOwnProperty(e)}function OC(){let e,t,i=!1;const n=TC(),r=AC(),a=RC().name,s=RC().version,o=DC(r),l=function(e,t){let i=yc()?.environments;return!(!DC(e)||!i[e].hasOwnProperty(t))&&i[e][t].isSupportedOnSdkVersion}(r,a);return l&&kC(s,function(e,t){let i=yc()?.environments;return i.hasOwnProperty(e)&&i[e].hasOwnProperty(t)?i[e][t].minVersion:yC}(r,a))>=0&&(i=!0),t={platform:n.os.name,browser:n.browser.name,browserVersion:n.browser.version},e={environment:t,isSupportedPlatform:o,isSupportedBrowser:l,isSupportedBrowserVersion:i,isSupportedEnvironment:o&&l&&i},e}class NC{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,i){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild("MediaConstraintsManager"),this._telemetryLogManager=i}async setVideoConstraints(e,t,i,n){const r=this.getTelemetryPayload({video:e}),a=e=>{let r=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,...xg(e)}:void 0;bg({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:{deltaTimeInMs:+new Date-n},featureDetails:{name:"setConstraints",step:e?Yh.failure:Yh.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...r}},this._telemetryLogManager,this._logger)};try{if(bg({correlationId:i,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:"SetConstraints",featureType:"Call",initializationType:"None",timestampInfo:"",featureDetails:{name:"setConstraints",step:Yh.attempt,stage:t},additionalDetails:{constraints:r}},this._telemetryLogManager,this._logger),!yc().calling.constraints.enabled)throw this._logger.error("Setting call constraints is disabled"),new b({defaultError:f.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);const n={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},s=this._tsCall.setCallConstraints?.(n);if("mid-call"!==t)s?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`);const i=new b({defaultError:f.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e});a(i)}));else try{await s,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()}catch(e){throw new b({defaultError:f.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){const i=new b({defaultError:f.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw a(i),i}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){const t=yc(),i=t.calling.constraints.maxOutgoingResolution,n=t.calling.constraints.maxOutgoingFrameRate,r=t.calling.constraints.maxOutgoingVideoBitrate,a=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,s=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,o=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(i,"maxOutgoingResolution",a)},frameRate:{max:this._getConstraintValue(n,"maxOutgoingFrameRate",s)},bitrate:{max:this._getConstraintValue(r,"maxOutgoingBitrate",o)}}}}_getConstraintValue(e,t,i){return"number"==typeof i?i<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&i>e&&(this._logger.info(`${t} value ${i} is larger than ${e}, resetting to ${e}`),i=e),i):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([bf,function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type",Object)],NC.prototype,"_logger",void 0);var LC=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},xC=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class FC{constructor(e,t,i,n){this.logger=i.createChild("Lobby"),this._tsCall=e,this._eventEmitter=new wm(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=n,this._lobbySupportedConversationTypes=yc().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=yc().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(0!==e.added.length&&e.added.forEach((e=>{"InLobby"===e.state&&this.addLobbyParticipant(e),e.on("stateChanged",(()=>{"InLobby"===e.state?this.addLobbyParticipant(e):"Connected"===e.state&&this.removeLobbyParticipant(e)}))})),0!==e.removed.length){if(0===this._call.remoteParticipants.length)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on("remoteParticipantsUpdated",this._remoteParticipantUpdatedListener))}on(e,t){if("lobbyParticipantsUpdated"!==e)throw new b({defaultError:f.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("lobbyParticipantsUpdated"!==e)throw new b({defaultError:f.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const i=x(),n=+new Date;this._sendLobbyAdmitAndRejectUsage("Start admit participant",Qh.lobbyAdmit,i,Yh.attempt,void 0);try{oc(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(rc(e));const t=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant admitted successfully",Qh.lobbyAdmit,i,Yh.success,t-n)}catch(e){let t=Xh.Unexpected;this._hasExpectedError&&(t=Xh.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit participant from lobby",e,i,n,Qh.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn("Lobby is not enabled");const i=x(),n=+new Date;this._sendLobbyAdmitAndRejectUsage("Start reject participant",Qh.lobbyReject,i,Yh.attempt,void 0);try{oc(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(rc(e));const t=+new Date;this._sendLobbyAdmitAndRejectUsage("Lobby participant rejected successfully",Qh.lobbyReject,i,Yh.success,t-n)}catch(e){let t=Xh.Unexpected;this._hasExpectedError&&(t=Xh.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to reject participant from lobby",e,i,n,Qh.lobbyReject,t)}}async admitAll(e){const t=x(),i=+new Date;let n,r=0,a=0;if(!this._isLobbyEnabled)return this.logger.warn("Lobby is not enabled"),{successCount:r,failureCount:a};this._sendLobbyAdmitAndRejectUsage("Start admit all participants",Qh.lobbyAdmitAll,t,Yh.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:"all"},m.generateCauseId()).then((e=>{if(n=e,e.result){const t=JSON.parse(e.result);r=t.successCount,a=t.failureCount}}));const e=+new Date;if(0!==a)return this._sendLobbyAdmitAndRejectUsage(`${r} participants are admitted successfully, ${a} participants admit failed. TransactionEnd: ${n}`,Qh.lobbyAdmitAll,t,Yh.success,e-i),{successCount:r,failureCount:a};this._sendLobbyAdmitAndRejectUsage("All participants are admitted successfully",Qh.lobbyAdmitAll,t,Yh.success,e-i)}catch(e){let n=Xh.Unexpected;this._hasExpectedError&&(n=Xh.Expected,this._hasExpectedError=!1),this.handleLobbyAdmitAndRejectFailure("Failed to admit all participants from lobby",e,t,i,Qh.lobbyAdmitAll,n)}return{successCount:r,failureCount:a}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn("Lobby is not enabled"),[])}getInLobbyParticipants(e){e.forEach((e=>{if("InLobby"===e.state){const t=rc(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(0===this._participants.size)return;const e=Array.from(this._participants.values());this._participants.clear(),this.logger.info("All participants are removed from lobby"),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:e})}removeLobbyParticipant(e){const t=rc(e.identifier);this._participants.has(t)&&(this.logger.info(`${n.getIdentifierKind(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[],removed:[e]}))}addLobbyParticipant(e){const t=rc(e.identifier);this._participants.has(t)||(this.logger.info(`${n.getIdentifierKind(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit("lobbyParticipantsUpdated",{added:[e],removed:[]}))}validateLobbyOperation(e){const t=this._tsCall.conversationType?this._tsCall.conversationType:"oneToOneCall";if(this.logger.info("Current conversation type is: ",t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new b({defaultError:f.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>rc(t.identifier)===rc(e)));if(t&&"Connected"===t.state)throw this._hasExpectedError=!0,new b({defaultError:f.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[n.getIdentifierKind(e).kind]});if(t&&"InLobby"!==t.state||!t)throw this._hasExpectedError=!0,new b({defaultError:f.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[n.getIdentifierKind(e).kind]})}if(this._call.role!==Wl.Presenter&&this._call.role!==Wl.Organizer&&this._call.role!==Wl.Coorganizer)throw this._hasExpectedError=!0,new b({defaultError:f.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,i,n,r,a){const s=+new Date,o=function(e,t,i){const n=void 0===t?.code?500:t?._code,r=t?.subCode||t?._subCode||0;return new b({defaultError:{message:i+", reason: "+(t?.phrase||t?.message||"unknown error"),code:n,subCode:r,resultCategories:t?.resultCategories||[]}})}(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(o.message,r,i,Yh.failure,s-n,a,t),o}_sendLobbyAdmitAndRejectUsage(e,t,i,n,r,a,s){n===Yh.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:Jh.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:i,kindOfEvent:n,operation:t,isExpected:a??"",timestampInfo:r?{deltaTimeInMs:r}:"",additionalDetails:s?{failureReason:s.message,code:s.code,subCode:s.subCode,...xg(s)}:""})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send lobby admit and reject telemetry")}}}function UC(){const e=window.navigator.mediaDevices;if(e?.isRemote){const t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return"connected";if(!1===t)return"disconnected"}return""}function BC(){const e=window.navigator.mediaDevices,t={isMMREnabled:e?.isRemote??!1};return t.isMMREnabled&&(e?.mmrClientVersion&&(t.mmrClientVersion=e.mmrClientVersion),e?.mmrExtensionVersion&&(t.mmrExtensionVersion=e.mmrExtensionVersion),e?.mmrHostVersion&&(t.mmrHostVersion=e.mmrHostVersion),e?.activityId&&(t.mmrActivityId=e.activityId),e?.connectionId&&(t.mmrConnectionId=e.connectionId),t.mmrRdpState=UC()),t}LC([bf,xC("design:type",Object)],FC.prototype,"logger",void 0),LC([M(gp.LobbyAdmitParticipant),xC("design:type",Function),xC("design:paramtypes",[Object,Object]),xC("design:returntype",Promise)],FC.prototype,"admit",null),LC([M(gp.LobbyRejectParticipant),xC("design:type",Function),xC("design:paramtypes",[Object,Object]),xC("design:returntype",Promise)],FC.prototype,"reject",null),LC([M(gp.LobbyAdmitAll),xC("design:type",Function),xC("design:paramtypes",[Object]),xC("design:returntype",Promise)],FC.prototype,"admitAll",null);class VC{constructor(e){this._lastState="",this._callback=e=>{const t=e?.detail?.state??"";t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit("stateChange",t),this._lastState=t):this._logger.info("connection state is unknown")},this._logger=e.createChild("MmrRdpConnectionManager"),this._eventEmitter=new Kp.EventEmitter;const t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("listener registered"))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return UC()}dispose(){const e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener("rdpClientConnectionStateChanged",this._callback),this._logger.info("event listener unregistered")),this._eventEmitter.removeAllListeners()}}var HC=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class $C extends Yf{constructor(e,t,i,n,r,a,s){super(e,t,i,r,a,"RemoteVideoStream"),this._remoteParticipantIdentifier=s,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit("isAvailableChanged",this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};const o=()=>{if("Video"===this.mediaStreamType&&i.isHandlingLargeMeetingVideoRendering){for(const e of i.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&rc(e.identifier)===rc(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else this.setIsAvailable(this.tsStream.isAvailable)};this._streamChangedHandler=this.tsStream.changed((()=>{o()})),o()}on(e,t){if("isAvailableChanged"!==e&&"sizeChanged"!==e&&"isReceivingChanged"!==e)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("isAvailableChanged"!==e&&"sizeChanged"!==e&&"isReceivingChanged"!==e)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){const e=x(),t=+new Date,i={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:xp.getMediaStream,mediaType:this.getMediaType(),streamType:Lp.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:Yh.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(i);try{if(!this.tsStream.getRawStream)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});const i=this.tsStream.getRawStream(),n=new Promise((async(e,t)=>{const n=setTimeout((()=>{r.dispose(),t(new b({defaultError:f.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),yc().rendering.remoteVideo.getMediaStreamTimeout),r=i.changed((()=>{a()})),a=async()=>{try{const t=await i.getMediaStream();if(!t)return void this.logger.warn("MediaStream is not yet ready.");clearTimeout(n),r.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||"unknown"}`)}};a()})),r=await n,a=r.getVideoTracks()[0];if(!a)throw new b({defaultError:f.REMOTE_VIDEO_STREAM.GET_TRACK});const s=new Promise(((e,t)=>{const i=()=>{a.removeEventListener("unmute",i,!1),e()};a.addEventListener("unmute",i,!1),a.muted?setTimeout((()=>{a.removeEventListener("unmute",i,!1),t(new b({defaultError:f.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),yc().rendering.remoteVideo.getMediaStreamTimeout):i()}));await s;const o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},operation:xp.getMediaStream,mediaType:this.getMediaType(),streamType:Lp.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),r}catch(i){const n={correlationId:e,operation:xp.getMediaStream,mediaType:this.getMediaType(),streamType:Lp.Remote,additionalDetails:{failureReason:i?.message||"",code:i.code||_,...xg(i),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:Yh.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(n),new b({defaultError:f.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:i})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:"remote",rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((e=>e.viewId)).join(", "),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return"ScreenSharing"===this.mediaStreamType?Np.ScreenSharingRaw:Np.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:Jh.acs_calling_media_stream,tenant:hl,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||"",kindOfEvent:e.kindOfEvent||"",mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||"",callId:e.callId||""}})}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([M(bp.GetMediaStream),HC("design:type",Function),HC("design:paramtypes",[]),HC("design:returntype",Promise)],$C.prototype,"getMediaStream",null);var GC=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},jC=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let zC=1;class WC{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,i,n,r,a){this._target=e,this._viewId=t,this._videoStream=i,this._onDisposedCallback=r,this._eventEmitter=new Kp.EventEmitter,this._isRendering=!1,this._scalingMode="Stretch",this._isMirrored=!1,this._size={height:0,width:0},this._disposed=!1,this._handleTsRendererChanged=e=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this._renderingDeferred&&this._renderingDeferred.isPending()&&this._renderingDeferred.resolve(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){const e=this._tsRenderer.streamSize.height,t=this._tsRenderer.streamSize.width;e===this._size.height&&t===this._size.width||(this._size.height=e,this._size.width=t,this._videoStream.updateSize())}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{const e={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(function(e,t){const i=Object.keys(e);for(let n of i)if(e[n]!==t[n])return!1;return!0}(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;const t=this._videoStream.getStreamMetadata(),{callId:i,localParticipantId:n,isDisposed:r,viewIdsRegistered:a,height:s,width:o,...l}=t,c={...e,...l,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:Kh.remote_view,callId:i,localParticipantId:n,data:c})}catch(e){}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&("RemoteVideoStream"===this._videoStream.kind&&this._videoStream?.off("isAvailableChanged",this._availableCallback),this._availableCallback=void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&(this._tsRendererChanged.dispose(),this._tsRendererChanged=void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug("disposing underlying remote renderer");try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new b({defaultError:f.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=n.createChild("RemoteStreamRenderer"+zC++),this.logger.log("created"),void 0!==a?.scalingMode&&(this._scalingMode=a.scalingMode),void 0!==a?.isMirrored&&(this._isMirrored=a.isMirrored),this._remoteStreamTelemetryEventSender=new Mf(this._videoStream.telemetryLogManager)}async start(){const e=x(),t=+new Date,i=this.logger.createFnLogger(Ip.Start),n={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:xp.render,kindOfEvent:Yh.attempt,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n),this._disposed)throw this.logger.warn("already disposed"),new b({defaultError:f.VIEW.START_ALREADY_DISPOSED});try{i.info(`scalingMode=${Tc(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=kh(),this._renderingDeferred.promise.catch(Oc),"RemoteVideoStream"===this._videoStream.kind&&(this._availableCallback=()=>{this._videoStream.isAvailable||(i.warn("stream isAvailable changed to false, attempting to reject operation"),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new b({defaultError:f.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on("isAvailableChanged",this._availableCallback)),this._videoStream.tsStream.start(this._target,{scalingMode:Tc(this._scalingMode),transparent:!1}).then((e=>{if(this._isMirrored&&(this._target.style.transform="rotateY(180deg)",this._target.style.webkitTransform="rotateY(180deg)"),this._tsRenderer=e,this.logger.info("subscribed to video, waiting for the first frame"),this._disposed)throw this.logger.warn("already disposed, dispose underlying renderer"),this._attemptToDisposeTsRenderer(),new b({defaultError:f.VIEW.START_ALREADY_DISPOSED});this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),-1!==yc().rendering.remoteVideo.createViewTimeout&&setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new b({defaultError:f.VIEW.TIMEOUT}))}catch(e){}}),yc().rendering.remoteVideo.createViewTimeout),this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(i))),this._tsRenderer.isRendering&&this._renderingDeferred?.isPending()&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this._size.width=e.streamSize.width,this._size.height=e.streamSize.height,this._videoStream.updateSize(),this._renderingDeferred.resolve())})).catch((e=>{if(this.logger.info("Failed to subscribe to video"),this._renderingDeferred?.isPending()){const t=new b({defaultError:f.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),yc().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();const n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:xp.render,kindOfEvent:Yh.success,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Remote};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n),this}catch(i){this.logger.warn(`Failed to render, message=${i}`);try{this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}const n=new b({defaultError:f.VIEW.START,originalError:i});if(n.message!==f.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&n.message!==f.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const i={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:xp.render,additionalDetails:{failureReason:n.message,code:C,...xg(n)},kindOfEvent:Yh.failure,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Remote};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(i)}throw n}}async setScalingMode(e){if(!this._tsRenderer)throw new b({defaultError:f.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(Tc(e)),this._scalingMode=e}dispose(e=Bp.Public_App){if(this._disposed)throw new b({defaultError:f.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case Bp.Internal_LargeMeetingVideoRendering:t=f.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case Bp.Internal_RemoteVideoStreamDisposed:t=f.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=f.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new b({defaultError:t}))}this._target&&this._target.remove();try{e!==Bp.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.message} error`)}this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0}_checkIfVideoWasAttachedToDom(){if(yc().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=yc().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries;const t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&setTimeout((()=>t),yc().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime))};t()}else setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),yc().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}}GC([bf,jC("design:type",Object)],WC.prototype,"logger",void 0),GC([M(Ip.Start),jC("design:type",Function),jC("design:paramtypes",[]),jC("design:returntype",Promise)],WC.prototype,"start",null),GC([P(Ip.Dispose),jC("design:type",Function),jC("design:paramtypes",[String]),jC("design:returntype",void 0)],WC.prototype,"dispose",null);var qC=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},KC=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class JC{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}constructor(e,t,i,n,r){this._target=e,this._videoStream=t,this._onDisposed=n,this._eventEmitter=new Kp.EventEmitter,this._isRendering=!1,this._scalingMode="Stretch",this._isMirrored=!0,this._disposed=!1,this.logger=i.createChild("LocalStreamRenderer"),this.logger.log("created"),void 0!==r?.scalingMode&&(this._scalingMode=r.scalingMode),void 0!==r?.isMirrored?this._isMirrored=r.isMirrored:"ScreenSharing"===this._videoStream.mediaStreamType&&(this._isMirrored=!1),this._localStreamTelemetryEventSender=new Mf(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){const e=x(),t=this.logger.createFnLogger(Ip.Start),i=+new Date,n={timestampInfo:{attemptTimestamp:i},correlationId:e,operation:xp.render,kindOfEvent:Yh.attempt,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(n);try{if(t.info("attempting to select new device as a source"),this._videoStream.source instanceof Tf&&"Video"===this._videoStream.mediaStreamType){const e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info("device selected"),t.info("creating preview"),this._tsRenderer=await e.createPreview(this._target,{kind:"camera"},{scalingMode:Tc(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if("RawMedia"!==this._videoStream.mediaStreamType&&"ScreenSharing"!==this._videoStream.mediaStreamType)throw new b({defaultError:f.VIEW.UNKNOWN_STREAM_TYPE});{const e=document.createElement("video");e.srcObject=await this._videoStream.getMediaStream(),e.play(),this._target.appendChild(e)}}this._isMirrored&&(this._target.style.transform="rotateY(180deg)",this._target.style.webkitTransform="rotateY(180deg)"),this._videoStream.registerRenderer(this);const n={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:e,operation:xp.render,kindOfEvent:Yh.success,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(n),this}catch(n){this.dispose();const t=Ng(0,n),r={timestampInfo:{deltaTimeInMs:+new Date-i},correlationId:e,operation:xp.render,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...xg(t)},kindOfEvent:Yh.failure,mediaType:this._videoStream.mediaStreamType,streamType:Lp.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),t}}setScalingMode(e){if(!this._tsRenderer)throw new b({defaultError:f.VIEW.SCALING_MODE});this._tsRenderer.setScalingMode(Tc(e)),this._scalingMode=e}setSourceObject(e){this.disposeScreenSharingMediaStream();const t=this._target.querySelector("video");t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log("disposing underlying local renderer"),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new b({defaultError:f.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){const e=this._target.querySelector("video"),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info("disposed of ScreenSharing MediaStream"))}}}qC([bf,KC("design:type",Object)],JC.prototype,"logger",void 0),qC([M(wp.Start),KC("design:type",Function),KC("design:paramtypes",[]),KC("design:returntype",Promise)],JC.prototype,"start",null),qC([P(wp.SetScalingMode),KC("design:type",Function),KC("design:paramtypes",[String]),KC("design:returntype",void 0)],JC.prototype,"setScalingMode",null),qC([P(wp.SetSourceObject),KC("design:type",Function),KC("design:paramtypes",[MediaStream]),KC("design:returntype",void 0)],JC.prototype,"setSourceObject",null),qC([P(wp.Dispose),KC("design:type",Function),KC("design:paramtypes",[]),KC("design:returntype",void 0)],JC.prototype,"dispose",null);var YC=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},QC=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let ZC=1;class XC{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,i,n){if(this._videoStream=e,this._viewId=i,this._options=n,this._disposed=!1,this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let i=e.call.activeRemoteVideoStreamViews?.get(e.id);i?.delete(t),0==i?.size&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild("VideoStreamRendererView"+ZC++),this.target=document.createElement("div"),this.target.style.width="100%",this.target.style.height="100%",this._videoStream instanceof Yf)this._streamRenderer=new WC(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),this._options);else{if(!(this._videoStream instanceof Nf))throw new b({defaultError:f.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new JC(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info("created")}async render(){const e=this.logger.createFnLogger(this._videoStream instanceof Yf?yp.RenderRemoteStream:yp.RenderLocalStream);if(this._disposed)throw e.log("failed, stream disposed!"),new b({defaultError:f.VIEW.RENDER_FAIL_STREAM_DISPOSED});try{await this._streamRenderer.start()}catch(t){e.error("failed");try{this.dispose()}catch(e){this.logger.warn(`Failed to dispose, message=${e.message}`)}throw t}}async updateScalingMode(e){if(this._disposed)throw new b({defaultError:f.VIEW.SCALING_MODE_DISPOSED});if("Crop"!==e&&"Fit"!==e&&"Stretch"!==e)throw new b({defaultError:f.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new b({defaultError:f.VIEW.SCALING_MODE,originalError:e})}}dispose(e=Bp.Public_App){if(this._disposed)throw new b({defaultError:f.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;const t=+new Date,i=x();try{e===Bp.Public_App&&this.sendDisposeViewEvent({eventName:Jh.acs_calling_dispose_view_attempt,correlationId:i,timestampInfo:{attemptTimestamp:t}}),this._videoStream instanceof $C&&this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),this.logger.debug("attempt to dispose stream renderer"),this._streamRenderer.dispose(e),this.target?.remove();const n=+new Date;e===Bp.Public_App&&this.sendDisposeViewEvent({eventName:Jh.acs_calling_dispose_view_success,correlationId:i,timestampInfo:{deltaTimeInMs:n-t}})}catch(n){const r=new b({defaultError:f.VIEW.DISPOSE_FAIL,originalError:n});if(e===Bp.Public_App){const e=+new Date;this.sendDisposeViewEvent({eventName:Jh.acs_calling_dispose_view_failure,correlationId:i,timestampInfo:{deltaTimeInMS:e-t}},r)}throw r}}sendDisposeViewEvent(e,t){try{let i,n;t&&(i="string"==typeof t?.message?t?.message:"",n={...xg(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:i,additionalDetails:n}})}catch(e){this.logger.debug("Unable to send telemtery")}}}YC([bf,QC("design:type",Object)],XC.prototype,"logger",void 0),YC([M(yp.Render),QC("design:type",Function),QC("design:paramtypes",[]),QC("design:returntype",Promise)],XC.prototype,"render",null),YC([M(yp.UpdateScalingMode),QC("design:type",Function),QC("design:paramtypes",[String]),QC("design:returntype",Promise)],XC.prototype,"updateScalingMode",null),YC([P(yp.Dispose),QC("design:type",Function),QC("design:paramtypes",[String]),QC("design:returntype",void 0)],XC.prototype,"dispose",null);class e_{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,i,n,r){this._statsCollector=e,this._streamId=t,this._logger=i,this._call=n,this._attemptTimestamp=r,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on("sampleReported",(e=>{!function(e,t,i,n){const r=yc()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength,a=yc()?.rendering.remoteVideo.createViewSendMediaStatsInitialMaxLength,s=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","healedRatio","lossRate"],o=["bitrate","packetsPerSecond","packetsLostPerSecond","jitterInMs","rttInMs","pairRttInMs","frameRateDecoded","frameRateReceived","frameWidthReceived","frameHeightReceived","longestFreezeDurationInMs","totalFreezeDurationInMs","framesReceived","framesDropped","framesDecoded","keyFramesDecoded"],l=o;if(i.audio.receive.length>0){const n=i.audio.receive[0];e.audio=e.audio??{},t.audio=t.audio??{},s.forEach((i=>{const s=i;if(void 0!==n[s]&&e.audio){const t=n[s];if(void 0===e.audio[s])e.audio[s]=[t];else{const i=e.audio[s]?.length;i>=r&&e.audio[s]?.shift(),e.audio[s]?.push(t)}}if(void 0!==n[s]&&t.audio){const e=n[s];if(void 0===t.audio[s])t.audio[s]=[e];else{const i=t.audio[s]?.length;i<a&&t.audio[s]?.push(e)}}}))}if(i.video.receive.length>0){const s=i.video.receive.find((e=>e.streamId===n));void 0!==s&&(e.video=e.video??{},t.video=t.video??{},o.forEach((i=>{const n=i;if(void 0!==s[n]&&e.video){const t=s[n];if(void 0===e.video[n])e.video[n]=[t];else{const i=e.video[n]?.length;i>=r&&e.video[n]?.shift(),e.video[n]?.push(t)}}if(void 0!==s[n]&&t.video){const e=s[n];if(void 0===t.video[n])t.video[n]=[e];else{const i=t.video[n]?.length;i<a&&t.video[n]?.push(e)}}})))}if(i.screenShare.receive.length>0){const s=i.screenShare.receive.find((e=>e.streamId===n));void 0!==s&&(e.screenShare=e.screenShare??{},t.screenShare=t.screenShare??{},l.forEach((i=>{const n=i;if(void 0!==s[n]&&e.screenShare){const t=s[n];if(void 0===e.screenShare[n])e.screenShare[n]=[t];else{const i=e.screenShare[n]?.length;i>=r&&e.screenShare[n]?.shift(),e.screenShare[n]?.push(t)}}if(void 0!==s[n]&&t.screenShare){const e=s[n];if(void 0===t.screenShare[n])t.screenShare[n]=[e];else{const i=t.screenShare[n]?.length;i<a&&t.screenShare[n]?.push(e)}}})))}}(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;void 0!==this.createViewStats.video?.framesDropped&&void 0!==this.initialCreateViewStats.video?.framesDropped&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let i=NaN,n=NaN;void 0!==this.createViewStats.video?.framesReceived&&void 0!==this.initialCreateViewStats.video?.framesReceived&&(e=this.createViewStats.video.framesReceived.length,i=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0],e=this.initialCreateViewStats.video.framesReceived.length,n=this.initialCreateViewStats.video.framesReceived[0]);let r=NaN;void 0!==this.createViewStats.video?.framesDecoded&&void 0!==this.initialCreateViewStats.video?.framesDecoded&&(e=this.createViewStats.video.framesDecoded.length,r=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let a=NaN;void 0!==this.createViewStats.video?.keyFramesDecoded&&void 0!==this.initialCreateViewStats.video?.keyFramesDecoded&&(e=this.createViewStats.video.keyFramesDecoded.length,a=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let s=0;!isNaN(t)&&!isNaN(i)&&i>0&&(s=Number((t/i*100).toFixed(7)));let o=!1;i>0&&0===r&&(o=!0);let l=!1;isNaN(r)||isNaN(a)||r!==a||(l=!0);const c=[],d=this._call.networkQualityUfdEventDetails,u=yc().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;d.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=u&&c.push(e)}));let h=!1;isNaN(i)||isNaN(n)||i!==n||(h=!0),this._createViewFailureStats.video={framesDroppedPercentage:s,framesReceivedButNothingDecoded:o,onlyKeyFramesDecoded:l,networkQualityEventsDuringAttempt:c,zeroFramesReceived:h}}catch(e){this._logger.debug("Error calculating create view failure stats!")}return this._createViewFailureStats}}class t_{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};const i=yc()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on("sampleReported",(e=>{(function(e,t,i,n){const r=t[i.toString()];void 0!==r&&["audioBitrate","videoBitrate","downloadBitrate","bufferLengthInMs","videoHeight","videoWidth","currentPlayPosition"].forEach((t=>{const i=t,a=t;if(void 0!==r[i]){const t=r[i];if(void 0===e[a])e[a]=[t];else{const i=e[a]?.length;i>=n&&e[a]?.shift(),e[a]?.push(t)}}}))})(this._liveStreamStats,e,this._streamId,i),g.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}}var i_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},n_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class r_{get _createViewStats(){return"RemoteVideoStream"!==this._videoStream.kind&&"ComposedVideoStream"!==this._videoStream.kind||!this._createViewTelemetryHelper?"LiveVideoStream"===this._videoStream.kind&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||"Failed to dispose, unknown error")}},this._addActiveRemoteVideoStreamView=(e,t,i)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n&&n.set(t,i)}else{let n=new Map;n.set(t,i),e.call.activeRemoteVideoStreamViews?.set(e.id,n)}},!(e instanceof Nf||e instanceof Yf||e instanceof $C))throw new b({defaultError:f.VIEW.RENDERER_WRONG_STREAM_TYPE});const i=t.createClientLogger("ACS");this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new Pf(i,e instanceof Nf?[()=>`VideoStreamRenderer:LocalVideoStream:${p.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info("created")}async createView(e){if(this.disposed)throw new b({defaultError:f.VIEW.RENDERER_DISPOSED});const t=+new Date,i=x(),n=x();let r,a;try{if(this.sendCreateViewEvent({eventName:Jh.acs_calling_create_view_attempt,viewId:i,correlationId:n,timestampInfo:{attemptTimestamp:t}}),"RemoteVideoStream"===this._videoStream.kind&&!this._videoStream.isAvailable){const e=new b({defaultError:f.VIEW.ISAVAILABLE_FALSE}),r=+new Date;throw this.sendCreateViewEvent({eventName:Jh.acs_calling_create_view_failure,viewId:i,correlationId:n,timestampInfo:{deltaTimeInMs:r-t}},e),e}if("RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&yc()?.calling.applyViewLimit&&Cc()?.numVideoChannelsGvc){const e=Cc().numVideoChannelsGvc,r=this._videoStream;if(!r.call.activeRemoteVideoStreamViews?.has(r.id)&&r.call.activeRemoteVideoStreamViews?.size>=e){const r=new b({defaultError:f.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]}),a=+new Date;throw this.sendCreateViewEvent({eventName:Jh.acs_calling_create_view_failure,viewId:i,correlationId:n,timestampInfo:{deltaTimeInMs:a-t}},r),r}}if(yc()?.rendering.remoteVideo.createViewSendMediaStats)if("RemoteVideoStream"===this._videoStream.kind||"ComposedVideoStream"===this._videoStream.kind){const e=this._videoStream,i=e.call;a=e.call.feature(hC.MediaStats).createCollector();const n=e.id;this._createViewTelemetryHelper=new e_(a,n,this.logger,i,t)}else if("LiveVideoStream"===this._videoStream.kind){const e=this._videoStream;a=e.call.feature(hC.LiveStream).createStatsCollector();const t=e.id;this._createViewLiveStreamTelemetryHelper=new t_(a,t)}r=new XC(this._videoStream,this.logger,i,e),this.views.set(i,r),await r.render(),"RemoteVideoStream"===this._videoStream.kind&&"ScreenSharing"!==this._videoStream.mediaStreamType&&this._addActiveRemoteVideoStreamView(this._videoStream,i,r);const s=+new Date;return this.sendCreateViewEvent({eventName:Jh.acs_calling_create_view_success,viewId:i,correlationId:n,timestampInfo:{deltaTimeInMs:s-t}}),a?.dispose(),r}catch(e){const s=new b({defaultError:f.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(i),this._attemptToDisposeView(r),a?.dispose(),s.message!==f.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&s.message!==f.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){const e=+new Date;this.sendCreateViewEvent({eventName:Jh.acs_calling_create_view_failure,viewId:i,correlationId:n,timestampInfo:{deltaTimeInMs:e-t}},s)}throw s}}async sendCreateViewEvent(e,t){try{let i={},n={},r={};if(yc()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===Jh.acs_calling_create_view_failure||e.eventName===Jh.acs_calling_create_view_success)){if("RemoteVideoStream"===this._videoStream.kind){const e=this._videoStream.call,t=e.tsCall.getMediaSessionStats();i={videoSubscriptionEvents:t?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:t?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:t?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:t?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:t?.metrics?.IceConnectedStateTime,relayCandidate:t?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:t?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:t?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:e.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:e.activeRemoteVideoStreamViews?.size||0}}e.eventName===Jh.acs_calling_create_view_failure&&(r=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},n=this._createViewStats)}i.visibilityState=document.visibilityState;let a="",s={};t&&(a="string"==typeof t?.message?t?.message:"",s={...xg(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:a,additionalProperties:i,additionalDetails:s,stats:n,createViewFailureDebugStats:r,videoStreamKind:this._videoStream.kind}})}catch(e){this.logger.debug("Unable to send telemtery")}}dispose(){if(this.disposed)throw new b({defaultError:f.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}}i_([bf,n_("design:type",Object)],r_.prototype,"logger",void 0),i_([M(Cp.CreateView),n_("design:type",Function),n_("design:paramtypes",[Object]),n_("design:returntype",Promise)],r_.prototype,"createView",null),i_([P(Cp.Dispose),n_("design:type",Function),n_("design:paramtypes",[]),n_("design:returntype",void 0)],r_.prototype,"dispose",null);var a_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},s_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class o_{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get role(){return this._role}constructor(e,t,i,n,r){this._mappedStreams=new Map,this._state="Idle",this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName="",this._role="Unknown",this.acsToTsStreamType=e=>"Video"===e?0:"ScreenSharing"===e?1:void 0,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=r,this._eventEmitter=new wm(this.logger),this._callAgent=n,this._call=i,this.logger.log("created"),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if("stateChanged"!==e&&"isMutedChanged"!==e&&"isSpeakingChanged"!==e&&"displayNameChanged"!==e&&"roleChanged"!==e&&"videoStreamsUpdated"!==e)throw new b({defaultError:f.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("stateChanged"!==e&&"isMutedChanged"!==e&&"isSpeakingChanged"!==e&&"displayNameChanged"!==e&&"roleChanged"!==e&&"videoStreamsUpdated"!==e)throw new b({defaultError:f.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){if(!yc().calling.enableMuteOthers)throw new b({defaultError:f.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});const e=this.logger.createFnLogger(mp.Mute),t=+new Date,i=x();this.sendAudioEvent({eventName:Jh.acs_calling_mute_attempt,eventType:Zh.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{e.info("remote mute specific");var n=[];void 0!==this._tsParticipant&&(n=n.concat(this._tsParticipant)),await this._call.tsCall.muteParticipants(1,n),e.info("remote mute specific success");const r=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_mute_success,eventType:Zh.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:r-t},correlationId:i,step:"mid-call"})}catch(n){const r=new b({defaultError:f.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:n});e.error(r.message);const a=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_mute_failure,eventType:Zh.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call"},r),r}}_dispose(){this.logger.log("dispose"),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.dispose())),this._eventEmitter.emit("stateChanged",this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return"RemoteParticipant"}setCallEndReason(e){this._callEndReason=e}observeParticipant(e){this._tsParticipant||(this._tsParticipant=e,this._displayName=e.displayName,this._isMuted=e.isServerMuted,this._participantChangedHandler=this._tsParticipant.changed((()=>{if(this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit("isMutedChanged")),this._tsParticipant&&this._tsParticipant.displayName!==this._displayName&&(this._displayName=e.displayName,this._eventEmitter.emit("displayNameChanged")),this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){const e=0!==this._tsParticipant.voiceLevel;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit("isSpeakingChanged"))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,"Disconnected"==this._state?this._dispose():this._eventEmitter.emit("stateChanged",this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return"function"==typeof e?this._updateRenderingState(e,"Video",t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,i){if("function"==typeof e){let n;const r="Video"===t?0:1;this._tsParticipant&&(n=i?.stream?i.stream:new $C(this._tsParticipant.streams[r][0],this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier),n.on("isReceivingChanged",(()=>{this._renderers[t].renderingState.isFrozen=!n.isReceiving,e(this._renderers[t].renderingState)})),n.on("isAvailableChanged",(async()=>{this._renderers[t].renderingState.isStreaming!==n?.isAvailable&&(this._renderers[t].renderingState.isStreaming=n.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new r_(n),this._renderers[t].view||(this._renderers[t].view=await(this._renderers[t].renderer?.createView(i?.viewOptions))),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return"function"==typeof e?this._updateRenderingState(e,"ScreenSharing",t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,i){if(this._tsParticipant){const n=0===t?"Video":"ScreenSharing",r=i?.stream?i.stream:new $C(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier);return r.isAvailable&&(this._renderers[n].view=await this._appendVideo(e,t,r,i?.viewOptions)),r.on("isAvailableChanged",(async()=>{r.isAvailable?this._renderers[n].view=await this._appendVideo(e,t,r,i?.viewOptions):this._renderers[n]?.view&&this._renderers[n].view?.target&&this._renderers[n].view?.target.parentNode?.removeChild(this._renderers[n].view?.target)})),Promise.resolve({stream:r,view:this._renderers[n]?.view})}return Promise.reject()}async _appendVideo(e,t,i,n){try{const r=0===t?"Video":"ScreenSharing";if(0===t&&(this._renderers[r]?.renderer||(this._renderers[r].renderer=this._renderers[r]?.renderer?this._renderers[r].renderer:new r_(i),this._renderers[r].view=await(this._renderers[r].renderer?.createView(n))),this._renderers[r].view))return e.appendChild(this._renderers[r].view?.target||document.createElement("emptyNode")),Promise.resolve(this._renderers[r].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){const t=0===e?"Video":"ScreenSharing";this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=Hc(yc(),e);"Unknown"===t?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit("roleChanged"))}_mapTsParticipantState(e){let t;const i={0:"Idle",1:"Connecting",2:"Ringing",3:"Connected",4:"Disconnected",5:"Hold",7:"InLobby",6:"EarlyMedia"};i[e]?(t=i[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){const e=[],t=[],i=i=>{if(this._tsParticipant)if(this._tsParticipant.streams&&pc(this._tsParticipant.streams[i])){let n=[];this._tsParticipant&&(n=this._tsParticipant.streams[i]),n.forEach((t=>{if(!this._mappedStreams.get(t.id)){const i=new $C(t,this.logger,this._call,this._callAgent,this._tsParticipant.id,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${i.mediaStreamType} id=${t.id}`),e.push(i)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===i&&(n.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===i&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach((e=>{this._mappedStreams.set(e.id,e)})),t.forEach((e=>{const t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())})),this._eventEmitter.emit("videoStreamsUpdated",{added:e,removed:t}))}sendAudioEvent(e,t){try{let i,n;t&&(i=t.message,n=xg(t));const r={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:i||"",additionalDetails:{...n}};void 0!==e.eventType&&(r.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:r})}catch(e){this.logger.debug("Unable to send mute others audio telemetry")}}}a_([bf,s_("design:type",Object)],o_.prototype,"logger",void 0),a_([M(mp.Mute),s_("design:type",Function),s_("design:paramtypes",[]),s_("design:returntype",Promise)],o_.prototype,"mute",null);class l_{constructor(e){this._deviceManager=e,this._eventEmitter=new Kp.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;const t=e=>()=>{const t=this._selectedDevices.get(e),i=(()=>"Speaker"===e?this._deviceManager.selectedSpeaker:"Microphone"===e?this._deviceManager.selectedMicrophone:void 0)(),n=void 0===i?void 0:{id:this._deviceInfoMapper.getDeviceId(i.id),name:this._deviceInfoMapper.scrubDeviceLabel(i.name)};this._selectedDevices.set(e,n),this._eventEmitter.emit("selectedDeviceChanged",{selectedDeviceType:e,oldDevice:t,newDevice:n})},i=t("Speaker");this._selectedDeviceListeners.set("Speaker",i),this._deviceManager.on("selectedSpeakerChanged",i),i();const n=t("Microphone");this._selectedDeviceListeners.set("Microphone",n),this._deviceManager.on("selectedMicrophoneChanged",n),n()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){const e=this._selectedDeviceListeners.get("Speaker");e&&this._deviceManager.off("selectedSpeakerChanged",e);const t=this._selectedDeviceListeners.get("Microphone");t&&this._deviceManager.off("selectedMicrophoneChanged",t),this._eventEmitter.removeAllListeners()}}function c_(t,i,n,r){const a=r===zl.RoomCall||t.kind===e.CallKind.Call&&"Incoming"==t.direction&&!t.tsCall.groupId&&!!t.tsCall.meetingData?.meetingCode&&!t.tsCall.threadId,s=!a&&r===zl.TeamsMeetingLink||r===zl.TeamsMeetingId||r===zl.TeamsCoordinates||"Incoming"==t.direction&&!t.tsCall.groupId&&!!t.tsCall.meetingData&&!!t.tsCall.threadId;return{timestampInfo:{attemptTimestamp:+new Date},correlationId:n,localParticipantId:t.tsCall.participantId||"",isACSModeledInteropCall:t.isACSModeledInteropCall,callId:t.tsCall.callId||"",callType:t.tsCall.callType||"",callDirection:t.direction,state:"Ringing"===t.state?"Ringing":Mg[t.tsCall.state],groupJoin:!!t.tsCall.groupId,roomJoin:a,meetingJoin:s,callEndDiagnosticsInfo:t.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:i?.runningEnvironmentInfo?.isSupportedEnvironment,diagnosticInfo:{...t.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:rp.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:rp.telemetryPayloadBytesCompressed}}}function d_(e,t,i){try{"state-changed"===i.step&&"Connecting"===i.newState&&(rp.telemetryPayloadBytesOriginal=0,rp.telemetryPayloadBytesCompressed=0),e.sendEvent({name:Jh.acs_calling_call_progress,tenant:hl,properties:i})}catch(e){t.error(`Failed to send event: ${Jh.acs_calling_call_progress} step: ${i.step}`)}}var u_,h_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},p_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class g_{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isACSModeledInteropCall(){return this._isACSModeledInteropCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{let e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(0===this._remoteAudioStreams.length){if(!await e.getMediaStream())throw new b({defaultError:f.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new fC(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[]});else{const e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[e]})}}catch(e){throw new b({defaultError:f.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(Oc)})),t().catch((()=>{this.logger.info("Failed to update remote audio stream collection, retrying on changed")}))}catch(e){this.logger.info("Failed to get raw audio stream from the stack")}}get remoteAudioStreams(){if(!yc().calling.allowAccessRawMediaStream)throw new b({defaultError:f.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}constructor(e,t,i,n,r,a){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=x(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=x(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=Dl,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=zl.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._isACSModeledInteropCall=!1,this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state="None",this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this._handleCallingApplicationIdentifier=e=>{this._isClosedCaptionsBot(e)&&this.logger.info("Handle participant: Ignore closed captions application")},this._handleMuteChanges=()=>{const e=new $p(this.tsCall,{config:this._config}),t=this.tsCall.conversationType||e.context===Mp.RoomJoin?!!(this.tsCall.isMuted||10!==this.tsCall.state&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);let e=[];this.tsCall.isMuted&&e.push("isMicrophoneMuted"),this.tsCall.isServerMuted&&(e.push("isServerMuted"),this._eventEmitter.emit("mutedByOthers")),this._isDeviceNotFunctioningMuted&&e.push("isDeviceNotFunctioningMuted");let i="";e.length>=1&&(i=e.join(", ")),t&&(this._isMuted_correlationIdCache=x()),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:"isMuted-changed",oldIsMuted:this._isMuted,newIsMuted:t,reason:i}),this._isMuted=t,this._eventEmitter.emit("isMutedChanged")}},this._handleIncomingAudioMuteChanges=()=>{const e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=x()),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:"isIncomingAudioMuted-changed",oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:""}),this._isIncomingAudioMuted=e,this._eventEmitter.emit("isIncomingAudioMutedChanged"))},this._isClosedCaptionsBot=e=>"28:b1902c3e-b9f7-4650-9b23-5772bd429747"===e.id,this.getTotalNotBotParticipantCount=()=>{let e=1;return this.tsCall.participantCounts&&this.tsCall.participantCounts.totalParticipants>0&&(e=this.tsCall.participantCounts.totalParticipants),this.tsCall.participants&&(e-=this.tsCall.participants.filter((e=>this.isHiddenBot(e))).length),e},this._id=e.callId,this.tsCall=i,this._direction=e.isIncoming?"Incoming":"Outgoing",this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=n,this.stats=new gC(this.logger,this._telemetryLogManager),this._eventEmitter=new wm(this.logger),this.activeRemoteVideoStreamViews=new Map,this._mediaMetricsDeviceEvents={},this._kind=r,this._optimalVideoCount=1,this._ufdsCorrelationIdCache={1:{0:void 0,1:void 0,2:void 0,3:void 0},2:{0:void 0,1:void 0,2:void 0,3:void 0},3:{0:void 0,1:void 0,2:void 0,3:void 0},4:{0:void 0,1:void 0,2:void 0,3:void 0},5:{0:void 0,1:void 0,2:void 0,3:void 0},6:{0:void 0,1:void 0,2:void 0,3:void 0},7:{0:void 0,1:void 0,2:void 0,3:void 0},8:{0:void 0,1:void 0,2:void 0,3:void 0},9:{0:void 0,1:void 0,2:void 0,3:void 0},10:{0:void 0,1:void 0,2:void 0,3:void 0},11:{0:void 0,1:void 0,2:void 0,3:void 0},12:{0:void 0,1:void 0,2:void 0,3:void 0},13:{0:void 0,1:void 0,2:void 0,3:void 0},14:{0:void 0,1:void 0,2:void 0,3:void 0},15:{0:void 0,1:void 0,2:void 0,3:void 0},16:{0:void 0,1:void 0,2:void 0,3:void 0},17:{0:void 0,1:void 0,2:void 0,3:void 0},18:{0:void 0,1:void 0,2:void 0,3:void 0},19:{0:void 0,1:void 0,2:void 0,3:void 0},20:{0:void 0,1:void 0,2:void 0,3:void 0},21:{0:void 0,1:void 0,2:void 0,3:void 0},22:{0:void 0,1:void 0,2:void 0,3:void 0},23:{0:void 0,1:void 0,2:void 0,3:void 0},24:{0:void 0,1:void 0,2:void 0,3:void 0},25:{0:void 0,1:void 0,2:void 0,3:void 0},26:{0:void 0,1:void 0,2:void 0,3:void 0},27:{0:void 0,1:void 0,2:void 0,3:void 0},28:{0:void 0,1:void 0,2:void 0,3:void 0},29:{0:void 0,1:void 0,2:void 0,3:void 0},30:{0:void 0,1:void 0,2:void 0,3:void 0},31:{0:void 0,1:void 0,2:void 0,3:void 0},32:{0:void 0,1:void 0,2:void 0,3:void 0},33:{0:void 0,1:void 0,2:void 0,3:void 0},34:{0:void 0,1:void 0,2:void 0,3:void 0},35:{0:void 0,1:void 0,2:void 0,3:void 0},36:{0:void 0,1:void 0,2:void 0,3:void 0},37:{0:void 0,1:void 0,2:void 0,3:void 0},38:{0:void 0,1:void 0,2:void 0,3:void 0},39:{0:void 0,1:void 0,2:void 0,3:void 0},40:{0:void 0,1:void 0,2:void 0,3:void 0},41:{0:void 0,1:void 0,2:void 0,3:void 0},42:{0:void 0,1:void 0,2:void 0,3:void 0},43:{0:void 0,1:void 0,2:void 0,3:void 0},44:{0:void 0,1:void 0,2:void 0,3:void 0},45:{0:void 0,1:void 0,2:void 0,3:void 0},46:{0:void 0,1:void 0,2:void 0,3:void 0},47:{0:void 0,1:void 0,2:void 0,3:void 0},48:{0:void 0,1:void 0,2:void 0,3:void 0},49:{0:void 0,1:void 0,2:void 0,3:void 0},50:{0:void 0,1:void 0,2:void 0,3:void 0},51:{0:void 0,1:void 0,2:void 0,3:void 0},52:{0:void 0,1:void 0,2:void 0,3:void 0},53:{0:void 0,1:void 0,2:void 0,3:void 0},54:{0:void 0,1:void 0,2:void 0,3:void 0},55:{0:void 0,1:void 0,2:void 0,3:void 0},56:{0:void 0,1:void 0,2:void 0,3:void 0},57:{0:void 0,1:void 0,2:void 0,3:void 0},58:{0:void 0,1:void 0,2:void 0,3:void 0},59:{0:void 0,1:void 0,2:void 0,3:void 0},60:{0:void 0,1:void 0,2:void 0,3:void 0},61:{0:void 0,1:void 0,2:void 0,3:void 0},62:{0:void 0,1:void 0,2:void 0,3:void 0},63:{0:void 0,1:void 0,2:void 0,3:void 0},64:{0:void 0,1:void 0,2:void 0,3:void 0},65:{0:void 0,1:void 0,2:void 0,3:void 0},66:{0:void 0,1:void 0,2:void 0,3:void 0},67:{0:void 0,1:void 0,2:void 0,3:void 0},68:{0:void 0,1:void 0,2:void 0,3:void 0},69:{0:void 0,1:void 0,2:void 0,3:void 0},70:{0:void 0,1:void 0,2:void 0,3:void 0},71:{0:void 0,1:void 0,2:void 0,3:void 0},72:{0:void 0,1:void 0,2:void 0,3:void 0},73:{0:void 0,1:void 0,2:void 0,3:void 0},74:{0:void 0,1:void 0,2:void 0,3:void 0},75:{0:void 0,1:void 0,2:void 0,3:void 0},76:{0:void 0,1:void 0,2:void 0,3:void 0},77:{0:void 0,1:void 0,2:void 0,3:void 0}};const s=new $p(this.tsCall,{config:this._config});this._capabilityResolver=new Jg(this._eventEmitter,this.logger,this,s,t,i),yc().calling.mediaMetricsDeviceEventsEnabled&&(this._dmDevicesChangedSub=this._callAgent.tsStack?.getDeviceManager().on("devicesChanged",(()=>{this.setOrUpdateMediaMetricsDeviceEvents()}))),this._extensibleApi=new vg(this.logger,{call:this,callAgent:this._callAgent,callInfo:new $p(this.tsCall,{config:this._config})},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this._lobby=new FC(this.tsCall,this,this.logger,this._telemetryLogManager);const o=pC(Yp.CallFeature);for(const e of o)"OnExtendedObjectConstructor"===e.activationOptions.activationEvent&&this.feature(e);this._mmrRdpConnectionManager=new VC(this.logger),yc().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),yc().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new l_(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new NC(this.tsCall,this.logger,this._telemetryLogManager),this._isACSModeledInteropCall=a??!1}async accept(e={}){const t=e.audioOptions?.muted??!1,i=this.getLocalVideoStreamFromCallOptions(e),n=this.getLocalAudioStreamFromCallOptions(e),r=+new Date,a=x(),s=this._callAgent.getEcsConfigIds();let o={joinContextDescription:"",additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:!!i,...BC(),AcsCallingSDKWeb_ecsConfigId:s.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:s.SkypeWebMedia},additionalDetails:{}};const l=(e,t)=>{const s=+new Date;let l,c={...o};if(t){const{callEndReason:t,callingCommunicationError:i}=Dg(e,this);c.additionalDetails.callEndReason=t,l=i}else l=new b({defaultError:f.CALL.ACCEPT_INCOMING_CALL,originalError:e}),c.additionalDetails.communicationServicesError=xg(l).communicationServicesError;return this.sendCallStageEvent({eventName:Jh.acs_calling_call_accept_failed,correlationId:a,timestampInfo:{deltaTimeInMs:s-r},additionalPayload:c},l),i&&(this.sendVideoEvent({correlationId:a,eventName:Jh.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:s-r},localVideoStream:i,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn},l),this.removeLocalVideoStream(i)),n&&this.removeLocalAudioStream(n),l};try{if(e?.videoOptions?.constraints){let t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});o.additionalProperties.constraints=t}this.sendCallStageEvent({eventName:Jh.acs_calling_call_accept_attempt,correlationId:a,timestampInfo:{attemptTimestamp:r},additionalPayload:o});let s={...o};if(i&&this.setLocalVideoStream(i),this.setLocalAudioStream(n),i&&this.sendVideoEvent({eventName:Jh.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:r},correlationId:a,step:"accept",isScreenSharingOnFlag:this._isScreenSharingOn}),1!==this.tsCall.state)throw new b({defaultError:f.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){const t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,"accept",a,r),i=this._mediaConstraintsManager.getTelemetryPayload({video:t});s.additionalProperties.constraints=i}}catch(e){const t=new b({defaultError:f.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}const c=this._getReceiveOnlyAudioOnCallStart(n),d={withVideo:!!i,receiveOnlyAudioOnCallStart:c,muted:t};return t&&(d.muteFlags=1),yc()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(d.mediaConfiguration={connectionType:"NoDirectConnection"}),"RawMedia"===i?.mediaStreamType&&await this._setRawStream(i,1),this.tsCall.accept(d).then((async()=>{const e=+new Date;i&&this.shallRemoveLvsAfterConnectedSuccessfully(i,"accept",a,e,r),n&&(this.startAudioInternal(n,!0).catch((e=>{})),this.shallRemoveLasAfterConnectedSuccessfully(n,"accept",a,e,r)),this.sendCallStageEvent({eventName:Jh.acs_calling_call_accept_connected,correlationId:a,timestampInfo:{deltaTimeInMs:e-r},additionalPayload:s})})).catch((e=>{l(e,!0)})),this}catch(e){throw l(e,!1)}}async reject(){const e=+new Date,t=x();this.sendCallStageEvent({eventName:Jh.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});const i=this._callAgent.getEcsConfigIds(),n={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:i.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:i.SkypeWebMedia},additionalDetails:{}};if(1!==this.tsCall.state){const i=new b({defaultError:f.CALL.REJECT_NOT_RINGING});n.additionalDetails.communicationServicesError=xg(i).communicationServicesError;const r=+new Date;throw this.sendCallStageEvent({eventName:Jh.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:r-e},additionalPayload:n},i),i}return this.tsCall.reject().then((()=>{const i=+new Date;this.sendCallStageEvent({eventName:Jh.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:i-e}})})).catch((i=>{const r=+new Date,{callEndReason:a,callingCommunicationError:s}=Dg(this,i);throw n.additionalDetails.callEndReason=a,this.sendCallStageEvent({eventName:Jh.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:r-e},additionalPayload:n},s),s}))}dispose(){this._disposed||(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener("online",this._onlineListener),this._offlineListener&&window.removeEventListener("offline",this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this._disposed=!0)}async startAudioInternal(e,t=!1){const i=x(),n=+new Date;if(this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.attempt,isInternal:t,timestampInfo:"",additionalDetails:""}),"RawMedia"!==e.mediaStreamType){if(t)return void this.logger.info("startAudioInternal internal call: LocalAudioStream media type is not raw media, skipping raw audio startAudioInternal");{const e=new b({defaultError:f.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA});this.logger.error(`Failed to start raw media audio: ${f.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA.message}`);const r=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,isInternal:t,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:r-n},additionalDetails:{failureReason:e.message||"",code:e.code,subCode:e.subCode,...xg(e)}}),e}}let r;this._userProvidedLocalAudioStreamCache=e;try{r=await e.getMediaStream()}catch(e){const r=new b({defaultError:f.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e});this.logger.error(`Failed to get raw stream with error: ${e}`);const a=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,isInternal:t,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:a-n},additionalDetails:{failureReason:r.message||"",code:r.code,subCode:r.subCode,...xg(r)}}),r}const a=this._callAgent.tsStack?.getDeviceManager();if(!yc()?.calling?.allowAccessRawMediaStream||!a?.setRawMediaStream){const e=new b({defaultError:f.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});this.logger.error("Failed to set raw input audio stream");const r=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,isInternal:t,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:r-n},additionalDetails:{failureReason:e.message||"",code:e.code,subCode:e.subCode,...xg(e)}}),e}const s=new MediaStream(r);a?.setRawMediaStream(s,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);const o=+new Date;this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:""})}stopAudioInternal(e=!1){const t=x(),i=+new Date;this.sendRawMediaEvent({eventName:Jh.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.attempt,isInternal:e,timestampInfo:"",additionalDetails:""});const n=this._localAudioStreams[0];if("RawMedia"!==n?.mediaStreamType){if(e)return void this.logger.info("stopAudioInternal internal call: LocalAudioStream media type is not raw media, skipping raw audio stopAudioInternal");{const n=new b({defaultError:f.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA});this.logger.error(`Failed to stop raw media audio: ${f.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA.message}`);const r=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:n.message||"",code:n.code,subCode:n.subCode,...xg(n)}}),n}}const r=this._callAgent.tsStack?.getDeviceManager();if(!yc()?.calling?.allowAccessRawMediaStream||!r?.unsetRawMediaStream){const n=new b({defaultError:f.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});this.logger.error("Failed to unset raw input audio stream");const r=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:n.message||"",code:n.code,subCode:n.subCode,...xg(n)}}),n}r.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();const a=+new Date;this.sendRawMediaEvent({eventName:Jh.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:a-i},additionalDetails:""})}bindTsCall(){void 0!==this.tsCall.callerMri&&(this._callerIdentity=ac(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.updateCallMode(),this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"id-changed",isACSModeledInteropCall:this.isACSModeledInteropCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit("idChanged")),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit("isScreenSharingOnChanged")),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||this.tsCall.threadId)&&this.tsCall.meetingDetails&&function(e,t){return null==t.meetingCapability&&null!=e.meetingCapability||null==t.capabilities&&null!=e.capabilities||!(g.isEqual(t.capabilities,e.capabilities)&&g.isEqual(t.meetingCapability,e.meetingCapability))}(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode(),this.optimalVideoCountChanged()})),this.tsCall.on("serverMutedChanged",(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()})),this._totalParticipantCount=this.getTotalNotBotParticipantCount(),this.tsCall.on("participantCountsUpdated",(()=>{const e=this.getTotalNotBotParticipantCount();if(this._totalParticipantCount!==e){const t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),yc().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit("totalParticipantCountChanged");try{this.stats.recordEvent({name:Kh.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch(e){this.logger.error("failed to send participant count change telemetry")}}})),this.tsCall.on("callQualityChanged",(async e=>{try{let t;5===e.type||32===e.type||2===e.type||1===e.type||37===e.type?(t=Kh.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):t=44===e.type||43===e.type||9===e.type||25===e.type||27===e.type||45===e.type||33===e.type||34===e.type||55===e.type||26===e.type||47===e.type?Kh.video_device_issue:Kh.other_diagnostic,3===e.value||2===e.value?(this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===Kh.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!1}))):(this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===Kh.network_quality&&window.dispatchEvent(new CustomEvent("online",{detail:!0})));let i="";const n=this._ufdsCorrelationIdCache[e.type][e.mediaType];3==e.value||2==e.value?n?i=n:(i=x(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=i):(n&&(i=n),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);const r={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:i};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:r}),this.shallStopVideo(e)){const t=+new Date,i=x();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:Jh.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch(t){const i=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(i)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){const t=new b({defaultError:f.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});this.localVideoStream&&(this.sendVideoEvent({eventName:Jh.acs_calling_start_video_failure,correlationId:x(),timestampInfo:{attemptTimestamp:+new Date},step:"start",additionalDetails:{...xg(t)},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)),this.logger.error(t.message)}if(this.shallStopAudio(e)){const t=+new Date,i=x();if(yc()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:Jh.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.mute()}catch(t){const i=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(i)}}const n=yc()?.calling?.preventStopAudio;if(n)return this.sendAudioEvent({eventName:Jh.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"}),void(!yc()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:Jh.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.stopAudio(),this.markCallMuted();const e=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new b({defaultError:f.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:n});this.logger.error(r.message);const a=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call"},r)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch(e){this.logger.error("Failed to send ufd telemetry")}})),this.tsCall.on("participantAdded",(async e=>{this.logger.debug("tsCall participant added");const t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),0===t.length&&t.push("remoteParticipantId unavailable");const i=ac(e.id);if(this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"added",kindOfEvent:Yh.event}),this.isHiddenBot(e))return this.logger.info("Add participant: Handle hidden calling application"),void this._handleCallingApplicationIdentifier(e);this._handleLocalRingingCallState(e);try{const t=this.getOrCreateRemoteParticipant(i,e);this._eventEmitter.emit("remoteParticipantsUpdated",{added:[t],removed:[]})}catch(e){this.logger.log("unable to map call participant to ACS user")}})),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`),this.tsCall.participants.forEach((e=>{const t=ac(e.id);this.getOrCreateRemoteParticipant(t,e),this._handleLocalRingingCallState(e)}));try{const e=[];this.tsCall.participants.forEach((t=>{t.endpoints?.endpointDetails.forEach((t=>e.push(t.participantId)))})),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:e,participantAddedOrRemoved:"added",kindOfEvent:Yh.initialize})}catch(e){this.logger.info("Remove participant: Ignore calling application")}this.tsCall.on("participantRemoved",(async e=>{this.logger.debug("tsCall participant removed");const t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),0===t.length&&t.push("remoteParticipantId unavailable"),this.isHiddenBot(e))return this.logger.info("Remove participant: Ignore calling application"),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"removed",kindOfEvent:Yh.event});const i=e.id;if(i){const n=this._remoteParticipants.find((e=>rc(e.identifier)===i));if(n){const{callEndReason:i}=Og(this,e);n.setCallEndReason(i),this.deleteRemoteParticipant(n),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[n]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:"removed",kindOfEvent:Yh.event,additionalDetails:{...Fg(i)}})}else this.logger.log("unable to find participant to remove")}}))}_trackNetworkQualityUfdEventDetails(e){const t=+new Date;let i="";switch(e){case 5:i=im;break;case 32:i=am;break;case 2:i=nm;break;case 1:i=rm;break;case 37:i=sm}this._networkQualityUfdEventDetails.push({eventName:i,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{const t=yc().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||9!==e.type||3!==e.value)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await Dh(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info("Unable to perform mute and unmute to recover microphoneNotFunctioning",e)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"callMode-changed",oldState:kg[this._callMode],newState:kg[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}async startCallInternal(e,t,i,n){const r=!!e?.audioOptions?.muted,a=this.getLocalVideoStreamFromCallOptions(e),s=this.getLocalAudioStreamFromCallOptions(e);let o;const l=+new Date,c=x();this._joinContextDescription=function(e){return e?e.groupId?zl.GroupCall:!e.threadId||e.organizerId||e.tenantId||e.messageId?e.threadId&&e.organizerId&&e.tenantId&&e.messageId?zl.TeamsCoordinates:e.meetingId?zl.TeamsMeetingId:e.meetingLink?zl.TeamsMeetingLink:e.roomId?zl.RoomCall:zl.Unknown:zl.GroupChatCall:zl.Unknown}(i);const d=this._callAgent.getEcsConfigIds(),u={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:n?.isEmergency||!1,trouterState:this._callAgent.getTrouterState(),muted:r,withVideo:!!a,...BC(),AcsCallingSDKWeb_ecsConfigId:d.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:d.SkypeWebMedia},additionalDetails:{}};e?.videoOptions?.constraints&&(u.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),n?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=n.meetingInfo.tenantId,u.additionalProperties.teamsMeetingTenantId=n.meetingInfo.tenantId),n?.threadId&&(this._teamsMeetingThreadId=n.threadId,u.additionalProperties.teamsMeetingThreadId=n.threadId),yc().calling.setDeviceType&&"default"!==this._callAgent.getDeviceType()&&(u.additionalProperties.firstPartyOptions={deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode}),this.sendCallStageEvent({eventName:Jh.acs_calling_call_attempt,correlationId:c,timestampInfo:{attemptTimestamp:l},additionalPayload:u});let h={...u},p={...u};try{this._isMicrophoneMuted=r,e?.alternateCallerId&&(o=rc(e.alternateCallerId)),a&&this.setLocalVideoStream(a),this.setLocalAudioStream(s)}catch(e){const t=+new Date,i=new b({defaultError:f.CALL.INSTANTIATE_CALL,originalError:e});throw h.additionalDetails.communicationServicesError=xg(i).communicationServicesError,this.sendCallStageEvent({eventName:Jh.acs_calling_call_failed,correlationId:c,timestampInfo:{deltaTimeInMs:t-l},additionalPayload:h},i),this.logger.error(i.message),i}try{const i={...n};!yc().calling.setDeviceType||"mesh"!==this._callAgent.getDeviceType()&&"meshV2"!==this._callAgent.getDeviceType()||(i.endpointMetadata=JSON.stringify({meshapp:!0})),this.tsCall.init(i),a&&this.sendVideoEvent({correlationId:c,eventName:Jh.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:l},localVideoStream:a,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn});try{if(e?.videoOptions?.constraints){const t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,"start",c,l),i=this._mediaConstraintsManager.getTelemetryPayload({video:t});p.additionalProperties.constraints=i}}catch(e){const t=new b({defaultError:f.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let d=this.setClientEndpointCapabilities(e);yc()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(d.mediaConfiguration={connectionType:"NoDirectConnection"}),r&&(d.muteFlags=1),"RawMedia"===a?.mediaStreamType&&await this._setRawStream(a,1);const u=this._getReceiveOnlyAudioOnCallStart(s);t?await this.tsCall.startWithMeetingData(m.generateCauseId(),{withVideo:!!a,muted:r,ringOthers:!0,alternateId:o,shouldResurrect:"resurrect",receiveOnlyAudioOnCallStart:u,...d}):await this.tsCall.start({withVideo:!!a,muted:r,ringOthers:!0,alternateId:o,receiveOnlyAudioOnCallStart:u,...d});const h=+new Date;this.sendCallStageEvent({eventName:Jh.acs_calling_call_connected,correlationId:c,timestampInfo:{deltaTimeInMs:h-l},additionalPayload:p}),a&&this.shallRemoveLvsAfterConnectedSuccessfully(a,"start",c,h,l),s&&(this.startAudioInternal(s,!0).catch((e=>{})),this.shallRemoveLasAfterConnectedSuccessfully(s,"start",c,h,l)),this._handleAudioEffectsOperations()}catch(e){const t=+new Date,{callEndReason:i,callingCommunicationError:n}=Dg(this,e);throw a&&(this.sendVideoEvent({correlationId:c,eventName:Jh.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-l},localVideoStream:a,step:"start",isScreenSharingOnFlag:this._isScreenSharingOn},n),this.removeLocalVideoStream(a)),s&&this.removeLocalAudioStream(s),h.additionalDetails.callEndReason=Fg(i).callEndReason,this.sendCallStageEvent({eventName:Jh.acs_calling_call_failed,correlationId:c,timestampInfo:{deltaTimeInMs:t-l},additionalPayload:h},n),this.logger.error(`Failed to start the call, message=${i?.message}, code=${i?.code}, subCode=${i?.subCode}, resultCategories=${i?.resultCategories}`),n}}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){const e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(rc(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${yc().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<yc().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){const t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{const i=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>"audio"===e.type)).map((e=>e.sourceId))??[],n=i.length>0?Math.min(...i):void 0,r=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>"audio"===e.type)).map((e=>e.sourceId))??[],a=r.length>0?Math.min(...r):void 0;return void 0!==n&&null!=a?n-a:0}));for(const i of t){if(e.length===yc().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(i)}}else e.splice(yc().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){const e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){const t=+new Date,i=x();return this.sendCallStageEvent({eventName:Jh.acs_calling_call_hangup_attempt,correlationId:i,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone).then((()=>{const e=+new Date;this.sendCallStageEvent({eventName:Jh.acs_calling_call_hangup_success,correlationId:i,timestampInfo:{deltaTimeInMs:e-t}})})).catch((e=>{const n=+new Date,{callEndReason:r,callingCommunicationError:a}=Dg(this,e),s=this._callAgent.getEcsConfigIds(),o={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:s.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:s.SkypeWebMedia},additionalDetails:{...Fg(r)}};throw this.sendCallStageEvent({eventName:Jh.acs_calling_call_hangup_failure,correlationId:i,timestampInfo:{deltaTimeInMs:n-t},additionalPayload:o},a),a}))}async mute(){const e=this.logger.createFnLogger(gp.Mute),t=+new Date,i=x();this.sendAudioEvent({eventName:Jh.acs_calling_mute_attempt,eventType:Zh.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info("mute"),await this.tsCall.mute(),e.info("mute success");const n=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_mute_success,eventType:Zh.MuteMicrophone,timestampInfo:{deltaTimeInMs:n-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK})}catch(n){const r=new b({defaultError:f.CALL.MIC_MUTE,originalError:n});e.error("Failed to mute microphone");const a=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_mute_failure,eventType:Zh.MuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK},r),r}}async unmute(){const e=this.logger.createFnLogger(gp.Unmute),t=+new Date,i=x();let n=!1;this.sendAudioEvent({eventName:Jh.acs_calling_unmute_attempt,eventType:Zh.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info("unmute"),await this.tsCall.unmute(),e.info("unmute success");const r=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_unmute_success,eventType:Zh.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:r-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});const a=+new Date,s=yc()?.calling?.preventStopAudio;if(!s&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:Jh.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:a},correlationId:i,step:"mid-call"}),n=!0,e.info("start audio"),await this.tsCall.startAudio(),e.info("start audio success");const t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Jh.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-a},correlationId:i,step:"mid-call"})}this.setLocalAudioStream()}catch(r){const a=n?f.CALL.MIC_UNMUTE_AND_STARTAUDIO:f.CALL.MIC_UNMUTE,s=new b({defaultError:a,originalError:r});e.error(a.message);const o=+new Date;throw this.sendAudioEvent({eventName:n?Jh.acs_calling_start_audio_failure:Jh.acs_calling_unmute_failure,eventType:n?void 0:Zh.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:o-t},correlationId:i,step:"mid-call",initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!n},s),s}}async muteAllRemoteParticipants(){if(!yc().calling.enableMuteOthers)throw new b({defaultError:f.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});const e=this.logger.createFnLogger(gp.MuteAllRemoteParticipants),t=+new Date,i=x();this.sendAudioEvent({eventName:Jh.acs_calling_mute_attempt,eventType:Zh.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{e.info("mute all others"),await this.tsCall.muteParticipants(0,[]),e.info("mute all others success");const n=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_mute_success,eventType:Zh.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:n-t},correlationId:i,step:"mid-call"})}catch(n){const r=new b({defaultError:f.CALL.MUTE_ALL_PARTICIPANTS,originalError:n});e.error(r.message);const a=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_mute_failure,eventType:Zh.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call"},r),r}}async muteIncomingAudio(){const e=this.logger.createFnLogger(gp.MuteIncomingAudio),t=+new Date,i=x();this.sendAudioEvent({eventName:Jh.acs_calling_mute_attempt,eventType:Zh.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.muteSpeaker();const e=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_mute_success,eventType:Zh.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new b({defaultError:f.CALL.MUTE_INCOMING_AUDIO,originalError:n});e.error(r.message);const a=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_mute_failure,eventType:Zh.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call"},r),r}}async unmuteIncomingAudio(){const e=this.logger.createFnLogger(gp.MuteIncomingAudio),t=+new Date,i=x();this.sendAudioEvent({eventName:Jh.acs_calling_unmute_attempt,eventType:Zh.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:i,step:"mid-call"});try{await this.tsCall.unmuteSpeaker();const e=+new Date;this.sendAudioEvent({eventName:Jh.acs_calling_unmute_success,eventType:Zh.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:i,step:"mid-call"})}catch(n){const r=new b({defaultError:f.CALL.UNMUTE_INCOMING_AUDIO,originalError:n});e.error(r.message);const a=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_unmute_failure,eventType:Zh.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:i,step:"mid-call"},r),r}}async sendDtmf(e){const t=function(e){switch(e){case"Num0":return 0;case"Num1":return 1;case"Num2":return 2;case"Num3":return 3;case"Num4":return 4;case"Num5":return 5;case"Num6":return 6;case"Num7":return 7;case"Num8":return 8;case"Num9":return 9;case"Star":return 10;case"Pound":return 11;case"A":return 12;case"B":return 13;case"C":return 14;case"D":return 15;case"Flash":return 16;default:throw new b({defaultError:f.CALL.INVALID_DTMF_TONE})}}(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error("Failed to send DTMF tone"),new b({defaultError:f.CALL.DTMF_TONE})}))}async startVideo(e){const t=this.logger.createFnLogger(gp.StartVideo),i=+new Date,n=x(),r=yc()?.calling?.preventStopAudio;if(this.sendVideoEvent({eventName:Jh.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},localVideoStream:e,correlationId:n,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:Jh.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:i},correlationId:n,step:"mid-call"});try{t.info("start audio before starting video"),await this.tsCall.startAudio(),t.info("start audio success before starting video");const e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Jh.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-i},correlationId:n,step:"mid-call"})}catch(e){const r="Failed to start audio before starting video",a=new b({defaultError:f.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(r);const s=+new Date;throw this.sendAudioEvent({eventName:Jh.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:s-i},correlationId:n,step:"mid-call"},a),a}}try{if(!e)throw new b({defaultError:f.CALL.STREAM_NULL});if(!(e instanceof Nf))throw new b({defaultError:f.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new b({defaultError:f.CALL.VIDEO_ALREADY_ON});"RawMedia"===e?.mediaStreamType&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){const r=new b({defaultError:f.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},r),r}try{t.info("start video"),await this.tsCall.startVideo();const r=+new Date;this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),t.info("video started")}catch(r){const t=+new Date,a=Ng(0,r);throw this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},a),this.removeLocalVideoStream(e),a}}async stopVideo(e){const t=this.logger.createFnLogger(gp.StopVideo),i=+new Date,n=x();if(this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),!this.tsCall.isVideoOn){const t=new b({defaultError:f.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},t),t}if(this.localVideoStream!==e){const t=new b({defaultError:f.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},t),t}const r=()=>{try{if(yc().calling.allowAccessRawMediaStream&&"RawMedia"===e.mediaStreamType){const e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??"Unkown error"}`)}};try{t.info("stop video"),await this.tsCall.stopVideo(),r();const a=+new Date;this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:a-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn}),t.info("video stopped"),this.removeLocalVideoStream(e)}catch(t){r();const a=+new Date,s=Ng(0,t);throw this.sendVideoEvent({correlationId:n,eventName:Jh.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:a-i},localVideoStream:e,step:"mid-call",isScreenSharingOnFlag:this._isScreenSharingOn},s),s}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){const e=+new Date,t=x();try{this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:Dp.Standard}}),await this.tsCall.hold(),this.removeLocalAudioStream(this._localAudioStreams[0]);const i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:Dp.Standard}})}catch(i){const n=+new Date,r=new b({defaultError:f.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:Dp.Standard,...xg(r)}}),r}}async resume(){const e=+new Date,t=x();try{this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:Dp.Standard}}),await this.tsCall.unhold(),this.setLocalAudioStream();const i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:Dp.Standard}})}catch(i){const n=+new Date,r=new b({defaultError:f.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:Dp.Standard,...xg(r)}}),r}}async startScreenSharing(e){this.logger.createFnLogger(gp.StartScreenShare);const t=+new Date,i=x();try{if(this.sendScreenShareEvent({eventName:Jh.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:e}),3!==this.tsCall.state)throw new b({defaultError:f.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new b({defaultError:f.CALL.SS_ALREADY_ON});if(e){if(!(e instanceof Nf))throw new b({defaultError:f.CALL.SS_RAW_STREAM_IS_NOT_LVS});if("RawMedia"!==e.mediaStreamType)throw new b({defaultError:f.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new Nf(new Tf(ic,x(),ic,this._callAgent.deviceManager))}catch(e){const n=+new Date;this.removeScreenSharingStream();const r=new b({defaultError:f.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:Jh.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-t},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...xg(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}return this.tsCall.startScreenSharing().then((()=>{const e=+new Date;this.localScreenSharingStream&&-1===this._localVideoStreams.indexOf(this.localScreenSharingStream)&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit("localVideoStreamsUpdated",{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:Jh.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:e-t},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream})})).catch((e=>{const n=+new Date;this.removeScreenSharingStream();const r=Ng(0,e);throw this.sendScreenShareEvent({eventName:Jh.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-t},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...xg(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}))}async stopScreenSharing(){this.logger.createFnLogger(gp.StopScreenShare);const e=+new Date,t=x();if(this.sendScreenShareEvent({eventName:Jh.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),3!==this.tsCall.state)throw new b({defaultError:f.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){const i=+new Date,n=new b({defaultError:f.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:Jh.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...xg(n)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),n}return this.tsCall.stopScreenSharing().then((()=>{const i=+new Date,n=g.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:Jh.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:"",isVideoOn:this._isLocalVideoStarted,localVideoStream:n})})).catch((i=>{const n=+new Date,r=Ng(0,i);let a="string"==typeof r?.message?r?.message:void 0;throw this.sendScreenShareEvent({eventName:Jh.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:a||"",code:r.code,subCode:r.subCode,...xg(r)},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),r}))}async setConstraints(e){const t=+new Date,i=x();try{let n=await this._mediaConstraintsManager.setVideoConstraints(e?.video,"mid-call",i,t);this.logger.info(`Video constraints set - ${JSON.stringify(n)}`)}catch(e){throw new b({defaultError:f.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if("stateChanged"!==e&&"idChanged"!==e&&"isMutedChanged"!==e&&"isIncomingAudioMutedChanged"!==e&&"isScreenSharingOnChanged"!==e&&"isLocalVideoStartedChanged"!==e&&"remoteParticipantsUpdated"!==e&&"localVideoStreamsUpdated"!==e&&"localAudioStreamsUpdated"!==e&&"remoteAudioStreamsUpdated"!==e&&"totalParticipantCountChanged"!==e&&"roleChanged"!=e&&"mutedByOthers"!==e)throw new b({defaultError:f.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("stateChanged"!==e&&"idChanged"!==e&&"isMutedChanged"!==e&&"isIncomingAudioMutedChanged"!=e&&"isScreenSharingOnChanged"!==e&&"isLocalVideoStartedChanged"!==e&&"remoteParticipantsUpdated"!==e&&"localVideoStreamsUpdated"!==e&&"localAudioStreamsUpdated"!==e&&"remoteAudioStreamsUpdated"!==e&&"totalParticipantCountChanged"!=e&&"roleChanged"!=e&&"mutedByOthers"!==e)throw new b({defaultError:f.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if("meetingCapabilitiesChanged"!==e)throw new b({defaultError:f.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if("meetingCapabilitiesChanged"!=e)throw new b({defaultError:f.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log("participant capabilities change event listener registered"),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log("participant capabilities change event listener unregistered"),this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let i=this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)));return i||(i=new o_(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(i),this._mriToRemoteParticipantMap.set(rc(i.identifier),i)),t&&i.observeParticipant(t),i}deleteRemoteParticipant(e){let t=!0;return 1!==this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length&&(this.logger.warn("Deleted remote participant array is not 1"),t=!1),this._mriToRemoteParticipantMap.delete(rc(e.identifier))||(this.logger.warn("Deleted remote participant was not found in mri-to-remoteparticipant map"),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send call hold or resume telemetry")}}sendVideoEvent(e,t){try{let i,n;try{i=e.localVideoStream?.getStreamMetadata()}catch(e){this.logger.error("Unable to get stream meta data on send video event")}t&&(n="string"==typeof t?.message?t?.message:void 0,e.additionalDetails={...xg(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{...i,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:n||"",isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{}}})}catch(e){this.logger.debug("Unable to send video telemetry")}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch(e){this.logger.error("Unable to get stream meta data on send video event")}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch(e){this.logger.debug("Unable to send screen share telemetry")}}sendRawMediaEvent(e){const t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?"MediaStream":"Device";try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:t})}catch(e){this.logger.debug("Unable to send raw media telemetry")}}sendAudioEvent(e,t){try{let i;t&&(i="string"==typeof t?.message?t?.message:void 0,e.additionalDetails={...xg(t)});const n={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||"",failureReason:i||"",additionalDetails:e.additionalDetails||{}};void 0!==e.eventType&&(n.eventType=e.eventType),e.initiatedBySdk&&(n.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:n})}catch(e){this.logger.debug("Unable to send audio telemetry")}}sendCallStageEvent(t,i,n){try{let r,a="";i&&(r=this?.tsCall?.callEndDiagnosticsInfo||n||{},a=i.message);const s=this._joinContextDescription===zl.RoomCall||this.kind===e.CallKind.Call&&"Incoming"===this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,o=!s&&this._joinContextDescription===zl.TeamsMeetingLink||this._joinContextDescription===zl.TeamsMeetingId||this._joinContextDescription===zl.TeamsCoordinates||"Incoming"==this._direction&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,l={localParticipantId:this?.tsCall?.participantId||"",callId:this?.tsCall?.callId||"",callType:this?.tsCall?.callType||"",callDirection:this._direction,failureReason:a,callEndDiagnosticsInfo:r,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:s,meetingJoin:o,correlationId:t.correlationId,timestampInfo:t.timestampInfo,...t.additionalPayload};this._telemetryLogManager.sendEvent({name:t.eventName,tenant:hl,properties:l})}catch(e){}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return nc.group;if(0===this.tsCall?.participants.length)return nc.unknown;const e=this.tsCall?.participants[0];return ac(e.id).kind}optimalVideoCountChanged(){const e=this._optimalVideoCount,t=this.tsCall.optimalVideoCount;if(t&&e!==t)try{d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"optimalVideoCount-changed",previousOptimalVideoCount:e,newOptimalVideoCount:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch(e){this.logger.error("Failed to send optimal video count change telemetry")}finally{this._optimalVideoCount=this.tsCall.optimalVideoCount||1}}_sendNetworkChangedTelemetry(){try{const e=(e,t,i)=>{d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"network-changed",trouterState:e,onLine:t,rdpState:i})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener("online",this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener("offline",this._offlineListener),this._mmrRdpConnectionManager.on("stateChange",(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch(e){this.logger.warn("Failed to subscribe to network changed")}}_setupSelectedDeviceChangedTelemetry(){try{const e=e=>{d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"selectedDevice-changed",selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on("selectedDeviceChanged",e);const t=this._selectedDeviceManager.selectedDevice("Speaker"),i=this._selectedDeviceManager.selectedDevice("Microphone");e({selectedDeviceType:"Speaker",oldDevice:void 0,newDevice:t}),e({selectedDeviceType:"Microphone",oldDevice:void 0,newDevice:i})}}catch(e){this.logger.warn("Failed to subscribe to selectedDevice changed")}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new b({defaultError:f.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),"RawMedia"!==this.localVideoStream.mediaStreamType&&this._callAgent.tsStack.getDeviceManager().selectDevices({camera:e.source.id}),this.localVideoStream.addCall(this);try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[this.localVideoStream],removed:[]})}catch(e){this.logger.warn("Application threw on emit localVideoStreamsUpdated added")}this.logger.log("isLocalVideoStarted changed=true"),this._isLocalVideoStarted=!0,this._eventEmitter.emit("isLocalVideoStartedChanged")}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log("Attempting to remove local video stream"),0===this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length)return void this.logger.warn("Stream not found, failed to remove stream from localVideoStreams collection");this.logger.log("Local video stream removed successfully"),this.localVideoStream.removeCall(this),this.localVideoStream.dispose();const t=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[t]})}catch(e){this.logger.warn("Application threw on emit localVideoStreamsUpdated removed")}this.logger.log("isLocalVideoStarted changed=false"),this._isLocalVideoStarted=!1,this._eventEmitter.emit("isLocalVideoStartedChanged")}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new b({defaultError:f.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],removed:[]});else if(0===this._localAudioStreams.length){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),void this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],removed:[]});const t=this.deviceManager?.selectedMicrophone;if(t){const e=new $f(t);e.on("audioSourceChanged",this.audioSourceChanged),this._localAudioStreams.push(e),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[e],removed:[]})}else this.logger.warn("Could not get current selected microphone to update localAudioStreams collection")}else this.logger.warn("No localAudioStream provided and the collection is not empty, doing nothing")}removeLocalAudioStream(e){if(e){if(this.logger.log("Attempting to remove local audio stream"),e.off("audioSourceChanged",this.audioSourceChanged),e.dispose(),0===this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length)return void this.logger.warn("Stream not found, failed to remove stream from localAudioStreams collection");this.logger.log("Local audio stream removed successfully"),this._eventEmitter.emit("localAudioStreamsUpdated",{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{const e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug("No LocalAudioStream found in the call, cannot handle call audio effects operations");this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e};const t=e.feature(hC.AudioEffects);t?.on("effectsProcessorStatsUpdated",this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(yc()?.calling?.allowAccessRawMediaStream&&"RawMedia"===this.localScreenSharingStream?.mediaStreamType){const e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);const e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);const t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._eventEmitter.emit("localVideoStreamsUpdated",{added:[],removed:[t]})}}mapTsCallState(e){let t=Mg[e];switch(t){case"Unknown":case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case"Disconnected":{this._callEndReason=Dg(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(Og(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState("Disconnected")}));const i=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:i}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose(),yc().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log("Telemetry flushed")})).catch((e=>{this.logger.warn("Failed to flush telemetry log manager events")}));break}case"Connected":this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this.setOrUpdateMediaMetricsDeviceEvents(),yc().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case"Incoming Call":{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);const e=new $p(this.tsCall,{config:this._config});d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"state-changed",oldState:this._state,newState:"Incoming Call",callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||"",teamsMeetingThreadId:this._teamsMeetingThreadId||"",callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){const t=yc()?.calling?.deviceNotFunctioningMuted,i=yc()?.calling?.deviceCaptureMutedVideo,n=yc()?.calling?.preventStopVideo,r=25===e.type&&3===e.value,a=r&&1===e.mediaType,s=33===e.type&&3===e.value,o=RC(),l="ios"===AC()&&"Safari"===o.engine,c="android"===AC(),d=3===this.tsCall.state;return n?d&&this.tsCall.isVideoOn&&s:t&&d&&this.tsCall.isVideoOn&&(s||l&&r||i&&c&&a)}shallRemoveLocalVideoStreamOnBadUfd(e){const t=this.tsCall.localMediaStreams.find((e=>1===e.mediaType)),i=1===e.mediaType&&3===e.value&&25===e.type,n=4==this.tsCall.state||5===this.tsCall.state;if("Mobile"===RC().formFactor&&(i||"hidden"==document.visibilityState)&&this.localVideoStream&&n&&!t)return!1;if(!yc()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;const r=3===this.tsCall.state;return!(1!==e.mediaType||3!==e.value||33!==e.type&&25!==e.type&&34!==e.type||!this.localVideoStream||r||t)}shallStopAudio(e){const t=yc()?.calling?.deviceNotFunctioningMuted,i=yc()?.calling?.osAutoRecoverAudio,n=25===e.type&&3===e.value&&0===e.mediaType,r=9===e.type&&3===e.value,a=RC(),s="ios"===AC()&&"Safari"===a.engine,o=3===this.tsCall.state;return i?t&&o&&r:t&&!this._isDeviceNotFunctioningMuted&&o&&(r||s&&n)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){const t=yc()?.calling?.deviceCaptureMuteRecover&&!yc()?.calling?.preventFakeMute,i=25===e.type&&1===e.value&&0===e.mediaType,n=3===this.tsCall.state,r=RC(),a="ios"===AC()&&"Safari"===r.engine,s=9===e.type&&1===e.value;return t&&this._isDeviceNotFunctioningMuted&&n&&(s||a&&i)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_participant_added_or_removed,tenant:hl,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,yc().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||"",timestampInfo:e.timestampInfo||"",additionalDetails:e.additionalDetails||{}}})}catch(e){this.logger.debug("Unable to send participant added telemtery")}}_handleLocalRingingCallState(e){"Connected"===this._state||"Outgoing"!==this._direction||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{2!==e.state||"Connected"===this._state||this._localRingingStateSet||(this._setCallState("Ringing"),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){const t=this._state,i=e,n=new $p(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${i}`),this._state=i,this._eventEmitter.emit("stateChanged"),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"state-changed",oldState:t,newState:i,callTypeInfo:{initiatorKind:n.initiatorKind,targetKind:n.targetKind,transferor:n.transferorKind,context:n.context,callScenario:n.callScenario,direction:n.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||"",teamsMeetingThreadId:this._teamsMeetingThreadId||"",callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:"Disconnected"===this._state&&this._callEndReason?{...Fg(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){let t=Hc(yc(),e);t===Dl?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"role-changed",oldAcsRole:this._role,newAcsRole:t,serviceRole:e||""}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit("roleChanged"))}}_setMeetingCapabilities(e){(function(e,t){return!!(e.capabilities&&null!=e.capabilities.allowVideo&&(null==t.capabilities?.allowVideo||t.capabilities.allowVideo!=e.capabilities.allowVideo)||e.meetingCapability&&null!=e.meetingCapability.allowIPVideo&&(null==t.meetingCapability?.allowIPVideo||t.meetingCapability.allowIPVideo!=e.meetingCapability.allowIPVideo)||e.meetingCapability&&null!=e.meetingCapability.attendeeRestrictions&&(null==t.meetingCapability?.attendeeRestrictions||t.meetingCapability.attendeeRestrictions!=e.meetingCapability.attendeeRestrictions)||e.meetingCapability&&null!=e.meetingCapability.allowPstnConferencing&&(null==t.meetingCapability?.allowPstnConferencing||t.meetingCapability.allowPstnConferencing!=e.meetingCapability.allowPstnConferencing)||e.meetingCapability&&null!=e.meetingCapability.allowTranslatedCaptions&&(null==t.meetingCapability?.allowTranslatedCaptions||t.meetingCapability?.allowTranslatedCaptions!=e.meetingCapability.allowTranslatedCaptions)||e.meetingCapability&&null!=e.meetingCapability.allowTranslatedTranscriptions&&(null==t.meetingCapability?.allowTranslatedTranscriptions||t.meetingCapability?.allowTranslatedTranscriptions!=e.meetingCapability.allowTranslatedTranscriptions)||e.meetingCapability&&null!=e.meetingCapability.allowRaiseHands&&(null==t.meetingCapability?.allowRaiseHands||t.meetingCapability?.allowRaiseHands!=e.meetingCapability.allowRaiseHands)||e.meetingCapability&&null!=e.meetingCapability.allowTeamsMeetingReactions&&(null==t.meetingCapability?.allowTeamsMeetingReactions||t.meetingCapability?.allowTeamsMeetingReactions!=e.meetingCapability.allowTeamsMeetingReactions)||e.meetingCapability&&null!=e.meetingCapability.presenterOption&&(null==t.meetingCapability?.presenterOption||t.meetingCapability?.presenterOption!=e.meetingCapability.presenterOption)||e.capabilities&&null!=e.capabilities.maskIdentitiesForRole&&(null==t.capabilities?.maskIdentitiesForRole||t.capabilities?.maskIdentitiesForRole!=e.capabilities.maskIdentitiesForRole))})(e,this._lastTsCallMeetingDetails)&&(d_(this._telemetryLogManager,this.logger,{...c_(this,this._callAgent,x(),this._joinContextDescription),step:"meetingCapabilities-changed",oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit("meetingCapabilitiesChanged")),Object.assign(this._lastTsCallMeetingDetails,e)}async audioSourceChanged(e){this._telemetryLogManager.sendEvent({name:Jh.acs_calling_local_audio_source_changed,tenant:hl,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:x(),localAudioStream:e.source?.source instanceof MediaStream?"MediaStream":"Device"}}),e.source instanceof Lf?(this.localAudioStreams[0]&&"RawMedia"===this.localAudioStreams[0].mediaStreamType&&this.stopAudioInternal(!0),this._callAgent.tsStack?.getDeviceManager().selectDevices({microphone:e.source.id})):await this.startAudioInternal(e.source,!0)}removeRemoteAudioStream(e){if(e){if(this.logger.log("Attempting to remove remote audio stream"),0===this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),1).length)return void this.logger.warn("Stream not found, failed to remove stream from remoteAudioStreams collection");this.logger.log("remote audio stream removed successfully"),this._eventEmitter.emit("remoteAudioStreamsUpdated",{added:[],removed:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(yc().calling.mediaMetricsDeviceEventsEnabled)try{const e=this.tsCall.getMediaSessionStats();if(void 0!==e?.metrics?.DeviceEvents){const t=JSON.parse(e.metrics.DeviceEvents),i=Vc(this._mediaMetricsDeviceEvents||{},t);i.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:Kh.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:i||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.error("Failed to set media metrics device events telemetry: no valid events data")}catch(e){this.logger.error("Failed to set media metrics device events telemetry")}}setClientEndpointCapabilities(e){const t={};let i=0;return e?.firstPartyOptions?.isImmersiveMode&&(i|=32768),yc()?.calling?.supportLiveStreaming&&(i|=32),i>0&&(t.clientEndpointCapabilities=i),t}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(1!==e?.videoOptions?.localVideoStreams.length)throw new b({defaultError:f.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof Nf))throw new b({defaultError:f.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(1!==e?.audioOptions?.localAudioStreams.length)throw new b({defaultError:f.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof $f))throw new b({defaultError:f.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!yc().calling.allowAccessRawMediaStream)throw new b({defaultError:f.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});const i=this._callAgent.tsStack?.getDeviceManager();if(!i?.setRawMediaStream)throw new b({defaultError:f.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{const n=await e.getMediaStream();if(!n)throw new b({defaultError:f.CALL.SS_RAW_STREAM_UNDEFINED});i.setRawMediaStream(n,t)}catch(e){if(1===t)throw new b({defaultError:f.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(2===t)throw new b({defaultError:f.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,i,n,r){if(this.tsCall.localMediaStreams.find((e=>1===e.mediaType)))this.sendVideoEvent({correlationId:i,eventName:Jh.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:n-r},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn});else{if(!yc()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);const n=+new Date,a=new b({defaultError:f.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(a.message),this.sendVideoEvent({correlationId:i,eventName:Jh.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:n-r},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn},a)}}shallRemoveLasAfterConnectedSuccessfully(e,t,i,n,r){if(this.tsCall.localMediaStreams.find((e=>0===e.mediaType)))this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,kindOfEvent:Yh.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:n-r},additionalDetails:""});else{if(!yc().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);const n=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);const a=new b({defaultError:f.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:Jh.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:i,localAudioStream:e,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:n-r},additionalDetails:{failureReason:a.message||"",code:a.code,subCode:a.subCode,...xg(a)}})}}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=yc().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new Im(new wm(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info("Initialized internal dominant speakers listener"),this._internalDominantSpeakersListener.on("dominantSpeakersChanged",(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info("Initialized large meeting video rendering handler")):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=yc().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info("Disposed of internal dominant speakers listener"),this.remoteParticipants.forEach((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info("All remote streams isAvailable flags were reset"),this.logger.info("Disposed large meeting video rendering handler")))}catch(e){this.logger.error("Failed to handle large meeting video rendering",e)}}isHiddenBot(e){if(sc(e.id)){if(function(e){return!(!e.startsWith(Pl)||e.startsWith(Hl)||e.startsWith(Gl)||e.startsWith($l))}(e.id))return!0;if(yc()?.calling?.blacklistedBots?.includes(e.id))return!0;if(e.endpoints?.endpointDetails&&e.endpoints?.endpointDetails.length>0)return e.endpoints?.endpointDetails[0].endpointMetadata?.__platform?.ui?.hidden}return!1}handleDominantSpeakersVideos(){this.logger.info("Dominant speakers changed during large meeting");const e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>"Video"===e.mediaStreamType)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){const t=new b({defaultError:f.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}const t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(Bp.Internal_LargeMeetingVideoRendering),this.logger.info("Successfully disposed of view during large meeting"))}catch(e){const t=new b({defaultError:f.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}_getReceiveOnlyAudioOnCallStart(e){return"RawMedia"===e?.mediaStreamType&&(this.logger.info("Raw media LocalAudioStream in call options, starting the call as receiveOnlyAudio"),!0)}}h_([bf,p_("design:type",Object)],g_.prototype,"logger",void 0),h_([P(gp.BindToCall),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",void 0)],g_.prototype,"bindTsCall",null),h_([P(gp.Feature),p_("design:type",Function),p_("design:paramtypes",[Object]),p_("design:returntype","function"==typeof(u_="undefined"!=typeof TFeature&&TFeature)?u_:Object)],g_.prototype,"feature",null),h_([M(gp.HangUp),p_("design:type",Function),p_("design:paramtypes",[Object]),p_("design:returntype",Promise)],g_.prototype,"hangUp",null),h_([M(gp.Mute),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"mute",null),h_([M(gp.Unmute),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"unmute",null),h_([M(gp.MuteAllRemoteParticipants),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"muteAllRemoteParticipants",null),h_([M(gp.MuteIncomingAudio),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"muteIncomingAudio",null),h_([M(gp.UnmuteIncomingAudio),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"unmuteIncomingAudio",null),h_([M(gp.SendDtmf),p_("design:type",Function),p_("design:paramtypes",[String]),p_("design:returntype",Promise)],g_.prototype,"sendDtmf",null),h_([M(gp.StartVideo),p_("design:type",Function),p_("design:paramtypes",[Nf]),p_("design:returntype",Promise)],g_.prototype,"startVideo",null),h_([M(gp.StopVideo),p_("design:type",Function),p_("design:paramtypes",[Nf]),p_("design:returntype",Promise)],g_.prototype,"stopVideo",null),h_([M(gp.startAudio),p_("design:type",Function),p_("design:paramtypes",[$f]),p_("design:returntype",Promise)],g_.prototype,"startAudio",null),h_([k(gp.Hold),M(gp.Hold),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"hold",null),h_([k(gp.Resume),M(gp.Resume),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"resume",null),h_([M(gp.StartScreenShare),p_("design:type",Function),p_("design:paramtypes",[Nf]),p_("design:returntype",Promise)],g_.prototype,"startScreenSharing",null),h_([M(gp.StopScreenShare),p_("design:type",Function),p_("design:paramtypes",[]),p_("design:returntype",Promise)],g_.prototype,"stopScreenSharing",null),h_([M(gp.SetConstraints),p_("design:type",Function),p_("design:paramtypes",[Object]),p_("design:returntype",Promise)],g_.prototype,"setConstraints",null);var m_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},f_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class v_ extends g_{get info(){return this._info}constructor(t,i,n,r,a){super(t,i,n,r,e.CallKind.Call,a),this._info=new $p(n,{roomId:t.roomId}),this._info.initialize(this._eventEmitter,this.logger,this._telemetryLogManager)}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let i,r;const a=t,s=t,o=t,l=+new Date,c=x();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.attempt,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{attemptTimestamp:l}}),this._callAgent.isCteUser())switch(this.validateThreadId(e,t),n.getIdentifierKind(e).kind){case"communicationUser":r=a.threadId;break;case"microsoftTeamsUser":r=o.threadId;break;case"phoneNumber":r=s.threadId;break;default:{const e=new b({defaultError:f.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-l},additionalDetails:{code:e.code,failureReason:e.message,...xg(e)}}),e}}let d;s?.alternateCallerId&&(oc(s.alternateCallerId),i=rc(s.alternateCallerId));try{if(d=oc(e),!$c(this.acsProxy,this.acsCustomRelayManager,!1,d))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-l},additionalDetails:{code:e.code,failureReason:e.message,...xg(e)}}),e}if(this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)))){const t=new b({defaultError:f.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[n.getIdentifierKind(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-l},additionalDetails:{code:t.code,failureReason:t.message,...xg(t)}}),t}const u=Gc([e]);this._isACSModeledInteropCall=u,yc().calling.enableSmePassFakeConversation&&!r&&e&&u&&(r=this.tsCall.threadId||`${E}${x()}`);const h=this.getOrCreateRemoteParticipant(ac(rc(e)));return this.tsCall.addParticipant(rc(e),{alternateId:i,threadId:r}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.success,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-l}})})).catch((t=>{const{callEndReason:i}=Og(this,h.tsRemoteParticipant,t);h.callEndReason||h.setCallEndReason(i);const n=Fg(i);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-l},additionalDetails:{code:n?.callEndReason.code,subCode:n?.callEndReason.subCode,failureReason:n?.callEndReason.message,...n}}),this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)))&&(this.deleteRemoteParticipant(h),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[h]}))})),h}async removeParticipant(e,t){const i=+new Date,r=x();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.attempt,participantAddedOrRemoved:"remove",correlationId:r,timestampInfo:{attemptTimestamp:i}});try{oc(e)}catch(e){const t=new b({defaultError:f.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{code:e.code,failureReason:e.message,...xg(t)}}),t}let a=this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)));if(!a){const t=new b({defaultError:f.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[n.getIdentifierKind(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,...xg(t)}}),t}try{await this.tsCall.removeParticipant(rc(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.success,participantAddedOrRemoved:"remove",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date}})}catch(e){const t=Og(this,a.tsRemoteParticipant,e).callEndReason;a.callEndReason||a.setCallEndReason(t);const n=Fg(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:n?.callEndReason.code,subCode:n?.callEndReason.subCode,failureReason:n?.callEndReason.message,...n}}),new b({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new b({defaultError:f.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}}m_([P(gp.AddParticipant),f_("design:type",Function),f_("design:paramtypes",[Object,Object]),f_("design:returntype",Object)],v_.prototype,"addParticipant",null),m_([M(gp.RemoveParticipant),f_("design:type",Function),f_("design:paramtypes",[Object,Object]),f_("design:returntype",Promise)],v_.prototype,"removeParticipant",null);var S_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class y_{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get callEndReason(){return this._callCommon.callEndReason}constructor(e,t){this._callCommon=e,this._eventEmitter=new Kp.EventEmitter,this._kind=t,this._callConnected="Connected"===this._callCommon.state,this._callCommon.on("stateChanged",(()=>{"Connected"===this._callCommon.state?this._callConnected=!0:"Disconnected"!==this._callCommon.state||this._callConnected||this._eventEmitter.emit("callEnded",{callEndReason:this._callCommon.callEndReason})}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([M(),S_("design:type",Function),S_("design:paramtypes",[]),S_("design:returntype",Promise)],y_.prototype,"reject",null);var C_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class __ extends y_{get info(){return this._call.info}constructor(t){super(t,e.IncomingCallKind.IncomingCall),this._call=t}async accept(e){if("microsoftTeamsUser"===this.info?.initiatorKind&&!$c(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([M(gp.Accept),C_("design:type",Function),C_("design:paramtypes",[Object]),C_("design:returntype",Promise)],__.prototype,"accept",null);class E_{constructor(e,t){this.logger=e,this.proxy=t}async sendRequestWithRetry(e,t,i,n,r,a=1,s){if(a>r)throw new Error("Max retry reached");n.timeout||(n.timeout=2e4),n.maxRedirects=0,this.proxy&&(t=this.proxy.proxyfyUrl(t));try{switch(e){case"post":default:return await Uy.post(t,i,n);case"get":return await Uy.get(t,n);case"put":return await Uy.put(t,i,n);case"delete":return await Uy.delete(t,n)}}catch(o){let l=o?.response?.status;this.logger.error(`Found error for request ${e} ${t} ${l||""}`);const c=a+1;if(c<=r){let a=t;if(o&&o.response)if(301===o.response.status||302===o.response.status||303===o.response.status||307===o.response.status||404===o.response.status)a=o.response.headers&&o.response.headers.location?o.response.headers.location:a;else if(o.response.status<500)throw o;return this.logger.error(`Retrying, attempt #${c} url=${a}`),await new Promise((e=>setTimeout(e,s))),this.sendRequestWithRetry(e,a,i,n,r,c,s)}throw o}}}const T_="callNotification",b_="conversationInvitation",I_="debugContent",w_="groupContext";class R_{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,i){if(this._callId="",this._localParticipantId="",this._logger=i.createChild("IncomingCallPushNotificationHandler"),!e.incomingCallContext)throw new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse(Mh.inflate(atob(this._incomingCallContext),{to:"string"})),!(this._gp.hasOwnProperty(T_)&&this._gp.hasOwnProperty(b_)&&this._gp.hasOwnProperty(I_)&&this._gp.hasOwnProperty(w_)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((e=>e.callId==this._callId)))throw new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});const e=kh(),t=t=>{const i=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&1===t.state&&e.resolve()};this._tsCallStateSub=t.on("callStateChanged",i),i()};this._tsCallRegistrySub=this._tsCallRegistry.on("callAdded",t);const i={eventId:107,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(i))throw new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new b({defaultError:f.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}}class A_{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};const i=t.createClientLogger("ACS");this._logger=new Pf(i)}initialize(e){this._localParticipant=e.localParticipant,this._skypeToken=e.skypeToken,this._userDialedPstnNumber=e.pstnNumber,this._emergencyNumber=this._userDialedPstnNumber,this._telemetryLogManager=e.telemetryLogManager}async CreateChatThreadId(e,t){this._callId=e;let i="",n="",r={};const a=+new Date;let s=t?.createThreadIdSuffix;this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:s??yc().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:""});const o=this.getAcsMiddletierServiceRequestHeaderForThreadApi();n=0==s?.indexOf("/")?yc().MiddleTier.baseServiceUrl+s:yc().MiddleTier.baseServiceUrl+"/"+s,t?.participants.push({id:this._localParticipant}),r={Participants:t?.participants};try{let e=await this._httpRequestHelper.sendRequestWithRetry("post",n,r,{headers:o},yc().MiddleTier.maxRetry);this._logger.info("Successfully created chat thread using ACS MiddleTier Service."),this._threadIdData=e?.data;const t=+new Date;return this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:s??yc().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:t-a},additionalDetails:{phrase:"Thread Id was successfully created from ACS MiddleTier Service",code:0,subCode:220006}}),Promise.resolve(this._threadIdData.threadId)}catch(e){const t=+new Date;i="Error creating thread Id from ACS MiddleTier Service",this._logger.error(i);const n=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:s??yc().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-a},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...xg(n)}}),n}}async AddParticipantsToThread(e,t){this._callId=e;let i="",n={};const r=+new Date;let a=t?.addParticipantsSuffix;this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:a??yc().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:""});const s=this.getAcsMiddletierServiceRequestHeaderForThreadApi();i=0==a?.indexOf("/")?yc().MiddleTier.baseServiceUrl+a:yc().MiddleTier.baseServiceUrl+"/"+a,n={threadId:t?.threadId,Participants:t?.participants};try{let e=await this._httpRequestHelper.sendRequestWithRetry("post",i,n,{headers:s},yc().MiddleTier.maxRetry);this._logger.info("Call to add participants to chat thread using ACS MiddleTier Service");let t=e?.data;if(null!==t){if(!t.isSuccess)throw new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&735==t.multipleStatus[0].statusCode&&this._logger.info("Trying to add the same participant to the thread id")}const o=+new Date;return this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:a??yc().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:o-r},additionalDetails:{phrase:"Successfully add participants from ACS MiddleTier Service",code:0,subCode:220007}}),Promise.resolve(t.isSuccess)}catch(e){const t=+new Date;this._logger.error("");const i=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Jh.acs_calling_middletier_gateway_api,callId:this._callId,suffix:a??yc().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-r},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...xg(i)}}),i}}async fetchUserPoliciesFromAcsMiddleTier(e,t,i){this._callId=e,this._participantId=t;let n="",r={};const a=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_policy,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:""}),!this._localParticipant){const e=+new Date,t=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_policy,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:e-a},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...xg(t)}}),t}if(i){let e=i.policyUrlSuffix;n=0==e.indexOf("/")?yc().MiddleTier.baseServiceUrl+e:yc().MiddleTier.baseServiceUrl+"/"+e,r={id:this._localParticipant,userPolicies:i.userPolicies,userProperties:i.userProperties}}else n=yc().MiddleTier.baseServiceUrl+yc().MiddleTier.policyUrlSuffix,r={id:this._localParticipant};const s=this.getAcsMiddletierServiceRequestHeader();try{let e=await this._httpRequestHelper.sendRequestWithRetry("post",n,r,{headers:s},yc().MiddleTier.maxRetry);this._policySettingData=e?.data;const t=+new Date;this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_policy,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:t-a},additionalDetails:{phrase:"Teams user policy was fetched successfully from ACS MiddleTier Service",code:0,subCode:220004}})}catch(e){const t=+new Date,i=function(e,t){return new b({defaultError:{message:e?.response?.data?.operationFailure?.phrase||t.message,code:e?.response?.data?.operationFailure?.code||t.code,subCode:e?.response?.data?.operationFailure?.subCode||t.subCode,resultCategories:e?.response?.data?.operationFailure?.resultCategories||t.resultCategories},originalError:e})}(e,f.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(i.message),this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_policy,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-a},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...xg(i)}}),i}}isEvEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userProperties;return e?.evEnabled||!1}isMoHEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy,t=e?.musicOnHoldEnabledType;return this._logger.info("Checking Music on Hold Policy, Enabled Type is: "+t),t===(kp.Enabled||kp.UserOverride)}getTeamsUserCaptionsPoliciesData(){const e=+new Date;let t="";this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_user_policies_for_captions,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:""});let i=this._policySettingData.userAggregatedPolicySettingData,n=i?.userPolicies,r=i?.userProperties;if(!n?.teamsCallingPolicy){const t=+new Date,i=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_user_policies_for_captions,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...xg(i)}})}if(!n?.teamsMeetingPolicy){const t=+new Date,i=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_user_policies_for_captions,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...xg(i)}})}if(!r?.featureTypes){const t=+new Date,i=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_user_policies_for_captions,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:t-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...xg(i)}})}if(n?.teamsCallingPolicy||n?.teamsMeetingPolicy||r?.featureTypes?.includes(ec.TeamsProMgmt)){t=JSON.stringify({isLiveCaptionsEnabledForCalling:n?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===tc.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:n?.teamsMeetingPolicy?.liveCaptionsEnabledType===tc.DisabledUserOverride,isTeamsProMgmtSkuAvailable:r?.featureTypes?.includes(ec.TeamsProMgmt)??!1});const i=+new Date;this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_fetch_user_policies_for_captions,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{phrase:"Fetching Captions policy from ACS MiddleTier Service response was successful",code:0}}),this._logger.info(`Fetching user's captions policy content = ${t}`)}return t}getEmergencyContent(){const e=+new Date;this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_emergency_content,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.attempt,timestampInfo:"",additionalDetails:""});let t="";try{let i=this._policySettingData.userAggregatedPolicySettingData,n=i?.userPolicies,r=!1,a="";if(n?.locationPolicy?.emergencyNumbers){let e=n.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(e)&&(r=!0,t=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:i?.userProperties.region,locationPolicyTag:n?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:n?.teamsEmergencyCallingPolicy?.policyDocument}),a="LocationPolicy")}if(!r&&n?.teamsEmergencyCallRoutingPolicy){let e=n?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(e)&&(r=!0,t=JSON.stringify({enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:i?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:n?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:n?.teamsEmergencyCallingPolicy?.policyDocument}),a="TeamsEmergencyCallingRoutingPolicy")}const s=r?`Created Emergency policy using ${a}`:"This is NOT an emergency call",o=+new Date;return this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_emergency_content,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:o-e},additionalDetails:{phrase:"Deriving Emergency policy from ACS MiddleTier Service response was successful",code:0,subCode:220005}}),this._logger.info(`Deriving emergency policy message = ${s}. Emergency Content = ${t}`),t}catch(t){const i=+new Date,n=new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:Jh.acs_calling_middletier_gateway_emergency_content,callId:this._callId,localParticipantId:this._participantId,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...xg(n)}}),n}}isFetchUserPoliciesAndSettingsApplicable(e,t){return gc(e)||gc(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}isPhoneNumberInLocationPolicy(e){if(!gc(e))for(let t of e)if(t.dialString===this._userDialedPstnNumber||!gc(t.dialMask?.split(";").find((e=>e===this._userDialedPstnNumber))))return this._emergencyNumber=t.dialString,!0;return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e){if(!gc(e))for(let t of e)if(t.emergencyDialString===this._userDialedPstnNumber||!gc(t.emergencyDialMask?.split(";").find((e=>e===this._userDialedPstnNumber))))return this._emergencyNumber=t.emergencyDialString,!0;return!1}verifyFetchUserPoliciesSettings(e,t){let i=yc().MiddleTier;return i.enabled?i.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!n.isPhoneNumberIdentifier(t[0]))?(this._logger.info("Target particpant (Callee) is not a PSTN Number"),!1):Array.isArray(t)||n.isPhoneNumberIdentifier(t)?(this._logger.info("Teams user is eligible to fetch policies and settings from MiddleTier Service "),!0):(this._logger.info("Target particpant (Callee) is not a PSTN Number"),!1):(this._logger.info("Originator (Caller) is not a Teams User"),!1):(this._logger.info("ACS MiddleTier Policy API is disabled"),i.userPolicySettingsApi):(this._logger.info("ACS MiddleTier service is disabled"),i.enabled)}isSecurityDeskEnabled(){let e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(gc(e?.notificationGroup)&&gc(e?.notificationDialOutNumber)||0==e?.notificationGroup?.trim().length&&0==e?.notificationDialOutNumber?.trim().length)}getAcsMiddletierServiceRequestHeader(){return{"Content-Type":"application/json","X-Skypetoken":this._skypeToken||"","Access-Control-Allow-Origin":"*","X-Microsoft-Skype-Chain-ID":this._callId}}getAcsMiddletierServiceRequestHeaderForThreadApi(){let e={};return e=this.getAcsMiddletierServiceRequestHeader(),e.onbehalfOfUser=this._localParticipant,e}sendMiddleTierPolicyEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this._logger.debug("Unable to send AcsMiddleTierPolicyService telemetry")}}sendMiddleTierApiEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this._logger.debug("Unable to send MiddleTier Api telemetry")}}}var P_,M_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},k_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let D_=1;class O_{get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,i,n,r,a,s){this._callClient=e,this._disposed=!1,this.tokenProvider=async e=>{if(this._parsedTokenCredential.exp<Date.now()&&!e)throw this.updateConnectionState("tokenExpired"),new b({defaultError:f.CALL_AGENT.ACCESSTOKEN_EXPIRED});if(!this._communicationTokenCredential)throw new b({defaultError:f.CALL_AGENT.GET_TOKEN_BEFORE_INIT});const t=await Fc(this._communicationTokenCredential,yc().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal});return t.acsResourceId===this._parsedTokenCredential?.acsResourceId&&t.identityMri===this._parsedTokenCredential?.identityMri||Dc(f.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.sendTokenExpiredEvent(),this.updateConnectionState("tokenExpired"),this._disposed||await this.dispose(),Dc(f.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger)),t.jwtToken},this.sendTokenChangedEvent=(e,t)=>{try{this._telemetryLogManager.sendEvent({name:t?Jh.acs_calling_token_expiration_changed:Jh.acs_calling_token_expiration_changed_failure,tenant:hl,properties:{deltaTimeInMs:e}})}catch(e){this.logger.debug("Unable to send token change telemetry")}},this.sendTokenExpiredEvent=()=>{try{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_token_expired,tenant:hl})}catch(e){this.logger.debug("Unable to send token expired telemetry")}},this.logger=t.createChild("CallAgent"+D_++),this._telemetryLogManager=n,this._kind=a,this._connectionState="Connected",this._eventEmitter=new wm(this.logger),this.clientId=i,this._abortController=new AbortController,this._maxDisplayNameLength=yc()?.calling?.maxDisplayNameLength||256,this._previousTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=yc()?.calling?.maxNumberOfTokenFetchRetries||10,this._callStack=r,this.acsProxy=this._callClient.acsProxy,this.acsCustomRelayManager=this._callClient.acsCustomRelayManager,this._httpRequestHelper=new E_(this.logger,this.acsProxy),this.mtPolicyService=new A_(this._httpRequestHelper),this._parsedTokenCredential={jwtToken:"",acsResourceId:void 0,identityMri:"",cloudType:qo.Public,isCte:!1,region:"",rgnClaimExists:!1,exp:0},this._caConfigBag={clientId:"",acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isCte?il.Enterprise:il.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1},this.deviceManager=s,this._extensibleApi=new vg(this.logger,{callClient:this._callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});const o=pC(Yp.CallAgentFeature);for(const e of o)"OnExtendedObjectConstructor"===e.activationOptions.activationEvent&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState("trouterChanged")},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState("registrarChanged")}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():"Unknown"}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||""}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||""}getUserPolicy(){return this._userPolicies}async initialize(t,i,n){const r=+new Date;try{if(this.sendCallAgentInitializiedEvent(Jh.acs_calling_call_agent_init_attempt,{attemptTimestamp:r}),this._communicationTokenCredential=t,this._parsedTokenCredential=await Fc(t,yc().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==e.CallAgentKind.TeamsCallAgent||this._parsedTokenCredential.isCte?this._kind===e.CallAgentKind.CallAgent&&this._parsedTokenCredential.isCte&&Dc(f.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):Dc(f.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),n?.displayName){if(this._parsedTokenCredential.isCte)throw new b({defaultError:f.CALL_AGENT.CTE_DISPLAY_NAME});if(n?.displayName.length>this._maxDisplayNameLength)throw new b({defaultError:f.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===qo.Public&&(!this._parsedTokenCredential.region||""===this._parsedTokenCredential.region)){try{const e=+new Date-r;this._telemetryLogManager.sendEvent({name:Jh.acs_calling_token_has_no_data_location,tenant:hl,properties:{deltaTimeInMs:e}})}catch(e){this.logger.debug("Unable to send token has no data location assigned")}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?rl[0]:nl[0],this.logger.info("Used default data location because token has no data location assigned")}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isCte?il.Enterprise:il.Consumer,emergencyCountryCode:n?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!n?.emergencyCallOptions?.countryCode},this.addToCallAgentsMap(this._parsedTokenCredential),this.onDisposedCallback=i;const a=this._communicationTokenCredential.getToken;this._disposed=!1;const s=async e=>{const t=+new Date;try{const i=await a.apply(this._communicationTokenCredential,[e]),n=+new Date;return i.expiresOnTimestamp!==this._previousTokenExpiration&&(this.sendTokenChangedEvent(n-t,!0),this._previousTokenExpiration=i.expiresOnTimestamp),i}catch(e){const i=+new Date;this._previousTokenExpiration=0,this.sendTokenChangedEvent(i-t,!1),Dc(f.CALL_AGENT.FAILED_TO_GET_TOKEN,this.logger)}};t.getToken=s;try{this.runningEnvironmentInfo=await this._callClient.getEnvironmentInfoInternal()}catch(e){this.logger.debug("Unable to get the running environment info")}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(t)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||""}`)}this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,n),this.registerConnectionStateEventHandlers();const o=+new Date;this.sendCallAgentInitializiedEvent(Jh.acs_calling_call_agent_init_success,{deltaTimeInMs:o-r})}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);const t=new b({defaultError:f.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);const i=+new Date;throw this.sendCallAgentInitializiedEvent(Jh.acs_calling_call_agent_init_failure,{deltaTimeInMs:i-r},t),this._telemetryLogManager.clearTelemetryLoggers(),t}}isCteUser(){return void 0!==this._parsedTokenCredential?.isCte&&this._parsedTokenCredential?.isCte}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}createTransferTargetCall(e){const t=m.generateCauseId(),i=x(),n=x(),r=this._tsCallRegistry.createCall("",i,n,void 0,t),a=this.createNewCall(i,r);return this.addToCallArray(a),this.handleCallState(a),r.addParticipant(e.targetMri).catch((()=>{this.logger.error("Failed to add participant for transer call")})),a.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[a],removed:[]}),a}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){const t=x(),i=+new Date;let n;try{if(this.sendHandlePushNotificationEvent({eventName:Jh.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:"",localParticipantId:"",kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),!e.incomingCallContext)throw new b({defaultError:f.CALL_AGENT.INVALID_PUSH_NOTIFICAITON_DATA});n=new R_(e,this._tsCallRegistry,this.logger),await n.process(),this.sendHandlePushNotificationEvent({eventName:Jh.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:n.callId,localParticipantId:n.localParticipantId,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:""})}catch(e){const r=new b({defaultError:f.CALL_AGENT.PUSH_NOTIFICAITON_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:Jh.acs_calling_handle_push_notification,correlationId:t,featureName:"handlePushNotification",operationName:"handleIncomingCallPushNotification",callId:n?.callId||"",localParticipantId:n?.localParticipantId||"",kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{failureReason:r.message,code:r.code,...xg(r)}}),r}}getDeviceType(){const e=this._callClient?.firstPartyOptions?.acsDeviceType;return e?ql[e]:"default"}trackCallEndTimeToStopTelemetry(e){0===e.length?rp.callEndTimestamp=Date.now():rp.callEndTimestamp=Number.MAX_SAFE_INTEGER}updateConnectionState(e){const t=this.getCallAgentConnectionState(),i=this.getTrouterState(),n=this._callStack?.isRegistered()?"Connected":"Disconnected",r="Connected"===t?void 0:"tokenExpired"==e?"tokenExpired":"signalingIssue";if(t!==this._connectionState||r!==this._connectionStateReason){this.sendCallAgentInfoEvent({eventName:Jh.acs_calling_call_agent,additionalDetails:{step:"connectionState-changed",oldState:this._connectionState,newState:t,trouterState:i,registrarState:n,reason:r}});const e={oldValue:this._connectionState,newValue:t,reason:r};this._connectionState=t,this._connectionStateReason=r,this._eventEmitter.emit("connectionStateChanged",e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{...e.additionalDetails}})}catch(e){this.logger.debug("Failed to send connection state changed event",e)}}sendCallAgentInitializiedEvent(e,t,i){try{let n="string"==typeof i?.message?i?.message:void 0;e!==Jh.acs_calling_call_agent_init_failure&&(n=void 0);let r=i?xg(i):void 0;this._telemetryLogManager.sendEvent({name:e,tenant:hl,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:n,additionalInformation:{trouterState:this.getTrouterState()},additionalDetails:{...r}}})}catch(e){this.logger.debug("Unable to send telemtery")}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send handle push notification telemetry")}}async initializeCallRegistry(e,t){let i=t?.displayName;const n=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,i);return this.logger.info(`registry created for version number=${uc()}`),n}async getCallRegistry(e,t,i,n){const r={id:t.identityMri,displayName:n||"",tokenProvider:i},a=await e.createCallRegistry(r);await a.login(r);const s=yc()?.tsCalling?.accountConfiguration?.ring||void 0,o=t.isCte?il.Enterprise:il.Consumer,l=t.acsResourceId,c=t.region;let d={acsResourceId:l,clientType:o,ring:s};yc().calling.setDeviceType&&(d.deviceType=this.getDeviceType());const u=yc().calling.eudb;return u.isEnabled&&u.sendRegionToNgc&&(u.isRgnClaimEnabledForACS||t.isCte)&&(d={...d,region:c}),yc()?.calling.supportLiveStreaming&&(d.clientSupportsUms=!0),a.setConfiguration(d),a.on("callAdded",this.handleCallAdded),a.on("callRemoved",this.handleCallRemoved),n&&a.updateDisplayName(n),a}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await Fc(e,yc().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&"Connected"===this.getTrouterState()?"Connected":this._callStack?.isRegistered()||"Disconnected"!==this.getTrouterState()?"Connecting":"Disconnected"}}M_([bf,k_("design:type",Object)],O_.prototype,"logger",void 0),M_([M(pp.Initialize),k_("design:type",Function),k_("design:paramtypes",[Object,Function,Object]),k_("design:returntype",Promise)],O_.prototype,"initialize",null),M_([P(pp.Feature),k_("design:type",Function),k_("design:paramtypes",[Object]),k_("design:returntype","function"==typeof(P_="undefined"!=typeof TFeature&&TFeature)?P_:Object)],O_.prototype,"feature",null),M_([M(pp.HandlePushNotification),k_("design:type",Function),k_("design:paramtypes",[Object]),k_("design:returntype",Promise)],O_.prototype,"handlePushNotification",null);var N_=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},L_=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const x_=new Map;class F_ extends O_{get calls(){return this._calls}constructor(t,i,n,r,a,s,o){super(t,i,r,a,n,e.CallAgentKind.CallAgent,s),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);const t=this._calls.find((t=>t.id===e.callId));if(t){const e=this._calls.indexOf(t);-1!==e&&this._calls.splice(e,1),t.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls),this._eventEmitter.emit("callsUpdated",{added:[],removed:[t]}),this.logger.info("call removed")}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){const t=e.on("callStateChanged",(()=>{if(1===e.state){const i=e.callId;t.dispose();const n=new v_({callId:i,isIncoming:!0},this,e,this._telemetryLogManager),r=new __(n);this.handleCallState(n),n.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:r})}}))}},this.handleCallState=e=>{e.on("stateChanged",(()=>{try{"Disconnected"===e.state?this.tsStack?(this._tsCallRegistry.deleteCall(e.tsCall)||this.logger.error(`Failed to remove call from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry"):"Connecting"===e.state&&"Incoming"==e.direction&&(this.addToCallArray(e),this._eventEmitter.emit("callsUpdated",{added:[e],removed:[]}))}catch(e){this.logger.error("Failed to handle call state changed event")}}))},this.displayName=o?.displayName}addToCallAgentsMap(e){x_.get(e?.identityMri)&&Dc(f.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),x_.set(e?.identityMri,this)}removeFromCallAgentsMap(e){e?.identityMri&&x_.get(e?.identityMri)===this&&x_.delete(e?.identityMri)}async getExistingCallAgentWithToken(e){try{const t=await Fc(e,yc().calling.eudb.isRgnClaimEnabledForACS);return x_.get(t.identityMri)}catch(e){throw new b({defaultError:f.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){return new v_({callId:e},this,t,this._telemetryLogManager)}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}startCall(e,t){if(this.assertCallUserIds(e),t?.alternateCallerId&&oc(t.alternateCallerId),e.find((e=>rc(e)===this.getUserMri())))throw new b({defaultError:f.CALL_AGENT.CANT_CALL_YOURSELF});let i=t?.audioOptions?.muted;return void 0===i&&(i=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${i}`),this.createCall({participants:e,startCallOptions:t})}join(e,t){if(!$c(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let i=t?.audioOptions?.muted;return void 0===i&&(i=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${i}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){if(this._disposed)throw new b({defaultError:f.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&x_.delete(this._parsedTokenCredential?.identityMri);try{const e=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(e))}catch(e){this.logger.error("Call Agent failed to dispose to Call Stack")}this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),delete this._callStack,this._telemetryLogManager.clearTelemetryLoggers(),this.onDisposedCallback&&this.onDisposedCallback()}on(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new b({defaultError:f.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new b({defaultError:f.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&"meshV2"!==this.getDeviceType())throw new b({defaultError:f.CALL_AGENT.MESH_DEVICETYPE_V2});let t,i,n,r,a=e?.callContext?.threadId||e?.startCallOptions?.threadId,s=e?.callContext?.groupId;const o=e?.callContext?.roomId,l=e?.callContext?.meetingLink,c=e?.callContext?.meetingId,d=e?.callContext?.passcode||"";if(s&&s.startsWith("19:")&&(a=s,s=""),l&&(yc().calling.tfl.isEnabled&&this.isTflMeetingLink(l.trim().toLocaleLowerCase())?n=function(e){try{const t=new URL(e),i=t.pathname.split("/"),n=decodeURIComponent(i[2]);return{meetingUrl:decodeURIComponent(e),meetingCode:n,passcode:t.searchParams.get("p")??void 0}}catch(e){throw new b({defaultError:f.CALL_AGENT.INVALID_TFL_MEETING_LINK,originalError:e})}}(l):i=Op(l)),e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(i={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():"0",organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),i&&(r={meetingType:"0"===i.messageId?1:2,tenantId:i.tenantId,organizerId:i.organizerId,replyChainMessageId:i.messageId}||void 0,a=i.threadId,t=i.messageId),this.tsStack){const i=m.generateCauseId(),l=x(),u=x();let h,p=!1;s?h=this._tsCallRegistry.createCallWithGroupId(s,l,u,i):c?h=this._tsCallRegistry.createCallWithMeetingData({meetingCode:c,passcode:d,threadId:a},l,u,i):o?h=this._tsCallRegistry.createCallWithMeetingData({meetingCode:o},l,u,i):n?h=this._tsCallRegistry.createCallWithMeetingData(n,l,u,i):(p=!!e?.participants&&e.participants.length>=2&&Gc(e.participants),yc().calling.enableSmePassFakeConversation&&!a&&p&&(a=`${E}${x()}`),h=this._tsCallRegistry.createCall(a||"",l,u,t,i));const g=new v_({callId:l,roomId:o},this,h,this._telemetryLogManager,p);this.addToCallArray(g),this.handleCallState(g);const f={threadId:a||"",messageId:t||"",meetingInfo:r,mediaPeerType:2};return e?.participants&&e?.participants.forEach((e=>{h.addParticipant(rc(e)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),g.startCallInternal(e?.startCallOptions,!!c||!!o,e?.callContext,f).catch(Oc),g.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[g],removed:[]}),g}throw new b({defaultError:f.CALL_AGENT.STACK_NOT_INIT})}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new b({defaultError:f.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isTflMeetingLink(e){return yc().calling.tfl.hosts.some((t=>e.includes(t.trim().toLocaleLowerCase())))}assertCallUserIds(e){Mc(e,f.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Pc(e,f.CALL_AGENT.USERIDS_CANNOT_BE_NULL),function(e){if(!(e instanceof Array))throw new b({defaultError:f.IDENTIFIER.INVALID_IDENTIFIER_ARRAY})}(e),e.forEach((e=>{const t=oc(e);if(!$c(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}}N_([P(pp.StartCall),L_("design:type",Function),L_("design:paramtypes",[Array,Object]),L_("design:returntype",Object)],F_.prototype,"startCall",null),N_([P(pp.Join),L_("design:type",Function),L_("design:paramtypes",[Object,Object]),L_("design:returntype",Object)],F_.prototype,"join",null),N_([M(pp.Dispose),L_("design:type",Function),L_("design:paramtypes",[]),L_("design:returntype",Promise)],F_.prototype,"dispose",null);class U_{constructor(e,t,i){this._configIds={AcsCallingSDKWeb:"",SkypeWebMedia:""},this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((i=>{void 0!==e[i]&&(t[i]=e[i])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=i;const n=yc().calling.applicationSettingsUrls;this._trouterSettings={version:`3617/${dc()}`,productName:"AcsWeb",trouterServiceUrl:n.Public_TrouterServiceUrl,registrarServiceUrl:n.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:"AcsWeb",pnhTemplate:"AcsWeb_2.0",environment:"Prod",platform:bC()},this._JsCsaConfig={languageCode:"en",emergencyCallCountry:"",autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:i.proxyfyUrl(n.Public_ConversationServiceUrl),useInternalHttpDispatcher:!i.hasProxyUrl(),supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1},this._JamaSettingsMobile={webrtcCameraOpenFs:900,webrtcMultipartyMaxScalingFs:900,webrtcMaxScalingFs:900},this._JamaSettings={debug:!1,numVideoChannelsGvc:6,webcv:null},this._MDNTrapSettings={Service:{url:i.proxyfyUrl(n.Public_MdnTrapServiceUrl),tokenUrl:i.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[n.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[n.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:n.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}}}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){const e=RC();let t=this._JamaSettings;return"Mobile"==e.formFactor&&(t={...t,...this._JamaSettingsMobile}),t}getClientInformation(){const e=yc().telemetry.reportSdkUaToService,t=yc().telemetry.reportEnvToService;return`ACSWeb(3617/${dc()})`+(t?`/${function(){const e=RC();return`os=${AC()}; osVer=${PC()}; browser=${e.name}; browserVer=${e.version}; formFactor=${e.formFactor};`}()}`:"")+(e?`/(${this.sdkDiagnosticInformation})`:"")}getJsCsaConfig(){return{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info("Update ECS settings");const i=yc().calling.applicationSettingsUrls,n=yc().calling.applicationSettingsEudbUrls,r=e&&Lc(e.identityType,e.region);if(e?.identityType==il.Enterprise)r?(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=i.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case qo.Public:r&&(this._trouterSettings.trouterServiceUrl=n.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Public_MdnTrapRelayTurnUrl_EUDB);break;case qo.GccHigh:this._trouterSettings.trouterServiceUrl=i.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.GccHigh_RegistrarServiceUrl);break;case qo.Dod:this._trouterSettings.trouterServiceUrl=i.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.Dod_RegistrarServiceUrl);break;case qo.AirGap08:this._trouterSettings.trouterServiceUrl=i.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap08_RegistrarServiceUrl);break;case qo.AirGap09:this._trouterSettings.trouterServiceUrl=i.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap09_RegistrarServiceUrl)}if(t)this._configIds={AcsCallingSDKWeb:t?.ConfigIDs?.AcsCallingSDKWeb||"",SkypeWebMedia:t?.ConfigIDs?.SkypeWebMedia||""},this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===il.Enterprise)r?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case qo.Public:r&&(this._trouterSettings.trouterServiceUrl=n.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=n.Public_MdnTrapRelayTurnUrl_EUDB);break;case qo.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.GccHigh_MdnTrapRelayTurnUrl;break;case qo.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(i.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(i.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[i.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[i.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=i.Dod_MdnTrapRelayTurnUrl;break;case qo.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap08_ConversationServiceUrl);break;case qo.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(i.AirGap09_ConversationServiceUrl)}}getConfigIds(){return this._configIds}assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push("SkypeCalling"),e?.MDN_TRAP||t.push("MDN_TRAP"),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push("SkypeWebMedia.mediaAgent"):t.push("SkypeWebMedia"),e?.TrouterJScriptClient||t.push("TrouterJScriptClient"),t.length>0){const e=new b({defaultError:f.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(", ")]});throw this._logger.error(e.message),e}}}var B_,V_=s((function(e,t){var i;i=function(){return function(e){function t(n){if(i[n])return i[n].exports;var r=i[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var i={};return t.m=e,t.c=i,t.i=function(e){return e},t.d=function(e,i,n){t.o(e,i)||Object.defineProperty(e,i,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var i=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(i,"a",i),i},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=1)}([function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var i,n=new Promise((function(t,n){fetch(e).then((function(e){void 0!==i&&clearTimeout(i),t(e)})).catch((function(e){void 0!==i&&clearTimeout(i),n(e)}))}));if(0!==t){var r=new Promise((function(n,r){i=setTimeout(r,t,new Error("Fetch for '".concat(e.url,"' timed out")))}));return Promise.race([n,r])}return n},t.toJson=function(e){try{return JSON.stringify(e)}catch(t){return"Unable to serialize object of type ".concat(typeof e)}};var n=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}();t.Timespan=n},function(e,t,i){var n,r=this&&this.__extends||(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)},s=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var l=i(0),c=["skype","aad","cae"],d=function(e){function t(t){var i=e.call(this,t)||this;return i.name="CancelationError",i}return r(t,e),t}(Error),u=function(){function e(t,i,n){this.logger=t,this.maxBackoffInMs=i,this.initialDelay=n,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(void 0!==this.timerHandle)throw new Error("Retry sequence logical failure");if(-1===this.backoffCount)return new Promise((function(e,t){t(new d("Cancelled"))}));var i=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info("[RegistrarClient] Backing off ".concat(e," for ").concat(i," milliseconds with ID ").concat(this.id)),new Promise((function(n,r){t.cancelFunc=r,t.timerHandle=setTimeout((function(){t.logger.info("[RegistrarClient] Back off for ".concat(e," with ID ").concat(t.id," complete")),t.timerHandle=void 0,n()}),i)}))},e.prototype.cancel=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off"),clearTimeout(this.timerHandle),void 0!==this.cancelFunc&&this.cancelFunc(new d("Cancelled"))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*Math.pow(2,this.backoffCount)*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),h=function(){function e(e,t,i){var n;this.logger=e,this.tokenProvider=t,this.options=i,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=void 0===i.maxRetriesForGetToken||null===i.maxRetriesForGetToken?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:i.maxRetriesForGetToken,this.proxyUrlRewrite=null!==(n=i.proxyUrlRewrite)&&void 0!==n?n:function(e){return e}}return e.prototype.setTelemetryLogger=function(e){this.eventLogger=e},e.prototype.register=function(e,t){return s(this,void 0,void 0,(function(){return o(this,(function(i){switch(i.label){case 0:return[4,this.performRegistration(e,t,"pr_set_registration")];case 1:return i.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return s(this,void 0,void 0,(function(){var e;return o(this,(function(t){switch(t.label){case 0:return this.logger.info("[RegistrarClient] sending unregister request"),e=new Request(this.proxyUrlRewrite("".concat(this.options.registrarUrl,"/").concat(this.options.registrationId)),{method:"DELETE",mode:"cors",headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{accept:"application/json, text/javascript"}))}),[4,this.callRegistrar(e,"pr_delete_registration")];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return s(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:if(!this.cachedRegistrationParams)throw new Error("Re-registration failed because there is no registration parameters cached");return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1],"pr_resend_registration")];case 1:return e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t,i){return s(this,void 0,void 0,(function(){var n,r;return o(this,(function(s){switch(s.label){case 0:return this.logger.info("[RegistrarClient] Sending register request"),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:"",transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:"POST",mode:"cors",headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{"content-type":"application/json",accept:"application/json, text/javascript"})),body:(0,l.toJson)(n)}),[4,this.callRegistrar(r,i)];case 1:return s.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new u(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return s(this,void 0,void 0,(function(){var t,i,n,r,a,s,l;return o(this,(function(o){switch(o.label){case 0:t=this.startBackoff(),i=0,o.label=1;case 1:return o.trys.push([1,3,,8]),this.logger.info("[RegistrarClient] Asking for a new token"),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:c,wwwAuthenticateHeader:e,purpose:"registrar"})];case 2:return n=o.sent(),this.stopBackoff(t),[2,n];case 3:r=o.sent(),o.label=4;case 4:return o.trys.push([4,6,,7]),i++,a=JSON.stringify(r),i>this.maxRetriesForGetToken?(s="[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ".concat(a),this.logger.error(s),this.stopBackoff(t),[2,Promise.reject(s)]):(this.logger.warn("[RegistrarClient] Retrying for a new token. Retry Count: ".concat(i," Error: ").concat(a)),[4,t.delay("Fetching a new token")]);case 5:return o.sent(),[3,8];case 6:throw l=o.sent(),this.stopBackoff(t),l;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e,t){var i,n,r;return s(this,void 0,void 0,(function(){var a,s,d,u,h,p,g,m,f,v,S,y,C,_,E,T;return o(this,(function(o){switch(o.label){case 0:return a=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:c,wwwAuthenticateHeader:void 0,purpose:"registrar"})];case 1:s=o.sent(),this.setTokenHeader(e,s),d=new l.Timespan,u=0,o.label=2;case 2:h=void 0,o.label=3;case 3:return o.trys.push([3,10,15,16]),p=e.clone(),[4,(0,l.fetchWithTimeout)(p,this.options.requestTimeoutMs)];case 4:return 401!==(h=o.sent()).status?[3,8]:++u>this.maxRetriesForGetToken?(g="[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText),this.logger.error(g),this.stopBackoff(a),[2,Promise.reject(g)]):(this.logger.warn("[RegistrarClient] Retry Count ".concat(u,". Request '").concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText)),m=null!==(n=null===(i=h.headers)||void 0===i?void 0:i.get("www-authenticate"))&&void 0!==n?n:void 0,f=this.setTokenHeader,v=[e],[4,this.getToken(m)]);case 5:return f.apply(this,v.concat([o.sent()])),u>1?[4,a.delay("Registrar call retry after 401")]:[3,7];case 6:o.sent(),o.label=7;case 7:return[3,22];case 8:if(h.status>=500&&h.status<600)throw new Error("Fetch for '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText));o.label=9;case 9:return[3,16];case 10:S=o.sent(),this.logger.error("[RegistrarClient] Request failed with ".concat(S)),o.label=11;case 11:return o.trys.push([11,13,,14]),[4,a.delay("Registrar call retry")];case 12:return o.sent(),[3,22];case 13:throw y=o.sent(),this.logger.error("[RegistrarClient] Request cancelled"),this.stopBackoff(a),y;case 14:return[3,16];case 15:return this.sendTelemetryEvent(t,e,h,d),[7];case 16:return this.stopBackoff(a),h.ok?[2,h]:[3,17];case 17:C=void 0,o.label=18;case 18:return o.trys.push([18,20,,21]),E=(_=JSON).stringify,[4,h.json()];case 19:return C=E.apply(_,[o.sent()]),[3,21];case 20:return o.sent(),C="no details",[3,21];case 21:throw T="Fetch for '".concat(e.url,"' failed with ").concat(h.status," ").concat(h.statusText," (").concat(C,", MS-CV: ").concat(null===(r=h.headers)||void 0===r?void 0:r.get("MS-CV"),")"),this.logger.error("[RegistrarClient] ".concat(T)),new Error(T);case 22:return[3,2];case 23:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete("X-Skypetoken"),e.headers.delete("Authorization"),e.headers.delete("X-MS-Migration"),t.tokenType.toLowerCase()){case"skype":e.headers.set("X-Skypetoken",t.token);break;case"aad":case"cae":e.headers.set("Authorization","Bearer ".concat(t.token));break;default:throw new Error("unsupported token type: ".concat(t.tokenType))}!1===this.options.usingLegacyTokenApi&&e.headers.set("X-MS-Migration","True")},e.prototype.sendTelemetryEvent=function(e,t,i,n){if(void 0!==this.eventLogger){var r={name:e,properties:{url:{value:t.url},result_code:{value:void 0!==i?i.status:0},begin_timestamp:{value:n.startTime},elapsed:{value:n.duration}}};this.eventLogger.logEvent(r)}},e}();t.RegistrarClient=h,t.createRegistrarClient=function(e,t,i){return new h(e,t,i)}}])},e.exports=i()})),H_=s((function(e,t){var i;i=function(e){return function(e){function t(n){if(i[n])return i[n].exports;var r=i[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var i={};return t.m=e,t.c=i,t.i=function(e){return e},t.d=function(e,i,n){t.o(e,i)||Object.defineProperty(e,i,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var i=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(i,"a",i),i},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=20)}([function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0;var n=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug("[".concat(this.name,"] ").concat(e))},e.prototype.info=function(e){this.logger.info("[".concat(this.name,"] ").concat(e))},e.prototype.warn=function(e){this.logger.warn("[".concat(this.name,"] ").concat(e))},e.prototype.error=function(e){this.logger.error("[".concat(this.name,"] ").concat(e))},e}();t.Logger=n},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.constants={TROUTER_INIT:"trouterinit",TROUTER_READY_EVENT:"trouterReadyEvent",TROUTER_READY_TIMEOUT:"trouterReadyTimeout",TROUTER_TOKEN_REQUEST:"trouterTokenRequest",TROUTER_TOKEN_GET_SUCCEEDED:"trouterTokenGetSucceeded",TROUTER_TOKEN_GET_FAILED:"trouterTokenGetFailed",TROUTER_RECONNECTING:"trouterReconnecting",RENEWAL:"renewal",NEW_CONNECTION:"newConnection",ENDPOINT_REGISTRATION_FAILED:"endpointRegistrationFailed"},t.CLIENT_VERSION="2024.14.01.7",t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=["skype","aad","cae"],t.USER_AUTHENTICATE_EVENT_NAME="user.authenticate"},function(e,t,i){var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]="Unknown",e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"}(n||(t.UserActivityState=n={})),function(e){e[e.Unknown=0]="Unknown",e[e.Connected=2]="Connected",e[e.Disconnected=3]="Disconnected",e[e.Switching=9]="Switching"}(r||(t.TrouterState=r={}))},function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=t.fetchWithTimeout=t.calculateExpireTsInSec=t.calculateTtlInSec=t.toJson=void 0,t.toJson=function(e){try{return JSON.stringify(e)}catch(t){return"Unable to serialize object of type ".concat(typeof e)}},t.calculateTtlInSec=function(e){var t=Math.round((new Date).getTime()/1e3);return void 0!==e&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round((new Date).getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return n(this,void 0,void 0,(function(){var i,n,a;return r(this,(function(r){return n=new Promise((function(t,n){fetch(e).then((function(e){clearTimeout(i),t(e)})).catch((function(e){clearTimeout(i),n(e)}))})),0!==t?(a=new Promise((function(n,r){var a=new URL(e.url),s=new Error("".concat(e.method," ").concat(a.origin).concat(a.pathname," timed out"));i=setTimeout(r,t,s)})),[2,Promise.race([n,a])]):[2,n]}))}))};var a=function(){function e(e){this.base=void 0!==e?e:this.createCorrelationVectorBase(),this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return"".concat(this.base,".").concat(this.extension)},e.prototype.createCorrelationVectorBase=function(){for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+",t="AQgw",i="",n=0;n<21;n++)i+=e.charAt(Math.floor(64*Math.random()));return i+t.charAt(Math.floor(4*Math.random()))},e}();t.CorrelationVector=a;var s=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}();t.Timespan=s},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var n,r,a=i(3),s=function(){function e(e,t,i,n,r,a,s){this.connectionId=e,this.connectedClientId=t,this.domId=i,this.unsecureUrl=n,this.url=r,this.c2cUrlBase=a,this.expirationTsSec=s}return e.prototype.getRemainingTtlInSec=function(){return(0,a.calculateTtlInSec)(this.expirationTsSec)},e}();t.ServerState=s,function(e){e[e.Unknown=0]="Unknown",e[e.Modified=1]="Modified",e[e.Snapshot=2]="Snapshot",e[e.Connected=3]="Connected"}(n||(t.UserActivityEventReason=n={})),function(e){e[e.Unknown=0]="Unknown",e[e.Connected=2]="Connected",e[e.Disconnected=3]="Disconnected",e[e.Switching=9]="Switching",e[e.TerminalError=10]="TerminalError"}(r||(t.TrouterManagerState=r={}))},function(e,t,i){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.redirectUrlIfPresent=t.ensureNumber=t.reconnectParamsWithoutUrls=t.adaptUrl=t.isV4ConnectEvent=t.usedProtocolAfterFallback=t.usedProtocol=void 0,t.usedProtocol=function(e,t){return"skype"===e&&"1"!==function(e){return"string"==typeof e?e:"number"==typeof e?e.toString():void 0}(null==t?void 0:t.scae)?"v4a":"v4c"},t.usedProtocolAfterFallback=function(e,t){return"v4c-websocket-failure"===(null==t?void 0:t.kind)?"v4a":e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,"connectparams")},t.adaptUrl=function(e,t){return"v4a"===t?e.replace(/\/v4\/c\b/,"/v4/a").replace("wss://","https://").replace("ws://","http://"):e.replace(/\/v4\/a\b/,"/v4/c").replace("https://","wss://").replace("http://","ws://")},t.reconnectParamsWithoutUrls=function(e){if(void 0!==e)return n(n({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return"string"==typeof e?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if("redirect"===(null==e?void 0:e.kind)&&void 0!==e.host){var t=e.host;return t.endsWith("/")&&(t=t.substring(0,t.length-1)),t.endsWith("/v4/c")||t.endsWith("/v4/a")||(t+="/v4/c"),t}}},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var n,r,a=i(4),s=i(0),o=i(5);!function(e){e[e.Initial=0]="Initial",e[e.RetrievingToken=1]="RetrievingToken",e[e.Allocating=2]="Allocating",e[e.Handshaking=3]="Handshaking",e[e.Connecting=4]="Connecting",e[e.AnonymousConnecting=5]="AnonymousConnecting",e[e.WebsocketAuthenticating=6]="WebsocketAuthenticating",e[e.Connected=7]="Connected",e[e.Unregistering=8]="Unregistering",e[e.TerminalError=9]="TerminalError"}(n||(t.State=n={})),function(e){e[e.Initial=0]="Initial",e[e.Registering=1]="Registering",e[e.RegisteringButResendPending=2]="RegisteringButResendPending",e[e.Retrying=3]="Retrying",e[e.Registered=4]="Registered",e[e.RegistrationDisabled=5]="RegistrationDisabled"}(r||(r={}));var l=function(){function e(e,t,i,a){this.worker=t,this.incallModeEnabled=i,this.protocolSelector=a,this.state=n.Initial,this.autoReconnect=!0,this.logger=new s.Logger("ConnectionFsm",e),this.registrationState=r.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===n.Allocating||this.state===n.Connected||this.state===n.Handshaking||this.state===n.Connecting||this.state===n.RetrievingToken||this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===n.Allocating||this.state===n.Handshaking||this.state===n.Connecting||this.state===n.AnonymousConnecting},e.prototype.start=function(){return this.state===n.Initial?(this.setState(n.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored("start"),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=r.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===n.Connected&&this.worker.sendDisconnectTelemetryEvent("connection stopped"),this.registrationState!==r.Registered&&this.registrationState!==r.Registering&&this.registrationState!==r.RegisteringButResendPending||this.state===n.Unregistering?t?(this.setState(n.TerminalError),this.worker.dispatchTerminalError()):(this.setState(n.Initial),this.worker.dispatchDisconnected()):(this.registrationState=r.Initial,this.setState(n.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,i){this.state===n.RetrievingToken?"v4c"===(0,o.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,i),t)?(this.setState(n.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(n.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored("onTokenReceived")},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===n.Allocating&&this.registrationState===r.Registered&&this.worker.dispatchUnregistered(),this.state===n.Allocating?(this.setState(n.Handshaking),this.registrationState=r.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored("onAllocationSucceed"),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===n.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored("onAllocationFailed")},e.prototype.onV4cException=function(){this.state!==n.AnonymousConnecting&&this.state!==n.WebsocketAuthenticating||(this.logger.error("v4c exception, falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}}))},e.prototype.onConnectingTimeout=function(){this.state===n.Allocating||this.state===n.Connecting||this.state===n.Handshaking||this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored("onConnectingTimeout")},e.prototype.onConnecting=function(){this.state===n.Handshaking?this.setState(n.Connecting):this.showIgnored("onConnecting")},e.prototype.onSocketConnect=function(e){this.state===n.AnonymousConnecting?(this.setState(n.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored("onSocketConnect")},e.prototype.onConnectingFailed=function(){this.state===n.Connecting?this.onConnectingTimeout():this.state===n.Handshaking?(this.logger.error("Unexpected error in Socket.io - no valid transports"),this.onConnectingTimeout()):this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?(this.logger.info("/v4/c falling back to longpoll"),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"v4c-websocket-failure"}})):this.showIgnored("onConnectingFailed")},e.prototype.onSocketDisconnect=function(e){this.state===n.Handshaking||this.state===n.Connected||this.state===n.WebsocketAuthenticating?(this.state===n.Connected&&this.worker.sendDisconnectTelemetryEvent(null==e?void 0:e.toTelemetryString()),this.state===n.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),"skypetoken-deprecated"===(null==e?void 0:e.reason)?(this.logger.error("Skypetoken deprecated response, not retrying any further"),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==n.Connected&&"dup"!==(null==e?void 0:e.reason),allowCachedToken:"unauthorized"!==(null==e?void 0:e.reason),claimsChallenge:null==e?void 0:e.claims})):this.showIgnored("onSocketDisconnect")},e.prototype.onTrouterConnected=function(){this.state===n.Connecting||this.state===n.WebsocketAuthenticating?(this.setState(n.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(a.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=r.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=r.Registering,this.worker.sendRegisterRequest())):this.showIgnored("onTrouterConnected")},e.prototype.onReconnectRequired=function(e,t,i){this.state===n.AnonymousConnecting||this.state===n.WebsocketAuthenticating?void 0===i||"host"!==i.target||void 0===i.url||""===i.url?(this.logger.error("unexpected reconnect arguments: ".concat(null==i?void 0:i.target," ").concat(null==i?void 0:i.url,", reconnecting without cache")),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect-no-host"}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:"redirect",host:i.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===n.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored("onDownstreamRequest")},e.prototype.onTrouterMessageLost=function(e){this.state===n.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored("onTrouterMessageLost")},e.prototype.onPingInterval=function(){this.state===n.Connected?this.worker.sendPingRequest():this.showIgnored("onPingInterval")},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse("onPingResponseTimeout")},e.prototype.onPingResponse=function(){this.state===n.Connected||this.showIgnored("onPingResponse")},e.prototype.onRegistrationFailed=function(){this.state===n.Connected&&this.registrationState===r.Registering?(this.worker.dispatchUnregistered(),this.registrationState=r.Retrying,this.worker.startRegistrationRetryTimer()):this.state===n.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationFailed")},e.prototype.onRetryRegistration=function(){this.state===n.Connected&&this.registrationState===r.Retrying?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRetryRegistration")},e.prototype.onRegistrationSucceeded=function(){this.state===n.Connected&&this.registrationState===r.Registering?(this.registrationState=r.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===n.Connected&&this.registrationState===r.RegisteringButResendPending?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationSucceeded")},e.prototype.onRegistrationNearExpiry=function(){this.state===n.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.sendRegisterRequest()):this.showIgnored("onRegistrationNearExpiry")},e.prototype.onUnregistrationDone=function(){this.state===n.Unregistering?(this.setState(n.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored("onUnregistrationDone")},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===n.Connected&&this.registrationState===r.Registered?(this.registrationState=r.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===n.Connected&&this.registrationState===r.Registering&&(this.registrationState=r.RegisteringButResendPending)},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===n.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored("onIncallModeTimer")},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(a.UserActivityEventReason.Modified,this.state===n.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse("onActivityStateResponseTimeout")},e.prototype.forceReconnect=function(e){this.state===n.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error("Cannot proceed, reached terminal state. Switching from state '".concat(n[this.state],"' to ").concat(n[n.TerminalError])),this.stop(!0,!0),this.setState(n.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===n.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug("Ignoring event '".concat(e,"' in state '").concat(n[this.state],"'"))},e.prototype.setState=function(e){this.logger.info("Switching from state '".concat(n[this.state],"' to state '").concat(n[e],"'")),this.state!==e?this.state=e:this.logger.error("Attempt to switch to the current state '".concat(n[e],"'"))},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){if(!this.autoReconnect)return this.logger.info("Automatic reconnect is disabled, stopping this connection"),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(n.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}();t.TrouterFsm=l},function(e,t,i){function n(e,t){var i=t?void 0:{"X-MS-Migration":"True"};switch(e.tokenType.toLowerCase()){case"skype":return s({"X-Skypetoken":e.token},i);case"aad":case"cae":return s({Authorization:"Bearer ".concat(e.token)},i);default:throw new Error("unsupported token type: ".concat(e.tokenType))}}function r(e){return"object"==typeof e&&null!==e&&void 0!==e.stack?(0,u.toJson)(e.stack):'"(no error.stack)"'}function a(e){return"object"==typeof e&&null!==e&&"string"==typeof e.message?e.message:"(no error.message)"}var s=this&&this.__assign||function(){return s=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},s.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},l=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var c,d=i(21),u=i(3),h=i(15),p=i(1),g=i(16),m=i(17),f=i(2),v=i(4),S=i(0),y=i(5),C=i(6),_=i(12),E=function(){this.cv=p.CLIENT_VERSION,this.ua="",this.hr="",this.v=""},T=function(){function e(){this["force new connection"]=!0,this.reconnect=!1,this.query="",this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),b="MS-CV",I=function(){function e(e,t){this.logger=t,this.cvCounter=0;var i=JSON.parse(e);this.startTS=this.safeJsonNumber(i,"startTS",0),this.url=this.safeJsonString(i,"url",""),this.shortUrl=this.safeJsonString(i,"shortUrl",""),this.body=this.safeJsonString(i,"body",""),this.headers=this.safeJsonRecord(i,"headers",{}),this.id=this.safeJsonNumber(i,"id",-1),this.method=this.safeJsonString(i,"method",""),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[b],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?"".concat(this.receivedCv,".").concat(this.cvCounter):""},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){"data"===e?this.dataCallback=t:"end"===e&&("function"==typeof this.dataCallback&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[b]=e)},e.prototype.safeJsonNumber=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("number"==typeof r[t])return r[t];if("string"==typeof r[t])return parseFloat(r[t]);null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e.prototype.safeJsonString=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("string"==typeof r[t])return r[t];null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e.prototype.safeJsonRecord=function(e,t,i){var n;if(null!=e&&Object.prototype.hasOwnProperty.call(e,t)){var r=e;if("object"==typeof r[t])return r[t];null===(n=this.logger)||void 0===n||n.warn("unexpected type of '".concat(t,"': ").concat(typeof r[t]))}return i},e}(),w=function(){function e(e,t,i){this.request=e,this.responseData=t,this.sendResponse=i}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),R=function(e){this.name=e,this.args={},this.timeoutTimerId=0};!function(e){e[e.Configuration=0]="Configuration",e[e.ServerInitiated=1]="ServerInitiated"}(c||(t.ReconnectReason=c={}));var A=function(){function e(e,t,i,n,r,a,s,o){var l,c=this;this.options=t,this.manager=i,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.protocolSelector=s,this.audienceSubscriptionState=o,this.WEBSOCKET_TRANSPORT_NAME="websocket",this.XHR_POLLING_TRANSPORT_NAME="xhr-polling",this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR="Error",this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED="Unsubscribed",this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT="Timeout",this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST="BadRequest",this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.connectionId="",this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId="",this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase="",this.connectingErrorsInRow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.lastDisconnectReason="",this.UNKNOWN_TRANSPORT="unknown_transport",this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.logger=new S.Logger("Connection",e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new m.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),"undefined"!=typeof window&&window.location&&(this.domId=window.location.hostname);var u=new E;u.cv=p.CLIENT_VERSION,u.ua="",(null===(l=this.options)||void 0===l?void 0:l.clientInfo)&&(u.ua=this.safeString(this.options.clientInfo.ua),u.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=u,this.connectionTracker=new h.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return c.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var g=this.options.incallModeTimeoutMs>0;if(this.fsm=new C.TrouterFsm(e,this,g,this.protocolSelector),t.registration){var f={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,d.createRegistrarClient)(e,this.tokenProvider,f)}this.userActivityState=a}return e.prototype.start=function(e){this.logger.info("Starting"),this.reconnectParams=e,"undefined"!=typeof window&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.addEventListener("offline",this.onNavigatorOnlineStatusUpdateBound),this.logger.debug("Registered for browser online notifications - current state: ".concat(this.isNavigatorOnline))):this.isNavigatorOnline=!0,this.fsm.start()},e.prototype.stop=function(e){this.logger.info("Stopping"),"undefined"!=typeof window&&window.navigator&&(window.removeEventListener("online",this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener("offline",this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info("Configuration changed. Reconnection required."),this.fsm.onReconnectRequired(!1,c.Configuration))},e.prototype.checkConnection=function(e){this.logger.info("checkConnection called with ".concat(e)),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(h.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new v.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:"",this.allocateResult?this.allocateResult.url:"",this.allocateResult?this.allocateResult.surl:"",this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,i,n,r){var a=this;void 0===r&&(r=0),this.logger.info("Getting token ".concat(t?"with backoff":"without backoff"));var s=function(){a.connectionTracker.trackStart("token");var t={needFresh:!e,wwwAuthenticateHeader:i,supportedTokenTypes:p.SUPPORTED_TOKEN_TYPES,purpose:"trouter"};a.logger.info("Requesting token: needFresh=".concat(t.needFresh," ")+"types=[".concat(p.SUPPORTED_TOKEN_TYPES,"], ")+"wwwAuthenticateHeader is ".concat(t.wwwAuthenticateHeader?"non empty":"empty")),a.tokenProvider(t).then((function(e){a.logger.debug("".concat(e.tokenType," token is received")),a.connectionTracker.trackEnd("token"),a.fsm.onTokenReceived(e,n,a.reconnectParams)})).catch((function(t){var s=(0,u.toJson)(t.stack);if(a.logger.error("Getting token failed, will retry after timeout. Error: ".concat(s)),a.connectionTracker.trackError("token",s),!a.canRetryTokenFetchRequest(r+a.unauthorizedErrorCount))return a.connectionTracker.trackError("token","getToken retry limit hit, reached terminal error state"),a.resetTokenBackoff(),void a.fsm.onTerminalError();a.getToken(e,!0,i,n,r+1)}))};t?this.tokenBackoff.backoff("getting token",s):(this.resetTokenBackoff(),s())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug("Starting connection timeout for ".concat(this.timeoutOptions.connectionTimeoutMs," ms")),this.connectionTimeoutId=setTimeout((function(){e.logger.info("Connection timeout is fired"),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&(this.logger.debug("Stopping connection timeout"),clearTimeout(this.connectionTimeoutId),this.connectionTimeoutId=void 0)},e.prototype.startPingTimer=function(){var e=this;"websocket"===this.transportTypeName?(this.logger.debug("Starting ping timeout for ".concat(this.timeoutOptions.pingTimeoutMs," ms")),this.pingTimerId=setInterval((function(){e.logger.info("Ping interval fired"),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug("Not starting ping for transport ".concat(this.transportTypeName))},e.prototype.stopPingTimer=function(){this.pingTimerId&&(this.logger.debug("Stopping ping timeout"),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),this.pingTimerId=void 0)},e.prototype.shouldSkipRegistration=function(){return void 0===this.options.registration},e.prototype.hasCustomRegistrationTtl=function(){var e,t;return void 0!==(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)&&0!==(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),i=t[0],n=t[1];if(i<=30||!n)return this.logger.debug("Starting registration expiration timer (TTL ".concat(i," sec)")),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn("Registration expired but the connection is still alive. Should never happen"),e.dispatchUnregistered()}),1e3*i));var r=i-30;this.logger.debug("Starting registration extension timer for ".concat(r," sec")),this.registrationTimerId=setTimeout((function(){e.logger.info("Registration extension timer fired"),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug("Registration extension did not happen in time"),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*r)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&(this.logger.debug("Stopping registration timeout"),clearTimeout(this.registrationTimerId),this.registrationTimerId=void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw new Error("Trouter Client not configured to handle registrations");return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw new Error("Allocate result is undefined in buildSocketIoUrlParams()");for(var i={},n=this.allocateResult.connectparams,r=0,a=Object.keys(n);r<a.length;r++){var s=a[r];if(void 0!==n[s]){var o=n[s];"string"==typeof o||"number"==typeof o?i[s]=o:this.logger.error("signatureData[".concat(s,"] has unsupported type ").concat(typeof o))}}return i.v="v4",i.tc=encodeURI((0,u.toJson)(this.clientInfo)),i.timeout=this.timeoutOptions.pingTimeoutMs/1e3,i.auth="true",this.options.endpointId&&(i.epid=this.options.endpointId),e&&(i.userActivity=encodeURI((0,u.toJson)(e))),t&&(i.audienceSubscriptionState=encodeURIComponent((0,u.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(i),!0)},e.prototype.startSocketIo=function(e){var t,i;if(this.logger.debug("Starting socket io"),this.connectionTracker.trackStart("connectSocket"),!this.allocateResult)throw new Error("Allocate result is undefined in startSocketIo()");var r=this.options.ioOptions?s({},this.options.ioOptions):new T,a=this.userActivityState.state!==f.UserActivityState.Unknown?this.userActivityState.increaseCvAndGetEventObject():void 0,o=null===(t=this.audienceSubscriptionState)||void 0===t?void 0:t.increaseCvAndGetEventObject();if(r["force new connection"]=!0,r.reconnect=!1,r.rewriteUrlForProxy=this.options.rewriteUrlForProxy,r.requestHeaders=s(s({},this.options.extraConnectionHeaders),n(e,this.usingLegacyTokenApi)),r.query=this.buildSocketIoUrlParams(a,o),this.logger.info("connecting to ".concat(this.allocateResult.socketio,"?").concat(r.query)),this.stopSocketIo(),this.socket=(null!==(i=this.options.io)&&void 0!==i?i:_).connect(this.allocateResult.socketio,r),void 0===this.socket)throw new Error("Can't create Socket.io object");this.attachSocketIoHandlers(this.socket,e,a,o)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug("clearing socket.io");try{for(var e=0,t=["connecting","connect","connect_failed","close_during_connecting","disconnect","reconnect","reconnect_failed","reconnecting","error","message","trouter.connected","trouter.reconnect","trouter.message_loss"];e<t.length;e++){var i=t[e];this.socket.removeAllListeners(i)}this.socket.disconnect(),this.logger.debug("cleared socket"),this.socket=void 0}catch(e){this.logger.error("exception in disconnecting previous socket. Error: ".concat(r(e)))}}},e.prototype.dispatchConnected=function(){this.logger.info("dispatching connected"),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info("dispatching registered"),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info("dispatching unregistered"),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug("dispatching downstream request");try{var i=new w(e,new h.ResponseData(e.id),(function(e,i){return t.logger.debug("sending response to downstream"),t.sendResponse(e,i)}));this.manager.onDownstreamRequest(this,e,i)}catch(e){this.logger.error("exception in socket.on message. Error : ".concat(r(e)))}},e.prototype.dispatchReconnecting=function(){this.logger.info("dispatching reconnecting"),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info("dispatching reconnect is required by server"),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info("dispatching disconnected"),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info("dispatching terminal error"),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info("dispatching trouter message lost"),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn("counting disconnect before connection was fully established as a connection failure"),++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug("emitting processed flow tags to the server");var i=new R("trouter.processed_message_loss");i.args={droppedIndicators:e},this.sendDownstreamEvent(i,(function(){t.logger.info("emitted processed flow tags to the server")}))}catch(e){var n=r(e);this.logger.error("unable to send processed message loss event. Error: ".concat(n)),this.connectionTracker.trackError("trouter.processed_message_loss",n,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var i,r=this.options.trouterUrl,a=this.reconnectParams,o="string"==typeof(null==a?void 0:a.se)?parseInt(a.se,10):"number"==typeof(null==a?void 0:a.se)?a.se:void 0;o&&o<=Date.now()+36e5&&(this.logger.warn("Dropping expired cached connection parameters: ".concat(new Date(o))),this.reconnectParams=a=void 0),a&&a.serviceUrl!==r&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(a.serviceUrl,", now ").concat(r,")")),this.reconnectParams=a=void 0),(null==a?void 0:a.reconnectUrl)&&(r=a.reconnectUrl),i=a?s(s({},a),{serviceUrl:void 0,reconnectUrl:void 0}):null,r=(0,y.adaptUrl)(r,"v4a"),r=this.appendCorrelationIds(r,!1),r=this.appendEndpointId(r,!1),i&&(r+="&".concat(this.buildQuery(i)),i.v||(r+="&v=".concat("v4"))),r=this.options.rewriteUrlForProxy(r);var l=new Request(r,{method:"POST",mode:"cors",headers:new Headers(s(s({"Content-Type":"text/plain"},this.options.extraConnectionHeaders),n(e,this.usingLegacyTokenApi)))});this.logger.info("sendAllocateRequest: POST ".concat(r)),this.connectionTracker.trackStart("allocation");var c,d=Date.now(),h=-1,p=!1;(0,u.fetchWithTimeout)(l,this.timeoutOptions.fetchTimeoutMs).then((function(e){var i;if(h=e.status,!e.ok)throw c=null!==(i=e.headers.get("www-authenticate"))&&void 0!==i?i:void 0,p="1"===e.headers.get("x-trouter-skypetoken-deprecated"),t.logger.warn("Allocation request got response status ".concat(e.status,", www-authenticate header was ").concat(c?"not empty":"empty")),new Error(e.statusText);var n=e.headers.get("content-type");if(!n||"application/json"!==n&&!n.startsWith("application/json;"))throw new Error("Content-type '".concat(n,"' is unexpected"));return t.connectionTracker.trackEnd("allocation"),e.json()})).then((function(i){t.unauthorizedErrorCount=0,t.onAllocationResponse(i,e)})).catch((function(e){t.connectingErrorsInRow++;var i="".concat(e).concat(h>=0?", status code ".concat(h):"");if(t.logger.error("".concat(t.connectingErrorsInRow," failed connecting attempt(s) in a row. ").concat(i)),t.connectionTracker.trackError("allocation",i),p){var n="Skypetoken deprecated response, not retrying any further";return t.logger.error(n),t.connectionTracker.trackError("allocation",n),void t.fsm.onTerminalError()}if(401===h&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return n="getToken retry limit hit, reached terminal error state",t.connectionTracker.trackError("allocation",n),void t.fsm.onTerminalError();if(-1!==h||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold)if(h>=400&&h<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn("".concat(t.connectingErrorsInRow," connection attempts, testing nominal service URL"));var r=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-d)-500,t.timeoutOptions.fetchTimeoutMs);return void t.testNominalUrlConnectivity(r).then((function(e){t.connectionTracker.trackProgress("nomcheck",e?"ok":"failed"),e?(t.logger.warn("Nominal service URL is reachable, erasing cached reconnect URL"),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn("Nominal service URL is not reachable either, keeping cached reconnect URL"),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}))}}else t.logger.info("Expected failure, the browser says it is not online at the moment");t.fsm.onAllocationFailed(401===h,c)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,i=this;if(e<1e3)return this.logger.warn("There is no time left to reasonably perform the nominal service URL connectivity check (".concat(e," ms), falling back to assuming that the connectivity is fine")),Promise.resolve(!0);try{var n=new URL(this.options.trouterUrl);n.pathname="/",n.search="?"+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:""),tc:encodeURIComponent((0,u.toJson)(this.clientInfo))}),t=new Request(this.options.rewriteUrlForProxy(n.toString()),{method:"GET",headers:{Accept:"text/plain"}})}catch(e){return this.logger.warn("Nominal service URL connectivity test request could not be created (".concat(e,"), falling back to assuming that the connectivity is fine")),Promise.resolve(!0)}return(0,u.fetchWithTimeout)(t,e).then((function(e){if(200!==e.status)throw new Error("Not 200 OK: ".concat(e.status," ").concat(e.statusText));return e.text()})).then((function(e){if("Trouter"!==e)throw new Error('Not "Trouter": '.concat(e.substring(0,16)).concat(e.length>16?"...":""));return!0})).catch((function(e){return i.logger.error("Nominal service URL connectivity test failed: ".concat(e)),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&void 0===this.pingResponseTimerId)try{this.logger.debug("emitting ping event");var t=!1;this.socket.emit("ping",(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error("Ping response timeout is fired"),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var i=r(e);this.logger.error("unable to send ping. Error: ".concat(i)),this.connectionTracker.trackError("ping",i,!1)}},e.prototype.connectV4c=function(e,t){var i,n,r,a,o,l,c=this.options.ioOptions?s({},this.options.ioOptions):new T;c["force new connection"]=!0,c.reconnect=!1,(null===(i=this.reconnectParams)||void 0===i?void 0:i.serviceUrl)&&(0,y.adaptUrl)(this.reconnectParams.serviceUrl,"v4c")!==(0,y.adaptUrl)(this.options.trouterUrl,"v4c")&&(this.logger.warn("Dropping cached connection parameters for a different environment (".concat(this.reconnectParams.serviceUrl,", now ").concat(this.options.trouterUrl,")")),this.reconnectParams=void 0);var d=null!==(a=null!==(n=(0,y.redirectUrlIfPresent)(t))&&void 0!==n?n:"redirect-no-host"!==(null==t?void 0:t.kind)?null===(r=this.reconnectParams)||void 0===r?void 0:r.reconnectUrl:void 0)&&void 0!==a?a:this.options.trouterUrl,u=(0,y.adaptUrl)(d,"v4c");c["skipped handshake data"]={timeout:70,websocketUrl:u},c.query=this.buildV4cUrlParams(),c.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName="websocket",this.socket=(null!==(o=this.options.io)&&void 0!==o?o:_).connect(this.options.trouterUrl,c),void 0===this.socket)throw new Error("failed to create Socket.io object");var h=null===(l=this.audienceSubscriptionState)||void 0===l?void 0:l.increaseCvAndGetEventObject();this.attachSocketIoHandlers(this.socket,e,void 0,h)}catch(e){this.logger.error("".concat(e)),this.connectionTracker.trackError("v4c","".concat(e)),this.fsm.onV4cException()}},e.prototype.sendV4cAuthenticationEvent=function(e){var t,i={headers:s(s({},this.options.extraConnectionHeaders),n(e,this.usingLegacyTokenApi)),connectparams:(0,y.reconnectParamsWithoutUrls)(this.reconnectParams)};null===(t=this.socket)||void 0===t||t.emit(p.USER_AUTHENTICATE_EVENT_NAME,i)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info("Changing user activity state to '".concat(e.toEventJSON(),"'")),this.fsm.onSetNewUserActivityState()):(this.logger.debug("Not changing the same user activity state '".concat(e.toEventJSON(),"'")),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){this.userActivityState.state!==f.UserActivityState.Unknown&&("websocket"===this.transportTypeName&&t?e===v.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):"xhr-polling"===this.transportTypeName&&e===v.UserActivityEventReason.Modified&&this.fsm.forceReconnect("user activity/force reconnect"))},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var i=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var n=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,i);return this.fsm.forceReconnect("set audience subscription force reconnect"),n}throw new Error("set audience subscription executed on an unknown transport")},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return o(this,void 0,void 0,(function(){var i,n,r=this;return l(this,(function(a){switch(a.label){case 0:return this.logger.info("[WebSocket] Audience subscription set requested."),(i=new R("audience.subscribe")).args=e,[4,new Promise((function(n){var a=!1,s=setTimeout((function(){return a=!0,n(r.buildAudienceSubscriptionsTimeoutResponse(e))}),t);r.sendDownstreamEvent(i,(function(e,t){a||(clearTimeout(s),r.logger.debug("[Websocket] Audience subscription response: ".concat(t)),r.pendingAudienceSubscription&&r.onAudienceSubscriptionResult(t),n(t))}))}))];case 1:return n=a.sent(),this.manager.onAudiencesSetResolved(n,e.cv),[2,n]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,i){var n;return o(this,void 0,void 0,(function(){var r,a,s,o,c,d,u=this;return l(this,(function(l){switch(l.label){case 0:return this.logger.info("[XHR Polling] Audience subscription set requested."),this.pendingAudienceSubscription&&(this.logger.error("Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons."),clearTimeout(this.pendingAudienceSubscription.timeoutId)),0===e.audiences.length?[2,this.handleAudienceUnsubscribeLongpoll(e.cv,i)]:[4,new Promise((function(i){var n=setTimeout((function(){return u.pendingAudienceSubscription=void 0,i(u.buildAudienceSubscriptionsTimeoutResponse(e))}),t);u.pendingAudienceSubscription={audienceSetResolve:i,timeoutId:n}}))];case 1:return r=l.sent(),this.manager.getState()===f.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?[2,r]:(null==(a=r.responses[0])?void 0:a.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]):(s=r.responses.find((function(t){return t.audienceId===e.audiences[0].id})),(null==s?void 0:s.result.audienceSubscriptionState)===this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR?(this.clearAudienceSubscriptionStateQueryParam(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]):(o=(null===(n=null==i?void 0:i.audienceSubscriptionModel.audienceSubscriptions[0])||void 0===n?void 0:n.id)!==(null==a?void 0:a.audienceId),i&&o&&(c=this.mapToSyntheticAudienceSubscriptionResponses(i.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200),(d=r.responses).push.apply(d,c)),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]))}}))}))},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e,t,i;(null===(i=null===(t=null===(e=this.socket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.options)||void 0===i?void 0:i.query)&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,""))},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var i;this.audienceSubscriptionState=void 0;var n={responses:[]};if(t){var r=this.mapToSyntheticAudienceSubscriptionResponses(t.audienceSubscriptionModel.audienceSubscriptions,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);(i=n.responses).push.apply(i,r)}return this.manager.onAudiencesSetResolved(n,e),n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error("Audience subscription attempt has timed out."),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,i){return e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:i}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=this;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");if(!this.allocateResult)throw new Error("Allocate result is undefined in sendRegisterRequest()");this.logger.info("sending register request");var t=new u.Timespan;this.connectionTracker.trackStart("registration");var i=this.getRegistrationTtl()[0];this.registrarClient.register({appId:this.options.registration.pnhAppId,aesKey:"",languageId:"en-US",platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},{TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:i}]}).then((function(){e.logger.info("Register request successful"),e.connectionTracker.trackEnd("registration"),e.fsm.onRegistrationSucceeded(),e.connectionTracker.sendTelemetry(h.ClientEventName.Registration,{duration:t.duration},[])})).catch((function(i){e.logger.error("Register request failed. Error: ".concat(i)),e.connectionTracker.trackError("registration",a(i)),e.fsm.onRegistrationFailed(),e.connectionTracker.sendTelemetry(h.ClientEventName.Registration,{duration:t.duration},[])}))},e.prototype.sendUnregisterRequest=function(){var e=this;this.logger.info("sending unregister request");var t=new u.Timespan;if(!this.options.registration||!this.registrarClient)throw new Error("Internal error - options.registration is undefined");this.connectionTracker.trackStart("unregistration"),this.registrarClient.unregister().then((function(){e.logger.info("Unregister request successful"),e.connectionTracker.trackEnd("unregistration"),e.fsm.onUnregistrationDone(),e.connectionTracker.sendTelemetry(h.ClientEventName.Unregistration,{duration:t.duration},[])})).catch((function(i){e.logger.error("Unregister request failed. Error: ".concat(i)),e.connectionTracker.trackError("unregistration",a(i)),e.fsm.onUnregistrationDone(),e.connectionTracker.sendTelemetry(h.ClientEventName.Unregistration,{duration:t.duration},[])}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug("Clearing all pending downstream events related timers");for(var t=0,i=e;t<i.length;t++){var n=i[t];this.clearSentEventTimer(Number(n))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug("Restarting incall mode timer"),this.incallModeTimerId=setTimeout((function(){e.logger.info("Call mode timer fired"),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info("Entering incall mode"),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.prototype.exitIncallMode=function(){this.logger.info("Exiting incall mode"),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect("force reconnect due to no registration")},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn("".concat(this.connectingErrorsInRow," connection attempts, server-side failure: erasing cached connection parameters")),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info("onSocketConnecting(".concat(e,")")),this.transportTypeName=e,this.connectionTracker.trackProgress("connecting",this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info("onSocketConnect"),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error("onSocketConnectFailed"),this.connectionTracker.trackError("connect_failed",e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,i=g.DisconnectReason.fromRawReason(e);this.logger.error("onSocketDisconnect, reason: ".concat(i.reason)),"dup"===i.reason&&"dup"===this.lastDisconnectReason&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn("Socket was closed by server as Duplicate for the second time in a row "+"after ".concat(t," ms which is below the threshold of ")+"".concat(this.options.duplicateDisconnectThresholdMs," ms. Resetting cached ")+"connection parameters and making a new allocation."),this.reconnectParams=void 0),this.lastDisconnectReason=i.reason,this.fsm.onSocketDisconnect(i),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error("onSocketReconnect"),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error("onSocketReconnectFailed with '".concat(e,"'")),this.fsm.onSocketDisconnect(g.DisconnectReason.fromSocketIoEventData("reconnecterror",e))},e.prototype.onSocketReconnecting=function(){this.logger.error("onSocketReconnecting")},e.prototype.onSocketError=function(e){this.logger.error("onSocketError with '".concat((0,u.toJson)(e),"'")),this.fsm.isConnecting()&&++this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold(),this.connectionTracker.trackError("connectSocket",function(e){return null!=e&&"function"==typeof e.toString?e.toString():"[".concat(typeof e,"]")}(e)),this.fsm.onSocketDisconnect(g.DisconnectReason.fromSocketIoEventData("socketerror",e))},e.prototype.onSocketMessage=function(e){var t,i,n=this;this.logger.debug("onSocketMessage");try{var s=null===(t=(i=new I(e,this.logger)).headers)||void 0===t?void 0:t["X-Microsoft-Skype-Chain-ID"],o=s?" Chain-Id ".concat(s):"";this.logger.info("Received request N ".concat(i.id).concat(o," CV ").concat(i.correlationVector," to '").concat(i.url,"'")),i.startTS=Date.now(),i.url&&this.urlPath&&i.url.startsWith(this.urlPath)&&(i.shortUrl=i.url.substring(this.urlPath.length))}catch(e){var l=r(e);return this.logger.error("unable to parse request. Error: ".concat(l)),this.connectionTracker.trackRequest(void 0,l),void this.connectionTracker.sendResponseError("unable to parse request, error: ".concat(e))}i.timeoutTimerId=setTimeout((function(){if(!i.replied){n.logger.error("Request ".concat(i.id," timed out"));var e=new h.ResponseData(i.id);e.status=504,e.headers={"Trouter-Responder":"ClientLib"},n.sendResponse(i,e),i.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.connectionTracker.trackRequest(i),this.fsm.onDownstreamRequest(i)}catch(e){this.logger.error("exception in socket.on message. Error: ".concat(r(e))),this.connectionTracker.sendResponseError(a(e),i,void 0)}},e.prototype.onTrouterConnected=function(e,t,i){var n,r,a,o,l=this;if((0,y.isV4ConnectEvent)(e)){var c=e;this.allocateResult=s(s({},c),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(c,c.reconnectUrl),this.populateConnectionStateFields(c)}else if(!this.allocateResult)return void this.logger.error("Invalid internal state - received onTrouterConnected while allocateResult is not set");this.connectingErrorsInRow=0,this.logger.info("onTrouterConnected: ".concat(this.allocateResult.url)),"xhr-polling"===this.transportTypeName&&t&&this.manager.onUserActivityStateAccepted(t.cv),(null===(a=null===(r=null===(n=this.socket)||void 0===n?void 0:n.socket)||void 0===r?void 0:r.options)||void 0===a?void 0:a.query)&&(this.socket.socket.options.query+="&connected=true"),this.urlPath=this.allocateResult.url.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,"/");var d=this.connectedUrl!==this.allocateResult.url;this.connectedUrl=this.allocateResult.url,this.connectionExpireTimestampInSecs=(0,u.calculateExpireTsInSec)((0,y.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd("connectSocket"),this.connectionTracker.trackConnected(d,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),null===(o=this.setAudienceSubscriptionsUnsafeAsync(i))||void 0===o||o.catch((function(e){return l.logger.error("Re-subscribe to audiences has failed with ".concat(e))})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info("onTrouterReconnect target: ".concat(t)),"self"===t?this.fsm.onReconnectRequired(!0,c.ServerInitiated):this.fsm.onReconnectRequired(!1,c.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug("onTrouterMessageLoss"),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.onAudienceSubscriptionResult=function(e){this.logger.info("onAudienceSubscriptionResult"),this.pendingAudienceSubscription&&(clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),this.pendingAudienceSubscription=void 0)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,u.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,i,n){var r=this;e.on("connecting",(function(e){r.onSocketConnecting(e)})),e.on("connect",(function(){r.onSocketConnect(t)})),e.on("connect_failed",(function(e){r.onSocketConnectFailed(e)})),e.on("close_during_connecting",(function(e){r.onSocketConnectFailed(e)})),e.on("disconnect",(function(e){r.onSocketDisconnect(e)})),e.on("reconnect",(function(){r.onSocketReconnect()})),e.on("reconnect_failed",(function(e){r.onSocketReconnectFailed(e)})),e.on("reconnecting",(function(){r.onSocketReconnecting()})),e.on("error",(function(e){r.onSocketError(e)})),e.on("message",(function(e){r.onSocketMessage(e)})),e.on("trouter.connected",(function(e){r.onTrouterConnected(e,i,n)})),e.on("trouter.reconnect",(function(e){r.onTrouterReconnect(e)})),e.on("trouter.message_loss",(function(e){r.onTrouterMessageLoss(e)})),e.on("audience.subscriptionresult",(function(e,t){r.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug("Browser online status update - new state: ".concat(e,", previously: ").concat(this.isNavigatorOnline)),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress("browserNet","online")):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress("browserNet","offline"))},e.prototype.onAllocationResponse=function(e,t){this.logger.info("Received allocation response ".concat(JSON.stringify(e))),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,"".concat(this.allocateResult.socketio,"v4/a")),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=s({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t,i,n="string"==typeof e.ttl?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,u.calculateExpireTsInSec)(n),this.connectionId=null!==(t=e.id)&&void 0!==t?t:"",this.connectedClientId=e.ccid,this.logger.debug("connected client id set {connectedClientId:".concat(this.connectedClientId,"}")),this.c2cUrlBase=null!==(i=e.curlb)&&void 0!==i?i:"",""===this.c2cUrlBase){var r=e.surl.indexOf("://");r>=0&&(r=e.surl.indexOf("/",r+3))>=5&&":3443"===e.surl.substr(r-5,5)&&(this.c2cUrlBase=e.surl.substr(0,r-5))}},e.prototype.onPingResponse=function(){this.logger.debug("onPingResponse"),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){void 0!==this.pingResponseTimerId&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],i=0,n=Object.keys(e);i<n.length;i++){var r=n[i];void 0!==e[r]&&t.push("".concat(r,"=").concat(e[r]))}return t.join("&")},e.prototype.appendConnectedClientIds=function(e,t){var i="";e.includes("ccid=")||(i="ccid=".concat(this.connectedClientId,"&")),this.domId&&(i+="dom=".concat(this.domId,"&")),i.length>0&&(i=i.slice(0,-1));var n=t||e.includes("?")?"&":"?";return this.appendCorrelationIds(e+n+i,t)},e.prototype.appendEndpointId=function(e,t){var i=t||e.includes("?")?"&":"?";return!e.includes("epid")&&this.options.endpointId?"".concat(e).concat(i,"epid=").concat(this.options.endpointId):e},e.prototype.appendCorrelationIds=function(e,t){var i=t||e.includes("?")?"&":"?";return e.includes("cor_id")?e:"".concat(e).concat(i,"cor_id=").concat(this.options.clientCorrelationID)+"&con_num=".concat(this.clientID,"_").concat(this.connectionAttempt)},e.prototype.safeString=function(e){return"string"==typeof e?e:""},e.prototype.sendResponse=function(e,t){var i,n,a;if(e.timedout)return this.logger.error("Request ".concat(e.id," already timed out")),1;if(e.replied)return this.logger.error("Response for request ".concat(e.id," already sent")),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=null!==(i=t.headers)&&void 0!==i?i:{};var s=e.correlationVector;this.logger.info("Sending response N ".concat(e.id," CV ").concat(s," with status ").concat(t.status)),s&&(t.headers[b]=s),(null===(n=e.headers)||void 0===n?void 0:n["trouter-request"])&&(t.headers["trouter-request"]=e.headers["trouter-request"]);var o=Date.now()-e.startTS;if(t.headers["trouter-client"]=(0,u.toJson)({cd:o}),(null===(a=e.headers)||void 0===a?void 0:a["trouter-is-broadcast"])&&(t.headers["trouter-is-broadcast"]=e.headers["trouter-is-broadcast"]),this.logger.debug("response: ".concat((0,u.toJson)(t))),!this.socket)return this.connectionTracker.sendResponseError("no socket",e,t),4;try{return this.socket.send((0,u.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,o,t),"websocket"===this.transportTypeName&&this.sendPingRequest(),0}catch(i){var l="unable to send data on response.end. Error: ".concat(r(i));return this.logger.error(l),this.connectionTracker.sendResponseError(l,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,i=new R("user.activity"),n=this.userActivityState.increaseCvAndGetEventObject();i.args=n,this.logger.debug("Sending user activity '".concat(this.userActivityState.toEventJSON(),"', remaining ").concat(e-1));var r=!1;this.sendDownstreamEvent(i,(function(){if(!0!==r&&(t.logger.info("User activity state: ".concat(n.state,", cv: ").concat(n.cv," accepted")),t.manager.onUserActivityStateAccepted(n.cv),t.clearSentEventTimer(i.timeoutTimerId),e>1)){var a=setTimeout((function(){t.clearSentEventTimer(a),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(a,"user.activity/resend")}})),i.timeoutTimerId=setTimeout((function(){t.logger.error("Activity state response timeout is fired"),r=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(i.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(i.timeoutTimerId,"user.activity/response")},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug("Sending downstream event ".concat(e.name)),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug("registering timer ".concat(e," -> ").concat(t)),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug("clearing timer ".concat(e," -> ").concat(t)),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e,t,i=(0,u.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug("Current connectionID will expire in ".concat(i," seconds")),(null===(e=this.options.registration)||void 0===e?void 0:e.registrarTtlSec)&&i>0){var n=this.options.registration.registrarTtlSec<i;return[Math.min(this.options.registration.registrarTtlSec,i),n]}return(null===(t=this.options.registration)||void 0===t?void 0:t.registrarTtlSec)?[this.options.registration.registrarTtlSec,!1]:i>0?[i,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){void 0!==this.incallModeTimerId&&(this.logger.debug("Clearing in-call mode timer"),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&"function"==typeof e.eventLogger.logEvent?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn("Trouter client event logging disabled due to invalid configuration.")}catch(e){this.logger.warn("Trouter client event logging disabled. Error: ".concat(r(e))),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return null==t||e<t||(this.logger.warn("Reached limit on maximum number of token fetch request. Current count: ".concat(e,", retry limit: ").concat(t)),!1)},e}();t.TrouterConnection=A},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var n=i(1),r=i(0),a=function(){function e(e){this.messageHandlers=[],this.logger=new r.Logger("MessageHandlers",e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw new Error("Registering the same handler twice is not allowed");this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug("Clearing message handlers"),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:n.UNHANDLED_MESSAGE_ACK,isHandled:!1},i=0,r=this.messageHandlers;i<r.length;i++){var a=r[i],s=this.safeExecuteHandle(a,e);if(void 0!==s&&(void 0===s.isHandled||s.isHandled))return void 0===s.resultCode&&(s.resultCode=n.HANDLED_MESSAGE_ACK),s}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){return void this.logger.warn("Trouter message handler threw an exception: ".concat(e))}},e}();t.MessageHandlerRegistry=a},function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=void 0,t.addCacheAsBackupTo=function(e){var t,i=this;return function(a){return n(i,void 0,void 0,(function(){return r(this,(function(i){return a&&(t=void 0),[2,new Promise((function(i,n){e(a).then((function(e){t=e,i(e)})).catch((function(e){void 0!==t&&t.length>0&&i(t),n(e)}))}))]}))}))}}},function(e,t,i){var n=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var a=i(3),s=i(2),o=i(4),l=i(0),c=i(5),d=i(18),u=i(7),h=i(6),p=i(19),g=function(){function e(e,t){this.state=e,this.correlationVector=void 0!==t?t:a.CorrelationVector.extend()}return e.prototype.getStateString=function(){switch(this.state){case s.UserActivityState.Active:return"active";case s.UserActivityState.Inactive:return"inactive";case s.UserActivityState.Unknown:return"unknown";default:return"undefined"}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.UserActivityObject=g;var m=function(){function e(e,t){void 0===t&&(t=a.CorrelationVector.extend()),this.audienceSubscriptionModel=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.audienceSubscriptionModel.audienceSubscriptions,cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.AudienceSubscriptionState=m;var f=function(){function e(e,t,i,n,r,o){var d=this;this.logFunc=e,this.options=t,this.tokenProvider=i,this.usingLegacyTokenApi=n,this.listener=r,this.tokenTypeProtocolSelector=function(e,t){return d.options.forceV4aProtocol?"v4a":(0,c.usedProtocol)(e,t)},this.logger=new l.Logger("Manager",e),this.logger.info("Created TrouterManager with options ".concat((0,a.toJson)(this.options))),this.fsm=new p.TrouterManagerFsm(e,this),this.baseEndpointUrl="",this.processedMessageLoss={},this.userActivityObject=new g(s.UserActivityState.Unknown),this.protocolSelector=null!=o?o:this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,void 0!==this.firstConnection&&this.firstConnection.configure(e),void 0!==this.secondConnection&&this.secondConnection.configure(e),this.logger.info("Reconfigured TrouterManager with options ".concat((0,a.toJson)(this.options)))},e.prototype.checkConnection=function(e){void 0!==this.firstConnection&&this.firstConnection.checkConnection(e),void 0!==this.secondConnection&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return n(this,void 0,void 0,(function(){return r(this,(function(e){return void 0!==this.secondConnection?(this.logger.info("Resending registration on the second/new connection"),[2,this.secondConnection.resendRegistration()]):void 0!==this.firstConnection?(this.logger.info("Resending registration on the first/current connection"),[2,this.firstConnection.resendRegistration()]):(this.logger.info("No connection to resend registration on, will be done upon (re)connect"),[2])}))}))},e.prototype.getServerState=function(){if(void 0!==this.firstConnection)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===o.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?h.State[this.firstConnection.getState()]:"Unknown",t=o.TrouterManagerState[this.fsm.getInternalState()];if(this.secondConnection){var i=h.State[this.secondConnection.getState()];return"Manager ".concat(t,"; 1st ").concat(e,"; 2nd ").concat(i)}return"Manager ".concat(t,"; Connection ").concat(e)},e.prototype.startFirstConnection=function(){var e=new u.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=e,this.getConnectionCache().then((function(t){e.start(t)})).catch((function(){}))},e.prototype.startSecondConnection=function(e){var t=new u.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=t,void 0!==this.firstConnection&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?this.getConnectionCache().then((function(e){t.start(e)})).catch((function(){})):t.start()},e.prototype.stopFirstConnection=function(e){void 0!==this.firstConnection&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){void 0!==this.secondConnection&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(void 0!==this.secondConnection){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info("Closing an inactive connection in ".concat(Math.round(this.options.lingeringConnectionDelayMs/1e3),"s")),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&(this.storedFirstConnection.stop(!1),this.storedFirstConnection=void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return void 0!==this.secondConnection},e.prototype.dispatchConnected=function(){if(void 0!==this.firstConnection){var e=this.firstConnection.getServerState(),t=e.url.endsWith("/")?e.url.slice(0,-1):e.url,i={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,i)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){var e;void 0!==this.lastExpediteBackoffCallAt&&Date.now()-this.lastExpediteBackoffCallAt<(null!==(e=this.options.expediteBackoffOnStartMinimumDelayMs)&&void 0!==e?e:1e4)?this.logger.info("Expedite backoff due to start() too frequent, skipping"):(this.lastExpediteBackoffCallAt=Date.now(),void 0!==this.firstConnection&&this.firstConnection.expediteBackoff(),void 0!==this.secondConnection&&this.secondConnection.expediteBackoff())},e.prototype.onDownstreamRequest=function(e,t,i){var n={id:t.id,method:t.method,path:"/".concat(t.shortUrl),body:t.body,headers:t.headers},r={id:t.id,status:0,headers:{},body:"",send:function(){return r.status<=100||r.status>=999?3:(i.writeHead(r.status,r.headers),i.end(r.body))}};this.listener.onTrouterRequest(n,r)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,i){this.fsm.onReconnectionRequired(e===this.firstConnection,t,i)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var i,n;null===(n=(i=this.listener).onAudiencesSetResolved)||void 0===n||n.call(i,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){return this.userActivityObject=new g(e,a.CorrelationVector.extend(t)),void 0!==this.secondConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the second/new connection")),void this.secondConnection.setUserActivityState(this.userActivityObject)):void 0!==this.firstConnection?(this.logger.info("Setting user activity ".concat(this.userActivityObject.toEventJSON()," on the first/current connection")),void this.firstConnection.setUserActivityState(this.userActivityObject)):void 0},e.prototype.setAudienceSubscriptionsAsync=function(e,t,i){if(this.audienceSubscriptionState=new m(e,a.CorrelationVector.extend(i)),this.secondConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on second/new connection")),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info("Setting audience subscriptions ".concat(this.audienceSubscriptionState.toEventJSON()," on first/current connection")),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw new Error("No connection found")},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(null==e?void 0:e.length){var i=e.filter((function(e){return void 0!==t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]}));if(i.length&&(this.logger.info("onTrouterMessageLoss - immediately acknowledging ".concat(i.length," seen dropped indicators")),this.sendProcessedDroppedIndicators(i),!(e=e.filter((function(e){return void 0===t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]}))).length))return void this.logger.info("onTrouterMessageLoss - all declared dropped indicators have been seen before");if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn("onTrouterMessageLoss - some flow tag(s) have not been processed by listeners");e.forEach((function(e){t.processedMessageLoss["".concat(e.tag,"-").concat(e.etag)]=""})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn("onTrouterMessageLoss - no flow tags have been provided")},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug("Querying host's connection cache"),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return"object"==typeof t?t:void 0})).catch((function(t){return e.logger.warn("Invalid connection cache content provided: ".concat(t)),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn("Error setting external connection cache: ".concat(e))}},e.prototype.sendProcessedDroppedIndicators=function(e){return void 0!==this.firstConnection?void this.firstConnection.sendProcessedDroppedIndicators(e):void 0!==this.secondConnection?void this.secondConnection.sendProcessedDroppedIndicators(e):void 0},e.prototype.configuredTrouterManager=function(){return new d.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e}();t.TrouterManager=f},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var n=i(0),r=function(){function e(e){this.logger=new n.Logger("UrlPromise",e)}return e.prototype.getPromise=function(){var e=this;return void 0!==this.url?(this.logger.debug("returning previously resolved url: ".concat(this.url)),Promise.resolve(this.url)):(void 0===this.pendingPromise?(this.logger.debug("creating and returning promise"),this.pendingPromise=new Promise((function(t,i){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=i}))):this.logger.debug("returning existing promise"),this.pendingPromise)},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug("got url: ".concat(this.url));var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==t&&(this.logger.debug("resolving promise"),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug("aborting");var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,void 0!==t&&(this.logger.debug("rejecting promise"),t(e))},e.prototype.resetUrl=function(){this.logger.debug("resetting url"),this.url=void 0},e}();t.TrouterUrlPromise=r},function(e,t,i){(function(e,i){!function(e,t){var i=e;i.version="0.9.6",i.protocol=1,i.transports=[],i.j=[],i.sockets={},i.connect=function(e,n){var r,a,s=i.util.parseUri(e);t&&t.location&&(s.protocol=s.protocol||t.location.protocol.slice(0,-1),s.host=s.host||(t.document?t.document.domain:t.location.hostname),s.port=s.port||t.location.port),r=i.util.uniqueUri(s);var o={host:s.host,secure:"https"==s.protocol,port:s.port||("https"==s.protocol?443:80),query:s.query||""};return i.util.merge(o,n),!o["force new connection"]&&i.sockets[r]||(a=new i.Socket(o)),!o["force new connection"]&&a&&(i.sockets[r]=a),a=a||i.sockets[r],o["skipped handshake data"]?a.of(""):a.of(s.path.length>1?s.path:"")}}(i.exports,void 0===e?window:e);var n=i.exports;!function(e,t){var i=e.util={},n=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];i.parseUri=function(e){for(var t=n.exec(e||""),i={},a=14;a--;)i[r[a]]=t[a]||"";return i},i.uniqueUri=function(e){var i=e.protocol,n=e.host,r=e.port;return"document"in t?(n=n||document.domain,r=r||("https"==i&&"https:"!==document.location.protocol?443:document.location.port)):(n=n||"localhost",r||"https"!=i||(r=443)),(i||"http")+"://"+n+":"+(r||80)},i.query=function(e,t){var n=i.chunkQuery(e||""),r=[];for(var a in i.merge(n,i.chunkQuery(t||"")),n)n.hasOwnProperty(a)&&r.push(a+"="+n[a]);return r.length?"?"+r.join("&"):""},i.chunkQuery=function(e){for(var t,i={},n=e.split("&"),r=0,a=n.length;r<a;++r)(t=n[r].split("="))[0]&&(i[t[0]]=t[1]);return i};var a=!1;i.load=function(e){if("document"in t&&"complete"===document.readyState||a)return e();i.on(t,"load",e,!1)},i.on=function(e,t,i,n){e.attachEvent?e.attachEvent("on"+t,i):e.addEventListener&&e.addEventListener(t,i,n)},i.request=function(e){if(e&&"undefined"!=typeof XDomainRequest)return new XDomainRequest;if("undefined"!=typeof XMLHttpRequest&&(!e||i.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new(window[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}return null},"undefined"!=typeof window&&i.load((function(){a=!0})),i.defer=function(e){if(!i.ua.webkit||"undefined"!=typeof importScripts)return e();i.load((function(){setTimeout(e,100)}))},i.merge=function(e,t,n,r){var a,s=r||[],o=void 0===n?2:n;for(a in t)t.hasOwnProperty(a)&&i.indexOf(s,a)<0&&("object"==typeof e[a]&&o?i.merge(e[a],t[a],o-1,s):(e[a]=t[a],s.push(t[a])));return e},i.mixin=function(e,t){i.merge(e.prototype,t.prototype)},i.inherit=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},i.intersect=function(e,t){for(var n=[],r=e.length>t.length?e:t,a=e.length>t.length?t:e,s=0,o=a.length;s<o;s++)~i.indexOf(r,a[s])&&n.push(a[s]);return n},i.indexOf=function(e,t,i){var n=e.length;for(i=i<0?i+n<0?0:i+n:i||0;i<n&&e[i]!==t;i++);return n<=i?-1:i},i.toArray=function(e){for(var t=[],i=0,n=e.length;i<n;i++)t.push(e[i]);return t},i.ua={},i.ua.hasCORS="undefined"!=typeof XMLHttpRequest&&function(){try{var e=new XMLHttpRequest}catch(e){return!1}return null!=e.withCredentials}(),i.ua.webkit="undefined"!=typeof navigator&&/webkit/i.test(navigator.userAgent)}(void 0!==n?n:i.exports,void 0===e?window:e),function(e,t){function i(){}e.EventEmitter=i,i.prototype.on=function(e,i){return this.$events||(this.$events={}),this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(i):this.$events[e]=[this.$events[e],i]:this.$events[e]=i,this},i.prototype.addListener=i.prototype.on,i.prototype.once=function(e,t){function i(){n.removeListener(e,i),t.apply(this,arguments)}var n=this;return i.listener=t,this.on(e,i),this},i.prototype.removeListener=function(e,i){if(this.$events&&this.$events[e]){var n=this.$events[e];if(t.util.isArray(n)){for(var r=-1,a=0,s=n.length;a<s;a++)if(n[a]===i||n[a].listener&&n[a].listener===i){r=a;break}if(r<0)return this;n.splice(r,1),n.length||delete this.$events[e]}else(n===i||n.listener&&n.listener===i)&&delete this.$events[e]}return this},i.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},i.prototype.listeners=function(e){return this.$events||(this.$events={}),this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},i.prototype.emit=function(e){if(!this.$events)return!1;var i=this.$events[e];if(!i)return!1;var n=Array.prototype.slice.call(arguments,1);if("function"==typeof i)i.apply(this,n);else{if(!t.util.isArray(i))return!1;for(var r=i.slice(),a=0,s=r.length;a<s;a++)r[a].apply(this,n)}return!0}}(void 0!==n?n:i.exports,void 0!==n?n:i.parent.exports),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw new Error("JSON not available")}(void 0!==n?n:i.exports,"undefined"!=typeof JSON?JSON:void 0),function(e,t){var i=e.parser={},n=i.packets=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],r=i.reasons=["transport not supported","client not handshaken","unauthorized"],a=i.advice=["reconnect"],s=t.JSON,o=t.util.indexOf;i.encodePacket=function(e){var t=o(n,e.type),i=e.id||"",l=e.endpoint||"",c=e.ack,d=null;switch(e.type){case"error":var u=e.reason?o(r,e.reason):"",h=e.advice?o(a,e.advice):"";""===u&&""===h||(d=u+(""!==h?"+"+h:""));break;case"message":""!==e.data&&(d=e.data);break;case"event":var p={name:e.name};e.args&&e.args.length&&(p.args=e.args),d=s.stringify(p);break;case"json":d=s.stringify(e.data);break;case"connect":e.qs&&(d=e.qs);break;case"ack":d=e.ackId+(e.args&&e.args.length?"+"+s.stringify(e.args):"")}var g=[t,i+("data"==c?"+":""),l];return null!=d&&g.push(d),g.join(":")},i.encodePayload=function(e){var t="";if(1==e.length)return e[0];for(var i=0,n=e.length;i<n;i++)t+="�"+e[i].length+"�"+e[i];return t};var l=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;i.decodePacket=function(e){if(!(o=e.match(l)))return{};var t=o[2]||"",i=(e=o[5]||"",{type:n[o[1]],endpoint:o[4]||""});switch(t&&(i.id=t,o[3]?i.ack="data":i.ack=!0),i.type){case"error":var o=e.split("+");i.reason=r[o[0]]||"",i.advice=a[o[1]]||"";break;case"message":i.data=e||"";break;case"event":try{var c=s.parse(e);i.name=c.name,i.args=c.args}catch(e){}i.args=i.args||[];break;case"json":try{i.data=s.parse(e)}catch(e){}break;case"connect":i.qs=e||"";break;case"ack":if((o=e.match(/^([0-9]+)(\+)?(.*)/))&&(i.ackId=o[1],i.args=[],o[3]))try{i.args=o[3]?s.parse(o[3]):[]}catch(e){}break;case"disconnect":i.reason=e}return i},i.decodePayload=function(e){if("�"==e.charAt(0)){for(var t=[],n=1,r="";n<e.length;n++)"�"==e.charAt(n)?(t.push(i.decodePacket(e.substr(n+1).substr(0,r))),n+=Number(r)+1,r=""):r+=e.charAt(n);return t}return[i.decodePacket(e)]}}(void 0!==n?n:i.exports,void 0!==n?n:i.parent.exports),function(e,t){function i(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=i,t.util.mixin(i,t.EventEmitter),i.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),""!==e){var i=t.parser.decodePayload(e);if(i&&i.length)for(var n=0,r=i.length;n<r;n++)this.onPacket(i[n])}return this},i.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),"heartbeat"==e.type?this.onHeartbeat():("connect"==e.type&&""==e.endpoint&&this.onConnect(),"error"==e.type&&"reconnect"==e.advice&&(this.isOpened=!1),this.socket.onPacket(e),this)},i.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},i.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},i.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},i.prototype.clearCloseTimeout=function(){this.closeTimeout&&(clearTimeout(this.closeTimeout),this.closeTimeout=null)},i.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},i.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},i.prototype.onHeartbeat=function(e){this.packet({type:"heartbeat"})},i.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},i.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},i.prototype.prepareUrl=function(e){var i=this.socket.options;if(i["skipped handshake data"])return i.rewriteUrlForProxy(i["skipped handshake data"].websocketUrl+(e||""));var n=this.scheme()+"://"+i.host+":"+i.port+"/"+i.resource+"/"+t.protocol+"/"+this.name+"/"+this.sessid+(e||"");return i.rewriteUrlForProxy(n)},i.prototype.ready=function(e,t){t.call(this)},i.prototype.clearEventHandlers=function(){return this}}(void 0!==n?n:i.exports,void 0!==n?n:i.parent.exports),function(e,t,i){function n(e){if(this.options={port:80,secure:!1,document:"document"in i&&document,resource:"socket.io",transports:t.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},t.util.merge(this.options,e),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options["sync disconnect on unload"]&&(!this.isXDomain()||t.util.ua.hasCORS)){var n=this;t.util.on(i,"unload",(function(){n.disconnectSync()}),!1)}this.options["auto connect"]&&this.connect()}function r(){}e.Socket=n,t.util.mixin(n,t.EventEmitter),n.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),""!==e&&this.namespaces[e].packet({type:"connect"})),this.namespaces[e]},n.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},n.prototype.handshake=function(e){function i(t){t instanceof Error?n.onError(t.message):e.apply(null,t.split(":"))}var n=this,a=this.options;if(!n.disconnected){var s=a.rewriteUrlForProxy(["http"+(a.secure?"s":"")+":/",a.host+":"+a.port,a.resource,t.protocol,t.util.query(this.options.query,"t="+ +new Date)].join("/"));if(this.isXDomain()&&!t.util.ua.hasCORS){var o=document.getElementsByTagName("script")[0],l=document.createElement("script");l.src=s+"&jsonp="+t.j.length,o.parentNode.insertBefore(l,o),t.j.push((function(e){i(e),l.parentNode.removeChild(l)}))}else{var c=t.util.request();c.open("GET",s,!0);var d=this.options.requestHeaders;void 0!==d&&Object.keys(d).forEach((function(e){c.setRequestHeader(e,d[e])})),c.onreadystatechange=function(){4==c.readyState&&(c.onreadystatechange=r,200==c.status?i(c.responseText):!n.reconnecting&&n.onError(c.responseText))},c.send(null)}}},n.prototype.getTransport=function(e){for(var i,n=e||this.transports,r=0;i=n[r];r++)if(t.Transport[i]&&t.Transport[i].check(this)&&(!this.isXDomain()||t.Transport[i].xdomainCheck()))return new t.Transport[i](this,this.sessionid);return null},n.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var i=this,n=function(n,r,a,s){function o(){if(!i.connected&&!i.disconnected)if(i.connecting=!1,clearTimeout(i.connectTimeoutTimer),i.options["try multiple transports"]){for(;i.remainingTransports.length>0&&i.remainingTransports.splice(0,1)[0]!=i.transport.name;);i.remainingTransports.length?l(i.remainingTransports):i.publish("connect_failed")}else i.publish("connect_failed")}function l(e){if(i.transport&&(i.transport.clearTimeouts(),i.transport.clearEventHandlers()),i.transport=i.getTransport(e),!i.transport||i.disconnected)return i.publish("connect_failed");i.transport.ready(i,(function(){i.connecting=!0,i.publish("connecting",i.transport.name),i.transport.open(o),i.options["connect timeout"]&&(i.connectTimeoutTimer=setTimeout((function(){o()}),i.options["connect timeout"]))}))}i.sessionid=n,i.closeTimeout=1e3*a+2e3,i.heartbeatTimeout=1e3*r+2e3,i.transports=s?t.util.intersect(s.split(","),i.options.transports):i.options.transports,i.setHeartbeatTimeout(),i.remainingTransports=i.transports.slice(0),l(i.transports),i.once("connect",(function(){clearTimeout(i.connectTimeoutTimer),e&&"function"==typeof e&&e()}))};if(this.options["skipped handshake data"]){var r=this.options["skipped handshake data"];n("v4c-"+(new Date).getTime(),r.timeout,r.timeout,"websocket")}else this.handshake(n);return this},n.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},n.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},n.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},n.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of("").packet({type:"disconnect"}),this.onDisconnect("booted")),this.disconnected=!0,this},n.prototype.disconnectSync=function(){var e=t.util.request(),i=this.resource+"/"+t.protocol+"/"+this.sessionid;e.open("GET",i,!0),this.onDisconnect("booted")},n.prototype.isXDomain=function(){var e=i.location.port||("https:"==i.location.protocol?443:80);return this.options.host!==i.location.hostname||this.options.port!=e},n.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit("connect"))},n.prototype.onOpen=function(){this.open=!0},n.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},n.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},n.prototype.onError=function(e){e&&e.advice&&"reconnect"===e.advice&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish("error",e&&e.reason?e.reason:e)},n.prototype.onDisconnect=function(e){var t=this.connected,i=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||i)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish("disconnect",e),"booted"!=e&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish("close_during_connecting",e))},n.prototype.reconnect=function(){function e(){if(i.connected){for(var e in i.namespaces)i.namespaces.hasOwnProperty(e)&&""!==e&&i.namespaces[e].packet({type:"connect"});i.publish("reconnect",i.transport.name,i.reconnectionAttempts)}clearTimeout(i.reconnectionTimer),i.removeListener("connect_failed",t),i.removeListener("connect",t),i.reconnecting=!1,delete i.reconnectionAttempts,delete i.reconnectionDelay,delete i.reconnectionTimer,delete i.redoTransports,i.options["try multiple transports"]=r}function t(){if(i.reconnecting)return i.connected?e():i.connecting&&i.reconnecting?i.reconnectionTimer=setTimeout(t,1e3):void(i.reconnectionAttempts++>=n?i.redoTransports?(i.publish("reconnect_failed"),e()):(i.on("connect_failed",t),i.options["try multiple transports"]=!0,i.transport=i.getTransport(),i.redoTransports=!0,i.connect()):(i.reconnectionDelay<a&&(i.reconnectionDelay*=2),i.connect(),i.publish("reconnecting",i.reconnectionDelay,i.reconnectionAttempts),i.reconnectionTimer=setTimeout(t,i.reconnectionDelay)))}this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options["reconnection delay"];var i=this,n=this.options["max reconnection attempts"],r=this.options["try multiple transports"],a=this.options["reconnection limit"];this.options["try multiple transports"]=!1,this.reconnectionTimer=setTimeout(t,this.reconnectionDelay),this.on("connect",t)}}(void 0!==n?n:i.exports,void 0!==n?n:i.parent.exports,void 0===e?window:e),function(e,t){function i(e,t){this.socket=e,this.name=t||"",this.flags={},this.json=new n(this,"json"),this.ackPackets=0,this.acks={}}function n(e,t){this.namespace=e,this.name=t}e.SocketNamespace=i,t.util.mixin(i,t.EventEmitter),i.prototype.$emit=t.EventEmitter.prototype.emit,i.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},i.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},i.prototype.send=function(e,t){var i={type:this.flags.json?"json":"message",data:e};return"function"==typeof t&&(i.id=++this.ackPackets,i.ack=!0,this.acks[i.id]=t),this.packet(i)},i.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),i=t[t.length-1],n={type:"event",name:e};return"function"==typeof i&&(n.id=++this.ackPackets,n.ack="data",this.acks[n.id]=i,t=t.slice(0,t.length-1)),n.args=t,this.packet(n)},i.prototype.disconnect=function(){return""===this.name?this.socket.disconnect():(this.packet({type:"disconnect"}),this.$emit("disconnect")),this},i.prototype.onPacket=function(e){function i(){n.packet({type:"ack",args:t.util.toArray(arguments),ackId:e.id})}var n=this;switch(e.type){case"connect":this.$emit("connect");break;case"disconnect":""===this.name?this.socket.onDisconnect(e.reason||"booted"):this.$emit("disconnect",e.reason||"");break;case"message":case"json":var r=["message",e.data];"data"==e.ack?r.push(i):e.ack&&this.packet({type:"ack",ackId:e.id}),this.$emit.apply(this,r);break;case"event":r=[e.name].concat(e.args),"data"==e.ack&&r.push(i),this.$emit.apply(this,r);break;case"ack":this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case"error":e.advice?this.socket.onError(e):"unauthorized"==e.reason?this.$emit("connect_failed",e.reason):this.$emit("error",e.reason)}},n.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},n.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(void 0!==n?n:i.exports,void 0!==n?n:i.parent.exports),function(e,t,i){function n(e){t.Transport.apply(this,arguments)}function r(){}e.websocket=n,t.util.inherit(n,t.Transport),n.prototype.name="websocket",n.prototype.open=function(e){var n,r=t.util.query(this.socket.options.query),a=this;return this.connectErrorCallback=e,n||(n=i.MozWebSocket||i.WebSocket),this.websocket=new n(this.prepareUrl(r)),this.websocket.onopen=function(){a.onOpen(),a.socket.setBuffer(!1)},this.websocket.onmessage=function(e){a.onData(e.data)},this.websocket.onclose=function(){a.onClose(),a.socket.setBuffer(!0)},this.websocket.onerror=function(e){a.onError(e)},this},n.prototype.send=function(e){return this.websocket.send(e),this},n.prototype.payload=function(e){for(var t=0,i=e.length;t<i;t++)this.packet(e[t]);return this},n.prototype.close=function(){return this.websocket.close(),this},n.prototype.onError=function(e){void 0!==this.connectErrorCallback&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},n.prototype.scheme=function(){return this.socket.options.secure?"wss":"ws"},n.check=function(){return"WebSocket"in i&&!("__addTask"in WebSocket)||"MozWebSocket"in i},n.xdomainCheck=function(){return!0},n.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=r),this},t.transports.push("websocket")}(void 0!==n?n.Transport:i.exports,void 0!==n?n:i.parent.exports,void 0===e?window:e),function(e,t,i){function n(e){e&&t.Transport.apply(this,arguments)}function r(){}e.XHR=n,t.util.inherit(n,t.Transport),n.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},n.prototype.payload=function(e){for(var i=[],n=0,r=e.length;n<r;n++)i.push(t.parser.encodePacket(e[n]));this.send(t.parser.encodePayload(i))},n.prototype.send=function(e){return this.post(e),this},n.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request("POST"),i.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=r,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=r,200==this.status?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},n.prototype.close=function(){return this.onClose(),this},n.prototype.request=function(e){var i=t.util.request(this.socket.isXDomain()),n=t.util.query(this.socket.options.query,"t="+ +new Date);i.open(e||"GET",this.prepareUrl(n),!0);var r=this.socket.options.requestHeaders;if(void 0!==r&&Object.keys(r).forEach((function(e){i.setRequestHeader(e,r[e])})),"POST"==e)try{i.setRequestHeader?i.setRequestHeader("Content-type","text/plain;charset=UTF-8"):i.contentType="text/plain"}catch(e){}return i},n.prototype.scheme=function(){return this.socket.options.secure?"https":"http"},n.check=function(e,n){try{var r=t.util.request(n),a=i.XDomainRequest&&r instanceof XDomainRequest,s=(e&&e.options&&e.options.secure?"https:":"http:")!=i.location.protocol;if(r&&(!a||!s))return!0}catch(e){}return!1},n.xdomainCheck=function(){return n.check(null,!0)},n.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=r),this}}(void 0!==n?n.Transport:i.exports,void 0!==n?n:i.parent.exports,void 0===e?window:e),function(e,t,i){function n(){t.Transport.XHR.apply(this,arguments)}function r(){}e["xhr-polling"]=n,t.util.inherit(n,t.Transport.XHR),t.util.merge(n,t.Transport.XHR),n.prototype.name="xhr-polling",n.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},n.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),i.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=r,this.onerror=r,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),void 0!==e.connectErrorCallback&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){4==this.readyState&&(this.onreadystatechange=r,200==this.status?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),void 0!==e.connectErrorCallback&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},n.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r;try{this.xhr.abort()}catch(e){}this.xhr=null}},n.prototype.ready=function(e,i){var n=this;t.util.defer((function(){i.call(n)}))},n.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=r),this},t.transports.push("xhr-polling")}(void 0!==n?n.Transport:i.exports,void 0!==n?n:i.parent.exports,void 0===e?window:e),t.io=n}).call(t,i(13),i(14)(e))},function(e,t){var i;i=function(){return this}();try{i=i||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(i=window)}e.exports=i},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var n,r=i(3),a=i(1),s=i(0),o=function(e){this.id=e,this.status=200,this.headers={},this.body=""};t.ResponseData=o,function(e){e.Connected="trouter_js_client_connected",e.Disconnected="trouter_js_client_disconnected",e.Error="trouter_js_client_error",e.Progress="trouter_js_client_progress",e.Response="trouter_js_client_response",e.Request="trouter_js_client_request",e.CheckConnection="trouter_js_client_check_connection",e.Registration="trouter_js_client_registration",e.Unregistration="trouter_js_client_unregistration"}(n||(t.ClientEventName=n={}));var l=function(e,t,i,n,r){this.stepName=e,this.operation=t,this.delta=i,this.ts=n,this.error=r};t.TrackerStep=l;var c=function(){};t.Properties=c;var d=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType="",this.connectionNumber=0},u=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0},h=function(){function e(e,t,i,n,a,o,l){this.clientId=t,this.clientInfo=i,this.getServerState=n,this.endpointId=a,this.clientCorrelationID=o,this.environment=l,this.logger=new s.Logger("ConnectionTracker",e),this.clientCorrelationID=void 0!==o?o:"",this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new r.Timespan,this.eventLogSettings=new u,this.connectedInfo=new d}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(n.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){void 0!==this.progressTimeout&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),void 0!==this.eventLogSettings.sendProgressTimeoutSecs&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:"timeout",timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=""},e.prototype.copyProperties=function(e,t){for(var i=0,n=Object.keys(t);i<n.length;i++){var r=n[i];void 0!==t[r]&&(e[r.replace(/-/g,"_")]={value:t[r]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,i){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&void 0!==this.eventLogger){var n=this.getServerState(),s={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,r.toJson)(i)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:a.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:n.connectionId},connectedClientId:{value:n.connectedClientId},domId:{value:n.domId},url:{value:n.unsecureUrl},surl:{value:n.url},ttlInSecs:{value:n.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(s.properties,t),this.eventLogger.logEvent(s)}}catch(t){this.logger.warn("error in sending event ".concat(e,": ").concat((0,r.toJson)(t)))}},e.prototype.createStep=function(e,t,i){return new l(e,t,this.beginTimestamp.duration,Date.now(),i)},e.prototype.addStep=function(e,t,i){if(!1!==this.eventLogSettings.enabled&&(0===this.steps.length&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,i)),++this.totalStepCount,void 0!==this.eventLogSettings.numberOfStepsToMaintain&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var r=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(n.Progress,{reason:"flush"},r)}},e.prototype.trackStart=function(e){this.addStep(e,"start")},e.prototype.trackEnd=function(e){this.addStep(e,"end")},e.prototype.trackError=function(e,t,i,r){void 0===i&&(i=!0),"health"===e&&!0!==this.eventLogSettings.logHealthCheckError||"ping"===e&&!1===this.eventLogSettings.logSendPingError||(void 0===r&&(r="error"),!0===i&&this.addStep(e,r,t),this.sendTelemetry(n.Error,{},[this.createStep(e,r,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var i=this.steps.slice(0),r=this.totalStepCount,a=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(n.Connected,{stepCount:i.length,totalStepCount:r,connectionEstablishmentMs_Total:a},i),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(n.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackRequest=function(e,t){var i={};void 0!==t&&(i.hasError=!0,i.error=t);try{if(e){i.requestID=e.id,i.httpMethod=e.method,i.url=e.url,i.bodyLength=e.body.length,i.shortUrl=e.shortUrl,i.requestTimeStamp=e.startTS,i.correlationVector=e.correlationVector;for(var a=e.headers,s=0,o=Object.keys(a);s<o.length;s++){var l=o[s];i[l]=a[l]}}}catch(e){i.hasError=!0,i.error="".concat(i.error," error creating request context ").concat((0,r.toJson)(e))}this.sendTelemetry(n.Request,i,[])},e.prototype.trackResponse=function(e,t,i,a){var s={};void 0!==a&&(s.hasError=!0,s.error=a);try{if(s.responseTimestamp=void 0!==i?i.sentTS:Date.now(),e){s.requestID=e.id,s.httpMethod=e.method,s.shortUrl=e.shortUrl,s.correlationVector=e.correlationVector;for(var o=e.headers,l=0,c=Object.keys(o);l<c.length;l++){var d=c[l];s[d]=o[d]}}i&&(s.latencyMS=t,s.responseCode=i.status,s.responseLength=i.body.length)}catch(e){s.hasError=!0,s.error="".concat(s.error," error creating response context ").concat((0,r.toJson)(e))}this.sendTelemetry(n.Response,s,[])},e.prototype.sendResponseError=function(e,t,i){this.trackResponse(t,void 0,i,e)},e.prototype.close=function(){this.sendProgress({reason:"closed"}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,void 0!==e.numberOfStepsToMaintain?e.numberOfStepsToMaintain:0));var t=Math.min(3600,Math.max(55,void 0!==e.sendProgressTimeoutSecs?e.sendProgressTimeoutSecs:0));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var i=0,r=Object.keys(n).map((function(e){return n[e]}));i<r.length;i++){var a=r[i];void 0!==e[a]&&(this.eventLogSettings[a]=e[a])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}();t.ConnectionTracker=h},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0;var n=function(){function e(e,t,i){this.reason=e,this.claims=t,this.details=i}return e.fromRawReason=function(t,i){if(""===t||"dup"===t)return new e(t);try{var n=JSON.parse(t);return"object"!=typeof n||void 0===n.reason?(null==i||i.error("invalid disconnect reason format"),new e("unknown",void 0,t)):new e(n.reason,n.claims,n.details)}catch(i){return new e("disconnect",void 0,t)}},e.fromSocketIoEventData=function(t,i){return"string"==typeof i?new e(t,void 0,i):void 0},e.prototype.toTelemetryString=function(){return"socketerror"===this.reason||"reconnecterror"===this.reason||"disconnect"===this.reason?this.details:this.reason},e}();t.DisconnectReason=n},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0;var n=function(){function e(e,t,i){void 0===i&&(i={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=i,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var i=1+.4*(Math.random()-.5),n=1e3*Math.pow(2,e)*i;return n=Math.round(n),Math.min(t,n)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,i){var n=this;if(void 0!==this.timerHandle&&(this.logger.debug("Clearing current back off"),clearTimeout(this.timerHandle),this.timerHandle=void 0),void 0!==this.previousCompleteTime){var r=Date.now()-this.previousCompleteTime;r>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&r>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info("Back off for ".concat(t," with ID ").concat(this.backoffId," will be reset due to a lot of time having passed since the previous backoff (").concat(r," ms)")),this.backoffCount=0,this.previousCompleteTime=void 0)}var a=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info("Backing off ".concat(t," for ").concat(a," milliseconds with ID ").concat(this.backoffId)),this.callback=function(e,r){(function(e,t,i){if(void 0===e||void 0===t)return!1;var n=Date.now()-e;return n>t*i.tolerance&&n>i.minimumWaitMs})(e,r,n.gapDetectionSettings)&&(n.logger.info("Back off for ".concat(t," with ID ").concat(n.backoffId," will be reset due to the wait (").concat(Date.now()-(null!=e?e:0)," ms) being longer than expected (").concat(r," ms)")),n.backoffCount=0),n.logger.info("Back off for ".concat(t," with ID ").concat(n.backoffId," complete, invoking handler")),n.timerHandle=void 0,n.callback=void 0,n.previousCompleteTime=Date.now(),i()};var s=Date.now();this.timerHandle=setTimeout((function(){var e;return null===(e=n.callback)||void 0===e?void 0:e.call(n,s,a)}),a)},e.prototype.reset=function(){void 0!==this.timerHandle&&(this.logger.debug("Resetting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},e.prototype.expediteIfPending=function(){if(this.backoffCount=0,void 0!==this.timerHandle){this.logger.debug("Expediting back off with ID ".concat(this.backoffId)),clearTimeout(this.timerHandle),this.timerHandle=void 0;var e=this.callback;this.callback=void 0,e&&e()}},e}();t.ExponentialBackoff=n},function(e,t,i){var n=this&&this.__spreadArray||function(e,t,i){if(i||2===arguments.length)for(var n,r=0,a=t.length;r<a;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var r=i(6),a=function(){function e(e,t,i){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=i,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,i){this.passIfRegisteredOrNotNeeded("onDownstreamRequest",e,t,i)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded("onConnected",e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){this.isRegistered=!1,this.wrapped.onUnregistered(e),e.getState()===r.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,i){this.wrapped.onReconnectIsRequired(e,t,i)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded("onTrouterMessageLost",e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded("onUserActivityStateAccepted",e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded("onAudiencesSetResolved",e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,i=[],r=1;r<arguments.length;r++)i[r-1]=arguments[r];var a=this.shouldConnectionDependOnRegistration(),s=this.shouldHoldBackEvents();a&&s||this.fireHeldBackEvents(a?function(e){return"onConnected"!==e.kind}:void 0),this.isRegistered||!a||!1===s&&"onConnected"!==e?(t=this.wrapped)[e].apply(t,i):this.holdBackEvent.apply(this,n([e],i,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,i=0,n=this.heldBackEvents;i<n.length;i++){var r=n[i];(void 0===e||e(r))&&(t=this.wrapped)[r.kind].apply(t,r.args)}this.heldBackEvents=void 0===e?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}();t.RegistrationEnforcer=a;var s=function(){function e(e,t,i,n){this.wrapped=e,this.prefix=t,this.logger=i,this.onEventAction=n}return e.prototype.onEvent=function(e,t){var i;void 0!==this.onEventAction?this.onEventAction(e,t):(null!==(i=this.logger)&&void 0!==i?i:console).log("".concat(this.prefix," TracingEnforcer: ").concat(e,"(").concat(t,")"))},e.prototype.onDownstreamRequest=function(e,t,i){this.onEvent("onDownstreamRequest",JSON.stringify({request:t,response:i})),this.wrapped.onDownstreamRequest(e,t,i)},e.prototype.onConnected=function(e){this.onEvent("onConnected",e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent("onRegistered",e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent("onUnregistered",e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent("onReconnecting",e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,i){this.onEvent("onReconnectIsRequired",JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:i})),this.wrapped.onReconnectIsRequired(e,t,i)},e.prototype.onDisconnected=function(e){this.onEvent("onDisconnected",e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent("onTerminalError",JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent("onConnectionParametersUpdated",JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent("onTrouterMessageLost",JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent("onUserActivityStateAccepted",JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent("onAudiencesSetResolved",JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}();t.LoggingManagerConsumer=s},function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var n=i(2),r=i(4),a=i(0),s=i(7),o=function(){function e(e,t){this.worker=t,this.state=r.TrouterManagerState.Unknown,this.logger=new a.Logger("ManagerFsm",e)}return e.prototype.start=function(){this.state===r.TrouterManagerState.Unknown?(this.setState(r.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info("start called in state '".concat(r.TrouterManagerState[this.state],"', expediting pending backoffs, if any")),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state!==r.TrouterManagerState.Unknown?(this.setState(r.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e)):this.showIgnored("stop")},e.prototype.getState=function(){switch(this.state){case r.TrouterManagerState.Unknown:case r.TrouterManagerState.Connected:case r.TrouterManagerState.Disconnected:case r.TrouterManagerState.Switching:return this.state;case r.TrouterManagerState.TerminalError:return n.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===r.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(r.TrouterManagerState.Switching):(this.setState(r.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored("onConnected(".concat(e,")"))},e.prototype.onRegistered=function(e){this.state!==r.TrouterManagerState.Disconnected||e?this.state!==r.TrouterManagerState.Switching||e?this.state===r.TrouterManagerState.Disconnected&&e&&(this.setState(r.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(r.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(r.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==r.TrouterManagerState.Connected&&this.state!==r.TrouterManagerState.Switching||!e?this.showIgnored("onReconnecting(".concat(e,")")):(this.setState(r.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,i){this.state===r.TrouterManagerState.Connected&&e?(this.setState(r.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===r.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===r.TrouterManagerState.Switching&&e&&i===s.ReconnectReason.Configuration?(this.logger.debug("onReconnectionRequired: switch requested while already in Switching state"),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored("onReconnectionRequired(".concat(e,")"))},e.prototype.onDisconnected=function(e){this.state==r.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==r.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(r.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored("onDisconnected(".concat(e,")"))},e.prototype.onTerminalError=function(){this.setState(r.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info("Ignoring event '".concat(e,"' in state '").concat(r.TrouterManagerState[this.state],"'"))},e.prototype.setState=function(e){this.logger.info("Switching from state '".concat(r.TrouterManagerState[this.state],"' to state '").concat(r.TrouterManagerState[e],"'")),this.state!==e?this.state=e:this.logger.error("Attempt to switch to the current state '".concat(r.TrouterManagerState[e],"'"))},e}();t.TrouterManagerFsm=o},function(e,t,i){function n(e,t){if(!t)return e;var i=a(a({},e),{enabled:t.TelemetryEnabled});return void 0!==t.ClientTelemetryEventEnabled&&(i=a(a({},i),t.ClientTelemetryEventEnabled)),i}function r(e,t,i){var r,s,o,l,c,d,u,h,p,g,m=function(i){return e.proxyUrlRewrite?(t.info("Using rewritten URL for proxy"),e.proxyUrlRewrite(i)):i};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:m},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:n(e.telemetryConfig.settings,i),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:(null==i?void 0:i.TrouterConnectionUrl)||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl?{registrarUrl:e.trouterSettings.registrarServiceUrl,registrationId:null!==(r=e.trouterSettings.registrationId)&&void 0!==r?r:"",pnhAppId:null!==(s=e.trouterSettings.pnhAppId)&&void 0!==s?s:"",platform:null!==(o=e.trouterSettings.platform)&&void 0!==o?o:"",pnhTemplateKey:null!==(l=e.trouterSettings.pnhTemplate)&&void 0!==l?l:"",platformUIVersion:null!==(c=e.trouterSettings.platformUIVersion)&&void 0!==c?c:"",productContext:e.trouterSettings.pnhProductContext||void 0,context:null!==(d=e.trouterSettings.pnhContext)&&void 0!==d?d:"",registrarTtlSec:(null!==(u=e.trouterSettings.maxRegistrationTimeInMs)&&void 0!==u?u:0)/1e3}:void 0,connectionDependsOnRegistration:void 0===e.trouterSettings.registrarServiceUrl?function(){return!1}:null!==(h=e.trouterSettings.connectionDependsOnRegistration)&&void 0!==h?h:function(){return!1},delayEventsUntilRegistered:null!==(p=e.trouterSettings.delayEventsUntilRegistered)&&void 0!==p?p:function(){return!1},timeoutOptions:a({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:"TeamsCDL"===e.trouterSettings.productName?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:a({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:"TeamsCDL"===e.trouterSettings.productName?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:null!==(g=e.trouterSettings.incallModeTimeoutMs)&&void 0!==g?g:0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:m,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,toJSON:function(){return a(a({},this),{connectionCache:this.connectionCache?{}:this.connectionCache})}}}var a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},a.apply(this,arguments)},s=this&&this.__awaiter||function(e,t,i,n){function r(e){return e instanceof i?e:new i((function(t){t(e)}))}return new(i||(i=Promise))((function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){e.done?i(e.value):r(e.value).then(s,o)}l((n=n.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){function i(e){return function(t){return n([e,t])}}function n(i){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,i[0]&&(l=0)),l;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return l.label++,{value:i[1],done:!1};case 5:l.label++,a=i[1],i=[0];continue;case 7:i=l.ops.pop(),l.trys.pop();continue;default:if(!(s=(s=l.trys).length>0&&s[s.length-1])&&(6===i[0]||2===i[0])){l=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){l.label=i[1];break}if(6===i[0]&&l.label<s[1]){l.label=s[1],s=i;break}if(s&&l.label<s[2]){l.label=s[2],l.ops.push(i);break}s[2]&&l.ops.pop(),l.trys.pop();continue}i=t.call(e,l)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}var r,a,s,o,l={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return o={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o};Object.defineProperty(t,"__esModule",{value:!0}),t.replaceTrouterUrlBase=t.getTrouterServiceVersion=t.createTrouterService=t.TrouterService=t.UserActivityState=t.TrouterState=void 0;var l=i(1),c=i(2);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return c.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return c.UserActivityState}});var d=i(0),u=i(8),h=i(9),p=i(10),g=i(11),m=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new d.Logger("Trouter",e),this.trouterUrlPromise=new g.TrouterUrlPromise(e),this.messageHandlers=new u.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info("Created TrouterService version ".concat(l.CLIENT_VERSION))}return e.prototype.start=function(e){var t;if(this.logger.info("Start"),!e.skypeTokenProvider&&!e.authTokenProvider)throw new Error("no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated");e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,h.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var i=r(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(i.forceV4aProtocol=!0);var n=function(e,t){var i,n=this;return function(r){return s(n,void 0,void 0,(function(){var n,a,s;return o(this,(function(o){switch(o.label){case 0:n=new Date,a=setInterval((function(){var t=Math.round((Date.now()-n.getTime())/6e4);e.warn("Note: Trouter auth token request promise from ".concat(n.toISOString()," has not been resolved for ").concat(t," minutes. The client is blocked from operating properly"))}),3e5),o.label=1;case 1:return o.trys.push([1,,3,4]),[4,t(r)];case 2:return s=o.sent(),r.needFresh&&s.token===i&&e.error("API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app"),i=s.token,[2,s];case 3:return clearInterval(a),[7];case 4:return[2]}}))}))}}(this.logger,null!==(t=e.authTokenProvider)&&void 0!==t?t:function(e){var t=this;return function(i){return s(t,void 0,void 0,(function(){var t;return o(this,(function(n){switch(n.label){case 0:return t={},[4,e(i.needFresh)];case 1:return[2,(t.token=n.sent(),t.tokenType="skype",t)]}}))}))}}(e.skypeTokenProvider));void 0===this.trouterServer&&(this.trouterServer=new p.TrouterManager(this.logProvider,i,n,void 0===e.authTokenProvider,this)),void 0!==this.pendingActivityState&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info("close connection"),this.trouterUrlPromise.rejectUrl(new Error("TrouterService is stopped")),void 0!==this.trouterServer&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return s(this,void 0,void 0,(function(){var t=this;return o(this,(function(i){return[2,new Promise((function(i){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info("Setting ECS configuration to ".concat(JSON.stringify(t.ecsCfg))),void 0!==t.trouterServer&&void 0!==t.trouterCfg){var n=r(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(n)}i()}))]}))}))},e.prototype.checkConnection=function(e){void 0!==this.trouterServer&&this.trouterServer.checkConnection(null!=e&&e)},e.prototype.resendRegistration=function(){return s(this,void 0,void 0,(function(){return o(this,(function(e){if(!this.trouterServer)throw new Error("resendRegistration called too early");return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerListener=function(e,t){return""===t||!t.startsWith("/")||t.includes("?")||t.includes("#")?(this.logger.error("Listener path '".concat(t,"' is not valid")),!1):this.listeners[t]?(this.logger.error("Another listener is already registered for path '".concat(t,"'")),!1):(this.listeners[t]=e,this.logger.debug("Listener for path '".concat(t,"' registered")),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i];this.listeners[r]===e&&t.push(r)}if(0===t.length)return!1;for(var a=0,s=t;a<s.length;a++)r=s[a],delete this.listeners[r];return this.logger.debug("Listener for path(s) '".concat(t.join("', '"),"' unregistered")),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug("Trouter is now connected");for(var i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i];try{this.listeners[r].onTrouterConnected(t.baseEndpointUrl+r,t)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onTrouterConnected(): ").concat(e))}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(c.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug("Trouter is now disconnected"),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var i=t[e],n=this.listeners[i];if(n.onTrouterDisconnected)try{n.onTrouterDisconnected()}catch(e){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterDisconnected(): ").concat(e))}}this.notifyStateChanged(c.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var i="",n=0,r=Object.keys(this.listeners);n<r.length;n++){var a=r[n];e.path.startsWith(a)&&a.length>i.length&&(i=a)}if(""===i)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":"ClientLib"},t.send());else try{this.listeners[i].onTrouterRequest(e,t)}catch(e){this.logger.error("Listener '".concat(i,"' threw an exception from onTrouterRequest(): ").concat(e)),t.status=500,t.headers={"Trouter-Responder":"ClientLib"},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info("onTrouterMessageLoss called with tags [".concat(e,"]"));for(var t=!0,i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i],a=this.listeners[r];if(a.onTrouterMessageLoss)try{void 0===(t=a.onTrouterMessageLoss(e)&&t)&&(this.logger.error("Listener '".concat(r,"' did not return a boolean value from onTrouterMessageLoss()")),t=!1)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onTrouterMessageLoss(): ").concat(e)),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug("onTrouterUserActivityStateAccepted cv: ".concat(e));for(var t=0,i=Object.keys(this.listeners);t<i.length;t++){var n=i[t],r=this.listeners[n];if(r.onTrouterUserActivityStateAccepted)try{r.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error("Listener '".concat(n,"' threw an exception from onTrouterUserActivityStateAccepted(): ").concat(e))}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug("onAudiencesSetResolved cv: ".concat(t));for(var i=0,n=Object.keys(this.listeners);i<n.length;i++){var r=n[i],a=this.listeners[r];if(a.onAudiencesSetResolved)try{a.onAudiencesSetResolved(e,t)}catch(e){this.logger.error("Listener '".concat(r,"' threw an exception from onAudienceSubscribed(): ").concat(e))}}},e.prototype.setUserActivityState=function(e,t){if(e!==c.UserActivityState.Active&&e!==c.UserActivityState.Inactive)throw new Error("setUserActivityState called with unsupported value ".concat(e));this.logger.info("setUserActivityState called with value ".concat(c.UserActivityState[e])),this.trouterServer&&this.state()!==c.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn("setUserActivityState called before start() or after stop()"))},e.prototype.setAudienceSubscriptions=function(e,t){if(e.audienceSubscriptions.length>1)throw new Error("Only singular audience subscription is supported");if(this.trouterServer&&this.state()!==c.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw new Error("audience subscribe called before start() or after stop()")},e.prototype.state=function(){return void 0!==this.trouterServer?this.trouterServer.getState():c.TrouterState.Unknown},e.prototype.isInTerminalState=function(){return void 0!==this.trouterServer&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return void 0===this.trouterServer?"":this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(void 0!==this.trouterServer)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return void 0!==this.trouterServer?this.trouterUrlPromise.getPromise():Promise.reject(new Error("TrouterService has not been started"))},e.prototype.onStateChanged=function(e){if(this.logger.info("onStateChanged called"),void 0===e)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return void 0===e.wrappedCallback}));else{this.offStateChanged(e);var t=function(t,i){e(t,i?i.url:"")};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info("offStateChanged called");var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info("addListener called"),-1===this.stateChangedListeners.indexOf(e,0)&&void 0!==e&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info("removeListener called");var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info("registerMessageHandler is called"),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info("clearMessageHandlers is called"),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var i=this;this.logger.info("notifyStateChanged called, will forward to ".concat(this.stateChangedListeners.length," listeners")),this.stateChangedListeners.forEach((function(n){try{n(e,t)}catch(e){i.logger.error("Error in callback ".concat(e))}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var i,n=null;try{n=(i=JSON.parse(e.body))&&(i.evt||i.eventId)||null}catch(e){}var r={eventId:n,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:"")+e.path,body:i,rawBody:e.body,headers:e.headers},a=this.messageHandlers.handleMessage(r);return!!a.isHandled&&(t.status=a.resultCode,a.responseHeaders&&(t.headers=a.responseHeaders),a.responseBody&&(t.body=a.responseBody),t.send(),!0)},e}();t.TrouterService=m,t.createTrouterService=function(e){return new m(e)},t.getTrouterServiceVersion=function(){return l.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var i=e.indexOf("://");if(i>=0){var n=e.indexOf("/",i+3);if(n>=0)return t+e.substr(n)}return""}},function(t,i){t.exports=e}])},e.exports=i(V_)}));class $_{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:"708a9eb9fe2646fe8f4c37b7eee2e3da-9b97485a-57b9-43a8-8177-07ca7a653a30-6706",properties:{...e.properties}})},this._logger=e.createChild("TelemetrySender"),this._telemetryLogManager=t}}class G_{constructor(e,t,i,n,r){this._ecsProvider=t,this._tokenProvider=i,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild("Trouter"),this._logger.info("init"),this._initialRegistrationCompleteDefer=kh(),this._telemetryLogManager=n,this._acsProxy=r}async start(e){let t;if(this._trouterService)throw this._logger.error("Trouterservice already initialized"),new b({defaultError:f.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{const i=new Promise((async(t,i)=>{try{if(this._logger.info("Trouterservice start"),this._trouterService=H_.createTrouterService(this._logger),!this._trouterService)throw this._logger.error("Failed to create trouter service"),new b({defaultError:f.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||"",this._options.trouterSettings.sessionId=e.sessionId);let i,n,r=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===H_.TrouterState.Connected&&(i=+new Date)})),await this._initialRegistrationCompleteDefer.promise;const a=+new Date;i=i??+new Date,n=i,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,i-r),registrarRequestCompletionTimeDeltaMs:Math.max(0,a-n)})}catch(e){i(e)}}));try{const e=Lh((()=>i),25e3);t=await e}catch(e){throw 408===e.code?(this._logger.error("Signaling init timeout"),new b({defaultError:f.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[25e3]})):(this._logger.error("Signaling init failed"),new b({defaultError:f.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info("TrouterService onRegisteredChanged"),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){const t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info("Trouterservice stop"),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error("Trouterservice not inited")}registerMessageHandler(e){this._logger.info("Trouterservice registerMessageHandler"),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info("Trouterservice state"),this._trouterService?this._trouterService.state():H_.TrouterState.Unknown}onStateChanged(e){this._logger.info("Trouterservice onStateChanged"),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info("Trouterservice offStateChanged"),this._trouterService&&this._trouterService.offStateChanged(e)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info("getTrouterUrlAsync called"),this._trouterService.getTrouterUrlAsync()):Promise.reject("Trouterservice not started yet")}_getSettings(){return{registrationId:x(),registrarServiceUrl:this._ecsProvider.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:this._ecsProvider.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:this._ecsProvider.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:this._ecsProvider.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:this._ecsProvider.getTrouterSettings().pnhAppId,pnhTemplate:this._ecsProvider.getTrouterSettings().pnhTemplate,platform:this._ecsProvider.getTrouterSettings().platform,platformUIVersion:this._ecsProvider.getTrouterSettings().version,trouterServiceUrl:this._ecsProvider.getTrouterSettings().trouterServiceUrl,version:this._ecsProvider.getTrouterSettings().version,trouterConnectTimeoutInMs:this._ecsProvider.getTrouterSettings().trouterConnectTimeoutInMs,productName:this._ecsProvider.getTrouterSettings().productName,sessionId:x(),environment:this._ecsProvider.getTrouterSettings().environment,timeoutOptions:this._ecsProvider.getTrouterSettings().timeoutOptions}}_createTrouterTelemetryConfig(e){return{eventLogger:new $_(e.createChild("TrouterTelemetry"),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info("Signaling service is currently registered"):this._logger.error("Signaling service is currently not registered. Unable to receive incoming calls"),this._onRegisteredChanged(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}}class j_{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:pl,skypecosi_concore_web_ts_calling_in_call_session:pl,skypecosi_concore_web_ts_calling_call_setup_session:pl,skypecosi_concore_native_ts_calling_in_call_session:pl,skypecosi_concore_native_ts_calling_call_setup_session:pl,skypecosi_concore_web_pluginless_call_session:pl,skypecosi_concore_web_pluginless_modality_session:pl,skypecosi_concore_web_csa_conversation_callmodality:pl,skypecosi_concore_web_ts_calling_registry:pl,mdsc_webrtc_session:gl,mdsc_webrtc_session_initial:gl,live_events:"2efdf03d07594586a5977c404e185186-71b046c4-f48f-4ba7-96d3-2a74b54e1d46-7326",mdsc_ortc_reports:gl,mdsc_ortc_reports_initial:gl,mdsc_rt_log:gl},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:"",this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}}class z_{constructor(e,t,i,n,r,a=!0,s,o,l,c){this.configType=e,this.caConfigBag=t,this.queryParameters=i,this.ecsConfigReceiver=n,this.platformId=r,this.isAppInitiallyInForeground=a,this.userRawSkypeToken=s,this.userSkypeTokenExpiration=o,this.projectName=l,this.ecsHosts=c}}class W_{constructor(){this._timedVideoEffectProviderPromise=Ac(3e3),this._timedModelConfigPromise=Ac(3e3)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:"",weightPathPrefix:""}),this._timedModelConfigPromise.deferredPromise.promise}}class q_{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}}class K_{constructor(e,t){this.logger=e,this.proxy=t}getRequestOptions(e,t,i,n,r){return{headers:t||{},timeout:n,payload:i||null,responseType:r}}getAsync(e,t){return this.sendRequest(this.proxy.proxyfyUrl(e),t,"GET")}postAsync(e,t){return this.sendRequest(this.proxy.proxyfyUrl(e),t,"POST")}putAsync(e,t){return this.sendRequest(this.proxy.proxyfyUrl(e),t,"PUT")}removeAsync(e,t){return this.sendRequest(this.proxy.proxyfyUrl(e),t,"DELETE")}async sendRequest(e,t={headers:{}},i){const n=this.logger.createChild(`[${t.causeId||x()}][Request]`);n.info(`sending, ${i}-${e}`);const r=Date.now();let a;t.headers=t.headers||{},t.headers["content-type"]||(t.headers["content-type"]=t.contentType||"application/json");try{const s=Uy.request({url:e,method:i,headers:t.headers||{},timeout:"number"==typeof t.timeout?t.timeout:45e3,data:t.payload||"",responseType:t.responseType||t.dataType||"json",withCredentials:mc(t.withCredentials,!1),cancelToken:new Uy.CancelToken((e=>{a=e}))});(function(e){return!!e&&"function"==typeof e.then})(t.timeout)&&t.timeout.then((()=>{n.info("Aborting pending request"),a()}),(()=>{n.info("Timeout promise rejected, ignoring")}));const o=await s;return n.info(`success, status=${o.status}`),{response:o.data,request:o.request,duration:Date.now()-r}}catch(e){if(n.info("failed"),Uy.isCancel(e))throw n.info(`response=${fc(e.response)}`),{aborted:!0};throw e.response?n.info(`response=${fc(e.response)}`):e.request?n.info(`no response, request=${fc(e.request)}`):n.info(`request not made, error=${fc(e)}`),e||new Error("Request failed")}}}class J_{constructor(){this._activeEffects=[],this.eventEmitter=new Kp.EventEmitter}on(e,t){if("statusChanged"!==e)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("statusChanged"!==e)throw new b({defaultError:f.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){const t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit("statusChanged",t,this._activeEffects)}}!function(e){e[e.Default=0]="Default",e[e.User=1]="User"}(B_||(B_={}));class Y_{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new Kp.EventEmitter}on(e,t){if("statusChanged"!==e)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if("statusChanged"!==e)throw new b({defaultError:f.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){const i={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit("statusChanged",i,this._activeEffects,t)}}class Q_{get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}}var Z_=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this._isAllowed=!1}return e.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},e.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},e.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?c.Resolved():(this._isAllowedDeferral||(this._isAllowedDeferral=c.Defer()),this._isAllowedDeferral.promise())},e}();t.default=i})),X_=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this._isActive=!1}return e.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},e.prototype.isAppActive=function(){return this._isActive},e.prototype.waitForAppActive=function(){return this.isAppActive()?c.Resolved():(this._appActiveDeferral||(this._appActiveDeferral=c.Defer()),this._appActiveDeferral.promise())},e}();t.default=i})),eE=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),tE=function(){function e(e){void 0===e&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];for(var n=t._subscribers,r=n.length-1;r>=0;r--){var a=n[r].apply(null,e);if(t._allowStopPropagation&&a)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new eE(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),iE=Object.freeze({__proto__:null,SubscriptionToken:eE,default:tE}),nE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Default=0]="Default",e[e.User=1]="User"}(t.EcsConfigType||(t.EcsConfigType={}))})),rE=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(i){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})})),t}(iE),aE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._config=e,this.configUpdated=new rE.default,this._cachedConfigs={}}return e.prototype.initialize=function(){return this.updateConfigsToFetch()},e.prototype.updateConfigsToFetch=function(){var e=this,t=this._config.getConfig(),i=t.databaseInterface,n=t.configsToFetch;if(!i)return c.Resolved();for(var r=[],a=function(t){if(s._cachedConfigs[t])return"continue";r.push(i.getData(t).then((function(i){i&&(e._cachedConfigs[t]=i)})).catch((function(){return c.Resolved()})))},s=this,o=0,l=n;o<l.length;o++)a(l[o]);return c.all(r).then((function(){r.length>0&&e.configUpdated.fire()}))},e.prototype.getEcsConfig=function(){return this._cachedConfigs[nE.EcsConfigType.User]||this._cachedConfigs[nE.EcsConfigType.Default]},e.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},e.prototype.putConfig=function(e){var t=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var i=this.getEcsConfig();(i&&i.configType===e.configType||t&&i&&t.configType!==i.configType)&&this.configUpdated.fire();var n=this._config.getConfig().databaseInterface;return n?n.putData(e.configType,e):c.Resolved()},e}();t.default=i})),sE=s((function(e,t){var i=a&&a.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){}return e.prototype.initialize=function(e){if(this._config)throw"ECS Configuration already initialized";this._config=e},e.prototype.getConfig=function(){if(!this._config)throw"ECS Configuration not yet initialized";return this._config},e.prototype.setConfigsToFetch=function(e){if(!this._config)throw"ECS Configuration not yet initialized";this._config=i({},this._config,{configsToFetch:e})},e.prototype.setFetchTimeout=function(e){if(!this._config)throw"ECS Configuration not yet initialized";this._config=i({},this._config,{fetchTimeout:e})},e}();t.default=n})),oE=s((function(e,t){var i=a&&a.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.assert=function(e,t){if(!e)throw new Error(t)},t.isObject=function(e){return null!==e&&"object"==typeof e},t.isString=function(e){return"string"==typeof e},t.attempt=function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];try{return e.apply(void 0,t)}catch(e){return new Error(e)}},t.remove=function(e,t){for(var i=e.length-1;i>=0;i--)e[i]===t&&e.splice(i,1)},t.clone=function(e){return Array.isArray(e)?e.map(t.clone):t.isObject(e)?Object.keys(e).reduce((function(n,r){var a;return i(i({},n),((a={})[r]=t.clone(e[r]),a))}),{}):e}})),lE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,t.DEFAULT_TIME_JITTER=.11962656472;var i=function(){function e(e,i,n,r){void 0===n&&(n=t.DEFAULT_TIME_GROW_FACTOR),void 0===r&&(r=t.DEFAULT_TIME_JITTER),this._initialTime=e,this._maxTime=i,this._growFactor=n,this._jitterFactor=r,oE.assert(this._initialTime>0,"Initial delay must be positive"),oE.assert(this._maxTime>0,"Delay upper bound must be positive"),oE.assert(this._growFactor>=0,"Ratio must be non-negative"),oE.assert(this._jitterFactor>=0,"Jitter factor must be non-negative"),this.reset()}return e.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},e.prototype.getTime=function(){return this._currentTime},e.prototype.getIncrementCount=function(){return this._incrementCount},e.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},e.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},e}();t.ExponentialTime=i})),cE=s((function(e,t){var i,n,r,s=a&&a.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),o=a&&a.__assign||function(){return o=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)};function l(e){return!!e&&0===e.indexOf("application/json")}function d(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?r.DoNotRetry:r.RetryCountedWithBackoff}Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.DontCare=0]="DontCare",e[e.Low=1]="Low",e[e.Normal=2]="Normal",e[e.High=3]="High",e[e.Critical=4]="Critical"}(n=t.WebRequestPriority||(t.WebRequestPriority={})),function(e){e[e.DoNotRetry=0]="DoNotRetry",e[e.RetryUncountedImmediately=1]="RetryUncountedImmediately",e[e.RetryUncountedWithBackoff=2]="RetryUncountedWithBackoff",e[e.RetryCountedWithBackoff=3]="RetryCountedWithBackoff",e[e.PauseUntilResumed=4]="PauseUntilResumed"}(r=t.ErrorHandlingType||(t.ErrorHandlingType={})),t.DefaultOptions={priority:n.Normal},t.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},t.DefaultErrorHandler=d;var u,h=[],p=[],g=[],m=0,f=0,v=function(){function e(e,i,n,r,a){this._action=e,this._url=i,this.options=n,this._getHeaders=r,this._blockRequestUntil=a,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new lE.ExponentialTime(1e3,3e5),this._options=o(o({},t.DefaultOptions),n)}return e.prototype.getPriority=function(){return this._options.priority||n.DontCare},e.checkQueueProcessing=function(){for(var e=function(){var e=h.shift();p.push(e),(e._blockRequestUntil&&e._blockRequestUntil()||c.Resolved()).finally((function(){oE.remove(p,e)})).then((function(){g.length<t.SimpleWebRequestOptions.MaxSimultaneousRequests&&!e._aborted?(g.push(e),S._scheduleHungRequestCleanupIfNeeded(),e._fire()):e._enqueue()}),(function(t){e._respond("_blockRequestUntil rejected: "+t)}))};h.length>0&&g.length<t.SimpleWebRequestOptions.MaxSimultaneousRequests;)e()},e._scheduleHungRequestCleanupIfNeeded=function(){g.length>0&&void 0===u?u=t.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,t.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):0===g.length&&u&&(t.SimpleWebRequestOptions.clearTimeout(u),u=void 0)},e.prototype._removeFromQueue=function(){oE.remove(g,this),oE.remove(h,this)},e.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),oE.assert(e,t))},e.prototype._fire=function(){var i=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var n=oE.attempt((function(){i._xhr.open(i._action,i._url,!0)}));if(n)this._respond(n.toString());else{if(this._options.timeout){var r=f;3!==r&&(this._assertAndClean(!this._requestTimeoutTimer,"Double-fired requestTimeoutTimer"),this._requestTimeoutTimer=t.SimpleWebRequestOptions.setTimeout((function(){i._requestTimeoutTimer=void 0,i._timedOut=!0,i.abort()}),this._options.timeout)),(3===r||r<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){f=3,3===r&&(i._timedOut=!0,i._aborted=!0,i._respond("TimedOut"))})}var a=m;3!==a?(0===a&&(m=1),this._xhr.onreadystatechange=function(){i._xhr&&(3!==i._xhr.readyState||!i._options.streamingDownloadProgress||i._aborted?4===i._xhr.readyState&&(0===a&&1===m&&t.SimpleWebRequestOptions.setTimeout((function(){3!==m&&(m=2)}),1e4),i._respond()):i._options.streamingDownloadProgress(i._xhr.responseText))}):this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){i._xhr&&3===i._xhr.readyState&&i._options.streamingDownloadProgress&&!i._aborted&&i._options.streamingDownloadProgress(i._xhr.responseText)}),2!==a&&(this._xhr.onload=function(){m=3,3===a&&i._respond()},this._xhr.onerror=function(){m=3,3===a&&i._respond()}),this._xhr.onabort=function(){i._aborted=!0,i._respond("Aborted")},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var s=this._options.acceptType||"json",o=this._options.customResponseType||e._getResponseType(s),l=oE.attempt((function(){i._xhr.responseType=o}));if(l&&"json"!==o)throw l;S._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Accept",e.mapContentType(s)),this._xhr.withCredentials=!!this._options.withCredentials;var c=this.getRequestHeaders(),d={};if(Object.keys(c).forEach((function(e){var t=c[e],n=e.toLowerCase();"content-type"!==n?"accept"!==n?(i._assertAndClean(!d[n],"Setting duplicate header key: "+d[n]+" and "+e),null!=t?(d[n]=!0,S._setRequestHeader(i._xhr,i._xhrRequestHeaders,e,t)):console.warn('Tried to set header "'+e+'" on request with "'+t+'" value, header will be dropped')):i._assertAndClean(!1,"Don't set Accept with options.headers -- use it with the options.acceptType property"):i._assertAndClean(!1,"Don't set Content-Type with options.headers -- use it with the options.contentType property")})),this._options.sendData){var u=e.mapContentType(this._options.contentType||"json");S._setRequestHeader(this._xhr,this._xhrRequestHeaders,"Content-Type",u);var h=e.mapBody(this._options.sendData,u);this._xhr.send(h)}else this._xhr.send()}},e._setRequestHeader=function(e,t,i,n){e.setRequestHeader(i,n),t[i]=n},e.mapContentType=function(e){return"json"===e?"application/json":"form"===e?"application/x-www-form-urlencoded":e},e.mapBody=function(e,t){if(l(t)){if(!oE.isString(e))return JSON.stringify(e)}else if(function(e){return!!e&&0===e.indexOf("application/x-www-form-urlencoded")}(t)){if(!oE.isString(e)&&oE.isObject(e)){var i=e;return Object.keys(i).map((function(e){return encodeURIComponent(e)+(i[e]?"="+encodeURIComponent(i[e].toString()):"")})).join("&")}}else if(function(e){return!!e&&0===e.indexOf("multipart/form-data")}(t)){if(oE.isObject(e)){var n=new FormData,r=e;return Object.keys(r).forEach((function(e){return n.append(e,r[e])})),n}oE.assert(!1,"contentType multipart/form-data must include an object as sendData")}return e},e.prototype.setUrl=function(e){this._url=e},e.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},e.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=o(o({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=o(o({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=o(o({},e),this._options.headers)),this._options.augmentHeaders&&(e=o(o({},e),this._options.augmentHeaders)),e},e.prototype.getOptions=function(){return oE.clone(this._options)},e.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(oE.remove(h,this),this._enqueue()))},e.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):oE.assert(!1,"resumeRetrying() called but not paused!")},e.prototype._enqueue=function(){var t=this;if(!this._aborted&&!(g.indexOf(this)>=0||p.indexOf(this)>=0||h.indexOf(this)>=0)){var i=h.findIndex((function(e){return e.getPriority()===t.getPriority()&&e._created>t._created||e.getPriority()<t.getPriority()}));i>-1?h.splice(i,0,this):h.push(this),e.checkQueueProcessing()}},e._getResponseType=function(e){return"blob"===e?"arraybuffer":"text/xml"===e||"application/xml"===e?"document":"text/plain"===e?"text":"json"},e._hungRequestCleanupTimerCallback=function(){u=void 0,g.filter((function(e){return!(!e._xhr||4!==e._xhr.readyState||(console.warn("SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding"),0))})).forEach((function(e){e._respond()})),S._scheduleHungRequestCleanupIfNeeded()},e}();t.SimpleWebRequestBase=v;var S=function(e){function i(t,i,n,r,a){return e.call(this,t,i,n,r,a)||this}return s(i,e),i.prototype.abort=function(){this._aborted?oE.assert(!1,"Already aborted "+this._action+" request to "+this._url):(this._aborted=!0,this._retryTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0),this._deferred?(this._respond("Aborted"),this._xhr&&this._xhr.abort()):oE.assert(!1,"Haven't even fired start() yet -- can't abort"))},i.prototype.start=function(){var e=this;return this._deferred?(oE.assert(!1,"WebRequest already started"),c.Rejected("WebRequest already started")):(this._deferred=c.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},i.prototype._respond=function(e){var i=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._retryTimer),this._retryTimer=void 0),this._requestTimeoutTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0);var n,a=0;if(this._xhr)try{a=this._xhr.status,n=this._xhr.statusText||e}catch(e){}else n=e||"Browser Error - Possible CORS or Connectivity Issue";var s,o,c={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||"").split(/\r?\n/).forEach((function(e){if(0!==e.length){var t=e.indexOf(":");-1===t?c[e]="":c[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!c["content-type"]){var u=this._xhr.getResponseHeader("content-type");u&&(c["content-type"]=u)}if(s=this._xhr.response,c["content-type"]&&l(c["content-type"])&&(!s||!oE.isObject(s))&&("text"===this._xhr.responseType||""===this._xhr.responseType)&&this._xhr.responseText)try{s=JSON.parse(this._xhr.responseText)}catch(e){o=e,console.warn("Failed to parse XHR JSON response")}}if(this._xhr&&4===this._xhr.readyState&&(a>=200&&a<300||304===a)){var h={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:a,statusText:n,headers:c,body:s,responseParsingException:o};this._deferred.resolve(h)}else{var p={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:a,statusText:n,headers:c,body:s,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:o};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(p);var g=this._options.customErrorHandler?this._options.customErrorHandler(this,p):d(0,p);g!==r.DoNotRetry&&(this._options.retries&&this._options.retries>0||g===r.PauseUntilResumed||g===r.RetryUncountedImmediately||g===r.RetryUncountedWithBackoff)?(g===r.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&(t.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),this._requestTimeoutTimer=void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),g===r.PauseUntilResumed?this._paused=!0:g===r.RetryUncountedImmediately?this._enqueue():this._retryTimer=t.SimpleWebRequestOptions.setTimeout((function(){i._retryTimer=void 0,i._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(p)}v.checkQueueProcessing()}},i}(v);t.SimpleWebRequest=S})),dE=s((function(e,t){var i=a&&a.__assign||function(){return i=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},i.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return e.prototype._performApiCall=function(e,t,n,r){var a=this;void 0===r&&(r={});var s=i(i({},this._defaultOptions),r);n&&(s.sendData=n),s.eTag&&(s.augmentHeaders||(s.augmentHeaders={}),s.augmentHeaders["If-None-Match"]=s.eTag),s.contentType||(s.contentType=oE.isString(s.sendData)?"form":"json");var o=s.excludeEndpointUrl?e:this._endpointUrl+e;return new cE.SimpleWebRequest(t,o,s,(function(){return a._getHeaders(s)}),(function(){return a._blockRequestUntil(s)})).start().then((function(e){return a._processSuccessResponse(e),e}))},e.prototype._getHeaders=function(e){return{}},e.prototype._blockRequestUntil=function(e){},e.prototype._processSuccessResponse=function(e){},e.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},e.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,"GET",void 0,t)},e.prototype.performApiPost=function(e,t,i){return this.performApiPostDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPostDetailed=function(e,t,i){return this._performApiCall(e,"POST",t,i)},e.prototype.performApiPatch=function(e,t,i){return this.performApiPatchDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPatchDetailed=function(e,t,i){return this._performApiCall(e,"PATCH",t,i)},e.prototype.performApiPut=function(e,t,i){return this.performApiPutDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiPutDetailed=function(e,t,i){return this._performApiCall(e,"PUT",t,i)},e.prototype.performApiDelete=function(e,t,i){return this.performApiDeleteDetailed(e,t,i).then((function(e){return e.body}))},e.prototype.performApiDeleteDetailed=function(e,t,i){return this._performApiCall(e,"DELETE",t,i)},e}();t.GenericRestClient=n})),uE=s((function(e,t){function i(e){for(var i in e)t.hasOwnProperty(i)||(t[i]=e[i])}Object.defineProperty(t,"__esModule",{value:!0}),i(lE),i(dE),i(cE)})),hE=uE,pE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:"ecs_client"}},e}();t.TelemetryEventBase=i})),gE=s((function(e,t){var i,n=a&&a.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0});var r=function(e){function t(t,i,n,r,a,s,o,l,c,d,u,h,p){var g=e.call(this)||this;return g._responseTime=t,g._responseCode=i,g._fetchAttempts=n,g._hasValidToken=r,g._serverEndpoint=a,g._etag=s,g._fetchDurationValid=o,g._cacheAvailable=l,g._responseSize=c,g._configAge=d,g._configExpired=u,g._fetchStart=h,g._fetchEnd=p,g}return n(t,e),t.prototype.getEventName=function(){return"ecs_tsclient_fetch_config"},t.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetched_etag=this._etag,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t},t}(pE.TelemetryEventBase);t.EcsConfigFetchResponse=r})),mE=s((function(e,t){var i,n=a&&a.__extends||(i=function(e,t){return i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])},i(e,t)},function(e,t){function n(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),r=a&&a.__assign||function(){return r=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},r.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0});var s,o,l=function(e){function t(t,i,n,r,a,s,o,l){var c=e.call(this,t)||this;if(c._config=i,c._skypeTokenData=n,c._appActiveData=r,c._allowBackgroundFetchData=a,c._etag=s,c._getUserConfig=o,c._apiPath="/config/v1/"+c._config.getConfig().clientName+"/"+c._config.getConfig().clientVersion,l){var d=Object.keys(l).map((function(e){return encodeURIComponent(e)+"="+encodeURIComponent(l[e].toString())}));d&&(c._apiPath+="?"+d.join("&"))}return c}return n(t,e),t.prototype._blockRequestUntil=function(e){var t=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log("ECS - Delaying User config fetch until we have a valid SkypeToken"),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var i=this._getUserConfig?"User config":"config";console.log("ECS - Delaying "+i+" fetch until the app is active (or background fetch is allowed)")}return c.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){o=Date.now()}))},t.prototype._getHeaders=function(){var e={};return this._etag&&(e["If-None-Match"]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},t.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return void 0!==t&&(t<0?t=0:t>0&&t<3e4&&(t=3e4)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},t}(hE.GenericRestClient),d=function(){function e(e,t,i,n,r){this._config=e,this._skypeTokenData=t,this._appActiveData=i,this._allowBackgroundFetchData=n,this._telemetryManager=r,this._ecsFailureBackoffTimer=new hE.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,i){var n=this,a=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>a.length-1)&&(this._serverIndex=Math.floor(Math.random()*a.length)),!a||!a.length)return c.Rejected(new Error("no configuration service endpoint"));var d=c.Defer(),u=0,h=function(){var p=e&&e.eTag?e.eTag:void 0,g=new l(a[n._serverIndex],n._config,n._skypeTokenData,n._appActiveData,n._allowBackgroundFetchData,p,t,i);u++,g.getConfig().then((function(i){var l=i.headers.etag,h=i.headers.expires;if(i.body&&i.body.Headers&&(l||(l=i.body.Headers.ETag),h||(h=i.body.Headers.Expires)),s=Date.now(),!l||!h)return console.warn("ECS - Service returned an empty ETag or Expiration header: "+JSON.stringify(i)),c.Rejected();var g,m=new Date(n._calculateExpirationDate(i.headers)).getTime();if(304===i.statusCode&&e)(g=r({},e)).eTag=l,g.expiration=m,g.cacheUpdateTime=s,g.lastFetchTokenHash=n._skypeTokenData.getSkypeTokenHash(i.requestHeaders.Authorization);else{if("object"!=typeof i.body)return console.warn("ECS - Service returned invalid response "+JSON.stringify(i)),c.Rejected();g={config:i.body,configType:t?nE.EcsConfigType.User:nE.EcsConfigType.Default,eTag:l,expiration:m,cacheUpdateTime:o,lastFetchTokenHash:n._skypeTokenData.getSkypeTokenHash(i.requestHeaders.Authorization),appVersion:n._config.getConfig().clientVersion}}var f=s-o,v=!(f<0||f>31536e6),S=e?Date.now()-e.cacheUpdateTime:0;n._telemetryManager.sendTelemetryEvent(new gE.EcsConfigFetchResponse(f,i.statusCode,u,n._skypeTokenData.isSkypeTokenValid(),a[n._serverIndex],l,v,!!p,JSON.stringify(i).length,S,!(e&&e.expiration-Date.now()>0),o,s)),n._ecsFailureBackoffTimer.reset(),d.resolve(g)})).catch((function(){n._serverIndex=(n._serverIndex+1)%a.length,setTimeout((function(){h()}),n._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return h(),d.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+1728e5;if(e.date&&e.expires){var i=new Date(e.date).getTime(),n=Date.now()-i,r=new Date(e.expires).getTime();return isNaN(r)?t:Math.min(t,r+n)}var a=this._cacheMaxAgeRegex.exec(e["cache-control"]);return this._cacheMaxAgeRegex.lastIndex=0,a&&2===a.length?Math.min(t,Date.now()+1e3*Number(a[1])):Date.now()+18e5},e}();t.default=d})),fE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t,i,n,r,a){var s=this;this._config=e,this._skypeTokenData=t,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._paused=!1,this._fetchEcsSettingsIfNeeded=function(e){var t=s._config.getConfig(),i=s._cache.getEcsConfigByType(e);if(-1!==t.configsToFetch.indexOf(e)&&!s._isFetchingSettings[e])if(i||!s._pendingFetch[e]){var n=i?i.expiration-Date.now():-1;n<=0||i&&e===nE.EcsConfigType.User&&s._skypeTokenData.isSkypeTokenValid()&&i.lastFetchTokenHash!==s._skypeTokenData.getSkypeTokenHash(s._skypeTokenData.getSkypeToken())?s._fetchSkypeEcsSettings(e):setTimeout((function(){return s._fetchEcsSettingsIfNeeded(e)}),n)}else s._fetchSkypeEcsSettings(e)},this._fetchSkypeEcsSettings=function(e,t){void 0===t&&(t=!1),s._isFetchingSettings[e]||s._paused&&!t?s._pendingFetch[e]=!0:(s._pendingFetch[e]=!1,s._isFetchingSettings[e]=!0,s._config.getConfig().getEcsParameters().catch((function(){return console.warn("ECS - Failed to fetch ECS fetching parameters"),{}})).then((function(t){return s._ecsClient.getConfig(s._cache.getEcsConfig(),e===nE.EcsConfigType.User,t)})).then((function(t){console.log("ECS - Config fetch complete"),s._isFetchingSettings[e]=!1,s._cache.putConfig(t),s._fetchEcsSettingsIfNeeded(e)})))},this._ecsClient=new mE.default(this._config,this._skypeTokenData,n,r,a)}return e.prototype.initialize=function(){var e=this;this.updateConfigsToFetch(),this._skypeTokenData.skypeTokenChanged.subscribe((function(){return e._fetchEcsSettingsIfNeeded(nE.EcsConfigType.User)}))},e.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,i=e.configsToFetch;t<i.length;t++)(a=i[t])in this._isFetchingSettings||(this._isFetchingSettings[a]=!1),a in this._isFetchingSettings||(this._pendingFetch[a]=!1);for(var n=0,r=e.configsToFetch;n<r.length;n++){var a=r[n],s=this._cache.getEcsConfigByType(a);!s||s.appVersion&&s.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(a,!0):this._fetchEcsSettingsIfNeeded(a)}},e.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var i=t[e];this._fetchSkypeEcsSettings(i)}},e.prototype.pause=function(){this._paused=!0},e.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var i=t[e];this._fetchEcsSettingsIfNeeded(i)}},e}();t.default=i})),vE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){this.skypeTokenChanged=new rE.default}return e.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},e.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},e.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw"No Skype Token provided";return e.skypeToken},e.prototype.getSkypeTokenHash=function(e){return void 0===e?0:e.split("").reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},e.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?c.Resolved():(this._validSkypeTokenDeferral||(this._validSkypeTokenDeferral=c.Defer()),this._validSkypeTokenDeferral.promise())},e}();t.default=i})),SE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e){this._cache=e,this.telemetryEventAdded=new rE.default}return e.prototype.sendTelemetryEvent=function(t){var i=t.getEventName(),n=t.getAttributes(),r=!1,a=this._cache.getEcsConfig();if(a&&e._containsEcsClientTelemetryConfig(a.config)){var s=a.config.ECSCONFIG;s&&s.ecsClientTelemetry&&(r=!!s.ecsClientTelemetry[i])}r&&this.telemetryEventAdded.fire(i,n)},e._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},e}();t.default=i})),yE=s((function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.Models=nE;var i=function(){function e(){this._allowBackgroundFetchData=new Z_.default,this._appActiveData=new X_.default,this._config=new sE.default,this._cache=new aE.default(this._config),this._skypeTokenData=new vE.default,this._telemetryManager=new SE.default(this._cache),this._scheduler=new fE.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return e.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},e.prototype.getConfig=function(){return this._cache.getEcsConfig()},e.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},e.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},e.prototype.pause=function(){this._scheduler.pause()},e.prototype.resume=function(){this._scheduler.resume()},e.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},e.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},e.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},e.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},e.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},e}();t.default=i})),CE=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(yE);class _E{constructor(e,t){this.skypeToken=e,this.skypeTokenExpiration=t}}class EE{constructor(e,t,i){this._logger=e,this._acsProxy=t,this._counter=0,this._resumeCounter=3e3,this._disposed=!1,this._ecsClient=i||new CE,this._isSubscribed=this._initialized=!1}subscribeEcsConfig(e){return e.configType!==B_.Default&&e.configType!==B_.User?Promise.reject("This type of config is not currently supported."):(this._resetConfigCache(e),this._initialized||this._isSubscribed?Promise.reject("Possible duplicate call. Ecs already initialized for this confiugration definition."):Promise.resolve(this._initializeEcsConfig(e).then((()=>{this._ecsClient.configUpdated.subscribe((()=>{if(this._isSubscribed=!0,this._config=this._ecsClient.getConfig(),e.ecsConfigReceiver&&this._config&&(e.ecsConfigReceiver(this._config.config)?this._counter=0:this._counter+=1,this._counter>3))try{this._ecsClient.pause(),this._counter=0,this._resumeCounter*=2,window.setTimeout((()=>{this._disposed||this._ecsClient.resume()}),this._resumeCounter)}catch(e){this._logger.warn("Failed to retry fetch ECS")}}))})).catch((e=>{this._logger.warn("Failed to initialize ECS config because: "+e)}))))}setConfigsToFetch(e){return this._ecsClient.setConfigsToFetch(e)}dispose(){try{this._ecsClient.configUpdated.dispose(),this._disposed=!0}catch(e){this._logger.warn(`Failed to dispose ECS config update, e=${e}`)}}getConfigType(){if(void 0!==this._configDefCache)return this._ecsClient.getConfigType()}getETag(){return void 0===this._config?"":this._config.eTag}getConfigId(e){return void 0===this._config?Promise.reject("Ecs Service has not yet responded. Try calling this API again in sometime."):Promise.resolve(this._config.config.ConfigIDs[e])}setAllowBackgroundFetch(e){return this._ecsClient.setAllowBackgroundFetch(e),Promise.resolve()}setSkypeToken(e,t){return this._ecsClient.useSkypeToken(e,t),Promise.resolve()}setAppActiveState(e){return this._ecsClient.setAppActive(e),Promise.resolve()}_resetConfigCache(e){void 0===e||void 0===this._configDefCache||e.queryParameters===this._configDefCache.queryParameters&&e.configType===this._configDefCache.configType||(this._isSubscribed=!1,this._initialized=!1,this._config=void 0),this._configDefCache=e}_initializeEcsConfig(e){this._initialized=!0;const t={hosts:e.ecsHosts?e.ecsHosts:this._getHostUrls(e.caConfigBag),clientName:"Skype",clientVersion:this._getClientVersion(e.platformId),configsToFetch:this._getLibConfigType(e.configType),getEcsParameters:()=>this._getQueryParameterPromise(e.queryParameters),initialAppActiveState:e.isAppInitiallyInForeground,initialSkypeTokenData:new _E(e.userRawSkypeToken,e.userSkypeTokenExpiration)};return new Promise(((e,i)=>{this._ecsClient.initialize(t).then(e,i)}))}_getHostUrls(e){let t;if(e)if(e.identityType===il.Enterprise)t=Yo.Enterprise_Ecs_ServerUrl;else switch(e.cloudType){case qo.Public:t=Yo.Public_EcsServer_Url;break;case qo.Dod:t=Yo.Dod_EcsServer_Url;break;case qo.GccHigh:t=Yo.GccHigh_EcsServer_Url;break;case qo.AirGap08:t=Yo.AirGap08_EcsServer_Url;break;case qo.AirGap09:t=Yo.AirGap09_EcsServer_Url;break;default:t=Yo.Public_EcsServer_Url}else t=Yo.Public_EcsServer_Url;return[this._acsProxy.proxyfyUrl(t)]}_getClientVersion(e){let t="";return t+=e||"3617",t+="_",t+=dc(),t}_getLibConfigType(e){return[e===B_.Default?yE.Models.EcsConfigType.Default:yE.Models.EcsConfigType.User]}_getQueryParameterPromise(e={}){return c.Resolved(e)}}var TE,bE=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},IE=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class wE{constructor(e,t,i,n,r,a,s){if(this._ECS_FETCH_TYPE_USER="User",this._ECS_FETCH_TYPE_DEFAULT="Default",this._disposed=!1,this._trouterStateChangedListenersRegistered=new Map,this.clientId=t,this.sdkDiagnosticInformation=n,this.logger=e.createChild("CallStack"),this._telemetryLogManager=i,this._acsProxy=r,this._acsCustomRelayManager=a,this._webcvProvider=new W_,this._wasmvqeProvider=new Q_,"https:"!==location.protocol&&"file:"!==location.protocol&&"localhost"!==location.hostname)throw new b({defaultError:f.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new j_(this._telemetryLogManager),this._ecsProvider=new U_(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsFetcher=new EE(this.logger,this._acsProxy),this._videoEffectsStatusManager=new J_,this._audioEffectsStatusManager=new Y_,void 0!==s&&(this._encodedStreamsWorkerProvider=new q_(s))}getClientId(){return this.clientId}getTrouterState(){const e=this?._trouterService?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return this._ecsProvider.getConfigIds()}isRegistered(){return this._trouterService?.isRegistered()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e)}onTrouterStateChanged(e){const t=(t,i)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){const t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t="Uninitialized";if(void 0!==e)switch(e){case 0:t="Unknown";break;case 2:t="Connected";break;case 3:t="Disconnected";break;case 9:t="Switching"}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;const t=new Promise((async(t,i)=>{try{const i=this._getBaseStackConfig();this._tsStack=await m.pluginlessStackFactory.buildBaseStack(i),await this.initializeEcsBase(e),t(this._tsStack)}catch(e){i(e)}}));try{this._createStackBaseWaitPromise=Lh((()=>t),5e4);const e=await this._createStackBaseWaitPromise;return this.logger.log("Base stack init success"),e}catch(e){throw await this.dispose(),e.code===S?new b({defaultError:f.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new b({defaultError:f.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this.caConfigBag=t,this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._tsStack=await this.createStackBase(t),this._disposed=!1;const i=new Promise((async(i,n)=>{try{this._tsStack?(this._telemetryService=new j_(this._telemetryLogManager),this._ecsProvider=new U_(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsFetcher=new EE(this.logger,this._acsProxy),await this.initializeEcsBase(t),await this.initializeEcsForUser(e),Pf.overrideDefaultLogDump(),yc().calling.doNotWaitForTrouter?this._initTrouter(e).catch((()=>{this.logger.warn(f.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):await this._initTrouter(e),this.logger.log("Signaling initialized successfully."),await this._tsStack.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{const e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),await this._tsStack.initializeSignalingAgentProvider({signalingAgentConfig:this._getSignalingConfig(e),trouterService:this._trouterService}),await this._tsStack.init(),i(this._tsStack)):(this.logger.error("Base stack failed to create"),n(new b({defaultError:f.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){n(e)}}));try{this._initializeStackForUserWaitPromise=Lh((()=>i),3e4);const e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log("User stack init success"),e}catch(e){if(await this.dispose(),e.code===S)throw this.sendStackInitEvent(!1,"User stack init timeout",e),new b({defaultError:f.CALL_STACK.USER_STACK_INIT_TIMEOUT});if("Uninitialized"===this.getTrouterState())throw new b({defaultError:f.CALL_STACK.SIGNALING_UNINITIALIZED});throw this.sendStackInitEvent(!1,"User stack init failed",e),new b({defaultError:f.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e})}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info("Using custom proxy for network requests (non media)"),new K_(this.logger,this._acsProxy)):new m.HttpRequestDispatcherImplementation}async initializeEcsBase(e){const t=Rc(),i=this.getEcsQueryParameters(e),n=x(),r=e?this._ECS_FETCH_TYPE_USER:this._ECS_FETCH_TYPE_DEFAULT,a=new z_(B_.Default,e,i,(i=>{if(i?.Headers?.CountryCode&&this.updateEmergencyCallCountry(i?.Headers?.CountryCode),t.resolve(),this._ecsFetcher.getConfigType()===B_.User&&this._ecsSetupCompleteForUser.resolve(),this._ecsFetcher&&this._tsStack&&void 0!==i){let t;const a=+new Date;try{return function(e){if(!e)throw new b({defaultError:f.INTERNAL.ECS_CONFIG_EMPTY});if(!e.AcsCallingSDKWeb)throw new b({defaultError:f.INTERNAL.ECS_CONFIG_MISSING_ACS});try{const t=Sc.telemetry.deviceChangedEvents.piiSafeWords.slice();g.mergeWith(Sc,e.AcsCallingSDKWeb,hc);const i=Sc.telemetry.deviceChangedEvents;"merge"===i.piiSafeWordsMode&&(i.piiSafeWords=g.union(t,i.piiSafeWords))}catch(e){throw new b({defaultError:f.INTERNAL.ECS_CONFIG_MERGING_ERROR})}}(i),this._ecsProvider.setConfig(e,i),function(e){vc=e}(this._ecsProvider.getJamaSettings()),t=JSON.stringify(i),this._tsStack.getEcsProvider().setEcsConfig({ecsBlob:t,userIdentity:"",etag:this._ecsFetcher.getETag()}),this._ecsProvider.assertConfigs(i),!0}catch(e){const t=+new Date;this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_failure,{deltaTimeInMs:t-a},r,n,this._ecsProvider.getConfigIds(),new b({defaultError:f.CALL_STACK.PARSE_CONFIG,originalError:e})),this.logger.error("Unable to parse configuration")}}return!1}),"3617"),s=+new Date;try{await this._ecsFetcher.subscribeEcsConfig(a),this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_attempt,{attemptTimestamp:s},r,n);const e=Lh((()=>t.promise),7e3);await e;const i=+new Date;this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_success,{deltaTimeInMs:i-s},r,n,this._ecsProvider.getConfigIds())}catch(t){const i=new b({defaultError:f.CALL_STACK.PARSE_CONFIG,originalError:t}),a=+new Date;this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_failure,{deltaTimeInMs:a-s},r,n,this._ecsProvider.getConfigIds(),i),this.logger.warn("Failed to fetch base settings. Stack will initialize without default settings",t),this._ecsProvider.setConfig(e,void 0)}}async initializeEcsForUser(e){const t=await e();this._ecsSetupCompleteForUser=Rc();try{await this._ecsFetcher.setConfigsToFetch([B_.User]),await this._ecsFetcher.setSkypeToken(t,1e3*kc(t).exp)}catch(e){throw this.logger.error("Unable to set skype token for user ecs config"),new b({defaultError:f.CALL_STACK.SET_STACK_CONFIG})}const i=x(),n=this.caConfigBag?"User":"Default",r=+new Date;try{this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_attempt,{attemptTimestamp:r},n,i);const e=Lh((()=>this._ecsSetupCompleteForUser.promise),7e3);await e;const t=+new Date;this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_success,{deltaTimeInMs:t-r},n,i,this._ecsProvider.getConfigIds())}catch(e){const t=+new Date;this.sendEcsSettingsFetchedDataEvent(Jh.acs_calling_config_fetched_failure,{deltaTimeInMs:t-r},n,i,this._ecsProvider.getConfigIds(),e),this.logger.warn("Failed to fetch user settings. Stack will initialize without user settings",e)}}async getDeviceManager(){if(!this._createStackBaseWaitPromise)throw new b({defaultError:f.CALL_STACK.GET_DM});return(await this._createStackBaseWaitPromise).getDeviceManager()}async dispose(e){if(!this._disposed){if(this._disposed=!0,this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch(e){this.logger.error("Failed to dispose signaling")}if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch(e){this.logger.error("Failed to dispose calling stack")}this._ecsFetcher.dispose(),this._createStackBaseWaitPromise=void 0,this._initializeStackForUserWaitPromise=void 0,this._tsStack=void 0,this.logger.info("Calling stack disposed")}}getEcsQueryParameters(e){const t={};try{t.CLRelease=m.getVersion();const i=RC();t.BrowserName=i.name,t.BrowserEngine=i.engine,t.BrowserVersion=i.version,t.FormFactor=i.formFactor,t.IdentityType=il.Consumer,t.Cloud=qo.Public,t.OSVer=`${AC()}-${PC()}`,e&&(t.Cloud=e.cloudType,t.IdentityType=e.identityType);const n="_TS_BUILC_VERSION_".replace("C","D");t.CLRelease===n?t.CLRelease="9999.99":t.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete t.CLRelease}catch(e){throw this.logger.error(e),new b({defaultError:f.CALL_STACK.SET_STACK_PARAMS,originalError:e})}return t}sendEcsSettingsFetchedDataEvent(e,t,i,n,r,a){let s,o;a&&(s=a.message,o=xg(a)),this._telemetryLogManager.sendEvent({name:e,tenant:hl,properties:{...t,ecsFetchType:i,correlationId:n,failureReason:s,ecsConfigIds_AcsCallingSDKWeb:r?.AcsCallingSDKWeb||"",ecsConfigIds_SkypeWebMedia:r?.SkypeWebMedia||"",additionalDetails:{...o}}})}updateEmergencyCallCountry(e){this.caConfigBag&&!this.caConfigBag.emergencyCountryCode&&!this.caConfigBag.IsUserEmergencyCountryCode&&e&&(this.caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new G_(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let i=await this._trouterService.start();return void this.sendSignalingInitEvent(!0,+new Date-t,i.trouterRequestCompletionTimeDeltaMs,i.registrarRequestCompletionTimeDeltaMs)}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,void 0,void 0,e),e}}_getBaseStackConfig(){const e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:bC(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:"mediaAgent",signaling:"signalingAgent",tlePlayer:"tlePlayer"},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return void 0!==this._encodedStreamsWorkerProvider&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getSignalingConfig(e){const t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:()=>e(),trouterServiceProvider:this._trouterService,ecsEtag:this._ecsFetcher.getETag()};return this.caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this.caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings()}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,i){try{let n,r;i&&(n=i.message,r=xg(i)),this._telemetryLogManager.sendEvent({name:Jh.acs_calling_stack_init,tenant:hl,properties:{success:e,reason:t,failureReason:n||"unknown",additionalDetails:{...r}}})}catch(e){}}sendSignalingInitEvent(e,t,i,n,r){try{let a,s;r&&(a=r.message,s=xg(r)),this._telemetryLogManager.sendEvent({name:Jh.acs_calling_signaling_init,tenant:hl,properties:{success:e,failureReason:a||"unknown",timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:i,deltaTimeInMsRegistrarRequest:n},additionalDetails:{...s}}})}catch(e){}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&yc().calling.enableCustomTurnUsage)return this.logger.info("Using custom relays for media traffic"),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}}bE([bf,IE("design:type",Object)],wE.prototype,"logger",void 0),bE([M(vp.CreateStackBase),IE("design:type",Function),IE("design:paramtypes",[Object]),IE("design:returntype",Promise)],wE.prototype,"createStackBase",null),bE([M(vp.InitializeStackForUser),IE("design:type",Function),IE("design:paramtypes",[Function,Object]),IE("design:returntype",Promise)],wE.prototype,"initializeStackForUser",null),bE([M(vp.InitializeEcsBase),IE("design:type",Function),IE("design:paramtypes",[Object]),IE("design:returntype",Promise)],wE.prototype,"initializeEcsBase",null),bE([M(vp.InitializeEcsForUser),IE("design:type",Function),IE("design:paramtypes",[Function]),IE("design:returntype",Promise)],wE.prototype,"initializeEcsForUser",null),bE([M(vp.GetDeviceManager),IE("design:type",Function),IE("design:paramtypes",[]),IE("design:returntype",Promise)],wE.prototype,"getDeviceManager",null),bE([M(vp.Dispose),IE("design:type",Function),IE("design:paramtypes",[Boolean]),IE("design:returntype",Promise)],wE.prototype,"dispose",null);class RE{constructor(){this._eventEmitter=new Kp.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((i,n)=>{let r=0;const a=()=>{i(),clearTimeout(r)};this._eventEmitter.once(e,a),r=window.setTimeout((()=>{this._eventEmitter.off(e,a),n(new Error("timeout"))}),t)}))}}class AE{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=yc().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return void 0!==t||(++this._deviceId,t=`${e.split(":")[0]??""}:${this._deviceId}`,this._deviceIdMapping.set(e,t)),t}scrubDeviceLabel(e){return function(e,t){if(!e)return"";if(e.length<3)return e;const i=[],n=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);n&&i.push(n[1]);try{if(!t?.length)return"no_keywords";{const n=new RegExp(`(${t.join("|")})`,"gi");let r=n.exec(e);for(;r;)i.push(r[1]),r=n.exec(e)}}catch(e){const t=e=>g.isString(e)?e:e?.message??"";i.push(`Error: ${t(e)}`)}return 0===i.length?"unknown":i.join(" ")}(e,this._keywords)}}!function(e){e.deviceSelection="deviceSelection"}(TE||(TE={}));var PE=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},ME=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class kE{constructor(e,t,i){this._callStack=t,this._videoDevices=[],this._audioDevices=[],this._tsDeviceTypeToAudioDeviceType={2:"Microphone",3:"Speaker",4:"CompositeAudioDevice"},this.logger=e.createChild("DeviceManager"),this._telemetryLogManager=i,this._eventEmitter=new wm(this.logger),this._browserInfo=RC(),this._safariVideoPermissionState="unknown",this._combinedDevicePermission=new Map,this._deviceInfoMapper=new AE,this._deviceSelectionNotifications=new RE}get telemetryLogManager(){return this._telemetryLogManager}getRawDeviceMediaStream(e){const t=x(),i=+new Date;if(this.sendRawMediaEvent({eventName:Jh.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"attempt",mediaType:e,timestampInfo:"",additionalDetails:""}),!this._tsDeviceManager?.getRawDeviceMediaStream){const n=new b({defaultError:f.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error("Failed to get raw device stream track");const r=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"failure",mediaType:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:n.message||"",code:n.code,subCode:n.subCode,...xg(n)}}),n}let n;try{n=this._tsDeviceManager?.getRawDeviceMediaStream(e);const r=+new Date;return this.sendRawMediaEvent({eventName:Jh.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"success",mediaType:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:""}),n}catch(n){const r=new b({defaultError:f.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:n});this.logger.error("Failed to get raw device stream track");const a=+new Date;throw this.sendRawMediaEvent({eventName:Jh.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:"failure",mediaType:e,timestampInfo:{deltaTimeInMs:a-i},additionalDetails:{failureReason:r.message||"",code:r.code,subCode:r.subCode,...xg(r)}}),r}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;const e=+new Date;try{this.sendGetDeviceManagerEvent({eventName:Jh.acs_calling_get_device_manager,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),await this._callStack.createStackBase(),this._tsDeviceManager=await this._callStack.getDeviceManager();const t=await this._tsDeviceManager.enumerateDevicesAsync();this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(1===e.kind){const t=e;this._videoDevices.push(new Tf(t.label,t.id,"UsbCamera",this))}else if(2===e.kind||3===e.kind){const t=e,i=new Lf(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(i)}}));const i=this._tsDeviceManager.getSelectedDevices();this._selectedMicrophone=this._audioDevices.find((e=>e.id===i.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===i.speaker)),this._dmDevicesChangedSub=this._tsDeviceManager.on("devicesChanged",(async()=>{try{await this.syncDeviceList(await(this._tsDeviceManager?.enumerateDevicesAsync())),this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);const i=+new Date;this.sendGetDeviceManagerEvent({eventName:Jh.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:t?.message,code:t?.code,...xg(t),context:"devicesChanged"}})}})),yc().calling.devicePermissions.getCurrentState&&(this._audioDevicePermission=Bc(this._tsDeviceManager?.getPermissionState("microphone"),this.logger),this._videoDevicePermission=Bc(this._tsDeviceManager?.getPermissionState("camera"),this.logger)),this.logger.info("Initial permission state audio:",this._audioDevicePermission,"video:",this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on("onPermissionStateChanged",this.permissionsChanged.bind(this));const n=+new Date;this.sendGetDeviceManagerEvent({eventName:Jh.acs_calling_get_device_manager,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:n-e},additionalDetails:""})}catch(t){const i=new b({defaultError:f.DEVICE_MANAGER.GET_DM,originalError:t});this.logger.error(i.message);const n=+new Date;this.sendGetDeviceManagerEvent({eventName:Jh.acs_calling_get_device_manager,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:i.message,code:i.code,...xg(i)}})}return this._tsDeviceManager}on(e,t){if("videoDevicesUpdated"!==e&&"audioDevicesUpdated"!==e&&"selectedMicrophoneChanged"!==e&&"selectedSpeakerChanged"!==e)throw new b({defaultError:f.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("videoDevicesUpdated"!==e&&"audioDevicesUpdated"!==e&&"selectedMicrophoneChanged"!==e&&"selectedSpeakerChanged"!==e)throw new b({defaultError:f.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}getTsDeviceManager(){if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return"Safari"===this._browserInfo.engine?this._safariVideoPermissionState:"unknown"}getAcsResourceId(){return this._callStack?.caConfigBag?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||(this._environmentInfo=OC()),this._environmentInfo}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send raw media telemetry")}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send get_device_manager telemetry")}}permissionsChanged(e,t){const i=this._audioDevicePermission,n=this._videoDevicePermission;let r,a;yc().calling.devicePermissions.getCurrentState?(r=Bc(this._tsDeviceManager?.getPermissionState("microphone"),this.logger),a=Bc(this._tsDeviceManager?.getPermissionState("camera"),this.logger)):(r=i,a=n),this._audioDevicePermission=r||!!e?.audio,this._videoDevicePermission=a||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),i===this._audioDevicePermission&&n===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${i}, video: ${n}\n                          to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:Jh.acs_calling_device_permission_changed,tenant:hl,properties:{previousAudioDevicePermission:this.nullHandler(i),previousVideoDevicePermission:this.nullHandler(n),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}checkForSelectedDevicesChanges(){if(this.logger.info("checkForSelectedDevicesChanges"),this._tsDeviceManager){const e=this._tsDeviceManager.getSelectedDevices();e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit("selectedMicrophoneChanged"),void 0!==e.microphone&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit("selectedSpeakerChanged"),void 0!==e.speaker&&this._deviceSelectionNotifications.notifyAll(e.speaker))}else this.logger.warn("DeviceManager is undefined, Unable to check selected devices")}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});this.logger.info("syncDeviceList"),void 0===e&&(e=await this._tsDeviceManager.enumerateDevicesAsync());const t=[];let i=[];const n=[];let r=[];e.map((e=>{if(1===e.kind){const i=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(i)i.setName(e.label),i.setId(e.id),i.setDeviceType("UsbCamera");else{const i=new Tf(e.label,e.id,"UsbCamera",this);t.push(i),this._videoDevices.push(i)}}else if(2===e.kind||3===e.kind){const t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){const i=e;t.setName(i.label),t.setId(i.id),t.setIsSystemDefault(i.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[i.kind])}else{const t=new Lf(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);n.push(t),this._audioDevices.push(t)}}}));const a=t=>{const i=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return i.map((e=>{t.splice(t.indexOf(e),1)})),i};i=a(this._videoDevices),r=a(this._audioDevices),(t.length>0||i.length>0)&&this._eventEmitter.emit("videoDevicesUpdated",{added:t,removed:i}),(n.length>0||r.length>0)&&this._eventEmitter.emit("audioDevicesUpdated",{added:n,removed:r})}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){return await this.syncDeviceList(),this._audioDevices.filter((e=>"Microphone"===e.deviceType))}async getSpeakers(){if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>"Speaker"===e.deviceType));throw new b({defaultError:f.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new b({defaultError:f.DEVICE_MANAGER.INVALID_DEVICE});if("microphone:"===e.id)throw new b({defaultError:f.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info("selectMicrophone called"),this._selectedMicrophone?.id!==e.id){const t=yc().calling.deviceSelectionTimeoutInMs,i=this._deviceSelectionNotifications.waitFor(e.id,t),n="Microphone",r=this._deviceInfoMapper.getDeviceId(e.id),a=this._deviceInfoMapper.scrubDeviceLabel(e.name),s=x(),o=(e,t,i)=>{this.sendDeviceSelectionEvent({eventName:Jh.acs_calling_client_operations,operation:TE.deviceSelection,kindOfEvent:e,correlationId:s,timestampInfo:void 0!==t?{deltaTimeInMs:t}:{},additionalDetails:void 0!==i?{failureReason:i.message,code:i.code,...xg(i)}:"",deviceSelection:{deviceId:r,deviceName:a,deviceType:n}})};o("attempt");const l=Date.now();try{this._tsDeviceManager.selectDevices({microphone:e.id}),await i.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o("success",Date.now()-l)}catch(e){let t;throw t=new b("timeout"===e?.message?{defaultError:f.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:f.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o("failure",Date.now()-l,t),t}}else this.logger.warn("microphoneDevice is already active")}async selectSpeaker(e){const t=this.logger.createFnLogger(Sp.SelectSpeaker);if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new b({defaultError:f.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new b({defaultError:f.DEVICE_MANAGER.INVALID_DEVICE});if("speaker:"===e.id)throw new b({defaultError:f.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info("selectSpeaker called"),this._selectedSpeaker?.id!==e.id){const t=yc().calling.deviceSelectionTimeoutInMs,i=this._deviceSelectionNotifications.waitFor(e.id,t),n="Speaker",r=this._deviceInfoMapper.getDeviceId(e.id),a=this._deviceInfoMapper.scrubDeviceLabel(e.name),s=x(),o=(e,t,i)=>{this.sendDeviceSelectionEvent({eventName:Jh.acs_calling_client_operations,operation:TE.deviceSelection,kindOfEvent:e,correlationId:s,timestampInfo:void 0!==t?{deltaTimeInMs:t}:{},additionalDetails:void 0!==i?{failureReason:i.message,code:i.code,...xg(i)}:"",deviceSelection:{deviceId:r,deviceName:a,deviceType:n}})};o("attempt");const l=Date.now();try{this._tsDeviceManager.selectDevices({speaker:e.id}),await i.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o("success",Date.now()-l)}catch(e){let t;throw t=new b("timeout"===e?.message?{defaultError:f.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:f.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o("failure",Date.now()-l,t),t}}else t.warn("device is already selected")}async askDevicePermission(e){const t={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new b({defaultError:f.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});const i=this.getKeyForConstrains(t);let n=this._combinedDevicePermission.get(i);return n?this.logger.info(`askDevicePermission attempt: audio:${t.audio}, video:${t.video} on pending existing request ${Uc(n)}`):(n=this.askDevicePermissionInternal(t),this._combinedDevicePermission.set(i,n),n.finally((()=>{this._combinedDevicePermission.delete(i)}))),n}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);const t=x(),i=+new Date;this.sendAudioVideoPermissionEvent({eventName:Jh.acs_calling_adp_attempt,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video});try{if(!this._tsDeviceManager)throw new b({defaultError:f.DEVICE_MANAGER.ACCESS_DM});const n=[];if(yc().calling.devicePermissions.splitAskAudioVideo){this.logger.info("askDevicePermission, split permission check");const t=[];if(e.audio&&(this.logger.info("askDevicePermission, split permission audio"),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video){const i=async t=>new Promise(((i,n)=>{const r=async()=>{if(this.logger.info("askDevicePermission, split permission video"),!this._tsDeviceManager){const e="askDevicePermission, split permission video failed device manager not found";return this.logger.error(e),void n(e)}try{const t=await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video});i(t)}catch(e){n(e)}};t?window.setTimeout(r,t):r()}));t.push(i(yc().calling.devicePermissions.timeoutInBetween))}const i=await Promise.allSettled(t);let r={audio:!1,video:!1};i.forEach((e=>{"fulfilled"===e.status&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),"rejected"===e.status&&e?.reason&&n.push(e.reason)})),this.permissionsChanged(r,e),this._safariVideoPermissionState=this._videoDevicePermission?"granted":"denied"}else{const t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video});this.permissionsChanged(t,e)}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAudioVideoPermissionEvent({eventName:Jh.acs_calling_adp_failure,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission},new b({defaultError:f.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[Uc(n)]}));else{const n=+new Date;this.sendAudioVideoPermissionEvent({eventName:Jh.acs_calling_adp_success,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:n-i})}}catch(n){const r=new b({defaultError:f.DEVICE_MANAGER.ADP_FAIL,originalError:n}),a=+new Date;this.sendAudioVideoPermissionEvent({eventName:Jh.acs_calling_adp_failure,correlationId:t,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:a-i},r)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAudioVideoPermissionEvent(e,t){try{let i,n,r;t&&(i="string"==typeof t?.message?t?.message:void 0,n=xg(t)),e.deltaTimeInMs&&(r=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||"",failureReason:i||"",deltaTimeInMs:e.deltaTimeInMs||"",deltaTimeGreaterThanJAMATimeout:this.nullHandler(r),additionalDetails:{...n}}})}catch(e){this.logger.debug("Unable to send audio video permission failure success telemtery")}}sendDeviceSelectionEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send device selection telemetry")}}nullHandler(e){return void 0===e?"":e}dispose(){this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0}}PE([bf,ME("design:type",Object)],kE.prototype,"logger",void 0),PE([M(Sp.GetDeviceManager),ME("design:type",Function),ME("design:paramtypes",[]),ME("design:returntype",Promise)],kE.prototype,"getDeviceManager",null),PE([M(Sp.GetCameras),ME("design:type",Function),ME("design:paramtypes",[]),ME("design:returntype",Promise)],kE.prototype,"getCameras",null),PE([M(Sp.GetMicrophones),ME("design:type",Function),ME("design:paramtypes",[]),ME("design:returntype",Promise)],kE.prototype,"getMicrophones",null),PE([P(Sp.GetSpeakers),ME("design:type",Function),ME("design:paramtypes",[]),ME("design:returntype",Promise)],kE.prototype,"getSpeakers",null),PE([M(Sp.SelectMicrophone),ME("design:type",Function),ME("design:paramtypes",[Object]),ME("design:returntype",Promise)],kE.prototype,"selectMicrophone",null),PE([M(Sp.SelectSpeaker),ME("design:type",Function),ME("design:paramtypes",[Object]),ME("design:returntype",Promise)],kE.prototype,"selectSpeaker",null),PE([M(Sp.AskDevicePermission),ME("design:type",Function),ME("design:paramtypes",[Object]),ME("design:returntype",Promise)],kE.prototype,"askDevicePermission",null);var DE=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class OE extends y_{get info(){return this._teamsCall.info}constructor(t){super(t,e.IncomingCallKind.TeamsIncomingCall),this._teamsCall=t}async accept(e){if(!$c(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}}!function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);a>3&&s&&Object.defineProperty(t,i,s)}([M(gp.Accept),DE("design:type",Function),DE("design:paramtypes",[Object]),DE("design:returntype",Promise)],OE.prototype,"accept",null);class NE extends Hp{constructor(e){super(e)}}var LE=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},xE=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class FE extends g_{get info(){return this._info}constructor(t,i,n,r){super(t,i,n,r,e.CallKind.TeamsCall),this._isEmergencyCall=!1,this._musicOnHoldEnabled=!1,this._info=new NE(n),this._info.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._mtPolicyService=i.mtPolicyService}async startCallInternal(e,t,i,n,r){if(this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable()){let t="",i=!0;this._isEmergencyCall=!1;try{this.logger.info("Fetching Teams User policy from MiddleTier Service"),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this.tsCall.participantId)}catch(e){i=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n                    Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n                    Proceeding as normal pstn call`)}if(i){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){return void this.handlePolicyAndLicenseRestrictionsFailure(e)}try{this.logger.info("Deriving emergency content from fetched policies and settings"),t=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n                    Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}n&&(n.emergencyContent=t||"",n.isEmergency=t?.trim().length>0||!1,this._isEmergencyCall=n.isEmergency)}}if(r){let t=[];Array.isArray(r)?t=r:t.push(r),this._isEmergencyCall&&1==t.length&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&this.setupThreadIdWhenStartingGroupCall(t,e,n),t.forEach((e=>{this.tsCall.addParticipant(rc(e)).catch((()=>{this.logger.error("Failed to add participant during call start")}))})),this.logger.info("Paticipant added during startCall")}super.startCallInternal(e,t,i,n)}isEmergencyCallInProgress(){return this._isEmergencyCall}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){const i=+new Date,r=x();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.attempt,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{attemptTimestamp:i}});let a="";try{if(t.threadId)this.logger.info("Customer provided threadId in options: "+JSON.stringify(t)),this.validateThreadId(e,t),a=t.threadId;else{if(!yc().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new b({defaultError:f.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(null!==this._info.threadId&&void 0!==this._info.threadId){a=this._info.threadId;let t=[];t.push({id:rc(e)}),this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:a,addParticipantsSuffix:yc().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:t}).catch((e=>{this.logger.warn("Error when adding participants "+JSON.stringify(t)+" to thread. "+e)}))}else{let i=[];this._remoteParticipants.forEach((e=>{i.push({id:rc(e.identifier)})})),i.push({id:rc(e)});try{this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:yc().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:i}).then((e=>{e&&(t.threadId=e,a=e,this._info.setThreadId(e)),this.logger.info("Add participant into 1on1 call to convert it into Teams group call. Create thread id: "+a)}))}catch(t){let i="Error when adding participants "+rc(e)+" to thread to create a Teams group call. ";if(!yc().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(i+t)}}}oc(e)}catch(e){const t=new b({defaultError:f.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,...xg(t)}}),t}if(!$c(this.acsProxy,this.acsCustomRelayManager,!0)){const e=new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:e.code,failureReason:e.message,...xg(e)}}),e}if(this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)))){const t=new b({defaultError:f.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[n.getIdentifierKind(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:t.code,failureReason:t.message,...xg(t)}}),t}const s=this.getOrCreateRemoteParticipant(ac(rc(e)));if(yc().calling.enableSmePassFakeConversation&&(n.isPhoneNumberIdentifier(e)||n.isCommunicationUserIdentifier(e)||"communicationUser"===s.identifier.kind))throw new b({defaultError:f.CALL_AGENT.ACTION_BLOCKED});return this.tsCall.addParticipant(rc(e),{threadId:a}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.success,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date}})})).catch((t=>{const{callEndReason:n}=Og(this,s.tsRemoteParticipant,t);s.callEndReason||s.setCallEndReason(n);const a=Fg(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"add",correlationId:r,timestampInfo:{deltaTimeInMs:i-+new Date},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)))&&(this.deleteRemoteParticipant(s),this._eventEmitter.emit("remoteParticipantsUpdated",{added:[],removed:[s]}))})),s}async removeParticipant(e){const t=+new Date,i=x();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.attempt,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{attemptTimestamp:t}});try{oc(e)}catch(e){const n=new b({defaultError:f.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date},additionalDetails:{code:e.code,failureReason:e.message,...xg(n)}}),n}let r=this._remoteParticipants.find((t=>rc(t.identifier)===rc(e)));if(!r){const r=new b({defaultError:f.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[n.getIdentifierKind(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:r.code,subCode:r.subCode,failureReason:r.message,...xg(r)}}),r}try{await this.tsCall.removeParticipant(rc(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.success,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date}})}catch(e){const{callEndReason:n}=Og(this,r.tsRemoteParticipant,e);r.callEndReason||r.setCallEndReason(n);const a=Fg(n);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:Yh.failure,participantAddedOrRemoved:"remove",correlationId:i,timestampInfo:{deltaTimeInMs:t-+new Date},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),new b({defaultError:{message:n.message,code:n.code,subCode:n.subCode||0,resultCategories:n.resultCategories},originalError:e})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(4===this.tsCall.state)return void this.logger.info("Call already on hold");if(!yc().calling.musicOnHoldEnabled)return this.logger.warn("Music on Hold is not enabled"),super.hold();this._musicOnHoldEnabled=!1;const e=+new Date,t=x();this._causeId=m.generateCauseId(),this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:Dp.MusicOnHold}});try{this.logger.info("Fetching Teams Calling Policy from Azure Communication Services"),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this.tsCall.participantId,{policyUrlSuffix:yc().MiddleTier.policyUrlSuffixV2,userPolicies:["TeamsCallingPolicy"]}),this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled()}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n                Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info("Successfully detached devices as part of Hold"),await this.tsCall.park(3,this._causeId).then((()=>{const i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:Dp.MusicOnHold}}),this.logger.info("Successful park() as part of hold, Music on Hold completed successfully")}))})).catch((()=>{const i=+new Date,n=new b({defaultError:f.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n                    Error message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Hold,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,holdType:Dp.MusicOnHold,...xg(n)}}),n})):(this.logger.info("Fetching  of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold"),super.hold())}async resume(){if(this._musicOnHoldEnabled){const e=+new Date,t=x();return this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:Dp.MusicOnHold}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info("Successful unpark() as part of resume"),await this.tsCall.unhold(void 0,this._causeId).then((()=>{const i=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.success,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{holdType:Dp.MusicOnHold}}),this.logger.info("Successful unhold() as part of resume, resume completed successfully")}))})).catch((()=>{const i=+new Date,n=new b({defaultError:f.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n                    Error message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Jh.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:gp.Resume,kindOfEvent:Yh.failure,timestampInfo:{deltaTimeInMs:i-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,holdType:Dp.MusicOnHold,...xg(n)}}),n}))}return this.logger.info("Music on Hold Disabled, proceeding with standard resume"),super.resume()}validateThreadId(e,t){if(!t?.threadId){const e=new b({defaultError:f.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}this.validateThreadIdFormat(t?.threadId)}validateThreadIdFormat(e){if(!e.startsWith("19")){const e=new b({defaultError:f.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){const e=+new Date;if(!this._mtPolicyService.isEvEnabled()){const t=+new Date,i=new b({defaultError:f.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${i.message}, code = ${i.code}, subcode = ${i.subCode}`);const n=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:Jh.acs_calling_call_failed,correlationId:x(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||"",IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{...xg(i)}}},i,{code:i.code,subCode:i.subCode,phrase:i.message}),i}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:"Unknown",code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state="Disconnected",this._eventEmitter.emit("stateChanged"),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,i){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info("ThreadId is already provided in the options parameter: "+JSON.stringify(t))),void 0===t||!t.threadId){let n=[];e.forEach((e=>{n.push({id:rc(e)})}));try{this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:yc().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:n}).then((e=>{t||(t={}),t.threadId=e,e&&this._info.setThreadId(e),i&&e&&(i.threadId=e)}))}catch(e){let t="Failed to create thread Id for Teams group call ";if(!yc().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new b({defaultError:f.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(t+e)}}}}LE([k(gp.AddParticipant),P(gp.AddParticipant),xE("design:type",Function),xE("design:paramtypes",[Object,Object]),xE("design:returntype",Object)],FE.prototype,"addParticipant",null),LE([k(gp.RemoveParticipant),M(gp.RemoveParticipant),xE("design:type",Function),xE("design:paramtypes",[Object]),xE("design:returntype",Promise)],FE.prototype,"removeParticipant",null),LE([k(gp.Mute),xE("design:type",Function),xE("design:paramtypes",[]),xE("design:returntype",Promise)],FE.prototype,"mute",null),LE([k(gp.Unmute),xE("design:type",Function),xE("design:paramtypes",[]),xE("design:returntype",Promise)],FE.prototype,"unmute",null),LE([k(gp.Hold),M(gp.Hold),xE("design:type",Function),xE("design:paramtypes",[]),xE("design:returntype",Promise)],FE.prototype,"hold",null),LE([k(gp.Resume),M(gp.Resume),xE("design:type",Function),xE("design:paramtypes",[]),xE("design:returntype",Promise)],FE.prototype,"resume",null);var UE=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},BE=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};const VE=new Map;class HE extends O_{get calls(){return this._calls}constructor(t,i,n,r,a,s){super(t,i,r,a,n,e.CallAgentKind.TeamsCallAgent,s),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){const t=e.on("callStateChanged",(()=>{if(1===e.state){const i=e.callId;t.dispose();const n=new FE({callId:i,isIncoming:!0},this,e,this._telemetryLogManager),r=new OE(n);this.handleCallState(n),n.bindTsCall(),this._eventEmitter.emit("incomingCall",{incomingCall:r})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);const t=this._calls.find((t=>t.id===e.callId));if(t){const e=this._calls.indexOf(t);-1!==e&&this._calls.splice(e,1),t.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls),this._eventEmitter.emit("callsUpdated",{added:[],removed:[t]}),this.logger.info("call removed")}},this.handleCallState=e=>{e.on("stateChanged",(()=>{try{"Disconnected"===e.state?this.tsStack?(this._tsCallRegistry.deleteCall(e.tsCall)||this.logger.error(`Failed to remove call from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error("Failed to flush telemetry log manager events")}))):this.logger.info("Unable to remove call from registry"):"Connecting"===e.state&&"Incoming"==e.direction&&(this.addToCallArray(e),this._eventEmitter.emit("callsUpdated",{added:[e],removed:[]}))}catch(e){this.logger.error("Failed to handle call state changed event")}}))},this.logger=i}createNewCall(e,t){return new FE({callId:e},this,t,this._telemetryLogManager)}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(e){VE.get(e?.identityMri)&&Dc(f.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),VE.set(e?.identityMri,this)}removeFromCallAgentsMap(e){e?.identityMri&&VE.get(e?.identityMri)===this&&VE.delete(e?.identityMri)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){try{if(this.isCteUser()){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),skypeToken:this._parsedTokenCredential.jwtToken,telemetryLogManager:this._telemetryLogManager});let e=x();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:yc().MiddleTier.policyUrlSuffixV2,userPolicies:["EmergencyPolicies","TeamsCallingPolicy","TeamsMeetingPolicy"],userProperties:["FeatureTypes","PoliciesMetadata","phoneNumber","sipUri","hostType","accountEnabled","useTeamsCalling","evEnabled","region","routingType","preferredDataLocation","featureTypes"]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`)}}catch(e){this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n            Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}startCall(e,t){let i;if(this.assertParticipants(e),Array.isArray(e)){if(i=t,e.length>1&&!yc().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!i?.threadId)throw new b({defaultError:f.CALL_AGENT.GROUPCALL_THREADID});if(1==e.length&&i?.threadId)throw new b({defaultError:f.CALL_AGENT.ONE_TO_ONE_THREADID})}else i=t;if(yc().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e))throw new b({defaultError:f.CALL_AGENT.ACTION_BLOCKED});this.mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(this.isCteUser(),e)&&this.mtPolicyService.initialize({localParticipant:this.getUserMri(),pstnNumber:Array.isArray(e)?e[0].phoneNumber:e.phoneNumber,skypeToken:this._parsedTokenCredential.jwtToken,telemetryLogManager:this._telemetryLogManager});let n=i?.audioOptions?.muted;return void 0===n&&(n=!1),this.logger.info(`startCall with video=${!!i?.videoOptions},muted=${n}`),this.createCall({participants:e,startCallOptions:i})}join(e,t){this.assertCallContext(e);let i=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${i}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){if(this._disposed)throw new b({defaultError:f.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&VE.delete(this._parsedTokenCredential?.identityMri);try{const e=this._tokenFetchTries>this._maxNmberOfRetries;await(this._callStack?.dispose(e))}catch(e){this.logger.error("Call Agent failed to dispose to Call Stack")}this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),delete this._callStack,this._telemetryLogManager.clearTelemetryLoggers(),this.onDisposedCallback&&this.onDisposedCallback()}on(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new b({defaultError:f.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if("incomingCall"!==e&&"callsUpdated"!==e&&"connectionStateChanged"!==e)throw new b({defaultError:f.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e){let t,i,n,r=e?.teamsCallContext?.threadId;const a=e?.teamsCallContext?.meetingLink,s=e?.teamsCallContext?.meetingId,o=e?.teamsCallContext?.passcode||"",l=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isCteUser()&&l&&(r=(e?.startCallOptions).threadId),!$c(this.acsProxy,this.acsCustomRelayManager,!0))throw new b({defaultError:f.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(a&&(i=Op(a)),e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(i={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():"0",organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),i&&(n={meetingType:"0"===i.messageId?1:2,tenantId:i.tenantId,organizerId:i.organizerId,replyChainMessageId:i.messageId}||void 0,r=i.threadId,t=i.messageId),this.tsStack){const i=m.generateCauseId(),a=x(),l=x();let c;c=s?this._tsCallRegistry.createCallWithMeetingData({meetingCode:s,passcode:o,threadId:r},a,l,i):this._tsCallRegistry.createCall(r||"",a,l,t,i);const d=new FE({callId:a},this,c,this._telemetryLogManager);this.addToCallArray(d),this.handleCallState(d);const u={threadId:r||"",messageId:t||"",meetingInfo:n,mediaPeerType:2};return d.startCallInternal(e?.startCallOptions,!!s,e?.teamsCallContext,u,e?.participants).catch(Oc),d.bindTsCall(),this._eventEmitter.emit("callsUpdated",{added:[d],removed:[]}),d}throw new b({defaultError:f.CALL_AGENT.STACK_NOT_INIT})}assertParticipants(e){Mc(e,f.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Pc(e,f.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new b({defaultError:f.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isCteUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>n.isCommunicationUserIdentifier(e)))&&(t=!0):n.isCommunicationUserIdentifier(e)&&(t=!0)),t}}UE([P(pp.StartCall),BE("design:type",Function),BE("design:paramtypes",[Object,Object]),BE("design:returntype",Object)],HE.prototype,"startCall",null),UE([P(pp.Join),BE("design:type",Function),BE("design:paramtypes",[Object,Object]),BE("design:returntype",Object)],HE.prototype,"join",null),UE([M(pp.Dispose),BE("design:type",Function),BE("design:paramtypes",[]),BE("design:returntype",Promise)],HE.prototype,"dispose",null);class $E{constructor(){this._proxyInUse=!1;const e=t.createClientLogger("ACS-calling");this.logger=new Pf(e,[()=>"AcsProxy"])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||""}set proxyUrl(e){if(e.length<4)throw new b({defaultError:f.CALL_CLIENT.PROXY_SHORT_URL});"/"!==e.slice(-1)&&(e=e.concat("","/"));try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new b({defaultError:f.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){const i=new b({defaultError:f.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(i.message),i}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${t}`),t;try{const e=new URL(t);t=`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${e} to ${t}`)}catch(e){const t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}}class GE{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;const e=t.createClientLogger("ACS-calling");this._logger=new Pf(e,[()=>"AcsCustomRelayManager"])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info("Custom relay config provided"),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn("No relay config provided. No op.");const e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((i=>{const n=this._getIndividualRelay(i,t?.username,t?.credential);e.push(n)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,i){const n=[],r=[],a=[Fp.turn,Fp.turns,Fp.stun],s=[Up.tcp,Up.tls,Up.udp];let o;try{o=new URL(e)}catch(t){throw new b({defaultError:f.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}const l=o.protocol.replace(":","");if(!a.includes(l))throw new b({defaultError:f.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let c,d="";try{d=o.href.replace(/((turn)s?|stun):/,"https:"),c=new URL(d)}catch(e){throw new b({defaultError:f.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let u=c.searchParams.get("transport")??"";s.includes(u)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${Up.udp}`),u=Up.udp);let h=""===c.port?this._extractPortFromUrl(o):Number(c.port);h||(this._logger.warn("Could not read port from relay url, defaulting to 3478"),h=3478);let p=c.hostname;return function(e){return new RegExp(Zl).test(e)}(p)?n.push(p):r.push(p),{addresses:n,udpPort:u===Up.udp?h:void 0,tcpPort:u===Up.tcp?h:void 0,tlsPort:u===Up.tls?h:void 0,username:t??"",password:i??"",type:"turn",fqdns:r}}_extractPortFromUrl(e){const t=e.href.match(Xl)?.[0];return Number(t?.replace(":",""))}}var jE,zE=function(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},WE=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let qE=1;class KE{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(yc().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(const e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug("Error logging telemetry",e)}},this.handleVisibilityChange=()=>{"hidden"===document.visibilityState?(this.logger.debug("Visibility changed to hidden"),this.sendPageVisibilityInfoEvent("visibilityChange",!0),this.hangupCalls()):(this.logger.debug("Visibility changed to visible"),this.sendPageVisibilityInfoEvent("visibilityChange",!1))},this.handlePageShow=()=>{this.logger.debug("Page show"),this.sendPageVisibilityInfoEvent("pageShow",!0)},this.handlePageHide=()=>{this.logger.debug("Page hide"),this.sendPageVisibilityInfoEvent("pageHide",!1)},this.handleOrientationChange=()=>{this.logger.debug(`Orientation changed to ${screen.orientation.type}`),this.sendOrientationChangeEvent(screen.orientation.type)},this.getOrientationBasedOnWindowSize=()=>window.innerHeight>window.innerWidth?"portrait-primary":"landscape-primary",this.handleResize=()=>{const e=this.getOrientationBasedOnWindowSize();this._previousOrientation!==e&&(this._previousOrientation=e,this.sendOrientationChangeEvent(e))};const i=+new Date;this.clientId=x();const n=e?.logger||t.createClientLogger("ACS-calling"),r=qE++;if(this._acsProxy=new $E,this._acsCustomRelayManager=new GE,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));const t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new Pf(n,[()=>`CallClient${r}`]),this._eventEmitter=new wm(this.logger),this._sdkDiagnosticInformation=function(e,t,i){const n=`azsdk-js-communication-calling/${e}`;let r="";if(i?.diagnostics?.appName){let e=i?.diagnostics?.appName.trim().replace(/\s/g,"_");e.length>64&&(t.warn("appName is too long, max allowed length is 64 chars, appName was truncated to max length"),e=e.substr(0,64)),r+=e?`${e}/`:"default/"}else r+="default/";if(i?.diagnostics?.appVersion){let e=i?.diagnostics?.appVersion.trim().replace(/\s/g,"_");e.length>64&&(t.warn("appVersion is too long, max allowed length is 64 chars, appVersion was truncated to max length"),e=e.substr(0,64)),r+=e||"0.0.0"}else r+="0.0.0";if(r+=` ${n}`,i?.diagnostics?.tags&&Array.isArray(i?.diagnostics?.tags)&&i?.diagnostics?.tags.length>0){let e=i?.diagnostics?.tags.map((e=>e.trim().replace(/\s/g,"_"))).filter((e=>!!e)).join(";");e.length>128&&(t.warn("tags are too long, max allowed length is 128 chars, tags were truncated to max length"),e=e.substr(0,128)),e.length>0&&(r+=" ("+e+").")}return r}(uc(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new rp(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:Jh.acs_calling_call_client_init,kindOfEvent:"attempt",timestampInfo:"",additionalDetails:""}),Object.defineProperty(globalThis,Il,{value:r,writable:!0,enumerable:!1}),1===r&&Object.defineProperty(globalThis,bl,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info("created"),this._callStack=new wE(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath),this._deviceManager=new kE(this.logger,this._callStack,this._telemetryLogManager),this._previousOrientation="",this.sendInitialOrientation(),window.addEventListener("beforeunload",this.sendTelemetry),window.addEventListener("visibilitychange",this.handleVisibilityChange,!1),window.addEventListener("pageshow",this.handlePageShow,!1),window.addEventListener("pagehide",this.handlePageHide,!1),screen.orientation?screen.orientation.addEventListener("change",this.handleOrientationChange):window.addEventListener("resize",this.handleResize,!1),this._extensibleApi=new vg(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});const e=pC(Yp.CallClientFeature);for(const t of e)"OnExtendedObjectConstructor"===t.activationOptions.activationEvent&&this.feature(t);this.sendCallClientInitEvent({eventName:Jh.acs_calling_call_client_init,kindOfEvent:"success",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:""})}catch(e){const t=new b({defaultError:f.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:Jh.acs_calling_call_client_init,kindOfEvent:"failure",timestampInfo:{deltaTimeInMs:+new Date-i},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...xg(t)}}),t}}createInstance(e){return new KE(e)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return uc()}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){(this._callAgent||this._teamsCallAgent)&&Dc(f.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger),this.validateEmergencyCountryCode(t);try{const i=()=>{this._callAgent=void 0};return this._callAgent=new F_(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,i,t),this._eventEmitter.emit("callAgentCreated"),this._callAgent}catch(e){throw this._callAgent=void 0,new b({defaultError:f.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e})}}async createTeamsCallAgent(e,t){(this._callAgent||this._teamsCallAgent)&&Dc(f.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger);try{const i=()=>{this._teamsCallAgent=void 0};return this._teamsCallAgent=new HE(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,i,t),this._teamsCallAgent.setUserPoliciesOnAgentInitialization(),this._eventEmitter.emit("teamsCallAgentCreated"),this._teamsCallAgent}catch(e){throw this._teamsCallAgent=void 0,new b({defaultError:f.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e})}}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._deviceManager}async getEnvironmentInfoInternal(){return this._environmentInfos||(await this._callStack.createStackBase(),this._environmentInfos=OC()),this._environmentInfos}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>10&&Dc(f.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendOrientationChangeEvent(e,t=!1){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_orientation_changed,tenant:hl,properties:{orientation:e,isInitial:t}})}catch(e){this.logger.debug("Unable to send orientation change telemetry")}}sendInitialOrientation(){let e=screen.orientation&&screen.orientation.type;e||(e=this.getOrientationBasedOnWindowSize()),this.sendOrientationChangeEvent(e,!0)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:hl,properties:e})}catch(e){this.logger.debug("Unable to send CallClient initialized telemetry event")}}hangupCalls(){try{"Mobile"===RC().formFactor&&yc().calling.hangUpCallOnPageHide&&this._callAgent?.calls.forEach((e=>e.hangUp()))}catch(e){try{this.logger.error(`Unable to hangup call on page hide due to ${JSON.stringify(e)}`)}catch(e){this.logger.error("Unable to hangup call on page hide due to unknown error")}}}sendPageVisibilityInfoEvent(e,t){if(this._callAgent?._calls?.length)try{this._telemetryLogManager.sendEvent({name:Jh.acs_calling_page_hidden,tenant:hl,properties:{eventName:e,pageHidden:t}})}catch(e){this.logger.debug("Unable to send page hide telemetry")}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?Kl.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?Kl.onlyUsedProxy:this._customProxyAndTurnInformation.turn?Kl.onlyUsedNonMsftTurn:""}}zE([bf,WE("design:type",Object)],KE.prototype,"logger",void 0),zE([P(hp.GetSDKVersion),WE("design:type",Function),WE("design:paramtypes",[]),WE("design:returntype",String)],KE.prototype,"getSDKVersion",null),zE([P(hp.Feature),WE("design:type",Function),WE("design:paramtypes",[Object]),WE("design:returntype","function"==typeof(jE="undefined"!=typeof TFeature&&TFeature)?jE:Object)],KE.prototype,"feature",null),zE([M(hp.CreateCallAgent),WE("design:type",Function),WE("design:paramtypes",[Object,Object]),WE("design:returntype",Promise)],KE.prototype,"createCallAgent",null),zE([M(hp.CreateTeamsCallAgent),WE("design:type",Function),WE("design:paramtypes",[Object,Object]),WE("design:returntype",Promise)],KE.prototype,"createTeamsCallAgent",null),zE([M(hp.GetDeviceManager),WE("design:type",Function),WE("design:paramtypes",[]),WE("design:returntype",Promise)],KE.prototype,"getDeviceManager",null),zE([M(hp.GetEnvironmentInfo),WE("design:type",Function),WE("design:paramtypes",[]),WE("design:returntype",Promise)],KE.prototype,"getEnvironmentInfoInternal",null),e.CallClient=KE,e.Features=hC,e.LocalAudioStream=$f,e.LocalVideoStream=Nf,e.VideoStreamRenderer=r_,Object.defineProperty(e,"__esModule",{value:!0})}(t,i(2561),i(5810))},5810:(e,t,i)=>{"use strict";function n(e){this.message=e}i.r(t),i.d(t,{AzureCommunicationTokenCredential:()=>u,createCommunicationAccessKeyCredentialPolicy:()=>C,createCommunicationAuthPolicy:()=>T,createIdentifierFromRawId:()=>B,deserializeCommunicationIdentifier:()=>$,getIdentifierKind:()=>L,getIdentifierRawId:()=>x,isCommunicationUserIdentifier:()=>M,isKeyCredential:()=>A,isMicrosoftTeamsAppIdentifier:()=>O,isMicrosoftTeamsUserIdentifier:()=>D,isPhoneNumberIdentifier:()=>k,isUnknownIdentifier:()=>N,parseClientArguments:()=>P,parseConnectionString:()=>w,serializeCommunicationIdentifier:()=>H}),n.prototype=new Error,n.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(e){var t=String(e).replace(/=+$/,"");if(t.length%4==1)throw new n("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,r,a=0,s=0,o="";r=t.charAt(s++);~r&&(i=a%4?64*i+r:r,a++%4)?o+=String.fromCharCode(255&i>>(-2*a&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return o};function a(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,t){var i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return r(t)}}function s(e){this.message=e}s.prototype=new Error,s.prototype.name="InvalidTokenError";const o=e=>{const{exp:t}=function(e,t){if("string"!=typeof e)throw new s("Invalid token specified");var i=!0===(t=t||{}).header?0:1;try{return JSON.parse(a(e.split(".")[i]))}catch(e){throw new s("Invalid token specified: "+e.message)}}(e);return{token:e,expiresOnTimestamp:1e3*t}},l={token:"",expiresOnTimestamp:-10};class c{constructor(e){this.expiringSoonIntervalInMs=6e5,this.refreshAfterLifetimePercentage=.5,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.disposed=!1;const{tokenRefresher:t,token:i,refreshProactively:n}=e;this.refresh=t,this.currentToken=i?o(i):l,this.refreshProactively=null!=n&&n,this.refreshProactively&&this.scheduleRefresh()}async getToken(e){if(!this.isTokenExpiringSoon(this.currentToken))return this.currentToken;if(!this.isTokenValid(this.currentToken)){const t=this.updateTokenAndReschedule(null==e?void 0:e.abortSignal);await t}return this.currentToken}dispose(){this.disposed=!0,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.currentToken=l,this.activeTimeout&&clearTimeout(this.activeTimeout)}async updateTokenAndReschedule(e){if(this.activeTokenUpdating)return this.activeTokenUpdating;this.activeTokenUpdating=this.refreshTokenAndReschedule(e);try{await this.activeTokenUpdating}finally{this.activeTokenUpdating=null}}async refreshTokenAndReschedule(e){const t=await this.refreshToken(e);if(!this.isTokenValid(t))throw new Error("The token returned from the tokenRefresher is expired.");this.currentToken=t,this.refreshProactively&&this.scheduleRefresh()}async refreshToken(e){try{return this.activeTokenFetching||(this.activeTokenFetching=this.refresh(e)),o(await this.activeTokenFetching)}finally{this.activeTokenFetching=null}}scheduleRefresh(){if(this.disposed)return;this.activeTimeout&&clearTimeout(this.activeTimeout);const e=this.currentToken.expiresOnTimestamp-Date.now();let t=null;t=this.isTokenExpiringSoon(this.currentToken)?e*this.refreshAfterLifetimePercentage:e-this.expiringSoonIntervalInMs,this.activeTimeout=setTimeout((()=>this.updateTokenAndReschedule()),t)}isTokenValid(e){return e&&Date.now()<e.expiresOnTimestamp}isTokenExpiringSoon(e){return!e||Date.now()>=e.expiresOnTimestamp-this.expiringSoonIntervalInMs}}class d{constructor(e){this.token=e}async getToken(){return this.token}dispose(){}}class u{constructor(e){this.disposed=!1,this.tokenCredential="string"==typeof e?new d(o(e)):new c(e)}async getToken(e){this.throwIfDisposed();const t=await this.tokenCredential.getToken(e);return this.throwIfDisposed(),t}dispose(){this.disposed=!0,this.tokenCredential.dispose()}throwIfDisposed(){if(this.disposed)throw new Error("User credential is disposed")}}const h=e=>(new TextEncoder).encode(e);function p(e){if("function"!=typeof btoa)throw new Error("Your browser environment is missing the global `btoa` function");const t=new Uint8Array(e);let i="";for(const e of t)i+=String.fromCharCode(e);return btoa(i)}var g;const m=null===(g=null===globalThis||void 0===globalThis?void 0:globalThis.crypto)||void 0===g?void 0:g.subtle,f=async e=>{const t=h(e);return p(await m.digest("SHA-256",t))},v=async(e,t)=>{const i={name:"HMAC",hash:{name:"SHA-256"}},n=h(t),r=function(e){if("function"!=typeof atob)throw new Error("Your browser environment is missing the global `atob` function");const t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i}(e),a=m,s=await a.importKey("raw",r,i,!1,["sign"]);return p(await a.sign(i,s,n))};var S=i(1447);const y="CommunicationAccessKeyCredentialPolicy";function C(e){return{name:y,async sendRequest(t,i){var n;const r=t.method.toUpperCase(),a=(new Date).toUTCString(),s=await f((null===(n=t.body)||void 0===n?void 0:n.toString())||""),o="x-ms-date",l=`${o};host;x-ms-content-sha256`,c=new URL(t.url),d=c.searchParams.toString(),u=d?`${c.pathname}?${d}`:c.pathname,h=c.port,p=h?`${c.host}:${h}`:c.host,g=`${r}\n${u}\n${a};${p};${s}`,m=await v(e.key,g);return S.UG&&t.headers.set("Host",p||""),t.headers.set(o,a),t.headers.set("x-ms-content-sha256",s),t.headers.set("Authorization",`HMAC-SHA256 SignedHeaders=${l}&Signature=${m}`),i(t)}}}var _=i(8685),E=i(127);function T(e){if((0,E.c)(e)){const t={credential:e,scopes:["https://communication.azure.com//.default"]};return(0,_.v)(t)}return C(e)}class b{get key(){return this._key}constructor(e){if(!e)throw new Error("key must be a non-empty string");this._key=e}update(e){this._key=e}}const I=/endpoint=(.*);accesskey=(.*)/i,w=e=>{const t=(e=>{const t=e.match(I);if((null==t?void 0:t[1])&&t[2])return{endpoint:t[1],credential:new b(t[2])}})(e);if(t)return t;throw new Error(`Invalid connection string ${e}`)},R=e=>{if(!(e=>{var t;const i=new URL(e);return!!(null===(t=i.protocol)||void 0===t?void 0:t.match(/^http[s]?/))&&void 0!==i.host&&""!==i.host&&(void 0===i.pathname||""===i.pathname||"/"===i.pathname)})(e))throw new Error(`Invalid endpoint url ${e}`)},A=e=>{const t=e;return t&&"string"==typeof t.key&&void 0===t.getToken},P=(e,t)=>{if(A(t)||(0,E.c)(t))return R(e),{url:e,credential:t};{const{endpoint:t,credential:i}=w(e);return R(t),{url:t,credential:i}}},M=e=>"string"==typeof e.communicationUserId,k=e=>"string"==typeof e.phoneNumber,D=e=>"string"==typeof e.microsoftTeamsUserId,O=e=>"string"==typeof e.teamsAppId,N=e=>"string"==typeof e.id,L=e=>M(e)?Object.assign(Object.assign({},e),{kind:"communicationUser"}):k(e)?Object.assign(Object.assign({},e),{kind:"phoneNumber"}):D(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsUser"}):O(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsApp"}):Object.assign(Object.assign({},e),{kind:"unknown"}),x=e=>{const t=L(e);switch(t.kind){case"communicationUser":return t.communicationUserId;case"microsoftTeamsUser":{const{microsoftTeamsUserId:e,rawId:i,cloud:n,isAnonymous:r}=t;if(i)return i;if(r)return`8:teamsvisitor:${e}`;switch(n){case"dod":return`8:dod:${e}`;case"gcch":return`8:gcch:${e}`;case"public":return`8:orgid:${e}`}return`8:orgid:${e}`}case"microsoftTeamsApp":{const{teamsAppId:e,rawId:i,cloud:n}=t;if(i)return i;switch(n){case"dod":return`28:dod:${e}`;case"gcch":return`28:gcch:${e}`}return`28:orgid:${e}`}case"phoneNumber":{const{phoneNumber:e,rawId:i}=t;return i||`4:${e}`}case"unknown":return t.id}},F=(e,t)=>({kind:"microsoftTeamsApp",teamsAppId:e,cloud:t}),U=(e,t,i)=>({kind:"microsoftTeamsUser",microsoftTeamsUserId:e,isAnonymous:i,cloud:t}),B=e=>{if(e.startsWith("4:"))return{kind:"phoneNumber",phoneNumber:`${e.substring(2)}`};const t=e.split(":");if(3!==t.length)return{kind:"unknown",id:e};const i=`${t[0]}:${t[1]}:`,n=t[2];switch(i){case"8:teamsvisitor:":return{kind:"microsoftTeamsUser",microsoftTeamsUserId:n,isAnonymous:!0};case"8:orgid:":return U(n,"public",!1);case"8:dod:":return U(n,"dod",!1);case"8:gcch:":return U(n,"gcch",!1);case"8:acs:":case"8:spool:":case"8:dod-acs:":case"8:gcch-acs:":return{kind:"communicationUser",communicationUserId:e};case"28:orgid:":return F(n,"public");case"28:gcch:":return F(n,"gcch");case"28:dod:":return F(n,"dod")}return{kind:"unknown",id:e}},V=(e,t)=>{const i=Object.keys(e)[0],n=e[i];if(t in n)return n[t];throw new Error(`Property ${t} is required for identifier of type ${i}.`)},H=e=>{var t,i,n,r,a,s;const o=L(e);switch(o.kind){case"communicationUser":return{rawId:x(o),communicationUser:{id:o.communicationUserId}};case"phoneNumber":return{rawId:null!==(t=o.rawId)&&void 0!==t?t:x(o),phoneNumber:{value:o.phoneNumber}};case"microsoftTeamsUser":return{rawId:null!==(i=o.rawId)&&void 0!==i?i:x(o),microsoftTeamsUser:{userId:o.microsoftTeamsUserId,isAnonymous:null!==(n=o.isAnonymous)&&void 0!==n&&n,cloud:null!==(r=o.cloud)&&void 0!==r?r:"public"}};case"microsoftTeamsApp":return{rawId:null!==(a=o.rawId)&&void 0!==a?a:x(o),microsoftTeamsApp:{teamsAppId:o.teamsAppId,cloud:null!==(s=o.cloud)&&void 0!==s?s:"public"}};case"unknown":return{rawId:o.id};default:throw new Error(`Can't serialize an identifier with kind ${o.kind}`)}},$=e=>{var t;(e=>{const t=[];if(void 0!==e.communicationUser&&t.push("communicationUser"),void 0!==e.microsoftTeamsUser&&t.push("microsoftTeamsUser"),void 0!==e.microsoftTeamsApp&&t.push("microsoftTeamsApp"),void 0!==e.phoneNumber&&t.push("phoneNumber"),t.length>1)throw new Error(`Only one of the properties in ${JSON.stringify(t)} should be present.`)})(e);const{communicationUser:i,microsoftTeamsUser:n,microsoftTeamsApp:r,phoneNumber:a}=e,s=null!==(t=e.kind)&&void 0!==t?t:(e=>e.communicationUser?"communicationUser":e.phoneNumber?"phoneNumber":e.microsoftTeamsUser?"microsoftTeamsUser":e.microsoftTeamsApp?"microsoftTeamsApp":"unknown")(e);return"communicationUser"===s&&i?{kind:"communicationUser",communicationUserId:V({communicationUser:i},"id")}:"phoneNumber"===s&&a?{kind:"phoneNumber",phoneNumber:V({phoneNumber:a},"value"),rawId:V({phoneNumber:e},"rawId")}:"microsoftTeamsUser"===s&&n?{kind:"microsoftTeamsUser",microsoftTeamsUserId:V({microsoftTeamsUser:n},"userId"),isAnonymous:V({microsoftTeamsUser:n},"isAnonymous"),cloud:V({microsoftTeamsUser:n},"cloud"),rawId:V({microsoftTeamsUser:e},"rawId")}:"microsoftTeamsApp"===s&&r?{kind:"microsoftTeamsApp",teamsAppId:V({microsoftTeamsApp:r},"teamsAppId"),cloud:V({microsoftTeamsApp:r},"cloud"),rawId:V({microsoftTeamsApp:e},"rawId")}:{kind:"unknown",id:V({unknown:e},"rawId")}}},127:(e,t,i)=>{"use strict";function n(e){const t=e;return t&&"function"==typeof t.getToken&&(void 0===t.signRequest||t.getToken.length>0)}i.d(t,{c:()=>n})},7110:(e,t,i)=>{"use strict";i.d(t,{k:()=>n});const n=(0,i(2561).createClientLogger)("core-rest-pipeline")},8685:(e,t,i)=>{"use strict";i.d(t,{v:()=>o});var n=i(3027),r=i(7110);const a="bearerTokenAuthenticationPolicy";async function s(e){const{scopes:t,getAccessToken:i,request:n}=e,r={abortSignal:n.abortSignal,tracingOptions:n.tracingOptions},a=await i(t,r);a&&e.request.headers.set("Authorization",`Bearer ${a.token}`)}function o(e){var t;const{credential:i,scopes:o,challengeCallbacks:l}=e,c=e.logger||r.k,d=Object.assign({authorizeRequest:null!==(t=null==l?void 0:l.authorizeRequest)&&void 0!==t?t:s,authorizeRequestOnChallenge:null==l?void 0:l.authorizeRequestOnChallenge},l),u=i?(0,n.K)(i):()=>Promise.resolve(null);return{name:a,async sendRequest(e,t){if(!e.url.toLowerCase().startsWith("https://"))throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");let i,n;await d.authorizeRequest({scopes:Array.isArray(o)?o:[o],request:e,getAccessToken:u,logger:c});try{i=await t(e)}catch(e){n=e,i=e.response}if(d.authorizeRequestOnChallenge&&401===(null==i?void 0:i.status)&&function(e){const t=e.headers.get("WWW-Authenticate");if(401===e.status&&t)return t}(i)&&await d.authorizeRequestOnChallenge({scopes:Array.isArray(o)?o:[o],request:e,response:i,getAccessToken:u,logger:c}))return t(e);if(n)throw n;return i}}}},7432:(e,t,i)=>{"use strict";i.d(t,{g:()=>a});var n=i(4473);const r="The operation was aborted.";function a(e,t,i){return new Promise(((a,s)=>{let o,l;const c=()=>s(new n._((null==i?void 0:i.abortErrorMsg)?null==i?void 0:i.abortErrorMsg:r)),d=()=>{(null==i?void 0:i.abortSignal)&&l&&i.abortSignal.removeEventListener("abort",l)};if(l=()=>(o&&clearTimeout(o),d(),c()),(null==i?void 0:i.abortSignal)&&i.abortSignal.aborted)return c();o=setTimeout((()=>{d(),a(t)}),e),(null==i?void 0:i.abortSignal)&&i.abortSignal.addEventListener("abort",l)}))}},3027:(e,t,i)=>{"use strict";i.d(t,{K:()=>a});var n=i(7432);const r={forcedRefreshWindowInMs:1e3,retryIntervalInMs:3e3,refreshWindowInMs:12e4};function a(e,t){let i,a=null,s=null;const o=Object.assign(Object.assign({},r),t),l={get isRefreshing(){return null!==a},get shouldRefresh(){var e;return!l.isRefreshing&&(null!==(e=null==s?void 0:s.expiresOnTimestamp)&&void 0!==e?e:0)-o.refreshWindowInMs<Date.now()},get mustRefresh(){return null===s||s.expiresOnTimestamp-o.forcedRefreshWindowInMs<Date.now()}};function c(t,r){var c;return l.isRefreshing||(a=async function(e,t,i){async function r(){if(!(Date.now()<i)){const t=await e();if(null===t)throw new Error("Failed to refresh access token.");return t}try{return await e()}catch(e){return null}}let a=await r();for(;null===a;)await(0,n.g)(t),a=await r();return a}((()=>e.getToken(t,r)),o.retryIntervalInMs,null!==(c=null==s?void 0:s.expiresOnTimestamp)&&void 0!==c?c:Date.now()).then((e=>(a=null,s=e,i=r.tenantId,s))).catch((e=>{throw a=null,s=null,i=void 0,e}))),a}return async(e,t)=>i!==t.tenantId||Boolean(t.claims)||l.mustRefresh?c(e,t):(l.shouldRefresh&&c(e,t),s)}},1447:(e,t,i)=>{"use strict";var n,r,a,s;i.d(t,{UG:()=>l}),"undefined"!=typeof window&&window.document,"object"==typeof self&&"function"==typeof(null===self||void 0===self?void 0:self.importScripts)&&("DedicatedWorkerGlobalScope"===(null===(n=self.constructor)||void 0===n?void 0:n.name)||"ServiceWorkerGlobalScope"===(null===(r=self.constructor)||void 0===r?void 0:r.name)||null===(a=self.constructor)||void 0===a||a.name);const o="undefined"!=typeof Deno&&void 0!==Deno.version&&void 0!==Deno.version.deno,l="undefined"!=typeof process&&Boolean(process.version)&&Boolean(null===(s=process.versions)||void 0===s?void 0:s.node)&&!o;"undefined"!=typeof Bun&&Bun.version,"undefined"!=typeof navigator&&(null===navigator||void 0===navigator||navigator.product)},2561:(e,t,i)=>{"use strict";i.r(t),i.d(t,{AzureLogger:()=>S,createClientLogger:()=>T,getLogLevel:()=>_,setLogLevel:()=>C});const n="undefined"!=typeof process&&process.env&&process.env.DEBUG||void 0;let r,a=[],s=[];const o=[];n&&c(n);const l=Object.assign((e=>u(e)),{enable:c,enabled:d,disable:function(){const e=r||"";return c(""),e},log:function(...e){if(e.length>0){const t=String(e[0]);t.includes(":error")?console.error(...e):t.includes(":warning")?console.warn(...e):t.includes(":info")?console.info(...e):(t.includes(":verbose"),console.debug(...e))}}});function c(e){r=e,a=[],s=[];const t=/\*/g,i=e.split(",").map((e=>e.trim().replace(t,".*?")));for(const e of i)e.startsWith("-")?s.push(new RegExp(`^${e.substr(1)}$`)):a.push(new RegExp(`^${e}$`));for(const e of o)e.enabled=d(e.namespace)}function d(e){if(e.endsWith("*"))return!0;for(const t of s)if(t.test(e))return!1;for(const t of a)if(t.test(e))return!0;return!1}function u(e){const t=Object.assign((function(...i){t.enabled&&(i.length>0&&(i[0]=`${e} ${i[0]}`),t.log(...i))}),{enabled:d(e),destroy:h,log:l.log,namespace:e,extend:p});return o.push(t),t}function h(){const e=o.indexOf(this);return e>=0&&(o.splice(e,1),!0)}function p(e){const t=u(`${this.namespace}:${e}`);return t.log=this.log,t}const g=l,m=new Set,f="undefined"!=typeof process&&process.env&&process.env.AZURE_LOG_LEVEL||void 0;let v;const S=g("azure");S.log=(...e)=>{g.log(...e)};const y=["verbose","info","warning","error"];function C(e){if(e&&!R(e))throw new Error(`Unknown log level '${e}'. Acceptable values: ${y.join(",")}`);v=e;const t=[];for(const e of m)w(e)&&t.push(e.namespace);g.enable(t.join(","))}function _(){return v}f&&(R(f)?C(f):console.error(`AZURE_LOG_LEVEL set to unknown log level '${f}'; logging is not enabled. Acceptable values: ${y.join(", ")}.`));const E={verbose:400,info:300,warning:200,error:100};function T(e){const t=S.extend(e);return b(S,t),{error:I(t,"error"),warning:I(t,"warning"),info:I(t,"info"),verbose:I(t,"verbose")}}function b(e,t){t.log=(...t)=>{e.log(...t)}}function I(e,t){const i=Object.assign(e.extend(t),{level:t});if(b(e,i),w(i)){const e=g.disable();g.enable(e+","+i.namespace)}return m.add(i),i}function w(e){return Boolean(v&&E[e.level]<=E[v])}function R(e){return y.includes(e)}},6731:(e,t,i)=>{"use strict";var n=i(3011),r={"text/plain":"Text","text/html":"Url",default:"Text"};e.exports=function(e,t){var i,a,s,o,l,c,d=!1;t||(t={}),i=t.debug||!1;try{if(s=n(),o=document.createRange(),l=document.getSelection(),(c=document.createElement("span")).textContent=e,c.ariaHidden="true",c.style.all="unset",c.style.position="fixed",c.style.top=0,c.style.clip="rect(0, 0, 0, 0)",c.style.whiteSpace="pre",c.style.webkitUserSelect="text",c.style.MozUserSelect="text",c.style.msUserSelect="text",c.style.userSelect="text",c.addEventListener("copy",(function(n){if(n.stopPropagation(),t.format)if(n.preventDefault(),void 0===n.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var a=r[t.format]||r.default;window.clipboardData.setData(a,e)}else n.clipboardData.clearData(),n.clipboardData.setData(t.format,e);t.onCopy&&(n.preventDefault(),t.onCopy(n.clipboardData))})),document.body.appendChild(c),o.selectNodeContents(c),l.addRange(o),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");d=!0}catch(n){i&&console.error("unable to copy using execCommand: ",n),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(t.format||"text",e),t.onCopy&&t.onCopy(window.clipboardData),d=!0}catch(n){i&&console.error("unable to copy using clipboardData: ",n),i&&console.error("falling back to prompt"),a=function(e){var t=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return e.replace(/#{\s*key\s*}/g,t)}("message"in t?t.message:"Copy to clipboard: #{key}, Enter"),window.prompt(a,e)}}finally{l&&("function"==typeof l.removeRange?l.removeRange(o):l.removeAllRanges()),c&&document.body.removeChild(c),s()}return d}},4090:e=>{"use strict";var t,i="object"==typeof Reflect?Reflect:null,n=i&&"function"==typeof i.apply?i.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};t=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function a(){a.init.call(this)}e.exports=a,e.exports.once=function(e,t){return new Promise((function(i,n){function r(i){e.removeListener(t,a),n(i)}function a(){"function"==typeof e.removeListener&&e.removeListener("error",r),i([].slice.call(arguments))}m(e,t,a,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&m(e,"error",t,{once:!0})}(e,r)}))},a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var s=10;function o(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var r,a,s,c;if(o(i),void 0===(a=e._events)?(a=e._events=Object.create(null),e._eventsCount=0):(void 0!==a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),s=a[t]),void 0===s)s=a[t]=i,++e._eventsCount;else if("function"==typeof s?s=a[t]=n?[i,s]:[s,i]:n?s.unshift(i):s.push(i),(r=l(e))>0&&s.length>r&&!s.warned){s.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=s.length,c=d,console&&console.warn&&console.warn(c)}return e}function d(){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 u(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=d.bind(n);return r.listener=i,n.wrapFn=r,r}function h(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=new Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):g(r,r.length)}function p(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function g(e,t){for(var i=new Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);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 r(a){n.once&&e.removeEventListener(t,r),i(a)}))}}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),a.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},a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(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},a.prototype.getMaxListeners=function(){return l(this)},a.prototype.emit=function(e){for(var t=[],i=1;i<arguments.length;i++)t.push(arguments[i]);var r="error"===e,a=this._events;if(void 0!==a)r=r&&void 0===a.error;else if(!r)return!1;if(r){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 l=a[e];if(void 0===l)return!1;if("function"==typeof l)n(l,this,t);else{var c=l.length,d=g(l,c);for(i=0;i<c;++i)n(d[i],this,t)}return!0},a.prototype.addListener=function(e,t){return c(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return c(this,e,t,!0)},a.prototype.once=function(e,t){return o(t),this.on(e,u(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,u(this,e,t)),this},a.prototype.removeListener=function(e,t){var i,n,r,a,s;if(o(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,a=i.length-1;a>=0;a--)if(i[a]===t||i[a].listener===t){s=i[a].listener,r=a;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,s||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0===arguments.length){var r,a=Object.keys(i);for(n=0;n<a.length;++n)"removeListener"!==(r=a[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[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},a.prototype.listeners=function(e){return h(this,e,!0)},a.prototype.rawListeners=function(e){return h(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p,a.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},8303:(e,t,i)=>{"use strict";var n=i(3981),r=i(7574);function a(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,i=1;i<arguments.length;i++)t+="&args[]="+encodeURIComponent(arguments[i]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var s=new Set,o={};function l(e,t){c(e,t),c(e+"Capture",t)}function c(e,t){for(o[e]=t,e=0;e<t.length;e++)s.add(t[e])}var d=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),u=Object.prototype.hasOwnProperty,h=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,p={},g={};function m(e,t,i,n,r,a,s){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=r,this.mustUseProperty=i,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=s}var f={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){f[e]=new m(e,0,!1,e,null,!1,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];f[t]=new m(t,1,!1,e[1],null,!1,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){f[e]=new m(e,2,!1,e.toLowerCase(),null,!1,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){f[e]=new m(e,2,!1,e,null,!1,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){f[e]=new m(e,3,!1,e.toLowerCase(),null,!1,!1)})),["checked","multiple","muted","selected"].forEach((function(e){f[e]=new m(e,3,!0,e,null,!1,!1)})),["capture","download"].forEach((function(e){f[e]=new m(e,4,!1,e,null,!1,!1)})),["cols","rows","size","span"].forEach((function(e){f[e]=new m(e,6,!1,e,null,!1,!1)})),["rowSpan","start"].forEach((function(e){f[e]=new m(e,5,!1,e.toLowerCase(),null,!1,!1)}));var v=/[\-:]([a-z])/g;function S(e){return e[1].toUpperCase()}function y(e,t,i,n){var r=f.hasOwnProperty(t)?f[t]:null;(null!==r?0!==r.type:n||!(2<t.length)||"o"!==t[0]&&"O"!==t[0]||"n"!==t[1]&&"N"!==t[1])&&(function(e,t,i,n){if(null==t||function(e,t,i,n){if(null!==i&&0===i.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!n&&(null!==i?!i.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,i,n))return!0;if(n)return!1;if(null!==i)switch(i.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,i,r,n)&&(i=null),n||null===r?function(e){return!!u.call(g,e)||!u.call(p,e)&&(h.test(e)?g[e]=!0:(p[e]=!0,!1))}(t)&&(null===i?e.removeAttribute(t):e.setAttribute(t,""+i)):r.mustUseProperty?e[r.propertyName]=null===i?3!==r.type&&"":i:(t=r.attributeName,n=r.attributeNamespace,null===i?e.removeAttribute(t):(i=3===(r=r.type)||4===r&&!0===i?"":""+i,n?e.setAttributeNS(n,t,i):e.setAttribute(t,i))))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,null,!1,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(v,S);f[t]=new m(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)})),["tabIndex","crossOrigin"].forEach((function(e){f[e]=new m(e,1,!1,e.toLowerCase(),null,!1,!1)})),f.xlinkHref=new m("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach((function(e){f[e]=new m(e,1,!1,e.toLowerCase(),null,!0,!0)}));var C=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,_=Symbol.for("react.element"),E=Symbol.for("react.portal"),T=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),w=Symbol.for("react.provider"),R=Symbol.for("react.context"),A=Symbol.for("react.forward_ref"),P=Symbol.for("react.suspense"),M=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),D=Symbol.for("react.lazy");Symbol.for("react.scope"),Symbol.for("react.debug_trace_mode");var O=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden"),Symbol.for("react.cache"),Symbol.for("react.tracing_marker");var N=Symbol.iterator;function L(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=N&&e[N]||e["@@iterator"])?e:null}var x,F=Object.assign;function U(e){if(void 0===x)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);x=t&&t[1]||""}return"\n"+x+e}var B=!1;function V(e,t){if(!e||B)return"";B=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(t)if(t=function(){throw Error()},Object.defineProperty(t.prototype,"props",{set:function(){throw Error()}}),"object"==typeof Reflect&&Reflect.construct){try{Reflect.construct(t,[])}catch(e){var n=e}Reflect.construct(e,[],t)}else{try{t.call()}catch(e){n=e}e.call(t.prototype)}else{try{throw Error()}catch(e){n=e}e()}}catch(t){if(t&&n&&"string"==typeof t.stack){for(var r=t.stack.split("\n"),a=n.stack.split("\n"),s=r.length-1,o=a.length-1;1<=s&&0<=o&&r[s]!==a[o];)o--;for(;1<=s&&0<=o;s--,o--)if(r[s]!==a[o]){if(1!==s||1!==o)do{if(s--,0>--o||r[s]!==a[o]){var l="\n"+r[s].replace(" at new "," at ");return e.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",e.displayName)),l}}while(1<=s&&0<=o);break}}}finally{B=!1,Error.prepareStackTrace=i}return(e=e?e.displayName||e.name:"")?U(e):""}function H(e){switch(e.tag){case 5:return U(e.type);case 16:return U("Lazy");case 13:return U("Suspense");case 19:return U("SuspenseList");case 0:case 2:case 15:return V(e.type,!1);case 11:return V(e.type.render,!1);case 1:return V(e.type,!0);default:return""}}function $(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case T:return"Fragment";case E:return"Portal";case I:return"Profiler";case b:return"StrictMode";case P:return"Suspense";case M:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case R:return(e.displayName||"Context")+".Consumer";case w:return(e._context.displayName||"Context")+".Provider";case A:var t=e.render;return(e=e.displayName)||(e=""!==(e=t.displayName||t.name||"")?"ForwardRef("+e+")":"ForwardRef"),e;case k:return null!==(t=e.displayName||null)?t:$(e.type)||"Memo";case D:t=e._payload,e=e._init;try{return $(e(t))}catch(e){}}return null}function G(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=(e=t.render).displayName||e.name||"",t.displayName||(""!==e?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return $(t);case 8:return t===b?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof t)return t.displayName||t.name||null;if("string"==typeof t)return t}return null}function j(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function z(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function W(e){e._valueTracker||(e._valueTracker=function(e){var t=z(e)?"checked":"value",i=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var r=i.get,a=i.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return r.call(this)},set:function(e){n=""+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:i.enumerable}),{getValue:function(){return n},setValue:function(e){n=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function q(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),n="";return e&&(n=z(e)?e.checked?"true":"false":e.value),(e=n)!==i&&(t.setValue(e),!0)}function K(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function J(e,t){var i=t.checked;return F({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=i?i:e._wrapperState.initialChecked})}function Y(e,t){var i=null==t.defaultValue?"":t.defaultValue,n=null!=t.checked?t.checked:t.defaultChecked;i=j(null!=t.value?t.value:i),e._wrapperState={initialChecked:n,initialValue:i,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function Q(e,t){null!=(t=t.checked)&&y(e,"checked",t,!1)}function Z(e,t){Q(e,t);var i=j(t.value),n=t.type;if(null!=i)"number"===n?(0===i&&""===e.value||e.value!=i)&&(e.value=""+i):e.value!==""+i&&(e.value=""+i);else if("submit"===n||"reset"===n)return void e.removeAttribute("value");t.hasOwnProperty("value")?ee(e,t.type,i):t.hasOwnProperty("defaultValue")&&ee(e,t.type,j(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function X(e,t,i){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!("submit"!==n&&"reset"!==n||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,i||t===e.value||(e.value=t),e.defaultValue=t}""!==(i=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==i&&(e.name=i)}function ee(e,t,i){"number"===t&&K(e.ownerDocument)===e||(null==i?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+i&&(e.defaultValue=""+i))}var te=Array.isArray;function ie(e,t,i,n){if(e=e.options,t){t={};for(var r=0;r<i.length;r++)t["$"+i[r]]=!0;for(i=0;i<e.length;i++)r=t.hasOwnProperty("$"+e[i].value),e[i].selected!==r&&(e[i].selected=r),r&&n&&(e[i].defaultSelected=!0)}else{for(i=""+j(i),t=null,r=0;r<e.length;r++){if(e[r].value===i)return e[r].selected=!0,void(n&&(e[r].defaultSelected=!0));null!==t||e[r].disabled||(t=e[r])}null!==t&&(t.selected=!0)}}function ne(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(a(91));return F({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function re(e,t){var i=t.value;if(null==i){if(i=t.children,t=t.defaultValue,null!=i){if(null!=t)throw Error(a(92));if(te(i)){if(1<i.length)throw Error(a(93));i=i[0]}t=i}null==t&&(t=""),i=t}e._wrapperState={initialValue:j(i)}}function ae(e,t){var i=j(t.value),n=j(t.defaultValue);null!=i&&((i=""+i)!==e.value&&(e.value=i),null==t.defaultValue&&e.defaultValue!==i&&(e.defaultValue=i)),null!=n&&(e.defaultValue=""+n)}function se(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}function oe(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function le(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?oe(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var ce,de,ue=(de=function(e,t){if("http://www.w3.org/2000/svg"!==e.namespaceURI||"innerHTML"in e)e.innerHTML=t;else{for((ce=ce||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ce.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(e,t,i,n){MSApp.execUnsafeLocalFunction((function(){return de(e,t)}))}:de);function he(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&3===i.nodeType)return void(i.nodeValue=t)}e.textContent=t}var pe={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ge=["Webkit","ms","Moz","O"];function me(e,t,i){return null==t||"boolean"==typeof t||""===t?"":i||"number"!=typeof t||0===t||pe.hasOwnProperty(e)&&pe[e]?(""+t).trim():t+"px"}function fe(e,t){for(var i in e=e.style,t)if(t.hasOwnProperty(i)){var n=0===i.indexOf("--"),r=me(i,t[i],n);"float"===i&&(i="cssFloat"),n?e.setProperty(i,r):e[i]=r}}Object.keys(pe).forEach((function(e){ge.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),pe[t]=pe[e]}))}));var ve=F({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Se(e,t){if(t){if(ve[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(a(137,e));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(a(60));if("object"!=typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(a(61))}if(null!=t.style&&"object"!=typeof t.style)throw Error(a(62))}}function ye(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Ce=null;function _e(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var Ee=null,Te=null,be=null;function Ie(e){if(e=yr(e)){if("function"!=typeof Ee)throw Error(a(280));var t=e.stateNode;t&&(t=_r(t),Ee(e.stateNode,e.type,t))}}function we(e){Te?be?be.push(e):be=[e]:Te=e}function Re(){if(Te){var e=Te,t=be;if(be=Te=null,Ie(e),t)for(e=0;e<t.length;e++)Ie(t[e])}}function Ae(e,t){return e(t)}function Pe(){}var Me=!1;function ke(e,t,i){if(Me)return e(t,i);Me=!0;try{return Ae(e,t,i)}finally{Me=!1,(null!==Te||null!==be)&&(Pe(),Re())}}function De(e,t){var i=e.stateNode;if(null===i)return null;var n=_r(i);if(null===n)return null;i=n[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(n=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!n;break e;default:e=!1}if(e)return null;if(i&&"function"!=typeof i)throw Error(a(231,t,typeof i));return i}var Oe=!1;if(d)try{var Ne={};Object.defineProperty(Ne,"passive",{get:function(){Oe=!0}}),window.addEventListener("test",Ne,Ne),window.removeEventListener("test",Ne,Ne)}catch(de){Oe=!1}function Le(e,t,i,n,r,a,s,o,l){var c=Array.prototype.slice.call(arguments,3);try{t.apply(i,c)}catch(e){this.onError(e)}}var xe=!1,Fe=null,Ue=!1,Be=null,Ve={onError:function(e){xe=!0,Fe=e}};function He(e,t,i,n,r,a,s,o,l){xe=!1,Fe=null,Le.apply(Ve,arguments)}function $e(e){var t=e,i=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{!!(4098&(t=e).flags)&&(i=t.return),e=t.return}while(e)}return 3===t.tag?i:null}function Ge(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&null!==(e=e.alternate)&&(t=e.memoizedState),null!==t)return t.dehydrated}return null}function je(e){if($e(e)!==e)throw Error(a(188))}function ze(e){return null!==(e=function(e){var t=e.alternate;if(!t){if(null===(t=$e(e)))throw Error(a(188));return t!==e?null:e}for(var i=e,n=t;;){var r=i.return;if(null===r)break;var s=r.alternate;if(null===s){if(null!==(n=r.return)){i=n;continue}break}if(r.child===s.child){for(s=r.child;s;){if(s===i)return je(r),e;if(s===n)return je(r),t;s=s.sibling}throw Error(a(188))}if(i.return!==n.return)i=r,n=s;else{for(var o=!1,l=r.child;l;){if(l===i){o=!0,i=r,n=s;break}if(l===n){o=!0,n=r,i=s;break}l=l.sibling}if(!o){for(l=s.child;l;){if(l===i){o=!0,i=s,n=r;break}if(l===n){o=!0,n=s,i=r;break}l=l.sibling}if(!o)throw Error(a(189))}}if(i.alternate!==n)throw Error(a(190))}if(3!==i.tag)throw Error(a(188));return i.stateNode.current===i?e:t}(e))?We(e):null}function We(e){if(5===e.tag||6===e.tag)return e;for(e=e.child;null!==e;){var t=We(e);if(null!==t)return t;e=e.sibling}return null}var qe=r.unstable_scheduleCallback,Ke=r.unstable_cancelCallback,Je=r.unstable_shouldYield,Ye=r.unstable_requestPaint,Qe=r.unstable_now,Ze=r.unstable_getCurrentPriorityLevel,Xe=r.unstable_ImmediatePriority,et=r.unstable_UserBlockingPriority,tt=r.unstable_NormalPriority,it=r.unstable_LowPriority,nt=r.unstable_IdlePriority,rt=null,at=null,st=Math.clz32?Math.clz32:function(e){return 0===(e>>>=0)?32:31-(ot(e)/lt|0)|0},ot=Math.log,lt=Math.LN2,ct=64,dt=4194304;function ut(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&e;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&e;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function ht(e,t){var i=e.pendingLanes;if(0===i)return 0;var n=0,r=e.suspendedLanes,a=e.pingedLanes,s=268435455&i;if(0!==s){var o=s&~r;0!==o?n=ut(o):0!=(a&=s)&&(n=ut(a))}else 0!=(s=i&~r)?n=ut(s):0!==a&&(n=ut(a));if(0===n)return 0;if(0!==t&&t!==n&&!(t&r)&&((r=n&-n)>=(a=t&-t)||16===r&&4194240&a))return t;if(4&n&&(n|=16&i),0!==(t=e.entangledLanes))for(e=e.entanglements,t&=n;0<t;)r=1<<(i=31-st(t)),n|=e[i],t&=~r;return n}function pt(e,t){switch(e){case 1:case 2:case 4:return t+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function gt(e){return 0!=(e=-1073741825&e.pendingLanes)?e:1073741824&e?1073741824:0}function mt(){var e=ct;return!(4194240&(ct<<=1))&&(ct=64),e}function ft(e){for(var t=[],i=0;31>i;i++)t.push(e);return t}function vt(e,t,i){e.pendingLanes|=t,536870912!==t&&(e.suspendedLanes=0,e.pingedLanes=0),(e=e.eventTimes)[t=31-st(t)]=i}function St(e,t){var i=e.entangledLanes|=t;for(e=e.entanglements;i;){var n=31-st(i),r=1<<n;r&t|e[n]&t&&(e[n]|=t),i&=~r}}var yt=0;function Ct(e){return 1<(e&=-e)?4<e?268435455&e?16:536870912:4:1}var _t,Et,Tt,bt,It,wt=!1,Rt=[],At=null,Pt=null,Mt=null,kt=new Map,Dt=new Map,Ot=[],Nt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Lt(e,t){switch(e){case"focusin":case"focusout":At=null;break;case"dragenter":case"dragleave":Pt=null;break;case"mouseover":case"mouseout":Mt=null;break;case"pointerover":case"pointerout":kt.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Dt.delete(t.pointerId)}}function xt(e,t,i,n,r,a){return null===e||e.nativeEvent!==a?(e={blockedOn:t,domEventName:i,eventSystemFlags:n,nativeEvent:a,targetContainers:[r]},null!==t&&null!==(t=yr(t))&&Et(t),e):(e.eventSystemFlags|=n,t=e.targetContainers,null!==r&&-1===t.indexOf(r)&&t.push(r),e)}function Ft(e){var t=Sr(e.target);if(null!==t){var i=$e(t);if(null!==i)if(13===(t=i.tag)){if(null!==(t=Ge(i)))return e.blockedOn=t,void It(e.priority,(function(){Tt(i)}))}else if(3===t&&i.stateNode.current.memoizedState.isDehydrated)return void(e.blockedOn=3===i.tag?i.stateNode.containerInfo:null)}e.blockedOn=null}function Ut(e){if(null!==e.blockedOn)return!1;for(var t=e.targetContainers;0<t.length;){var i=Jt(e.domEventName,e.eventSystemFlags,t[0],e.nativeEvent);if(null!==i)return null!==(t=yr(i))&&Et(t),e.blockedOn=i,!1;var n=new(i=e.nativeEvent).constructor(i.type,i);Ce=n,i.target.dispatchEvent(n),Ce=null,t.shift()}return!0}function Bt(e,t,i){Ut(e)&&i.delete(t)}function Vt(){wt=!1,null!==At&&Ut(At)&&(At=null),null!==Pt&&Ut(Pt)&&(Pt=null),null!==Mt&&Ut(Mt)&&(Mt=null),kt.forEach(Bt),Dt.forEach(Bt)}function Ht(e,t){e.blockedOn===t&&(e.blockedOn=null,wt||(wt=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Vt)))}function $t(e){function t(t){return Ht(t,e)}if(0<Rt.length){Ht(Rt[0],e);for(var i=1;i<Rt.length;i++){var n=Rt[i];n.blockedOn===e&&(n.blockedOn=null)}}for(null!==At&&Ht(At,e),null!==Pt&&Ht(Pt,e),null!==Mt&&Ht(Mt,e),kt.forEach(t),Dt.forEach(t),i=0;i<Ot.length;i++)(n=Ot[i]).blockedOn===e&&(n.blockedOn=null);for(;0<Ot.length&&null===(i=Ot[0]).blockedOn;)Ft(i),null===i.blockedOn&&Ot.shift()}var Gt=C.ReactCurrentBatchConfig,jt=!0;function zt(e,t,i,n){var r=yt,a=Gt.transition;Gt.transition=null;try{yt=1,qt(e,t,i,n)}finally{yt=r,Gt.transition=a}}function Wt(e,t,i,n){var r=yt,a=Gt.transition;Gt.transition=null;try{yt=4,qt(e,t,i,n)}finally{yt=r,Gt.transition=a}}function qt(e,t,i,n){if(jt){var r=Jt(e,t,i,n);if(null===r)jn(e,t,n,Kt,i),Lt(e,n);else if(function(e,t,i,n,r){switch(t){case"focusin":return At=xt(At,e,t,i,n,r),!0;case"dragenter":return Pt=xt(Pt,e,t,i,n,r),!0;case"mouseover":return Mt=xt(Mt,e,t,i,n,r),!0;case"pointerover":var a=r.pointerId;return kt.set(a,xt(kt.get(a)||null,e,t,i,n,r)),!0;case"gotpointercapture":return a=r.pointerId,Dt.set(a,xt(Dt.get(a)||null,e,t,i,n,r)),!0}return!1}(r,e,t,i,n))n.stopPropagation();else if(Lt(e,n),4&t&&-1<Nt.indexOf(e)){for(;null!==r;){var a=yr(r);if(null!==a&&_t(a),null===(a=Jt(e,t,i,n))&&jn(e,t,n,Kt,i),a===r)break;r=a}null!==r&&n.stopPropagation()}else jn(e,t,n,null,i)}}var Kt=null;function Jt(e,t,i,n){if(Kt=null,null!==(e=Sr(e=_e(n))))if(null===(t=$e(e)))e=null;else if(13===(i=t.tag)){if(null!==(e=Ge(t)))return e;e=null}else if(3===i){if(t.stateNode.current.memoizedState.isDehydrated)return 3===t.tag?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null);return Kt=e,null}function Yt(e){switch(e){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Ze()){case Xe:return 1;case et:return 4;case tt:case it:return 16;case nt:return 536870912;default:return 16}default:return 16}}var Qt=null,Zt=null,Xt=null;function ei(){if(Xt)return Xt;var e,t,i=Zt,n=i.length,r="value"in Qt?Qt.value:Qt.textContent,a=r.length;for(e=0;e<n&&i[e]===r[e];e++);var s=n-e;for(t=1;t<=s&&i[n-t]===r[a-t];t++);return Xt=r.slice(e,1<t?1-t:void 0)}function ti(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}function ii(){return!0}function ni(){return!1}function ri(e){function t(t,i,n,r,a){for(var s in this._reactName=t,this._targetInst=n,this.type=i,this.nativeEvent=r,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(s)&&(t=e[s],this[s]=t?t(r):r[s]);return this.isDefaultPrevented=(null!=r.defaultPrevented?r.defaultPrevented:!1===r.returnValue)?ii:ni,this.isPropagationStopped=ni,this}return F(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ii)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ii)},persist:function(){},isPersistent:ii}),t}var ai,si,oi,li={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},ci=ri(li),di=F({},li,{view:0,detail:0}),ui=ri(di),hi=F({},di,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:bi,button:0,buttons:0,relatedTarget:function(e){return void 0===e.relatedTarget?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return"movementX"in e?e.movementX:(e!==oi&&(oi&&"mousemove"===e.type?(ai=e.screenX-oi.screenX,si=e.screenY-oi.screenY):si=ai=0,oi=e),ai)},movementY:function(e){return"movementY"in e?e.movementY:si}}),pi=ri(hi),gi=ri(F({},hi,{dataTransfer:0})),mi=ri(F({},di,{relatedTarget:0})),fi=ri(F({},li,{animationName:0,elapsedTime:0,pseudoElement:0})),vi=F({},li,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Si=ri(vi),yi=ri(F({},li,{data:0})),Ci={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},_i={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},Ei={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ti(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Ei[e])&&!!t[e]}function bi(){return Ti}var Ii=F({},di,{key:function(e){if(e.key){var t=Ci[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=ti(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?_i[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:bi,charCode:function(e){return"keypress"===e.type?ti(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?ti(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),wi=ri(Ii),Ri=ri(F({},hi,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Ai=ri(F({},di,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:bi})),Pi=ri(F({},li,{propertyName:0,elapsedTime:0,pseudoElement:0})),Mi=F({},hi,{deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0}),ki=ri(Mi),Di=[9,13,27,32],Oi=d&&"CompositionEvent"in window,Ni=null;d&&"documentMode"in document&&(Ni=document.documentMode);var Li=d&&"TextEvent"in window&&!Ni,xi=d&&(!Oi||Ni&&8<Ni&&11>=Ni),Fi=String.fromCharCode(32),Ui=!1;function Bi(e,t){switch(e){case"keyup":return-1!==Di.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vi(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Hi=!1,$i={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Gi(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!$i[e.type]:"textarea"===t}function ji(e,t,i,n){we(n),0<(t=Wn(t,"onChange")).length&&(i=new ci("onChange","change",null,i,n),e.push({event:i,listeners:t}))}var zi=null,Wi=null;function qi(e){Un(e,0)}function Ki(e){if(q(Cr(e)))return e}function Ji(e,t){if("change"===e)return t}var Yi=!1;if(d){var Qi;if(d){var Zi="oninput"in document;if(!Zi){var Xi=document.createElement("div");Xi.setAttribute("oninput","return;"),Zi="function"==typeof Xi.oninput}Qi=Zi}else Qi=!1;Yi=Qi&&(!document.documentMode||9<document.documentMode)}function en(){zi&&(zi.detachEvent("onpropertychange",tn),Wi=zi=null)}function tn(e){if("value"===e.propertyName&&Ki(Wi)){var t=[];ji(t,Wi,e,_e(e)),ke(qi,t)}}function nn(e,t,i){"focusin"===e?(en(),Wi=i,(zi=t).attachEvent("onpropertychange",tn)):"focusout"===e&&en()}function rn(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Ki(Wi)}function an(e,t){if("click"===e)return Ki(t)}function sn(e,t){if("input"===e||"change"===e)return Ki(t)}var on="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t};function ln(e,t){if(on(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(n=0;n<i.length;n++){var r=i[n];if(!u.call(t,r)||!on(e[r],t[r]))return!1}return!0}function cn(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function dn(e,t){var i,n=cn(e);for(e=0;n;){if(3===n.nodeType){if(i=e+n.textContent.length,e<=t&&i>=t)return{node:n,offset:t-e};e=i}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cn(n)}}function un(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?un(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function hn(){for(var e=window,t=K();t instanceof e.HTMLIFrameElement;){try{var i="string"==typeof t.contentWindow.location.href}catch(e){i=!1}if(!i)break;t=K((e=t.contentWindow).document)}return t}function pn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function gn(e){var t=hn(),i=e.focusedElem,n=e.selectionRange;if(t!==i&&i&&i.ownerDocument&&un(i.ownerDocument.documentElement,i)){if(null!==n&&pn(i))if(t=n.start,void 0===(e=n.end)&&(e=t),"selectionStart"in i)i.selectionStart=t,i.selectionEnd=Math.min(e,i.value.length);else if((e=(t=i.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var r=i.textContent.length,a=Math.min(n.start,r);n=void 0===n.end?a:Math.min(n.end,r),!e.extend&&a>n&&(r=n,n=a,a=r),r=dn(i,a);var s=dn(i,n);r&&s&&(1!==e.rangeCount||e.anchorNode!==r.node||e.anchorOffset!==r.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&((t=t.createRange()).setStart(r.node,r.offset),e.removeAllRanges(),a>n?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}for(t=[],e=i;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i<t.length;i++)(e=t[i]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var mn=d&&"documentMode"in document&&11>=document.documentMode,fn=null,vn=null,Sn=null,yn=!1;function Cn(e,t,i){var n=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;yn||null==fn||fn!==K(n)||(n="selectionStart"in(n=fn)&&pn(n)?{start:n.selectionStart,end:n.selectionEnd}:{anchorNode:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset},Sn&&ln(Sn,n)||(Sn=n,0<(n=Wn(vn,"onSelect")).length&&(t=new ci("onSelect","select",null,t,i),e.push({event:t,listeners:n}),t.target=fn)))}function _n(e,t){var i={};return i[e.toLowerCase()]=t.toLowerCase(),i["Webkit"+e]="webkit"+t,i["Moz"+e]="moz"+t,i}var En={animationend:_n("Animation","AnimationEnd"),animationiteration:_n("Animation","AnimationIteration"),animationstart:_n("Animation","AnimationStart"),transitionend:_n("Transition","TransitionEnd")},Tn={},bn={};function In(e){if(Tn[e])return Tn[e];if(!En[e])return e;var t,i=En[e];for(t in i)if(i.hasOwnProperty(t)&&t in bn)return Tn[e]=i[t];return e}d&&(bn=document.createElement("div").style,"AnimationEvent"in window||(delete En.animationend.animation,delete En.animationiteration.animation,delete En.animationstart.animation),"TransitionEvent"in window||delete En.transitionend.transition);var wn=In("animationend"),Rn=In("animationiteration"),An=In("animationstart"),Pn=In("transitionend"),Mn=new Map,kn="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Dn(e,t){Mn.set(e,t),l(t,[e])}for(var On=0;On<kn.length;On++){var Nn=kn[On];Dn(Nn.toLowerCase(),"on"+(Nn[0].toUpperCase()+Nn.slice(1)))}Dn(wn,"onAnimationEnd"),Dn(Rn,"onAnimationIteration"),Dn(An,"onAnimationStart"),Dn("dblclick","onDoubleClick"),Dn("focusin","onFocus"),Dn("focusout","onBlur"),Dn(Pn,"onTransitionEnd"),c("onMouseEnter",["mouseout","mouseover"]),c("onMouseLeave",["mouseout","mouseover"]),c("onPointerEnter",["pointerout","pointerover"]),c("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ln="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),xn=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ln));function Fn(e,t,i){var n=e.type||"unknown-event";e.currentTarget=i,function(e,t,i,n,r,s,o,l,c){if(He.apply(this,arguments),xe){if(!xe)throw Error(a(198));var d=Fe;xe=!1,Fe=null,Ue||(Ue=!0,Be=d)}}(n,t,void 0,e),e.currentTarget=null}function Un(e,t){t=!!(4&t);for(var i=0;i<e.length;i++){var n=e[i],r=n.event;n=n.listeners;e:{var a=void 0;if(t)for(var s=n.length-1;0<=s;s--){var o=n[s],l=o.instance,c=o.currentTarget;if(o=o.listener,l!==a&&r.isPropagationStopped())break e;Fn(r,o,c),a=l}else for(s=0;s<n.length;s++){if(l=(o=n[s]).instance,c=o.currentTarget,o=o.listener,l!==a&&r.isPropagationStopped())break e;Fn(r,o,c),a=l}}}if(Ue)throw e=Be,Ue=!1,Be=null,e}function Bn(e,t){var i=t[mr];void 0===i&&(i=t[mr]=new Set);var n=e+"__bubble";i.has(n)||(Gn(t,e,2,!1),i.add(n))}function Vn(e,t,i){var n=0;t&&(n|=4),Gn(i,e,n,t)}var Hn="_reactListening"+Math.random().toString(36).slice(2);function $n(e){if(!e[Hn]){e[Hn]=!0,s.forEach((function(t){"selectionchange"!==t&&(xn.has(t)||Vn(t,!1,e),Vn(t,!0,e))}));var t=9===e.nodeType?e:e.ownerDocument;null===t||t[Hn]||(t[Hn]=!0,Vn("selectionchange",!1,t))}}function Gn(e,t,i,n){switch(Yt(t)){case 1:var r=zt;break;case 4:r=Wt;break;default:r=qt}i=r.bind(null,t,i,e),r=void 0,!Oe||"touchstart"!==t&&"touchmove"!==t&&"wheel"!==t||(r=!0),n?void 0!==r?e.addEventListener(t,i,{capture:!0,passive:r}):e.addEventListener(t,i,!0):void 0!==r?e.addEventListener(t,i,{passive:r}):e.addEventListener(t,i,!1)}function jn(e,t,i,n,r){var a=n;if(!(1&t||2&t||null===n))e:for(;;){if(null===n)return;var s=n.tag;if(3===s||4===s){var o=n.stateNode.containerInfo;if(o===r||8===o.nodeType&&o.parentNode===r)break;if(4===s)for(s=n.return;null!==s;){var l=s.tag;if((3===l||4===l)&&((l=s.stateNode.containerInfo)===r||8===l.nodeType&&l.parentNode===r))return;s=s.return}for(;null!==o;){if(null===(s=Sr(o)))return;if(5===(l=s.tag)||6===l){n=a=s;continue e}o=o.parentNode}}n=n.return}ke((function(){var n=a,r=_e(i),s=[];e:{var o=Mn.get(e);if(void 0!==o){var l=ci,c=e;switch(e){case"keypress":if(0===ti(i))break e;case"keydown":case"keyup":l=wi;break;case"focusin":c="focus",l=mi;break;case"focusout":c="blur",l=mi;break;case"beforeblur":case"afterblur":l=mi;break;case"click":if(2===i.button)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":l=pi;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":l=gi;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":l=Ai;break;case wn:case Rn:case An:l=fi;break;case Pn:l=Pi;break;case"scroll":l=ui;break;case"wheel":l=ki;break;case"copy":case"cut":case"paste":l=Si;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":l=Ri}var d=!!(4&t),u=!d&&"scroll"===e,h=d?null!==o?o+"Capture":null:o;d=[];for(var p,g=n;null!==g;){var m=(p=g).stateNode;if(5===p.tag&&null!==m&&(p=m,null!==h&&null!=(m=De(g,h))&&d.push(zn(g,m,p))),u)break;g=g.return}0<d.length&&(o=new l(o,c,null,i,r),s.push({event:o,listeners:d}))}}if(!(7&t)){if(l="mouseout"===e||"pointerout"===e,(!(o="mouseover"===e||"pointerover"===e)||i===Ce||!(c=i.relatedTarget||i.fromElement)||!Sr(c)&&!c[gr])&&(l||o)&&(o=r.window===r?r:(o=r.ownerDocument)?o.defaultView||o.parentWindow:window,l?(l=n,null!==(c=(c=i.relatedTarget||i.toElement)?Sr(c):null)&&(c!==(u=$e(c))||5!==c.tag&&6!==c.tag)&&(c=null)):(l=null,c=n),l!==c)){if(d=pi,m="onMouseLeave",h="onMouseEnter",g="mouse","pointerout"!==e&&"pointerover"!==e||(d=Ri,m="onPointerLeave",h="onPointerEnter",g="pointer"),u=null==l?o:Cr(l),p=null==c?o:Cr(c),(o=new d(m,g+"leave",l,i,r)).target=u,o.relatedTarget=p,m=null,Sr(r)===n&&((d=new d(h,g+"enter",c,i,r)).target=p,d.relatedTarget=u,m=d),u=m,l&&c)e:{for(h=c,g=0,p=d=l;p;p=qn(p))g++;for(p=0,m=h;m;m=qn(m))p++;for(;0<g-p;)d=qn(d),g--;for(;0<p-g;)h=qn(h),p--;for(;g--;){if(d===h||null!==h&&d===h.alternate)break e;d=qn(d),h=qn(h)}d=null}else d=null;null!==l&&Kn(s,o,l,d,!1),null!==c&&null!==u&&Kn(s,u,c,d,!0)}if("select"===(l=(o=n?Cr(n):window).nodeName&&o.nodeName.toLowerCase())||"input"===l&&"file"===o.type)var f=Ji;else if(Gi(o))if(Yi)f=sn;else{f=rn;var v=nn}else(l=o.nodeName)&&"input"===l.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(f=an);switch(f&&(f=f(e,n))?ji(s,f,i,r):(v&&v(e,o,n),"focusout"===e&&(v=o._wrapperState)&&v.controlled&&"number"===o.type&&ee(o,"number",o.value)),v=n?Cr(n):window,e){case"focusin":(Gi(v)||"true"===v.contentEditable)&&(fn=v,vn=n,Sn=null);break;case"focusout":Sn=vn=fn=null;break;case"mousedown":yn=!0;break;case"contextmenu":case"mouseup":case"dragend":yn=!1,Cn(s,i,r);break;case"selectionchange":if(mn)break;case"keydown":case"keyup":Cn(s,i,r)}var S;if(Oi)e:{switch(e){case"compositionstart":var y="onCompositionStart";break e;case"compositionend":y="onCompositionEnd";break e;case"compositionupdate":y="onCompositionUpdate";break e}y=void 0}else Hi?Bi(e,i)&&(y="onCompositionEnd"):"keydown"===e&&229===i.keyCode&&(y="onCompositionStart");y&&(xi&&"ko"!==i.locale&&(Hi||"onCompositionStart"!==y?"onCompositionEnd"===y&&Hi&&(S=ei()):(Zt="value"in(Qt=r)?Qt.value:Qt.textContent,Hi=!0)),0<(v=Wn(n,y)).length&&(y=new yi(y,e,null,i,r),s.push({event:y,listeners:v}),(S||null!==(S=Vi(i)))&&(y.data=S))),(S=Li?function(e,t){switch(e){case"compositionend":return Vi(t);case"keypress":return 32!==t.which?null:(Ui=!0,Fi);case"textInput":return(e=t.data)===Fi&&Ui?null:e;default:return null}}(e,i):function(e,t){if(Hi)return"compositionend"===e||!Oi&&Bi(e,t)?(e=ei(),Xt=Zt=Qt=null,Hi=!1,e):null;switch(e){case"paste":default:return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return xi&&"ko"!==t.locale?null:t.data}}(e,i))&&0<(n=Wn(n,"onBeforeInput")).length&&(r=new yi("onBeforeInput","beforeinput",null,i,r),s.push({event:r,listeners:n}),r.data=S)}Un(s,t)}))}function zn(e,t,i){return{instance:e,listener:t,currentTarget:i}}function Wn(e,t){for(var i=t+"Capture",n=[];null!==e;){var r=e,a=r.stateNode;5===r.tag&&null!==a&&(r=a,null!=(a=De(e,i))&&n.unshift(zn(e,a,r)),null!=(a=De(e,t))&&n.push(zn(e,a,r))),e=e.return}return n}function qn(e){if(null===e)return null;do{e=e.return}while(e&&5!==e.tag);return e||null}function Kn(e,t,i,n,r){for(var a=t._reactName,s=[];null!==i&&i!==n;){var o=i,l=o.alternate,c=o.stateNode;if(null!==l&&l===n)break;5===o.tag&&null!==c&&(o=c,r?null!=(l=De(i,a))&&s.unshift(zn(i,l,o)):r||null!=(l=De(i,a))&&s.push(zn(i,l,o))),i=i.return}0!==s.length&&e.push({event:t,listeners:s})}var Jn=/\r\n?/g,Yn=/\u0000|\uFFFD/g;function Qn(e){return("string"==typeof e?e:""+e).replace(Jn,"\n").replace(Yn,"")}function Zn(e,t,i){if(t=Qn(t),Qn(e)!==t&&i)throw Error(a(425))}function Xn(){}var er=null,tr=null;function ir(e,t){return"textarea"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var nr="function"==typeof setTimeout?setTimeout:void 0,rr="function"==typeof clearTimeout?clearTimeout:void 0,ar="function"==typeof Promise?Promise:void 0,sr="function"==typeof queueMicrotask?queueMicrotask:void 0!==ar?function(e){return ar.resolve(null).then(e).catch(or)}:nr;function or(e){setTimeout((function(){throw e}))}function lr(e,t){var i=t,n=0;do{var r=i.nextSibling;if(e.removeChild(i),r&&8===r.nodeType)if("/$"===(i=r.data)){if(0===n)return e.removeChild(r),void $t(t);n--}else"$"!==i&&"$?"!==i&&"$!"!==i||n++;i=r}while(i);$t(t)}function cr(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break;if(8===t){if("$"===(t=e.data)||"$!"===t||"$?"===t)break;if("/$"===t)return null}}return e}function dr(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var i=e.data;if("$"===i||"$!"===i||"$?"===i){if(0===t)return e;t--}else"/$"===i&&t++}e=e.previousSibling}return null}var ur=Math.random().toString(36).slice(2),hr="__reactFiber$"+ur,pr="__reactProps$"+ur,gr="__reactContainer$"+ur,mr="__reactEvents$"+ur,fr="__reactListeners$"+ur,vr="__reactHandles$"+ur;function Sr(e){var t=e[hr];if(t)return t;for(var i=e.parentNode;i;){if(t=i[gr]||i[hr]){if(i=t.alternate,null!==t.child||null!==i&&null!==i.child)for(e=dr(e);null!==e;){if(i=e[hr])return i;e=dr(e)}return t}i=(e=i).parentNode}return null}function yr(e){return!(e=e[hr]||e[gr])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function Cr(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(a(33))}function _r(e){return e[pr]||null}var Er=[],Tr=-1;function br(e){return{current:e}}function Ir(e){0>Tr||(e.current=Er[Tr],Er[Tr]=null,Tr--)}function wr(e,t){Tr++,Er[Tr]=e.current,e.current=t}var Rr={},Ar=br(Rr),Pr=br(!1),Mr=Rr;function kr(e,t){var i=e.type.contextTypes;if(!i)return Rr;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var r,a={};for(r in i)a[r]=t[r];return n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function Dr(e){return null!=e.childContextTypes}function Or(){Ir(Pr),Ir(Ar)}function Nr(e,t,i){if(Ar.current!==Rr)throw Error(a(168));wr(Ar,t),wr(Pr,i)}function Lr(e,t,i){var n=e.stateNode;if(t=t.childContextTypes,"function"!=typeof n.getChildContext)return i;for(var r in n=n.getChildContext())if(!(r in t))throw Error(a(108,G(e)||"Unknown",r));return F({},i,n)}function xr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Rr,Mr=Ar.current,wr(Ar,e),wr(Pr,Pr.current),!0}function Fr(e,t,i){var n=e.stateNode;if(!n)throw Error(a(169));i?(e=Lr(e,t,Mr),n.__reactInternalMemoizedMergedChildContext=e,Ir(Pr),Ir(Ar),wr(Ar,e)):Ir(Pr),wr(Pr,i)}var Ur=null,Br=!1,Vr=!1;function Hr(e){null===Ur?Ur=[e]:Ur.push(e)}function $r(){if(!Vr&&null!==Ur){Vr=!0;var e=0,t=yt;try{var i=Ur;for(yt=1;e<i.length;e++){var n=i[e];do{n=n(!0)}while(null!==n)}Ur=null,Br=!1}catch(t){throw null!==Ur&&(Ur=Ur.slice(e+1)),qe(Xe,$r),t}finally{yt=t,Vr=!1}}return null}var Gr=[],jr=0,zr=null,Wr=0,qr=[],Kr=0,Jr=null,Yr=1,Qr="";function Zr(e,t){Gr[jr++]=Wr,Gr[jr++]=zr,zr=e,Wr=t}function Xr(e,t,i){qr[Kr++]=Yr,qr[Kr++]=Qr,qr[Kr++]=Jr,Jr=e;var n=Yr;e=Qr;var r=32-st(n)-1;n&=~(1<<r),i+=1;var a=32-st(t)+r;if(30<a){var s=r-r%5;a=(n&(1<<s)-1).toString(32),n>>=s,r-=s,Yr=1<<32-st(t)+r|i<<r|n,Qr=a+e}else Yr=1<<a|i<<r|n,Qr=e}function ea(e){null!==e.return&&(Zr(e,1),Xr(e,1,0))}function ta(e){for(;e===zr;)zr=Gr[--jr],Gr[jr]=null,Wr=Gr[--jr],Gr[jr]=null;for(;e===Jr;)Jr=qr[--Kr],qr[Kr]=null,Qr=qr[--Kr],qr[Kr]=null,Yr=qr[--Kr],qr[Kr]=null}var ia=null,na=null,ra=!1,aa=null;function sa(e,t){var i=Dc(5,null,null,0);i.elementType="DELETED",i.stateNode=t,i.return=e,null===(t=e.deletions)?(e.deletions=[i],e.flags|=16):t.push(i)}function oa(e,t){switch(e.tag){case 5:var i=e.type;return null!==(t=1!==t.nodeType||i.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,ia=e,na=cr(t.firstChild),!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,ia=e,na=null,!0);case 13:return null!==(t=8!==t.nodeType?null:t)&&(i=null!==Jr?{id:Yr,overflow:Qr}:null,e.memoizedState={dehydrated:t,treeContext:i,retryLane:1073741824},(i=Dc(18,null,null,0)).stateNode=t,i.return=e,e.child=i,ia=e,na=null,!0);default:return!1}}function la(e){return!(!(1&e.mode)||128&e.flags)}function ca(e){if(ra){var t=na;if(t){var i=t;if(!oa(e,t)){if(la(e))throw Error(a(418));t=cr(i.nextSibling);var n=ia;t&&oa(e,t)?sa(n,i):(e.flags=-4097&e.flags|2,ra=!1,ia=e)}}else{if(la(e))throw Error(a(418));e.flags=-4097&e.flags|2,ra=!1,ia=e}}}function da(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;ia=e}function ua(e){if(e!==ia)return!1;if(!ra)return da(e),ra=!0,!1;var t;if((t=3!==e.tag)&&!(t=5!==e.tag)&&(t="head"!==(t=e.type)&&"body"!==t&&!ir(e.type,e.memoizedProps)),t&&(t=na)){if(la(e))throw ha(),Error(a(418));for(;t;)sa(e,t),t=cr(t.nextSibling)}if(da(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(a(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var i=e.data;if("/$"===i){if(0===t){na=cr(e.nextSibling);break e}t--}else"$"!==i&&"$!"!==i&&"$?"!==i||t++}e=e.nextSibling}na=null}}else na=ia?cr(e.stateNode.nextSibling):null;return!0}function ha(){for(var e=na;e;)e=cr(e.nextSibling)}function pa(){na=ia=null,ra=!1}function ga(e){null===aa?aa=[e]:aa.push(e)}var ma=C.ReactCurrentBatchConfig;function fa(e,t){if(e&&e.defaultProps){for(var i in t=F({},t),e=e.defaultProps)void 0===t[i]&&(t[i]=e[i]);return t}return t}var va=br(null),Sa=null,ya=null,Ca=null;function _a(){Ca=ya=Sa=null}function Ea(e){var t=va.current;Ir(va),e._currentValue=t}function Ta(e,t,i){for(;null!==e;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==n&&(n.childLanes|=t)):null!==n&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===i)break;e=e.return}}function ba(e,t){Sa=e,Ca=ya=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(!!(e.lanes&t)&&(Co=!0),e.firstContext=null)}function Ia(e){var t=e._currentValue;if(Ca!==e)if(e={context:e,memoizedValue:t,next:null},null===ya){if(null===Sa)throw Error(a(308));ya=e,Sa.dependencies={lanes:0,firstContext:e}}else ya=ya.next=e;return t}var wa=null;function Ra(e){null===wa?wa=[e]:wa.push(e)}function Aa(e,t,i,n){var r=t.interleaved;return null===r?(i.next=i,Ra(t)):(i.next=r.next,r.next=i),t.interleaved=i,Pa(e,n)}function Pa(e,t){e.lanes|=t;var i=e.alternate;for(null!==i&&(i.lanes|=t),i=e,e=e.return;null!==e;)e.childLanes|=t,null!==(i=e.alternate)&&(i.childLanes|=t),i=e,e=e.return;return 3===i.tag?i.stateNode:null}var Ma=!1;function ka(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Da(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Oa(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Na(e,t,i){var n=e.updateQueue;if(null===n)return null;if(n=n.shared,2&Pl){var r=n.pending;return null===r?t.next=t:(t.next=r.next,r.next=t),n.pending=t,Pa(e,i)}return null===(r=n.interleaved)?(t.next=t,Ra(n)):(t.next=r.next,r.next=t),n.interleaved=t,Pa(e,i)}function La(e,t,i){if(null!==(t=t.updateQueue)&&(t=t.shared,4194240&i)){var n=t.lanes;i|=n&=e.pendingLanes,t.lanes=i,St(e,i)}}function xa(e,t){var i=e.updateQueue,n=e.alternate;if(null!==n&&i===(n=n.updateQueue)){var r=null,a=null;if(null!==(i=i.firstBaseUpdate)){do{var s={eventTime:i.eventTime,lane:i.lane,tag:i.tag,payload:i.payload,callback:i.callback,next:null};null===a?r=a=s:a=a.next=s,i=i.next}while(null!==i);null===a?r=a=t:a=a.next=t}else r=a=t;return i={baseState:n.baseState,firstBaseUpdate:r,lastBaseUpdate:a,shared:n.shared,effects:n.effects},void(e.updateQueue=i)}null===(e=i.lastBaseUpdate)?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}function Fa(e,t,i,n){var r=e.updateQueue;Ma=!1;var a=r.firstBaseUpdate,s=r.lastBaseUpdate,o=r.shared.pending;if(null!==o){r.shared.pending=null;var l=o,c=l.next;l.next=null,null===s?a=c:s.next=c,s=l;var d=e.alternate;null!==d&&(o=(d=d.updateQueue).lastBaseUpdate)!==s&&(null===o?d.firstBaseUpdate=c:o.next=c,d.lastBaseUpdate=l)}if(null!==a){var u=r.baseState;for(s=0,d=c=l=null,o=a;;){var h=o.lane,p=o.eventTime;if((n&h)===h){null!==d&&(d=d.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=e,m=o;switch(h=t,p=i,m.tag){case 1:if("function"==typeof(g=m.payload)){u=g.call(p,u,h);break e}u=g;break e;case 3:g.flags=-65537&g.flags|128;case 0:if(null==(h="function"==typeof(g=m.payload)?g.call(p,u,h):g))break e;u=F({},u,h);break e;case 2:Ma=!0}}null!==o.callback&&0!==o.lane&&(e.flags|=64,null===(h=r.effects)?r.effects=[o]:h.push(o))}else p={eventTime:p,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},null===d?(c=d=p,l=u):d=d.next=p,s|=h;if(null===(o=o.next)){if(null===(o=r.shared.pending))break;o=(h=o).next,h.next=null,r.lastBaseUpdate=h,r.shared.pending=null}}if(null===d&&(l=u),r.baseState=l,r.firstBaseUpdate=c,r.lastBaseUpdate=d,null!==(t=r.shared.interleaved)){r=t;do{s|=r.lane,r=r.next}while(r!==t)}else null===a&&(r.shared.lanes=0);Fl|=s,e.lanes=s,e.memoizedState=u}}function Ua(e,t,i){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var n=e[t],r=n.callback;if(null!==r){if(n.callback=null,n=i,"function"!=typeof r)throw Error(a(191,r));r.call(n)}}}var Ba=(new n.Component).refs;function Va(e,t,i,n){i=null==(i=i(n,t=e.memoizedState))?t:F({},t,i),e.memoizedState=i,0===e.lanes&&(e.updateQueue.baseState=i)}var Ha={isMounted:function(e){return!!(e=e._reactInternals)&&$e(e)===e},enqueueSetState:function(e,t,i){e=e._reactInternals;var n=tc(),r=ic(e),a=Oa(n,r);a.payload=t,null!=i&&(a.callback=i),null!==(t=Na(e,a,r))&&(nc(t,e,r,n),La(t,e,r))},enqueueReplaceState:function(e,t,i){e=e._reactInternals;var n=tc(),r=ic(e),a=Oa(n,r);a.tag=1,a.payload=t,null!=i&&(a.callback=i),null!==(t=Na(e,a,r))&&(nc(t,e,r,n),La(t,e,r))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var i=tc(),n=ic(e),r=Oa(i,n);r.tag=2,null!=t&&(r.callback=t),null!==(t=Na(e,r,n))&&(nc(t,e,n,i),La(t,e,n))}};function $a(e,t,i,n,r,a,s){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(n,a,s):!(t.prototype&&t.prototype.isPureReactComponent&&ln(i,n)&&ln(r,a))}function Ga(e,t,i){var n=!1,r=Rr,a=t.contextType;return"object"==typeof a&&null!==a?a=Ia(a):(r=Dr(t)?Mr:Ar.current,a=(n=null!=(n=t.contextTypes))?kr(e,r):Rr),t=new t(i,a),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=Ha,e.stateNode=t,t._reactInternals=e,n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=r,e.__reactInternalMemoizedMaskedChildContext=a),t}function ja(e,t,i,n){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(i,n),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(i,n),t.state!==e&&Ha.enqueueReplaceState(t,t.state,null)}function za(e,t,i,n){var r=e.stateNode;r.props=i,r.state=e.memoizedState,r.refs=Ba,ka(e);var a=t.contextType;"object"==typeof a&&null!==a?r.context=Ia(a):(a=Dr(t)?Mr:Ar.current,r.context=kr(e,a)),r.state=e.memoizedState,"function"==typeof(a=t.getDerivedStateFromProps)&&(Va(e,t,a,i),r.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof r.getSnapshotBeforeUpdate||"function"!=typeof r.UNSAFE_componentWillMount&&"function"!=typeof r.componentWillMount||(t=r.state,"function"==typeof r.componentWillMount&&r.componentWillMount(),"function"==typeof r.UNSAFE_componentWillMount&&r.UNSAFE_componentWillMount(),t!==r.state&&Ha.enqueueReplaceState(r,r.state,null),Fa(e,i,r,n),r.state=e.memoizedState),"function"==typeof r.componentDidMount&&(e.flags|=4194308)}function Wa(e,t,i){if(null!==(e=i.ref)&&"function"!=typeof e&&"object"!=typeof e){if(i._owner){if(i=i._owner){if(1!==i.tag)throw Error(a(309));var n=i.stateNode}if(!n)throw Error(a(147,e));var r=n,s=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===s?t.ref:(t=function(e){var t=r.refs;t===Ba&&(t=r.refs={}),null===e?delete t[s]:t[s]=e},t._stringRef=s,t)}if("string"!=typeof e)throw Error(a(284));if(!i._owner)throw Error(a(290,e))}return e}function qa(e,t){throw e=Object.prototype.toString.call(t),Error(a(31,"[object Object]"===e?"object with keys {"+Object.keys(t).join(", ")+"}":e))}function Ka(e){return(0,e._init)(e._payload)}function Ja(e){function t(t,i){if(e){var n=t.deletions;null===n?(t.deletions=[i],t.flags|=16):n.push(i)}}function i(i,n){if(!e)return null;for(;null!==n;)t(i,n),n=n.sibling;return null}function n(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function r(e,t){return(e=Nc(e,t)).index=0,e.sibling=null,e}function s(t,i,n){return t.index=n,e?null!==(n=t.alternate)?(n=n.index)<i?(t.flags|=2,i):n:(t.flags|=2,i):(t.flags|=1048576,i)}function o(t){return e&&null===t.alternate&&(t.flags|=2),t}function l(e,t,i,n){return null===t||6!==t.tag?((t=Uc(i,e.mode,n)).return=e,t):((t=r(t,i)).return=e,t)}function c(e,t,i,n){var a=i.type;return a===T?u(e,t,i.props.children,n,i.key):null!==t&&(t.elementType===a||"object"==typeof a&&null!==a&&a.$$typeof===D&&Ka(a)===t.type)?((n=r(t,i.props)).ref=Wa(e,t,i),n.return=e,n):((n=Lc(i.type,i.key,i.props,null,e.mode,n)).ref=Wa(e,t,i),n.return=e,n)}function d(e,t,i,n){return null===t||4!==t.tag||t.stateNode.containerInfo!==i.containerInfo||t.stateNode.implementation!==i.implementation?((t=Bc(i,e.mode,n)).return=e,t):((t=r(t,i.children||[])).return=e,t)}function u(e,t,i,n,a){return null===t||7!==t.tag?((t=xc(i,e.mode,n,a)).return=e,t):((t=r(t,i)).return=e,t)}function h(e,t,i){if("string"==typeof t&&""!==t||"number"==typeof t)return(t=Uc(""+t,e.mode,i)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case _:return(i=Lc(t.type,t.key,t.props,null,e.mode,i)).ref=Wa(e,null,t),i.return=e,i;case E:return(t=Bc(t,e.mode,i)).return=e,t;case D:return h(e,(0,t._init)(t._payload),i)}if(te(t)||L(t))return(t=xc(t,e.mode,i,null)).return=e,t;qa(e,t)}return null}function p(e,t,i,n){var r=null!==t?t.key:null;if("string"==typeof i&&""!==i||"number"==typeof i)return null!==r?null:l(e,t,""+i,n);if("object"==typeof i&&null!==i){switch(i.$$typeof){case _:return i.key===r?c(e,t,i,n):null;case E:return i.key===r?d(e,t,i,n):null;case D:return p(e,t,(r=i._init)(i._payload),n)}if(te(i)||L(i))return null!==r?null:u(e,t,i,n,null);qa(e,i)}return null}function g(e,t,i,n,r){if("string"==typeof n&&""!==n||"number"==typeof n)return l(t,e=e.get(i)||null,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case _:return c(t,e=e.get(null===n.key?i:n.key)||null,n,r);case E:return d(t,e=e.get(null===n.key?i:n.key)||null,n,r);case D:return g(e,t,i,(0,n._init)(n._payload),r)}if(te(n)||L(n))return u(t,e=e.get(i)||null,n,r,null);qa(t,n)}return null}function m(r,a,o,l){for(var c=null,d=null,u=a,m=a=0,f=null;null!==u&&m<o.length;m++){u.index>m?(f=u,u=null):f=u.sibling;var v=p(r,u,o[m],l);if(null===v){null===u&&(u=f);break}e&&u&&null===v.alternate&&t(r,u),a=s(v,a,m),null===d?c=v:d.sibling=v,d=v,u=f}if(m===o.length)return i(r,u),ra&&Zr(r,m),c;if(null===u){for(;m<o.length;m++)null!==(u=h(r,o[m],l))&&(a=s(u,a,m),null===d?c=u:d.sibling=u,d=u);return ra&&Zr(r,m),c}for(u=n(r,u);m<o.length;m++)null!==(f=g(u,r,m,o[m],l))&&(e&&null!==f.alternate&&u.delete(null===f.key?m:f.key),a=s(f,a,m),null===d?c=f:d.sibling=f,d=f);return e&&u.forEach((function(e){return t(r,e)})),ra&&Zr(r,m),c}function f(r,o,l,c){var d=L(l);if("function"!=typeof d)throw Error(a(150));if(null==(l=d.call(l)))throw Error(a(151));for(var u=d=null,m=o,f=o=0,v=null,S=l.next();null!==m&&!S.done;f++,S=l.next()){m.index>f?(v=m,m=null):v=m.sibling;var y=p(r,m,S.value,c);if(null===y){null===m&&(m=v);break}e&&m&&null===y.alternate&&t(r,m),o=s(y,o,f),null===u?d=y:u.sibling=y,u=y,m=v}if(S.done)return i(r,m),ra&&Zr(r,f),d;if(null===m){for(;!S.done;f++,S=l.next())null!==(S=h(r,S.value,c))&&(o=s(S,o,f),null===u?d=S:u.sibling=S,u=S);return ra&&Zr(r,f),d}for(m=n(r,m);!S.done;f++,S=l.next())null!==(S=g(m,r,f,S.value,c))&&(e&&null!==S.alternate&&m.delete(null===S.key?f:S.key),o=s(S,o,f),null===u?d=S:u.sibling=S,u=S);return e&&m.forEach((function(e){return t(r,e)})),ra&&Zr(r,f),d}return function e(n,a,s,l){if("object"==typeof s&&null!==s&&s.type===T&&null===s.key&&(s=s.props.children),"object"==typeof s&&null!==s){switch(s.$$typeof){case _:e:{for(var c=s.key,d=a;null!==d;){if(d.key===c){if((c=s.type)===T){if(7===d.tag){i(n,d.sibling),(a=r(d,s.props.children)).return=n,n=a;break e}}else if(d.elementType===c||"object"==typeof c&&null!==c&&c.$$typeof===D&&Ka(c)===d.type){i(n,d.sibling),(a=r(d,s.props)).ref=Wa(n,d,s),a.return=n,n=a;break e}i(n,d);break}t(n,d),d=d.sibling}s.type===T?((a=xc(s.props.children,n.mode,l,s.key)).return=n,n=a):((l=Lc(s.type,s.key,s.props,null,n.mode,l)).ref=Wa(n,a,s),l.return=n,n=l)}return o(n);case E:e:{for(d=s.key;null!==a;){if(a.key===d){if(4===a.tag&&a.stateNode.containerInfo===s.containerInfo&&a.stateNode.implementation===s.implementation){i(n,a.sibling),(a=r(a,s.children||[])).return=n,n=a;break e}i(n,a);break}t(n,a),a=a.sibling}(a=Bc(s,n.mode,l)).return=n,n=a}return o(n);case D:return e(n,a,(d=s._init)(s._payload),l)}if(te(s))return m(n,a,s,l);if(L(s))return f(n,a,s,l);qa(n,s)}return"string"==typeof s&&""!==s||"number"==typeof s?(s=""+s,null!==a&&6===a.tag?(i(n,a.sibling),(a=r(a,s)).return=n,n=a):(i(n,a),(a=Uc(s,n.mode,l)).return=n,n=a),o(n)):i(n,a)}}var Ya=Ja(!0),Qa=Ja(!1),Za={},Xa=br(Za),es=br(Za),ts=br(Za);function is(e){if(e===Za)throw Error(a(174));return e}function ns(e,t){switch(wr(ts,t),wr(es,e),wr(Xa,Za),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:le(null,"");break;default:t=le(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}Ir(Xa),wr(Xa,t)}function rs(){Ir(Xa),Ir(es),Ir(ts)}function as(e){is(ts.current);var t=is(Xa.current),i=le(t,e.type);t!==i&&(wr(es,e),wr(Xa,i))}function ss(e){es.current===e&&(Ir(Xa),Ir(es))}var os=br(0);function ls(e){for(var t=e;null!==t;){if(13===t.tag){var i=t.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(128&t.flags)return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var cs=[];function ds(){for(var e=0;e<cs.length;e++)cs[e]._workInProgressVersionPrimary=null;cs.length=0}var us=C.ReactCurrentDispatcher,hs=C.ReactCurrentBatchConfig,ps=0,gs=null,ms=null,fs=null,vs=!1,Ss=!1,ys=0,Cs=0;function _s(){throw Error(a(321))}function Es(e,t){if(null===t)return!1;for(var i=0;i<t.length&&i<e.length;i++)if(!on(e[i],t[i]))return!1;return!0}function Ts(e,t,i,n,r,s){if(ps=s,gs=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,us.current=null===e||null===e.memoizedState?so:oo,e=i(n,r),Ss){s=0;do{if(Ss=!1,ys=0,25<=s)throw Error(a(301));s+=1,fs=ms=null,t.updateQueue=null,us.current=lo,e=i(n,r)}while(Ss)}if(us.current=ao,t=null!==ms&&null!==ms.next,ps=0,fs=ms=gs=null,vs=!1,t)throw Error(a(300));return e}function bs(){var e=0!==ys;return ys=0,e}function Is(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===fs?gs.memoizedState=fs=e:fs=fs.next=e,fs}function ws(){if(null===ms){var e=gs.alternate;e=null!==e?e.memoizedState:null}else e=ms.next;var t=null===fs?gs.memoizedState:fs.next;if(null!==t)fs=t,ms=e;else{if(null===e)throw Error(a(310));e={memoizedState:(ms=e).memoizedState,baseState:ms.baseState,baseQueue:ms.baseQueue,queue:ms.queue,next:null},null===fs?gs.memoizedState=fs=e:fs=fs.next=e}return fs}function Rs(e,t){return"function"==typeof t?t(e):t}function As(e){var t=ws(),i=t.queue;if(null===i)throw Error(a(311));i.lastRenderedReducer=e;var n=ms,r=n.baseQueue,s=i.pending;if(null!==s){if(null!==r){var o=r.next;r.next=s.next,s.next=o}n.baseQueue=r=s,i.pending=null}if(null!==r){s=r.next,n=n.baseState;var l=o=null,c=null,d=s;do{var u=d.lane;if((ps&u)===u)null!==c&&(c=c.next={lane:0,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null}),n=d.hasEagerState?d.eagerState:e(n,d.action);else{var h={lane:u,action:d.action,hasEagerState:d.hasEagerState,eagerState:d.eagerState,next:null};null===c?(l=c=h,o=n):c=c.next=h,gs.lanes|=u,Fl|=u}d=d.next}while(null!==d&&d!==s);null===c?o=n:c.next=l,on(n,t.memoizedState)||(Co=!0),t.memoizedState=n,t.baseState=o,t.baseQueue=c,i.lastRenderedState=n}if(null!==(e=i.interleaved)){r=e;do{s=r.lane,gs.lanes|=s,Fl|=s,r=r.next}while(r!==e)}else null===r&&(i.lanes=0);return[t.memoizedState,i.dispatch]}function Ps(e){var t=ws(),i=t.queue;if(null===i)throw Error(a(311));i.lastRenderedReducer=e;var n=i.dispatch,r=i.pending,s=t.memoizedState;if(null!==r){i.pending=null;var o=r=r.next;do{s=e(s,o.action),o=o.next}while(o!==r);on(s,t.memoizedState)||(Co=!0),t.memoizedState=s,null===t.baseQueue&&(t.baseState=s),i.lastRenderedState=s}return[s,n]}function Ms(){}function ks(e,t){var i=gs,n=ws(),r=t(),s=!on(n.memoizedState,r);if(s&&(n.memoizedState=r,Co=!0),n=n.queue,Gs(Ns.bind(null,i,n,e),[e]),n.getSnapshot!==t||s||null!==fs&&1&fs.memoizedState.tag){if(i.flags|=2048,Us(9,Os.bind(null,i,n,r,t),void 0,null),null===Ml)throw Error(a(349));30&ps||Ds(i,t,r)}return r}function Ds(e,t,i){e.flags|=16384,e={getSnapshot:t,value:i},null===(t=gs.updateQueue)?(t={lastEffect:null,stores:null},gs.updateQueue=t,t.stores=[e]):null===(i=t.stores)?t.stores=[e]:i.push(e)}function Os(e,t,i,n){t.value=i,t.getSnapshot=n,Ls(t)&&xs(e)}function Ns(e,t,i){return i((function(){Ls(t)&&xs(e)}))}function Ls(e){var t=e.getSnapshot;e=e.value;try{var i=t();return!on(e,i)}catch(e){return!0}}function xs(e){var t=Pa(e,1);null!==t&&nc(t,e,1,-1)}function Fs(e){var t=Is();return"function"==typeof e&&(e=e()),t.memoizedState=t.baseState=e,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Rs,lastRenderedState:e},t.queue=e,e=e.dispatch=to.bind(null,gs,e),[t.memoizedState,e]}function Us(e,t,i,n){return e={tag:e,create:t,destroy:i,deps:n,next:null},null===(t=gs.updateQueue)?(t={lastEffect:null,stores:null},gs.updateQueue=t,t.lastEffect=e.next=e):null===(i=t.lastEffect)?t.lastEffect=e.next=e:(n=i.next,i.next=e,e.next=n,t.lastEffect=e),e}function Bs(){return ws().memoizedState}function Vs(e,t,i,n){var r=Is();gs.flags|=e,r.memoizedState=Us(1|t,i,void 0,void 0===n?null:n)}function Hs(e,t,i,n){var r=ws();n=void 0===n?null:n;var a=void 0;if(null!==ms){var s=ms.memoizedState;if(a=s.destroy,null!==n&&Es(n,s.deps))return void(r.memoizedState=Us(t,i,a,n))}gs.flags|=e,r.memoizedState=Us(1|t,i,a,n)}function $s(e,t){return Vs(8390656,8,e,t)}function Gs(e,t){return Hs(2048,8,e,t)}function js(e,t){return Hs(4,2,e,t)}function zs(e,t){return Hs(4,4,e,t)}function Ws(e,t){return"function"==typeof t?(e=e(),t(e),function(){t(null)}):null!=t?(e=e(),t.current=e,function(){t.current=null}):void 0}function qs(e,t,i){return i=null!=i?i.concat([e]):null,Hs(4,4,Ws.bind(null,t,e),i)}function Ks(){}function Js(e,t){var i=ws();t=void 0===t?null:t;var n=i.memoizedState;return null!==n&&null!==t&&Es(t,n[1])?n[0]:(i.memoizedState=[e,t],e)}function Ys(e,t){var i=ws();t=void 0===t?null:t;var n=i.memoizedState;return null!==n&&null!==t&&Es(t,n[1])?n[0]:(e=e(),i.memoizedState=[e,t],e)}function Qs(e,t,i){return 21&ps?(on(i,t)||(i=mt(),gs.lanes|=i,Fl|=i,e.baseState=!0),t):(e.baseState&&(e.baseState=!1,Co=!0),e.memoizedState=i)}function Zs(e,t){var i=yt;yt=0!==i&&4>i?i:4,e(!0);var n=hs.transition;hs.transition={};try{e(!1),t()}finally{yt=i,hs.transition=n}}function Xs(){return ws().memoizedState}function eo(e,t,i){var n=ic(e);i={lane:n,action:i,hasEagerState:!1,eagerState:null,next:null},io(e)?no(t,i):null!==(i=Aa(e,t,i,n))&&(nc(i,e,n,tc()),ro(i,t,n))}function to(e,t,i){var n=ic(e),r={lane:n,action:i,hasEagerState:!1,eagerState:null,next:null};if(io(e))no(t,r);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=t.lastRenderedReducer))try{var s=t.lastRenderedState,o=a(s,i);if(r.hasEagerState=!0,r.eagerState=o,on(o,s)){var l=t.interleaved;return null===l?(r.next=r,Ra(t)):(r.next=l.next,l.next=r),void(t.interleaved=r)}}catch(e){}null!==(i=Aa(e,t,r,n))&&(nc(i,e,n,r=tc()),ro(i,t,n))}}function io(e){var t=e.alternate;return e===gs||null!==t&&t===gs}function no(e,t){Ss=vs=!0;var i=e.pending;null===i?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function ro(e,t,i){if(4194240&i){var n=t.lanes;i|=n&=e.pendingLanes,t.lanes=i,St(e,i)}}var ao={readContext:Ia,useCallback:_s,useContext:_s,useEffect:_s,useImperativeHandle:_s,useInsertionEffect:_s,useLayoutEffect:_s,useMemo:_s,useReducer:_s,useRef:_s,useState:_s,useDebugValue:_s,useDeferredValue:_s,useTransition:_s,useMutableSource:_s,useSyncExternalStore:_s,useId:_s,unstable_isNewReconciler:!1},so={readContext:Ia,useCallback:function(e,t){return Is().memoizedState=[e,void 0===t?null:t],e},useContext:Ia,useEffect:$s,useImperativeHandle:function(e,t,i){return i=null!=i?i.concat([e]):null,Vs(4194308,4,Ws.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Vs(4194308,4,e,t)},useInsertionEffect:function(e,t){return Vs(4,2,e,t)},useMemo:function(e,t){var i=Is();return t=void 0===t?null:t,e=e(),i.memoizedState=[e,t],e},useReducer:function(e,t,i){var n=Is();return t=void 0!==i?i(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=eo.bind(null,gs,e),[n.memoizedState,e]},useRef:function(e){return e={current:e},Is().memoizedState=e},useState:Fs,useDebugValue:Ks,useDeferredValue:function(e){return Is().memoizedState=e},useTransition:function(){var e=Fs(!1),t=e[0];return e=Zs.bind(null,e[1]),Is().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,i){var n=gs,r=Is();if(ra){if(void 0===i)throw Error(a(407));i=i()}else{if(i=t(),null===Ml)throw Error(a(349));30&ps||Ds(n,t,i)}r.memoizedState=i;var s={value:i,getSnapshot:t};return r.queue=s,$s(Ns.bind(null,n,s,e),[e]),n.flags|=2048,Us(9,Os.bind(null,n,s,i,t),void 0,null),i},useId:function(){var e=Is(),t=Ml.identifierPrefix;if(ra){var i=Qr;t=":"+t+"R"+(i=(Yr&~(1<<32-st(Yr)-1)).toString(32)+i),0<(i=ys++)&&(t+="H"+i.toString(32)),t+=":"}else t=":"+t+"r"+(i=Cs++).toString(32)+":";return e.memoizedState=t},unstable_isNewReconciler:!1},oo={readContext:Ia,useCallback:Js,useContext:Ia,useEffect:Gs,useImperativeHandle:qs,useInsertionEffect:js,useLayoutEffect:zs,useMemo:Ys,useReducer:As,useRef:Bs,useState:function(){return As(Rs)},useDebugValue:Ks,useDeferredValue:function(e){return Qs(ws(),ms.memoizedState,e)},useTransition:function(){return[As(Rs)[0],ws().memoizedState]},useMutableSource:Ms,useSyncExternalStore:ks,useId:Xs,unstable_isNewReconciler:!1},lo={readContext:Ia,useCallback:Js,useContext:Ia,useEffect:Gs,useImperativeHandle:qs,useInsertionEffect:js,useLayoutEffect:zs,useMemo:Ys,useReducer:Ps,useRef:Bs,useState:function(){return Ps(Rs)},useDebugValue:Ks,useDeferredValue:function(e){var t=ws();return null===ms?t.memoizedState=e:Qs(t,ms.memoizedState,e)},useTransition:function(){return[Ps(Rs)[0],ws().memoizedState]},useMutableSource:Ms,useSyncExternalStore:ks,useId:Xs,unstable_isNewReconciler:!1};function co(e,t){try{var i="",n=t;do{i+=H(n),n=n.return}while(n);var r=i}catch(e){r="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:t,stack:r,digest:null}}function uo(e,t,i){return{value:e,source:null,stack:null!=i?i:null,digest:null!=t?t:null}}function ho(e,t){try{console.error(t.value)}catch(e){setTimeout((function(){throw e}))}}var po="function"==typeof WeakMap?WeakMap:Map;function go(e,t,i){(i=Oa(-1,i)).tag=3,i.payload={element:null};var n=t.value;return i.callback=function(){zl||(zl=!0,Wl=n),ho(0,t)},i}function mo(e,t,i){(i=Oa(-1,i)).tag=3;var n=e.type.getDerivedStateFromError;if("function"==typeof n){var r=t.value;i.payload=function(){return n(r)},i.callback=function(){ho(0,t)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(i.callback=function(){ho(0,t),"function"!=typeof n&&(null===ql?ql=new Set([this]):ql.add(this));var e=t.stack;this.componentDidCatch(t.value,{componentStack:null!==e?e:""})}),i}function fo(e,t,i){var n=e.pingCache;if(null===n){n=e.pingCache=new po;var r=new Set;n.set(t,r)}else void 0===(r=n.get(t))&&(r=new Set,n.set(t,r));r.has(i)||(r.add(i),e=wc.bind(null,e,t,i),t.then(e,e))}function vo(e){do{var t;if((t=13===e.tag)&&(t=null===(t=e.memoizedState)||null!==t.dehydrated),t)return e;e=e.return}while(null!==e);return null}function So(e,t,i,n,r){return 1&e.mode?(e.flags|=65536,e.lanes=r,e):(e===t?e.flags|=65536:(e.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((t=Oa(-1,1)).tag=2,Na(i,t,1))),i.lanes|=1),e)}var yo=C.ReactCurrentOwner,Co=!1;function _o(e,t,i,n){t.child=null===e?Qa(t,null,i,n):Ya(t,e.child,i,n)}function Eo(e,t,i,n,r){i=i.render;var a=t.ref;return ba(t,r),n=Ts(e,t,i,n,a,r),i=bs(),null===e||Co?(ra&&i&&ea(t),t.flags|=1,_o(e,t,n,r),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~r,zo(e,t,r))}function To(e,t,i,n,r){if(null===e){var a=i.type;return"function"!=typeof a||Oc(a)||void 0!==a.defaultProps||null!==i.compare||void 0!==i.defaultProps?((e=Lc(i.type,null,n,t,t.mode,r)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=a,bo(e,t,a,n,r))}if(a=e.child,!(e.lanes&r)){var s=a.memoizedProps;if((i=null!==(i=i.compare)?i:ln)(s,n)&&e.ref===t.ref)return zo(e,t,r)}return t.flags|=1,(e=Nc(a,n)).ref=t.ref,e.return=t,t.child=e}function bo(e,t,i,n,r){if(null!==e){var a=e.memoizedProps;if(ln(a,n)&&e.ref===t.ref){if(Co=!1,t.pendingProps=n=a,!(e.lanes&r))return t.lanes=e.lanes,zo(e,t,r);131072&e.flags&&(Co=!0)}}return Ro(e,t,i,n,r)}function Io(e,t,i){var n=t.pendingProps,r=n.children,a=null!==e?e.memoizedState:null;if("hidden"===n.mode)if(1&t.mode){if(!(1073741824&i))return e=null!==a?a.baseLanes|i:i,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,wr(Nl,Ol),Ol|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},n=null!==a?a.baseLanes:i,wr(Nl,Ol),Ol|=n}else t.memoizedState={baseLanes:0,cachePool:null,transitions:null},wr(Nl,Ol),Ol|=i;else null!==a?(n=a.baseLanes|i,t.memoizedState=null):n=i,wr(Nl,Ol),Ol|=n;return _o(e,t,r,i),t.child}function wo(e,t){var i=t.ref;(null===e&&null!==i||null!==e&&e.ref!==i)&&(t.flags|=512,t.flags|=2097152)}function Ro(e,t,i,n,r){var a=Dr(i)?Mr:Ar.current;return a=kr(t,a),ba(t,r),i=Ts(e,t,i,n,a,r),n=bs(),null===e||Co?(ra&&n&&ea(t),t.flags|=1,_o(e,t,i,r),t.child):(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~r,zo(e,t,r))}function Ao(e,t,i,n,r){if(Dr(i)){var a=!0;xr(t)}else a=!1;if(ba(t,r),null===t.stateNode)jo(e,t),Ga(t,i,n),za(t,i,n,r),n=!0;else if(null===e){var s=t.stateNode,o=t.memoizedProps;s.props=o;var l=s.context,c=i.contextType;c="object"==typeof c&&null!==c?Ia(c):kr(t,c=Dr(i)?Mr:Ar.current);var d=i.getDerivedStateFromProps,u="function"==typeof d||"function"==typeof s.getSnapshotBeforeUpdate;u||"function"!=typeof s.UNSAFE_componentWillReceiveProps&&"function"!=typeof s.componentWillReceiveProps||(o!==n||l!==c)&&ja(t,s,n,c),Ma=!1;var h=t.memoizedState;s.state=h,Fa(t,n,s,r),l=t.memoizedState,o!==n||h!==l||Pr.current||Ma?("function"==typeof d&&(Va(t,i,d,n),l=t.memoizedState),(o=Ma||$a(t,i,o,n,h,l,c))?(u||"function"!=typeof s.UNSAFE_componentWillMount&&"function"!=typeof s.componentWillMount||("function"==typeof s.componentWillMount&&s.componentWillMount(),"function"==typeof s.UNSAFE_componentWillMount&&s.UNSAFE_componentWillMount()),"function"==typeof s.componentDidMount&&(t.flags|=4194308)):("function"==typeof s.componentDidMount&&(t.flags|=4194308),t.memoizedProps=n,t.memoizedState=l),s.props=n,s.state=l,s.context=c,n=o):("function"==typeof s.componentDidMount&&(t.flags|=4194308),n=!1)}else{s=t.stateNode,Da(e,t),o=t.memoizedProps,c=t.type===t.elementType?o:fa(t.type,o),s.props=c,u=t.pendingProps,h=s.context,l="object"==typeof(l=i.contextType)&&null!==l?Ia(l):kr(t,l=Dr(i)?Mr:Ar.current);var p=i.getDerivedStateFromProps;(d="function"==typeof p||"function"==typeof s.getSnapshotBeforeUpdate)||"function"!=typeof s.UNSAFE_componentWillReceiveProps&&"function"!=typeof s.componentWillReceiveProps||(o!==u||h!==l)&&ja(t,s,n,l),Ma=!1,h=t.memoizedState,s.state=h,Fa(t,n,s,r);var g=t.memoizedState;o!==u||h!==g||Pr.current||Ma?("function"==typeof p&&(Va(t,i,p,n),g=t.memoizedState),(c=Ma||$a(t,i,c,n,h,g,l)||!1)?(d||"function"!=typeof s.UNSAFE_componentWillUpdate&&"function"!=typeof s.componentWillUpdate||("function"==typeof s.componentWillUpdate&&s.componentWillUpdate(n,g,l),"function"==typeof s.UNSAFE_componentWillUpdate&&s.UNSAFE_componentWillUpdate(n,g,l)),"function"==typeof s.componentDidUpdate&&(t.flags|=4),"function"==typeof s.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!=typeof s.componentDidUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),"function"!=typeof s.getSnapshotBeforeUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),t.memoizedProps=n,t.memoizedState=g),s.props=n,s.state=g,s.context=l,n=c):("function"!=typeof s.componentDidUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=4),"function"!=typeof s.getSnapshotBeforeUpdate||o===e.memoizedProps&&h===e.memoizedState||(t.flags|=1024),n=!1)}return Po(e,t,i,n,a,r)}function Po(e,t,i,n,r,a){wo(e,t);var s=!!(128&t.flags);if(!n&&!s)return r&&Fr(t,i,!1),zo(e,t,a);n=t.stateNode,yo.current=t;var o=s&&"function"!=typeof i.getDerivedStateFromError?null:n.render();return t.flags|=1,null!==e&&s?(t.child=Ya(t,e.child,null,a),t.child=Ya(t,null,o,a)):_o(e,t,o,a),t.memoizedState=n.state,r&&Fr(t,i,!0),t.child}function Mo(e){var t=e.stateNode;t.pendingContext?Nr(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Nr(0,t.context,!1),ns(e,t.containerInfo)}function ko(e,t,i,n,r){return pa(),ga(r),t.flags|=256,_o(e,t,i,n),t.child}var Do,Oo,No,Lo,xo={dehydrated:null,treeContext:null,retryLane:0};function Fo(e){return{baseLanes:e,cachePool:null,transitions:null}}function Uo(e,t,i){var n,r=t.pendingProps,s=os.current,o=!1,l=!!(128&t.flags);if((n=l)||(n=(null===e||null!==e.memoizedState)&&!!(2&s)),n?(o=!0,t.flags&=-129):null!==e&&null===e.memoizedState||(s|=1),wr(os,1&s),null===e)return ca(t),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated)?(1&t.mode?"$!"===e.data?t.lanes=8:t.lanes=1073741824:t.lanes=1,null):(l=r.children,e=r.fallback,o?(r=t.mode,o=t.child,l={mode:"hidden",children:l},1&r||null===o?o=Fc(l,r,0,null):(o.childLanes=0,o.pendingProps=l),e=xc(e,r,i,null),o.return=t,e.return=t,o.sibling=e,t.child=o,t.child.memoizedState=Fo(i),t.memoizedState=xo,e):Bo(t,l));if(null!==(s=e.memoizedState)&&null!==(n=s.dehydrated))return function(e,t,i,n,r,s,o){if(i)return 256&t.flags?(t.flags&=-257,Vo(e,t,o,n=uo(Error(a(422))))):null!==t.memoizedState?(t.child=e.child,t.flags|=128,null):(s=n.fallback,r=t.mode,n=Fc({mode:"visible",children:n.children},r,0,null),(s=xc(s,r,o,null)).flags|=2,n.return=t,s.return=t,n.sibling=s,t.child=n,1&t.mode&&Ya(t,e.child,null,o),t.child.memoizedState=Fo(o),t.memoizedState=xo,s);if(!(1&t.mode))return Vo(e,t,o,null);if("$!"===r.data){if(n=r.nextSibling&&r.nextSibling.dataset)var l=n.dgst;return n=l,Vo(e,t,o,n=uo(s=Error(a(419)),n,void 0))}if(l=!!(o&e.childLanes),Co||l){if(null!==(n=Ml)){switch(o&-o){case 4:r=2;break;case 16:r=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:r=32;break;case 536870912:r=268435456;break;default:r=0}0!==(r=r&(n.suspendedLanes|o)?0:r)&&r!==s.retryLane&&(s.retryLane=r,Pa(e,r),nc(n,e,r,-1))}return fc(),Vo(e,t,o,n=uo(Error(a(421))))}return"$?"===r.data?(t.flags|=128,t.child=e.child,t=Ac.bind(null,e),r._reactRetry=t,null):(e=s.treeContext,na=cr(r.nextSibling),ia=t,ra=!0,aa=null,null!==e&&(qr[Kr++]=Yr,qr[Kr++]=Qr,qr[Kr++]=Jr,Yr=e.id,Qr=e.overflow,Jr=t),(t=Bo(t,n.children)).flags|=4096,t)}(e,t,l,r,n,s,i);if(o){o=r.fallback,l=t.mode,n=(s=e.child).sibling;var c={mode:"hidden",children:r.children};return 1&l||t.child===s?(r=Nc(s,c)).subtreeFlags=14680064&s.subtreeFlags:((r=t.child).childLanes=0,r.pendingProps=c,t.deletions=null),null!==n?o=Nc(n,o):(o=xc(o,l,i,null)).flags|=2,o.return=t,r.return=t,r.sibling=o,t.child=r,r=o,o=t.child,l=null===(l=e.child.memoizedState)?Fo(i):{baseLanes:l.baseLanes|i,cachePool:null,transitions:l.transitions},o.memoizedState=l,o.childLanes=e.childLanes&~i,t.memoizedState=xo,r}return e=(o=e.child).sibling,r=Nc(o,{mode:"visible",children:r.children}),!(1&t.mode)&&(r.lanes=i),r.return=t,r.sibling=null,null!==e&&(null===(i=t.deletions)?(t.deletions=[e],t.flags|=16):i.push(e)),t.child=r,t.memoizedState=null,r}function Bo(e,t){return(t=Fc({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function Vo(e,t,i,n){return null!==n&&ga(n),Ya(t,e.child,null,i),(e=Bo(t,t.pendingProps.children)).flags|=2,t.memoizedState=null,e}function Ho(e,t,i){e.lanes|=t;var n=e.alternate;null!==n&&(n.lanes|=t),Ta(e.return,t,i)}function $o(e,t,i,n,r){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:i,tailMode:r}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=n,a.tail=i,a.tailMode=r)}function Go(e,t,i){var n=t.pendingProps,r=n.revealOrder,a=n.tail;if(_o(e,t,n.children,i),2&(n=os.current))n=1&n|2,t.flags|=128;else{if(null!==e&&128&e.flags)e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Ho(e,i,t);else if(19===e.tag)Ho(e,i,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(wr(os,n),1&t.mode)switch(r){case"forwards":for(i=t.child,r=null;null!==i;)null!==(e=i.alternate)&&null===ls(e)&&(r=i),i=i.sibling;null===(i=r)?(r=t.child,t.child=null):(r=i.sibling,i.sibling=null),$o(t,!1,r,i,a);break;case"backwards":for(i=null,r=t.child,t.child=null;null!==r;){if(null!==(e=r.alternate)&&null===ls(e)){t.child=r;break}e=r.sibling,r.sibling=i,i=r,r=e}$o(t,!0,i,null,a);break;case"together":$o(t,!1,null,null,void 0);break;default:t.memoizedState=null}else t.memoizedState=null;return t.child}function jo(e,t){!(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function zo(e,t,i){if(null!==e&&(t.dependencies=e.dependencies),Fl|=t.lanes,!(i&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(a(153));if(null!==t.child){for(i=Nc(e=t.child,e.pendingProps),t.child=i,i.return=t;null!==e.sibling;)e=e.sibling,(i=i.sibling=Nc(e,e.pendingProps)).return=t;i.sibling=null}return t.child}function Wo(e,t){if(!ra)switch(e.tailMode){case"hidden":t=e.tail;for(var i=null;null!==t;)null!==t.alternate&&(i=t),t=t.sibling;null===i?e.tail=null:i.sibling=null;break;case"collapsed":i=e.tail;for(var n=null;null!==i;)null!==i.alternate&&(n=i),i=i.sibling;null===n?t||null===e.tail?e.tail=null:e.tail.sibling=null:n.sibling=null}}function qo(e){var t=null!==e.alternate&&e.alternate.child===e.child,i=0,n=0;if(t)for(var r=e.child;null!==r;)i|=r.lanes|r.childLanes,n|=14680064&r.subtreeFlags,n|=14680064&r.flags,r.return=e,r=r.sibling;else for(r=e.child;null!==r;)i|=r.lanes|r.childLanes,n|=r.subtreeFlags,n|=r.flags,r.return=e,r=r.sibling;return e.subtreeFlags|=n,e.childLanes=i,t}function Ko(e,t,i){var n=t.pendingProps;switch(ta(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qo(t),null;case 1:case 17:return Dr(t.type)&&Or(),qo(t),null;case 3:return n=t.stateNode,rs(),Ir(Pr),Ir(Ar),ds(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),null!==e&&null!==e.child||(ua(t)?t.flags|=4:null===e||e.memoizedState.isDehydrated&&!(256&t.flags)||(t.flags|=1024,null!==aa&&(oc(aa),aa=null))),Oo(e,t),qo(t),null;case 5:ss(t);var r=is(ts.current);if(i=t.type,null!==e&&null!=t.stateNode)No(e,t,i,n,r),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!n){if(null===t.stateNode)throw Error(a(166));return qo(t),null}if(e=is(Xa.current),ua(t)){n=t.stateNode,i=t.type;var s=t.memoizedProps;switch(n[hr]=t,n[pr]=s,e=!!(1&t.mode),i){case"dialog":Bn("cancel",n),Bn("close",n);break;case"iframe":case"object":case"embed":Bn("load",n);break;case"video":case"audio":for(r=0;r<Ln.length;r++)Bn(Ln[r],n);break;case"source":Bn("error",n);break;case"img":case"image":case"link":Bn("error",n),Bn("load",n);break;case"details":Bn("toggle",n);break;case"input":Y(n,s),Bn("invalid",n);break;case"select":n._wrapperState={wasMultiple:!!s.multiple},Bn("invalid",n);break;case"textarea":re(n,s),Bn("invalid",n)}for(var l in Se(i,s),r=null,s)if(s.hasOwnProperty(l)){var c=s[l];"children"===l?"string"==typeof c?n.textContent!==c&&(!0!==s.suppressHydrationWarning&&Zn(n.textContent,c,e),r=["children",c]):"number"==typeof c&&n.textContent!==""+c&&(!0!==s.suppressHydrationWarning&&Zn(n.textContent,c,e),r=["children",""+c]):o.hasOwnProperty(l)&&null!=c&&"onScroll"===l&&Bn("scroll",n)}switch(i){case"input":W(n),X(n,s,!0);break;case"textarea":W(n),se(n);break;case"select":case"option":break;default:"function"==typeof s.onClick&&(n.onclick=Xn)}n=r,t.updateQueue=n,null!==n&&(t.flags|=4)}else{l=9===r.nodeType?r:r.ownerDocument,"http://www.w3.org/1999/xhtml"===e&&(e=oe(i)),"http://www.w3.org/1999/xhtml"===e?"script"===i?((e=l.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"==typeof n.is?e=l.createElement(i,{is:n.is}):(e=l.createElement(i),"select"===i&&(l=e,n.multiple?l.multiple=!0:n.size&&(l.size=n.size))):e=l.createElementNS(e,i),e[hr]=t,e[pr]=n,Do(e,t,!1,!1),t.stateNode=e;e:{switch(l=ye(i,n),i){case"dialog":Bn("cancel",e),Bn("close",e),r=n;break;case"iframe":case"object":case"embed":Bn("load",e),r=n;break;case"video":case"audio":for(r=0;r<Ln.length;r++)Bn(Ln[r],e);r=n;break;case"source":Bn("error",e),r=n;break;case"img":case"image":case"link":Bn("error",e),Bn("load",e),r=n;break;case"details":Bn("toggle",e),r=n;break;case"input":Y(e,n),r=J(e,n),Bn("invalid",e);break;case"option":default:r=n;break;case"select":e._wrapperState={wasMultiple:!!n.multiple},r=F({},n,{value:void 0}),Bn("invalid",e);break;case"textarea":re(e,n),r=ne(e,n),Bn("invalid",e)}for(s in Se(i,r),c=r)if(c.hasOwnProperty(s)){var d=c[s];"style"===s?fe(e,d):"dangerouslySetInnerHTML"===s?null!=(d=d?d.__html:void 0)&&ue(e,d):"children"===s?"string"==typeof d?("textarea"!==i||""!==d)&&he(e,d):"number"==typeof d&&he(e,""+d):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(o.hasOwnProperty(s)?null!=d&&"onScroll"===s&&Bn("scroll",e):null!=d&&y(e,s,d,l))}switch(i){case"input":W(e),X(e,n,!1);break;case"textarea":W(e),se(e);break;case"option":null!=n.value&&e.setAttribute("value",""+j(n.value));break;case"select":e.multiple=!!n.multiple,null!=(s=n.value)?ie(e,!!n.multiple,s,!1):null!=n.defaultValue&&ie(e,!!n.multiple,n.defaultValue,!0);break;default:"function"==typeof r.onClick&&(e.onclick=Xn)}switch(i){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}}n&&(t.flags|=4)}null!==t.ref&&(t.flags|=512,t.flags|=2097152)}return qo(t),null;case 6:if(e&&null!=t.stateNode)Lo(e,t,e.memoizedProps,n);else{if("string"!=typeof n&&null===t.stateNode)throw Error(a(166));if(i=is(ts.current),is(Xa.current),ua(t)){if(n=t.stateNode,i=t.memoizedProps,n[hr]=t,(s=n.nodeValue!==i)&&null!==(e=ia))switch(e.tag){case 3:Zn(n.nodeValue,i,!!(1&e.mode));break;case 5:!0!==e.memoizedProps.suppressHydrationWarning&&Zn(n.nodeValue,i,!!(1&e.mode))}s&&(t.flags|=4)}else(n=(9===i.nodeType?i:i.ownerDocument).createTextNode(n))[hr]=t,t.stateNode=n}return qo(t),null;case 13:if(Ir(os),n=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(ra&&null!==na&&1&t.mode&&!(128&t.flags))ha(),pa(),t.flags|=98560,s=!1;else if(s=ua(t),null!==n&&null!==n.dehydrated){if(null===e){if(!s)throw Error(a(318));if(!(s=null!==(s=t.memoizedState)?s.dehydrated:null))throw Error(a(317));s[hr]=t}else pa(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;qo(t),s=!1}else null!==aa&&(oc(aa),aa=null),s=!0;if(!s)return 65536&t.flags?t:null}return 128&t.flags?(t.lanes=i,t):((n=null!==n)!=(null!==e&&null!==e.memoizedState)&&n&&(t.child.flags|=8192,1&t.mode&&(null===e||1&os.current?0===Ll&&(Ll=3):fc())),null!==t.updateQueue&&(t.flags|=4),qo(t),null);case 4:return rs(),Oo(e,t),null===e&&$n(t.stateNode.containerInfo),qo(t),null;case 10:return Ea(t.type._context),qo(t),null;case 19:if(Ir(os),null===(s=t.memoizedState))return qo(t),null;if(n=!!(128&t.flags),null===(l=s.rendering))if(n)Wo(s,!1);else{if(0!==Ll||null!==e&&128&e.flags)for(e=t.child;null!==e;){if(null!==(l=ls(e))){for(t.flags|=128,Wo(s,!1),null!==(n=l.updateQueue)&&(t.updateQueue=n,t.flags|=4),t.subtreeFlags=0,n=i,i=t.child;null!==i;)e=n,(s=i).flags&=14680066,null===(l=s.alternate)?(s.childLanes=0,s.lanes=e,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=l.childLanes,s.lanes=l.lanes,s.child=l.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=l.memoizedProps,s.memoizedState=l.memoizedState,s.updateQueue=l.updateQueue,s.type=l.type,e=l.dependencies,s.dependencies=null===e?null:{lanes:e.lanes,firstContext:e.firstContext}),i=i.sibling;return wr(os,1&os.current|2),t.child}e=e.sibling}null!==s.tail&&Qe()>Gl&&(t.flags|=128,n=!0,Wo(s,!1),t.lanes=4194304)}else{if(!n)if(null!==(e=ls(l))){if(t.flags|=128,n=!0,null!==(i=e.updateQueue)&&(t.updateQueue=i,t.flags|=4),Wo(s,!0),null===s.tail&&"hidden"===s.tailMode&&!l.alternate&&!ra)return qo(t),null}else 2*Qe()-s.renderingStartTime>Gl&&1073741824!==i&&(t.flags|=128,n=!0,Wo(s,!1),t.lanes=4194304);s.isBackwards?(l.sibling=t.child,t.child=l):(null!==(i=s.last)?i.sibling=l:t.child=l,s.last=l)}return null!==s.tail?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=Qe(),t.sibling=null,i=os.current,wr(os,n?1&i|2:1&i),t):(qo(t),null);case 22:case 23:return hc(),n=null!==t.memoizedState,null!==e&&null!==e.memoizedState!==n&&(t.flags|=8192),n&&1&t.mode?!!(1073741824&Ol)&&(qo(t),6&t.subtreeFlags&&(t.flags|=8192)):qo(t),null;case 24:case 25:return null}throw Error(a(156,t.tag))}function Jo(e,t){switch(ta(t),t.tag){case 1:return Dr(t.type)&&Or(),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return rs(),Ir(Pr),Ir(Ar),ds(),65536&(e=t.flags)&&!(128&e)?(t.flags=-65537&e|128,t):null;case 5:return ss(t),null;case 13:if(Ir(os),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(a(340));pa()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return Ir(os),null;case 4:return rs(),null;case 10:return Ea(t.type._context),null;case 22:case 23:return hc(),null;default:return null}}Do=function(e,t){for(var i=t.child;null!==i;){if(5===i.tag||6===i.tag)e.appendChild(i.stateNode);else if(4!==i.tag&&null!==i.child){i.child.return=i,i=i.child;continue}if(i===t)break;for(;null===i.sibling;){if(null===i.return||i.return===t)return;i=i.return}i.sibling.return=i.return,i=i.sibling}},Oo=function(){},No=function(e,t,i,n){var r=e.memoizedProps;if(r!==n){e=t.stateNode,is(Xa.current);var a,s=null;switch(i){case"input":r=J(e,r),n=J(e,n),s=[];break;case"select":r=F({},r,{value:void 0}),n=F({},n,{value:void 0}),s=[];break;case"textarea":r=ne(e,r),n=ne(e,n),s=[];break;default:"function"!=typeof r.onClick&&"function"==typeof n.onClick&&(e.onclick=Xn)}for(d in Se(i,n),i=null,r)if(!n.hasOwnProperty(d)&&r.hasOwnProperty(d)&&null!=r[d])if("style"===d){var l=r[d];for(a in l)l.hasOwnProperty(a)&&(i||(i={}),i[a]="")}else"dangerouslySetInnerHTML"!==d&&"children"!==d&&"suppressContentEditableWarning"!==d&&"suppressHydrationWarning"!==d&&"autoFocus"!==d&&(o.hasOwnProperty(d)?s||(s=[]):(s=s||[]).push(d,null));for(d in n){var c=n[d];if(l=null!=r?r[d]:void 0,n.hasOwnProperty(d)&&c!==l&&(null!=c||null!=l))if("style"===d)if(l){for(a in l)!l.hasOwnProperty(a)||c&&c.hasOwnProperty(a)||(i||(i={}),i[a]="");for(a in c)c.hasOwnProperty(a)&&l[a]!==c[a]&&(i||(i={}),i[a]=c[a])}else i||(s||(s=[]),s.push(d,i)),i=c;else"dangerouslySetInnerHTML"===d?(c=c?c.__html:void 0,l=l?l.__html:void 0,null!=c&&l!==c&&(s=s||[]).push(d,c)):"children"===d?"string"!=typeof c&&"number"!=typeof c||(s=s||[]).push(d,""+c):"suppressContentEditableWarning"!==d&&"suppressHydrationWarning"!==d&&(o.hasOwnProperty(d)?(null!=c&&"onScroll"===d&&Bn("scroll",e),s||l===c||(s=[])):(s=s||[]).push(d,c))}i&&(s=s||[]).push("style",i);var d=s;(t.updateQueue=d)&&(t.flags|=4)}},Lo=function(e,t,i,n){i!==n&&(t.flags|=4)};var Yo=!1,Qo=!1,Zo="function"==typeof WeakSet?WeakSet:Set,Xo=null;function el(e,t){var i=e.ref;if(null!==i)if("function"==typeof i)try{i(null)}catch(i){Ic(e,t,i)}else i.current=null}function tl(e,t,i){try{i()}catch(i){Ic(e,t,i)}}var il=!1;function nl(e,t,i){var n=t.updateQueue;if(null!==(n=null!==n?n.lastEffect:null)){var r=n=n.next;do{if((r.tag&e)===e){var a=r.destroy;r.destroy=void 0,void 0!==a&&tl(t,i,a)}r=r.next}while(r!==n)}}function rl(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var i=t=t.next;do{if((i.tag&e)===e){var n=i.create;i.destroy=n()}i=i.next}while(i!==t)}}function al(e){var t=e.ref;if(null!==t){var i=e.stateNode;e.tag,e=i,"function"==typeof t?t(e):t.current=e}}function sl(e){var t=e.alternate;null!==t&&(e.alternate=null,sl(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(t=e.stateNode)&&(delete t[hr],delete t[pr],delete t[mr],delete t[fr],delete t[vr]),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ol(e){return 5===e.tag||3===e.tag||4===e.tag}function ll(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||ol(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(2&e.flags)continue e;if(null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function cl(e,t,i){var n=e.tag;if(5===n||6===n)e=e.stateNode,t?8===i.nodeType?i.parentNode.insertBefore(e,t):i.insertBefore(e,t):(8===i.nodeType?(t=i.parentNode).insertBefore(e,i):(t=i).appendChild(e),null!=(i=i._reactRootContainer)||null!==t.onclick||(t.onclick=Xn));else if(4!==n&&null!==(e=e.child))for(cl(e,t,i),e=e.sibling;null!==e;)cl(e,t,i),e=e.sibling}function dl(e,t,i){var n=e.tag;if(5===n||6===n)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(4!==n&&null!==(e=e.child))for(dl(e,t,i),e=e.sibling;null!==e;)dl(e,t,i),e=e.sibling}var ul=null,hl=!1;function pl(e,t,i){for(i=i.child;null!==i;)gl(e,t,i),i=i.sibling}function gl(e,t,i){if(at&&"function"==typeof at.onCommitFiberUnmount)try{at.onCommitFiberUnmount(rt,i)}catch(e){}switch(i.tag){case 5:Qo||el(i,t);case 6:var n=ul,r=hl;ul=null,pl(e,t,i),hl=r,null!==(ul=n)&&(hl?(e=ul,i=i.stateNode,8===e.nodeType?e.parentNode.removeChild(i):e.removeChild(i)):ul.removeChild(i.stateNode));break;case 18:null!==ul&&(hl?(e=ul,i=i.stateNode,8===e.nodeType?lr(e.parentNode,i):1===e.nodeType&&lr(e,i),$t(e)):lr(ul,i.stateNode));break;case 4:n=ul,r=hl,ul=i.stateNode.containerInfo,hl=!0,pl(e,t,i),ul=n,hl=r;break;case 0:case 11:case 14:case 15:if(!Qo&&null!==(n=i.updateQueue)&&null!==(n=n.lastEffect)){r=n=n.next;do{var a=r,s=a.destroy;a=a.tag,void 0!==s&&(2&a||4&a)&&tl(i,t,s),r=r.next}while(r!==n)}pl(e,t,i);break;case 1:if(!Qo&&(el(i,t),"function"==typeof(n=i.stateNode).componentWillUnmount))try{n.props=i.memoizedProps,n.state=i.memoizedState,n.componentWillUnmount()}catch(e){Ic(i,t,e)}pl(e,t,i);break;case 21:pl(e,t,i);break;case 22:1&i.mode?(Qo=(n=Qo)||null!==i.memoizedState,pl(e,t,i),Qo=n):pl(e,t,i);break;default:pl(e,t,i)}}function ml(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var i=e.stateNode;null===i&&(i=e.stateNode=new Zo),t.forEach((function(t){var n=Pc.bind(null,e,t);i.has(t)||(i.add(t),t.then(n,n))}))}}function fl(e,t){var i=t.deletions;if(null!==i)for(var n=0;n<i.length;n++){var r=i[n];try{var s=e,o=t,l=o;e:for(;null!==l;){switch(l.tag){case 5:ul=l.stateNode,hl=!1;break e;case 3:case 4:ul=l.stateNode.containerInfo,hl=!0;break e}l=l.return}if(null===ul)throw Error(a(160));gl(s,o,r),ul=null,hl=!1;var c=r.alternate;null!==c&&(c.return=null),r.return=null}catch(e){Ic(r,t,e)}}if(12854&t.subtreeFlags)for(t=t.child;null!==t;)vl(t,e),t=t.sibling}function vl(e,t){var i=e.alternate,n=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:if(fl(t,e),Sl(e),4&n){try{nl(3,e,e.return),rl(3,e)}catch(t){Ic(e,e.return,t)}try{nl(5,e,e.return)}catch(t){Ic(e,e.return,t)}}break;case 1:fl(t,e),Sl(e),512&n&&null!==i&&el(i,i.return);break;case 5:if(fl(t,e),Sl(e),512&n&&null!==i&&el(i,i.return),32&e.flags){var r=e.stateNode;try{he(r,"")}catch(t){Ic(e,e.return,t)}}if(4&n&&null!=(r=e.stateNode)){var s=e.memoizedProps,o=null!==i?i.memoizedProps:s,l=e.type,c=e.updateQueue;if(e.updateQueue=null,null!==c)try{"input"===l&&"radio"===s.type&&null!=s.name&&Q(r,s),ye(l,o);var d=ye(l,s);for(o=0;o<c.length;o+=2){var u=c[o],h=c[o+1];"style"===u?fe(r,h):"dangerouslySetInnerHTML"===u?ue(r,h):"children"===u?he(r,h):y(r,u,h,d)}switch(l){case"input":Z(r,s);break;case"textarea":ae(r,s);break;case"select":var p=r._wrapperState.wasMultiple;r._wrapperState.wasMultiple=!!s.multiple;var g=s.value;null!=g?ie(r,!!s.multiple,g,!1):p!==!!s.multiple&&(null!=s.defaultValue?ie(r,!!s.multiple,s.defaultValue,!0):ie(r,!!s.multiple,s.multiple?[]:"",!1))}r[pr]=s}catch(t){Ic(e,e.return,t)}}break;case 6:if(fl(t,e),Sl(e),4&n){if(null===e.stateNode)throw Error(a(162));r=e.stateNode,s=e.memoizedProps;try{r.nodeValue=s}catch(t){Ic(e,e.return,t)}}break;case 3:if(fl(t,e),Sl(e),4&n&&null!==i&&i.memoizedState.isDehydrated)try{$t(t.containerInfo)}catch(t){Ic(e,e.return,t)}break;case 4:default:fl(t,e),Sl(e);break;case 13:fl(t,e),Sl(e),8192&(r=e.child).flags&&(s=null!==r.memoizedState,r.stateNode.isHidden=s,!s||null!==r.alternate&&null!==r.alternate.memoizedState||($l=Qe())),4&n&&ml(e);break;case 22:if(u=null!==i&&null!==i.memoizedState,1&e.mode?(Qo=(d=Qo)||u,fl(t,e),Qo=d):fl(t,e),Sl(e),8192&n){if(d=null!==e.memoizedState,(e.stateNode.isHidden=d)&&!u&&1&e.mode)for(Xo=e,u=e.child;null!==u;){for(h=Xo=u;null!==Xo;){switch(g=(p=Xo).child,p.tag){case 0:case 11:case 14:case 15:nl(4,p,p.return);break;case 1:el(p,p.return);var m=p.stateNode;if("function"==typeof m.componentWillUnmount){n=p,i=p.return;try{t=n,m.props=t.memoizedProps,m.state=t.memoizedState,m.componentWillUnmount()}catch(e){Ic(n,i,e)}}break;case 5:el(p,p.return);break;case 22:if(null!==p.memoizedState){El(h);continue}}null!==g?(g.return=p,Xo=g):El(h)}u=u.sibling}e:for(u=null,h=e;;){if(5===h.tag){if(null===u){u=h;try{r=h.stateNode,d?"function"==typeof(s=r.style).setProperty?s.setProperty("display","none","important"):s.display="none":(l=h.stateNode,o=null!=(c=h.memoizedProps.style)&&c.hasOwnProperty("display")?c.display:null,l.style.display=me("display",o))}catch(t){Ic(e,e.return,t)}}}else if(6===h.tag){if(null===u)try{h.stateNode.nodeValue=d?"":h.memoizedProps}catch(t){Ic(e,e.return,t)}}else if((22!==h.tag&&23!==h.tag||null===h.memoizedState||h===e)&&null!==h.child){h.child.return=h,h=h.child;continue}if(h===e)break e;for(;null===h.sibling;){if(null===h.return||h.return===e)break e;u===h&&(u=null),h=h.return}u===h&&(u=null),h.sibling.return=h.return,h=h.sibling}}break;case 19:fl(t,e),Sl(e),4&n&&ml(e);case 21:}}function Sl(e){var t=e.flags;if(2&t){try{e:{for(var i=e.return;null!==i;){if(ol(i)){var n=i;break e}i=i.return}throw Error(a(160))}switch(n.tag){case 5:var r=n.stateNode;32&n.flags&&(he(r,""),n.flags&=-33),dl(e,ll(e),r);break;case 3:case 4:var s=n.stateNode.containerInfo;cl(e,ll(e),s);break;default:throw Error(a(161))}}catch(t){Ic(e,e.return,t)}e.flags&=-3}4096&t&&(e.flags&=-4097)}function yl(e,t,i){Xo=e,Cl(e,t,i)}function Cl(e,t,i){for(var n=!!(1&e.mode);null!==Xo;){var r=Xo,a=r.child;if(22===r.tag&&n){var s=null!==r.memoizedState||Yo;if(!s){var o=r.alternate,l=null!==o&&null!==o.memoizedState||Qo;o=Yo;var c=Qo;if(Yo=s,(Qo=l)&&!c)for(Xo=r;null!==Xo;)l=(s=Xo).child,22===s.tag&&null!==s.memoizedState?Tl(r):null!==l?(l.return=s,Xo=l):Tl(r);for(;null!==a;)Xo=a,Cl(a,t,i),a=a.sibling;Xo=r,Yo=o,Qo=c}_l(e)}else 8772&r.subtreeFlags&&null!==a?(a.return=r,Xo=a):_l(e)}}function _l(e){for(;null!==Xo;){var t=Xo;if(8772&t.flags){var i=t.alternate;try{if(8772&t.flags)switch(t.tag){case 0:case 11:case 15:Qo||rl(5,t);break;case 1:var n=t.stateNode;if(4&t.flags&&!Qo)if(null===i)n.componentDidMount();else{var r=t.elementType===t.type?i.memoizedProps:fa(t.type,i.memoizedProps);n.componentDidUpdate(r,i.memoizedState,n.__reactInternalSnapshotBeforeUpdate)}var s=t.updateQueue;null!==s&&Ua(t,s,n);break;case 3:var o=t.updateQueue;if(null!==o){if(i=null,null!==t.child)switch(t.child.tag){case 5:case 1:i=t.child.stateNode}Ua(t,o,i)}break;case 5:var l=t.stateNode;if(null===i&&4&t.flags){i=l;var c=t.memoizedProps;switch(t.type){case"button":case"input":case"select":case"textarea":c.autoFocus&&i.focus();break;case"img":c.src&&(i.src=c.src)}}break;case 6:case 4:case 12:case 19:case 17:case 21:case 22:case 23:case 25:break;case 13:if(null===t.memoizedState){var d=t.alternate;if(null!==d){var u=d.memoizedState;if(null!==u){var h=u.dehydrated;null!==h&&$t(h)}}}break;default:throw Error(a(163))}Qo||512&t.flags&&al(t)}catch(e){Ic(t,t.return,e)}}if(t===e){Xo=null;break}if(null!==(i=t.sibling)){i.return=t.return,Xo=i;break}Xo=t.return}}function El(e){for(;null!==Xo;){var t=Xo;if(t===e){Xo=null;break}var i=t.sibling;if(null!==i){i.return=t.return,Xo=i;break}Xo=t.return}}function Tl(e){for(;null!==Xo;){var t=Xo;try{switch(t.tag){case 0:case 11:case 15:var i=t.return;try{rl(4,t)}catch(e){Ic(t,i,e)}break;case 1:var n=t.stateNode;if("function"==typeof n.componentDidMount){var r=t.return;try{n.componentDidMount()}catch(e){Ic(t,r,e)}}var a=t.return;try{al(t)}catch(e){Ic(t,a,e)}break;case 5:var s=t.return;try{al(t)}catch(e){Ic(t,s,e)}}}catch(e){Ic(t,t.return,e)}if(t===e){Xo=null;break}var o=t.sibling;if(null!==o){o.return=t.return,Xo=o;break}Xo=t.return}}var bl,Il=Math.ceil,wl=C.ReactCurrentDispatcher,Rl=C.ReactCurrentOwner,Al=C.ReactCurrentBatchConfig,Pl=0,Ml=null,kl=null,Dl=0,Ol=0,Nl=br(0),Ll=0,xl=null,Fl=0,Ul=0,Bl=0,Vl=null,Hl=null,$l=0,Gl=1/0,jl=null,zl=!1,Wl=null,ql=null,Kl=!1,Jl=null,Yl=0,Ql=0,Zl=null,Xl=-1,ec=0;function tc(){return 6&Pl?Qe():-1!==Xl?Xl:Xl=Qe()}function ic(e){return 1&e.mode?2&Pl&&0!==Dl?Dl&-Dl:null!==ma.transition?(0===ec&&(ec=mt()),ec):0!==(e=yt)?e:e=void 0===(e=window.event)?16:Yt(e.type):1}function nc(e,t,i,n){if(50<Ql)throw Ql=0,Zl=null,Error(a(185));vt(e,i,n),2&Pl&&e===Ml||(e===Ml&&(!(2&Pl)&&(Ul|=i),4===Ll&&lc(e,Dl)),rc(e,n),1===i&&0===Pl&&!(1&t.mode)&&(Gl=Qe()+500,Br&&$r()))}function rc(e,t){var i=e.callbackNode;!function(e,t){for(var i=e.suspendedLanes,n=e.pingedLanes,r=e.expirationTimes,a=e.pendingLanes;0<a;){var s=31-st(a),o=1<<s,l=r[s];-1===l?o&i&&!(o&n)||(r[s]=pt(o,t)):l<=t&&(e.expiredLanes|=o),a&=~o}}(e,t);var n=ht(e,e===Ml?Dl:0);if(0===n)null!==i&&Ke(i),e.callbackNode=null,e.callbackPriority=0;else if(t=n&-n,e.callbackPriority!==t){if(null!=i&&Ke(i),1===t)0===e.tag?function(e){Br=!0,Hr(e)}(cc.bind(null,e)):Hr(cc.bind(null,e)),sr((function(){!(6&Pl)&&$r()})),i=null;else{switch(Ct(n)){case 1:i=Xe;break;case 4:i=et;break;case 16:default:i=tt;break;case 536870912:i=nt}i=Mc(i,ac.bind(null,e))}e.callbackPriority=t,e.callbackNode=i}}function ac(e,t){if(Xl=-1,ec=0,6&Pl)throw Error(a(327));var i=e.callbackNode;if(Tc()&&e.callbackNode!==i)return null;var n=ht(e,e===Ml?Dl:0);if(0===n)return null;if(30&n||n&e.expiredLanes||t)t=vc(e,n);else{t=n;var r=Pl;Pl|=2;var s=mc();for(Ml===e&&Dl===t||(jl=null,Gl=Qe()+500,pc(e,t));;)try{yc();break}catch(t){gc(e,t)}_a(),wl.current=s,Pl=r,null!==kl?t=0:(Ml=null,Dl=0,t=Ll)}if(0!==t){if(2===t&&0!==(r=gt(e))&&(n=r,t=sc(e,r)),1===t)throw i=xl,pc(e,0),lc(e,n),rc(e,Qe()),i;if(6===t)lc(e,n);else{if(r=e.current.alternate,!(30&n||function(e){for(var t=e;;){if(16384&t.flags){var i=t.updateQueue;if(null!==i&&null!==(i=i.stores))for(var n=0;n<i.length;n++){var r=i[n],a=r.getSnapshot;r=r.value;try{if(!on(a(),r))return!1}catch(e){return!1}}}if(i=t.child,16384&t.subtreeFlags&&null!==i)i.return=t,t=i;else{if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}(r)||(t=vc(e,n),2===t&&(s=gt(e),0!==s&&(n=s,t=sc(e,s))),1!==t)))throw i=xl,pc(e,0),lc(e,n),rc(e,Qe()),i;switch(e.finishedWork=r,e.finishedLanes=n,t){case 0:case 1:throw Error(a(345));case 2:case 5:Ec(e,Hl,jl);break;case 3:if(lc(e,n),(130023424&n)===n&&10<(t=$l+500-Qe())){if(0!==ht(e,0))break;if(((r=e.suspendedLanes)&n)!==n){tc(),e.pingedLanes|=e.suspendedLanes&r;break}e.timeoutHandle=nr(Ec.bind(null,e,Hl,jl),t);break}Ec(e,Hl,jl);break;case 4:if(lc(e,n),(4194240&n)===n)break;for(t=e.eventTimes,r=-1;0<n;){var o=31-st(n);s=1<<o,(o=t[o])>r&&(r=o),n&=~s}if(n=r,10<(n=(120>(n=Qe()-n)?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*Il(n/1960))-n)){e.timeoutHandle=nr(Ec.bind(null,e,Hl,jl),n);break}Ec(e,Hl,jl);break;default:throw Error(a(329))}}}return rc(e,Qe()),e.callbackNode===i?ac.bind(null,e):null}function sc(e,t){var i=Vl;return e.current.memoizedState.isDehydrated&&(pc(e,t).flags|=256),2!==(e=vc(e,t))&&(t=Hl,Hl=i,null!==t&&oc(t)),e}function oc(e){null===Hl?Hl=e:Hl.push.apply(Hl,e)}function lc(e,t){for(t&=~Bl,t&=~Ul,e.suspendedLanes|=t,e.pingedLanes&=~t,e=e.expirationTimes;0<t;){var i=31-st(t),n=1<<i;e[i]=-1,t&=~n}}function cc(e){if(6&Pl)throw Error(a(327));Tc();var t=ht(e,0);if(!(1&t))return rc(e,Qe()),null;var i=vc(e,t);if(0!==e.tag&&2===i){var n=gt(e);0!==n&&(t=n,i=sc(e,n))}if(1===i)throw i=xl,pc(e,0),lc(e,t),rc(e,Qe()),i;if(6===i)throw Error(a(345));return e.finishedWork=e.current.alternate,e.finishedLanes=t,Ec(e,Hl,jl),rc(e,Qe()),null}function dc(e,t){var i=Pl;Pl|=1;try{return e(t)}finally{0===(Pl=i)&&(Gl=Qe()+500,Br&&$r())}}function uc(e){null!==Jl&&0===Jl.tag&&!(6&Pl)&&Tc();var t=Pl;Pl|=1;var i=Al.transition,n=yt;try{if(Al.transition=null,yt=1,e)return e()}finally{yt=n,Al.transition=i,!(6&(Pl=t))&&$r()}}function hc(){Ol=Nl.current,Ir(Nl)}function pc(e,t){e.finishedWork=null,e.finishedLanes=0;var i=e.timeoutHandle;if(-1!==i&&(e.timeoutHandle=-1,rr(i)),null!==kl)for(i=kl.return;null!==i;){var n=i;switch(ta(n),n.tag){case 1:null!=(n=n.type.childContextTypes)&&Or();break;case 3:rs(),Ir(Pr),Ir(Ar),ds();break;case 5:ss(n);break;case 4:rs();break;case 13:case 19:Ir(os);break;case 10:Ea(n.type._context);break;case 22:case 23:hc()}i=i.return}if(Ml=e,kl=e=Nc(e.current,null),Dl=Ol=t,Ll=0,xl=null,Bl=Ul=Fl=0,Hl=Vl=null,null!==wa){for(t=0;t<wa.length;t++)if(null!==(n=(i=wa[t]).interleaved)){i.interleaved=null;var r=n.next,a=i.pending;if(null!==a){var s=a.next;a.next=r,n.next=s}i.pending=n}wa=null}return e}function gc(e,t){for(;;){var i=kl;try{if(_a(),us.current=ao,vs){for(var n=gs.memoizedState;null!==n;){var r=n.queue;null!==r&&(r.pending=null),n=n.next}vs=!1}if(ps=0,fs=ms=gs=null,Ss=!1,ys=0,Rl.current=null,null===i||null===i.return){Ll=1,xl=t,kl=null;break}e:{var s=e,o=i.return,l=i,c=t;if(t=Dl,l.flags|=32768,null!==c&&"object"==typeof c&&"function"==typeof c.then){var d=c,u=l,h=u.tag;if(!(1&u.mode||0!==h&&11!==h&&15!==h)){var p=u.alternate;p?(u.updateQueue=p.updateQueue,u.memoizedState=p.memoizedState,u.lanes=p.lanes):(u.updateQueue=null,u.memoizedState=null)}var g=vo(o);if(null!==g){g.flags&=-257,So(g,o,l,0,t),1&g.mode&&fo(s,d,t),c=d;var m=(t=g).updateQueue;if(null===m){var f=new Set;f.add(c),t.updateQueue=f}else m.add(c);break e}if(!(1&t)){fo(s,d,t),fc();break e}c=Error(a(426))}else if(ra&&1&l.mode){var v=vo(o);if(null!==v){!(65536&v.flags)&&(v.flags|=256),So(v,o,l,0,t),ga(co(c,l));break e}}s=c=co(c,l),4!==Ll&&(Ll=2),null===Vl?Vl=[s]:Vl.push(s),s=o;do{switch(s.tag){case 3:s.flags|=65536,t&=-t,s.lanes|=t,xa(s,go(0,c,t));break e;case 1:l=c;var S=s.type,y=s.stateNode;if(!(128&s.flags||"function"!=typeof S.getDerivedStateFromError&&(null===y||"function"!=typeof y.componentDidCatch||null!==ql&&ql.has(y)))){s.flags|=65536,t&=-t,s.lanes|=t,xa(s,mo(s,l,t));break e}}s=s.return}while(null!==s)}_c(i)}catch(e){t=e,kl===i&&null!==i&&(kl=i=i.return);continue}break}}function mc(){var e=wl.current;return wl.current=ao,null===e?ao:e}function fc(){0!==Ll&&3!==Ll&&2!==Ll||(Ll=4),null===Ml||!(268435455&Fl)&&!(268435455&Ul)||lc(Ml,Dl)}function vc(e,t){var i=Pl;Pl|=2;var n=mc();for(Ml===e&&Dl===t||(jl=null,pc(e,t));;)try{Sc();break}catch(t){gc(e,t)}if(_a(),Pl=i,wl.current=n,null!==kl)throw Error(a(261));return Ml=null,Dl=0,Ll}function Sc(){for(;null!==kl;)Cc(kl)}function yc(){for(;null!==kl&&!Je();)Cc(kl)}function Cc(e){var t=bl(e.alternate,e,Ol);e.memoizedProps=e.pendingProps,null===t?_c(e):kl=t,Rl.current=null}function _c(e){var t=e;do{var i=t.alternate;if(e=t.return,32768&t.flags){if(null!==(i=Jo(i,t)))return i.flags&=32767,void(kl=i);if(null===e)return Ll=6,void(kl=null);e.flags|=32768,e.subtreeFlags=0,e.deletions=null}else if(null!==(i=Ko(i,t,Ol)))return void(kl=i);if(null!==(t=t.sibling))return void(kl=t);kl=t=e}while(null!==t);0===Ll&&(Ll=5)}function Ec(e,t,i){var n=yt,r=Al.transition;try{Al.transition=null,yt=1,function(e,t,i,n){do{Tc()}while(null!==Jl);if(6&Pl)throw Error(a(327));i=e.finishedWork;var r=e.finishedLanes;if(null===i)return null;if(e.finishedWork=null,e.finishedLanes=0,i===e.current)throw Error(a(177));e.callbackNode=null,e.callbackPriority=0;var s=i.lanes|i.childLanes;if(function(e,t){var i=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var n=e.eventTimes;for(e=e.expirationTimes;0<i;){var r=31-st(i),a=1<<r;t[r]=0,n[r]=-1,e[r]=-1,i&=~a}}(e,s),e===Ml&&(kl=Ml=null,Dl=0),!(2064&i.subtreeFlags)&&!(2064&i.flags)||Kl||(Kl=!0,Mc(tt,(function(){return Tc(),null}))),s=!!(15990&i.flags),15990&i.subtreeFlags||s){s=Al.transition,Al.transition=null;var o=yt;yt=1;var l=Pl;Pl|=4,Rl.current=null,function(e,t){if(er=jt,pn(e=hn())){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{var n=(i=(i=e.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(n&&0!==n.rangeCount){i=n.anchorNode;var r=n.anchorOffset,s=n.focusNode;n=n.focusOffset;try{i.nodeType,s.nodeType}catch(e){i=null;break e}var o=0,l=-1,c=-1,d=0,u=0,h=e,p=null;t:for(;;){for(var g;h!==i||0!==r&&3!==h.nodeType||(l=o+r),h!==s||0!==n&&3!==h.nodeType||(c=o+n),3===h.nodeType&&(o+=h.nodeValue.length),null!==(g=h.firstChild);)p=h,h=g;for(;;){if(h===e)break t;if(p===i&&++d===r&&(l=o),p===s&&++u===n&&(c=o),null!==(g=h.nextSibling))break;p=(h=p).parentNode}h=g}i=-1===l||-1===c?null:{start:l,end:c}}else i=null}i=i||{start:0,end:0}}else i=null;for(tr={focusedElem:e,selectionRange:i},jt=!1,Xo=t;null!==Xo;)if(e=(t=Xo).child,1028&t.subtreeFlags&&null!==e)e.return=t,Xo=e;else for(;null!==Xo;){t=Xo;try{var m=t.alternate;if(1024&t.flags)switch(t.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==m){var f=m.memoizedProps,v=m.memoizedState,S=t.stateNode,y=S.getSnapshotBeforeUpdate(t.elementType===t.type?f:fa(t.type,f),v);S.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var C=t.stateNode.containerInfo;1===C.nodeType?C.textContent="":9===C.nodeType&&C.documentElement&&C.removeChild(C.documentElement);break;default:throw Error(a(163))}}catch(e){Ic(t,t.return,e)}if(null!==(e=t.sibling)){e.return=t.return,Xo=e;break}Xo=t.return}m=il,il=!1}(e,i),vl(i,e),gn(tr),jt=!!er,tr=er=null,e.current=i,yl(i,e,r),Ye(),Pl=l,yt=o,Al.transition=s}else e.current=i;if(Kl&&(Kl=!1,Jl=e,Yl=r),0===(s=e.pendingLanes)&&(ql=null),function(e){if(at&&"function"==typeof at.onCommitFiberRoot)try{at.onCommitFiberRoot(rt,e,void 0,!(128&~e.current.flags))}catch(e){}}(i.stateNode),rc(e,Qe()),null!==t)for(n=e.onRecoverableError,i=0;i<t.length;i++)n((r=t[i]).value,{componentStack:r.stack,digest:r.digest});if(zl)throw zl=!1,e=Wl,Wl=null,e;!!(1&Yl)&&0!==e.tag&&Tc(),1&(s=e.pendingLanes)?e===Zl?Ql++:(Ql=0,Zl=e):Ql=0,$r()}(e,t,i,n)}finally{Al.transition=r,yt=n}return null}function Tc(){if(null!==Jl){var e=Ct(Yl),t=Al.transition,i=yt;try{if(Al.transition=null,yt=16>e?16:e,null===Jl)var n=!1;else{if(e=Jl,Jl=null,Yl=0,6&Pl)throw Error(a(331));var r=Pl;for(Pl|=4,Xo=e.current;null!==Xo;){var s=Xo,o=s.child;if(16&Xo.flags){var l=s.deletions;if(null!==l){for(var c=0;c<l.length;c++){var d=l[c];for(Xo=d;null!==Xo;){var u=Xo;switch(u.tag){case 0:case 11:case 15:nl(8,u,s)}var h=u.child;if(null!==h)h.return=u,Xo=h;else for(;null!==Xo;){var p=(u=Xo).sibling,g=u.return;if(sl(u),u===d){Xo=null;break}if(null!==p){p.return=g,Xo=p;break}Xo=g}}}var m=s.alternate;if(null!==m){var f=m.child;if(null!==f){m.child=null;do{var v=f.sibling;f.sibling=null,f=v}while(null!==f)}}Xo=s}}if(2064&s.subtreeFlags&&null!==o)o.return=s,Xo=o;else e:for(;null!==Xo;){if(2048&(s=Xo).flags)switch(s.tag){case 0:case 11:case 15:nl(9,s,s.return)}var S=s.sibling;if(null!==S){S.return=s.return,Xo=S;break e}Xo=s.return}}var y=e.current;for(Xo=y;null!==Xo;){var C=(o=Xo).child;if(2064&o.subtreeFlags&&null!==C)C.return=o,Xo=C;else e:for(o=y;null!==Xo;){if(2048&(l=Xo).flags)try{switch(l.tag){case 0:case 11:case 15:rl(9,l)}}catch(e){Ic(l,l.return,e)}if(l===o){Xo=null;break e}var _=l.sibling;if(null!==_){_.return=l.return,Xo=_;break e}Xo=l.return}}if(Pl=r,$r(),at&&"function"==typeof at.onPostCommitFiberRoot)try{at.onPostCommitFiberRoot(rt,e)}catch(e){}n=!0}return n}finally{yt=i,Al.transition=t}}return!1}function bc(e,t,i){e=Na(e,t=go(0,t=co(i,t),1),1),t=tc(),null!==e&&(vt(e,1,t),rc(e,t))}function Ic(e,t,i){if(3===e.tag)bc(e,e,i);else for(;null!==t;){if(3===t.tag){bc(t,e,i);break}if(1===t.tag){var n=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof n.componentDidCatch&&(null===ql||!ql.has(n))){t=Na(t,e=mo(t,e=co(i,e),1),1),e=tc(),null!==t&&(vt(t,1,e),rc(t,e));break}}t=t.return}}function wc(e,t,i){var n=e.pingCache;null!==n&&n.delete(t),t=tc(),e.pingedLanes|=e.suspendedLanes&i,Ml===e&&(Dl&i)===i&&(4===Ll||3===Ll&&(130023424&Dl)===Dl&&500>Qe()-$l?pc(e,0):Bl|=i),rc(e,t)}function Rc(e,t){0===t&&(1&e.mode?(t=dt,!(130023424&(dt<<=1))&&(dt=4194304)):t=1);var i=tc();null!==(e=Pa(e,t))&&(vt(e,t,i),rc(e,i))}function Ac(e){var t=e.memoizedState,i=0;null!==t&&(i=t.retryLane),Rc(e,i)}function Pc(e,t){var i=0;switch(e.tag){case 13:var n=e.stateNode,r=e.memoizedState;null!==r&&(i=r.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(a(314))}null!==n&&n.delete(t),Rc(e,i)}function Mc(e,t){return qe(e,t)}function kc(e,t,i,n){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Dc(e,t,i,n){return new kc(e,t,i,n)}function Oc(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Nc(e,t){var i=e.alternate;return null===i?((i=Dc(e.tag,t,e.key,e.mode)).elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=14680064&e.flags,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i}function Lc(e,t,i,n,r,s){var o=2;if(n=e,"function"==typeof e)Oc(e)&&(o=1);else if("string"==typeof e)o=5;else e:switch(e){case T:return xc(i.children,r,s,t);case b:o=8,r|=8;break;case I:return(e=Dc(12,i,t,2|r)).elementType=I,e.lanes=s,e;case P:return(e=Dc(13,i,t,r)).elementType=P,e.lanes=s,e;case M:return(e=Dc(19,i,t,r)).elementType=M,e.lanes=s,e;case O:return Fc(i,r,s,t);default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case w:o=10;break e;case R:o=9;break e;case A:o=11;break e;case k:o=14;break e;case D:o=16,n=null;break e}throw Error(a(130,null==e?e:typeof e,""))}return(t=Dc(o,i,t,r)).elementType=e,t.type=n,t.lanes=s,t}function xc(e,t,i,n){return(e=Dc(7,e,n,t)).lanes=i,e}function Fc(e,t,i,n){return(e=Dc(22,e,n,t)).elementType=O,e.lanes=i,e.stateNode={isHidden:!1},e}function Uc(e,t,i){return(e=Dc(6,e,null,t)).lanes=i,e}function Bc(e,t,i){return(t=Dc(4,null!==e.children?e.children:[],e.key,t)).lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Vc(e,t,i,n,r){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ft(0),this.expirationTimes=ft(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ft(0),this.identifierPrefix=n,this.onRecoverableError=r,this.mutableSourceEagerHydrationData=null}function Hc(e,t,i,n,r,a,s,o,l){return e=new Vc(e,t,i,o,l),1===t?(t=1,!0===a&&(t|=8)):t=0,a=Dc(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:n,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},ka(a),e}function $c(e){if(!e)return Rr;e:{if($e(e=e._reactInternals)!==e||1!==e.tag)throw Error(a(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(Dr(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(a(171))}if(1===e.tag){var i=e.type;if(Dr(i))return Lr(e,i,t)}return t}function Gc(e,t,i,n,r,a,s,o,l){return(e=Hc(i,n,!0,e,0,a,0,o,l)).context=$c(null),i=e.current,(a=Oa(n=tc(),r=ic(i))).callback=null!=t?t:null,Na(i,a,r),e.current.lanes=r,vt(e,r,n),rc(e,n),e}function jc(e,t,i,n){var r=t.current,a=tc(),s=ic(r);return i=$c(i),null===t.context?t.context=i:t.pendingContext=i,(t=Oa(a,s)).payload={element:e},null!==(n=void 0===n?null:n)&&(t.callback=n),null!==(e=Na(r,t,s))&&(nc(e,r,s,a),La(e,r,s)),s}function zc(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function Wc(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var i=e.retryLane;e.retryLane=0!==i&&i<t?i:t}}function qc(e,t){Wc(e,t),(e=e.alternate)&&Wc(e,t)}bl=function(e,t,i){if(null!==e)if(e.memoizedProps!==t.pendingProps||Pr.current)Co=!0;else{if(!(e.lanes&i||128&t.flags))return Co=!1,function(e,t,i){switch(t.tag){case 3:Mo(t),pa();break;case 5:as(t);break;case 1:Dr(t.type)&&xr(t);break;case 4:ns(t,t.stateNode.containerInfo);break;case 10:var n=t.type._context,r=t.memoizedProps.value;wr(va,n._currentValue),n._currentValue=r;break;case 13:if(null!==(n=t.memoizedState))return null!==n.dehydrated?(wr(os,1&os.current),t.flags|=128,null):i&t.child.childLanes?Uo(e,t,i):(wr(os,1&os.current),null!==(e=zo(e,t,i))?e.sibling:null);wr(os,1&os.current);break;case 19:if(n=!!(i&t.childLanes),128&e.flags){if(n)return Go(e,t,i);t.flags|=128}if(null!==(r=t.memoizedState)&&(r.rendering=null,r.tail=null,r.lastEffect=null),wr(os,os.current),n)break;return null;case 22:case 23:return t.lanes=0,Io(e,t,i)}return zo(e,t,i)}(e,t,i);Co=!!(131072&e.flags)}else Co=!1,ra&&1048576&t.flags&&Xr(t,Wr,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;jo(e,t),e=t.pendingProps;var r=kr(t,Ar.current);ba(t,i),r=Ts(null,t,n,e,r,i);var s=bs();return t.flags|=1,"object"==typeof r&&null!==r&&"function"==typeof r.render&&void 0===r.$$typeof?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Dr(n)?(s=!0,xr(t)):s=!1,t.memoizedState=null!==r.state&&void 0!==r.state?r.state:null,ka(t),r.updater=Ha,t.stateNode=r,r._reactInternals=t,za(t,n,e,i),t=Po(null,t,n,!0,s,i)):(t.tag=0,ra&&s&&ea(t),_o(null,t,r,i),t=t.child),t;case 16:n=t.elementType;e:{switch(jo(e,t),e=t.pendingProps,n=(r=n._init)(n._payload),t.type=n,r=t.tag=function(e){if("function"==typeof e)return Oc(e)?1:0;if(null!=e){if((e=e.$$typeof)===A)return 11;if(e===k)return 14}return 2}(n),e=fa(n,e),r){case 0:t=Ro(null,t,n,e,i);break e;case 1:t=Ao(null,t,n,e,i);break e;case 11:t=Eo(null,t,n,e,i);break e;case 14:t=To(null,t,n,fa(n.type,e),i);break e}throw Error(a(306,n,""))}return t;case 0:return n=t.type,r=t.pendingProps,Ro(e,t,n,r=t.elementType===n?r:fa(n,r),i);case 1:return n=t.type,r=t.pendingProps,Ao(e,t,n,r=t.elementType===n?r:fa(n,r),i);case 3:e:{if(Mo(t),null===e)throw Error(a(387));n=t.pendingProps,r=(s=t.memoizedState).element,Da(e,t),Fa(t,n,null,i);var o=t.memoizedState;if(n=o.element,s.isDehydrated){if(s={element:n,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=s,t.memoizedState=s,256&t.flags){t=ko(e,t,n,i,r=co(Error(a(423)),t));break e}if(n!==r){t=ko(e,t,n,i,r=co(Error(a(424)),t));break e}for(na=cr(t.stateNode.containerInfo.firstChild),ia=t,ra=!0,aa=null,i=Qa(t,null,n,i),t.child=i;i;)i.flags=-3&i.flags|4096,i=i.sibling}else{if(pa(),n===r){t=zo(e,t,i);break e}_o(e,t,n,i)}t=t.child}return t;case 5:return as(t),null===e&&ca(t),n=t.type,r=t.pendingProps,s=null!==e?e.memoizedProps:null,o=r.children,ir(n,r)?o=null:null!==s&&ir(n,s)&&(t.flags|=32),wo(e,t),_o(e,t,o,i),t.child;case 6:return null===e&&ca(t),null;case 13:return Uo(e,t,i);case 4:return ns(t,t.stateNode.containerInfo),n=t.pendingProps,null===e?t.child=Ya(t,null,n,i):_o(e,t,n,i),t.child;case 11:return n=t.type,r=t.pendingProps,Eo(e,t,n,r=t.elementType===n?r:fa(n,r),i);case 7:return _o(e,t,t.pendingProps,i),t.child;case 8:case 12:return _o(e,t,t.pendingProps.children,i),t.child;case 10:e:{if(n=t.type._context,r=t.pendingProps,s=t.memoizedProps,o=r.value,wr(va,n._currentValue),n._currentValue=o,null!==s)if(on(s.value,o)){if(s.children===r.children&&!Pr.current){t=zo(e,t,i);break e}}else for(null!==(s=t.child)&&(s.return=t);null!==s;){var l=s.dependencies;if(null!==l){o=s.child;for(var c=l.firstContext;null!==c;){if(c.context===n){if(1===s.tag){(c=Oa(-1,i&-i)).tag=2;var d=s.updateQueue;if(null!==d){var u=(d=d.shared).pending;null===u?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}s.lanes|=i,null!==(c=s.alternate)&&(c.lanes|=i),Ta(s.return,i,t),l.lanes|=i;break}c=c.next}}else if(10===s.tag)o=s.type===t.type?null:s.child;else if(18===s.tag){if(null===(o=s.return))throw Error(a(341));o.lanes|=i,null!==(l=o.alternate)&&(l.lanes|=i),Ta(o,i,t),o=s.sibling}else o=s.child;if(null!==o)o.return=s;else for(o=s;null!==o;){if(o===t){o=null;break}if(null!==(s=o.sibling)){s.return=o.return,o=s;break}o=o.return}s=o}_o(e,t,r.children,i),t=t.child}return t;case 9:return r=t.type,n=t.pendingProps.children,ba(t,i),n=n(r=Ia(r)),t.flags|=1,_o(e,t,n,i),t.child;case 14:return r=fa(n=t.type,t.pendingProps),To(e,t,n,r=fa(n.type,r),i);case 15:return bo(e,t,t.type,t.pendingProps,i);case 17:return n=t.type,r=t.pendingProps,r=t.elementType===n?r:fa(n,r),jo(e,t),t.tag=1,Dr(n)?(e=!0,xr(t)):e=!1,ba(t,i),Ga(t,n,r),za(t,n,r,i),Po(null,t,n,!0,e,i);case 19:return Go(e,t,i);case 22:return Io(e,t,i)}throw Error(a(156,t.tag))};var Kc="function"==typeof reportError?reportError:function(e){console.error(e)};function Jc(e){this._internalRoot=e}function Yc(e){this._internalRoot=e}function Qc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType)}function Zc(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Xc(){}function ed(e,t,i,n,r){var a=i._reactRootContainer;if(a){var s=a;if("function"==typeof r){var o=r;r=function(){var e=zc(s);o.call(e)}}jc(t,s,e,r)}else s=function(e,t,i,n,r){if(r){if("function"==typeof n){var a=n;n=function(){var e=zc(s);a.call(e)}}var s=Gc(t,n,e,0,null,!1,0,"",Xc);return e._reactRootContainer=s,e[gr]=s.current,$n(8===e.nodeType?e.parentNode:e),uc(),s}for(;r=e.lastChild;)e.removeChild(r);if("function"==typeof n){var o=n;n=function(){var e=zc(l);o.call(e)}}var l=Hc(e,0,!1,null,0,!1,0,"",Xc);return e._reactRootContainer=l,e[gr]=l.current,$n(8===e.nodeType?e.parentNode:e),uc((function(){jc(t,l,i,n)})),l}(i,t,e,r,n);return zc(s)}Yc.prototype.render=Jc.prototype.render=function(e){var t=this._internalRoot;if(null===t)throw Error(a(409));jc(e,t,null,null)},Yc.prototype.unmount=Jc.prototype.unmount=function(){var e=this._internalRoot;if(null!==e){this._internalRoot=null;var t=e.containerInfo;uc((function(){jc(null,e,null,null)})),t[gr]=null}},Yc.prototype.unstable_scheduleHydration=function(e){if(e){var t=bt();e={blockedOn:null,target:e,priority:t};for(var i=0;i<Ot.length&&0!==t&&t<Ot[i].priority;i++);Ot.splice(i,0,e),0===i&&Ft(e)}},_t=function(e){switch(e.tag){case 3:var t=e.stateNode;if(t.current.memoizedState.isDehydrated){var i=ut(t.pendingLanes);0!==i&&(St(t,1|i),rc(t,Qe()),!(6&Pl)&&(Gl=Qe()+500,$r()))}break;case 13:uc((function(){var t=Pa(e,1);if(null!==t){var i=tc();nc(t,e,1,i)}})),qc(e,1)}},Et=function(e){if(13===e.tag){var t=Pa(e,134217728);null!==t&&nc(t,e,134217728,tc()),qc(e,134217728)}},Tt=function(e){if(13===e.tag){var t=ic(e),i=Pa(e,t);null!==i&&nc(i,e,t,tc()),qc(e,t)}},bt=function(){return yt},It=function(e,t){var i=yt;try{return yt=e,t()}finally{yt=i}},Ee=function(e,t,i){switch(t){case"input":if(Z(e,i),t=i.name,"radio"===i.type&&null!=t){for(i=e;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<i.length;t++){var n=i[t];if(n!==e&&n.form===e.form){var r=_r(n);if(!r)throw Error(a(90));q(n),Z(n,r)}}}break;case"textarea":ae(e,i);break;case"select":null!=(t=i.value)&&ie(e,!!i.multiple,t,!1)}},Ae=dc,Pe=uc;var td={usingClientEntryPoint:!1,Events:[yr,Cr,_r,we,Re,dc]},id={findFiberByHostInstance:Sr,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},nd={bundleType:id.bundleType,version:id.version,rendererPackageName:id.rendererPackageName,rendererConfig:id.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:C.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=ze(e))?null:e.stateNode},findFiberByHostInstance:id.findFiberByHostInstance||function(){return null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__){var rd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!rd.isDisabled&&rd.supportsFiber)try{rt=rd.inject(nd),at=rd}catch(de){}}t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=td,t.createPortal=function(e,t){var i=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Qc(t))throw Error(a(200));return function(e,t,i){var n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:E,key:null==n?null:""+n,children:e,containerInfo:t,implementation:i}}(e,t,null,i)},t.createRoot=function(e,t){if(!Qc(e))throw Error(a(299));var i=!1,n="",r=Kc;return null!=t&&(!0===t.unstable_strictMode&&(i=!0),void 0!==t.identifierPrefix&&(n=t.identifierPrefix),void 0!==t.onRecoverableError&&(r=t.onRecoverableError)),t=Hc(e,1,!1,null,0,i,0,n,r),e[gr]=t.current,$n(8===e.nodeType?e.parentNode:e),new Jc(t)},t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternals;if(void 0===t){if("function"==typeof e.render)throw Error(a(188));throw e=Object.keys(e).join(","),Error(a(268,e))}return null===(e=ze(t))?null:e.stateNode},t.flushSync=function(e){return uc(e)},t.hydrate=function(e,t,i){if(!Zc(t))throw Error(a(200));return ed(null,e,t,!0,i)},t.hydrateRoot=function(e,t,i){if(!Qc(e))throw Error(a(405));var n=null!=i&&i.hydratedSources||null,r=!1,s="",o=Kc;if(null!=i&&(!0===i.unstable_strictMode&&(r=!0),void 0!==i.identifierPrefix&&(s=i.identifierPrefix),void 0!==i.onRecoverableError&&(o=i.onRecoverableError)),t=Gc(t,null,e,1,null!=i?i:null,r,0,s,o),e[gr]=t.current,$n(e),n)for(e=0;e<n.length;e++)r=(r=(i=n[e])._getVersion)(i._source),null==t.mutableSourceEagerHydrationData?t.mutableSourceEagerHydrationData=[i,r]:t.mutableSourceEagerHydrationData.push(i,r);return new Yc(t)},t.render=function(e,t,i){if(!Zc(t))throw Error(a(200));return ed(null,e,t,!1,i)},t.unmountComponentAtNode=function(e){if(!Zc(e))throw Error(a(40));return!!e._reactRootContainer&&(uc((function(){ed(null,null,e,!1,(function(){e._reactRootContainer=null,e[gr]=null}))})),!0)},t.unstable_batchedUpdates=dc,t.unstable_renderSubtreeIntoContainer=function(e,t,i,n){if(!Zc(i))throw Error(a(200));if(null==e||void 0===e._reactInternals)throw Error(a(38));return ed(e,t,i,!1,n)},t.version="18.2.0-next-9e3b772b8-20220608"},1112:(e,t,i)=>{"use strict";var n=i(2997);t.s=n.createRoot,n.hydrateRoot},2997:(e,t,i)=>{"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=i(8303)},2805:(e,t)=>{"use strict";var i=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),u=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),p=Symbol.iterator,g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,f={};function v(e,t,i){this.props=e,this.context=t,this.refs=f,this.updater=i||g}function S(){}function y(e,t,i){this.props=e,this.context=t,this.refs=f,this.updater=i||g}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},S.prototype=v.prototype;var C=y.prototype=new S;C.constructor=y,m(C,v.prototype),C.isPureReactComponent=!0;var _=Array.isArray,E=Object.prototype.hasOwnProperty,T={current:null},b={key:!0,ref:!0,__self:!0,__source:!0};function I(e,t,n){var r,a={},s=null,o=null;if(null!=t)for(r in void 0!==t.ref&&(o=t.ref),void 0!==t.key&&(s=""+t.key),t)E.call(t,r)&&!b.hasOwnProperty(r)&&(a[r]=t[r]);var l=arguments.length-2;if(1===l)a.children=n;else if(1<l){for(var c=Array(l),d=0;d<l;d++)c[d]=arguments[d+2];a.children=c}if(e&&e.defaultProps)for(r in l=e.defaultProps)void 0===a[r]&&(a[r]=l[r]);return{$$typeof:i,type:e,key:s,ref:o,props:a,_owner:T.current}}function w(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}var R=/\/+/g;function A(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,(function(e){return t[e]}))}(""+e.key):t.toString(36)}function P(e,t,r,a,s){var o=typeof e;"undefined"!==o&&"boolean"!==o||(e=null);var l=!1;if(null===e)l=!0;else switch(o){case"string":case"number":l=!0;break;case"object":switch(e.$$typeof){case i:case n:l=!0}}if(l)return s=s(l=e),e=""===a?"."+A(l,0):a,_(s)?(r="",null!=e&&(r=e.replace(R,"$&/")+"/"),P(s,t,r,"",(function(e){return e}))):null!=s&&(w(s)&&(s=function(e,t){return{$$typeof:i,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(s,r+(!s.key||l&&l.key===s.key?"":(""+s.key).replace(R,"$&/")+"/")+e)),t.push(s)),1;if(l=0,a=""===a?".":a+":",_(e))for(var c=0;c<e.length;c++){var d=a+A(o=e[c],c);l+=P(o,t,r,d,s)}else if(d=function(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=p&&e[p]||e["@@iterator"])?e:null}(e),"function"==typeof d)for(e=d.call(e),c=0;!(o=e.next()).done;)l+=P(o=o.value,t,r,d=a+A(o,c++),s);else if("object"===o)throw t=String(e),Error("Objects are not valid as a React child (found: "+("[object Object]"===t?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.");return l}function M(e,t,i){if(null==e)return e;var n=[],r=0;return P(e,n,"","",(function(e){return t.call(i,e,r++)})),n}function k(e){if(-1===e._status){var t=e._result;(t=t()).then((function(t){0!==e._status&&-1!==e._status||(e._status=1,e._result=t)}),(function(t){0!==e._status&&-1!==e._status||(e._status=2,e._result=t)})),-1===e._status&&(e._status=0,e._result=t)}if(1===e._status)return e._result.default;throw e._result}var D={current:null},O={transition:null},N={ReactCurrentDispatcher:D,ReactCurrentBatchConfig:O,ReactCurrentOwner:T};t.Children={map:M,forEach:function(e,t,i){M(e,(function(){t.apply(this,arguments)}),i)},count:function(e){var t=0;return M(e,(function(){t++})),t},toArray:function(e){return M(e,(function(e){return e}))||[]},only:function(e){if(!w(e))throw Error("React.Children.only expected to receive a single React element child.");return e}},t.Component=v,t.Fragment=r,t.Profiler=s,t.PureComponent=y,t.StrictMode=a,t.Suspense=d,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=N,t.cloneElement=function(e,t,n){if(null==e)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+e+".");var r=m({},e.props),a=e.key,s=e.ref,o=e._owner;if(null!=t){if(void 0!==t.ref&&(s=t.ref,o=T.current),void 0!==t.key&&(a=""+t.key),e.type&&e.type.defaultProps)var l=e.type.defaultProps;for(c in t)E.call(t,c)&&!b.hasOwnProperty(c)&&(r[c]=void 0===t[c]&&void 0!==l?l[c]:t[c])}var c=arguments.length-2;if(1===c)r.children=n;else if(1<c){l=Array(c);for(var d=0;d<c;d++)l[d]=arguments[d+2];r.children=l}return{$$typeof:i,type:e.type,key:a,ref:s,props:r,_owner:o}},t.createContext=function(e){return(e={$$typeof:l,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null}).Provider={$$typeof:o,_context:e},e.Consumer=e},t.createElement=I,t.createFactory=function(e){var t=I.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:c,render:e}},t.isValidElement=w,t.lazy=function(e){return{$$typeof:h,_payload:{_status:-1,_result:e},_init:k}},t.memo=function(e,t){return{$$typeof:u,type:e,compare:void 0===t?null:t}},t.startTransition=function(e){var t=O.transition;O.transition={};try{e()}finally{O.transition=t}},t.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")},t.useCallback=function(e,t){return D.current.useCallback(e,t)},t.useContext=function(e){return D.current.useContext(e)},t.useDebugValue=function(){},t.useDeferredValue=function(e){return D.current.useDeferredValue(e)},t.useEffect=function(e,t){return D.current.useEffect(e,t)},t.useId=function(){return D.current.useId()},t.useImperativeHandle=function(e,t,i){return D.current.useImperativeHandle(e,t,i)},t.useInsertionEffect=function(e,t){return D.current.useInsertionEffect(e,t)},t.useLayoutEffect=function(e,t){return D.current.useLayoutEffect(e,t)},t.useMemo=function(e,t){return D.current.useMemo(e,t)},t.useReducer=function(e,t,i){return D.current.useReducer(e,t,i)},t.useRef=function(e){return D.current.useRef(e)},t.useState=function(e){return D.current.useState(e)},t.useSyncExternalStore=function(e,t,i){return D.current.useSyncExternalStore(e,t,i)},t.useTransition=function(){return D.current.useTransition()},t.version="18.2.0"},3981:(e,t,i)=>{"use strict";e.exports=i(2805)},2390:(e,t)=>{"use strict";function i(e,t){var i=e.length;e.push(t);e:for(;0<i;){var n=i-1>>>1,r=e[n];if(!(0<a(r,t)))break e;e[n]=t,e[i]=r,i=n}}function n(e){return 0===e.length?null:e[0]}function r(e){if(0===e.length)return null;var t=e[0],i=e.pop();if(i!==t){e[0]=i;e:for(var n=0,r=e.length,s=r>>>1;n<s;){var o=2*(n+1)-1,l=e[o],c=o+1,d=e[c];if(0>a(l,i))c<r&&0>a(d,l)?(e[n]=d,e[c]=i,n=c):(e[n]=l,e[o]=i,n=o);else{if(!(c<r&&0>a(d,i)))break e;e[n]=d,e[c]=i,n=c}}}return t}function a(e,t){var i=e.sortIndex-t.sortIndex;return 0!==i?i:e.id-t.id}if("object"==typeof performance&&"function"==typeof performance.now){var s=performance;t.unstable_now=function(){return s.now()}}else{var o=Date,l=o.now();t.unstable_now=function(){return o.now()-l}}var c=[],d=[],u=1,h=null,p=3,g=!1,m=!1,f=!1,v="function"==typeof setTimeout?setTimeout:null,S="function"==typeof clearTimeout?clearTimeout:null,y="undefined"!=typeof setImmediate?setImmediate:null;function C(e){for(var t=n(d);null!==t;){if(null===t.callback)r(d);else{if(!(t.startTime<=e))break;r(d),t.sortIndex=t.expirationTime,i(c,t)}t=n(d)}}function _(e){if(f=!1,C(e),!m)if(null!==n(c))m=!0,O(E);else{var t=n(d);null!==t&&N(_,t.startTime-e)}}function E(e,i){m=!1,f&&(f=!1,S(w),w=-1),g=!0;var a=p;try{for(C(i),h=n(c);null!==h&&(!(h.expirationTime>i)||e&&!P());){var s=h.callback;if("function"==typeof s){h.callback=null,p=h.priorityLevel;var o=s(h.expirationTime<=i);i=t.unstable_now(),"function"==typeof o?h.callback=o:h===n(c)&&r(c),C(i)}else r(c);h=n(c)}if(null!==h)var l=!0;else{var u=n(d);null!==u&&N(_,u.startTime-i),l=!1}return l}finally{h=null,p=a,g=!1}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var T,b=!1,I=null,w=-1,R=5,A=-1;function P(){return!(t.unstable_now()-A<R)}function M(){if(null!==I){var e=t.unstable_now();A=e;var i=!0;try{i=I(!0,e)}finally{i?T():(b=!1,I=null)}}else b=!1}if("function"==typeof y)T=function(){y(M)};else if("undefined"!=typeof MessageChannel){var k=new MessageChannel,D=k.port2;k.port1.onmessage=M,T=function(){D.postMessage(null)}}else T=function(){v(M,0)};function O(e){I=e,b||(b=!0,T())}function N(e,i){w=v((function(){e(t.unstable_now())}),i)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){m||g||(m=!0,O(E))},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):R=0<e?Math.floor(1e3/e):5},t.unstable_getCurrentPriorityLevel=function(){return p},t.unstable_getFirstCallbackNode=function(){return n(c)},t.unstable_next=function(e){switch(p){case 1:case 2:case 3:var t=3;break;default:t=p}var i=p;p=t;try{return e()}finally{p=i}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var i=p;p=e;try{return t()}finally{p=i}},t.unstable_scheduleCallback=function(e,r,a){var s=t.unstable_now();switch(a="object"==typeof a&&null!==a&&"number"==typeof(a=a.delay)&&0<a?s+a:s,e){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return e={id:u++,callback:r,priorityLevel:e,startTime:a,expirationTime:o=a+o,sortIndex:-1},a>s?(e.sortIndex=a,i(d,e),null===n(c)&&e===n(d)&&(f?(S(w),w=-1):f=!0,N(_,a-s))):(e.sortIndex=o,i(c,e),m||g||(m=!0,O(E))),e},t.unstable_shouldYield=P,t.unstable_wrapCallback=function(e){var t=p;return function(){var i=p;p=t;try{return e.apply(this,arguments)}finally{p=i}}}},7574:(e,t,i)=>{"use strict";e.exports=i(2390)},3011:e=>{e.exports=function(){var e=document.getSelection();if(!e.rangeCount)return function(){};for(var t=document.activeElement,i=[],n=0;n<e.rangeCount;n++)i.push(e.getRangeAt(n));switch(t.tagName.toUpperCase()){case"INPUT":case"TEXTAREA":t.blur();break;default:t=null}return e.removeAllRanges(),function(){"Caret"===e.type&&e.removeAllRanges(),e.rangeCount||i.forEach((function(t){e.addRange(t)})),t&&t.focus()}}},2289:e=>{"use strict";e.exports="1.16.0-beta.1"}},n={};function r(e){var t=n[e];if(void 0!==t)return t.exports;var a=n[e]={exports:{}};return i[e].call(a.exports,a,a.exports,r),a.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(i,n){if(1&n&&(i=this(i)),8&n)return i;if("object"==typeof i&&i){if(4&n&&i.__esModule)return i;if(16&n&&"function"==typeof i.then)return i}var a=Object.create(null);r.r(a);var s={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&i;"object"==typeof o&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach((e=>s[e]=()=>i[e]));return s.default=()=>i,r.d(a,s),a},r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var a={};return(()=>{"use strict";r.r(a),r.d(a,{loadCallComposite:()=>yO});var e=r(3981),t=r.t(e,2),i=r(1112);class n extends Error{}n.prototype.name="InvalidTokenError";const s=e=>{const{exp:t}=function(e,t){if("string"!=typeof e)throw new n("Invalid token specified: must be a string");t||(t={});const i=!0===t.header?0:1,r=e.split(".")[i];if("string"!=typeof r)throw new n(`Invalid token specified: missing part #${i+1}`);let a;try{a=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,((e,t)=>{let i=t.charCodeAt(0).toString(16).toUpperCase();return i.length<2&&(i="0"+i),"%"+i})))}(t)}catch(e){return atob(t)}}(r)}catch(e){throw new n(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(a)}catch(e){throw new n(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}(e);return{token:e,expiresOnTimestamp:1e3*t}},o={token:"",expiresOnTimestamp:-10};class l{constructor(e){this.expiringSoonIntervalInMs=6e5,this.refreshAfterLifetimePercentage=.5,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.disposed=!1;const{tokenRefresher:t,token:i,refreshProactively:n}=e;this.refresh=t,this.currentToken=i?s(i):o,this.refreshProactively=null!=n&&n,this.refreshProactively&&this.scheduleRefresh()}async getToken(e){if(!this.isTokenExpiringSoon(this.currentToken))return this.currentToken;if(!this.isTokenValid(this.currentToken)){const t=this.updateTokenAndReschedule(null==e?void 0:e.abortSignal);await t}return this.currentToken}dispose(){this.disposed=!0,this.activeTokenFetching=null,this.activeTokenUpdating=null,this.currentToken=o,this.activeTimeout&&clearTimeout(this.activeTimeout)}async updateTokenAndReschedule(e){if(this.activeTokenUpdating)return this.activeTokenUpdating;this.activeTokenUpdating=this.refreshTokenAndReschedule(e);try{await this.activeTokenUpdating}finally{this.activeTokenUpdating=null}}async refreshTokenAndReschedule(e){const t=await this.refreshToken(e);if(!this.isTokenValid(t))throw new Error("The token returned from the tokenRefresher is expired.");this.currentToken=t,this.refreshProactively&&this.scheduleRefresh()}async refreshToken(e){try{return this.activeTokenFetching||(this.activeTokenFetching=this.refresh(e)),s(await this.activeTokenFetching)}finally{this.activeTokenFetching=null}}scheduleRefresh(){if(this.disposed)return;this.activeTimeout&&clearTimeout(this.activeTimeout);const e=this.currentToken.expiresOnTimestamp-Date.now();let t=null;t=this.isTokenExpiringSoon(this.currentToken)?e*this.refreshAfterLifetimePercentage:e-this.expiringSoonIntervalInMs,this.activeTimeout=setTimeout((()=>this.updateTokenAndReschedule()),t)}isTokenValid(e){return e&&Date.now()<e.expiresOnTimestamp}isTokenExpiringSoon(e){return!e||Date.now()>=e.expiresOnTimestamp-this.expiringSoonIntervalInMs}}class c{constructor(e){this.token=e}async getToken(){return this.token}dispose(){}}class d{constructor(e){this.disposed=!1,this.tokenCredential="string"==typeof e?new c(s(e)):new l(e)}async getToken(e){this.throwIfDisposed();const t=await this.tokenCredential.getToken(e);return this.throwIfDisposed(),t}dispose(){this.disposed=!0,this.tokenCredential.dispose()}throwIfDisposed(){if(this.disposed)throw new Error("User credential is disposed")}}var u=r(2561);const h=(0,u.createClientLogger)("communication-react:composite");var p=r(6251);const g=e=>"string"==typeof e.communicationUserId,m=e=>"string"==typeof e.phoneNumber,f=e=>"string"==typeof e.microsoftTeamsUserId,v=e=>"string"==typeof e.teamsAppId,S=e=>g(e)?Object.assign(Object.assign({},e),{kind:"communicationUser"}):m(e)?Object.assign(Object.assign({},e),{kind:"phoneNumber"}):f(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsUser"}):v(e)?Object.assign(Object.assign({},e),{kind:"microsoftTeamsApp"}):Object.assign(Object.assign({},e),{kind:"unknown"}),y=(e,t)=>({kind:"microsoftTeamsApp",teamsAppId:e,cloud:t}),C=(e,t,i)=>({kind:"microsoftTeamsUser",microsoftTeamsUserId:e,isAnonymous:i,cloud:t}),_=e=>(e=>{const t=S(e);switch(t.kind){case"communicationUser":return t.communicationUserId;case"microsoftTeamsUser":{const{microsoftTeamsUserId:e,rawId:i,cloud:n,isAnonymous:r}=t;if(i)return i;if(r)return`8:teamsvisitor:${e}`;switch(n){case"dod":return`8:dod:${e}`;case"gcch":return`8:gcch:${e}`;case"public":return`8:orgid:${e}`}return`8:orgid:${e}`}case"microsoftTeamsApp":{const{teamsAppId:e,rawId:i,cloud:n}=t;if(i)return i;switch(n){case"dod":return`28:dod:${e}`;case"gcch":return`28:gcch:${e}`}return`28:orgid:${e}`}case"phoneNumber":{const{phoneNumber:e,rawId:i}=t;return i||`4:${e}`}case"unknown":return t.id}})(e),E=e=>(e=>{if(e.startsWith("4:"))return{kind:"phoneNumber",phoneNumber:`${e.substring(2)}`};const t=e.split(":");if(3!==t.length)return{kind:"unknown",id:e};const i=`${t[0]}:${t[1]}:`,n=t[2];switch(i){case"8:teamsvisitor:":return{kind:"microsoftTeamsUser",microsoftTeamsUserId:n,isAnonymous:!0};case"8:orgid:":return C(n,"public",!1);case"8:dod:":return C(n,"dod",!1);case"8:gcch:":return C(n,"gcch",!1);case"8:acs:":case"8:spool:":case"8:dod-acs:":case"8:gcch-acs:":return{kind:"communicationUser",communicationUserId:e};case"28:orgid:":return y(n,"public");case"28:gcch:":return y(n,"gcch");case"28:dod:":return y(n,"dod")}return{kind:"unknown",id:e}})(0===e.indexOf("+")?"4:"+e:e),T=e=>"string"==typeof e?E(e):e,b=(e,t=Object.is)=>{let i=new Map,n=new Map;return r=>{const a=r(((r,...a)=>{const s=i.get(r);if(s){const[e,i]=s;if(l=a,c=t,(o=e).length===l.length&&o.every(((e,t)=>c(l[t],e))))return n.set(r,[a,i]),i}var o,l,c;const d=e(r,...a);return n.set(r,[a,d]),d}));return i=n,n=new Map,a}};const I=e=>!!e&&!["None","Disconnected","Connecting","Ringing","EarlyMedia","Disconnecting"].includes(e),w=e=>!!e&&["Connecting","Ringing","InLobby","EarlyMedia"].includes(e),R=e=>e.unparentedViews.length>0&&void 0!==e.unparentedViews[0].view,A=e=>{return t=void 0,i=void 0,r=function*(){const t=e.getState().deviceManager.unparentedViews;for(const i of t)yield e.disposeView(void 0,void 0,i)},new((n=void 0)||(n=Promise))((function(e,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(s,o)}l((r=r.apply(t,i||[])).next())}));var t,i,n,r},P=e=>e?M((t=>Object.values(e).map((e=>{const i=_(e.identifier);return t(i,e)})))):[],M=b(((e,t)=>m(t.identifier)?Object.assign(Object.assign({},t),{displayName:t.identifier.phoneNumber}):t)),k=e=>m(e.identifier)&&"Connecting"===e.state?"Ringing":e.state;var D=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};class O{constructor(e,t){this.setDeviceManager=()=>{this._context.setDeviceManagerIsSpeakerSelectionAvailable(this._deviceManager.isSpeakerSelectionAvailable),this._context.setDeviceManagerSelectedMicrophone(this._deviceManager.selectedMicrophone),this._context.setDeviceManagerSelectedSpeaker(this._deviceManager.selectedSpeaker)},this.subscribe=()=>{this._deviceManager.on("videoDevicesUpdated",this.videoDevicesUpdated),this._deviceManager.on("audioDevicesUpdated",this.audioDevicesUpdated),this._deviceManager.on("selectedMicrophoneChanged",this.selectedMicrophoneChanged),this._deviceManager.on("selectedSpeakerChanged",this.selectedSpeakerChanged);try{navigator.permissions.query({name:"camera"}).then((e=>{e.addEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not subscribe to Permissions API Camera changed events, API is not supported by browser",e)}try{navigator.permissions.query({name:"microphone"}).then((e=>{e.addEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not subscribe to Permissions API Microphone changed events, API is not supported by browser",e)}},this.unsubscribe=()=>{this._deviceManager.off("videoDevicesUpdated",this.videoDevicesUpdated),this._deviceManager.off("audioDevicesUpdated",this.audioDevicesUpdated),this._deviceManager.off("selectedMicrophoneChanged",this.selectedMicrophoneChanged),this._deviceManager.off("selectedSpeakerChanged",this.selectedSpeakerChanged);try{navigator.permissions.query({name:"camera"}).then((e=>{e.removeEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not Unsubscribe to Permissions API Camera changed events, API is not supported by browser",e)}try{navigator.permissions.query({name:"microphone"}).then((e=>{e.removeEventListener("change",this.permissionsApiStateChangeHandler)}))}catch(e){console.info("Could not Unsubscribe to Permissions API Camera changed events, API is not supported by browser",e)}},this.permissionsApiStateChangeHandler=()=>D(this,void 0,void 0,(function*(){yield this.updateDevicePermissionState()})),this.selectCamera=e=>{this._context.setDeviceManagerSelectedCamera(e)},this.videoDevicesUpdated=()=>D(this,void 0,void 0,(function*(){const e=(yield this._deviceManager.getCameras()).filter((e=>!!e.name));this._context.setDeviceManagerCameras(N(e))})),this.audioDevicesUpdated=()=>D(this,void 0,void 0,(function*(){this._context.setDeviceManagerMicrophones(N(yield this._deviceManager.getMicrophones())),this._context.setDeviceManagerSpeakers(N(yield this._deviceManager.getSpeakers()))})),this.selectedMicrophoneChanged=()=>{this._context.setDeviceManagerSelectedMicrophone(this._deviceManager.selectedMicrophone)},this.selectedSpeakerChanged=()=>{this._context.setDeviceManagerSelectedSpeaker(this._deviceManager.selectedSpeaker)},this.updateDevicePermissionState=e=>D(this,void 0,void 0,(function*(){let t=!!(null==e?void 0:e.video),i=!!(null==e?void 0:e.audio);try{const[e,n]=yield Promise.all([navigator.permissions.query({name:"camera"}),navigator.permissions.query({name:"microphone"})]);t="granted"===e.state,i="granted"===n.state}catch(e){console.info("Permissions API is not supported by browser",e)}this._context.setDeviceManagerDeviceAccess({video:t,audio:i}),this.setDeviceManager()})),this._deviceManager=e,this._context=t,this.setDeviceManager(),this.subscribe()}get(e,t){switch(t){case"getCameras":return this._context.withAsyncErrorTeedToState((()=>e.getCameras().then((e=>{const t=e.filter((e=>!!e.name));return this._context.setDeviceManagerCameras(N(t)),t}))),"DeviceManager.getCameras");case"getMicrophones":return this._context.withAsyncErrorTeedToState((()=>e.getMicrophones().then((e=>(this._context.setDeviceManagerMicrophones(N(e)),e)))),"DeviceManager.getMicrophones");case"getSpeakers":return this._context.withAsyncErrorTeedToState((()=>e.getSpeakers().then((e=>(this._context.setDeviceManagerSpeakers(N(e)),e)))),"DeviceManager.getSpeakers");case"selectMicrophone":return this._context.withAsyncErrorTeedToState(((...t)=>e.selectMicrophone(...t).then((()=>{this._context.setDeviceManagerSelectedMicrophone(e.selectedMicrophone)}))),"DeviceManager.selectMicrophone");case"selectSpeaker":return this._context.withAsyncErrorTeedToState(((...t)=>e.selectSpeaker(...t).then((()=>{this._context.setDeviceManagerSelectedSpeaker(e.selectedSpeaker)}))),"DeviceManager.selectSpeaker");case"askDevicePermission":return this._context.withAsyncErrorTeedToState(((...t)=>e.askDevicePermission(...t).then((e=>D(this,void 0,void 0,(function*(){return yield this.updateDevicePermissionState(e),e}))))),"DeviceManager.askDevicePermission");default:return Reflect.get(e,t)}}}const N=e=>{const t=new Set,i=[];return e.forEach((e=>{t.has(e.id)||(i.push(e),t.add(e.id))})),i};var L=r(4090),x=r.n(L),F=Symbol.for("immer-nothing"),U=Symbol.for("immer-draftable"),B=Symbol.for("immer-state");function V(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var H=Object.getPrototypeOf;function $(e){return!!e&&!!e[B]}function G(e){return!!e&&(z(e)||Array.isArray(e)||!!e[U]||!!e.constructor?.[U]||Q(e)||Z(e))}var j=Object.prototype.constructor.toString();function z(e){if(!e||"object"!=typeof e)return!1;const t=H(e);if(null===t)return!0;const i=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;return i===Object||"function"==typeof i&&Function.toString.call(i)===j}function W(e,t){0===q(e)?Reflect.ownKeys(e).forEach((i=>{t(i,e[i],e)})):e.forEach(((i,n)=>t(n,i,e)))}function q(e){const t=e[B];return t?t.type_:Array.isArray(e)?1:Q(e)?2:Z(e)?3:0}function K(e,t){return 2===q(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function J(e,t){return 2===q(e)?e.get(t):e[t]}function Y(e,t,i){const n=q(e);2===n?e.set(t,i):3===n?e.add(i):e[t]=i}function Q(e){return e instanceof Map}function Z(e){return e instanceof Set}function X(e){return e.copy_||e.base_}function ee(e,t){if(Q(e))return new Map(e);if(Z(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&z(e)){if(!H(e)){const t=Object.create(null);return Object.assign(t,e)}return{...e}}const i=Object.getOwnPropertyDescriptors(e);delete i[B];let n=Reflect.ownKeys(i);for(let t=0;t<n.length;t++){const r=n[t],a=i[r];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(i[r]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[r]})}return Object.create(H(e),i)}function te(e,t=!1){return ne(e)||$(e)||!G(e)||(q(e)>1&&(e.set=e.add=e.clear=e.delete=ie),Object.freeze(e),t&&Object.entries(e).forEach((([e,t])=>te(t,!0)))),e}function ie(){V(2)}function ne(e){return Object.isFrozen(e)}var re,ae={};function se(e){const t=ae[e];return t||V(0),t}function oe(e,t){ae[e]||(ae[e]=t)}function le(){return re}function ce(e,t){t&&(se("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function de(e){ue(e),e.drafts_.forEach(pe),e.drafts_=null}function ue(e){e===re&&(re=e.parent_)}function he(e){return re={drafts_:[],parent_:re,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function pe(e){const t=e[B];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function ge(e,t){t.unfinalizedDrafts_=t.drafts_.length;const i=t.drafts_[0];return void 0!==e&&e!==i?(i[B].modified_&&(de(t),V(4)),G(e)&&(e=me(t,e),t.parent_||ve(t,e)),t.patches_&&se("Patches").generateReplacementPatches_(i[B].base_,e,t.patches_,t.inversePatches_)):e=me(t,i,[]),de(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==F?e:void 0}function me(e,t,i){if(ne(t))return t;const n=t[B];if(!n)return W(t,((r,a)=>fe(e,n,t,r,a,i))),t;if(n.scope_!==e)return t;if(!n.modified_)return ve(e,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const t=n.copy_;let r=t,a=!1;3===n.type_&&(r=new Set(t),t.clear(),a=!0),W(r,((r,s)=>fe(e,n,t,r,s,i,a))),ve(e,t,!1),i&&e.patches_&&se("Patches").generatePatches_(n,i,e.patches_,e.inversePatches_)}return n.copy_}function fe(e,t,i,n,r,a,s){if($(r)){const s=me(e,r,a&&t&&3!==t.type_&&!K(t.assigned_,n)?a.concat(n):void 0);if(Y(i,n,s),!$(s))return;e.canAutoFreeze_=!1}else s&&i.add(r);if(G(r)&&!ne(r)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;me(e,r),t&&t.scope_.parent_||"symbol"==typeof n||!Object.prototype.propertyIsEnumerable.call(i,n)||ve(e,r)}}function ve(e,t,i=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&te(t,i)}var Se={get(e,t){if(t===B)return e;const i=X(e);if(!K(i,t))return function(e,t,i){const n=_e(t,i);return n?"value"in n?n.value:n.get?.call(e.draft_):void 0}(e,i,t);const n=i[t];return e.finalized_||!G(n)?n:n===Ce(e.base_,t)?(Te(e),e.copy_[t]=be(n,e)):n},has:(e,t)=>t in X(e),ownKeys:e=>Reflect.ownKeys(X(e)),set(e,t,i){const n=_e(X(e),t);if(n?.set)return n.set.call(e.draft_,i),!0;if(!e.modified_){const n=Ce(X(e),t),s=n?.[B];if(s&&s.base_===i)return e.copy_[t]=i,e.assigned_[t]=!1,!0;if(((r=i)===(a=n)?0!==r||1/r==1/a:r!=r&&a!=a)&&(void 0!==i||K(e.base_,t)))return!0;Te(e),Ee(e)}var r,a;return e.copy_[t]===i&&(void 0!==i||t in e.copy_)||Number.isNaN(i)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=i,e.assigned_[t]=!0),!0},deleteProperty:(e,t)=>(void 0!==Ce(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,Te(e),Ee(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){const i=X(e),n=Reflect.getOwnPropertyDescriptor(i,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:i[t]}:n},defineProperty(){V(11)},getPrototypeOf:e=>H(e.base_),setPrototypeOf(){V(12)}},ye={};function Ce(e,t){const i=e[B];return(i?X(i):e)[t]}function _e(e,t){if(!(t in e))return;let i=H(e);for(;i;){const e=Object.getOwnPropertyDescriptor(i,t);if(e)return e;i=H(i)}}function Ee(e){e.modified_||(e.modified_=!0,e.parent_&&Ee(e.parent_))}function Te(e){e.copy_||(e.copy_=ee(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function be(e,t){const i=Q(e)?se("MapSet").proxyMap_(e,t):Z(e)?se("MapSet").proxySet_(e,t):function(e,t){const i=Array.isArray(e),n={type_:i?1:0,scope_:t?t.scope_:le(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let r=n,a=Se;i&&(r=[n],a=ye);const{revoke:s,proxy:o}=Proxy.revocable(r,a);return n.draft_=o,n.revoke_=s,o}(e,t);return(t?t.scope_:le()).drafts_.push(i),i}function Ie(e){if(!G(e)||ne(e))return e;const t=e[B];let i;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,i=ee(e,t.scope_.immer_.useStrictShallowCopy_)}else i=ee(e,!0);return W(i,((e,t)=>{Y(i,e,Ie(t))})),t&&(t.finalized_=!1),i}W(Se,((e,t)=>{ye[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),ye.deleteProperty=function(e,t){return ye.set.call(this,e,t,void 0)},ye.set=function(e,t,i){return Se.set.call(this,e[0],t,i,e[0])};var we=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,i)=>{if("function"==typeof e&&"function"!=typeof t){const i=t;t=e;const n=this;return function(e=i,...r){return n.produce(e,(e=>t.call(this,e,...r)))}}let n;if("function"!=typeof t&&V(6),void 0!==i&&"function"!=typeof i&&V(7),G(e)){const r=he(this),a=be(e,void 0);let s=!0;try{n=t(a),s=!1}finally{s?de(r):ue(r)}return ce(r,i),ge(n,r)}if(!e||"object"!=typeof e){if(n=t(e),void 0===n&&(n=e),n===F&&(n=void 0),this.autoFreeze_&&te(n,!0),i){const t=[],r=[];se("Patches").generateReplacementPatches_(e,n,t,r),i(t,r)}return n}V(1)},this.produceWithPatches=(e,t)=>{if("function"==typeof e)return(t,...i)=>this.produceWithPatches(t,(t=>e(t,...i)));let i,n;return[this.produce(e,t,((e,t)=>{i=e,n=t})),i,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){var t;G(e)||V(8),$(e)&&($(t=e)||V(10),e=Ie(t));const i=he(this),n=be(e,void 0);return n[B].isManual_=!0,ue(i),n}finishDraft(e,t){const i=e&&e[B];i&&i.isManual_||V(9);const{scope_:n}=i;return ce(n,t),ge(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let i;for(i=t.length-1;i>=0;i--){const n=t[i];if(0===n.path.length&&"replace"===n.op){e=n.value;break}}i>-1&&(t=t.slice(i+1));const n=se("Patches").applyPatches_;return $(e)?n(e,t):this.produce(e,(e=>n(e,t)))}},Re=we.produce;we.produceWithPatches.bind(we),we.setAutoFreeze.bind(we),we.setUseStrictShallowCopy.bind(we),we.applyPatches.bind(we),we.createDraft.bind(we),we.finishDraft.bind(we);const Ae=(e,t=Pe(),i)=>{try{return JSON.stringify(e,t,i)}catch(e){return void console.error(e)}},Pe=()=>{const e=new Set;return function(t,i){return"object"!=typeof i?i:e.has(i)?"Visited-Ref":(e.add(i),i)}};class Me extends Error{constructor(e,t,i){super(),this.target=e,this.innerError=t,this.timestamp=null!=i?i:new Date(Date.now()),this.name="CallError",this.message=`${this.target}: ${this.innerError.message}`}}const ke=(0,u.createClientLogger)("communication-react:calling-stateful");var De;!function(e){e.VIEW_RENDER_SUCCEED="VIEW_RENDER_SUCCEED",e.START_DISPOSE_STREAM="START_DISPOSE_STREAM",e.START_STREAM_RENDERING="START_STREAM_RENDERING",e.DISPOSING_RENDERER="DISPOSING_RENDERER",e.CREATING_VIEW="CREATING_VIEW",e.CREATE_STREAM_INVALID_PARAMS="CREATE_STREAM_INVALID_PARAMS",e.DISPOSE_STREAM_INVALID_PARAMS="DISPOSE_STREAM_INVALID_PARAMS",e.STREAM_ALREADY_RENDERED="STREAM_ALREADY_RENDERED",e.STREAM_ALREADY_DISPOSED="STREAM_ALREADY_DISPOSED",e.STREAM_STOPPING="STREAM_STOPPING",e.CREATED_STREAM_STOPPING="CREATED_STREAM_STOPPING",e.STREAM_RENDERING="STREAM_RENDERING",e.STREAM_NOT_FOUND="STREAM_NOT_FOUND",e.RENDER_INFO_NOT_FOUND="RENDER_INFO_NOT_FOUND",e.DISPOSE_INFO_NOT_FOUND="DISPOSE_INFO_NOT_FOUND",e.RENDERER_NOT_FOUND="RENDERER_NOT_FOUND",e.CREATE_STREAM_FAIL="CREATE_STREAM_FAIL"}(De||(De={}));class Oe{constructor(){this._callIdHistory=new Map}updateCallIdHistory(e,t){const i=this._callIdHistory.get(e);void 0!==i&&this.latestCallId(e)!==t&&console.trace(`${e} alredy exists and maps to ${i}, which is not the same as ${t}`),this._callIdHistory.delete(e),this._callIdHistory.set(t,e)}latestCallId(e){let t=e;for(;;){const e=this._callIdHistory.get(t);if(void 0===e)break;t=e}return t}}const Ne=e=>!e.kind||"Call"===e.kind,Le=e=>!e.kind||"CallAgent"===e.kind,xe=e=>"TeamsCall"===e.kind,Fe=e=>"TeamsCallAgent"===e.kind;function Ue(e){const t=e.feature(p.Features.VideoEffects);return{source:e.source,mediaStreamType:e.mediaStreamType,view:void 0,videoEffects:$e(t.activeEffects)}}function Be(e){return{id:e.id,mediaStreamType:e.mediaStreamType,isAvailable:e.isAvailable,isReceiving:e.isReceiving,view:void 0,streamSize:e.size}}function Ve(e){const t={};for(const i of e.videoStreams)t[i.id]=Be(i);return{identifier:e.identifier,displayName:e.displayName,state:e.state,callEndReason:e.callEndReason,videoStreams:t,isMuted:e.isMuted,isSpeaking:e.isSpeaking,raisedHand:void 0,spotlight:void 0}}function He(e){return{scalingMode:e.scalingMode,isMirrored:e.isMirrored,target:e.target}}function $e(e){return{activeEffects:e}}function Ge(e){return{raisedHandOrderPosition:e.order}}!function(){class e extends Map{constructor(e,t){super(),this[B]={type_:2,parent_:t,scope_:t?t.scope_:le(),modified_:!1,finalized_:!1,copy_:void 0,assigned_:void 0,base_:e,draft_:this,isManual_:!1,revoked_:!1}}get size(){return X(this[B]).size}has(e){return X(this[B]).has(e)}set(e,i){const n=this[B];return r(n),X(n).has(e)&&X(n).get(e)===i||(t(n),Ee(n),n.assigned_.set(e,!0),n.copy_.set(e,i),n.assigned_.set(e,!0)),this}delete(e){if(!this.has(e))return!1;const i=this[B];return r(i),t(i),Ee(i),i.base_.has(e)?i.assigned_.set(e,!1):i.assigned_.delete(e),i.copy_.delete(e),!0}clear(){const e=this[B];r(e),X(e).size&&(t(e),Ee(e),e.assigned_=new Map,W(e.base_,(t=>{e.assigned_.set(t,!1)})),e.copy_.clear())}forEach(e,t){X(this[B]).forEach(((i,n,r)=>{e.call(t,this.get(n),n,this)}))}get(e){const i=this[B];r(i);const n=X(i).get(e);if(i.finalized_||!G(n))return n;if(n!==i.base_.get(e))return n;const a=be(n,i);return t(i),i.copy_.set(e,a),a}keys(){return X(this[B]).keys()}values(){const e=this.keys();return{[Symbol.iterator]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}}entries(){const e=this.keys();return{[Symbol.iterator]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const i=this.get(t.value);return{done:!1,value:[t.value,i]}}}}[Symbol.iterator](){return this.entries()}}function t(e){e.copy_||(e.assigned_=new Map,e.copy_=new Map(e.base_))}class i extends Set{constructor(e,t){super(),this[B]={type_:3,parent_:t,scope_:t?t.scope_:le(),modified_:!1,finalized_:!1,copy_:void 0,base_:e,draft_:this,drafts_:new Map,revoked_:!1,isManual_:!1}}get size(){return X(this[B]).size}has(e){const t=this[B];return r(t),t.copy_?!!t.copy_.has(e)||!(!t.drafts_.has(e)||!t.copy_.has(t.drafts_.get(e))):t.base_.has(e)}add(e){const t=this[B];return r(t),this.has(e)||(n(t),Ee(t),t.copy_.add(e)),this}delete(e){if(!this.has(e))return!1;const t=this[B];return r(t),n(t),Ee(t),t.copy_.delete(e)||!!t.drafts_.has(e)&&t.copy_.delete(t.drafts_.get(e))}clear(){const e=this[B];r(e),X(e).size&&(n(e),Ee(e),e.copy_.clear())}values(){const e=this[B];return r(e),n(e),e.copy_.values()}entries(){const e=this[B];return r(e),n(e),e.copy_.entries()}keys(){return this.values()}[Symbol.iterator](){return this.values()}forEach(e,t){const i=this.values();let n=i.next();for(;!n.done;)e.call(t,n.value,n.value,this),n=i.next()}}function n(e){e.copy_||(e.copy_=new Set,e.base_.forEach((t=>{if(G(t)){const i=be(t,e);e.drafts_.set(t,i),e.copy_.add(i)}else e.copy_.add(t)})))}function r(e){e.revoked_&&V(3,JSON.stringify(X(e)))}oe("MapSet",{proxyMap_:function(t,i){return new e(t,i)},proxySet_:function(e,t){return new i(e,t)}})}(),function(){const e="replace",t="add",i="remove";function n(e){if(!G(e))return e;if(Array.isArray(e))return e.map(n);if(Q(e))return new Map(Array.from(e.entries()).map((([e,t])=>[e,n(t)])));if(Z(e))return new Set(Array.from(e).map(n));const t=Object.create(H(e));for(const i in e)t[i]=n(e[i]);return K(e,U)&&(t[U]=e[U]),t}function r(e){return $(e)?n(e):e}oe("Patches",{applyPatches_:function(r,a){return a.forEach((a=>{const{path:s,op:o}=a;let l=r;for(let e=0;e<s.length-1;e++){const t=q(l);let i=s[e];"string"!=typeof i&&"number"!=typeof i&&(i=""+i),0!==t&&1!==t||"__proto__"!==i&&"constructor"!==i||V(19),"function"==typeof l&&"prototype"===i&&V(19),l=J(l,i),"object"!=typeof l&&V(18,s.join("/"))}const c=q(l),d=n(a.value),u=s[s.length-1];switch(o){case e:switch(c){case 2:return l.set(u,d);case 3:V(16);default:return l[u]=d}case t:switch(c){case 1:return"-"===u?l.push(d):l.splice(u,0,d);case 2:return l.set(u,d);case 3:return l.add(d);default:return l[u]=d}case i:switch(c){case 1:return l.splice(u,1);case 2:return l.delete(u);case 3:return l.delete(a.value);default:return delete l[u]}default:V(17)}})),r},generatePatches_:function(n,a,s,o){switch(n.type_){case 0:case 2:return function(n,a,s,o){const{base_:l,copy_:c}=n;W(n.assigned_,((n,d)=>{const u=J(l,n),h=J(c,n),p=d?K(l,n)?e:t:i;if(u===h&&p===e)return;const g=a.concat(n);s.push(p===i?{op:p,path:g}:{op:p,path:g,value:h}),o.push(p===t?{op:i,path:g}:p===i?{op:t,path:g,value:r(u)}:{op:e,path:g,value:r(u)})}))}(n,a,s,o);case 1:return function(n,a,s,o){let{base_:l,assigned_:c}=n,d=n.copy_;d.length<l.length&&([l,d]=[d,l],[s,o]=[o,s]);for(let t=0;t<l.length;t++)if(c[t]&&d[t]!==l[t]){const i=a.concat([t]);s.push({op:e,path:i,value:r(d[t])}),o.push({op:e,path:i,value:r(l[t])})}for(let e=l.length;e<d.length;e++){const i=a.concat([e]);s.push({op:t,path:i,value:r(d[e])})}for(let e=d.length-1;l.length<=e;--e){const t=a.concat([e]);o.push({op:i,path:t})}}(n,a,s,o);case 3:return function(e,n,r,a){let{base_:s,copy_:o}=e,l=0;s.forEach((e=>{if(!o.has(e)){const s=n.concat([l]);r.push({op:i,path:s,value:e}),a.unshift({op:t,path:s,value:e})}l++})),l=0,o.forEach((e=>{if(!s.has(e)){const s=n.concat([l]);r.push({op:t,path:s,value:e}),a.unshift({op:i,path:s,value:e})}l++}))}(n,a,s,o)}},generateReplacementPatches_:function(t,i,n,r){n.push({op:e,path:[],value:i===F?void 0:i}),r.push({op:e,path:[],value:t})}})}();class je{constructor(e,t=50,i){this._callIdHistory=new Oe,this._timeOutId={},this.teeErrorToState=(e,t)=>{const i=ze(t,e);this.setLatestError(t,i)},this._logger=(0,u.createClientLogger)("communication-react:calling-context"),this._state={calls:{},callsEnded:{},incomingCalls:{},incomingCallsEnded:{},deviceManager:{isSpeakerSelectionAvailable:!1,cameras:[],microphones:[],speakers:[],unparentedViews:[]},callAgent:void 0,userId:e,environmentInfo:void 0,alternateCallerId:i,latestErrors:{}},this._emitter=new(x()),this._emitter.setMaxListeners(t),this._atomicId=0}getState(){return this._state}modifyState(e){const t=this._state;this._state=Re(this._state,e,(e=>{"verbose"===(0,u.getLogLevel)()&&this._logger.info(`State change: ${Ae(e)}`)})),this._state!==t&&this._emitter.emit("stateChanged",this._state)}onStateChange(e){this._emitter.on("stateChanged",e)}offStateChange(e){this._emitter.off("stateChanged",e)}clearCallRelatedState(){this.modifyState((e=>{e.calls={},e.incomingCalls={},e.callsEnded={},e.incomingCallsEnded={}}))}setCallAgent(e){this.modifyState((t=>{t.callAgent=e}))}setCall(e){this.modifyState((t=>{const i=this._callIdHistory.latestCallId(e.id),n=t.calls[i];n?(n.callerInfo=e.callerInfo,n.state=e.state,n.callEndReason=e.callEndReason,n.direction=e.direction,n.isMuted=e.isMuted,n.isScreenSharingOn=e.isScreenSharingOn,n.localVideoStreams=e.localVideoStreams,n.remoteParticipants=e.remoteParticipants,n.transcription.isTranscriptionActive=e.transcription.isTranscriptionActive,n.optimalVideoCount.maxRemoteVideoStreams=e.optimalVideoCount.maxRemoteVideoStreams,n.recording.isRecordingActive=e.recording.isRecordingActive,n.raiseHand.raisedHands=e.raiseHand.raisedHands,n.pptLive.isActive=e.pptLive.isActive,n.raiseHand.localParticipantRaisedHand=e.raiseHand.localParticipantRaisedHand,n.role=e.role,n.totalParticipantCount=e.totalParticipantCount,n.captionsFeature.currentSpokenLanguage=e.captionsFeature.currentSpokenLanguage,n.captionsFeature.currentCaptionLanguage=e.captionsFeature.currentCaptionLanguage):t.calls[i]=e}))}removeCall(e){this.modifyState((t=>{delete t.calls[this._callIdHistory.latestCallId(e)]}))}setCallEnded(e,t){const i=this._callIdHistory.latestCallId(e);this.modifyState((e=>{const n=e.calls[i];if(n){for(n.endTime=new Date,n.callEndReason=t,delete e.calls[i];Object.keys(e.callsEnded).length>=10;)delete e.callsEnded[We(e.callsEnded)];e.callsEnded[i]=n}}))}setCallState(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.state=t)}))}setCallId(e,t){this._callIdHistory.updateCallIdHistory(e,t),this.modifyState((i=>{const n=i.calls[t];n&&(n.id=e,delete i.calls[t],i.calls[e]=n)}))}setEnvironmentInfo(e){this.modifyState((t=>{t.environmentInfo=e}))}setCallIsScreenSharingOn(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.isScreenSharingOn=t)}))}setCallRemoteParticipants(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(i.forEach((e=>{delete r.remoteParticipants[e]})),t.forEach((e=>{r.remoteParticipants[_(e.identifier)]=e})),r.contentSharingRemoteParticipant||(r.contentSharingRemoteParticipant=_(t[0].identifier)))}))}setCallRemoteParticipantsEnded(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(i.forEach((e=>{delete r.remoteParticipantsEnded[e]})),t.forEach((e=>{r.remoteParticipantsEnded[_(e.identifier)]=e})))}))}setCallLocalVideoStream(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){for(const e of i){const t=r.localVideoStreams.findIndex((t=>t.mediaStreamType===e.mediaStreamType));t>-1&&r.localVideoStreams.splice(t,1)}for(const e of t){const t=r.localVideoStreams.findIndex((t=>t.mediaStreamType===e.mediaStreamType));t>-1?r.localVideoStreams[t]=e:r.localVideoStreams.push(e)}}}))}setCallLocalVideoStreamVideoEffects(e,t){this.modifyState((i=>{var n;const r=i.calls[this._callIdHistory.latestCallId(e)];if(r){const e=null===(n=r.localVideoStreams)||void 0===n?void 0:n.find((e=>"Video"===e.mediaStreamType));e&&(e.videoEffects=t)}}))}setCallIsMicrophoneMuted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.isMuted=t)}))}setRole(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.role=t)}))}setTotalParticipantCount(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.totalParticipantCount=t)}))}setCallDominantSpeakers(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.dominantSpeakers=t)}))}setCallRecordingActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.recording.isRecordingActive=t)}))}setCallRecordingInfos(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.recording.activeRecordings=t,r.recording.lastStoppedRecording=i)}))}setCallLocalRecordingActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.localRecording.isLocalRecordingActive=t)}))}setCallLocalRecordingInfos(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.localRecording.activeLocalRecordings=t,r.localRecording.lastStoppedLocalRecording=i)}))}setCallPPTLiveActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.pptLive.isActive=t)}))}setCallParticipantPPTLive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)],r=n.contentSharingRemoteParticipant;if(n&&r){const e=n.remoteParticipants[r];e&&(e.contentSharingStream=t)}}))}setCallRaisedHands(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){n.raiseHand.raisedHands=t.map((e=>Ge(e)));const e=t.find((e=>_(e.identifier)===_(this._state.userId)));n.raiseHand.localParticipantRaisedHand=e?Ge(e):void 0}}))}setParticipantIsRaisedHand(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.raisedHand=i?Ge(i):i)}}))}setReceivedReactionFromParticipant(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(!r)return;clearTimeout(this._timeOutId[t]);const a=r.remoteParticipants[t],s=i?{reactionMessage:i,receivedOn:new Date}:void 0;t===_(this._state.userId)?r.localParticipantReaction=s:a.reactionState=s,i&&(this._timeOutId[t]=setTimeout((()=>{!function(e,t,i){e.setReceivedReactionFromParticipant(t,i,null)}(this,e,t)}),4133))}))}setCallTranscriptionActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.transcription.isTranscriptionActive=t)}))}setCapabilities(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.capabilitiesFeature={capabilities:t,latestCapabilitiesChangeInfo:i})}))}setSpotlight(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];r&&(r.spotlight=Object.assign(Object.assign({},r.spotlight),{spotlightedParticipants:t,maxParticipantsToSpotlight:i}))}))}setParticipantSpotlighted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e=n.remoteParticipants[_(t.identifier)];e?e.spotlight={spotlightedOrderPosition:t.order}:n.spotlight&&_(i.userId)===_(t.identifier)&&(n.spotlight.localParticipantSpotlight={spotlightedOrderPosition:t.order})}}))}setParticipantNotSpotlighted(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e=n.remoteParticipants[_(t.identifier)];e?e.spotlight=void 0:n.spotlight&&_(i.userId)===_(t.identifier)&&(n.spotlight.localParticipantSpotlight=void 0)}}))}setCallScreenShareParticipant(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.screenShareRemoteParticipant=t)}))}setLocalVideoStreamRendererView(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.localVideoStreams.find((e=>e.mediaStreamType===t));e&&(e.view=i)}}))}setParticipantState(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.state=i)}}))}setParticipantIsMuted(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.isMuted=i)}}))}setOptimalVideoCount(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.optimalVideoCount.maxRemoteVideoStreams=t)}))}setParticipantRole(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.role=i)}}))}setParticipantDisplayName(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.displayName=i)}}))}setParticipantIsSpeaking(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];e&&(e.isSpeaking=i)}}))}setParticipantVideoStream(e,t,i){this.modifyState((n=>{const r=n.calls[this._callIdHistory.latestCallId(e)];if(r){const e=r.remoteParticipants[t];if(e){const t=e.videoStreams[i.id];t?(t.isAvailable=i.isAvailable,t.isReceiving=i.isReceiving,t.mediaStreamType=i.mediaStreamType):e.videoStreams[i.id]=i}}}))}setRemoteVideoStreamIsAvailable(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.isAvailable=n)}}}))}setRemoteVideoStreamIsReceiving(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.isReceiving=n)}}}))}setRemoteVideoStreamSize(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.streamSize=n)}}}))}setRemoteVideoStreams(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){for(const t of n)delete e.videoStreams[t];for(const t of i){const i=e.videoStreams[t.id];i?(i.mediaStreamType=t.mediaStreamType,i.isAvailable=t.isAvailable,i.isReceiving=t.isReceiving):e.videoStreams[t.id]=t}}}}))}setRemoteVideoStreamRendererView(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&(t.view=n)}}}))}setRemoteVideoStreamViewScalingMode(e,t,i,n){this.modifyState((r=>{const a=r.calls[this._callIdHistory.latestCallId(e)];if(a){const e=a.remoteParticipants[t];if(e){const t=e.videoStreams[i];t&&t.view&&(t.view.scalingMode=n)}}}))}setIncomingCall(e){this.modifyState((t=>{const i=t.incomingCalls[e.id];i?i.callerInfo=e.callerInfo:t.incomingCalls[e.id]=e}))}removeIncomingCall(e){this.modifyState((t=>{delete t.incomingCalls[e]}))}setIncomingCallEnded(e,t){this.modifyState((i=>{const n=i.incomingCalls[e];if(n){for(n.endTime=new Date,n.callEndReason=t,delete i.incomingCalls[e];Object.keys(i.incomingCallsEnded).length>=10;)delete i.incomingCallsEnded[We(i.incomingCallsEnded)];i.incomingCallsEnded[e]=n}}))}setDeviceManagerIsSpeakerSelectionAvailable(e){this.modifyState((t=>{t.deviceManager.isSpeakerSelectionAvailable=e}))}setDeviceManagerSelectedMicrophone(e){this.modifyState((t=>{t.deviceManager.selectedMicrophone=e}))}setDeviceManagerSelectedSpeaker(e){this.modifyState((t=>{t.deviceManager.selectedSpeaker=e}))}setDeviceManagerSelectedCamera(e){this.modifyState((t=>{t.deviceManager.selectedCamera=e}))}setDeviceManagerCameras(e){this.modifyState((t=>{e.length>0&&!e.some((e=>{var i;return e.id===(null===(i=t.deviceManager.selectedCamera)||void 0===i?void 0:i.id)}))&&(t.deviceManager.selectedCamera=e[0]),t.deviceManager.cameras=e}))}setDeviceManagerMicrophones(e){this.modifyState((t=>{t.deviceManager.microphones=e}))}setDeviceManagerSpeakers(e){this.modifyState((t=>{t.deviceManager.speakers=e}))}setDeviceManagerDeviceAccess(e){this.modifyState((t=>{t.deviceManager.deviceAccess=e}))}setDeviceManagerUnparentedView(e,t){this.modifyState((i=>{i.deviceManager.unparentedViews.push({source:e.source,mediaStreamType:e.mediaStreamType,view:t})}))}deleteDeviceManagerUnparentedView(e){this.modifyState((t=>{const i=t.deviceManager.unparentedViews.findIndex((t=>t.mediaStreamType===e.mediaStreamType));-1!==i&&t.deviceManager.unparentedViews.splice(i,1)}))}setDeviceManagerUnparentedViewVideoEffects(e,t){this.modifyState((i=>{const n=i.deviceManager.unparentedViews.findIndex((t=>t.mediaStreamType===e.mediaStreamType));-1!==n&&(i.deviceManager.unparentedViews[n].videoEffects=t)}))}getAndIncrementAtomicId(){const e=this._atomicId;return this._atomicId++,e}processNewCaption(e,t){t.timestamp=new Date,0===e.length||"Final"===e[e.length-1].resultType?e.push(t):_(e[e.length-1].speaker.identifier)===_(t.speaker.identifier)?e[e.length-1]=t:Date.now()-e[e.length-1].timestamp.getTime()>5e3&&(e[e.length-1].resultType="Final",e.push(t)),e.length>50&&e.shift()}addTeamsCaption(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];if(n){const e=n.captionsFeature.currentCaptionLanguage;t.captionLanguage.toUpperCase()!==e.toUpperCase()&&""!==e&&void 0!==e||this.processNewCaption(n.captionsFeature.captions,function(e){return Object.assign({},e)}(t))}}))}addCaption(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&this.processNewCaption(n.captionsFeature.captions,function(e){return Object.assign({captionText:e.spokenText},e)}(t))}))}setCaptionsKind(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.captionsKind=t)}))}clearCaptions(e){this.modifyState((t=>{const i=t.calls[this._callIdHistory.latestCallId(e)];i&&(i.captionsFeature.captions=[])}))}setIsCaptionActive(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.isCaptionsFeatureActive=t)}))}setStartCaptionsInProgress(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.startCaptionsInProgress=t)}))}setSelectedSpokenLanguage(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.currentSpokenLanguage=t)}))}setSelectedCaptionLanguage(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.currentCaptionLanguage=t)}))}setAvailableCaptionLanguages(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.supportedCaptionLanguages=t)}))}setAvailableSpokenLanguages(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.captionsFeature.supportedSpokenLanguages=t)}))}setAcceptedTransfer(e,t){this.modifyState((i=>{const n=i.calls[this._callIdHistory.latestCallId(e)];n&&(n.transfer.acceptedTransfers[t.callId]=t)}))}withAsyncErrorTeedToState(e,t){return(...i)=>{return n=this,r=void 0,s=function*(){try{return yield e(...i)}catch(e){const i=ze(t,e);throw this.setLatestError(t,i),i}},new((a=void 0)||(a=Promise))((function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof a?n:new a((function(e){e(n)}))).then(i,o)}l((s=s.apply(n,r||[])).next())}));var n,r,a,s}}withErrorTeedToState(e,t){return(...i)=>{try{return ke.info(`Calling stateful client target function called: ${t}`),e(...i)}catch(e){const i=ze(t,e);throw this.setLatestError(t,i),i}}}setLatestError(e,t){this.modifyState((i=>{i.latestErrors[e]=t}))}}const ze=(e,t)=>t instanceof Error?new Me(e,t):new Me(e,new Error(t)),We=e=>{var t,i,n,r;const a=Object.entries(e);let[s,o]=a[0];if(void 0===o.endTime)return s;for(const[e,l]of a.slice(1)){if(void 0===l.endTime)return e;(null!==(i=null===(t=l.endTime)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)<(null!==(r=null===(n=o.endTime)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&([s,o]=[e,l])}return s};class qe{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.on("CaptionsReceived",this.onCaptionsReceived),this._captions.on("CaptionLanguageChanged",this.isCaptionLanguageChanged),this._captions.on("SpokenLanguageChanged",this.isSpokenLanguageChanged)},this.unsubscribe=()=>{this._captions.off("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.off("CaptionsReceived",this.onCaptionsReceived),this._captions.off("CaptionLanguageChanged",this.isCaptionLanguageChanged),this._captions.off("SpokenLanguageChanged",this.isSpokenLanguageChanged)},this.onCaptionsReceived=e=>{this._context.addTeamsCaption(this._callIdRef.callId,e)},this.isCaptionsActiveChanged=()=>{this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive)},this.isCaptionLanguageChanged=()=>{this._context.setSelectedCaptionLanguage(this._callIdRef.callId,this._captions.activeCaptionLanguage)},this.isSpokenLanguageChanged=()=>{this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage)},this._callIdRef=e,this._context=t,this._captions=i,this._captions.isCaptionsFeatureActive&&this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive),this._context.setAvailableSpokenLanguages(this._callIdRef.callId,this._captions.supportedSpokenLanguages),"supportedCaptionLanguages"in this._captions&&this._context.setAvailableCaptionLanguages(this._callIdRef.callId,this._captions.supportedCaptionLanguages),this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage),this._context.setSelectedCaptionLanguage(this._callIdRef.callId,this._captions.activeCaptionLanguage),this.subscribe()}}class Ke{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.on("SpokenLanguageChanged",this.isSpokenLanguageChanged),this._captions.on("CaptionsReceived",this.onCaptionsReceived)},this.unsubscribe=()=>{this._captions.off("CaptionsActiveChanged",this.isCaptionsActiveChanged),this._captions.off("SpokenLanguageChanged",this.isSpokenLanguageChanged),this._captions.off("CaptionsReceived",this.onCaptionsReceived)},this.onCaptionsReceived=e=>{this._context.addCaption(this._callIdRef.callId,e)},this.isCaptionsActiveChanged=()=>{this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive)},this.isSpokenLanguageChanged=()=>{this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage)},this._callIdRef=e,this._context=t,this._captions=i,this._captions.isCaptionsFeatureActive&&this._context.setIsCaptionActive(this._callIdRef.callId,this._captions.isCaptionsFeatureActive),this._context.setAvailableSpokenLanguages(this._callIdRef.callId,this._captions.supportedSpokenLanguages),this._context.setSelectedSpokenLanguage(this._callIdRef.callId,this._captions.activeSpokenLanguage),this.subscribe()}}class Je{constructor(e,t,i){this.subscribe=()=>{this._captions.on("CaptionsKindChanged",this.isCaptionsKindChanged)},this.unsubscribe=()=>{var e,t;this._captions.off("CaptionsKindChanged",this.isCaptionsKindChanged),null===(e=this._TeamsCaptionsSubscriber)||void 0===e||e.unsubscribe(),null===(t=this._CaptionsSubscriber)||void 0===t||t.unsubscribe()},this.isCaptionsKindChanged=()=>{var e;this._context.setCaptionsKind(this._callIdRef.callId,this._captions.captions.kind),"TeamsCaptions"===this._captions.captions.kind&&(null===(e=this._CaptionsSubscriber)||void 0===e||e.unsubscribe(),this._TeamsCaptionsSubscriber=new qe(this._callIdRef,this._context,this._captions.captions))},this._callIdRef=e,this._context=t,this._captions=i,this._context.setCaptionsKind(this._callIdRef.callId,this._captions.captions.kind),"TeamsCaptions"===this._captions.captions.kind?this._TeamsCaptionsSubscriber=new qe(this._callIdRef,this._context,this._captions.captions):this._CaptionsSubscriber=new Ke(this._callIdRef,this._context,this._captions.captions),this.subscribe()}}class Ye{constructor(e){this.subscribe=()=>{this._localVideoStreamEffectsAPI.on("effectsStarted",this.effectsStarted),this._localVideoStreamEffectsAPI.on("effectsStopped",this.effectsStopped),this._localVideoStreamEffectsAPI.on("effectsError",this.effectsError)},this.unsubscribe=()=>{this._localVideoStreamEffectsAPI.off("effectsStarted",this.effectsStarted),this._localVideoStreamEffectsAPI.off("effectsStopped",this.effectsStopped),this._localVideoStreamEffectsAPI.off("effectsError",this.effectsError)},this.effectsStarted=()=>{this.updateStatefulVideoEffects()},this.effectsStopped=()=>{this.updateStatefulVideoEffects()},this.effectsError=e=>{this.updateStatefulVideoEffects(),this._context.teeErrorToState(new Error(e.message),"VideoEffectsFeature.startEffects")},this.updateStatefulVideoEffects=()=>{const e=$e(this._localVideoStreamEffectsAPI.activeEffects);"unparented"===this._parent?this._context.setDeviceManagerUnparentedViewVideoEffects(this._localVideoStream,e):this._context.setCallLocalVideoStreamVideoEffects(this._parent.callId,e)},this._parent=e.parent,this._context=e.context,this._localVideoStream=e.localVideoStream,this._localVideoStreamEffectsAPI=e.localVideoStreamEffectsAPI,this.subscribe()}}class Qe{constructor(e,t,i,n){this.subscribe=()=>{this._remoteVideoStream.on("isAvailableChanged",this.isAvailableChanged),this._remoteVideoStream.on("isReceivingChanged",this.isReceivingChanged),this._remoteVideoStream.on("sizeChanged",this.isSizeChanged),this.checkAndUpdateScreenShareState()},this.unsubscribe=()=>{this._remoteVideoStream.off("isAvailableChanged",this.isAvailableChanged),this._remoteVideoStream.off("isReceivingChanged",this.isReceivingChanged),this._remoteVideoStream.off("sizeChanged",this.isSizeChanged)},this.includesActiveScreenShareStream=e=>{for(const t of Object.values(e))if("ScreenSharing"===t.mediaStreamType&&t.isAvailable)return!0;return!1},this.checkAndUpdateScreenShareState=()=>{var e,t,i;if("ScreenSharing"!==this._remoteVideoStream.mediaStreamType)return;if(this._remoteVideoStream.isAvailable)return void this._context.setCallScreenShareParticipant(this._callIdRef.callId,this._participantKey);const n=null===(e=this._context.getState().calls[this._callIdRef.callId])||void 0===e?void 0:e.screenShareRemoteParticipant;if(!n||n===this._participantKey)return void this._context.setCallScreenShareParticipant(this._callIdRef.callId,void 0);const r=null===(i=null===(t=this._context.getState().calls[this._callIdRef.callId])||void 0===t?void 0:t.remoteParticipants[n])||void 0===i?void 0:i.videoStreams;r&&this.includesActiveScreenShareStream(r)||this._context.setCallScreenShareParticipant(this._callIdRef.callId,void 0)},this.isAvailableChanged=()=>{this._context.setRemoteVideoStreamIsAvailable(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.isAvailable),this.checkAndUpdateScreenShareState()},this.isReceivingChanged=()=>{this._context.setRemoteVideoStreamIsReceiving(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.isReceiving)},this.isSizeChanged=()=>{var e,t,i,n,r,a,s;if(0===(null===(e=this._remoteVideoStream)||void 0===e?void 0:e.size.width)&&0===(null===(t=this._remoteVideoStream)||void 0===t?void 0:t.size.height))return;const o=null===(r=null===(n=null===(i=this._context.getState().calls[this._callIdRef.callId])||void 0===i?void 0:i.remoteParticipants[this._participantKey])||void 0===n?void 0:n.videoStreams[this._remoteVideoStream.id])||void 0===r?void 0:r.streamSize,l=o?o.width/o.height:void 0,c=(null===(a=this._remoteVideoStream)||void 0===a?void 0:a.size.width)/(null===(s=this._remoteVideoStream)||void 0===s?void 0:s.size.height);o&&l===c||this._context.setRemoteVideoStreamSize(this._callIdRef.callId,this._participantKey,this._remoteVideoStream.id,this._remoteVideoStream.size)},this._callIdRef=e,this._participantKey=t,this._remoteVideoStream=i,this._context=n,this.subscribe()}}const Ze=(e,t)=>{e[t.level](Ae(t))};function Xe(e,t,i){"disposeViewLocal"===t.streamEventType||"disposeViewRemote"===t.streamEventType||"disposeViewUnparented"===t.streamEventType?function(e,t){switch(e){case De.DISPOSE_STREAM_INVALID_PARAMS:return void Ze(ke,{name:De.DISPOSE_STREAM_INVALID_PARAMS,level:"warning",message:"Dispose View invalid combination of parameters.",data:{streamType:t.streamType}});case De.START_DISPOSE_STREAM:return void Ze(ke,{name:De.START_DISPOSE_STREAM,level:"info",message:"Start disposing stream.",data:t});case De.DISPOSE_INFO_NOT_FOUND:return void Ze(ke,{name:De.DISPOSE_INFO_NOT_FOUND,level:"error",message:"Cannot find render info when disposing stream.",data:t});case De.STREAM_STOPPING:return void Ze(ke,{name:De.STREAM_STOPPING,level:"info",message:"Stream is currently marked as stopping, will continue if is local preview",data:t});case De.DISPOSING_RENDERER:return void Ze(ke,{name:De.DISPOSING_RENDERER,level:"info",message:"Disposing view renderer.",data:t});case De.RENDERER_NOT_FOUND:return void Ze(ke,{name:De.RENDERER_NOT_FOUND,level:"error",message:"Cannot find renderer when disposing stream.",data:t});case De.STREAM_ALREADY_DISPOSED:Ze(ke,{name:De.STREAM_ALREADY_DISPOSED,level:"info",message:"Stream is already disposed.",data:t})}}(e,t):"createViewLocal"!==t.streamEventType&&"createViewRemote"!==t.streamEventType||function(e,t,i){switch(e){case De.CREATE_STREAM_INVALID_PARAMS:return void Ze(ke,{name:De.CREATE_STREAM_INVALID_PARAMS,level:"warning",message:"Create View invalid combination of parameters.",data:{streamType:t.streamType}});case De.START_STREAM_RENDERING:return void Ze(ke,{name:De.START_STREAM_RENDERING,level:"info",message:"Start creating view for local video.",data:t});case De.STREAM_NOT_FOUND:return void Ze(ke,{name:De.STREAM_NOT_FOUND,level:"error",message:"Stream not found in state.",data:{callId:t.callId}});case De.STREAM_ALREADY_RENDERED:return void Ze(ke,{name:De.STREAM_ALREADY_RENDERED,level:"warning",message:"Stream is already rendered.",data:t});case De.STREAM_RENDERING:return void Ze(ke,{name:De.STREAM_RENDERING,level:"warning",message:"Stream is rendering.",data:t});case De.STREAM_STOPPING:return void Ze(ke,{name:De.STREAM_STOPPING,level:"warning",message:'Stream was marked as stopping by dispose view. Resetting state to "Rendering".',data:t});case De.CREATE_STREAM_FAIL:return void Ze(ke,{name:De.CREATE_STREAM_FAIL,level:"error",message:"Failed to create view.",data:{error:i,streamType:t.streamType,callId:t.callId}});case De.RENDER_INFO_NOT_FOUND:return void Ze(ke,{name:De.RENDER_INFO_NOT_FOUND,level:"error",message:"Cannot find render info after create the view. ",data:t});case De.CREATED_STREAM_STOPPING:return void Ze(ke,{name:De.CREATED_STREAM_STOPPING,level:"warning",message:"Render info status is stopping, dispose renderer.",data:t});case De.VIEW_RENDER_SUCCEED:return void Ze(ke,{name:De.VIEW_RENDER_SUCCEED,level:"info",message:"Successfully render the view.",data:t});case De.CREATING_VIEW:Ze(ke,{name:De.CREATING_VIEW,level:"info",message:"Start creating view for remote video.",data:t})}}(e,t,i)}var et=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};function tt(e,t,i,n,r){const a=r.mediaStreamType;if(i)!function(e,t,i,n,r){let a;a=r?"disposeViewRemote":i?"disposeViewLocal":"disposeViewUnparented";const s=n.mediaStreamType,o=n.mediaStreamType,l=n.id,c="disposeViewRemote"===a&&r?"string"==typeof r?r:_(r):void 0,d={callId:i,participantKey:c,streamId:null!=l?l:o,streamType:s};Xe(De.START_DISPOSE_STREAM,d),"disposeViewRemote"===a&&c&&e.setRemoteVideoStreamRendererView(i,c,l,void 0);const u="disposeViewRemote"===a&&c?t.getRemoteRenderInfoForParticipant(i,c,l):t.getLocalRenderInfo(i,o);if(u)if("NotRendered"!==u.status){if("Stopping"!==u.status)return"Rendering"===u.status?(Xe(De.STREAM_STOPPING,d),void("disposeViewRemote"===a&&c?t.setRemoteRenderInfo(i,c,l,u.stream,"Stopping",void 0):t.setLocalRenderInfo(i,o,u.stream,"Stopping",u.renderer))):void(u.renderer?(Xe(De.DISPOSING_RENDERER,d),u.renderer.dispose(),"disposeViewRemote"===a&&c?t.setRemoteRenderInfo(i,c,l,u.stream,"NotRendered",void 0):"disposeViewLocal"===a&&(t.setLocalRenderInfo(i,o,u.stream,"NotRendered",void 0),e.setLocalVideoStreamRendererView(i,o,void 0))):Xe(De.RENDERER_NOT_FOUND,d));Xe(De.STREAM_STOPPING,d)}else Xe(De.STREAM_ALREADY_DISPOSED,d);else Xe(De.DISPOSE_INFO_NOT_FOUND,d)}(e,t,i,r,n);else{if("id"in r||i)return void Xe(De.DISPOSE_STREAM_INVALID_PARAMS,{streamType:a});e.withErrorTeedToState((()=>function(e,t,i){const n={streamType:i.mediaStreamType,streamEventType:"disposeViewUnparented"};Xe(De.START_DISPOSE_STREAM,n),e.deleteDeviceManagerUnparentedView(i);const r=t.getUnparentedRenderInfo(i);r?("Rendering"===r.status?(Xe(De.STREAM_STOPPING,n),t.setUnparentedRenderInfo(i,r.stream,"Stopping",void 0)):t.deleteUnparentedRenderInfo(i),r.renderer?(Xe(De.DISPOSING_RENDERER,n),r.renderer.dispose()):Xe(De.RENDERER_NOT_FOUND,n)):Xe(De.DISPOSE_INFO_NOT_FOUND,n)}(e,t,r)),"Call.stopVideo")()}}function it(e,t,i){const n=t.getRemoteRenderInfoForCall(i);if(n)for(const[r,a]of n.entries())for(const[n,s]of a.entries())tt(e,t,i,r,Be(s.stream));const r=t.getLocalRenderInfosForCall(i);if(r)for(const n of r.values())n&&n.renderer&&tt(e,t,i,void 0,Ue(n.stream))}class nt{constructor(e,t,i,n){this.subscribe=()=>{if(this._participant.on("stateChanged",this.stateChanged),this._participant.on("isMutedChanged",this.isMutedChanged),this._participant.on("displayNameChanged",this.displayNameChanged),this._participant.on("isSpeakingChanged",this.isSpeakingChanged),this._participant.on("videoStreamsUpdated",this.videoStreamsUpdated),this._participant.on("roleChanged",this.roleChanged),this._participant.videoStreams.length>0){for(const e of this._participant.videoStreams)this._internalContext.setRemoteRenderInfo(this._callIdRef.callId,this._participantKey,e.id,e,"NotRendered",void 0),this.addRemoteVideoStreamSubscriber(e);this._context.setRemoteVideoStreams(this._callIdRef.callId,this._participantKey,this._participant.videoStreams.map(Be),[])}},this.unsubscribe=()=>{if(this._participant.off("stateChanged",this.stateChanged),this._participant.off("isMutedChanged",this.isMutedChanged),this._participant.off("displayNameChanged",this.displayNameChanged),this._participant.off("isSpeakingChanged",this.isSpeakingChanged),this._participant.off("videoStreamsUpdated",this.videoStreamsUpdated),this._participant.off("roleChanged",this.roleChanged),this._participant.videoStreams.length>0)for(const e of this._participant.videoStreams)tt(this._context,this._internalContext,this._callIdRef.callId,this._participantKey,Be(e)),this._internalContext.deleteRemoteRenderInfo(this._callIdRef.callId,this._participantKey,e.id)},this.addRemoteVideoStreamSubscriber=e=>{var t;null===(t=this._remoteVideoStreamSubscribers.get(e.id))||void 0===t||t.unsubscribe(),this._remoteVideoStreamSubscribers.set(e.id,new Qe(this._callIdRef,this._participantKey,e,this._context))},this.stateChanged=()=>{this._context.setParticipantState(this._callIdRef.callId,this._participantKey,this._participant.state)},this.isMutedChanged=()=>{this._context.setParticipantIsMuted(this._callIdRef.callId,this._participantKey,this._participant.isMuted)},this.roleChanged=()=>{this._context.setParticipantRole(this._callIdRef.callId,this._participantKey,this._participant.role)},this.displayNameChanged=()=>{this._context.setParticipantDisplayName(this._callIdRef.callId,this._participantKey,this._participant.displayName||"")},this.isSpeakingChanged=()=>{this._context.setParticipantIsSpeaking(this._callIdRef.callId,this._participantKey,this._participant.isSpeaking)},this.videoStreamsUpdated=e=>{var t;for(const i of e.removed)null===(t=this._remoteVideoStreamSubscribers.get(i.id))||void 0===t||t.unsubscribe(),tt(this._context,this._internalContext,this._callIdRef.callId,this._participantKey,Be(i)),this._internalContext.deleteRemoteRenderInfo(this._callIdRef.callId,this._participantKey,i.id);for(const t of e.added)this._internalContext.setRemoteRenderInfo(this._callIdRef.callId,this._participantKey,t.id,t,"NotRendered",void 0),this.addRemoteVideoStreamSubscriber(t);this._context.setRemoteVideoStreams(this._callIdRef.callId,this._participantKey,e.added.map(Be),e.removed.map((e=>e.id)))},this._callIdRef=e,this._participant=t,this._context=i,this._internalContext=n,this._participantKey=_(this._participant.identifier),this._remoteVideoStreamSubscribers=new Map,this.subscribe()}}class rt{constructor(e,t,i){this.subscribe=()=>{this._recording.on("isRecordingActiveChanged",this.isAvailableChanged),this._recording.on("recordingsUpdated",this.isRecordingsUpdated)},this.unsubscribe=()=>{this._recording.off("isRecordingActiveChanged",this.isAvailableChanged),this._recording.off("recordingsUpdated",this.isRecordingsUpdated)},this.isAvailableChanged=()=>{this._context.setCallRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive)},this.isRecordingsUpdated=e=>{this._context.setCallRecordingInfos(this._callIdRef.callId,this._recording.recordings,e.removed)},this._callIdRef=e,this._context=t,this._recording=i,this._recording.isRecordingActive&&(this._context.setCallRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive),this._context.setCallRecordingInfos(this._callIdRef.callId,this._recording.recordings,[])),this.subscribe()}}class at{constructor(e,t,i){this.subscribe=()=>{this._pptLive.on("isActiveChanged",this.isAvailableChanged)},this.unsubscribe=()=>{this._pptLive.off("isActiveChanged",this.isAvailableChanged)},this.isAvailableChanged=()=>{this._context.setCallPPTLiveActive(this._callIdRef.callId,this._pptLive.isActive),this.checkAndUpdatePPTLiveParticipant()},this.checkAndUpdatePPTLiveParticipant=()=>{return e=this,t=void 0,n=function*(){this._pptLive.isActive?(this._call.isScreenSharingOn&&(yield this._call.stopScreenSharing()),this._context.setCallParticipantPPTLive(this._callIdRef.callId,this._pptLive.target)):this._context.setCallParticipantPPTLive(this._callIdRef.callId,void 0)},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n},this._callIdRef=e,this._context=t,this._pptLive=i.feature(p.Features.PPTLive),this._call=i,this.subscribe()}}class st{constructor(e,t,i){this.subscribe=()=>{this._transcription.on("isTranscriptionActiveChanged",this.isTranscriptionActiveChanged)},this.unsubscribe=()=>{this._transcription.off("isTranscriptionActiveChanged",this.isTranscriptionActiveChanged)},this.isTranscriptionActiveChanged=()=>{this._context.setCallTranscriptionActive(this._callIdRef.callId,this._transcription.isTranscriptionActive)},this._callIdRef=e,this._context=t,this._transcription=i,this._transcription.isTranscriptionActive&&this._context.setCallTranscriptionActive(this._callIdRef.callId,this._transcription.isTranscriptionActive),this.subscribe()}}class ot{constructor(e,t,i){this.unsubscribe=()=>{this._diagnostics.network.off("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.off("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))},this._callIdRef=e,this._context=t,this._diagnostics=i,this.setInitialDiagnostics(),this.subscribe()}setInitialDiagnostics(){const e=this._diagnostics.network.getLatest(),t=this._diagnostics.media.getLatest();0===Object.entries(e).length&&0===Object.entries(t).length||this._context.modifyState((i=>{const n=i.calls[this._callIdRef.callId];void 0!==n&&(n.diagnostics={network:{latest:e},media:{latest:t}})}))}subscribe(){this._diagnostics.network.on("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.on("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))}networkDiagnosticsChanged(e){this._context.modifyState((t=>{var i;const n=t.calls[this._callIdRef.callId];if(void 0===n)return;const r=null===(i=n.diagnostics)||void 0===i?void 0:i.network.latest;r&&(r[e.diagnostic]=lt(e))}))}mediaDiagnosticsChanged(e){this._context.modifyState((t=>{var i;const n=t.calls[this._callIdRef.callId];if(void 0===n)return;const r=null===(i=n.diagnostics)||void 0===i?void 0:i.media.latest;r&&(r[e.diagnostic]=lt(e))}))}}const lt=e=>({value:e.value,valueType:e.valueType});class ct{constructor(e,t,i){this.subscribe=()=>{this._raiseHand.on("raisedHandEvent",this.raisedHand),this._raiseHand.on("loweredHandEvent",this.loweredHand)},this.unsubscribe=()=>{this._raiseHand.off("raisedHandEvent",this.raisedHand),this._raiseHand.off("loweredHandEvent",this.loweredHand)},this.raisedHand=()=>{this._context.setCallRaisedHands(this._callIdRef.callId,this._raiseHand.getRaisedHands());for(const e of this._raiseHand.getRaisedHands())this._context.setParticipantIsRaisedHand(this._callIdRef.callId,_(e.identifier),e)},this.loweredHand=e=>{this.raisedHand(),this._context.setParticipantIsRaisedHand(this._callIdRef.callId,_(e.identifier),void 0)},this._callIdRef=e,this._context=t,this._raiseHand=i,this.subscribe()}}class dt{constructor(e){this.subscribe=()=>{this._localOptimalVideoCountFeature.on("optimalVideoCountChanged",this.optimalVideoCountChanged)},this.unsubscribe=()=>{this._localOptimalVideoCountFeature.off("optimalVideoCountChanged",this.optimalVideoCountChanged)},this.optimalVideoCountChanged=()=>{this.updateOptimalVideoCountState({maxRemoteVideoStreams:this._localOptimalVideoCountFeature.optimalVideoCount})},this.updateOptimalVideoCountState=e=>{this._context.setOptimalVideoCount(this._callIdRef.callId,e.maxRemoteVideoStreams)},this._callIdRef=e.callIdRef,this._context=e.context,this._localOptimalVideoCountFeature=e.localOptimalVideoCountFeature,this.subscribe()}}class ut{constructor(e,t,i){this.subscribe=()=>{this._capabilitiesFeature.on("capabilitiesChanged",this.capabilitiesChanged)},this.unsubscribe=()=>{this._capabilitiesFeature.off("capabilitiesChanged",this.capabilitiesChanged)},this.capabilitiesChanged=e=>{this._context.setCapabilities(this._callIdRef.callId,this._capabilitiesFeature.capabilities,e)},this._callIdRef=e,this._context=t,this._capabilitiesFeature=i,this.subscribe()}}class ht{constructor(e,t,i){this.subscribe=()=>{this._reaction.on("reaction",this.onReactionEvent)},this.unsubscribe=()=>{this._reaction.off("reaction",this.onReactionEvent)},this.onReactionEvent=e=>{this._context.setReceivedReactionFromParticipant(this._callIdRef.callId,e.identifier,e.reactionMessage)},this._callIdRef=e,this._context=t,this._reaction=i,this.subscribe()}}class pt{constructor(e,t,i){this.subscribe=()=>{this._spotlightFeature.on("spotlightChanged",this.spotlightChanged)},this.unsubscribe=()=>{this._spotlightFeature.off("spotlightChanged",this.spotlightChanged)},this.spotlightChanged=e=>{this._context.setSpotlight(this._callIdRef.callId,this._spotlightFeature.getSpotlightedParticipants(),this._spotlightFeature.maxParticipantsToSpotlight);for(const t of e.added)this._context.setParticipantSpotlighted(this._callIdRef.callId,t);for(const t of e.removed)this._context.setParticipantNotSpotlighted(this._callIdRef.callId,t)},this._callIdRef=e,this._context=t,this._spotlightFeature=i,this.subscribe()}}class gt{constructor(e,t,i){this.subscribe=()=>{this._recording.on("isLocalRecordingActiveChanged",this.isAvailableChanged),this._recording.on("localRecordingsUpdated",this.isRecordingsUpdated)},this.unsubscribe=()=>{this._recording.off("isLocalRecordingActiveChanged",this.isAvailableChanged),this._recording.off("localRecordingsUpdated",this.isRecordingsUpdated)},this.isAvailableChanged=()=>{this._context.setCallLocalRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive)},this.isRecordingsUpdated=e=>{this._context.setCallLocalRecordingInfos(this._callIdRef.callId,this._recording.recordings,e.removed)},this._callIdRef=e,this._context=t,this._recording=i,this._recording.isRecordingActive&&(this._context.setCallLocalRecordingActive(this._callIdRef.callId,this._recording.isRecordingActive),this._context.setCallLocalRecordingInfos(this._callIdRef.callId,this._recording.recordings,[])),this.subscribe()}}class mt{constructor(e,t,i){this.subscribe=()=>{this._call.on("stateChanged",this.stateChanged),this._call.on("stateChanged",this.initCaptionSubscriber),this._call.on("stateChanged",this.initLocalRecordingNotificationSubscriber),this._call.on("idChanged",this.idChanged),this._call.on("isScreenSharingOnChanged",this.isScreenSharingOnChanged),this._call.on("remoteParticipantsUpdated",this.remoteParticipantsUpdated),this._call.on("localVideoStreamsUpdated",this.localVideoStreamsUpdated),this._call.on("isMutedChanged",this.isMuteChanged),this._call.on("roleChanged",this.callRoleChangedHandler),this._call.feature(p.Features.DominantSpeakers).on("dominantSpeakersChanged",this.dominantSpeakersChanged),this._call.on("totalParticipantCountChanged",this.totalParticipantCountChangedHandler);for(const e of this._call.localVideoStreams)this._internalContext.setLocalRenderInfo(this._callIdRef.callId,e.mediaStreamType,e,"NotRendered",void 0);this._call.remoteParticipants.length>0&&(this._call.remoteParticipants.forEach((e=>{this.addParticipantListener(e)})),this._context.setCallRemoteParticipants(this._callIdRef.callId,this._call.remoteParticipants.map(Ve),[]))},this.unsubscribe=()=>{var e,t,i,n;this._call.off("stateChanged",this.stateChanged),this._call.off("stateChanged",this.initCaptionSubscriber),this._call.off("stateChanged",this.initLocalRecordingNotificationSubscriber),this._call.off("idChanged",this.idChanged),this._call.off("isScreenSharingOnChanged",this.isScreenSharingOnChanged),this._call.off("remoteParticipantsUpdated",this.remoteParticipantsUpdated),this._call.off("localVideoStreamsUpdated",this.localVideoStreamsUpdated),this._call.off("isMutedChanged",this.isMuteChanged),this._call.off("roleChanged",this.callRoleChangedHandler),this._call.off("totalParticipantCountChanged",this.totalParticipantCountChangedHandler),this._participantSubscribers.forEach((e=>{e.unsubscribe()})),this._participantSubscribers.clear();for(const e of this._call.localVideoStreams){const t=e.mediaStreamType;tt(this._context,this._internalContext,this._callIdRef.callId,void 0,Ue(e)),this._internalContext.deleteLocalRenderInfo(this._callIdRef.callId,t)}this._diagnosticsSubscriber.unsubscribe(),this._recordingSubscriber.unsubscribe(),this._transcriptionSubscriber.unsubscribe(),null===(e=this._localRecordingSubscriber)||void 0===e||e.unsubscribe(),this._optimalVideoCountSubscriber.unsubscribe(),this._pptLiveSubscriber.unsubscribe(),null===(t=this._CaptionsFeatureSubscriber)||void 0===t||t.unsubscribe(),null===(i=this._raiseHandSubscriber)||void 0===i||i.unsubscribe(),this._capabilitiesSubscriber.unsubscribe(),null===(n=this._reactionSubscriber)||void 0===n||n.unsubscribe(),this._spotlightSubscriber.unsubscribe()},this.stateChanged=()=>{this._context.setCallState(this._callIdRef.callId,this._call.state)},this.initCaptionSubscriber=()=>{"Connected"!==this._call.state||this._CaptionsFeatureSubscriber||(this._CaptionsFeatureSubscriber=new Je(this._callIdRef,this._context,this._call.feature(p.Features.Captions)),this._call.off("stateChanged",this.initCaptionSubscriber))},this.initLocalRecordingNotificationSubscriber=()=>{"Connected"!==this._call.state||"TeamsCall"!==this._call.kind||this._localRecordingSubscriber||(this._localRecordingSubscriber=new gt(this._callIdRef,this._context,this._call.feature(p.Features.LocalRecording)),this._call.off("stateChanged",this.initLocalRecordingNotificationSubscriber))},this.idChanged=()=>{this._internalContext.setCallId(this._call.id,this._callIdRef.callId),this._context.setCallId(this._call.id,this._callIdRef.callId),this._callIdRef.callId=this._call.id},this.isScreenSharingOnChanged=()=>{this._context.setCallIsScreenSharingOn(this._callIdRef.callId,this._call.isScreenSharingOn)},this.isMuteChanged=()=>{this._context.setCallIsMicrophoneMuted(this._callIdRef.callId,this._call.isMuted)},this.callRoleChangedHandler=()=>{this._context.setRole(this._callIdRef.callId,this._call.role)},this.totalParticipantCountChangedHandler=()=>{this._context.setTotalParticipantCount(this._callIdRef.callId,this._call.totalParticipantCount)},this.remoteParticipantsUpdated=e=>{e.added.forEach((e=>{this.addParticipantListener(e)})),e.removed.forEach((e=>{this.removeParticipantListener(e)})),this._context.setCallRemoteParticipantsEnded(this._callIdRef.callId,e.removed.map(Ve),e.added.map((e=>_(e.identifier)))),this._context.setCallRemoteParticipants(this._callIdRef.callId,e.added.map(Ve),e.removed.map((e=>_(e.identifier))))},this.localVideoStreamsUpdated=e=>{var t,i;for(const i of e.added){const e=i.mediaStreamType;this._internalContext.setLocalRenderInfo(this._callIdRef.callId,e,i,"NotRendered",void 0),null===(t=this._localVideoStreamVideoEffectsSubscribers.get(e))||void 0===t||t.unsubscribe(),this._localVideoStreamVideoEffectsSubscribers.set(e,new Ye({parent:this._callIdRef,context:this._context,localVideoStream:i,localVideoStreamEffectsAPI:i.feature(p.Features.VideoEffects)}))}for(const t of e.removed){const e=t.mediaStreamType;null===(i=this._localVideoStreamVideoEffectsSubscribers.get(e))||void 0===i||i.unsubscribe(),tt(this._context,this._internalContext,this._callIdRef.callId,void 0,Ue(t)),this._internalContext.deleteLocalRenderInfo(this._callIdRef.callId,e)}this._context.setCallLocalVideoStream(this._callIdRef.callId,e.added.map(Ue),e.removed.map(Ue))},this.dominantSpeakersChanged=()=>{const e=this._call.feature(p.Features.DominantSpeakers).dominantSpeakers;this._context.setCallDominantSpeakers(this._callIdRef.callId,e)},this._call=e,this._callIdRef={callId:e.id},this._context=t,this._internalContext=i,this._diagnosticsSubscriber=new ot(this._callIdRef,this._context,this._call.feature(p.Features.UserFacingDiagnostics)),this._participantSubscribers=new Map,this._recordingSubscriber=new rt(this._callIdRef,this._context,this._call.feature(p.Features.Recording)),this._pptLiveSubscriber=new at(this._callIdRef,this._context,this._call),this._transcriptionSubscriber=new st(this._callIdRef,this._context,this._call.feature(p.Features.Transcription)),this._raiseHandSubscriber=new ct(this._callIdRef,this._context,this._call.feature(p.Features.RaiseHand)),this._reactionSubscriber=new ht(this._callIdRef,this._context,this._call.feature(p.Features.Reaction)),this._optimalVideoCountSubscriber=new dt({callIdRef:this._callIdRef,context:this._context,localOptimalVideoCountFeature:this._call.feature(p.Features.OptimalVideoCount)}),this._localVideoStreamVideoEffectsSubscribers=new Map,this._capabilitiesSubscriber=new ut(this._callIdRef,this._context,this._call.feature(p.Features.Capabilities)),this._spotlightSubscriber=new pt(this._callIdRef,this._context,this._call.feature(p.Features.Spotlight)),this.subscribe()}addParticipantListener(e){var t;const i=_(e.identifier);null===(t=this._participantSubscribers.get(i))||void 0===t||t.unsubscribe(),this._participantSubscribers.set(i,new nt(this._callIdRef,e,this._context,this._internalContext))}removeParticipantListener(e){const t=_(e.identifier),i=this._participantSubscribers.get(t);i&&(i.unsubscribe(),this._participantSubscribers.delete(t))}}var ft=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};class vt{constructor(e){this._context=e}get(e,t){switch(t){case"accept":return this._context.withAsyncErrorTeedToState((function(...t){return ft(this,void 0,void 0,(function*(){return yield e.accept(...t)}))}),"IncomingCall.accept");case"reject":return this._context.withAsyncErrorTeedToState((function(...t){return ft(this,void 0,void 0,(function*(){return yield e.reject(...t)}))}),"IncomingCall.reject");default:return Reflect.get(e,t)}}}class St{constructor(e,t){this.subscribe=()=>{this._incomingCall.on("callEnded",this.callEnded)},this.unsubscribe=()=>{this._incomingCall.off("callEnded",this.callEnded)},this.callEnded=e=>{this._setIncomingCallEnded(this._incomingCall.id,e.callEndReason)},this._incomingCall=e,this._setIncomingCallEnded=t,this.subscribe()}}class yt{constructor(e,t){this.unregisterSubscriber=()=>{for(const[e,t]of this._callSubscribers.entries())t.unsubscribe();this._callSubscribers.clear();for(const[e,t]of this._incomingCallSubscribers.entries())t.unsubscribe();this._incomingCallSubscribers.clear(),this._declarativeIncomingCalls.clear();for(const[e,t]of this._declarativeCalls.entries())t.unsubscribe();this._declarativeCalls.clear()},this.callsUpdated=e=>{const t=[];for(const i of e.added){const e=this.addCall(i);t.push(e)}const i=[];for(const t of e.removed){it(this._context,this._internalContext,t.id);const e=this._callSubscribers.get(t);e&&(e.unsubscribe(),this._callSubscribers.delete(t)),this._context.setCallEnded(t.id,t.callEndReason);const n=this._declarativeCalls.get(t);n?(n.unsubscribe(),i.push(n),this._declarativeCalls.delete(t)):i.push(this.callDeclaratify(t,this._context))}for(const e of this._externalCallsUpdatedListeners)e({added:t,removed:i})},this.setIncomingCallEnded=(e,t)=>{const i=this._incomingCallSubscribers.get(e);i&&(i.unsubscribe(),this._incomingCallSubscribers.delete(e)),this._declarativeIncomingCalls.delete(e),this._context.setIncomingCallEnded(e,t)},this.incomingCall=({incomingCall:e})=>{var t;this._incomingCallSubscribers.has(e.id)||this._incomingCallSubscribers.set(e.id,new St(e,this.setIncomingCallEnded)),this._declarativeIncomingCalls.set(e.id,((e,t)=>{const i=new vt(t);return new Proxy(e,i)})(e,this._context)),this._context.setIncomingCall({id:(t=e).id,callerInfo:t.callerInfo,startTime:new Date,endTime:void 0})},this.addCall=e=>{var t;return null===(t=this._callSubscribers.get(e))||void 0===t||t.unsubscribe(),this._context.setCall(function(e){const t={};return e.remoteParticipants.forEach((e=>{t[_(e.identifier)]=Ve(e)})),{id:e.id,kind:Ne(e)?"Call":"TeamsCall",callerInfo:e.callerInfo,state:e.state,callEndReason:e.callEndReason,diagnostics:{network:{latest:{}},media:{latest:{}}},direction:e.direction,isMuted:e.isMuted,isScreenSharingOn:e.isScreenSharingOn,localVideoStreams:e.localVideoStreams.map(Ue),remoteParticipants:t,remoteParticipantsEnded:{},recording:{isRecordingActive:!1},localRecording:{isLocalRecordingActive:!1},pptLive:{isActive:!1},raiseHand:{raisedHands:[]},localParticipantReaction:void 0,transcription:{isTranscriptionActive:!1},screenShareRemoteParticipant:void 0,startTime:new Date,endTime:void 0,role:e.role,captionsFeature:{captions:[],supportedSpokenLanguages:[],supportedCaptionLanguages:[],currentCaptionLanguage:"",currentSpokenLanguage:"",isCaptionsFeatureActive:!1,startCaptionsInProgress:!1,captionsKind:xe(e)?"TeamsCaptions":"Captions"},transfer:{acceptedTransfers:{}},optimalVideoCount:{maxRemoteVideoStreams:e.feature(p.Features.OptimalVideoCount).optimalVideoCount}}}(e)),this._callSubscribers.set(e,new mt(e,this._context,this._internalContext)),this.getOrCreateDeclarativeCall(e)},this.getOrCreateDeclarativeCall=e=>{const t=this._declarativeCalls.get(e);if(t)return t;const i=this.callDeclaratify(e,this._context);return this._declarativeCalls.set(e,i),i},this._context=e,this._internalContext=t,this._callSubscribers=new Map,this._incomingCallSubscribers=new Map,this._declarativeIncomingCalls=new Map,this._declarativeCalls=new Map,this._externalCallsUpdatedListeners=new Set}getCommon(e,t){switch(t){case"startCall":return this._context.withErrorTeedToState(((...t)=>{const i=this.startCall(e,t);return this.addCall(i),this.getOrCreateDeclarativeCall(i)}),"CallAgent.startCall");case"join":return this._context.withErrorTeedToState(((...t)=>{const i=this.joinCall(e,t);return this.addCall(i),this.getOrCreateDeclarativeCall(i)}),"CallAgent.join");case"calls":return Array.from(this._declarativeCalls.values());case"on":return(...t)=>{if("callsUpdated"===t[0]){const e=t[1];this._externalCallsUpdatedListeners.add(e)}else this.agentSubscribe(e,t)};case"off":return(...t)=>{if("callsUpdated"===t[0]){const e=t[1];this._externalCallsUpdatedListeners.delete(e)}else this.agentUnsubscribe(e,t)};case"dispose":return()=>{e.dispose(),this.unsubscribe()};case"incomingCalls":return Array.from(this._declarativeIncomingCalls.values());default:return Reflect.get(e,t)}}}const Ct=(e,t)=>{!function(e,t){const i=t.getCallIds();for(const n of i)it(e,t,n)}(e,t),e.clearCallRelatedState(),t.clearCallRelatedState()};var _t=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};class Et{constructor(e){this._context=e}unsubscribe(){}getContext(){return this._context}get(e,t){switch(t){case"mute":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.mute(...t)}))}),"Call.mute");case"unmute":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.unmute(...t)}))}),"Call.unmute");case"startVideo":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.startVideo(...t)}))}),"Call.startVideo");case"stopVideo":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.stopVideo(...t)}))}),"Call.stopVideo");case"startScreenSharing":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.startScreenSharing(...t)}))}),"Call.startScreenSharing");case"stopScreenSharing":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.stopScreenSharing(...t)}))}),"Call.stopScreenSharing");case"hold":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.hold(...t)}))}),"Call.hold");case"resume":return this._context.withAsyncErrorTeedToState((function(...t){return _t(this,void 0,void 0,(function*(){return yield e.resume(...t)}))}),"Call.resume");case"feature":return this._context.withErrorTeedToState(((...t)=>{if(t[0]===p.Features.Captions){const t=e.feature(p.Features.Captions).captions;let i;return"Captions"===t.kind?(i=new bt(this._context,e),{captions:new Proxy(t,i)}):(i=new Tt(this._context,e),{captions:new Proxy(t,i)})}if(t[0]===p.Features.Transfer){const t=e.feature(p.Features.Transfer),i=new wt(this._context,e);return new Proxy(t,i)}if(t[0]===p.Features.Spotlight){const t=e.feature(p.Features.Spotlight),i=new It(this._context);return new Proxy(t,i)}return e.feature(...t)}),"Call.feature");default:return Reflect.get(e,t)}}}class Tt{constructor(e,t){this._context=e,this._call=t}get(e,t){switch(t){case"startCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){var i,n;this._context.setStartCaptionsInProgress(this._call.id,!0);const r=yield e.startCaptions(...t);return this._context.setSelectedSpokenLanguage(this._call.id,null!==(n=null===(i=t[0])||void 0===i?void 0:i.spokenLanguage)&&void 0!==n?n:"en-us"),r}))),"Call.feature");case"stopCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){const i=yield e.stopCaptions(...t);return this._context.setIsCaptionActive(this._call.id,!1),this._context.setStartCaptionsInProgress(this._call.id,!1),this._context.clearCaptions(this._call.id),i}))),"Call.feature");case"setSpokenLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){const i=yield e.setSpokenLanguage(...t);return this._context.setSelectedSpokenLanguage(this._call.id,t[0]),i}))),"Call.feature");case"setCaptionLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){const i=yield e.setCaptionLanguage(...t);return this._context.setSelectedCaptionLanguage(this._call.id,t[0]),i}))),"Call.feature");default:return Reflect.get(e,t)}}}class bt{constructor(e,t){this._context=e,this._call=t}get(e,t){switch(t){case"startCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){var i,n;this._context.setStartCaptionsInProgress(this._call.id,!0);const r=yield e.startCaptions(...t);return this._context.setSelectedSpokenLanguage(this._call.id,null!==(n=null===(i=t[0])||void 0===i?void 0:i.spokenLanguage)&&void 0!==n?n:"en-us"),r}))),"Call.feature");case"stopCaptions":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){const i=yield e.stopCaptions(...t);return this._context.setIsCaptionActive(this._call.id,!1),this._context.setStartCaptionsInProgress(this._call.id,!1),this._context.clearCaptions(this._call.id),i}))),"Call.feature");case"setSpokenLanguage":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){const i=yield e.setSpokenLanguage(...t);return this._context.setSelectedSpokenLanguage(this._call.id,t[0]),i}))),"Call.feature");default:return Reflect.get(e,t)}}}class It{constructor(e){this._context=e}get(e,t){switch(t){case"startSpotlight":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){return yield e.startSpotlight(...t)}))),"Call.feature");case"stopSpotlight":return this._context.withAsyncErrorTeedToState(((...t)=>_t(this,void 0,void 0,(function*(){return yield e.stopSpotlight(...t)}))),"Call.feature");default:return Reflect.get(e,t)}}}class wt{constructor(e,t){this._context=e,this._call=t}get(e,t){return"on"===t?(...t)=>{if("transferAccepted"===t[0]){const i=t[1],n=e=>{this._context.setAcceptedTransfer(this._call.id,{callId:e.targetCall.id,timestamp:new Date}),i(e)};return e.on("transferAccepted",n)}}:Reflect.get(e,t)}}class Rt extends Et{get(e,t){return"addParticipant"===t?this.getContext().withAsyncErrorTeedToState((function(...t){return i=this,n=void 0,a=function*(){return yield e.addParticipant(...t)},new((r=void 0)||(r=Promise))((function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(s,o)}l((a=a.apply(i,n||[])).next())}));var i,n,r,a}),"Call.addParticipant"):super.get(e,t)}}class At extends yt{constructor(e,t,i){super(t,i),this.subscribe=()=>{this._callAgent.on("callsUpdated",this.callsUpdated),this._callAgent.on("incomingCall",this.incomingCall);for(const e of this._callAgent.calls)this.addCall(e)},this.unsubscribe=()=>{this._callAgent.off("callsUpdated",this.callsUpdated),this._callAgent.off("incomingCall",this.incomingCall),this.unregisterSubscriber()},this._callAgent=e,this.subscribe()}callDeclaratify(e,t){if(Ne(e))return((e,t)=>{const i=new Rt(t);return Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>i.unsubscribe()}),new Proxy(e,i)})(e,t);throw new Error("Not reachable code, DeclarativeCallAgent.callDeclaratify must be called with an ACS call.")}startCall(e,t){if(Le(e))return e.startCall(...t);throw Error("Unreachable code, DeclarativeCallAgent.startCall must be called with an ACS callAgent.")}joinCall(e,t){if(Le(e))return e.join(...t);throw Error("Unreachable code, DeclarativeCallAgent.joinCall must be called with an ACS callAgent.")}agentSubscribe(e,t){if(Le(e))return e.on(...t);throw Error("Unreachable code, DeclarativeCallAgent.agentSubscribe must be called with an ACS callAgent.")}agentUnsubscribe(e,t){if(Le(e))return e.off(...t);throw Error("Unreachable code, DeclarativeCallAgent.agentUnsubscribe must be called with an ACS callAgent.")}get(e,t){return super.getCommon(e,t)}}class Pt{constructor(){this._remoteRenderInfos=new Map,this._localRenderInfos=new Map,this._unparentedRenderInfos=new Map,this._callIdHistory=new Oe,this._unparentedViewVideoEffectsSubscriber=new Map}setCallId(e,t){this._callIdHistory.updateCallIdHistory(e,t);const i=this._remoteRenderInfos.get(t);i&&(this._remoteRenderInfos.delete(t),this._remoteRenderInfos.set(e,i));const n=this._localRenderInfos.get(t);n&&(this._localRenderInfos.delete(t),this._localRenderInfos.set(e,n))}getCallIds(){return this._remoteRenderInfos.keys()}getRemoteRenderInfoForCall(e){return this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e))}getRemoteRenderInfoForParticipant(e,t,i){const n=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));if(!n)return;const r=n.get(t);return r?r.get(i):void 0}setRemoteRenderInfo(e,t,i,n,r,a){let s=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));s||(s=new Map,this._remoteRenderInfos.set(this._callIdHistory.latestCallId(e),s));let o=s.get(t);o||(o=new Map,s.set(t,o)),o.set(i,{stream:n,status:r,renderer:a})}deleteRemoteRenderInfo(e,t,i){const n=this._remoteRenderInfos.get(this._callIdHistory.latestCallId(e));if(!n)return;const r=n.get(t);r&&r.delete(i)}setLocalRenderInfo(e,t,i,n,r){let a=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));a||(a=new Map,this._localRenderInfos.set(this._callIdHistory.latestCallId(e),a)),a.set(t,{stream:i,status:n,renderer:r})}getLocalRenderInfosForCall(e){return this._localRenderInfos.get(this._callIdHistory.latestCallId(e))}getLocalRenderInfo(e,t){const i=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));if(i)return i.get(t)}deleteLocalRenderInfo(e,t){const i=this._localRenderInfos.get(this._callIdHistory.latestCallId(e));i&&i.delete(t)}getUnparentedRenderInfo(e){return this._unparentedRenderInfos.get(e.mediaStreamType)}getUnparentedRenderInfos(){return[...this._unparentedRenderInfos].map((([,e])=>e.stream))}setUnparentedRenderInfo(e,t,i,n){this._unparentedRenderInfos.set(e.mediaStreamType,{stream:t,status:i,renderer:n})}deleteUnparentedRenderInfo(e){var t;null===(t=this._unparentedViewVideoEffectsSubscriber.get(e.mediaStreamType))||void 0===t||t.unsubscribe(),this._unparentedRenderInfos.delete(e.mediaStreamType)}subscribeToUnparentedViewVideoEffects(e,t){var i;null===(i=this._unparentedViewVideoEffectsSubscriber.get(e.mediaStreamType))||void 0===i||i.unsubscribe(),this._unparentedViewVideoEffectsSubscriber.set(e.mediaStreamType,new Ye({parent:"unparented",context:t,localVideoStream:e,localVideoStreamEffectsAPI:e.feature(p.Features.VideoEffects)}))}clearCallRelatedState(){this._remoteRenderInfos.clear(),this._localRenderInfos.clear()}}var Mt=r(2289),kt=r.n(Mt);const Dt=e=>{const t=(e=>{switch(e){case"Call":return 1;case"Chat":return 2;case"CallWithChat":return 3;case"StatefulComponents":return 4;default:return 0}})(e);return(e=>{const t=e.search(/alpha/);return t>=0?e.substring(0,t+5):e})(`acr1${t}0/${kt()}`)};class Ot extends Et{get(e,t){return"addParticipant"===t?this.getContext().withAsyncErrorTeedToState((function(...t){return i=this,n=void 0,a=function*(){return yield e.addParticipant(...t)},new((r=void 0)||(r=Promise))((function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(s,o)}l((a=a.apply(i,n||[])).next())}));var i,n,r,a}),"TeamsCall.addParticipant"):super.get(e,t)}}class Nt extends yt{constructor(e,t,i){super(t,i),this.subscribe=()=>{this._callAgent.on("callsUpdated",this.callsUpdated),this._callAgent.on("incomingCall",this.incomingCall);for(const e of this._callAgent.calls)this.addCall(e)},this.unsubscribe=()=>{this._callAgent.off("callsUpdated",this.callsUpdated),this._callAgent.off("incomingCall",this.incomingCall),this.unregisterSubscriber()},this._callAgent=e,this.subscribe()}callDeclaratify(e,t){if(xe(e))return((e,t)=>{const i=new Ot(t);return i.unsubscribe(),Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>i.unsubscribe()}),new Proxy(e,i)})(e,t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.callDeclaratify must be called with an TeamsCall.")}startCall(e,t){if(Fe(e))return e.startCall(...t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.startCall must be called with an TeamsCallAgent.")}joinCall(e,t){if(Fe(e))return e.join(...t);throw new Error("Not reachable code, DeclarativeTeamsCallAgent.joinCall must be called with an TeamsCallAgent.")}agentSubscribe(e,t){throw Fe(e)&&e.on(...t),new Error("Not reachable code, DeclarativeTeamsCallAgent.agentSubscribe must be called with an TeamsCallAgent.")}agentUnsubscribe(e,t){throw Fe(e)&&e.off(...t),new Error("Not reachable code, DeclarativeTeamsCallAgent.agentUnsubscribe must be called with an TeamsCallAgent.")}get(e,t){return super.getCommon(e,t)}}class Lt{constructor(e,t,i,n){this._context=e,this._callId=t,this._participantId=i,this._streamId=n}get(e,t){return"updateScalingMode"===t?(...t)=>{return i=this,n=void 0,a=function*(){yield e.updateScalingMode(...t),this._context.setRemoteVideoStreamViewScalingMode(this._callId,this._participantId,this._streamId,t[0])},new((r=void 0)||(r=Promise))((function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(s,o)}l((a=a.apply(i,n||[])).next())}));var i,n,r,a}:Reflect.get(e,t)}}var xt=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};class Ft{constructor(e,t){this._context=e,this._internalContext=t}get(e,t){switch(t){case"createCallAgent":return this._context.withAsyncErrorTeedToState(((...t)=>xt(this,void 0,void 0,(function*(){const i=yield e.createCallAgent(...t);return this._callAgent=((e,t,i)=>(Ct(t,i),new Proxy(e,new At(e,t,i))))(i,this._context,this._internalContext),this._context.setCallAgent({displayName:this._callAgent.displayName}),this._callAgent}))),"CallClient.createCallAgent");case"createTeamsCallAgent":return this._context.withAsyncErrorTeedToState(((...t)=>xt(this,void 0,void 0,(function*(){const i=yield e.createTeamsCallAgent(...t);return this._callAgent=((e,t,i)=>(Ct(t,i),new Proxy(e,new Nt(e,t,i))))(i,this._context,this._internalContext),this._context.setCallAgent({displayName:void 0}),this._callAgent}))),"CallClient.createTeamsCallAgent");case"getDeviceManager":return this._context.withAsyncErrorTeedToState((()=>xt(this,void 0,void 0,(function*(){const t=yield e.getDeviceManager();if(this._sdkDeviceManager){if(this._sdkDeviceManager===t)return this._deviceManager;throw new Error("Multiple DeviceManager not supported. This means a incompatible version of communication-calling is used OR calling declarative was not properly updated to communication-calling version.")}return this._sdkDeviceManager=t,this._deviceManager=((e,t,i)=>{const n=new O(e,t);return Object.defineProperty(e,"unsubscribe",{configurable:!1,value:()=>n.unsubscribe()}),Object.defineProperty(e,"selectCamera",{configurable:!1,value:e=>n.selectCamera(e)}),Object.defineProperty(e,"getUnparentedVideoStreams",{configurable:!1,value:()=>i.getUnparentedRenderInfos()}),new Proxy(e,n)})(t,this._context,this._internalContext),this._deviceManager}))),"CallClient.getDeviceManager");case"feature":return this._context.withErrorTeedToState(((...i)=>{if(i[0]===p.Features.DebugInfo){const t=e.feature(p.Features.DebugInfo);return Object.assign(Object.assign({},t),{getEnvironmentInfo:()=>xt(this,void 0,void 0,(function*(){const e=yield t.getEnvironmentInfo();return this._context.setEnvironmentInfo(e),e}))})}return Reflect.get(e,t)}),"CallClient.feature");default:return Reflect.get(e,t)}}}const Ut=(e,t,i)=>(Object.defineProperty(e,"getState",{configurable:!1,value:()=>t.getState()}),Object.defineProperty(e,"onStateChange",{configurable:!1,value:e=>t.onStateChange(e)}),Object.defineProperty(e,"offStateChange",{configurable:!1,value:e=>t.offStateChange(e)}),Object.defineProperty(e,"createView",{configurable:!1,value:(e,n,r,a)=>xt(void 0,void 0,void 0,(function*(){const s=n?S(n):void 0,o=yield function(e,t,i,n,r,a){const s=r.mediaStreamType;return i?function(e,t,i,n,r,a){return et(this,void 0,void 0,(function*(){let s;if(r)s="createViewRemote";else{if(!i)throw new Error("unparented createView not implemented yet here");s="createViewLocal"}const o=null==n?void 0:n.mediaStreamType,l=n.mediaStreamType,c=n.id,d="createViewRemote"===s&&r?"string"==typeof r?r:_(r):void 0,u={callId:i,participantKey:d,streamId:null!=c?c:l,streamType:o,streamEventType:s};Xe(De.CREATING_VIEW,u);const h="createViewRemote"===s&&d?t.getRemoteRenderInfoForParticipant(i,d,c):t.getLocalRenderInfo(i,l);if(!h)return void Xe(De.STREAM_NOT_FOUND,u);if("Rendered"===h.status)return void Xe(De.STREAM_ALREADY_RENDERED,u);if("Rendering"===h.status)return void Xe(De.STREAM_RENDERING,u);if("Stopping"===h.status)return void("createViewRemote"===s&&d?(Xe(De.STREAM_STOPPING,u),t.setRemoteRenderInfo(i,d,c,h.stream,"Rendering",h.renderer)):"createViewLocal"===s&&(Xe(De.STREAM_STOPPING,u),t.setLocalRenderInfo(i,l,h.stream,"Rendering",h.renderer)));const g=new p.VideoStreamRenderer(h.stream);let m;"createViewRemote"===s&&d?t.setRemoteRenderInfo(i,d,c,h.stream,"Rendering",void 0):t.setLocalRenderInfo(i,l,h.stream,"Rendering",g);try{m=yield g.createView(a)}catch(e){throw"createViewRemote"===s&&d?(Xe(De.CREATE_STREAM_FAIL,u),t.setRemoteRenderInfo(i,d,c,h.stream,"NotRendered",void 0)):"createViewLocal"===s&&(Xe(De.CREATE_STREAM_FAIL,u,e),t.setLocalRenderInfo(i,l,h.stream,"NotRendered",void 0)),e}const f="createViewRemote"===s&&d?t.getRemoteRenderInfoForParticipant(i,d,c):t.getLocalRenderInfo(i,l);return f?"Stopping"===f.status?(Xe(De.CREATED_STREAM_STOPPING,u),g.dispose(),void("createViewRemote"===s&&d?(t.setRemoteRenderInfo(i,d,c,f.stream,"NotRendered",void 0),e.setRemoteVideoStreamRendererView(i,d,c,void 0)):"createViewLocal"===s&&(t.setLocalRenderInfo(i,l,f.stream,"NotRendered",void 0),e.setLocalVideoStreamRendererView(i,l,void 0)))):("createViewRemote"===s&&d?(t.setRemoteRenderInfo(i,d,c,f.stream,"Rendered",g),e.setRemoteVideoStreamRendererView(i,d,c,He(m)),Xe(De.VIEW_RENDER_SUCCEED,u)):"createViewLocal"===s&&(t.setLocalRenderInfo(i,l,f.stream,"Rendered",g),e.setLocalVideoStreamRendererView(i,l,He(m)),Xe(De.VIEW_RENDER_SUCCEED,u)),{renderer:g,view:m}):(Xe(De.RENDER_INFO_NOT_FOUND,u),g.dispose(),void("createViewRemote"===s&&d?e.setRemoteVideoStreamRendererView(i,d,c,void 0):e.setLocalVideoStreamRendererView(i,l,void 0)))}))}(e,t,i,r,n,a):"id"in r||i?(Xe(De.CREATE_STREAM_INVALID_PARAMS,{streamType:s}),Promise.resolve(void 0)):e.withAsyncErrorTeedToState((()=>et(this,void 0,void 0,(function*(){return yield function(e,t,i,n){return et(this,void 0,void 0,(function*(){const r=t.getUnparentedRenderInfo(i);if(r&&"Rendered"===r.status)return void console.warn("Unparented LocalVideoStream is already rendered");if(r&&"Rendering"===r.status)return;if(r&&"Stopping"===r.status)return void console.warn("Unparented LocalVideoStream is in the middle of stopping");const a=new p.LocalVideoStream(i.source),s=new p.VideoStreamRenderer(a);let o;t.setUnparentedRenderInfo(i,a,"Rendering",void 0);try{o=yield s.createView(n)}catch(e){throw t.deleteUnparentedRenderInfo(i),e}const l=t.getUnparentedRenderInfo(i);return l?"Stopping"===l.status?(t.deleteUnparentedRenderInfo(i),void e.deleteDeviceManagerUnparentedView(i)):(t.setUnparentedRenderInfo(i,a,"Rendered",s),t.subscribeToUnparentedViewVideoEffects(a,e),e.setDeviceManagerUnparentedView(i,He(o)),{renderer:s,view:o}):(s.dispose(),void e.deleteDeviceManagerUnparentedView(i))}))}(e,t,r,a)}))),"Call.startVideo")()}(t,i,e,s,r,a);if("id"in r&&e&&n&&o){const i=_(n);o.view=((e,t,i,n,r)=>{const a=new Lt(t,i,n,r);return new Proxy(e,a)})(o.view,t,e,i,r.id)}return o}))}),Object.defineProperty(e,"disposeView",{configurable:!1,value:(e,n,r)=>{const a=n?S(n):void 0;tt(t,i,e,a,r)}}),new Proxy(e,new Ft(t,i))),Bt=(e,t)=>{var i,n;const r=null!==(n=null===(i=null==t?void 0:t.diagnostics)||void 0===i?void 0:i.tags)&&void 0!==n?n:[];return r.push(Dt(e)),Object.assign(Object.assign({},t),{diagnostics:Object.assign(Object.assign({},null==t?void 0:t.diagnostics),{tags:r})})},Vt=["accessDeniedTeamsMeeting","joinCallFailedDueToNoNetwork","leftCall","removedFromCall","unsupportedEnvironment"];var Ht=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const $t=56e4,Gt=[5e3,5300,$t],jt=e=>e.call?!!e.call.localVideoStreams.find((e=>"Video"===e.mediaStreamType)):!!e.devices.selectedCamera&&R(e.devices),zt=e=>{if(!1===e)return!1;const t=!0===e?{}:e||{};return t.displayType="compact",!0!==t.screenShareButton&&(t.screenShareButton=!1),t};var Wt;!function(e){e[e.LEFT_CALL=0]="LEFT_CALL",e[e.ACCESS_DENIED=1]="ACCESS_DENIED",e[e.REMOVED_FROM_CALL=2]="REMOVED_FROM_CALL"}(Wt||(Wt={}));const qt=e=>Vt.includes(e),Kt=(e,t)=>{var i;if(!1===e)return!1;let n=null!==(i=e instanceof Object?Object.assign({},e):e)&&void 0!==i?i:{};return!0===n||void 0===n?n=t.reduce(((e,t)=>(e[t]={disabled:!0},e)),{}):t.forEach((e=>{!1!==n[e]&&(n[e]={disabled:!0})})),n},Jt=e=>void 0!==e&&"boolean"!=typeof e&&e.disabled,Yt=(e,t)=>!(!1!==(null==e?void 0:e.isSupportedBrowser)&&(!1!==(null==e?void 0:e.isSupportedBrowserVersion)||t)&&!1!==(null==e?void 0:e.isSupportedPlatform)),Qt=e=>"safari"===(null==e?void 0:e.environment.browser),Zt=e=>e.devices.selectedCamera||e.devices.cameras[0],Xt=e=>!!Array.isArray(e);class ei{constructor(e,t){this.isMutedChangedHandler=()=>{this.emitter.emit("isMutedChanged",{participantId:this.participant.identifier,isMuted:this.participant.isMuted})},this.displayNameChangedHandler=()=>{this.emitter.emit("displayNameChanged",{participantId:this.participant.identifier,displayName:this.participant.displayName})},this.isSpeakingChangedHandler=()=>{this.emitter.emit("isSpeakingChanged",{participantId:this.participant.identifier,isSpeaking:this.participant.isSpeaking})},this.videoStreamsUpdatedHandler=e=>{this.emitter.emit("videoStreamsUpdated",e)},this.participant=e,this.emitter=t,this.subscribeParticipantEvents()}subscribeParticipantEvents(){this.participant.on("isMutedChanged",this.isMutedChangedHandler),this.participant.on("displayNameChanged",this.displayNameChangedHandler),this.participant.on("isSpeakingChanged",this.isSpeakingChangedHandler),this.participant.on("videoStreamsUpdated",this.videoStreamsUpdatedHandler)}unsubscribeAll(){this.participant.off("isMutedChanged",this.isMutedChangedHandler),this.participant.off("displayNameChanged",this.displayNameChangedHandler),this.participant.off("isSpeakingChanged",this.isSpeakingChangedHandler),this.participant.off("videoStreamsUpdated",this.videoStreamsUpdatedHandler)}}class ti{constructor(e,t){this.unsubscribe=()=>{this._diagnostics.network.off("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.off("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))},this._diagnostics=t.feature(p.Features.UserFacingDiagnostics),this._emitter=e,this.subscribe()}subscribe(){this._diagnostics.network.on("diagnosticChanged",this.networkDiagnosticsChanged.bind(this)),this._diagnostics.media.on("diagnosticChanged",this.mediaDiagnosticsChanged.bind(this))}networkDiagnosticsChanged(e){const t=Object.assign({type:"network"},e);this._emitter.emit("diagnosticChanged",t)}mediaDiagnosticsChanged(e){const t=Object.assign({type:"media"},e);this._emitter.emit("diagnosticChanged",t)}}var ii=Number.isNaN||function(e){return"number"==typeof e&&e!=e};function ni(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(!((n=e[i])===(r=t[i])||ii(n)&&ii(r)))return!1;var n,r;return!0}const ri=function(e,t){var i;void 0===t&&(t=ni);var n,r=[],a=!1;return function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];return a&&i===this&&t(s,r)||(n=e.apply(this,s),a=!0,i=this,r=s),n}};var ai=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const si=(e,t)=>!!e&&!!t&&e.source.id===t.source.id,oi=ri(((e,t,i,n)=>{const r=()=>ai(void 0,void 0,void 0,(function*(){yield A(e);const n=null==i?void 0:i.id;let r=e.getState().deviceManager.selectedCamera;if(!r){const e=yield null==t?void 0:t.getCameras();r=e&&e.length>0?e[0]:void 0,r&&(null==t||t.selectCamera(r))}if(!n||!r)return;const a=new p.LocalVideoStream(r);i&&!i.localVideoStreams.find((e=>si(e,a)))&&(yield i.startVideo(a))})),a=()=>ai(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.startScreenSharing()})),s=()=>ai(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.stopScreenSharing()})),o=()=>ai(void 0,void 0,void 0,(function*(){const t=i&&e.getState().calls[i.id],n=null==t?void 0:t.localVideoStreams.find((e=>"Video"===e.mediaStreamType));i&&t&&n&&e.disposeView(i.id,void 0,n),yield A(e)})),l=()=>{throw new Error("Not implemented, cannot call a method from an abstract object")},c=null==i?void 0:i.feature(p.Features.Capabilities).capabilities.spotlightParticipant.isPresent,d=null==i?void 0:i.feature(p.Features.Capabilities).capabilities.removeParticipantsSpotlight.isPresent;return{onHangUp:e=>ai(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.hangUp({forEveryone:!0===e})})),onToggleHold:()=>ai(void 0,void 0,void 0,(function*(){return"LocalHold"===(null==i?void 0:i.state)?yield null==i?void 0:i.resume():yield null==i?void 0:i.hold()})),onSelectCamera:(n,r)=>ai(void 0,void 0,void 0,(function*(){if(t)if(i&&I(i.state)){t.selectCamera(n);const e=i.localVideoStreams.find((e=>"Video"===e.mediaStreamType));yield null==e?void 0:e.switchSource(n),yield null==e?void 0:e.getMediaStream()}else{if(!R(e.getState().deviceManager))return void t.selectCamera(n);yield o(),t.selectCamera(n),yield e.createView(void 0,void 0,{source:n,mediaStreamType:"Video"},r)}})),onSelectMicrophone:e=>ai(void 0,void 0,void 0,(function*(){if(t)return t.selectMicrophone(e)})),onSelectSpeaker:e=>ai(void 0,void 0,void 0,(function*(){if(t)return t.selectSpeaker(e)})),onStartScreenShare:a,onStopScreenShare:s,onToggleCamera:t=>ai(void 0,void 0,void 0,(function*(){const n=R(e.getState().deviceManager);if(i&&(I(i.state)||w(i.state))){const t=i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)),n=e.getState().deviceManager.unparentedViews;t||n.length>0?(n&&(yield n.forEach((t=>"Video"===t.mediaStreamType&&e.disposeView(void 0,void 0,t)))),t&&(yield(e=>ai(void 0,void 0,void 0,(function*(){(null==i?void 0:i.id)&&i&&i.localVideoStreams.find((t=>si(t,e)))&&(yield i.stopVideo(e))})))(t))):yield r()}else{const i=e.getState().deviceManager.selectedCamera;i&&(n?yield o():yield e.createView(void 0,void 0,{source:i,mediaStreamType:"Video"},t))}})),onToggleMicrophone:()=>ai(void 0,void 0,void 0,(function*(){if(!i||!I(i.state)&&!w(i.state))throw new Error("Please invoke onToggleMicrophone after call is started");return i.isMuted?yield i.unmute():yield i.mute()})),onToggleScreenShare:()=>ai(void 0,void 0,void 0,(function*(){return(null==i?void 0:i.isScreenSharingOn)?yield s():yield a()})),onCreateLocalStreamView:(...t)=>ai(void 0,[...t],void 0,(function*(t={scalingMode:"Crop",isMirrored:!0}){var n;if(!i||0===i.localVideoStreams.length)return;const r=e.getState().calls[i.id];if(!r)return;const a=r.localVideoStreams.find((e=>"Video"===e.mediaStreamType));if(!a)return;const{view:s}=null!==(n=yield e.createView(i.id,void 0,a,t))&&void 0!==n?n:{};return s?{view:s}:void 0})),onCreateRemoteStreamView:(t,...n)=>ai(void 0,[t,...n],void 0,(function*(t,n={scalingMode:"Crop"}){if(!i)return;const r=e.getState().calls[i.id];if(!r)throw new Error(`Call Not Found: ${i.id}`);const a=Object.values(r.remoteParticipants).find((e=>_(e.identifier)===t));if(!a||!a.videoStreams)return;const s=Object.values(a.videoStreams).findLast((e=>"Video"===e.mediaStreamType&&e.isAvailable))||Object.values(a.videoStreams).findLast((e=>"Video"===e.mediaStreamType)),o=Object.values(a.videoStreams).findLast((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable))||Object.values(a.videoStreams).findLast((e=>"ScreenSharing"===e.mediaStreamType));let l;return s&&s.isAvailable&&!s.view&&(l=yield e.createView(i.id,a.identifier,s,n)),o&&o.isAvailable&&!o.view&&(l=yield e.createView(i.id,a.identifier,o,{scalingMode:"Fit"})),(null==l?void 0:l.view)?{view:null==l?void 0:l.view}:void 0})),onStartLocalVideo:r,onDisposeRemoteStreamView:t=>ai(void 0,void 0,void 0,(function*(){if(!i)return;const n=e.getState().calls[i.id];if(!n)throw new Error(`Call Not Found: ${i.id}`);const r=Object.values(n.remoteParticipants).find((e=>_(e.identifier)===t));if(!r||!r.videoStreams)return;const a=Object.values(r.videoStreams).find((e=>"Video"===e.mediaStreamType)),s=Object.values(r.videoStreams).find((e=>"ScreenSharing"===e.mediaStreamType));a&&a.view&&e.disposeView(i.id,r.identifier,a),s&&s.view&&e.disposeView(i.id,r.identifier,s)})),onDisposeLocalStreamView:o,onDisposeRemoteScreenShareStreamView:t=>ai(void 0,void 0,void 0,(function*(){if(!i)return;const n=e.getState().calls[i.id];if(!n)throw new Error(`Call Not Found: ${i.id}`);const r=Object.values(n.remoteParticipants).find((e=>_(e.identifier)===t));if(!r||!r.videoStreams)return;const a=Object.values(r.videoStreams).find((e=>"ScreenSharing"===e.mediaStreamType));a&&a.view&&e.disposeView(i.id,r.identifier,a)})),onDisposeRemoteVideoStreamView:t=>ai(void 0,void 0,void 0,(function*(){if(!i)return;const n=e.getState().calls[i.id];if(!n)throw new Error(`Call Not Found: ${i.id}`);const r=Object.values(n.remoteParticipants).find((e=>_(e.identifier)===t));if(!r||!r.videoStreams)return;const a=Object.values(r.videoStreams).find((e=>"Video"===e.mediaStreamType));a&&a.view&&e.disposeView(i.id,r.identifier,a)})),onRaiseHand:()=>ai(void 0,void 0,void 0,(function*(){var e;return yield null===(e=null==i?void 0:i.feature(p.Features.RaiseHand))||void 0===e?void 0:e.raiseHand()})),onLowerHand:()=>ai(void 0,void 0,void 0,(function*(){var e;return yield null===(e=null==i?void 0:i.feature(p.Features.RaiseHand))||void 0===e?void 0:e.lowerHand()})),onToggleRaiseHand:()=>ai(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(p.Features.RaiseHand),n=e.getState().userId;(null==t?void 0:t.getRaisedHands().find((e=>_(e.identifier)===_(n))))?yield null==t?void 0:t.lowerHand():yield null==t?void 0:t.raiseHand()})),onReactionClick:e=>ai(void 0,void 0,void 0,(function*(){var t;"like"===e||"applause"===e||"heart"===e||"laugh"===e||"surprised"===e?yield null===(t=null==i?void 0:i.feature(p.Features.Reaction))||void 0===t?void 0:t.sendReaction({reactionType:e}):console.warn(`Can not recognize ${e} as meeting reaction`)})),onAddParticipant:l,onRemoveParticipant:l,onStartCall:l,onSendDtmfTone:e=>ai(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.sendDtmf(e)})),askDevicePermission:e=>ai(void 0,void 0,void 0,(function*(){t&&(yield null==t?void 0:t.askDevicePermission(e))})),onRemoveVideoBackgroundEffects:()=>ai(void 0,void 0,void 0,(function*(){const e=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(e){if(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)return e.feature(p.Features.VideoEffects).stopEffects();throw new Error("Video background effects dependency not resolved")}})),onBlurVideoBackground:e=>ai(void 0,void 0,void 0,(function*(){var r;const a=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(a){if(!(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency))throw new Error("Video background effects dependency not resolved");const t=(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)&&(null===(r=yield n.onResolveVideoBackgroundEffectsDependency())||void 0===r?void 0:r.createBackgroundBlurEffect);return t&&a.feature(p.Features.VideoEffects).startEffects(t(e))}})),onReplaceVideoBackground:e=>ai(void 0,void 0,void 0,(function*(){var r;const a=(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||(null==t?void 0:t.getUnparentedVideoStreams().find((e=>"Video"===e.mediaStreamType)));if(a){if(!(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency))throw new Error("Video background effects dependency not resolved");const t=(null==n?void 0:n.onResolveVideoBackgroundEffectsDependency)&&(null===(r=yield n.onResolveVideoBackgroundEffectsDependency())||void 0===r?void 0:r.createBackgroundReplacementEffect);return t&&a.feature(p.Features.VideoEffects).startEffects(t(e))}})),onStartCaptions:e=>ai(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(p.Features.Captions).captions;yield null==t?void 0:t.startCaptions(e)})),onStopCaptions:()=>ai(void 0,void 0,void 0,(function*(){const e=null==i?void 0:i.feature(p.Features.Captions).captions;yield null==e?void 0:e.stopCaptions()})),onSetCaptionLanguage:e=>ai(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(p.Features.Captions).captions;yield t.setCaptionLanguage(e)})),onSetSpokenLanguage:e=>ai(void 0,void 0,void 0,(function*(){const t=null==i?void 0:i.feature(p.Features.Captions).captions;yield null==t?void 0:t.setSpokenLanguage(e)})),onSubmitSurvey:e=>ai(void 0,void 0,void 0,(function*(){return yield null==i?void 0:i.feature(p.Features.CallSurvey).submitSurvey(e)})),onStartSpotlight:e=>ai(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>T(e)));yield null==i?void 0:i.feature(p.Features.Spotlight).startSpotlight(t)})),onStopSpotlight:e=>ai(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>T(e)));yield null==i?void 0:i.feature(p.Features.Spotlight).stopSpotlight(t)})),onStopAllSpotlight:()=>ai(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(p.Features.Spotlight).stopAllSpotlight()})),onStartLocalSpotlight:c?()=>ai(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(p.Features.Spotlight).startSpotlight()})):void 0,onStopLocalSpotlight:()=>ai(void 0,void 0,void 0,(function*(){yield null==i?void 0:i.feature(p.Features.Spotlight).stopSpotlight()})),onStartRemoteSpotlight:c?e=>ai(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>T(e)));yield null==i?void 0:i.feature(p.Features.Spotlight).startSpotlight(t)})):void 0,onStopRemoteSpotlight:d?e=>ai(void 0,void 0,void 0,(function*(){const t=null==e?void 0:e.map((e=>T(e)));yield null==i?void 0:i.feature(p.Features.Spotlight).stopSpotlight(t)})):void 0}}));var li=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const ci=ri(((...e)=>{const[t,i,n,r,a]=e;return Object.assign(Object.assign({},oi(t,n,r,a)),{onStartCall:(e,t)=>null==i?void 0:i.startCall(e,t),onAddParticipant:(e,t)=>li(void 0,void 0,void 0,(function*(){const i=T(e);m(i)?null==r||r.addParticipant(i,t):(g(i)||f(i))&&(null==r||r.addParticipant(i))})),onRemoveParticipant:e=>li(void 0,void 0,void 0,(function*(){const t=T(e);yield null==r?void 0:r.removeParticipant(t)}))})}));var di=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const ui=ri(((e,t,i,n,r)=>Object.assign(Object.assign({},oi(e,i,n,r)),{onStartCall:(e,i)=>{const n=null==i?void 0:i.threadId;if(!(e=>e.every((e=>!g(e))))(e))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(t)return t.startCall(e,n?{threadId:n}:void 0)},onAddParticipant:(e,t)=>di(void 0,void 0,void 0,(function*(){const i=T(e),r=null==t?void 0:t.threadId;if(g(i))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(v(i))throw new Error("Adding Microsoft Teams app identifier is not supported!");m(i)&&(null==n||n.addParticipant(i,r?{threadId:r}:void 0)),null==n||n.addParticipant(i)})),onRemoveParticipant:e=>di(void 0,void 0,void 0,(function*(){const t=T(e);if(g(t))throw new Error("CommunicationIdentifier in Teams call is not supported!");if(v(t))throw new Error("Removing Microsoft Teams app identifier is not supported!");yield null==n?void 0:n.removeParticipant(t)}))})));function hi(e,t,i,n,r){if(Le(t)&&(!n||n&&Ne(n)))return ci(e,t,i,n,r);if(Fe(t)&&(!n||n&&xe(n)))return ui(e,t,i,n,r);throw new Error("Unhandled agent type")}const pi=(e,t)=>{const i={};return n=>{var r;const a=null===(r=n.call)||void 0===r?void 0:r.remoteParticipants;var s,o,l,c;s=void 0,o=void 0,c=function*(){let n=!1;for(const t in a){if(i[t])continue;const r=yield e(t,{displayName:a[t].displayName});(null==r?void 0:r.displayName)&&a[t].displayName!==(null==r?void 0:r.displayName)&&(i[t]=null==r?void 0:r.displayName,n=!0)}n&&t()},new((l=void 0)||(l=Promise))((function(e,t){function i(e){try{r(c.next(e))}catch(e){t(e)}}function n(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof l?r:new l((function(e){e(r)}))).then(i,n)}r((c=c.apply(s,o||[])).next())}));const d=(e=>{let t,i={};const n={};return r=>{var a,s,o,l;if((null===(a=r.call)||void 0===a?void 0:a.remoteParticipants)!==t){i={};const a=null===(s=r.call)||void 0===s?void 0:s.remoteParticipants;for(const t in a){const r=e(t,a[t]);void 0!==r?((null===(o=n[t])||void 0===o?void 0:o.originalRef)!==a[t]&&(n[t]={newParticipant:r,originalRef:a[t]}),i[t]=n[t].newParticipant):i[t]=a[t]}t=null===(l=r.call)||void 0===l?void 0:l.remoteParticipants}return Object.assign(Object.assign({},r),{call:r.call?Object.assign(Object.assign({},r.call),{remoteParticipants:i}):void 0})}})(((e,t)=>{if(i[e])return Object.assign(Object.assign({},t),{displayName:i[e]})}));return d(n)}};class gi{constructor(e,t,i){this.onCallStateChanged=()=>{this.call.on("stateChanged",(()=>{var e,t,i,n,r,a,s;mi(this.call,this.callee)&&(null===(e=this.soundsLoaded)||void 0===e?void 0:e.callRingingSound)&&(this.soundsLoaded.callRingingSound.loop=!0,this.playSound(this.soundsLoaded.callRingingSound)),!mi(this.call,this.callee)&&(null===(t=this.soundsLoaded)||void 0===t?void 0:t.callRingingSound)&&(this.soundsLoaded.callRingingSound.loop=!1,this.soundsLoaded.callRingingSound.pause()),"Disconnected"===this.call.state&&((null===(i=this.soundsLoaded)||void 0===i?void 0:i.callBusySound)&&603===(null===(n=this.call.callEndReason)||void 0===n?void 0:n.code)?this.playSound(this.soundsLoaded.callBusySound):(null===(r=this.soundsLoaded)||void 0===r?void 0:r.callEndedSound)&&0===(null===(a=this.call.callEndReason)||void 0===a?void 0:a.code)&&7015!==(null===(s=this.call.callEndReason)||void 0===s?void 0:s.subCode)&&this.playSound(this.soundsLoaded.callEndedSound))}))},this.call=e,this.callee=t,i&&(this.soundsLoaded=this.loadSounds(i),this.subscribeCallSoundEvents())}subscribeCallSoundEvents(){this.onCallStateChanged()}unsubscribeAll(){var e,t;null===(e=this.call)||void 0===e||e.off("stateChanged",this.onCallStateChanged),(null===(t=this.soundsLoaded)||void 0===t?void 0:t.callRingingSound)&&this.soundsLoaded.callRingingSound.pause()}loadSounds(e){var t,i,n;let r,a,s;return(null==e?void 0:e.callEnded)&&(r=new Audio(null===(t=null==e?void 0:e.callEnded)||void 0===t?void 0:t.url),r.preload="auto"),(null==e?void 0:e.callRinging)&&(a=new Audio(null===(i=null==e?void 0:e.callRinging)||void 0===i?void 0:i.url),a.preload="auto"),(null==e?void 0:e.callBusy)&&(s=new Audio(null===(n=null==e?void 0:e.callBusy)||void 0===n?void 0:n.url),s.preload="auto"),{callEndedSound:r,callRingingSound:a,callBusySound:s}}playSound(e){e.play().catch((e=>{console.error(e,"Failed to play sound, check loader config to make sure it is correct")}))}}const mi=(e,t)=>!(!(t&&t.length>=1)||m(t[0])||"Ringing"!==e.state&&"Connecting"!==e.state);var fi=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};class vi{constructor(e,t,i,n,r){var a,s,o,l;this.emitter=new L.EventEmitter,this.state={isLocalPreviewMicrophoneEnabled:!1,userId:e.userId,displayName:null===(a=e.callAgent)||void 0===a?void 0:a.displayName,devices:e.deviceManager,call:void 0,targetCallees:r,page:"configuration",latestErrors:e.latestErrors,isTeamsCall:t,isRoomsCall:i,alternateCallerId:e.alternateCallerId,environmentInfo:e.environmentInfo,unsupportedBrowserVersionsAllowed:!1,videoBackgroundImages:null===(s=null==n?void 0:n.videoBackgroundOptions)||void 0===s?void 0:s.videoBackgroundImages,onResolveVideoEffectDependency:null===(o=null==n?void 0:n.videoBackgroundOptions)||void 0===o?void 0:o.onResolveDependency,selectedVideoBackgroundEffect:void 0,cameraStatus:void 0,sounds:null==n?void 0:n.callingSounds,reactions:null==n?void 0:n.reactionResources},this.emitter.setMaxListeners(null!==(l=null==n?void 0:n.maxListeners)&&void 0!==l?l:50),this.bindPublicMethods(),this.displayNameModifier=(null==n?void 0:n.onFetchProfile)?pi(n.onFetchProfile,(()=>{this.setState(this.getState())})):void 0}bindPublicMethods(){this.setAllowedUnsupportedBrowser.bind(this)}onStateChange(e){this.emitter.on("stateChanged",e)}offStateChange(e){this.emitter.off("stateChanged",e)}setState(e){this.state=this.displayNameModifier?this.displayNameModifier(e):e,this.emitter.emit("stateChanged",this.state)}getState(){return this.state}setIsLocalMicrophoneEnabled(e){this.setState(Object.assign(Object.assign({},this.state),{isLocalPreviewMicrophoneEnabled:e}))}setCurrentCallId(e){this.callId=e}setTargetCallee(e){this.setState(Object.assign(Object.assign({},this.state),{targetCallees:e}))}onCallEnded(e){this.emitter.on("callEnded",e)}offCallEnded(e){this.emitter.off("callEnded",e)}updateClientState(e){var t;let i=this.callId?e.calls[this.callId]:void 0;const n=e.callsEnded?Si(e.callsEnded):void 0,r=this.state.page,a={environmentInfo:this.state.environmentInfo,unsupportedBrowserVersionOptedIn:this.state.unsupportedBrowserVersionsAllowed},s=(null==i?void 0:i.transfer.acceptedTransfers)?yi(i.transfer.acceptedTransfers):void 0,o=s?e.calls[s.callId]:void 0,l=((e,t,i,n)=>{if(Yt(null==n?void 0:n.environmentInfo,null==n?void 0:n.unsupportedBrowserVersionOptedIn))return"unsupportedEnvironment";if(void 0!==i)return"transferring";if(e)return w(null==e?void 0:e.state)?"lobby":"LocalHold"===(null==e?void 0:e.state)?"hold":"Disconnecting"===(null==e?void 0:e.state)?"leaving":I(null==e?void 0:e.state)?"call":"configuration";if(t){const e=(e=>{var t,i,n;const r=Array.from(Object.values(e.remoteParticipantsEnded));if(1===r.length&&m(r[0].identifier)&&(null===(t=e.callEndReason)||void 0===t?void 0:t.subCode)!==$t)return Wt.LEFT_CALL;if((null===(i=e.callEndReason)||void 0===i?void 0:i.subCode)&&5854===e.callEndReason.subCode)return Wt.ACCESS_DENIED;if((null===(n=e.callEndReason)||void 0===n?void 0:n.subCode)&&Gt.includes(e.callEndReason.subCode))return Wt.REMOVED_FROM_CALL;if(e.callEndReason)return Wt.LEFT_CALL;throw new Error("No matching call end reason")})(t);switch(e){case Wt.ACCESS_DENIED:return"accessDeniedTeamsMeeting";case Wt.REMOVED_FROM_CALL:return"removedFromCall";case Wt.LEFT_CALL:return t.diagnostics.network.latest.noNetwork?"joinCallFailedDueToNoNetwork":"leftCall"}}return"configuration"})(i,n,o,a);!qt(r)&&qt(l)&&(this.emitter.emit("callEnded",{callId:this.callId}),this.setCurrentCallId(void 0),i=void 0),this.state.page&&this.setState(Object.assign(Object.assign({},this.state),{userId:e.userId,displayName:null===(t=e.callAgent)||void 0===t?void 0:t.displayName,call:i,page:l,endedCall:n,devices:e.deviceManager,latestErrors:e.latestErrors,cameraStatus:(null==i?void 0:i.localVideoStreams.find((e=>"Video"===e.mediaStreamType)))||e.deviceManager.unparentedViews.find((e=>"Video"===e.mediaStreamType))?"On":"Off",acceptedTransferCallState:o}))}setAllowedUnsupportedBrowser(){this.setState(Object.assign(Object.assign({},this.state),{unsupportedBrowserVersionsAllowed:!0}))}setBackroundPickerImages(e){this.setState(Object.assign(Object.assign({},this.state),{videoBackgroundImages:e}))}setSelectedVideoBackgroundEffect(e){this.setState(Object.assign(Object.assign({},this.state),{selectedVideoBackgroundEffect:e}))}setAcceptedTransferCall(e){this.setState(Object.assign(Object.assign({},this.state),{acceptedTransferCallState:e}))}}const Si=e=>{var t,i,n,r;const a=Object.values(e);if(0===a.length)return;let s=a[0];for(const e of a.slice(1))(null!==(i=null===(t=e.endTime)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)>(null!==(r=null===(n=s.endTime)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&(s=e);return s},yi=e=>{var t,i,n,r;const a=Object.values(e);if(0===a.length)return;let s=a[0];for(const e of a.slice(1))(null!==(i=null===(t=e.timestamp)||void 0===t?void 0:t.getTime())&&void 0!==i?i:0)>(null!==(r=null===(n=s.timestamp)||void 0===n?void 0:n.getTime())&&void 0!==r?r:0)&&(s=e);return s};class Ci{get call(){return this._call}set call(e){this.resetDiagnosticsForwarder(e),this._call=e}constructor(e,t,i,n,r){var a;this.participantSubscribers=new Map,this.emitter=new L.EventEmitter,this.isMyMutedChanged=()=>{var e;this.emitter.emit("isMutedChanged",{participantId:this.getState().userId,isMuted:null===(e=this.call)||void 0===e?void 0:e.isMuted})},this.bindPublicMethods(),this.callClient=e,this.callAgent=i,this.targetCallees=!0===Xt(t)?t:void 0,this.locator=!1===Xt(t)?t:void 0,this.deviceManager=n;const s=!!this.locator&&"meetingLink"in this.locator,o=!!this.locator&&"roomId"in this.locator;this.onResolveVideoBackgroundEffectsDependency=null===(a=null==r?void 0:r.videoBackgroundOptions)||void 0===a?void 0:a.onResolveDependency,this.context=new vi(e.getState(),s,o,r,this.targetCallees),this.context.onCallEnded((e=>this.emitter.emit("callEnded",e)));const l=t=>{var i,n,r;this?((null===(i=this.call)||void 0===i?void 0:i.id)&&this.context.setCurrentCallId(this.call.id),("InLobby"===(null===(n=this.call)||void 0===n?void 0:n.state)||"Connected"===(null===(r=this.call)||void 0===r?void 0:r.state))&&this.callClient.getState().deviceManager.unparentedViews.length>0&&this.callClient.getState().deviceManager.unparentedViews.forEach((e=>{this.callClient.disposeView(void 0,void 0,e)})),this.context.updateClientState(t)):e.offStateChange(l)};if(this.handlers=hi(e,i,n,void 0,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency}),this.onClientStateChange=l,this.subscribeDeviceManagerEvents(),this.callClient.onStateChange(l),"CallAgent"===this.callAgent.kind){const e=e=>{var t;if(null===(t=this.call)||void 0===t?void 0:t.id){const t=e.removed.find((e=>{var t;return e.id===(null===(t=this.call)||void 0===t?void 0:t.id)}));if(t){const e=this.callClient.getState().callsEnded[t.id],n=yi(e.transfer.acceptedTransfers),r=i.calls.find((e=>e.id===(null==n?void 0:n.callId)));r&&this.processNewCall(r)}}};this.callAgent.on("callsUpdated",e)}if("TeamsCallAgent"===this.callAgent.kind){const e=e=>{var t;if(null===(t=this.call)||void 0===t?void 0:t.id){const t=e.removed.find((e=>{var t;return e.id===(null===(t=this.call)||void 0===t?void 0:t.id)}));if(t){const e=this.callClient.getState().callsEnded[t.id],n=yi(e.transfer.acceptedTransfers),r=i.calls.find((e=>e.id===(null==n?void 0:n.callId)));r&&this.processNewCall(r)}}};this.callAgent.on("callsUpdated",e)}}subscribeDeviceManagerEvents(){this.deviceManager.on("selectedMicrophoneChanged",(()=>{this.emitter.emit("selectedMicrophoneChanged")})),this.deviceManager.on("selectedSpeakerChanged",(()=>{this.emitter.emit("selectedSpeakerChanged")}))}bindPublicMethods(){this.onStateChange.bind(this),this.offStateChange.bind(this),this.getState.bind(this),this.dispose.bind(this),this.joinCall.bind(this),this.leaveCall.bind(this),this.setCamera.bind(this),this.setMicrophone.bind(this),this.setSpeaker.bind(this),this.askDevicePermission.bind(this),this.queryCameras.bind(this),this.queryMicrophones.bind(this),this.querySpeakers.bind(this),this.startCamera.bind(this),this.stopCamera.bind(this),this.mute.bind(this),this.unmute.bind(this),this.startCall.bind(this),this.startScreenShare.bind(this),this.stopScreenShare.bind(this),this.raiseHand.bind(this),this.onReactionClick.bind(this),this.lowerHand.bind(this),this.removeParticipant.bind(this),this.createStreamView.bind(this),this.disposeStreamView.bind(this),this.disposeScreenShareStreamView.bind(this),this.disposeRemoteVideoStreamView.bind(this),this.disposeLocalVideoStreamView.bind(this),this.on.bind(this),this.off.bind(this),this.processNewCall.bind(this),this.addParticipant.bind(this),this.holdCall.bind(this),this.resumeCall.bind(this),this.sendDtmfTone.bind(this),this.allowUnsupportedBrowserVersion.bind(this),this.startCaptions.bind(this),this.stopCaptions.bind(this),this.setSpokenLanguage.bind(this),this.setCaptionLanguage.bind(this),this.startVideoBackgroundEffect.bind(this),this.stopVideoBackgroundEffects.bind(this),this.updateBackgroundPickerImages.bind(this),this.submitSurvey.bind(this),this.startSpotlight.bind(this),this.stopSpotlight.bind(this),this.stopAllSpotlight.bind(this)}dispose(){this.resetDiagnosticsForwarder(),this.callClient.offStateChange(this.onClientStateChange),this.callAgent.dispose()}queryCameras(){return fi(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){const t=yield this.deviceManager.getCameras(),i=(new Date).getTime();return h.info("time to query cameras",i-e,"ms"),t}))))}))}queryMicrophones(){return fi(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){const t=yield this.deviceManager.getMicrophones(),i=(new Date).getTime();return h.info("time to query microphones",i-e,"ms"),t}))))}))}querySpeakers(){return fi(this,void 0,void 0,(function*(){const e=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){const t=(yield this.deviceManager.isSpeakerSelectionAvailable)?this.deviceManager.getSpeakers():[],i=(new Date).getTime();return h.info("time to query speakers",i-e,"ms"),t}))))}))}askDevicePermission(e){return fi(this,void 0,void 0,(function*(){const t=(new Date).getTime();return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.deviceManager.askDevicePermission(e);const i=(new Date).getTime();h.info("time to query askDevicePermissions",i-t,"ms")}))))}))}joinCall(e){var t,i;if(I(null!==(i=null===(t=this.getState().call)||void 0===t?void 0:t.state)&&void 0!==i?i:"None"))throw new Error("You are already in the call!");if(void 0===this.locator)throw new Error("Locator is not defined!");return this.teeErrorToEventEmitter((()=>{let t="On"===this.getState().cameraStatus,i=this.getState().isLocalPreviewMicrophoneEnabled;"boolean"==typeof e?i=e:"object"==typeof e&&(e.microphoneOn&&"keep"!==e.microphoneOn&&(i=e.microphoneOn),e.cameraOn&&"keep"!==e.cameraOn&&(t=e.cameraOn));const n={muted:!i},r=Zt(this.getState()),a=r&&t?{localVideoStreams:[new p.LocalVideoStream(r)]}:{},s=this._joinCall(n,a);return this.processNewCall(s),s}))}_joinCall(e,t){const i=!!this.locator&&"meetingLink"in this.locator;if(this.locator&&this.locator,Fe(this.callAgent)){if(i)return this.callAgent.join(this.locator,{audioOptions:e,videoOptions:t});throw new Error("Locator not supported by TeamsCallAgent")}return this.callAgent.join(this.locator,{audioOptions:e,videoOptions:t})}createStreamView(e,t){return fi(this,void 0,void 0,(function*(){return void 0===e?yield this.handlers.onCreateLocalStreamView(t):yield this.handlers.onCreateRemoteStreamView(e,t)}))}disposeStreamView(e){return fi(this,void 0,void 0,(function*(){void 0===e?yield this.handlers.onDisposeLocalStreamView():yield this.handlers.onDisposeRemoteStreamView(e)}))}disposeScreenShareStreamView(e){return fi(this,void 0,void 0,(function*(){yield this.handlers.onDisposeRemoteScreenShareStreamView(e)}))}disposeRemoteVideoStreamView(e){return fi(this,void 0,void 0,(function*(){yield this.handlers.onDisposeRemoteVideoStreamView(e)}))}disposeLocalVideoStreamView(){return fi(this,void 0,void 0,(function*(){yield this.handlers.onDisposeLocalStreamView()}))}leaveCall(e){return fi(this,void 0,void 0,(function*(){if("transferring"===this.getState().page){const e=this.callAgent.calls.filter((e=>{var t;return e.id===(null===(t=this.getState().acceptedTransferCallState)||void 0===t?void 0:t.id)}))[0];null==e||e.hangUp()}yield this.handlers.onHangUp(e),this.unsubscribeCallEvents(),this.handlers=hi(this.callClient,this.callAgent,this.deviceManager,this.call,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency}),this.call=void 0,this.stopCamera(),this.mute()}))}setCamera(e,t){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onSelectCamera(e,t)}))))}))}setMicrophone(e){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onSelectMicrophone(e)}))))}))}setSpeaker(e){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onSelectSpeaker(e)}))))}))}startCamera(e){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){if(!jt(this.getState())){{const e=this.getState().selectedVideoBackgroundEffect,t=Zt(this.getState());if(e&&t&&this.onResolveVideoBackgroundEffectsDependency){const i=new p.LocalVideoStream(t),n=((e,t)=>"blur"===(null==e?void 0:e.effectName)?t.createBackgroundBlurEffect():"replacement"===(null==e?void 0:e.effectName)?t.createBackgroundReplacementEffect({backgroundImageUrl:e.backgroundImageUrl}):void 0)(e,yield this.onResolveVideoBackgroundEffectsDependency());n?yield i.feature(p.Features.VideoEffects).startEffects(n):yield i.feature(p.Features.VideoEffects).stopEffects()}}yield this.handlers.onToggleCamera(e)}}))))}))}stopCamera(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){jt(this.getState())&&(yield this.handlers.onToggleCamera())}))))}))}mute(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){var e,t;this.context.setIsLocalMicrophoneEnabled(!1),I(null===(e=this.call)||void 0===e?void 0:e.state)&&!(null===(t=this.call)||void 0===t?void 0:t.isMuted)&&(yield this.handlers.onToggleMicrophone())}))))}))}unmute(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){var e,t,i;this.context.setIsLocalMicrophoneEnabled(!0),(I(null===(e=this.call)||void 0===e?void 0:e.state)||w(null===(t=this.call)||void 0===t?void 0:t.state))&&(null===(i=this.call)||void 0===i?void 0:i.isMuted)&&(yield this.handlers.onToggleMicrophone())}))))}))}startScreenShare(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){var e;(null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn)||(yield this.handlers.onToggleScreenShare())}))))}))}stopScreenShare(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){var e;(null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn)&&(yield this.handlers.onToggleScreenShare())}))))}))}raiseHand(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onToggleRaiseHand()}))))}))}lowerHand(){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onToggleRaiseHand()}))))}))}onReactionClick(e){return fi(this,void 0,void 0,(function*(){return yield this.asyncTeeErrorToEventEmitter((()=>fi(this,void 0,void 0,(function*(){yield this.handlers.onReactionClick(e)}))))}))}allowUnsupportedBrowserVersion(){this.context.setAllowedUnsupportedBrowser(),this.context.updateClientState(this.callClient.getState())}startVideoBackgroundEffect(e){return fi(this,void 0,void 0,(function*(){if(this.isBlurEffect(e)){const t=e;yield this.handlers.onBlurVideoBackground(t)}else if(this.isReplacementEffect(e)){const t=e;yield this.handlers.onReplaceVideoBackground(t)}}))}stopVideoBackgroundEffects(){return fi(this,void 0,void 0,(function*(){yield this.handlers.onRemoveVideoBackgroundEffects()}))}updateBackgroundPickerImages(e){this.context.setBackroundPickerImages(e)}updateSelectedVideoBackgroundEffect(e){this.context.setSelectedVideoBackgroundEffect(e)}startCall(e,t){var i,n;if(I(null!==(n=null===(i=this.getState().call)||void 0===i?void 0:i.state)&&void 0!==n?n:"None"))throw new Error("You are already in the call.");const r="On"===this.getState().cameraStatus,a=Zt(this.getState()),s=a?{videoOptions:r?{localVideoStreams:[new p.LocalVideoStream(a)]}:void 0}:{},o=Object.assign(Object.assign({},s),t),l=e.map((e=>{const i=T(e);if("phoneNumber"in i&&void 0===(null==t?void 0:t.alternateCallerId))throw new Error("Unable to start call, PSTN user present with no alternateCallerId.");return i}));this.context.setTargetCallee(l);const c=this.handlers.onStartCall(l,o);if(!c)throw new Error("Unable to start call.");return this.processNewCall(c),c}processNewCall(e){this.call=e,this.context.setCurrentCallId(e.id),this.context.updateClientState(this.callClient.getState()),this.handlers=hi(this.callClient,this.callAgent,this.deviceManager,this.call,{onResolveVideoBackgroundEffectsDependency:this.onResolveVideoBackgroundEffectsDependency}),this.subscribeCallEvents()}isBlurEffect(e){return"blur"===e.effectName}isReplacementEffect(e){return"replacement"===e.effectName}removeParticipant(e){return fi(this,void 0,void 0,(function*(){let t=e;t=T(e),this.handlers.onRemoveParticipant(t)}))}addParticipant(e,t){return fi(this,void 0,void 0,(function*(){m(e)&&t?this.handlers.onAddParticipant(e,t):g(e)&&this.handlers.onAddParticipant(e)}))}holdCall(){return fi(this,void 0,void 0,(function*(){var e,t;"LocalHold"!==(null===(e=this.call)||void 0===e?void 0:e.state)&&((null===(t=this.call)||void 0===t?void 0:t.isLocalVideoStarted)?this.stopCamera().then((()=>{this.handlers.onToggleHold()})):this.handlers.onToggleHold())}))}resumeCall(){return fi(this,void 0,void 0,(function*(){var e;"LocalHold"===(null===(e=this.call)||void 0===e?void 0:e.state)&&this.handlers.onToggleHold().then((()=>{var e;!1===(null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Capabilities).capabilities.turnVideoOn.isPresent)&&this.stopCamera()}))}))}sendDtmfTone(e){return fi(this,void 0,void 0,(function*(){this.handlers.onSendDtmfTone(e)}))}startCaptions(e){return fi(this,void 0,void 0,(function*(){this.handlers.onStartCaptions(e)}))}stopCaptions(){return fi(this,void 0,void 0,(function*(){this.handlers.onStopCaptions()}))}setCaptionLanguage(e){return fi(this,void 0,void 0,(function*(){this.handlers.onSetCaptionLanguage(e)}))}setSpokenLanguage(e){return fi(this,void 0,void 0,(function*(){this.handlers.onSetSpokenLanguage(e)}))}submitSurvey(e){return fi(this,void 0,void 0,(function*(){return this.handlers.onSubmitSurvey(e)}))}startSpotlight(e){return fi(this,void 0,void 0,(function*(){this.handlers.onStartSpotlight(e)}))}stopSpotlight(e){return fi(this,void 0,void 0,(function*(){this.handlers.onStopSpotlight(e)}))}stopAllSpotlight(){return fi(this,void 0,void 0,(function*(){this.handlers.onStopAllSpotlight()}))}getState(){return this.context.getState()}onStateChange(e){this.context.onStateChange(e)}offStateChange(e){this.context.offStateChange(e)}on(e,t){this.emitter.on(e,t)}subscribeToCaptionEvents(){var e,t;if(this.call&&"Connected"===this.call.state)if(this.context.getState().isTeamsCall){const t=null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Captions).captions;t.on("CaptionsReceived",this.teamsCaptionsReceived.bind(this)),t.on("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),t.on("CaptionLanguageChanged",this.isCaptionLanguageChanged.bind(this)),t.on("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}else{const e=null===(t=this.call)||void 0===t?void 0:t.feature(p.Features.Captions).captions;e.on("CaptionsReceived",this.captionsReceived.bind(this)),e.on("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.on("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}}unsubscribeFromCaptionEvents(){var e,t,i;if(this.call&&"Connected"===this.call.state){if(this.context.getState().isTeamsCall){const t=null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Captions).captions;t.off("CaptionsReceived",this.teamsCaptionsReceived.bind(this)),t.off("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),t.off("CaptionLanguageChanged",this.isCaptionLanguageChanged.bind(this)),t.off("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}else{const e=null===(t=this.call)||void 0===t?void 0:t.feature(p.Features.Captions).captions;e.off("CaptionsReceived",this.captionsReceived.bind(this)),e.off("CaptionsActiveChanged",this.isCaptionsActiveChanged.bind(this)),e.off("SpokenLanguageChanged",this.isSpokenLanguageChanged.bind(this))}null===(i=this.call)||void 0===i||i.off("stateChanged",this.subscribeToCaptionEvents.bind(this))}}subscribeCallEvents(){var e,t,i,n,r,a,s,o,l;this.call&&(this.callingSoundSubscriber=new gi(this.call,this.getState().targetCallees,this.getState().sounds)),null===(e=this.call)||void 0===e||e.on("remoteParticipantsUpdated",this.onRemoteParticipantsUpdated.bind(this)),null===(t=this.call)||void 0===t||t.on("isMutedChanged",this.isMyMutedChanged.bind(this)),null===(i=this.call)||void 0===i||i.on("isScreenSharingOnChanged",this.isScreenSharingOnChanged.bind(this)),null===(n=this.call)||void 0===n||n.on("idChanged",this.callIdChanged.bind(this)),null===(r=this.call)||void 0===r||r.on("stateChanged",this.subscribeToCaptionEvents.bind(this)),null===(a=this.call)||void 0===a||a.on("roleChanged",this.roleChanged.bind(this)),null===(s=this.call)||void 0===s||s.feature(p.Features.Transfer).on("transferAccepted",this.transferAccepted.bind(this)),null===(o=this.call)||void 0===o||o.feature(p.Features.Capabilities).on("capabilitiesChanged",this.capabilitiesChanged.bind(this)),null===(l=this.call)||void 0===l||l.feature(p.Features.Spotlight).on("spotlightChanged",this.spotlightChanged.bind(this))}unsubscribeCallEvents(){var e,t,i,n,r;for(const e of this.participantSubscribers.values())e.unsubscribeAll();this.participantSubscribers.clear(),null===(e=this.call)||void 0===e||e.off("remoteParticipantsUpdated",this.onRemoteParticipantsUpdated.bind(this)),null===(t=this.call)||void 0===t||t.off("isMutedChanged",this.isMyMutedChanged.bind(this)),null===(i=this.call)||void 0===i||i.off("isScreenSharingOnChanged",this.isScreenSharingOnChanged.bind(this)),null===(n=this.call)||void 0===n||n.off("idChanged",this.callIdChanged.bind(this)),null===(r=this.call)||void 0===r||r.off("roleChanged",this.roleChanged.bind(this)),this.unsubscribeFromCaptionEvents(),this.callingSoundSubscriber&&this.callingSoundSubscriber.unsubscribeAll()}onRemoteParticipantsUpdated({added:e,removed:t}){e&&e.length>0&&this.emitter.emit("participantsJoined",{joined:e}),t&&t.length>0&&this.emitter.emit("participantsLeft",{removed:t}),e.forEach((e=>{this.participantSubscribers.set(_(e.identifier),new ei(e,this.emitter))})),t.forEach((e=>{const t=this.participantSubscribers.get(_(e.identifier));t&&t.unsubscribeAll(),this.participantSubscribers.delete(_(e.identifier))}))}isScreenSharingOnChanged(){var e;this.emitter.emit("isLocalScreenSharingActiveChanged",{isScreenSharingOn:null===(e=this.call)||void 0===e?void 0:e.isScreenSharingOn})}teamsCaptionsReceived(e){this.emitter.emit("captionsReceived",{captionsInfo:e})}captionsReceived(e){this.emitter.emit("captionsReceived",{captionsInfo:e})}isCaptionsActiveChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Captions).captions;this.emitter.emit("isCaptionsActiveChanged",{isActive:t.isCaptionsFeatureActive})}isSpokenLanguageChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Captions).captions;this.emitter.emit("isSpokenLanguageChanged",{activeSpokenLanguage:t.activeSpokenLanguage})}isCaptionLanguageChanged(){var e;const t=null===(e=this.call)||void 0===e?void 0:e.feature(p.Features.Captions).captions;this.emitter.emit("isCaptionLanguageChanged",{activeCaptionLanguage:t.activeCaptionLanguage})}transferAccepted(e){this.emitter.emit("transferAccepted",e)}capabilitiesChanged(e){var t,i,n,r,a;!1===(null===(t=e.newValue.turnVideoOn)||void 0===t?void 0:t.isPresent)&&("LocalHold"!==(null===(i=this.call)||void 0===i?void 0:i.state)&&"RemoteHold"!==(null===(n=this.call)||void 0===n?void 0:n.state)&&this.stopCamera(),this.disposeLocalVideoStreamView()),!1===(null===(r=e.newValue.unmuteMic)||void 0===r?void 0:r.isPresent)&&this.mute(),!1===(null===(a=e.newValue.shareScreen)||void 0===a?void 0:a.isPresent)&&this.stopScreenShare(),this.emitter.emit("capabilitiesChanged",e)}roleChanged(){var e,t;"Consumer"===(null===(e=this.call)||void 0===e?void 0:e.role)&&(null===(t=this.call)||void 0===t||t.feature(p.Features.RaiseHand).lowerHand()),this.emitter.emit("roleChanged")}spotlightChanged(e){this.emitter.emit("spotlightChanged",e)}callIdChanged(){var e;(null===(e=this.call)||void 0===e?void 0:e.id)&&this.emitter.emit("callIdChanged",{callId:this.call.id})}resetDiagnosticsForwarder(e){this.diagnosticsForwarder&&this.diagnosticsForwarder.unsubscribe(),e&&(this.diagnosticsForwarder=new ti(this.emitter,e))}off(e,t){this.emitter.off(e,t)}asyncTeeErrorToEventEmitter(e){return fi(this,void 0,void 0,(function*(){try{return yield e()}catch(e){throw Ei(e)&&this.emitter.emit("error",e),e}}))}teeErrorToEventEmitter(e){try{return e()}catch(e){throw Ei(e)&&this.emitter.emit("error",e),e}}}const _i=e=>fi(void 0,[e],void 0,(function*({userId:e,displayName:t,credential:i,locator:n,targetCallees:r,alternateCallerId:a,options:s,telemetryImplementationHint:o="Call"}){if(!(g(l=e)||m(l)||f(l)||(e=>"string"==typeof e.id)(l)))throw new Error("Invalid identifier. Please provide valid identifier object.");var l;const c=((e,t,i="StatefulComponents")=>(ke.info(`Creating calling stateful client using library version: ${Dt(i)}`),Ut(new p.CallClient(Bt(i,null==t?void 0:t.callClientOptions)),new je(S(e.userId),null==t?void 0:t.maxStateChangeListeners,e.alternateCallerId),new Pt)))({userId:e,alternateCallerId:a},void 0,o),d=yield c.createCallAgent(i,{displayName:t});let u;return u=function(e,t,i,n){return fi(this,void 0,void 0,(function*(){const r=yield e.getDeviceManager();return yield Promise.all([r.getCameras(),r.getMicrophones()]),r.isSpeakerSelectionAvailable&&(yield r.getSpeakers()),yield e.feature(p.Features.DebugInfo).getEnvironmentInfo(),Xt(i),new Ci(e,i,t,r,n)}))}(c,d,n||r,s),u}));const Ei=e=>"target"in e&&"innerError"in e;var Ti=function(e,t){return Ti=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},Ti(e,t)};function bi(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}Ti(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var Ii=function(){return Ii=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},Ii.apply(this,arguments)};function wi(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(n=Object.getOwnPropertySymbols(e);r<n.length;r++)t.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]])}return i}function Ri(e,t,i,n){var r,a=arguments.length,s=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(s=(a<3?r(s):a>3?r(t,i,s):r(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s}function Ai(e,t,i){if(i||2===arguments.length)for(var n,r=0,a=t.length;r<a;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var Pi,Mi="__stylesheet__",ki="undefined"!=typeof navigator&&/rv:11.0/.test(navigator.userAgent),Di={};try{Di=window||{}}catch(Gi){}var Oi,Ni=function(){function e(e,t){var i,n,r,a,s,o;this._rules=[],this._preservedRules=[],this._counter=0,this._keyToClassName={},this._onInsertRuleCallbacks=[],this._onResetCallbacks=[],this._classNameToArgs={},this._config=Ii({injectionMode:"undefined"==typeof document?0:1,defaultPrefix:"css",namespace:void 0,cspSettings:void 0},e),this._classNameToArgs=null!==(i=null==t?void 0:t.classNameToArgs)&&void 0!==i?i:this._classNameToArgs,this._counter=null!==(n=null==t?void 0:t.counter)&&void 0!==n?n:this._counter,this._keyToClassName=null!==(a=null!==(r=this._config.classNameCache)&&void 0!==r?r:null==t?void 0:t.keyToClassName)&&void 0!==a?a:this._keyToClassName,this._preservedRules=null!==(s=null==t?void 0:t.preservedRules)&&void 0!==s?s:this._preservedRules,this._rules=null!==(o=null==t?void 0:t.rules)&&void 0!==o?o:this._rules}return e.getInstance=function(){if(!(Pi=Di[Mi])||Pi._lastStyleElement&&Pi._lastStyleElement.ownerDocument!==document){var t=(null==Di?void 0:Di.FabricConfig)||{},i=new e(t.mergeStyles,t.serializedStylesheet);Pi=i,Di[Mi]=i}return Pi},e.prototype.serialize=function(){return JSON.stringify({classNameToArgs:this._classNameToArgs,counter:this._counter,keyToClassName:this._keyToClassName,preservedRules:this._preservedRules,rules:this._rules})},e.prototype.setConfig=function(e){this._config=Ii(Ii({},this._config),e)},e.prototype.onReset=function(e){var t=this;return this._onResetCallbacks.push(e),function(){t._onResetCallbacks=t._onResetCallbacks.filter((function(t){return t!==e}))}},e.prototype.onInsertRule=function(e){var t=this;return this._onInsertRuleCallbacks.push(e),function(){t._onInsertRuleCallbacks=t._onInsertRuleCallbacks.filter((function(t){return t!==e}))}},e.prototype.getClassName=function(e){var t=this._config.namespace,i=e||this._config.defaultPrefix;return"".concat(t?t+"-":"").concat(i,"-").concat(this._counter++)},e.prototype.cacheClassName=function(e,t,i,n){this._keyToClassName[t]=e,this._classNameToArgs[e]={args:i,rules:n}},e.prototype.classNameFromKey=function(e){return this._keyToClassName[e]},e.prototype.getClassNameCache=function(){return this._keyToClassName},e.prototype.argsFromClassName=function(e){var t=this._classNameToArgs[e];return t&&t.args},e.prototype.insertedRulesFromClassName=function(e){var t=this._classNameToArgs[e];return t&&t.rules},e.prototype.insertRule=function(e,t){var i=this._config.injectionMode,n=0!==i?this._getStyleElement():void 0;if(t&&this._preservedRules.push(e),n)switch(i){case 1:var r=n.sheet;try{r.insertRule(e,r.cssRules.length)}catch(e){}break;case 2:n.appendChild(document.createTextNode(e))}else this._rules.push(e);this._config.onInsertRule&&this._config.onInsertRule(e),this._onInsertRuleCallbacks.forEach((function(e){return e()}))},e.prototype.getRules=function(e){return(e?this._preservedRules.join(""):"")+this._rules.join("")},e.prototype.reset=function(){this._rules=[],this._counter=0,this._classNameToArgs={},this._keyToClassName={},this._onResetCallbacks.forEach((function(e){return e()}))},e.prototype.resetKeys=function(){this._keyToClassName={}},e.prototype._getStyleElement=function(){var e=this;return this._styleElement||"undefined"==typeof document||(this._styleElement=this._createStyleElement(),ki||window.requestAnimationFrame((function(){e._styleElement=void 0}))),this._styleElement},e.prototype._createStyleElement=function(){var e=document.head,t=document.createElement("style"),i=null;t.setAttribute("data-merge-styles","true");var n=this._config.cspSettings;if(n&&n.nonce&&t.setAttribute("nonce",n.nonce),this._lastStyleElement)i=this._lastStyleElement.nextElementSibling;else{var r=this._findPlaceholderStyleTag();i=r?r.nextElementSibling:e.childNodes[0]}return e.insertBefore(t,e.contains(i)?i:null),this._lastStyleElement=t,t},e.prototype._findPlaceholderStyleTag=function(){var e=document.head;return e?e.querySelector("style[data-merge-styles]"):null},e}();function Li(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=[],n=[],r=Ni.getInstance();return function e(t){for(var a=0,s=t;a<s.length;a++){var o=s[a];if(o)if("string"==typeof o)if(o.indexOf(" ")>=0)e(o.split(" "));else{var l=r.argsFromClassName(o);l?e(l):-1===i.indexOf(o)&&i.push(o)}else Array.isArray(o)?e(o):"object"==typeof o&&n.push(o)}}(e),{classes:i,objects:n}}function xi(e){Oi!==e&&(Oi=e)}function Fi(){return void 0===Oi&&(Oi="undefined"!=typeof document&&!!document.documentElement&&"rtl"===document.documentElement.getAttribute("dir")),Oi}function Ui(){return{rtl:Fi()}}Oi=Fi();var Bi,Vi={},Hi={"user-select":1};function $i(e,t){var i=function(){var e;if(!Bi){var t="undefined"!=typeof document?document:void 0,i="undefined"!=typeof navigator?navigator:void 0,n=null===(e=null==i?void 0:i.userAgent)||void 0===e?void 0:e.toLowerCase();Bi=t?{isWebkit:!(!t||!("WebkitAppearance"in t.documentElement.style)),isMoz:!!(n&&n.indexOf("firefox")>-1),isOpera:!!(n&&n.indexOf("opera")>-1),isMs:!(!i||!/rv:11.0/i.test(i.userAgent)&&!/Edge\/\d./i.test(navigator.userAgent))}:{isWebkit:!0,isMoz:!0,isOpera:!0,isMs:!0}}return Bi}(),n=e[t];if(Hi[n]){var r=e[t+1];Hi[n]&&(i.isWebkit&&e.push("-webkit-"+n,r),i.isMoz&&e.push("-moz-"+n,r),i.isMs&&e.push("-ms-"+n,r),i.isOpera&&e.push("-o-"+n,r))}}var Gi,ji=["column-count","font-weight","flex","flex-grow","flex-shrink","fill-opacity","opacity","order","z-index","zoom"];function zi(e,t){var i=e[t],n=e[t+1];if("number"==typeof n){var r=ji.indexOf(i)>-1,a=i.indexOf("--")>-1,s=r||a?"":"px";e[t+1]="".concat(n).concat(s)}}var Wi="left",qi="right",Ki="@noflip",Ji=((Gi={})[Wi]=qi,Gi[qi]=Wi,Gi),Yi={"w-resize":"e-resize","sw-resize":"se-resize","nw-resize":"ne-resize"};function Qi(e,t,i){if(e.rtl){var n=t[i];if(!n)return;var r=t[i+1];if("string"==typeof r&&r.indexOf(Ki)>=0)t[i+1]=r.replace(/\s*(?:\/\*\s*)?\@noflip\b(?:\s*\*\/)?\s*?/g,"");else if(n.indexOf(Wi)>=0)t[i]=n.replace(Wi,qi);else if(n.indexOf(qi)>=0)t[i]=n.replace(qi,Wi);else if(String(r).indexOf(Wi)>=0)t[i+1]=r.replace(Wi,qi);else if(String(r).indexOf(qi)>=0)t[i+1]=r.replace(qi,Wi);else if(Ji[n])t[i]=Ji[n];else if(Yi[r])t[i+1]=Yi[r];else switch(n){case"margin":case"padding":t[i+1]=function(e){if("string"==typeof e){var t=e.split(" ");if(4===t.length)return"".concat(t[0]," ").concat(t[3]," ").concat(t[2]," ").concat(t[1])}return e}(r);break;case"box-shadow":t[i+1]=function(e,t){var i=e.split(" "),n=parseInt(i[0],10);return i[0]=i[0].replace(String(n),String(-1*n)),i.join(" ")}(r)}}}var Zi="displayName",Xi=/\:global\((.+?)\)/g;function en(e,t){return e.indexOf(":global(")>=0?e.replace(Xi,"$1"):0===e.indexOf(":")?t+e:e.indexOf("&")<0?t+" "+e:e}function tn(e,t,i,n){void 0===t&&(t={__order:[]}),0===i.indexOf("@")?nn([n],t,i=i+"{"+e):i.indexOf(",")>-1?function(e){if(!Xi.test(e))return e;for(var t=[],i=/\:global\((.+?)\)/g,n=null;n=i.exec(e);)n[1].indexOf(",")>-1&&t.push([n.index,n.index+n[0].length,n[1].split(",").map((function(e){return":global(".concat(e.trim(),")")})).join(", ")]);return t.reverse().reduce((function(e,t){var i=t[0],n=t[1],r=t[2];return e.slice(0,i)+r+e.slice(n)}),e)}(i).split(",").map((function(e){return e.trim()})).forEach((function(i){return nn([n],t,en(i,e))})):nn([n],t,en(i,e))}function nn(e,t,i){void 0===t&&(t={__order:[]}),void 0===i&&(i="&");var n=Ni.getInstance(),r=t[i];r||(r={},t[i]=r,t.__order.push(i));for(var a=0,s=e;a<s.length;a++){var o=s[a];if("string"==typeof o){var l=n.argsFromClassName(o);l&&nn(l,t,i)}else if(Array.isArray(o))nn(o,t,i);else for(var c in o)if(o.hasOwnProperty(c)){var d=o[c];if("selectors"===c){var u=o.selectors;for(var h in u)u.hasOwnProperty(h)&&tn(i,t,h,u[h])}else"object"==typeof d?null!==d&&tn(i,t,c,d):void 0!==d&&("margin"===c||"padding"===c?rn(r,c,d):r[c]=d)}}return t}function rn(e,t,i){var n="string"==typeof i?function(e){for(var t=[],i=0,n=0,r=0;r<e.length;r++)switch(e[r]){case"(":n++;break;case")":n&&n--;break;case"\t":case" ":n||(r>i&&t.push(e.substring(i,r)),i=r+1)}return i<e.length&&t.push(e.substring(i)),t}(i):[i];0===n.length&&n.push(i),"!important"===n[n.length-1]&&(n=n.slice(0,-1).map((function(e){return e+" !important"}))),e[t+"Top"]=n[0],e[t+"Right"]=n[1]||n[0],e[t+"Bottom"]=n[2]||n[0],e[t+"Left"]=n[3]||n[1]||n[0]}function an(e,t){return t<=0?"":1===t?e:e+an(e,t-1)}function sn(e,t){if(!t)return"";var i,n,r,a=[];for(var s in t)t.hasOwnProperty(s)&&s!==Zi&&void 0!==t[s]&&a.push(s,t[s]);for(var o=0;o<a.length;o+=2)r=void 0,"-"!==(r=(i=a)[n=o]).charAt(0)&&(i[n]=Vi[r]=Vi[r]||r.replace(/([A-Z])/g,"-$1").toLowerCase()),zi(a,o),Qi(e,a,o),$i(a,o);for(o=1;o<a.length;o+=4)a.splice(o,1,":",a[o],";");return a.join("")}function on(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=nn(t),r=function(e,t){for(var i=[e.rtl?"rtl":"ltr"],n=!1,r=0,a=t.__order;r<a.length;r++){var s=a[r];i.push(s);var o=t[s];for(var l in o)o.hasOwnProperty(l)&&void 0!==o[l]&&(n=!0,i.push(l,o[l]))}return n?i.join(""):void 0}(e,n);if(r){var a=Ni.getInstance(),s={className:a.classNameFromKey(r),key:r,args:t};if(!s.className){s.className=a.getClassName(function(e){var t=e&&e["&"];return t?t.displayName:void 0}(n));for(var o=[],l=0,c=n.__order;l<c.length;l++){var d=c[l];o.push(d,sn(e,n[d]))}s.rulesToInsert=o}return s}}function ln(e,t){void 0===t&&(t=1);var i=Ni.getInstance(),n=e.className,r=e.key,a=e.args,s=e.rulesToInsert;if(s){for(var o=0;o<s.length;o+=2){var l=s[o+1];if(l){var c=s[o];c=c.replace(/&/g,an(".".concat(e.className),t));var d="".concat(c,"{").concat(l,"}").concat(0===c.indexOf("@")?"}":"");i.insertRule(d)}}i.cacheClassName(n,r,a,s)}}function cn(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return dn(e,Ui())}function dn(e,t){var i=Li(e instanceof Array?e:[e]),n=i.classes,r=i.objects;return r.length&&n.push(function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=on.apply(void 0,Ai([e],t,!1));return n?(ln(n,e.specificityMultiplier),n.className):""}(t||{},r)),n.join(" ")}var un=!1,hn=0,pn={empty:!0},gn={},mn="undefined"==typeof WeakMap?null:WeakMap;function fn(){hn++}function vn(e,t,i){if(void 0===t&&(t=100),void 0===i&&(i=!1),!mn)return e;if(!un){var n=Ni.getInstance();n&&n.onReset&&Ni.getInstance().onReset(fn),un=!0}var r,a=0,s=hn;return function(){for(var n=[],o=0;o<arguments.length;o++)n[o]=arguments[o];var l,c=r;(void 0===r||s!==hn||t>0&&a>t)&&(r=yn(),a=0,s=hn),c=r;for(var d=0;d<n.length;d++){var u=(l=n[d])?"object"==typeof l||"function"==typeof l?l:(gn[l]||(gn[l]={val:l}),gn[l]):pn;c.map.has(u)||c.map.set(u,yn()),c=c.map.get(u)}return c.hasOwnProperty("value")||(c.value=e.apply(void 0,n),a++),!i||null!==c.value&&void 0!==c.value||(c.value=e.apply(void 0,n)),c.value}}function Sn(e){if(!mn)return e;var t=new mn;return function(i){if(!i||"function"!=typeof i&&"object"!=typeof i)return e(i);if(t.has(i))return t.get(i);var n=e(i);return t.set(i,n),n}}function yn(){return{map:mn?new mn:null}}function Cn(){return"undefined"!=typeof window&&!(!window.document||!window.document.createElement)}function _n(e){if(Cn()&&"undefined"!=typeof document){var t=e;return t&&t.ownerDocument?t.ownerDocument:document}}var En=void 0;try{En=window}catch(e){}function Tn(e){if(Cn()&&void 0!==En){var t=e;return t&&t.ownerDocument&&t.ownerDocument.defaultView?t.ownerDocument.defaultView:En}}function bn(e){var t=null;try{var i=Tn();t=i?i.sessionStorage.getItem(e):null}catch(e){}return t}var In,wn="isRTL";function Rn(e){if(void 0===e&&(e={}),void 0!==e.rtl)return e.rtl;if(void 0===In){var t=bn(wn);null!==t&&function(e,t){void 0===t&&(t=!1);var i=_n();i&&i.documentElement.setAttribute("dir",e?"rtl":"ltr"),t&&function(e,t){var i;try{null===(i=Tn())||void 0===i||i.sessionStorage.setItem(e,t)}catch(e){}}(wn,e?"1":"0"),xi(In=e)}(In="1"===t);var i=_n();void 0===In&&i&&xi(In="rtl"===(i.body&&i.body.getAttribute("dir")||i.documentElement.getAttribute("dir")))}return!!In}var An=Ii;function Pn(i,n){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];var s=i;return s.isSlot?0===(r=e.Children.toArray(r)).length?s(n):s(Ii(Ii({},n),{children:r})):e.createElement.apply(t,Ai([i,n],r,!1))}function Mn(t,i){void 0===i&&(i={});var n=i.defaultProp,r=void 0===n?"children":n;return function(i,n,a,s,o){if(e.isValidElement(n))return n;var l=function(e,t){var i,n;return"string"==typeof t||"number"==typeof t||"boolean"==typeof t?((i={})[e]=t,n=i):n=t,n}(r,n),c=function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];for(var r={},a=[],s=0,o=i;s<o.length;s++){var l=o[s];a.push(l&&l.className),An(r,l)}return r.className=dn([e,a],{rtl:Rn(t)}),r}(s,o,i,l);if(a){if(a.component){var d=a.component;return e.createElement(d,Ii({},c))}if(a.render)return a.render(c,t)}return e.createElement(t,Ii({},c))}}var kn=vn((function(e){return Mn(e)}));function Dn(e,t){var i={},n=e,r=function(e){if(t.hasOwnProperty(e)){var r=function(i){for(var r=[],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(r.length>0)throw new Error("Any module using getSlots must use withSlots. Please see withSlots javadoc for more info.");return function(e,t,i,n,r,a){return void 0!==e.create?e.create(t,i,n,r):kn(e)(t,i,n,r,a)}(t[e],i,n[e],n.slots&&n.slots[e],n._defaultStyles&&n._defaultStyles[e],n.theme)};r.isSlot=!0,i[e]=r}};for(var a in t)r(a);return i}function On(e){var t=Ni.getInstance(),i=[];for(var n in e)e.hasOwnProperty(n)&&i.push(n,"{",sn(Ui(),e[n]),"}");var r=i.join(""),a=t.classNameFromKey(r);if(a)return a;var s=t.getClassName();return t.insertRule("@keyframes ".concat(s,"{").concat(r,"}"),!0),t.cacheClassName(s,r,[],["keyframes",r]),s}var Nn="cubic-bezier(.1,.9,.2,1)",Ln="cubic-bezier(.1,.25,.75,.9)",xn="0.167s",Fn="0.267s",Un="0.367s",Bn="0.467s",Vn=On({from:{opacity:0},to:{opacity:1}}),Hn=On({from:{opacity:1},to:{opacity:0,visibility:"hidden"}}),$n=Tr(-10),Gn=Tr(-20),jn=Tr(-40),zn=Tr(-400),Wn=Tr(10),qn=Tr(20),Kn=Tr(40),Jn=Tr(400),Yn=br(10),Qn=br(20),Zn=br(-10),Xn=br(-20),er=Ir(10),tr=Ir(20),ir=Ir(40),nr=Ir(400),rr=Ir(-10),ar=Ir(-20),sr=Ir(-40),or=Ir(-400),lr=wr(-10),cr=wr(-20),dr=wr(10),ur=wr(20),hr=On({from:{transform:"scale3d(.98,.98,1)"},to:{transform:"scale3d(1,1,1)"}}),pr=On({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(.98,.98,1)"}}),gr=On({from:{transform:"scale3d(1.03,1.03,1)"},to:{transform:"scale3d(1,1,1)"}}),mr=On({from:{transform:"scale3d(1,1,1)"},to:{transform:"scale3d(1.03,1.03,1)"}}),fr=On({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(90deg)"}}),vr=On({from:{transform:"rotateZ(0deg)"},to:{transform:"rotateZ(-90deg)"}}),Sr=Ln,yr=Fn,Cr=Un,_r={slideRightIn10:Er("".concat(Vn,",").concat($n),Un,Nn),slideRightIn20:Er("".concat(Vn,",").concat(Gn),Un,Nn),slideRightIn40:Er("".concat(Vn,",").concat(jn),Un,Nn),slideRightIn400:Er("".concat(Vn,",").concat(zn),Un,Nn),slideLeftIn10:Er("".concat(Vn,",").concat(Wn),Un,Nn),slideLeftIn20:Er("".concat(Vn,",").concat(qn),Un,Nn),slideLeftIn40:Er("".concat(Vn,",").concat(Kn),Un,Nn),slideLeftIn400:Er("".concat(Vn,",").concat(Jn),Un,Nn),slideUpIn10:Er("".concat(Vn,",").concat(Yn),Un,Nn),slideUpIn20:Er("".concat(Vn,",").concat(Qn),Un,Nn),slideDownIn10:Er("".concat(Vn,",").concat(Zn),Un,Nn),slideDownIn20:Er("".concat(Vn,",").concat(Xn),Un,Nn),slideRightOut10:Er("".concat(Hn,",").concat(er),Un,Nn),slideRightOut20:Er("".concat(Hn,",").concat(tr),Un,Nn),slideRightOut40:Er("".concat(Hn,",").concat(ir),Un,Nn),slideRightOut400:Er("".concat(Hn,",").concat(nr),Un,Nn),slideLeftOut10:Er("".concat(Hn,",").concat(rr),Un,Nn),slideLeftOut20:Er("".concat(Hn,",").concat(ar),Un,Nn),slideLeftOut40:Er("".concat(Hn,",").concat(sr),Un,Nn),slideLeftOut400:Er("".concat(Hn,",").concat(or),Un,Nn),slideUpOut10:Er("".concat(Hn,",").concat(lr),Un,Nn),slideUpOut20:Er("".concat(Hn,",").concat(cr),Un,Nn),slideDownOut10:Er("".concat(Hn,",").concat(dr),Un,Nn),slideDownOut20:Er("".concat(Hn,",").concat(ur),Un,Nn),scaleUpIn100:Er("".concat(Vn,",").concat(hr),Un,Nn),scaleDownIn100:Er("".concat(Vn,",").concat(gr),Un,Nn),scaleUpOut103:Er("".concat(Hn,",").concat(mr),xn,Ln),scaleDownOut98:Er("".concat(Hn,",").concat(pr),xn,Ln),fadeIn100:Er(Vn,xn,Ln),fadeIn200:Er(Vn,Fn,Ln),fadeIn400:Er(Vn,Un,Ln),fadeIn500:Er(Vn,Bn,Ln),fadeOut100:Er(Hn,xn,Ln),fadeOut200:Er(Hn,Fn,Ln),fadeOut400:Er(Hn,Un,Ln),fadeOut500:Er(Hn,Bn,Ln),rotate90deg:Er(fr,"0.1s",Ln),rotateN90deg:Er(vr,"0.1s",Ln)};function Er(e,t,i){return{animationName:e,animationDuration:t,animationTimingFunction:i,animationFillMode:"both"}}function Tr(e){return On({from:{transform:"translate3d(".concat(e,"px,0,0)"),pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function br(e){return On({from:{transform:"translate3d(0,".concat(e,"px,0)"),pointerEvents:"none"},to:{transform:"translate3d(0,0,0)",pointerEvents:"auto"}})}function Ir(e){return On({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d(".concat(e,"px,0,0)")}})}function wr(e){return On({from:{transform:"translate3d(0,0,0)"},to:{transform:"translate3d(0,".concat(e,"px,0)")}})}var Rr,Ar,Pr,Mr,kr,Dr=function(e){var t={},i=function(i){var n;e.hasOwnProperty(i)&&Object.defineProperty(t,i,{get:function(){return void 0===n&&(n=cn(e[i]).toString()),n},enumerable:!0,configurable:!0})};for(var n in e)i(n);return t}(_r),Or={themeDarker:"#004578",themeDark:"#005a9e",themeDarkAlt:"#106ebe",themePrimary:"#0078d4",themeSecondary:"#2b88d8",themeTertiary:"#71afe5",themeLight:"#c7e0f4",themeLighter:"#deecf9",themeLighterAlt:"#eff6fc",black:"#000000",blackTranslucent40:"rgba(0,0,0,.4)",neutralDark:"#201f1e",neutralPrimary:"#323130",neutralPrimaryAlt:"#3b3a39",neutralSecondary:"#605e5c",neutralSecondaryAlt:"#8a8886",neutralTertiary:"#a19f9d",neutralTertiaryAlt:"#c8c6c4",neutralQuaternary:"#d2d0ce",neutralQuaternaryAlt:"#e1dfdd",neutralLight:"#edebe9",neutralLighter:"#f3f2f1",neutralLighterAlt:"#faf9f8",accent:"#0078d4",white:"#ffffff",whiteTranslucent40:"rgba(255,255,255,.4)",yellowDark:"#d29200",yellow:"#ffb900",yellowLight:"#fff100",orange:"#d83b01",orangeLight:"#ea4300",orangeLighter:"#ff8c00",redDark:"#a4262c",red:"#e81123",magentaDark:"#5c005c",magenta:"#b4009e",magentaLight:"#e3008c",purpleDark:"#32145a",purple:"#5c2d91",purpleLight:"#b4a0ff",blueDark:"#002050",blueMid:"#00188f",blue:"#0078d4",blueLight:"#00bcf2",tealDark:"#004b50",teal:"#008272",tealLight:"#00b294",greenDark:"#004b1c",green:"#107c10",greenLight:"#bad80a"};!function(e){e.Arabic="Segoe UI Web (Arabic)",e.Cyrillic="Segoe UI Web (Cyrillic)",e.EastEuropean="Segoe UI Web (East European)",e.Greek="Segoe UI Web (Greek)",e.Hebrew="Segoe UI Web (Hebrew)",e.Thai="Leelawadee UI Web",e.Vietnamese="Segoe UI Web (Vietnamese)",e.WestEuropean="Segoe UI Web (West European)",e.Selawik="Selawik Web",e.Armenian="Segoe UI Web (Armenian)",e.Georgian="Segoe UI Web (Georgian)"}(Rr||(Rr={})),function(e){e.Arabic="'".concat(Rr.Arabic,"'"),e.ChineseSimplified="'Microsoft Yahei UI', Verdana, Simsun",e.ChineseTraditional="'Microsoft Jhenghei UI', Pmingliu",e.Cyrillic="'".concat(Rr.Cyrillic,"'"),e.EastEuropean="'".concat(Rr.EastEuropean,"'"),e.Greek="'".concat(Rr.Greek,"'"),e.Hebrew="'".concat(Rr.Hebrew,"'"),e.Hindi="'Nirmala UI'",e.Japanese="'Yu Gothic UI', 'Meiryo UI', Meiryo, 'MS Pgothic', Osaka",e.Korean="'Malgun Gothic', Gulim",e.Selawik="'".concat(Rr.Selawik,"'"),e.Thai="'Leelawadee UI Web', 'Kmer UI'",e.Vietnamese="'".concat(Rr.Vietnamese,"'"),e.WestEuropean="'".concat(Rr.WestEuropean,"'"),e.Armenian="'".concat(Rr.Armenian,"'"),e.Georgian="'".concat(Rr.Georgian,"'")}(Ar||(Ar={})),function(e){e.size10="10px",e.size12="12px",e.size14="14px",e.size16="16px",e.size18="18px",e.size20="20px",e.size24="24px",e.size28="28px",e.size32="32px",e.size42="42px",e.size68="68px",e.mini="10px",e.xSmall="10px",e.small="12px",e.smallPlus="12px",e.medium="14px",e.mediumPlus="16px",e.icon="16px",e.large="18px",e.xLarge="20px",e.xLargePlus="24px",e.xxLarge="28px",e.xxLargePlus="32px",e.superLarge="42px",e.mega="68px"}(Pr||(Pr={})),function(e){e.light=100,e.semilight=300,e.regular=400,e.semibold=600,e.bold=700}(Mr||(Mr={})),function(e){e.xSmall="10px",e.small="12px",e.medium="16px",e.large="20px"}(kr||(kr={}));var Nr="@media screen and (-ms-high-contrast: active), screen and (forced-colors: active)",Lr="@media screen and (-ms-high-contrast: black-on-white), screen and (forced-colors: active) and (prefers-color-scheme: light)",xr=480,Fr=1366;function Ur(e,t){var i="number"==typeof e?" and (min-width: ".concat(e,"px)"):"",n="number"==typeof t?" and (max-width: ".concat(t,"px)"):"";return"@media only screen".concat(i).concat(n)}var Br,Vr="ms-Fabric--isFocusVisible",Hr="ms-Fabric--isFocusHidden";function $r(e,t){e&&(e.classList.add(t?Vr:Hr),e.classList.remove(t?Hr:Vr))}function Gr(e,t,i){var n;i?i.forEach((function(t){return $r(t.current,e)})):$r(null===(n=Tn(t))||void 0===n?void 0:n.document.body,e)}function jr(e,t,i,n,r,a,s,o){return function(e,t){var i,n;void 0===t&&(t={});var r=t.borderRadius,a=t.inset,s=void 0===a?0:a,o=t.width,l=void 0===o?1:o,c=t.position,d=void 0===c?"relative":c,u=t.highContrastStyle,h=t.borderColor,p=void 0===h?e.palette.white:h,g=t.outlineColor,m=void 0===g?e.palette.neutralSecondary:g,f=t.isFocusedOnly,v=void 0===f||f,S=t.pointerEvents;return{outline:"transparent",position:d,selectors:(i={"::-moz-focus-inner":{border:"0"}},i[".".concat(Vr," &").concat(v?":focus":"",":after")]={content:'""',position:"absolute",pointerEvents:S,left:s+1,top:s+1,bottom:s+1,right:s+1,border:"".concat(l,"px solid ").concat(p),outline:"".concat(l,"px solid ").concat(m),zIndex:Br.FocusStyle,borderRadius:r,selectors:(n={},n[Nr]=u,n)},i)}}(e,"number"!=typeof t&&t?t:{inset:t,position:i,highContrastStyle:n,borderColor:r,outlineColor:a,isFocusedOnly:s,borderRadius:o})}!function(e){e.Nav=1,e.ScrollablePane=1,e.FocusStyle=1,e.Coachmark=1e3,e.Layer=1e6,e.KeytipLayer=1000001}(Br||(Br={}));var zr=function(e,t,i,n){var r,a,s;void 0===i&&(i="border"),void 0===n&&(n=-1);var o="borderBottom"===i;return{borderColor:e,selectors:{":after":(r={pointerEvents:"none",content:"''",position:"absolute",left:o?0:n,top:n,bottom:n,right:o?0:n},r[i]="2px solid ".concat(e),r.borderRadius=t,r.width="borderBottom"===i?"100%":void 0,r.selectors=(a={},a[Nr]=(s={},s["border"===i?"borderColor":"borderBottomColor"]="Highlight",s),a),r)}}},Wr={position:"absolute",width:1,height:1,margin:-1,padding:0,border:0,overflow:"hidden",whiteSpace:"nowrap"},qr=vn((function(e,t){var i=Ni.getInstance();return t?Object.keys(e).reduce((function(t,n){return t[n]=i.getClassName(e[n]),t}),{}):e}));function Kr(e,t,i){return qr(e,void 0!==i?i:t.disableGlobalClassNames)}var Jr="__globalSettings__",Yr="__callbacks__",Qr=0,Zr=function(){function e(){}return e.getValue=function(e,t){var i=Xr();return void 0===i[e]&&(i[e]="function"==typeof t?t():t),i[e]},e.setValue=function(e,t){var i=Xr(),n=i[Yr],r=i[e];if(t!==r){i[e]=t;var a={oldValue:r,value:t,key:e};for(var s in n)n.hasOwnProperty(s)&&n[s](a)}return t},e.addChangeListener=function(e){var t=e.__id__,i=ea();t||(t=e.__id__=String(Qr++)),i[t]=e},e.removeChangeListener=function(e){delete ea()[e.__id__]},e}();function Xr(){var e,t=Tn()||{};return t[Jr]||(t[Jr]=((e={})[Yr]={},e)),t[Jr]}function ea(){return Xr()[Yr]}var ta,ia,na={settings:{},scopedSettings:{},inCustomizerContext:!1},ra=Zr.getValue("customizations",{settings:{},scopedSettings:{},inCustomizerContext:!1}),aa=[],sa=function(){function e(){}return e.reset=function(){ra.settings={},ra.scopedSettings={}},e.applySettings=function(t){ra.settings=Ii(Ii({},ra.settings),t),e._raiseChange()},e.applyScopedSettings=function(t,i){ra.scopedSettings[t]=Ii(Ii({},ra.scopedSettings[t]),i),e._raiseChange()},e.getSettings=function(e,t,i){void 0===i&&(i=na);for(var n={},r=t&&i.scopedSettings[t]||{},a=t&&ra.scopedSettings[t]||{},s=0,o=e;s<o.length;s++){var l=o[s];n[l]=r[l]||i.settings[l]||a[l]||ra.settings[l]}return n},e.applyBatchedUpdates=function(t,i){e._suppressUpdates=!0;try{t()}catch(e){}e._suppressUpdates=!1,i||e._raiseChange()},e.observe=function(e){aa.push(e)},e.unobserve=function(e){aa=aa.filter((function(t){return t!==e}))},e._raiseChange=function(){e._suppressUpdates||aa.forEach((function(e){return e()}))},e}(),oa=function(){return oa=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},oa.apply(this,arguments)},la="undefined"==typeof window?r.g:window,ca=la&&la.CSPSettings&&la.CSPSettings.nonce,da=((ia=la.__themeState__||{theme:void 0,lastStyleElement:void 0,registeredStyles:[]}).runState||(ia=oa(oa({},ia),{perf:{count:0,duration:0},runState:{flushTimer:0,mode:0,buffer:[]}})),ia.registeredThemableStyles||(ia=oa(oa({},ia),{registeredThemableStyles:[]})),la.__themeState__=ia,ia);function ua(e){da.theme=e,function(){if(da.theme){for(var e=[],t=0,i=da.registeredThemableStyles;t<i.length;t++){var n=i[t];e.push(n.themableStyle)}e.length>0&&(void 0===(a=1)&&(a=3),3!==a&&2!==a||(ha(da.registeredStyles),da.registeredStyles=[]),3!==a&&1!==a||(ha(da.registeredThemableStyles),da.registeredThemableStyles=[]),r=[].concat.apply([],e),da.loadStyles?da.loadStyles(pa(r).styleString,r):function(e){if("undefined"!=typeof document){var t=document.getElementsByTagName("head")[0],i=document.createElement("style"),n=pa(e),r=n.styleString,a=n.themable;i.setAttribute("data-load-themed-styles","true"),ca&&i.setAttribute("nonce",ca),i.appendChild(document.createTextNode(r)),da.perf.count++,t.appendChild(i);var s=document.createEvent("HTMLEvents");s.initEvent("styleinsert",!0,!1),s.args={newStyle:i},document.dispatchEvent(s);var o={styleElement:i,themableStyle:e};a?da.registeredThemableStyles.push(o):da.registeredStyles.push(o)}}(r))}var r,a}()}function ha(e){e.forEach((function(e){var t=e&&e.styleElement;t&&t.parentElement&&t.parentElement.removeChild(t)}))}function pa(e){var t=da.theme,i=!1;return{styleString:(e||[]).map((function(e){var n=e.theme;if(n){i=!0;var r=t?t[n]:void 0,a=e.defaultValue||"inherit";return t&&!r&&console&&!(n in t)&&"undefined"!=typeof DEBUG&&DEBUG&&console.warn('Theming value not provided for "'.concat(n,'". Falling back to "').concat(a,'".')),r||a}return e.rawString})).join(""),themable:i}}!function(e){e.depth0="0 0 0 0 transparent",e.depth4="0 1.6px 3.6px 0 rgba(0, 0, 0, 0.132), 0 0.3px 0.9px 0 rgba(0, 0, 0, 0.108)",e.depth8="0 3.2px 7.2px 0 rgba(0, 0, 0, 0.132), 0 0.6px 1.8px 0 rgba(0, 0, 0, 0.108)",e.depth16="0 6.4px 14.4px 0 rgba(0, 0, 0, 0.132), 0 1.2px 3.6px 0 rgba(0, 0, 0, 0.108)",e.depth64="0 25.6px 57.6px 0 rgba(0, 0, 0, 0.22), 0 4.8px 14.4px 0 rgba(0, 0, 0, 0.18)"}(ta||(ta={}));var ga={elevation4:ta.depth4,elevation8:ta.depth8,elevation16:ta.depth16,elevation64:ta.depth64,roundedCorner2:"2px",roundedCorner4:"4px",roundedCorner6:"6px"};function ma(e){var t=Ni.getInstance(),i=sn(Ui(),e);if(!t.classNameFromKey(i)){var n=t.getClassName();t.insertRule("@font-face{".concat(i,"}"),!0),t.cacheClassName(n,i,[],["font-face",i])}}var fa,va="'Segoe UI', '".concat(Rr.WestEuropean,"'"),Sa={ar:Ar.Arabic,bg:Ar.Cyrillic,cs:Ar.EastEuropean,el:Ar.Greek,et:Ar.EastEuropean,he:Ar.Hebrew,hi:Ar.Hindi,hr:Ar.EastEuropean,hu:Ar.EastEuropean,ja:Ar.Japanese,kk:Ar.EastEuropean,ko:Ar.Korean,lt:Ar.EastEuropean,lv:Ar.EastEuropean,pl:Ar.EastEuropean,ru:Ar.Cyrillic,sk:Ar.EastEuropean,"sr-latn":Ar.EastEuropean,th:Ar.Thai,tr:Ar.EastEuropean,uk:Ar.Cyrillic,vi:Ar.Vietnamese,"zh-hans":Ar.ChineseSimplified,"zh-hant":Ar.ChineseTraditional,hy:Ar.Armenian,ka:Ar.Georgian};function ya(e,t,i){return{fontFamily:i,MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontSize:e,fontWeight:t}}var Ca,_a,Ea,Ta="language",ba=(Ca=function(e){if(void 0===e&&(e="sessionStorage"),void 0===fa){var t=_n(),i="localStorage"===e?function(e){var t=null;try{var i=Tn();t=i?i.localStorage.getItem(e):null}catch(e){}return t}(Ta):"sessionStorage"===e?bn(Ta):void 0;i&&(fa=i),void 0===fa&&t&&(fa=t.documentElement.getAttribute("lang")),void 0===fa&&(fa="en")}return fa}(),_a=function(e){for(var t in Sa)if(Sa.hasOwnProperty(t)&&e&&0===t.indexOf(e))return Sa[t];return va}(Ca),Ea="".concat(_a,", ").concat("'Segoe UI', -apple-system, BlinkMacSystemFont, 'Roboto', 'Helvetica Neue', sans-serif"),{tiny:ya(Pr.mini,Mr.regular,Ea),xSmall:ya(Pr.xSmall,Mr.regular,Ea),small:ya(Pr.small,Mr.regular,Ea),smallPlus:ya(Pr.smallPlus,Mr.regular,Ea),medium:ya(Pr.medium,Mr.regular,Ea),mediumPlus:ya(Pr.mediumPlus,Mr.regular,Ea),large:ya(Pr.large,Mr.regular,Ea),xLarge:ya(Pr.xLarge,Mr.semibold,Ea),xLargePlus:ya(Pr.xLargePlus,Mr.semibold,Ea),xxLarge:ya(Pr.xxLarge,Mr.semibold,Ea),xxLargePlus:ya(Pr.xxLargePlus,Mr.semibold,Ea),superLarge:ya(Pr.superLarge,Mr.semibold,Ea),mega:ya(Pr.mega,Mr.semibold,Ea)});function Ia(e,t,i,n){ma({fontFamily:e="'".concat(e,"'"),src:(void 0!==n?"local('".concat(n,"'),"):"")+"url('".concat(t,".woff2') format('woff2'),")+"url('".concat(t,".woff') format('woff')"),fontWeight:i,fontStyle:"normal",fontDisplay:"swap"})}function wa(e,t,i,n,r){void 0===n&&(n="segoeui");var a="".concat(e,"/").concat(i,"/").concat(n);Ia(t,a+"-light",Mr.light,r&&r+" Light"),Ia(t,a+"-semilight",Mr.semilight,r&&r+" SemiLight"),Ia(t,a+"-regular",Mr.regular,r),Ia(t,a+"-semibold",Mr.semibold,r&&r+" SemiBold"),Ia(t,a+"-bold",Mr.bold,r&&r+" Bold")}function Ra(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=0,r=t;n<r.length;n++)Aa(e||{},r[n]);return e}function Aa(e,t,i){for(var n in void 0===i&&(i=[]),i.push(t),t)if(t.hasOwnProperty(n)&&"__proto__"!==n&&"constructor"!==n&&"prototype"!==n){var r=t[n];if("object"!=typeof r||null===r||Array.isArray(r))e[n]=r;else{var a=i.indexOf(r)>-1;e[n]=a?r:Aa(e[n]||{},r,i)}}return i.pop(),e}function Pa(e,t,i,n,r){return void 0===r&&(r=!1),function(e,t){var i="";return!0===t&&(i=" /* @deprecated */"),e.listTextColor=e.listText+i,e.menuItemBackgroundChecked+=i,e.warningHighlight+=i,e.warningText=e.messageText+i,e.successText+=i,e}(Ma(e,t,Ii({primaryButtonBorder:"transparent",errorText:n?"#F1707B":"#a4262c",messageText:n?"#F3F2F1":"#323130",messageLink:n?"#6CB8F6":"#005A9E",messageLinkHovered:n?"#82C7FF":"#004578",infoIcon:n?"#C8C6C4":"#605e5c",errorIcon:n?"#F1707B":"#A80000",blockingIcon:n?"#442726":"#FDE7E9",warningIcon:n?"#C8C6C4":"#797775",severeWarningIcon:n?"#FCE100":"#D83B01",successIcon:n?"#92C353":"#107C10",infoBackground:n?"#323130":"#f3f2f1",errorBackground:n?"#442726":"#FDE7E9",blockingBackground:n?"#442726":"#FDE7E9",warningBackground:n?"#433519":"#FFF4CE",severeWarningBackground:n?"#4F2A0F":"#FED9CC",successBackground:n?"#393D1B":"#DFF6DD",warningHighlight:n?"#fff100":"#ffb900",successText:n?"#92c353":"#107C10"},i),n),r)}function Ma(e,t,i,n,r){void 0===r&&(r=!1);var a={},s=e||{},o=s.white,l=s.black,c=s.themePrimary,d=s.themeDark,u=s.themeDarker,h=s.themeDarkAlt,p=s.themeLighter,g=s.neutralLight,m=s.neutralLighter,f=s.neutralDark,v=s.neutralQuaternary,S=s.neutralQuaternaryAlt,y=s.neutralPrimary,C=s.neutralSecondary,_=s.neutralSecondaryAlt,E=s.neutralTertiary,T=s.neutralTertiaryAlt,b=s.neutralLighterAlt,I=s.accent;return o&&(a.bodyBackground=o,a.bodyFrameBackground=o,a.accentButtonText=o,a.buttonBackground=o,a.primaryButtonText=o,a.primaryButtonTextHovered=o,a.primaryButtonTextPressed=o,a.inputBackground=o,a.inputForegroundChecked=o,a.listBackground=o,a.menuBackground=o,a.cardStandoutBackground=o),l&&(a.bodyTextChecked=l,a.buttonTextCheckedHovered=l),c&&(a.link=c,a.primaryButtonBackground=c,a.inputBackgroundChecked=c,a.inputIcon=c,a.inputFocusBorderAlt=c,a.menuIcon=c,a.menuHeader=c,a.accentButtonBackground=c),d&&(a.primaryButtonBackgroundPressed=d,a.inputBackgroundCheckedHovered=d,a.inputIconHovered=d),u&&(a.linkHovered=u),h&&(a.primaryButtonBackgroundHovered=h),p&&(a.inputPlaceholderBackgroundChecked=p),g&&(a.bodyBackgroundChecked=g,a.bodyFrameDivider=g,a.bodyDivider=g,a.variantBorder=g,a.buttonBackgroundCheckedHovered=g,a.buttonBackgroundPressed=g,a.listItemBackgroundChecked=g,a.listHeaderBackgroundPressed=g,a.menuItemBackgroundPressed=g,a.menuItemBackgroundChecked=g),m&&(a.bodyBackgroundHovered=m,a.buttonBackgroundHovered=m,a.buttonBackgroundDisabled=m,a.buttonBorderDisabled=m,a.primaryButtonBackgroundDisabled=m,a.disabledBackground=m,a.listItemBackgroundHovered=m,a.listHeaderBackgroundHovered=m,a.menuItemBackgroundHovered=m),v&&(a.primaryButtonTextDisabled=v,a.disabledSubtext=v),S&&(a.listItemBackgroundCheckedHovered=S),E&&(a.disabledBodyText=E,a.variantBorderHovered=(null==i?void 0:i.variantBorderHovered)||E,a.buttonTextDisabled=E,a.inputIconDisabled=E,a.disabledText=E),y&&(a.bodyText=y,a.actionLink=y,a.buttonText=y,a.inputBorderHovered=y,a.inputText=y,a.listText=y,a.menuItemText=y),b&&(a.bodyStandoutBackground=b,a.defaultStateBackground=b),f&&(a.actionLinkHovered=f,a.buttonTextHovered=f,a.buttonTextChecked=f,a.buttonTextPressed=f,a.inputTextHovered=f,a.menuItemTextHovered=f),C&&(a.bodySubtext=C,a.focusBorder=C,a.inputBorder=C,a.smallInputBorder=C,a.inputPlaceholderText=C),_&&(a.buttonBorder=_),T&&(a.disabledBodySubtext=T,a.disabledBorder=T,a.buttonBackgroundChecked=T,a.menuDivider=T),I&&(a.accentButtonBackground=I),(null==t?void 0:t.elevation4)&&(a.cardShadow=t.elevation4),!n&&(null==t?void 0:t.elevation8)?a.cardShadowHovered=t.elevation8:a.variantBorderHovered&&(a.cardShadowHovered="0 0 1px "+a.variantBorderHovered),Ii(Ii({},a),i)}function ka(e,t){var i,n,r;void 0===t&&(t={});var a=Ra({},e,t,{semanticColors:Ma(t.palette,t.effects,t.semanticColors,void 0===t.isInverted?e.isInverted:t.isInverted)});if((null===(i=t.palette)||void 0===i?void 0:i.themePrimary)&&!(null===(n=t.palette)||void 0===n?void 0:n.accent)&&(a.palette.accent=t.palette.themePrimary),t.defaultFontStyle)for(var s=0,o=Object.keys(a.fonts);s<o.length;s++){var l=o[s];a.fonts[l]=Ra(a.fonts[l],t.defaultFontStyle,null===(r=null==t?void 0:t.fonts)||void 0===r?void 0:r[l])}return a}!function(e){if(e){var t="".concat(e,"/fonts");wa(t,Rr.Thai,"leelawadeeui-thai","leelawadeeui"),wa(t,Rr.Arabic,"segoeui-arabic"),wa(t,Rr.Cyrillic,"segoeui-cyrillic"),wa(t,Rr.EastEuropean,"segoeui-easteuropean"),wa(t,Rr.Greek,"segoeui-greek"),wa(t,Rr.Hebrew,"segoeui-hebrew"),wa(t,Rr.Vietnamese,"segoeui-vietnamese"),wa(t,Rr.WestEuropean,"segoeui-westeuropean","segoeui","Segoe UI"),wa(t,Ar.Selawik,"selawik","selawik"),wa(t,Rr.Armenian,"segoeui-armenian"),wa(t,Rr.Georgian,"segoeui-georgian"),Ia("Leelawadee UI Web","".concat(t,"/leelawadeeui-thai/leelawadeeui-semilight"),Mr.light),Ia("Leelawadee UI Web","".concat(t,"/leelawadeeui-thai/leelawadeeui-bold"),Mr.semibold)}}(function(){var e,t,i=null===(e=Tn())||void 0===e?void 0:e.FabricConfig;return null!==(t=null==i?void 0:i.fontBaseUrl)&&void 0!==t?t:"https://res-1.cdn.office.net/files/fabric-cdn-prod_20230815.002/assets"}());var Da={s2:"4px",s1:"8px",m:"16px",l1:"20px",l2:"32px"};function Oa(e,t){void 0===e&&(e={}),void 0===t&&(t=!1);var i=!!e.isInverted;return ka({palette:Or,effects:ga,fonts:ba,spacing:Da,isInverted:i,disableGlobalClassNames:!1,semanticColors:Pa(Or,ga,void 0,i,t),rtl:void 0},e)}var Na=Oa({}),La=[],xa="theme";function Fa(){var e,t,i,n=Tn();(null===(t=null==n?void 0:n.FabricConfig)||void 0===t?void 0:t.legacyTheme)?function(e,t){var i;void 0===t&&(t=!1),Na=Oa(e,t),ua(Ii(Ii(Ii(Ii({},Na.palette),Na.semanticColors),Na.effects),function(e){for(var t={},i=0,n=Object.keys(e.fonts);i<n.length;i++)for(var r=n[i],a=e.fonts[r],s=0,o=Object.keys(a);s<o.length;s++){var l=o[s],c=r+l.charAt(0).toUpperCase()+l.slice(1),d=a[l];"fontSize"===l&&"number"==typeof d&&(d+="px"),t[c]=d}return t}(Na))),sa.applySettings(((i={})[xa]=Na,i)),La.forEach((function(e){try{e(Na)}catch(e){}}))}(n.FabricConfig.legacyTheme):sa.getSettings([xa]).theme||((null===(i=null==n?void 0:n.FabricConfig)||void 0===i?void 0:i.theme)&&(Na=Oa(n.FabricConfig.theme)),sa.applySettings(((e={})[xa]=Na,e)))}function Ua(e){return void 0===e&&(e=!1),!0===e&&(Na=Oa({},e)),Na}Fa();var Ba={boxShadow:"none",margin:0,padding:0,boxSizing:"border-box"},Va={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};function Ha(e){return{selectors:{"::placeholder":e,":-ms-input-placeholder":e,"::-ms-input-placeholder":e}}}function $a(e){console&&console.warn&&console.warn(e)}var Ga=Zr.getValue("icons",{__options:{disableWarnings:!1,warnOnMissingIcons:!0},__remapped:{}}),ja=Ni.getInstance();ja&&ja.onReset&&ja.onReset((function(){for(var e in Ga)Ga.hasOwnProperty(e)&&Ga[e].subset&&(Ga[e].subset.className=void 0)}));var za=function(e){return e.toLowerCase()};function Wa(e,t){var i=Ii(Ii({},e),{isRegistered:!1,className:void 0}),n=e.icons;for(var r in t=t?Ii(Ii({},Ga.__options),t):Ga.__options,n)if(n.hasOwnProperty(r)){var a=n[r],s=za(r);Ga[s]?Ya(r):Ga[s]={code:a,subset:i}}}function qa(e,t){Ga.__remapped[za(e)]=za(t)}var Ka=[],Ja=void 0;function Ya(e){Ga.__options.disableWarnings||(Ka.push(e),void 0===Ja&&(Ja=setTimeout((function(){$a("Some icons were re-registered. Applications should only call registerIcons for any given icon once. Redefining what an icon is may have unintended consequences. Duplicates include: \n"+Ka.slice(0,10).join(", ")+(Ka.length>10?" (+ ".concat(Ka.length-10," more)"):"")),Ja=void 0,Ka=[]}),2e3)))}function Qa(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(e&&1===e.length&&e[0]&&!e[0].subComponentStyles)return e[0];for(var i={},n={},r=0,a=e;r<a.length;r++){var s=a[r];if(s)for(var o in s)if(s.hasOwnProperty(o)){if("subComponentStyles"===o&&void 0!==s.subComponentStyles){var l=s.subComponentStyles;for(var c in l)l.hasOwnProperty(c)&&(n.hasOwnProperty(c)?n[c].push(l[c]):n[c]=[l[c]]);continue}var d=i[o],u=s[o];i[o]=void 0===d?u:Ai(Ai([],Array.isArray(d)?d:[d],!0),Array.isArray(u)?u:[u],!0)}}if(Object.keys(n).length>0){i.subComponentStyles={};var h=i.subComponentStyles,p=function(e){if(n.hasOwnProperty(e)){var t=n[e];h[e]=function(e){return Qa.apply(void 0,t.map((function(t){return"function"==typeof t?t(e):t})))}}};for(var c in n)p(c)}return i}function Za(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];for(var n=[],r=0,a=t;r<a.length;r++){var s=a[r];s&&n.push("function"==typeof s?s(e):s)}return 1===n.length?n[0]:n.length?Qa.apply(void 0,n):{}}function Xa(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return es(e,Ui())}function es(e,t){var i={subComponentStyles:{}};if(!e[0]&&e.length<=1)return{subComponentStyles:{}};var n=Qa.apply(void 0,e),r=[];for(var a in n)if(n.hasOwnProperty(a)){if("subComponentStyles"===a){i.subComponentStyles=n.subComponentStyles||{};continue}var s=Li(n[a]),o=s.classes,l=s.objects;(null==l?void 0:l.length)?(u=on(t||{},{displayName:a},l))&&(r.push(u),i[a]=o.concat([u.className]).join(" ")):i[a]=o.join(" ")}for(var c=0,d=r;c<d.length;c++){var u;(u=d[c])&&ln(u,null==t?void 0:t.specificityMultiplier)}return i}var ts={},is=void 0;try{is=window}catch(e){}function ns(e,t){if(void 0!==is){var i=is.__packages__=is.__packages__||{};i[e]&&ts[e]||(ts[e]=t,(i[e]=i[e]||[]).push(t))}}ns("@fluentui/set-version","6.0.0"),ns("@fluentui/style-utilities","8.10.6"),Fa();var rs=e.createContext({customizations:{inCustomizerContext:!1,settings:{},scopedSettings:{}}});function as(t,i){void 0===i&&(i={});var n=i.factoryOptions,r=(void 0===n?{}:n).defaultProp,a=function(n){var r,a,s,o=(r=i.displayName,a=e.useContext(rs),s=i.fields,sa.getSettings(s||["theme","styles","tokens"],r,a.customizations)),l=i.state;l&&(n=Ii(Ii({},n),l(n)));var c=n.theme||o.theme,d=ss(n,c,i.tokens,o.tokens,n.tokens),u=function(e,t,i){for(var n=[],r=3;r<arguments.length;r++)n[r-3]=arguments[r];return Qa.apply(void 0,n.map((function(n){return"function"==typeof n?n(e,t,i):n})))}(n,c,d,i.styles,o.styles,n.styles),h=Ii(Ii({},n),{styles:u,tokens:d,_defaultStyles:u,theme:c});return t(h)};return a.displayName=i.displayName||t.name,r&&(a.create=Mn(a,{defaultProp:r})),An(a,i.statics),a}function ss(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];for(var r={},a=0,s=i;a<s.length;a++){var o=s[a];o&&(o="function"==typeof o?o(e,t):o,Array.isArray(o)&&(o=ss.apply(void 0,Ai([e,t],o,!1))),An(r,o))}return r}var os=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i={},n=0,r=e;n<r.length;n++)for(var a=r[n],s=0,o=Array.isArray(a)?a:Object.keys(a);s<o.length;s++)i[o[s]]=1;return i},ls=os(["onCopy","onCut","onPaste","onCompositionEnd","onCompositionStart","onCompositionUpdate","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onInput","onSubmit","onLoad","onError","onKeyDown","onKeyDownCapture","onKeyPress","onKeyUp","onAbort","onCanPlay","onCanPlayThrough","onDurationChange","onEmptied","onEncrypted","onEnded","onLoadedData","onLoadedMetadata","onLoadStart","onPause","onPlay","onPlaying","onProgress","onRateChange","onSeeked","onSeeking","onStalled","onSuspend","onTimeUpdate","onVolumeChange","onWaiting","onClick","onClickCapture","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseOut","onMouseOver","onMouseUp","onMouseUpCapture","onSelect","onTouchCancel","onTouchEnd","onTouchMove","onTouchStart","onScroll","onWheel","onPointerCancel","onPointerDown","onPointerEnter","onPointerLeave","onPointerMove","onPointerOut","onPointerOver","onPointerUp","onGotPointerCapture","onLostPointerCapture"]),cs=os(["accessKey","children","className","contentEditable","dir","draggable","hidden","htmlFor","id","lang","ref","role","style","tabIndex","title","translate","spellCheck","name"]),ds=os(cs,ls),us=os(ds,["form"]),hs=os(ds,["height","loop","muted","preload","src","width"]),ps=os(hs,["poster"]),gs=os(ds,["start"]),ms=os(ds,["value"]),fs=os(ds,["download","href","hrefLang","media","rel","target","type"]),vs=os(ds,["autoFocus","disabled","form","formAction","formEncType","formMethod","formNoValidate","formTarget","type","value"]),Ss=os(vs,["accept","alt","autoCapitalize","autoComplete","checked","dirname","form","height","inputMode","list","max","maxLength","min","minLength","multiple","pattern","placeholder","readOnly","required","src","step","size","type","value","width"]),ys=os(vs,["autoCapitalize","cols","dirname","form","maxLength","minLength","placeholder","readOnly","required","rows","wrap"]),Cs=os(vs,["form","multiple","required"]),_s=os(ds,["selected","value"]),Es=os(ds,["cellPadding","cellSpacing"]),Ts=ds,bs=os(ds,["rowSpan","scope"]),Is=os(ds,["colSpan","headers","rowSpan","scope"]),ws=os(ds,["span"]),Rs=os(ds,["span"]),As=os(ds,["acceptCharset","action","encType","encType","method","noValidate","target"]),Ps=os(ds,["allow","allowFullScreen","allowPaymentRequest","allowTransparency","csp","height","importance","referrerPolicy","sandbox","src","srcDoc","width"]),Ms=os(ds,["alt","crossOrigin","height","src","srcSet","useMap","width"]),ks=ds;function Ds(e,t,i){for(var n=Array.isArray(t),r={},a=0,s=Object.keys(e);a<s.length;a++){var o=s[a];!(!n&&t[o]||n&&t.indexOf(o)>=0||0===o.indexOf("data-")||0===o.indexOf("aria-"))||i&&-1!==(null==i?void 0:i.indexOf(o))||(r[o]=e[o])}return r}function Os(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=[],n=0,r=e;n<r.length;n++){var a=r[n];if(a)if("string"==typeof a)i.push(a);else if(a.hasOwnProperty("toString")&&"function"==typeof a.toString)i.push(a.toString());else for(var s in a)a[s]&&i.push(s)}return i.join(" ")}var Ns={root:"ms-StackItem"},Ls={start:"flex-start",end:"flex-end"},xs=function(e,t){return t.spacing.hasOwnProperty(e)?t.spacing[e]:e},Fs=function(e){var t=parseFloat(e),i=isNaN(t)?0:t,n=isNaN(t)?"":t.toString();return{value:i,unit:e.substring(n.toString().length)||"px"}},Us=function(e,t){if(void 0===e||"number"==typeof e||""===e)return e;var i=e.split(" ");return i.length<2?xs(e,t):i.reduce((function(e,i){return xs(e,t)+" "+xs(i,t)}))},Bs={start:"flex-start",end:"flex-end"},Vs={root:"ms-Stack",inner:"ms-Stack-inner",child:"ms-Stack-child"},Hs=as((function(e){var t=e.children,i=Ds(e,ds);return null==t?null:Pn(Dn(e,{root:"div"}).root,Ii({},i),t)}),{displayName:"StackItem",styles:function(e,t,i){var n=e.grow,r=e.shrink,a=e.disableShrink,s=e.align,o=e.verticalFill,l=e.order,c=e.className,d=e.basis,u=void 0===d?"auto":d,h=Kr(Ns,t);return{root:[t.fonts.medium,h.root,{flexBasis:u,margin:i.margin,padding:i.padding,height:o?"100%":"auto",width:"auto"},n&&{flexGrow:!0===n?1:n},(a||!n&&!r)&&{flexShrink:0},r&&!a&&{flexShrink:1},s&&{alignSelf:Ls[s]||s},l&&{order:l},c]}}});function $s(t,i){var n=i.disableShrink,r=i.enableScopedSelectors,a=i.doNotRenderFalsyValues,s=e.Children.toArray(t);return e.Children.map(s,(function(t){if(!t)return a?null:t;if(!e.isValidElement(t))return t;if(t.type===e.Fragment)return t.props.children?$s(t.props.children,{disableShrink:n,enableScopedSelectors:r,doNotRenderFalsyValues:a}):null;var i,s=t,o={};(i=t)&&"object"==typeof i&&i.type&&i.type.displayName===Hs.displayName&&(o={shrink:!n});var l=s.props.className;return e.cloneElement(s,Ii(Ii(Ii(Ii({},o),s.props),l&&{className:l}),r&&{className:Os(Vs.child,l)}))}))}var Gs=as((function(e){var t=e.as,i=void 0===t?"div":t,n=e.disableShrink,r=void 0!==n&&n,a=e.doNotRenderFalsyValues,s=void 0!==a&&a,o=e.enableScopedSelectors,l=void 0!==o&&o,c=e.wrap,d=wi(e,["as","disableShrink","doNotRenderFalsyValues","enableScopedSelectors","wrap"]),u=$s(e.children,{disableShrink:r,enableScopedSelectors:l,doNotRenderFalsyValues:s}),h=Ds(d,ds),p=Dn(e,{root:i,inner:"div"});return Pn(p.root,Ii({},h),c?Pn(p.inner,null,u):u)}),{displayName:"Stack",styles:function(e,t,i){var n,r,a,s,o,l,c,d,u,h,p,g,m,f=e.className,v=e.disableShrink,S=e.enableScopedSelectors,y=e.grow,C=e.horizontal,_=e.horizontalAlign,E=e.reversed,T=e.verticalAlign,b=e.verticalFill,I=e.wrap,w=Kr(Vs,t),R=i&&i.childrenGap?i.childrenGap:e.gap,A=i&&i.maxHeight?i.maxHeight:e.maxHeight,P=i&&i.maxWidth?i.maxWidth:e.maxWidth,M=i&&i.padding?i.padding:e.padding,k=function(e,t){if(void 0===e||""===e)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if("number"==typeof e)return{rowGap:{value:e,unit:"px"},columnGap:{value:e,unit:"px"}};var i=e.split(" ");if(i.length>2)return{rowGap:{value:0,unit:"px"},columnGap:{value:0,unit:"px"}};if(2===i.length)return{rowGap:Fs(xs(i[0],t)),columnGap:Fs(xs(i[1],t))};var n=Fs(xs(e,t));return{rowGap:n,columnGap:n}}(R,t),D=k.rowGap,O=k.columnGap,N="".concat(-.5*O.value).concat(O.unit),L="".concat(-.5*D.value).concat(D.unit),x={textOverflow:"ellipsis"},F="> "+(S?"."+Vs.child:"*"),U=((n={})["".concat(F,":not(.").concat(Ns.root,")")]={flexShrink:0},n);return I?{root:[w.root,{flexWrap:"wrap",maxWidth:P,maxHeight:A,width:"auto",overflow:"visible",height:"100%"},_&&(r={},r[C?"justifyContent":"alignItems"]=Bs[_]||_,r),T&&(a={},a[C?"alignItems":"justifyContent"]=Bs[T]||T,a),f,{display:"flex"},C&&{height:b?"100%":"auto"}],inner:[w.inner,(s={display:"flex",flexWrap:"wrap",marginLeft:N,marginRight:N,marginTop:L,marginBottom:L,overflow:"visible",boxSizing:"border-box",padding:Us(M,t),width:0===O.value?"100%":"calc(100% + ".concat(O.value).concat(O.unit,")"),maxWidth:"100vw"},s[F]=Ii({margin:"".concat(.5*D.value).concat(D.unit," ").concat(.5*O.value).concat(O.unit)},x),s),v&&U,_&&(o={},o[C?"justifyContent":"alignItems"]=Bs[_]||_,o),T&&(l={},l[C?"alignItems":"justifyContent"]=Bs[T]||T,l),C&&(c={flexDirection:E?"row-reverse":"row",height:0===D.value?"100%":"calc(100% + ".concat(D.value).concat(D.unit,")")},c[F]={maxWidth:0===O.value?"100%":"calc(100% - ".concat(O.value).concat(O.unit,")")},c),!C&&(d={flexDirection:E?"column-reverse":"column",height:"calc(100% + ".concat(D.value).concat(D.unit,")")},d[F]={maxHeight:0===D.value?"100%":"calc(100% - ".concat(D.value).concat(D.unit,")")},d)]}:{root:[w.root,(u={display:"flex",flexDirection:C?E?"row-reverse":"row":E?"column-reverse":"column",flexWrap:"nowrap",width:"auto",height:b?"100%":"auto",maxWidth:P,maxHeight:A,padding:Us(M,t),boxSizing:"border-box"},u[F]=x,u),v&&U,y&&{flexGrow:!0===y?1:y},_&&(h={},h[C?"justifyContent":"alignItems"]=Bs[_]||_,h),T&&(p={},p[C?"alignItems":"justifyContent"]=Bs[T]||T,p),C&&O.value>0&&(g={},g["".concat(F,E?":not(:last-child)":":not(:first-child)")]={marginLeft:"".concat(O.value).concat(O.unit)},g),!C&&D.value>0&&(m={},m["".concat(F,E?":not(:last-child)":":not(:first-child)")]={marginTop:"".concat(D.value).concat(D.unit)},m),f]}},statics:{Item:Hs}});function js(t,i){var n,r=(n=e.useState(0)[1],function(){return n((function(e){return++e}))}),a=e.useContext(rs).customizations,s=a.inCustomizerContext;return e.useEffect((function(){return s||sa.observe(r),function(){s||sa.unobserve(r)}}),[s]),sa.getSettings(t,i,a)}var zs=["theme","styles"];function Ws(t,i,n,r,a){var s=(r=r||{scope:"",fields:void 0}).scope,o=r.fields,l=void 0===o?zs:o,c=e.forwardRef((function(r,a){var o=e.useRef(),c=js(l,s),d=c.styles,u=(c.dir,wi(c,["styles","dir"])),h=n?n(r):void 0,p=o.current&&o.current.__cachedInputs__||[],g=r.styles;if(!o.current||d!==p[1]||g!==p[2]){var m=function(e){return Za(e,i,d,g)};m.__cachedInputs__=[i,d,g],m.__noStyleOverride__=!d&&!g,o.current=m}return e.createElement(t,Ii({ref:a},u,h,r,{styles:o.current}))}));c.displayName="Styled".concat(t.displayName||t.name);var d=a?e.memo(c):c;return c.displayName&&(d.displayName=c.displayName),d}var qs=0,Ks=Ni.getInstance();Ks&&Ks.onReset&&Ks.onReset((function(){return qs++}));var Js="__retval__";function Ys(e){void 0===e&&(e={});var t=new Map,i=0,n=0,r=qs;return function(a,s){var o;if(void 0===s&&(s={}),e.useStaticStyles&&"function"==typeof a&&a.__noStyleOverride__)return a(s);n++;var l=t,c=s.theme,d=c&&void 0!==c.rtl?c.rtl:Rn(),u=e.disableCaching;if(r!==qs&&(r=qs,t=new Map,i=0),e.disableCaching||(l=Zs(t,a),l=Zs(l,s)),!u&&l[Js]||(l[Js]=void 0===a?{}:es(["function"==typeof a?a(s):a],{rtl:!!d,specificityMultiplier:e.useStaticStyles?5:void 0}),u||i++),i>(e.cacheSize||50)){var h=Tn();(null===(o=null==h?void 0:h.FabricConfig)||void 0===o?void 0:o.enableClassNameCacheFullWarning)&&(console.warn("Styles are being recalculated too frequently. Cache miss rate is ".concat(i,"/").concat(n,".")),console.trace()),t.clear(),i=0,e.disableCaching=!0}return l[Js]}}function Qs(e,t){return t=function(e){switch(e){case void 0:return"__undefined__";case null:return"__null__";default:return e}}(t),e.has(t)||e.set(t,new Map),e.get(t)}function Zs(e,t){if("function"==typeof t)if(t.__cachedInputs__)for(var i=0,n=t.__cachedInputs__;i<n.length;i++)e=Qs(e,n[i]);else e=Qs(e,t);else if("object"==typeof t)for(var r in t)t.hasOwnProperty(r)&&(e=Qs(e,t[r]));return e}var Xs=function(t){function i(e){var i=t.call(this,e)||this;return i.state={isRendered:void 0===Tn()},i}return bi(i,t),i.prototype.componentDidMount=function(){var e=this,t=this.props.delay;this._timeoutId=window.setTimeout((function(){e.setState({isRendered:!0})}),t)},i.prototype.componentWillUnmount=function(){this._timeoutId&&clearTimeout(this._timeoutId)},i.prototype.render=function(){return this.state.isRendered?e.Children.only(this.props.children):null},i.defaultProps={delay:0},i}(e.Component);var eo=function(e){var t={refs:[]};return function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return t.resolver&&function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}(t.refs,e)||(t.resolver=function(e){return function(t){for(var i=0,n=e.refs;i<n.length;i++){var r=n[i];"function"==typeof r?r(t):r&&(r.current=t)}}}(t)),t.refs=e,t.resolver}};function to(e,t){return void 0===t&&(t=!0),e&&(t&&function(e){var t,i;return e&&(i=e)&&i._virtual&&(t=e._virtual.parent),t}(e)||e.parentNode&&e.parentNode)}function io(e,t,i){return null!=i||(i=document),e&&e!==i.body?t(e)?e:io(to(e),t):null}var no="data-portal-element";function ro(e,t,i){var n=io(e,(function(e){return t===e||e.hasAttribute(no)}),i);return null!==n&&n.hasAttribute(no)}var ao={backspace:8,tab:9,enter:13,shift:16,ctrl:17,alt:18,pauseBreak:19,capslock:20,escape:27,space:32,pageUp:33,pageDown:34,end:35,home:36,left:37,up:38,right:39,down:40,insert:45,del:46,zero:48,one:49,two:50,three:51,four:52,five:53,six:54,seven:55,eight:56,nine:57,colon:58,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,leftWindow:91,rightWindow:92,select:93,zero_numpad:96,one_numpad:97,two_numpad:98,three_numpad:99,four_numpad:100,five_numpad:101,six_numpad:102,seven_numpad:103,eight_numpad:104,nine_numpad:105,multiply:106,add:107,subtract:109,decimalPoint:110,divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,numlock:144,scrollLock:145,semicolon:186,equalSign:187,comma:188,dash:189,period:190,forwardSlash:191,graveAccent:192,openBracket:219,backSlash:220,closeBracket:221,singleQuote:222};function so(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return t.length<2?t[0]:function(){for(var i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];t.forEach((function(t){return t&&t.apply(e,i)}))}}function oo(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=so(e,e[i],t[i]))}function lo(e){oo(e,{componentDidMount:co,componentDidUpdate:uo,componentWillUnmount:ho})}function co(){po(this.props.componentRef,this)}function uo(e){e.componentRef!==this.props.componentRef&&(po(e.componentRef,null),po(this.props.componentRef,this))}function ho(){po(this.props.componentRef,null)}function po(e,t){e&&("object"==typeof e?e.current=t:"function"==typeof e&&e(t))}var go=function(){function e(e,t){this._timeoutIds=null,this._immediateIds=null,this._intervalIds=null,this._animationFrameIds=null,this._isDisposed=!1,this._parent=e||null,this._onErrorHandler=t,this._noop=function(){}}return e.prototype.dispose=function(){var e;if(this._isDisposed=!0,this._parent=null,this._timeoutIds){for(e in this._timeoutIds)this._timeoutIds.hasOwnProperty(e)&&this.clearTimeout(parseInt(e,10));this._timeoutIds=null}if(this._immediateIds){for(e in this._immediateIds)this._immediateIds.hasOwnProperty(e)&&this.clearImmediate(parseInt(e,10));this._immediateIds=null}if(this._intervalIds){for(e in this._intervalIds)this._intervalIds.hasOwnProperty(e)&&this.clearInterval(parseInt(e,10));this._intervalIds=null}if(this._animationFrameIds){for(e in this._animationFrameIds)this._animationFrameIds.hasOwnProperty(e)&&this.cancelAnimationFrame(parseInt(e,10));this._animationFrameIds=null}},e.prototype.setTimeout=function(e,t){var i=this,n=0;return this._isDisposed||(this._timeoutIds||(this._timeoutIds={}),n=setTimeout((function(){try{i._timeoutIds&&delete i._timeoutIds[n],e.apply(i._parent)}catch(e){i._logError(e)}}),t),this._timeoutIds[n]=!0),n},e.prototype.clearTimeout=function(e){this._timeoutIds&&this._timeoutIds[e]&&(clearTimeout(e),delete this._timeoutIds[e])},e.prototype.setImmediate=function(e,t){var i=this,n=0,r=Tn(t);return this._isDisposed||(this._immediateIds||(this._immediateIds={}),n=r.setTimeout((function(){try{i._immediateIds&&delete i._immediateIds[n],e.apply(i._parent)}catch(e){i._logError(e)}}),0),this._immediateIds[n]=!0),n},e.prototype.clearImmediate=function(e,t){var i=Tn(t);this._immediateIds&&this._immediateIds[e]&&(i.clearTimeout(e),delete this._immediateIds[e])},e.prototype.setInterval=function(e,t){var i=this,n=0;return this._isDisposed||(this._intervalIds||(this._intervalIds={}),n=setInterval((function(){try{e.apply(i._parent)}catch(e){i._logError(e)}}),t),this._intervalIds[n]=!0),n},e.prototype.clearInterval=function(e){this._intervalIds&&this._intervalIds[e]&&(clearInterval(e),delete this._intervalIds[e])},e.prototype.throttle=function(e,t,i){var n=this;if(this._isDisposed)return this._noop;var r,a,s=t||0,o=!0,l=!0,c=0,d=null;i&&"boolean"==typeof i.leading&&(o=i.leading),i&&"boolean"==typeof i.trailing&&(l=i.trailing);var u=function(t){var i=Date.now(),h=i-c,p=o?s-h:s;return h>=s&&(!t||o)?(c=i,d&&(n.clearTimeout(d),d=null),r=e.apply(n._parent,a)):null===d&&l&&(d=n.setTimeout(u,p)),r};return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return a=e,u(!0)}},e.prototype.debounce=function(e,t,i){var n=this;if(this._isDisposed){var r=function(){};return r.cancel=function(){},r.flush=function(){return null},r.pending=function(){return!1},r}var a,s,o=t||0,l=!1,c=!0,d=null,u=0,h=Date.now(),p=null;i&&"boolean"==typeof i.leading&&(l=i.leading),i&&"boolean"==typeof i.trailing&&(c=i.trailing),i&&"number"==typeof i.maxWait&&!isNaN(i.maxWait)&&(d=i.maxWait);var g=function(e){p&&(n.clearTimeout(p),p=null),h=e},m=function(t){g(t),a=e.apply(n._parent,s)},f=function(e){var t=Date.now(),i=!1;e&&(l&&t-u>=o&&(i=!0),u=t);var r=t-u,s=o-r,g=t-h,v=!1;return null!==d&&(g>=d&&p?v=!0:s=Math.min(s,d-g)),r>=o||v||i?m(t):null!==p&&e||!c||(p=n.setTimeout(f,s)),a},v=function(){return!!p},S=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s=e,f(!0)};return S.cancel=function(){v()&&g(Date.now())},S.flush=function(){return v()&&m(Date.now()),a},S.pending=v,S},e.prototype.requestAnimationFrame=function(e,t){var i=this,n=0,r=Tn(t);if(!this._isDisposed){this._animationFrameIds||(this._animationFrameIds={});var a=function(){try{i._animationFrameIds&&delete i._animationFrameIds[n],e.apply(i._parent)}catch(e){i._logError(e)}};n=r.requestAnimationFrame?r.requestAnimationFrame(a):r.setTimeout(a,0),this._animationFrameIds[n]=!0}return n},e.prototype.cancelAnimationFrame=function(e,t){var i=Tn(t);this._animationFrameIds&&this._animationFrameIds[e]&&(i.cancelAnimationFrame?i.cancelAnimationFrame(e):i.clearTimeout(e),delete this._animationFrameIds[e])},e.prototype._logError=function(e){this._onErrorHandler&&this._onErrorHandler(e)},e}();function mo(e,t){if(!e||!t)return!e&&!t;for(var i in e)if(e.hasOwnProperty(i)&&(!t.hasOwnProperty(i)||t[i]!==e[i]))return!1;for(var i in t)if(t.hasOwnProperty(i)&&!e.hasOwnProperty(i))return!1;return!0}function fo(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];return vo.apply(this,[null,e].concat(t))}function vo(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];t=t||{};for(var r=0,a=i;r<a.length;r++){var s=a[r];if(s)for(var o in s)!s.hasOwnProperty(o)||e&&!e(o)||(t[o]=s[o])}return t}var So=function(){function e(t){this._id=e._uniqueId++,this._parent=t,this._eventRecords=[]}return e.raise=function(t,i,n,r,a){var s,o=null!=a?a:_n();if(e._isElement(t)){if(void 0!==o&&o.createEvent){var l=o.createEvent("HTMLEvents");l.initEvent(i,r||!1,!0),fo(l,n),s=t.dispatchEvent(l)}else if(void 0!==o&&o.createEventObject){var c=o.createEventObject(n);t.fireEvent("on"+i,c)}}else for(;t&&!1!==s;){var d=t.__events__,u=d?d[i]:null;if(u)for(var h in u)if(u.hasOwnProperty(h))for(var p=u[h],g=0;!1!==s&&g<p.length;g++){var m=p[g];m.objectCallback&&(s=m.objectCallback.call(m.parent,n))}t=r?t.parent:null}return s},e.isObserved=function(e,t){var i=e&&e.__events__;return!!i&&!!i[t]},e.isDeclared=function(e,t){var i=e&&e.__declaredEvents;return!!i&&!!i[t]},e.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},e._isElement=function(e){return!!e&&(!!e.addEventListener||"undefined"!=typeof HTMLElement&&e instanceof HTMLElement)},e.prototype.dispose=function(){this._isDisposed||(this._isDisposed=!0,this.off(),this._parent=null)},e.prototype.onAll=function(e,t,i){for(var n in t)t.hasOwnProperty(n)&&this.on(e,n,t[n],i)},e.prototype.on=function(t,i,n,r){var a=this;if(i.indexOf(",")>-1)for(var s=i.split(/[ ,]+/),o=0;o<s.length;o++)this.on(t,s[o],n,r);else{var l=this._parent,c={target:t,eventName:i,parent:l,callback:n,options:r};if((s=t.__events__=t.__events__||{})[i]=s[i]||{count:0},s[i][this._id]=s[i][this._id]||[],s[i][this._id].push(c),s[i].count++,e._isElement(t)){var d=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!a._isDisposed){var i;try{if(!1===(i=n.apply(l,e))&&e[0]){var r=e[0];r.preventDefault&&r.preventDefault(),r.stopPropagation&&r.stopPropagation(),r.cancelBubble=!0}}catch(r){}return i}};c.elementCallback=d,t.addEventListener?t.addEventListener(i,d,r):t.attachEvent&&t.attachEvent("on"+i,d)}else c.objectCallback=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(!a._isDisposed)return n.apply(l,e)};this._eventRecords.push(c)}},e.prototype.off=function(e,t,i,n){for(var r=0;r<this._eventRecords.length;r++){var a=this._eventRecords[r];if(!(e&&e!==a.target||t&&t!==a.eventName||i&&i!==a.callback||"boolean"==typeof n&&n!==a.options)){var s=a.target.__events__,o=s[a.eventName],l=o?o[this._id]:null;l&&(1!==l.length&&i?(o.count--,l.splice(l.indexOf(a),1)):(o.count-=l.length,delete s[a.eventName][this._id]),o.count||delete s[a.eventName]),a.elementCallback&&(a.target.removeEventListener?a.target.removeEventListener(a.eventName,a.elementCallback,a.options):a.target.detachEvent&&a.target.detachEvent("on"+a.eventName,a.elementCallback)),this._eventRecords.splice(r--,1)}}},e.prototype.raise=function(t,i,n){return e.raise(this._parent,t,i,n)},e.prototype.declare=function(e){var t=this._parent.__declaredEvents=this._parent.__declaredEvents||{};if("string"==typeof e)t[e]=!0;else for(var i=0;i<e.length;i++)t[e[i]]=!0},e._uniqueId=0,e}(),yo="__currentId__",Co="id__",_o=Tn()||{};void 0===_o[yo]&&(_o[yo]=0);var Eo,To=!1;function bo(e){if(!To){var t=Ni.getInstance();t&&t.onReset&&t.onReset(Io),To=!0}var i=_o[yo]++;return(void 0===e?Co:e)+i}function Io(e){void 0===e&&(e=0),_o[yo]=e}function wo(e,t,i){var n=e[i],r=t[i];(n||r)&&(e[i]=function(){for(var e,t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];return r&&(e=r.apply(this,t)),n!==r&&(e=n.apply(this,t)),e})}function Ro(){return null}!function(e){function t(i,n){var r=e.call(this,i,n)||this;return function(e,t,i){for(var n=0,r=i.length;n<r;n++)wo(e,t,i[n])}(r,t.prototype,["componentDidMount","shouldComponentUpdate","getSnapshotBeforeUpdate","render","componentDidUpdate","componentWillUnmount"]),r}bi(t,e),t.prototype.componentDidUpdate=function(e,t){this._updateComponentRef(e,this.props)},t.prototype.componentDidMount=function(){this._setComponentRef(this.props.componentRef,this)},t.prototype.componentWillUnmount=function(){if(this._setComponentRef(this.props.componentRef,null),this.__disposables){for(var e=0,t=this._disposables.length;e<t;e++){var i=this.__disposables[e];i.dispose&&i.dispose()}this.__disposables=null}},Object.defineProperty(t.prototype,"className",{get:function(){if(!this.__className){var e=/function (.{1,})\(/.exec(this.constructor.toString());this.__className=e&&e.length>1?e[1]:""}return this.__className},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_disposables",{get:function(){return this.__disposables||(this.__disposables=[]),this.__disposables},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_async",{get:function(){return this.__async||(this.__async=new go(this),this._disposables.push(this.__async)),this.__async},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_events",{get:function(){return this.__events||(this.__events=new So(this),this._disposables.push(this.__events)),this.__events},enumerable:!1,configurable:!0}),t.prototype._resolveRef=function(e){var t=this;return this.__resolves||(this.__resolves={}),this.__resolves[e]||(this.__resolves[e]=function(i){return t[e]=i}),this.__resolves[e]},t.prototype._updateComponentRef=function(e,t){void 0===t&&(t={}),e&&t&&e.componentRef!==t.componentRef&&(this._setComponentRef(e.componentRef,null),this._setComponentRef(t.componentRef,this))},t.prototype._warnDeprecations=function(e){this.className,this.props},t.prototype._warnMutuallyExclusive=function(e){this.className,this.props},t.prototype._warnConditionallyRequiredProps=function(e,t,i){this.className,this.props},t.prototype._setComponentRef=function(e,t){!this._skipComponentRefResolution&&e&&("function"==typeof e&&e(t),"object"==typeof e&&(e.current=t))}}(e.Component);var Ao=((Eo={})[ao.up]=1,Eo[ao.down]=1,Eo[ao.left]=1,Eo[ao.right]=1,Eo[ao.home]=1,Eo[ao.end]=1,Eo[ao.tab]=1,Eo[ao.pageUp]=1,Eo[ao.pageDown]=1,Eo);function Po(e){return!!Ao[e]}var Mo=new WeakMap,ko=new WeakMap;function Do(e,t){var i,n=Mo.get(e);return i=n?n+t:1,Mo.set(e,i),i}function Oo(e){var t=ko.get(e);return t||(t={onMouseDown:function(t){return Ho(t,e.registeredProviders)},onPointerDown:function(t){return $o(t,e.registeredProviders)},onKeyDown:function(t){return Go(t,e.registeredProviders)},onKeyUp:function(t){return jo(t,e.registeredProviders)}},ko.set(e,t),t)}var No=e.createContext(void 0);function Lo(t){var i=e.useContext(No);e.useEffect((function(){var e,n,r,a,s=Tn(null==t?void 0:t.current);if(s&&!0!==(null===(e=s.FabricConfig)||void 0===e?void 0:e.disableFocusRects)){var o,l,c,d,u=s;if((null===(n=null==i?void 0:i.providerRef)||void 0===n?void 0:n.current)&&(null===(a=null===(r=null==i?void 0:i.providerRef)||void 0===r?void 0:r.current)||void 0===a?void 0:a.addEventListener)){u=i.providerRef.current;var h=Oo(i);o=h.onMouseDown,l=h.onPointerDown,c=h.onKeyDown,d=h.onKeyUp}else o=Ho,l=$o,c=Go,d=jo;var p=Do(u,1);return p<=1&&(u.addEventListener("mousedown",o,!0),u.addEventListener("pointerdown",l,!0),u.addEventListener("keydown",c,!0),u.addEventListener("keyup",d,!0)),function(){var e;s&&!0!==(null===(e=s.FabricConfig)||void 0===e?void 0:e.disableFocusRects)&&0===(p=Do(u,-1))&&(u.removeEventListener("mousedown",o,!0),u.removeEventListener("pointerdown",l,!0),u.removeEventListener("keydown",c,!0),u.removeEventListener("keyup",d,!0))}}}),[i,t])}var xo,Fo,Uo,Bo,Vo=function(e){return Lo(e.rootRef),null};function Ho(e,t){Gr(!1,e.target,t)}function $o(e,t){"mouse"!==e.pointerType&&Gr(!1,e.target,t)}function Go(e,t){Po(e.which)&&Gr(!0,e.target,t)}function jo(e,t){Po(e.which)&&Gr(!0,e.target,t)}function zo(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=e.filter((function(e){return e})).join(" ").trim();return""===i?void 0:i}!function(e){e[e.default=0]="default",e[e.image=1]="image",e[e.Default=1e5]="Default",e[e.Image=100001]="Image"}(xo||(xo={})),function(e){e[e.center=0]="center",e[e.contain=1]="contain",e[e.cover=2]="cover",e[e.none=3]="none",e[e.centerCover=4]="centerCover",e[e.centerContain=5]="centerContain"}(Fo||(Fo={})),function(e){e[e.landscape=0]="landscape",e[e.portrait=1]="portrait"}(Uo||(Uo={})),function(e){e[e.notLoaded=0]="notLoaded",e[e.loaded=1]="loaded",e[e.error=2]="error",e[e.errorLoaded=3]="errorLoaded"}(Bo||(Bo={}));var Wo=Cn()?e.useLayoutEffect:e.useEffect;function qo(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];var n=e.useCallback((function(e){n.current=e;for(var i=0,r=t;i<r.length;i++){var a=r[i];"function"==typeof a?a(e):a&&(a.current=e)}}),Ai([],t,!0));return n}var Ko=Ys(),Jo=/\.svg$/i,Yo=e.forwardRef((function(t,i){var n=e.useRef(),r=e.useRef(),a=function(t,i){var n=t.onLoadingStateChange,r=t.onLoad,a=t.onError,s=t.src,o=e.useState(Bo.notLoaded),l=o[0],c=o[1];Wo((function(){c(Bo.notLoaded)}),[s]),e.useEffect((function(){l===Bo.notLoaded&&i.current&&(s&&i.current.naturalWidth>0&&i.current.naturalHeight>0||i.current.complete&&Jo.test(s))&&c(Bo.loaded)})),e.useEffect((function(){null==n||n(l)}),[l]);var d=e.useCallback((function(e){null==r||r(e),s&&c(Bo.loaded)}),[s,r]),u=e.useCallback((function(e){null==a||a(e),c(Bo.error)}),[a]);return[l,d,u]}(t,r),s=a[0],o=a[1],l=a[2],c=Ds(t,Ms,["width","height"]),d=t.src,u=t.alt,h=t.width,p=t.height,g=t.shouldFadeIn,m=void 0===g||g,f=t.shouldStartVisible,v=t.className,S=t.imageFit,y=t.role,C=t.maximizeFrame,_=t.styles,E=t.theme,T=t.loading,b=function(t,i,n,r){var a=e.useRef(i),s=e.useRef();return(void 0===s||a.current===Bo.notLoaded&&i===Bo.loaded)&&(s.current=function(e,t,i,n){var r=e.imageFit,a=e.width,s=e.height;if(void 0!==e.coverStyle)return e.coverStyle;if(t===Bo.loaded&&(r===Fo.cover||r===Fo.contain||r===Fo.centerContain||r===Fo.centerCover)&&i.current&&n.current){var o;if(o="number"==typeof a&&"number"==typeof s&&r!==Fo.centerContain&&r!==Fo.centerCover?a/s:n.current.clientWidth/n.current.clientHeight,i.current.naturalWidth/i.current.naturalHeight>o)return Uo.landscape}return Uo.portrait}(t,i,n,r)),a.current=i,s.current}(t,s,r,n),I=Ko(_,{theme:E,className:v,width:h,height:p,maximizeFrame:C,shouldFadeIn:m,shouldStartVisible:f,isLoaded:s===Bo.loaded||s===Bo.notLoaded&&t.shouldStartVisible,isLandscape:b===Uo.landscape,isCenter:S===Fo.center,isCenterContain:S===Fo.centerContain,isCenterCover:S===Fo.centerCover,isContain:S===Fo.contain,isCover:S===Fo.cover,isNone:S===Fo.none,isError:s===Bo.error,isNotImageFit:void 0===S});return e.createElement("div",{className:I.root,style:{width:h,height:p},ref:n},e.createElement("img",Ii({},c,{onLoad:o,onError:l,key:"fabricImage"+t.src||"",className:I.image,ref:qo(r,i),src:d,alt:u,role:y,loading:T})))}));Yo.displayName="ImageBase";var Qo={root:"ms-Image",rootMaximizeFrame:"ms-Image--maximizeFrame",image:"ms-Image-image",imageCenter:"ms-Image-image--center",imageContain:"ms-Image-image--contain",imageCover:"ms-Image-image--cover",imageCenterContain:"ms-Image-image--centerContain",imageCenterCover:"ms-Image-image--centerCover",imageNone:"ms-Image-image--none",imageLandscape:"ms-Image-image--landscape",imagePortrait:"ms-Image-image--portrait"},Zo=Ws(Yo,(function(e){var t=e.className,i=e.width,n=e.height,r=e.maximizeFrame,a=e.isLoaded,s=e.shouldFadeIn,o=e.shouldStartVisible,l=e.isLandscape,c=e.isCenter,d=e.isContain,u=e.isCover,h=e.isCenterContain,p=e.isCenterCover,g=e.isNone,m=e.isError,f=e.isNotImageFit,v=e.theme,S=Kr(Qo,v),y={position:"absolute",left:"50% /* @noflip */",top:"50%",transform:"translate(-50%,-50%)"},C=Tn(),_=void 0!==C&&void 0===C.navigator.msMaxTouchPoints,E=d&&l||u&&!l?{width:"100%",height:"auto"}:{width:"auto",height:"100%"};return{root:[S.root,v.fonts.medium,{overflow:"hidden"},r&&[S.rootMaximizeFrame,{height:"100%",width:"100%"}],a&&s&&!o&&Dr.fadeIn400,(c||d||u||h||p)&&{position:"relative"},t],image:[S.image,{display:"block",opacity:0},a&&["is-loaded",{opacity:1}],c&&[S.imageCenter,y],d&&[S.imageContain,_&&{width:"100%",height:"100%",objectFit:"contain"},!_&&E,!_&&y],u&&[S.imageCover,_&&{width:"100%",height:"100%",objectFit:"cover"},!_&&E,!_&&y],h&&[S.imageCenterContain,l&&{maxWidth:"100%"},!l&&{maxHeight:"100%"},y],p&&[S.imageCenterCover,l&&{maxHeight:"100%"},!l&&{maxWidth:"100%"},y],g&&[S.imageNone,{width:"auto",height:"auto"}],f&&[!!i&&!n&&{height:"auto",width:"100%"},!i&&!!n&&{height:"100%",width:"auto"},!!i&&!!n&&{height:"100%",width:"100%"}],l&&S.imageLandscape,!l&&S.imagePortrait,!a&&"is-notLoaded",s&&"is-fadeIn",m&&"is-error"]}}),void 0,{scope:"Image"},!0);Zo.displayName="Image";var Xo=Xa({root:{display:"inline-block"},placeholder:["ms-Icon-placeHolder",{width:"1em"}],image:["ms-Icon-imageContainer",{overflow:"hidden"}]}),el="ms-Icon",tl=vn((function(e){var t=function(e){var t=void 0,i=Ga.__options;if(e=e?za(e):"",e=Ga.__remapped[e]||e)if(t=Ga[e]){var n=t.subset;n&&n.fontFace&&(n.isRegistered||(ma(n.fontFace),n.isRegistered=!0),n.className||(n.className=cn(n.style,{fontFamily:n.fontFace.fontFamily,fontWeight:n.fontFace.fontWeight||"normal",fontStyle:n.fontFace.fontStyle||"normal"})))}else!i.disableWarnings&&i.warnOnMissingIcons&&$a('The icon "'.concat(e,'" was used but not registered. See https://github.com/microsoft/fluentui/wiki/Using-icons for more information.'));return t}(e)||{subset:{},code:void 0},i=t.code,n=t.subset;return i?{children:i,iconClassName:n.className,fontFamily:n.fontFace&&n.fontFace.fontFamily,mergeImageProps:n.mergeImageProps}:null}),void 0,!0),il=function(t){var i=t.iconName,n=t.className,r=t.style,a=void 0===r?{}:r,s=tl(i)||{},o=s.iconClassName,l=s.children,c=s.fontFamily,d=s.mergeImageProps,u=Ds(t,ds),h=t["aria-label"]||t.title,p=t["aria-label"]||t["aria-labelledby"]||t.title?{role:d?void 0:"img"}:{"aria-hidden":!0},g=l;return d&&"object"==typeof l&&"object"==typeof l.props&&h&&(g=e.cloneElement(l,{alt:h})),e.createElement("i",Ii({"data-icon-name":i},p,u,d?{title:void 0,"aria-label":void 0}:{},{className:Os(el,Xo.root,o,!i&&Xo.placeholder,n),style:Ii({fontFamily:c},a)}),g)},nl=(vn((function(e,t,i){return il({iconName:e,className:t,"aria-label":i})})),Ys({cacheSize:100})),rl=function(t){function i(e){var i=t.call(this,e)||this;return i._onImageLoadingStateChange=function(e){i.props.imageProps&&i.props.imageProps.onLoadingStateChange&&i.props.imageProps.onLoadingStateChange(e),e===Bo.error&&i.setState({imageLoadError:!0})},i.state={imageLoadError:!1},i}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.children,n=t.className,r=t.styles,a=t.iconName,s=t.imageErrorAs,o=t.theme,l="string"==typeof a&&0===a.length,c=!!this.props.imageProps||this.props.iconType===xo.image||this.props.iconType===xo.Image,d=tl(a)||{},u=d.iconClassName,h=d.children,p=d.mergeImageProps,g=nl(r,{theme:o,className:n,iconClassName:u,isImage:c,isPlaceholder:l}),m=c?"span":"i",f=Ds(this.props,ds,["aria-label"]),v=this.state.imageLoadError,S=Ii(Ii({},this.props.imageProps),{onLoadingStateChange:this._onImageLoadingStateChange}),y=v&&s||Zo,C=this.props["aria-label"]||this.props.ariaLabel,_=S.alt||C||this.props.title,E=_||this.props["aria-labelledby"]||S["aria-label"]||S["aria-labelledby"]?{role:c||p?void 0:"img","aria-label":c||p?void 0:_}:{"aria-hidden":!0},T=h;return p&&h&&"object"==typeof h&&_&&(T=e.cloneElement(h,{alt:_})),e.createElement(m,Ii({"data-icon-name":a},E,f,p?{title:void 0,"aria-label":void 0}:{},{className:g.root}),c?e.createElement(y,Ii({},S)):i||T)},i}(e.Component),al=Ws(rl,(function(e){var t=e.className,i=e.iconClassName,n=e.isPlaceholder,r=e.isImage,a=e.styles;return{root:[n&&Xo.placeholder,Xo.root,r&&Xo.image,i,t,a&&a.root,a&&a.imageContainer]}}),void 0,{scope:"Icon"},!0);al.displayName="Icon";var sl,ol=function(t){var i=t.className,n=t.imageProps,r=Ds(t,ds,["aria-label","aria-labelledby","title","aria-describedby"]),a=n.alt||t["aria-label"],s=a||t["aria-labelledby"]||t.title||n["aria-label"]||n["aria-labelledby"]||n.title,o={"aria-labelledby":t["aria-labelledby"],"aria-describedby":t["aria-describedby"],title:t.title},l=s?{}:{"aria-hidden":!0};return e.createElement("div",Ii({},l,r,{className:Os(el,Xo.root,Xo.image,i)}),e.createElement(Zo,Ii({},o,n,{alt:s?a:""})))},ll={topLeftEdge:0,topCenter:1,topRightEdge:2,topAutoEdge:3,bottomLeftEdge:4,bottomCenter:5,bottomRightEdge:6,bottomAutoEdge:7,leftTopEdge:8,leftCenter:9,leftBottomEdge:10,rightTopEdge:11,rightCenter:12,rightBottomEdge:13},cl=Sn((function(e){return Sn((function(t){var i=Sn((function(e){return function(i){return t(i,e)}}));return function(n,r){return e(n,r?i(r):t)}}))}));!function(e){e[e.Normal=0]="Normal",e[e.Divider=1]="Divider",e[e.Header=2]="Header",e[e.Section=3]="Section"}(sl||(sl={}));var dl;function ul(e,t,i){void 0===i&&(i=!0);var n=!1;if(e&&t)if(i)if(e===t)n=!0;else for(n=!1;t;){var r=to(t);if(r===e){n=!0;break}t=r}else e.contains&&(n=e.contains(t));return n}!function(e){e[e.vertical=0]="vertical",e[e.horizontal=1]="horizontal",e[e.bidirectional=2]="bidirectional",e[e.domOrder=3]="domOrder"}(dl||(dl={}));var hl="data-is-focusable",pl="data-is-visible",gl="data-focuszone-id",ml="data-is-sub-focuszone";function fl(e,t,i){return yl(e,t,!0,!1,!1,i)}function vl(e,t,i){return Sl(e,t,!0,!1,!0,i)}function Sl(e,t,i,n,r,a,s,o){if(!t||!s&&t===e)return null;var l=Cl(t);if(r&&l&&(a||!Tl(t)&&!bl(t))){var c=Sl(e,t.lastElementChild,!0,!0,!0,a,s,o);if(c){if(o&&El(c,!0)||!o)return c;var d=Sl(e,c.previousElementSibling,!0,!0,!0,a,s,o);if(d)return d;for(var u=c.parentElement;u&&u!==t;){var h=Sl(e,u.previousElementSibling,!0,!0,!0,a,s,o);if(h)return h;u=u.parentElement}}}return i&&l&&El(t,o)?t:Sl(e,t.previousElementSibling,!0,!0,!0,a,s,o)||(n?null:Sl(e,t.parentElement,!0,!1,!1,a,s,o))}function yl(e,t,i,n,r,a,s,o,l){if(!t||t===e&&r&&!s)return null;var c=(l?_l:Cl)(t);if(i&&c&&El(t,o))return t;if(!r&&c&&(a||!Tl(t)&&!bl(t))){var d=yl(e,t.firstElementChild,!0,!0,!1,a,s,o,l);if(d)return d}return t===e?null:yl(e,t.nextElementSibling,!0,!0,!1,a,s,o,l)||(n?null:yl(e,t.parentElement,!1,!1,!0,a,s,o,l))}function Cl(e){if(!e||!e.getAttribute)return!1;var t=e.getAttribute(pl);return null!=t?"true"===t:0!==e.offsetHeight||null!==e.offsetParent||!0===e.isVisible}function _l(e,t){var i=null!=t?t:Tn();return!!e&&Cl(e)&&!e.hidden&&"hidden"!==i.getComputedStyle(e).visibility}function El(e,t){if(!e||e.disabled)return!1;var i=0,n=null;e&&e.getAttribute&&(n=e.getAttribute("tabIndex"))&&(i=parseInt(n,10));var r=e.getAttribute?e.getAttribute(hl):null,a=null!==n&&i>=0,s=!!e&&"false"!==r&&("A"===e.tagName||"BUTTON"===e.tagName||"INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName||"true"===r||a);return t?-1!==i&&s:s}function Tl(e){return!!(e&&e.getAttribute&&e.getAttribute(gl))}function bl(e){return!(!e||!e.getAttribute||"true"!==e.getAttribute(ml))}function Il(e,t,i){return"true"!==function(e,t,i){var n=io(e,(function(e){return e.hasAttribute(t)}),i);return n&&n.getAttribute(t)}(e,t,null!=i?i:_n())}var wl,Rl=void 0;function Al(e){if(e){var t=Tn(e);t&&(void 0!==Rl&&t.cancelAnimationFrame(Rl),Rl=t.requestAnimationFrame((function(){e&&e.focus(),Rl=void 0})))}}var Pl=0,Ml=cn({overflow:"hidden !important"}),kl="data-is-scrollable",Dl=function(e,t){var i=Tn(e);if(e&&i){var n=0,r=null,a=i.getComputedStyle(e);t.on(e,"touchstart",(function(e){1===e.targetTouches.length&&(n=e.targetTouches[0].clientY)}),{passive:!1}),t.on(e,"touchmove",(function(e){if(1===e.targetTouches.length&&(e.stopPropagation(),r)){var t=e.targetTouches[0].clientY-n,s=Ll(e.target);s&&r!==s&&(r=s,a=i.getComputedStyle(r));var o=r.scrollTop,l="column-reverse"===(null==a?void 0:a.flexDirection);0===o&&(l?t<0:t>0)&&e.preventDefault(),r.scrollHeight-Math.abs(Math.ceil(o))<=r.clientHeight&&(l?t>0:t<0)&&e.preventDefault()}}),{passive:!1}),r=e}},Ol=function(e,t){e&&t.on(e,"touchmove",(function(e){e.stopPropagation()}),{passive:!1})},Nl=function(e){e.preventDefault()};function Ll(e){for(var t=e,i=_n(e);t&&t!==i.body;){if("true"===t.getAttribute(kl))return t;t=t.parentElement}for(t=e;t&&t!==i.body;){if("false"!==t.getAttribute(kl)){var n=getComputedStyle(t),r=n?n.getPropertyValue("overflow-y"):"";if(r&&("scroll"===r||"auto"===r))return t}t=t.parentElement}return t&&t!==i.body||(t=Tn(e)),t}var xl,Fl="data-is-focusable",Ul="data-focuszone-id",Bl="tabindex",Vl="data-no-vertical-wrap",Hl="data-no-horizontal-wrap",$l=999999999,Gl=-999999999;function jl(e,t){var i;"function"==typeof MouseEvent?i=new MouseEvent("click",{ctrlKey:null==t?void 0:t.ctrlKey,metaKey:null==t?void 0:t.metaKey,shiftKey:null==t?void 0:t.shiftKey,altKey:null==t?void 0:t.altKey,bubbles:null==t?void 0:t.bubbles,cancelable:null==t?void 0:t.cancelable}):(i=document.createEvent("MouseEvents")).initMouseEvent("click",!!t&&t.bubbles,!!t&&t.cancelable,window,0,0,0,0,0,!!t&&t.ctrlKey,!!t&&t.altKey,!!t&&t.shiftKey,!!t&&t.metaKey,0,null),e.dispatchEvent(i)}var zl,Wl={},ql=new Set,Kl=["text","number","password","email","tel","url","search","textarea"],Jl=!1,Yl=function(t){function i(n){var r,a,s,o,l=this;(l=t.call(this,n)||this)._root=e.createRef(),l._mergedRef=eo(),l._onFocus=function(e){if(!l._portalContainsElement(e.target)){var t,i=l.props,n=i.onActiveElementChanged,r=i.doNotAllowFocusEventToPropagate,a=i.stopFocusPropagation,s=i.onFocusNotification,o=i.onFocus,c=i.shouldFocusInnerElementWhenReceivedFocus,d=i.defaultTabbableElement,u=l._isImmediateDescendantOfZone(e.target);if(u)t=e.target;else for(var h=e.target;h&&h!==l._root.current;){if(El(h)&&l._isImmediateDescendantOfZone(h)){t=h;break}h=to(h,Jl)}if(c&&e.target===l._root.current){var p=d&&"function"==typeof d&&l._root.current&&d(l._root.current);p&&El(p)?(t=p,p.focus()):(l.focus(!0),l._activeElement&&(t=null))}var g=!l._activeElement;t&&t!==l._activeElement&&((u||g)&&l._setFocusAlignment(t,!0,!0),l._activeElement=t,g&&l._updateTabIndexes()),n&&n(l._activeElement,e),(a||r)&&e.stopPropagation(),o?o(e):s&&s()}},l._onBlur=function(){l._setParkedFocus(!1)},l._onMouseDown=function(e){if(!l._portalContainsElement(e.target)&&!l.props.disabled){for(var t=e.target,i=[];t&&t!==l._root.current;)i.push(t),t=to(t,Jl);for(;i.length&&((t=i.pop())&&El(t)&&l._setActiveElement(t,!0),!Tl(t)););}},l._onKeyDown=function(e,t){if(!l._portalContainsElement(e.target)){var i=l.props,n=i.direction,r=i.disabled,a=i.isInnerZoneKeystroke,s=i.pagingSupportDisabled,o=i.shouldEnterInnerZone;if(!(r||(l.props.onKeyDown&&l.props.onKeyDown(e),e.isDefaultPrevented()||l._getDocument().activeElement===l._root.current&&l._isInnerZone))){if((o&&o(e)||a&&a(e))&&l._isImmediateDescendantOfZone(e.target)){var c=l._getFirstInnerZone();if(c){if(!c.focus(!0))return}else{if(!bl(e.target))return;if(!l.focusElement(yl(e.target,e.target.firstChild,!0)))return}}else{if(e.altKey)return;switch(e.which){case ao.space:if(l._shouldRaiseClicksOnSpace&&l._tryInvokeClickForFocusable(e.target,e))break;return;case ao.left:if(n!==dl.vertical&&(l._preventDefaultWhenHandled(e),l._moveFocusLeft(t)))break;return;case ao.right:if(n!==dl.vertical&&(l._preventDefaultWhenHandled(e),l._moveFocusRight(t)))break;return;case ao.up:if(n!==dl.horizontal&&(l._preventDefaultWhenHandled(e),l._moveFocusUp()))break;return;case ao.down:if(n!==dl.horizontal&&(l._preventDefaultWhenHandled(e),l._moveFocusDown()))break;return;case ao.pageDown:if(!s&&l._moveFocusPaging(!0))break;return;case ao.pageUp:if(!s&&l._moveFocusPaging(!1))break;return;case ao.tab:if(l.props.allowTabKey||1===l.props.handleTabKey||2===l.props.handleTabKey&&l._isElementInput(e.target)){var d=!1;if(l._processingTabKey=!0,d=n!==dl.vertical&&l._shouldWrapFocus(l._activeElement,Hl)?(Rn(t)?!e.shiftKey:e.shiftKey)?l._moveFocusLeft(t):l._moveFocusRight(t):e.shiftKey?l._moveFocusUp():l._moveFocusDown(),l._processingTabKey=!1,d)break;l.props.shouldResetActiveElementWhenTabFromZone&&(l._activeElement=null)}return;case ao.home:if(l._isContentEditableElement(e.target)||l._isElementInput(e.target)&&!l._shouldInputLoseFocus(e.target,!1))return!1;var u=l._root.current&&l._root.current.firstChild;if(l._root.current&&u&&l.focusElement(yl(l._root.current,u,!0)))break;return;case ao.end:if(l._isContentEditableElement(e.target)||l._isElementInput(e.target)&&!l._shouldInputLoseFocus(e.target,!0))return!1;var h=l._root.current&&l._root.current.lastChild;if(l._root.current&&l.focusElement(Sl(l._root.current,h,!0,!0,!0)))break;return;case ao.enter:if(l._shouldRaiseClicksOnEnter&&l._tryInvokeClickForFocusable(e.target,e))break;return;default:return}}e.preventDefault(),e.stopPropagation()}}},l._getHorizontalDistanceFromCenter=function(e,t,i){var n=l._focusAlignment.left||l._focusAlignment.x||0,r=Math.floor(i.top),a=Math.floor(t.bottom),s=Math.floor(i.bottom),o=Math.floor(t.top);return e&&r>a||!e&&s<o?n>=i.left&&n<=i.left+i.width?0:Math.abs(i.left+i.width/2-n):l._shouldWrapFocus(l._activeElement,Vl)?$l:Gl},lo(l),l._id=bo("FocusZone"),l._focusAlignment={left:0,top:0},l._processingTabKey=!1;var c=null===(a=null!==(r=n.shouldRaiseClicks)&&void 0!==r?r:i.defaultProps.shouldRaiseClicks)||void 0===a||a;return l._shouldRaiseClicksOnEnter=null!==(s=n.shouldRaiseClicksOnEnter)&&void 0!==s?s:c,l._shouldRaiseClicksOnSpace=null!==(o=n.shouldRaiseClicksOnSpace)&&void 0!==o?o:c,l}return bi(i,t),i.getOuterZones=function(){return ql.size},i._onKeyDownCapture=function(e){e.which===ao.tab&&ql.forEach((function(e){return e._updateTabIndexes()}))},i.prototype.componentDidMount=function(){var e=this._root.current;if(Wl[this._id]=this,e){for(var t=to(e,Jl);t&&t!==this._getDocument().body&&1===t.nodeType;){if(Tl(t)){this._isInnerZone=!0;break}t=to(t,Jl)}this._isInnerZone||(ql.add(this),this._root.current&&this._root.current.addEventListener("keydown",i._onKeyDownCapture,!0)),this._root.current&&this._root.current.addEventListener("blur",this._onBlur,!0),this._updateTabIndexes(),this.props.defaultTabbableElement&&"string"==typeof this.props.defaultTabbableElement?this._activeElement=this._getDocument().querySelector(this.props.defaultTabbableElement):this.props.defaultActiveElement&&(this._activeElement=this._getDocument().querySelector(this.props.defaultActiveElement)),this.props.shouldFocusOnMount&&this.focus()}},i.prototype.componentDidUpdate=function(){var e=this._root.current,t=this._getDocument();if((this._activeElement&&!ul(this._root.current,this._activeElement,Jl)||this._defaultFocusElement&&!ul(this._root.current,this._defaultFocusElement,Jl))&&(this._activeElement=null,this._defaultFocusElement=null,this._updateTabIndexes()),!this.props.preventFocusRestoration&&t&&this._lastIndexPath&&(t.activeElement===t.body||null===t.activeElement||t.activeElement===e)){var i=function(e,t){for(var i=e,n=0,r=t;n<r.length;n++){var a=r[n],s=i.children[Math.min(a,i.children.length-1)];if(!s)break;i=s}return El(i)&&Cl(i)?i:yl(e,i,!0)||Sl(e,i)}(e,this._lastIndexPath);i?(this._setActiveElement(i,!0),i.focus(),this._setParkedFocus(!1)):this._setParkedFocus(!0)}},i.prototype.componentWillUnmount=function(){delete Wl[this._id],this._isInnerZone||(ql.delete(this),this._root.current&&this._root.current.removeEventListener("keydown",i._onKeyDownCapture,!0)),this._root.current&&this._root.current.removeEventListener("blur",this._onBlur,!0),this._activeElement=null,this._defaultFocusElement=null},i.prototype.render=function(){var t=this,i=this.props,n=i.as,r=i.elementType,a=i.rootProps,s=i.ariaDescribedBy,o=i.ariaLabelledBy,l=i.className,c=Ds(this.props,ds),d=n||r||"div";this._evaluateFocusBeforeRender();var u=Ua();return e.createElement(d,Ii({"aria-labelledby":o,"aria-describedby":s},c,a,{className:Os((xl||(xl=cn({selectors:{":focus":{outline:"none"}}},"ms-FocusZone")),xl),l),ref:this._mergedRef(this.props.elementRef,this._root),"data-focuszone-id":this._id,onKeyDown:function(e){return t._onKeyDown(e,u)},onFocus:this._onFocus,onMouseDownCapture:this._onMouseDown}),this.props.children)},i.prototype.focus=function(e,t){if(void 0===e&&(e=!1),void 0===t&&(t=!1),this._root.current){if(!e&&"true"===this._root.current.getAttribute(Fl)&&this._isInnerZone){var i=this._getOwnerZone(this._root.current);if(i!==this._root.current){var n=Wl[i.getAttribute(Ul)];return!!n&&n.focusElement(this._root.current)}return!1}if(!e&&this._activeElement&&ul(this._root.current,this._activeElement)&&El(this._activeElement)&&(!t||_l(this._activeElement)))return this._activeElement.focus(),!0;var r=this._root.current.firstChild;return this.focusElement(yl(this._root.current,r,!0,void 0,void 0,void 0,void 0,void 0,t))}return!1},i.prototype.focusLast=function(){if(this._root.current){var e=this._root.current&&this._root.current.lastChild;return this.focusElement(Sl(this._root.current,e,!0,!0,!0))}return!1},i.prototype.focusElement=function(e,t){var i=this.props,n=i.onBeforeFocus,r=i.shouldReceiveFocus;return!(r&&!r(e)||n&&!n(e)||!e||(this._setActiveElement(e,t),this._activeElement&&this._activeElement.focus(),0))},i.prototype.setFocusAlignment=function(e){this._focusAlignment=e},Object.defineProperty(i.prototype,"defaultFocusElement",{get:function(){return this._defaultFocusElement},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"activeElement",{get:function(){return this._activeElement},enumerable:!1,configurable:!0}),i.prototype._evaluateFocusBeforeRender=function(){var e=this._root.current,t=this._getDocument();if(t){var i=t.activeElement;if(i!==e){var n=ul(e,i,!1);this._lastIndexPath=n?function(e,t){for(var i=[];t&&e&&t!==e;){var n=to(t,!0);if(null===n)return[];i.unshift(Array.prototype.indexOf.call(n.children,t)),t=n}return i}(e,i):void 0}}},i.prototype._setParkedFocus=function(e){var t=this._root.current;t&&this._isParked!==e&&(this._isParked=e,e?(this.props.allowFocusRoot||(this._parkedTabIndex=t.getAttribute("tabindex"),t.setAttribute("tabindex","-1")),t.focus()):this.props.allowFocusRoot||(this._parkedTabIndex?(t.setAttribute("tabindex",this._parkedTabIndex),this._parkedTabIndex=void 0):t.removeAttribute("tabindex")))},i.prototype._setActiveElement=function(e,t){var i=this._activeElement;this._activeElement=e,i&&(Tl(i)&&this._updateTabIndexes(i),i.tabIndex=-1),this._activeElement&&(this._focusAlignment&&!t||this._setFocusAlignment(e,!0,!0),this._activeElement.tabIndex=0)},i.prototype._preventDefaultWhenHandled=function(e){this.props.preventDefaultWhenHandled&&e.preventDefault()},i.prototype._tryInvokeClickForFocusable=function(e,t){var i=e;if(i===this._root.current)return!1;do{if("BUTTON"===i.tagName||"A"===i.tagName||"INPUT"===i.tagName||"TEXTAREA"===i.tagName||"SUMMARY"===i.tagName)return!1;if(this._isImmediateDescendantOfZone(i)&&"true"===i.getAttribute(Fl)&&"true"!==i.getAttribute("data-disable-click-on-enter"))return jl(i,t),!0;i=to(i,Jl)}while(i!==this._root.current);return!1},i.prototype._getFirstInnerZone=function(e){if(!(e=e||this._activeElement||this._root.current))return null;if(Tl(e))return Wl[e.getAttribute(Ul)];for(var t=e.firstElementChild;t;){if(Tl(t))return Wl[t.getAttribute(Ul)];var i=this._getFirstInnerZone(t);if(i)return i;t=t.nextElementSibling}return null},i.prototype._moveFocus=function(e,t,i,n){void 0===n&&(n=!0);var r=this._activeElement,a=-1,s=void 0,o=!1,l=this.props.direction===dl.bidirectional;if(!r||!this._root.current)return!1;if(this._isElementInput(r)&&!this._shouldInputLoseFocus(r,e))return!1;var c=l?r.getBoundingClientRect():null;do{if(r=e?yl(this._root.current,r):Sl(this._root.current,r),!l){s=r;break}if(r){var d=t(c,r.getBoundingClientRect());if(-1===d&&-1===a){s=r;break}if(d>-1&&(-1===a||d<a)&&(a=d,s=r),a>=0&&d<0)break}}while(r);if(s&&s!==this._activeElement)o=!0,this.focusElement(s);else if(this.props.isCircularNavigation&&n)return e?this.focusElement(yl(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(Sl(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return o},i.prototype._moveFocusDown=function(){var e=this,t=-1,i=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!0,(function(n,r){var a=-1,s=Math.floor(r.top),o=Math.floor(n.bottom);return s<o?e._shouldWrapFocus(e._activeElement,Vl)?$l:Gl:((-1===t&&s>=o||s===t)&&(t=s,a=i>=r.left&&i<=r.left+r.width?0:Math.abs(r.left+r.width/2-i)),a)}))&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},i.prototype._moveFocusUp=function(){var e=this,t=-1,i=this._focusAlignment.left||this._focusAlignment.x||0;return!!this._moveFocus(!1,(function(n,r){var a=-1,s=Math.floor(r.bottom),o=Math.floor(r.top),l=Math.floor(n.top);return s>l?e._shouldWrapFocus(e._activeElement,Vl)?$l:Gl:((-1===t&&s<=l||o===t)&&(t=o,a=i>=r.left&&i<=r.left+r.width?0:Math.abs(r.left+r.width/2-i)),a)}))&&(this._setFocusAlignment(this._activeElement,!1,!0),!0)},i.prototype._moveFocusLeft=function(e){var t=this,i=this._shouldWrapFocus(this._activeElement,Hl);return!!this._moveFocus(Rn(e),(function(n,r){var a=-1;return(Rn(e)?parseFloat(r.top.toFixed(3))<parseFloat(n.bottom.toFixed(3)):parseFloat(r.bottom.toFixed(3))>parseFloat(n.top.toFixed(3)))&&r.right<=n.right&&t.props.direction!==dl.vertical?a=n.right-r.right:i||(a=Gl),a}),void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},i.prototype._moveFocusRight=function(e){var t=this,i=this._shouldWrapFocus(this._activeElement,Hl);return!!this._moveFocus(!Rn(e),(function(n,r){var a=-1;return(Rn(e)?parseFloat(r.bottom.toFixed(3))>parseFloat(n.top.toFixed(3)):parseFloat(r.top.toFixed(3))<parseFloat(n.bottom.toFixed(3)))&&r.left>=n.left&&t.props.direction!==dl.vertical?a=r.left-n.left:i||(a=Gl),a}),void 0,i)&&(this._setFocusAlignment(this._activeElement,!0,!1),!0)},i.prototype._moveFocusPaging=function(e,t){void 0===t&&(t=!0);var i=this._activeElement;if(!i||!this._root.current)return!1;if(this._isElementInput(i)&&!this._shouldInputLoseFocus(i,e))return!1;var n=Ll(i);if(!n)return!1;var r=-1,a=void 0,s=-1,o=-1,l=n.clientHeight,c=i.getBoundingClientRect();do{if(i=e?yl(this._root.current,i):Sl(this._root.current,i)){var d=i.getBoundingClientRect(),u=Math.floor(d.top),h=Math.floor(c.bottom),p=Math.floor(d.bottom),g=Math.floor(c.top),m=this._getHorizontalDistanceFromCenter(e,c,d);if(e&&u>h+l||!e&&p<g-l)break;m>-1&&(e&&u>s?(s=u,r=m,a=i):!e&&p<o?(o=p,r=m,a=i):(-1===r||m<=r)&&(r=m,a=i))}}while(i);var f=!1;if(a&&a!==this._activeElement)f=!0,this.focusElement(a),this._setFocusAlignment(a,!1,!0);else if(this.props.isCircularNavigation&&t)return e?this.focusElement(yl(this._root.current,this._root.current.firstElementChild,!0)):this.focusElement(Sl(this._root.current,this._root.current.lastElementChild,!0,!0,!0));return f},i.prototype._setFocusAlignment=function(e,t,i){if(this.props.direction===dl.bidirectional&&(!this._focusAlignment||t||i)){var n=e.getBoundingClientRect(),r=n.left+n.width/2,a=n.top+n.height/2;this._focusAlignment||(this._focusAlignment={left:r,top:a}),t&&(this._focusAlignment.left=r),i&&(this._focusAlignment.top=a)}},i.prototype._isImmediateDescendantOfZone=function(e){return this._getOwnerZone(e)===this._root.current},i.prototype._getOwnerZone=function(e){for(var t=to(e,Jl);t&&t!==this._root.current&&t!==this._getDocument().body;){if(Tl(t))return t;t=to(t,Jl)}return t},i.prototype._updateTabIndexes=function(e){!this._activeElement&&this.props.defaultTabbableElement&&"function"==typeof this.props.defaultTabbableElement&&(this._activeElement=this.props.defaultTabbableElement(this._root.current)),!e&&this._root.current&&(this._defaultFocusElement=null,e=this._root.current,this._activeElement&&!ul(e,this._activeElement)&&(this._activeElement=null)),this._activeElement&&!El(this._activeElement)&&(this._activeElement=null);for(var t=e&&e.children,i=0;t&&i<t.length;i++){var n=t[i];Tl(n)?"true"===n.getAttribute(Fl)&&(this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(Bl)&&n.setAttribute(Bl,"-1"):(this._defaultFocusElement=n,"0"!==n.getAttribute(Bl)&&n.setAttribute(Bl,"0"))):(n.getAttribute&&"false"===n.getAttribute(Fl)&&n.setAttribute(Bl,"-1"),El(n)?this.props.disabled?n.setAttribute(Bl,"-1"):this._isInnerZone||(this._activeElement||this._defaultFocusElement)&&this._activeElement!==n?"-1"!==n.getAttribute(Bl)&&n.setAttribute(Bl,"-1"):(this._defaultFocusElement=n,"0"!==n.getAttribute(Bl)&&n.setAttribute(Bl,"0")):"svg"===n.tagName&&"false"!==n.getAttribute("focusable")&&n.setAttribute("focusable","false")),this._updateTabIndexes(n)}},i.prototype._isContentEditableElement=function(e){return e&&"true"===e.getAttribute("contenteditable")},i.prototype._isElementInput=function(e){return!(!e||!e.tagName||"input"!==e.tagName.toLowerCase()&&"textarea"!==e.tagName.toLowerCase())},i.prototype._shouldInputLoseFocus=function(e,t){if(!this._processingTabKey&&e&&e.type&&Kl.indexOf(e.type.toLowerCase())>-1){var i=e.selectionStart,n=i!==e.selectionEnd,r=e.value,a=e.readOnly;if(n||i>0&&!t&&!a||i!==r.length&&t&&!a||this.props.handleTabKey&&(!this.props.shouldInputLoseFocusOnArrowKey||!this.props.shouldInputLoseFocusOnArrowKey(e)))return!1}return!0},i.prototype._shouldWrapFocus=function(e,t){return!this.props.checkForNoWrap||Il(e,t)},i.prototype._portalContainsElement=function(e){return e&&!!this._root.current&&ro(e,this._root.current)},i.prototype._getDocument=function(){return _n(this._root.current)},i.defaultProps={isCircularNavigation:!1,direction:dl.bidirectional,shouldRaiseClicks:!0,"data-tabster":'{"uncontrolled": {}}'},i}(e.Component);function Ql(e){var t;if(void 0===zl||e){var i=Tn(),n=null===(t=null==i?void 0:i.navigator)||void 0===t?void 0:t.userAgent;zl=!!n&&-1!==n.indexOf("Macintosh")}return!!zl}var Zl=function(){return!!(window&&window.navigator&&window.navigator.userAgent)&&/iPad|iPhone|iPod/i.test(window.navigator.userAgent)};function Xl(e,t){for(var i=Ii({},t),n=0,r=Object.keys(e);n<r.length;n++){var a=r[n];void 0===i[a]&&(i[a]=e[a])}return i}var ec,tc,ic=Sn((function(t){var i=t;return Sn((function(n){if(t===n)throw new Error("Attempted to compose a component with itself.");var r=n,a=Sn((function(t){return function(i){return e.createElement(r,Ii({},i,{defaultRender:t}))}}));return function(t){var n=t.defaultRender;return e.createElement(i,Ii({},t,{defaultRender:n?a(n):r}))}}))}));function nc(e,t){return ic(e)(t)}function rc(e){return e.canCheck?!(!e.isChecked&&!e.checked):"boolean"==typeof e.isChecked?e.isChecked:"boolean"==typeof e.checked?e.checked:null}function ac(e){return!(!e.subMenuProps&&!e.items)}function sc(e){return!(!e.isDisabled&&!e.disabled)}function oc(e){return null!==rc(e)?"menuitemcheckbox":"menuitem"}function lc(e,t,i,n){return e.addEventListener(t,i,n),function(){return e.removeEventListener(t,i,n)}}!function(e){e[e.top=1]="top",e[e.bottom=-1]="bottom",e[e.left=2]="left",e[e.right=-2]="right"}(ec||(ec={})),function(e){e[e.top=0]="top",e[e.bottom=1]="bottom",e[e.start=2]="start",e[e.end=3]="end"}(tc||(tc={}));var cc,dc=function(){function e(e,t,i,n){void 0===e&&(e=0),void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.top=i,this.bottom=n,this.left=e,this.right=t}return Object.defineProperty(e.prototype,"width",{get:function(){return this.right-this.left},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this.bottom-this.top},enumerable:!1,configurable:!0}),e.prototype.equals=function(e){return parseFloat(this.top.toFixed(4))===parseFloat(e.top.toFixed(4))&&parseFloat(this.bottom.toFixed(4))===parseFloat(e.bottom.toFixed(4))&&parseFloat(this.left.toFixed(4))===parseFloat(e.left.toFixed(4))&&parseFloat(this.right.toFixed(4))===parseFloat(e.right.toFixed(4))},e}();function uc(e,t,i){return{targetEdge:e,alignmentEdge:t,isAuto:i}}var hc=((cc={})[ll.topLeftEdge]=uc(ec.top,ec.left),cc[ll.topCenter]=uc(ec.top),cc[ll.topRightEdge]=uc(ec.top,ec.right),cc[ll.topAutoEdge]=uc(ec.top,void 0,!0),cc[ll.bottomLeftEdge]=uc(ec.bottom,ec.left),cc[ll.bottomCenter]=uc(ec.bottom),cc[ll.bottomRightEdge]=uc(ec.bottom,ec.right),cc[ll.bottomAutoEdge]=uc(ec.bottom,void 0,!0),cc[ll.leftTopEdge]=uc(ec.left,ec.top),cc[ll.leftCenter]=uc(ec.left),cc[ll.leftBottomEdge]=uc(ec.left,ec.bottom),cc[ll.rightTopEdge]=uc(ec.right,ec.top),cc[ll.rightCenter]=uc(ec.right),cc[ll.rightBottomEdge]=uc(ec.right,ec.bottom),cc);function pc(e,t){return!(e.top<t.top||e.bottom>t.bottom||e.left<t.left||e.right>t.right)}function gc(e,t){var i=[];return e.top<t.top&&i.push(ec.top),e.bottom>t.bottom&&i.push(ec.bottom),e.left<t.left&&i.push(ec.left),e.right>t.right&&i.push(ec.right),i}function mc(e,t){return e[ec[t]]}function fc(e,t,i){return e[ec[t]]=i,e}function vc(e,t){var i=Pc(t);return(mc(e,i.positiveEdge)+mc(e,i.negativeEdge))/2}function Sc(e,t){return e>0?t:-1*t}function yc(e,t){return Sc(e,mc(t,e))}function Cc(e,t,i){return Sc(i,mc(e,i)-mc(t,i))}function _c(e,t,i,n){void 0===n&&(n=!0);var r=mc(e,t)-i,a=fc(e,t,i);return n&&(a=fc(e,-1*t,mc(e,-1*t)-r)),a}function Ec(e,t,i,n){return void 0===n&&(n=0),_c(e,i,mc(t,i)+Sc(i,n))}function Tc(e,t,i){return yc(i,e)>yc(i,t)}function bc(e,t){for(var i=0,n=0,r=gc(e,t);n<r.length;n++){var a=r[n];i+=Math.pow(Cc(e,t,a),2)}return i}function Ic(e,t,i,n){return void 0===n&&(n=200),(i===ec.bottom||i===ec.top)&&Cc(e,t,i)>=n}function wc(e,t,i,n){for(var r=0,a=e;r<a.length;r++){var s=a[r],o=void 0;n&&n===-1*s?(o=_c(t.elementRectangle,s,mc(i,s),!1),t.forcedInBounds=!0):Tc(o=Ec(t.elementRectangle,i,s),i,-1*s)||(o=_c(o,-1*s,mc(i,-1*s),!1),t.forcedInBounds=!0),t.elementRectangle=o}return t}function Rc(e,t,i){var n=Pc(t).positiveEdge;return _c(e,n,i-(vc(e,t)-mc(e,n)))}function Ac(e,t,i,n,r){void 0===n&&(n=0);var a=new dc(e.left,e.right,e.top,e.bottom),s=i.alignmentEdge,o=i.targetEdge,l=r?o:-1*o;return a=r?Ec(a,t,o,n):function(e,t,i,n){void 0===n&&(n=0);var r=Sc(-1*i,n);return _c(e,-1*i,mc(t,i)+r)}(a,t,o,n),a=s?Ec(a,t,s):Rc(a,l,vc(t,o))}function Pc(e){return e===ec.top||e===ec.bottom?{positiveEdge:ec.left,negativeEdge:ec.right}:{positiveEdge:ec.top,negativeEdge:ec.bottom}}function Mc(e,t,i){return i&&Math.abs(Cc(e,i,t))>Math.abs(Cc(e,i,-1*t))?-1*t:t}function kc(e,t,i,n,r,a,s,o){var l,c={},d=Nc(t),u=a?i:-1*i,h=r||Pc(i).positiveEdge;return s&&!function(e,t,i){return void 0!==i&&mc(e,t)===mc(i,t)}(e,(l=h,-1*l),n)||(h=Mc(e,h,n)),c[ec[u]]=Cc(e,d,u),c[ec[h]]=Cc(e,d,h),o&&(c[ec[-1*u]]=Cc(e,d,-1*u),c[ec[-1*h]]=Cc(e,d,-1*h)),c}function Dc(e,t,i){var n=vc(t,e),r=vc(i,e),a=Pc(e),s=a.positiveEdge,o=a.negativeEdge;return n<=r?s:o}function Oc(e,t,i,n,r,a,s,o,l){void 0===a&&(a=!1);var c=Ac(e,t,n,r,l);return pc(c,i)?{elementRectangle:c,targetEdge:n.targetEdge,alignmentEdge:n.alignmentEdge}:function(e,t,i,n,r,a,s,o,l){void 0===r&&(r=!1),void 0===s&&(s=0);var c=n.alignmentEdge,d=n.alignTargetEdge,u={elementRectangle:e,targetEdge:n.targetEdge,alignmentEdge:c};o||l||(u=function(e,t,i,n,r,a,s){void 0===r&&(r=!1),void 0===s&&(s=0);var o=[ec.left,ec.right,ec.bottom,ec.top];Rn()&&(o[0]*=-1,o[1]*=-1);for(var l,c=e,d=n.targetEdge,u=n.alignmentEdge,h=d,p=u,g=0;g<4;g++){if(Tc(c,i,d))return{elementRectangle:c,targetEdge:d,alignmentEdge:u};if(r&&Ic(t,i,d,a)){switch(d){case ec.bottom:c.bottom=i.bottom;break;case ec.top:c.top=i.top}return{elementRectangle:c,targetEdge:d,alignmentEdge:u,forcedInBounds:!0}}var m=bc(c,i);(!l||m<l)&&(l=m,h=d,p=u),o.splice(o.indexOf(d),1),o.length>0&&(o.indexOf(-1*d)>-1?d*=-1:(u=d,d=o.slice(-1)[0]),c=Ac(e,t,{targetEdge:d,alignmentEdge:u},s))}return{elementRectangle:c=Ac(e,t,{targetEdge:h,alignmentEdge:p},s),targetEdge:h,alignmentEdge:p}}(e,t,i,n,r,a,s));var h=gc(u.elementRectangle,i),p=o?-u.targetEdge:void 0;if(h.length>0)if(d)if(u.alignmentEdge&&h.indexOf(-1*u.alignmentEdge)>-1){var g=function(e,t,i,n){var r=e.alignmentEdge,a=e.targetEdge,s=-1*r;return{elementRectangle:Ac(e.elementRectangle,t,{targetEdge:a,alignmentEdge:s},i,n),targetEdge:a,alignmentEdge:s}}(u,t,s,l);if(pc(g.elementRectangle,i))return g;u=wc(gc(g.elementRectangle,i),u,i,p)}else u=wc(h,u,i,p);else u=wc(h,u,i,p);return u}(c,t,i,n,a,s,r,o,l)}function Nc(e){var t=e.getBoundingClientRect();return new dc(t.left,t.right,t.top,t.bottom)}function Lc(e,t,i,n,r,a){void 0===r&&(r=!1);var s=e.gapSpace?e.gapSpace:0,o=function(e,t){var i;if(t){if(t.preventDefault){var n=t;i=new dc(n.clientX,n.clientX,n.clientY,n.clientY)}else if(t.getBoundingClientRect)i=Nc(t);else{var r=t,a=r.left||r.x,s=r.top||r.y,o=r.right||a,l=r.bottom||s;i=new dc(a,o,s,l)}if(!pc(i,e))for(var c=0,d=gc(i,e);c<d.length;c++){var u=d[c];i[ec[u]]=e[ec[u]]}}else i=new dc(0,0,0,0);return i}(i,e.target),l=function(e,t,i,n,r){return e.isAuto&&(e.alignmentEdge=Dc(e.targetEdge,t,i)),e.alignTargetEdge=r,e}(function(e,t,i){if(void 0===e&&(e=ll.bottomAutoEdge),i)return{alignmentEdge:i.alignmentEdge,isAuto:i.isAuto,targetEdge:i.targetEdge};var n=Ii({},hc[e]);return Rn()?(n.alignmentEdge&&n.alignmentEdge%2==0&&(n.alignmentEdge=-1*n.alignmentEdge),void 0!==t?hc[t]:n):n}(e.directionalHint,e.directionalHintForRTL,n),o,i,e.coverTarget,e.alignTargetEdge),c=Oc(Nc(t),o,i,l,s,r,a,e.directionalHintFixed,e.coverTarget);return Ii(Ii({},c),{targetRectangle:o})}function xc(e,t,i){return void 0===t&&(t=0),void 0===i&&(i=0),function(e){return Math.sqrt(e*e*2)}(e?t:0)/2+i}function Fc(e,t,i,n,r,a,s,o){void 0===r&&(r=!1);var l=null!=o?o:Tn(),c=e.isBeakVisible&&e.beakWidth||0,d=xc(e.isBeakVisible,e.beakWidth,e.gapSpace),u=e;u.gapSpace=d;var h,p,g,m,f,v,S,y,C,_=e.bounds?(C=e.bounds,new dc(C.left,C.right,C.top,C.bottom)):new dc(0,l.innerWidth-function(e){if(void 0===wl){var t=_n(),i=t.createElement("div");i.style.setProperty("width","100px"),i.style.setProperty("height","100px"),i.style.setProperty("overflow","scroll"),i.style.setProperty("position","absolute"),i.style.setProperty("top","-9999px"),t.body.appendChild(i),wl=i.offsetWidth-i.clientWidth,t.body.removeChild(i)}return wl}(),0,l.innerHeight),E=Lc(u,i,_,n,r,a),T=(h=E,p=function(e,t){var i=t.targetRectangle,n=Pc(t.targetEdge),r=n.positiveEdge,a=n.negativeEdge,s=vc(i,t.targetEdge),o=new dc(e/2,t.elementRectangle.width-e/2,e/2,t.elementRectangle.height-e/2),l=new dc(0,e,0,e);return Tc(l=Rc(l=_c(l,-1*t.targetEdge,-e/2),-1*t.targetEdge,s-yc(r,t.elementRectangle)),o,r)?Tc(l,o,a)||(l=Ec(l,o,a)):l=Ec(l,o,r),l}(c,E),g=_,m=-1*h.targetEdge,f=new dc(0,h.elementRectangle.width,0,h.elementRectangle.height),v={},S=Mc(h.elementRectangle,h.alignmentEdge?h.alignmentEdge:Pc(m).positiveEdge,g),y=Cc(h.elementRectangle,h.targetRectangle,m)>Math.abs(mc(p,m)),v[ec[m]]=mc(p,m),v[ec[S]]=Cc(p,f,S),{elementPosition:Ii({},v),closestEdge:Dc(h.targetEdge,p,f),targetEdge:m,hideBeak:!y});return Ii(Ii({},function(e,t,i,n,r){return{elementPosition:kc(e.elementRectangle,t,e.targetEdge,i,e.alignmentEdge,n,r,e.forcedInBounds),targetEdge:e.targetEdge,alignmentEdge:e.alignmentEdge}}(E,t,_,e.coverTarget,s)),{beakPosition:T})}var Uc=["TEMPLATE","STYLE","SCRIPT"];function Bc(e){var t=_n(e);if(!t)return function(){};for(var i=[];e!==t.body&&e.parentElement;){for(var n=0,r=e.parentElement.children;n<r.length;n++){var a=r[n],s=a.getAttribute("aria-hidden");a!==e&&"true"!==(null==s?void 0:s.toLowerCase())&&-1===Uc.indexOf(a.tagName)&&i.push([a,s])}e=e.parentElement}return i.forEach((function(e){e[0].setAttribute("aria-hidden","true")})),function(){!function(e){e.forEach((function(e){var t=e[0],i=e[1];i?t.setAttribute("aria-hidden",i):t.removeAttribute("aria-hidden")}))}(i),i=[]}}function Vc(){var t=e.useRef();return t.current||(t.current=new go),e.useEffect((function(){return function(){var e;null===(e=t.current)||void 0===e||e.dispose(),t.current=void 0}}),[]),t.current}function Hc(t,i,n,r){var a=e.useRef(n);a.current=n,e.useEffect((function(){var e=t&&"current"in t?t.current:t;if(e&&e.addEventListener)return lc(e,i,(function(e){return a.current(e)}),r)}),[t,i,r])}var $c=e.createContext({window:"object"==typeof window?window:void 0}),Gc=function(){return e.useContext($c).window},jc=function(){var t;return null===(t=e.useContext($c).window)||void 0===t?void 0:t.document};function zc(e){var t=e.originalElement,i=e.containsFocus;t&&i&&t!==Tn()&&setTimeout((function(){var e;null===(e=t.focus)||void 0===e||e.call(t)}),0)}var Wc=e.forwardRef((function(t,i){var n=Xl({shouldRestoreFocus:!0,enableAriaHiddenSiblings:!0},t),r=e.useRef(),a=qo(r,i);!function(t,i){var n="true"===String(t["aria-modal"]).toLowerCase()&&t.enableAriaHiddenSiblings;e.useEffect((function(){if(n&&i.current)return Bc(i.current)}),[i,n])}(n,r),function(t,i){var n=t.onRestoreFocus,r=void 0===n?zc:n,a=e.useRef(),s=e.useRef(!1);e.useEffect((function(){var e,t,n;return a.current=_n().activeElement,(n=(t=_n(e=i.current))&&t.activeElement)&&ul(e,n)&&(s.current=!0),function(){var e;null==r||r({originalElement:a.current,containsFocus:s.current,documentContainsFocus:(null===(e=_n())||void 0===e?void 0:e.hasFocus())||!1}),a.current=void 0}}),[]),Hc(i,"focus",e.useCallback((function(){s.current=!0}),[]),!0),Hc(i,"blur",e.useCallback((function(e){i.current&&e.relatedTarget&&!i.current.contains(e.relatedTarget)&&(s.current=!1)}),[]),!0)}(n,r);var s=n.role,o=n.className,l=n.ariaLabel,c=n.ariaLabelledBy,d=n.ariaDescribedBy,u=n.style,h=n.children,p=n.onDismiss,g=function(t,i){var n=Vc(),r=e.useState(!1),a=r[0],s=r[1];return e.useEffect((function(){return n.requestAnimationFrame((function(){var e;if(!t.style||!t.style.overflowY){var n=!1;if(i&&i.current&&(null===(e=i.current)||void 0===e?void 0:e.firstElementChild)){var r=i.current.clientHeight,o=i.current.firstElementChild.clientHeight;r>0&&o>r&&(n=o-r>1)}a!==n&&s(n)}})),function(){return n.dispose()}})),a}(n,r),m=e.useCallback((function(e){e.which===ao.escape&&p&&(p(e),e.preventDefault(),e.stopPropagation())}),[p]);return Hc(Gc(),"keydown",m),e.createElement("div",Ii({ref:a},Ds(n,ks),{className:o,role:s,"aria-label":l,"aria-labelledby":c,"aria-describedby":d,onKeyDown:m,style:Ii({overflowY:g?"scroll":void 0,outline:"none"},u)}),h)}));function qc(t){var i=e.useRef();return void 0===i.current&&(i.current={value:"function"==typeof t?t():t}),i.current.value}function Kc(t,i){var n=e.useRef(),r=e.useRef(null),a=Gc();if(!t||t!==n.current||"string"==typeof t){var s=null==i?void 0:i.current;if(t)if("string"==typeof t){var o=_n(s);r.current=o?o.querySelector(t):null}else r.current="stopPropagation"in t||"getBoundingClientRect"in t?t:"current"in t?t.current:t;n.current=t}return[r,a]}Wc.displayName="Popup";var Jc,Yc=function(){var e;return(null!==(e=Gc())&&void 0!==e?e:"undefined"!=typeof window)?window:void 0},Qc=function(e){var t,i;return(null!==(i=null===(t=null==e?void 0:e.window)||void 0===t?void 0:t.document)&&void 0!==i?i:"undefined"!=typeof document)?document:void 0},Zc=function(e){var t;return(null!==(t=null==e?void 0:e.window)&&void 0!==t?t:"undefined"!=typeof window)?window:void 0},Xc=((Jc={})[ec.top]=Dr.slideUpIn10,Jc[ec.bottom]=Dr.slideDownIn10,Jc[ec.left]=Dr.slideLeftIn10,Jc[ec.right]=Dr.slideRightIn10,Jc),ed={opacity:0,filter:"opacity(0)",pointerEvents:"none"},td=["role","aria-roledescription"],id={preventDismissOnLostFocus:!1,preventDismissOnScroll:!1,preventDismissOnResize:!1,isBeakVisible:!0,beakWidth:16,gapSpace:0,minPagePadding:8,directionalHint:ll.bottomAutoEdge},nd=Ys({disableCaching:!0});function rd(t,i,n,r){var a,s=t.calloutMaxHeight,o=t.finalHeight,l=t.directionalHint,c=t.directionalHintFixed,d=t.hidden,u=t.gapSpace,h=t.beakWidth,p=t.isBeakVisible,g=t.coverTarget,m=e.useState(),f=m[0],v=m[1],S=null!==(a=null==r?void 0:r.elementPosition)&&void 0!==a?a:{},y=S.top,C=S.bottom,_=(null==n?void 0:n.current)?function(e){var t,i,n,r,a=e,s=e,o=e,l=null!==(t=o.left)&&void 0!==t?t:o.x,c=null!==(i=o.top)&&void 0!==i?i:o.y,d=null!==(n=o.right)&&void 0!==n?n:l,u=null!==(r=o.bottom)&&void 0!==r?r:c;return a.stopPropagation?new dc(a.clientX,a.clientX,a.clientY,a.clientY):void 0!==l&&void 0!==c?new dc(l,d,c,u):Nc(s)}(n.current):void 0;return e.useEffect((function(){var e,t,n=null!==(e=i())&&void 0!==e?e:{},a=n.top,o=n.bottom;(null==r?void 0:r.targetEdge)===ec.top&&(null==_?void 0:_.top)&&!g&&(o=_.top-function(e,t,i){return xc(e,t,i)}(p,h,u)),"number"==typeof y&&o?t=o-y:"number"==typeof C&&"number"==typeof a&&o&&(t=o-a-C),v(!s&&!d||s&&t&&s>t?t:s||void 0)}),[C,s,o,l,c,i,d,r,y,u,h,p,_,g]),f}function ad(t,i,n,r,a,s){var o,l=e.useState(),c=l[0],d=l[1],u=e.useRef(0),h=e.useRef(),p=Vc(),g=t.hidden,m=t.target,f=t.finalHeight,v=t.calloutMaxHeight,S=t.onPositioned,y=t.directionalHint,C=t.hideOverflow,_=t.preferScrollResizePositioning,E=Yc(),T=e.useRef();T.current!==s.current&&(T.current=s.current,o=s.current?null==E?void 0:E.getComputedStyle(s.current):void 0);var b=null==o?void 0:o.overflowY;return e.useEffect((function(){if(!g){var e=p.requestAnimationFrame((function(){var e,s,o,l;if(i.current&&n){var p=Ii(Ii({},t),{target:r.current,bounds:a()}),g=n.cloneNode(!0);g.style.maxHeight=v?"".concat(v):"",g.style.visibility="hidden",null===(e=n.parentElement)||void 0===e||e.appendChild(g);var y=h.current===m?c:void 0,T=_&&!(C||"clip"===b||"hidden"===b),I=f?function(e,t,i,n,r){return function(e,t,i,n,r){return Fc(e,t,i,n,!1,void 0,!0,null!=r?r:Tn())}(e,t,i,n,r)}(p,i.current,g,y,E):function(e,t,i,n,r,a,s){return Fc(e,t,i,n,r,void 0,void 0,s)}(p,i.current,g,y,T,0,E);null===(s=n.parentElement)||void 0===s||s.removeChild(g),!c&&I||c&&I&&(l=I,!ld((o=c).elementPosition,l.elementPosition)||!ld(o.beakPosition.elementPosition,l.beakPosition.elementPosition))&&u.current<5?(u.current++,d(I)):u.current>0&&(u.current=0,null==S||S(c))}}),n);return h.current=m,function(){p.cancelAnimationFrame(e),h.current=void 0}}d(void 0),u.current=0}),[g,y,p,n,v,i,r,f,a,S,c,t,m,C,_,b,E]),c}var sd=e.memo(e.forwardRef((function(t,i){var n=Xl(id,t),r=n.styles,a=n.style,s=n.ariaLabel,o=n.ariaDescribedBy,l=n.ariaLabelledBy,c=n.className,d=n.isBeakVisible,u=n.children,h=n.beakWidth,p=n.calloutWidth,g=n.calloutMaxWidth,m=n.calloutMinWidth,f=n.doNotLayer,v=n.finalHeight,S=n.hideOverflow,y=void 0===S?!!v:S,C=n.backgroundColor,_=n.calloutMaxHeight,E=n.onScroll,T=n.shouldRestoreFocus,b=void 0===T||T,I=n.target,w=n.hidden,R=n.onLayerMounted,A=n.popupProps,P=e.useRef(null),M=qo(e.useRef(null),null==A?void 0:A.ref),k=e.useState(null),D=k[0],O=k[1],N=e.useCallback((function(e){O(e)}),[]),L=qo(P,i),x=Kc(n.target,{current:D}),F=x[0],U=x[1],B=function(t,i,n){var r=t.bounds,a=t.minPagePadding,s=void 0===a?id.minPagePadding:a,o=t.target,l=e.useState(!1),c=l[0],d=l[1],u=e.useRef(),h=e.useCallback((function(){if(!u.current||c){var e="function"==typeof r?n?r(o,n):void 0:r;!e&&n&&(e=function(e,t){return function(e,t){var i=void 0;if(t.getWindowSegments&&(i=t.getWindowSegments()),void 0===i||i.length<=1)return{top:0,left:0,right:t.innerWidth,bottom:t.innerHeight,width:t.innerWidth,height:t.innerHeight};var n=0,r=0;if(null!==e&&e.getBoundingClientRect){var a=e.getBoundingClientRect();n=(a.left+a.right)/2,r=(a.top+a.bottom)/2}else null!==e&&(n=e.left||e.x,r=e.top||e.y);for(var s={top:0,left:0,right:0,bottom:0,width:0,height:0},o=0,l=i;o<l.length;o++){var c=l[o];n&&c.left<=n&&c.right>=n&&r&&c.top<=r&&c.bottom>=r&&(s={top:c.top,left:c.left,right:c.right,bottom:c.bottom,width:c.width,height:c.height})}return s}(e,t)}(i.current,n),e={top:e.top+s,left:e.left+s,right:e.right-s,bottom:e.bottom-s,width:e.width-2*s,height:e.height-2*s}),u.current=e,c&&d(!1)}return u.current}),[r,s,o,i,n,c]),p=Vc();return Hc(n,"resize",p.debounce((function(){d(!0)}),500,{leading:!0})),h}(n,F,U),V=ad(n,P,D,F,B,M),H=rd(n,B,F,V),$=function(t,i,n,r,a){var s=t.hidden,o=t.onDismiss,l=t.preventDismissOnScroll,c=t.preventDismissOnResize,d=t.preventDismissOnLostFocus,u=t.dismissOnTargetClick,h=t.shouldDismissOnWindowFocus,p=t.preventDismissOnEvent,g=e.useRef(!1),m=Vc(),f=qc([function(){g.current=!0},function(){g.current=!1}]),v=!!i;return e.useEffect((function(){var e=function(e){v&&!l&&f(e)},t=function(e){c||p&&p(e)||null==o||o(e)},i=function(e){d||f(e)},f=function(e){var t=e.composedPath?e.composedPath():[],i=t.length>0?t[0]:e.target,s=n.current&&!ul(n.current,i);if(s&&g.current)g.current=!1;else if(!r.current&&s||e.target!==a&&s&&(!r.current||"stopPropagation"in r.current||u||i!==r.current&&!ul(r.current,i))){if(p&&p(e))return;null==o||o(e)}},S=function(e){h&&((!p||p(e))&&(p||d)||(null==a?void 0:a.document.hasFocus())||null!==e.relatedTarget||null==o||o(e))},y=new Promise((function(n){m.setTimeout((function(){if(!s&&a){var r=[lc(a,"scroll",e,!0),lc(a,"resize",t,!0),lc(a.document.documentElement,"focus",i,!0),lc(a.document.documentElement,"click",i,!0),lc(a,"blur",S,!0)];n((function(){r.forEach((function(e){return e()}))}))}}),0)}));return function(){y.then((function(e){return e()}))}}),[s,m,n,r,a,o,h,u,d,c,l,v,p]),f}(n,V,P,F,U),G=$[0],j=$[1],z=(null==V?void 0:V.elementPosition.top)&&(null==V?void 0:V.elementPosition.bottom),W=Ii(Ii({},null==V?void 0:V.elementPosition),{maxHeight:H});if(z&&(W.bottom=void 0),function(t,i,n){var r=t.hidden,a=t.setInitialFocus,s=Vc(),o=!!i;e.useEffect((function(){if(!r&&a&&o&&n){var e=s.requestAnimationFrame((function(){return!!(t=yl(e=n,e,!0,!1,!1,!0,void 0,void 0,void 0))&&(Al(t),!0);var e,t}),n);return function(){return s.cancelAnimationFrame(e)}}}),[r,o,s,n,a])}(n,V,D),e.useEffect((function(){w||null==R||R()}),[w]),!U)return null;var q=y,K=d&&!!I,J=nd(r,{theme:n.theme,className:c,overflowYHidden:q,calloutWidth:p,positions:V,beakWidth:h,backgroundColor:C,calloutMaxWidth:g,calloutMinWidth:m,doNotLayer:f}),Y=Ii(Ii({maxHeight:_||"100%"},a),q&&{overflowY:"hidden"}),Q=n.hidden?{visibility:"hidden"}:void 0;return e.createElement("div",{ref:L,className:J.container,style:Q},e.createElement("div",Ii({},Ds(n,ks,td),{className:Os(J.root,V&&V.targetEdge&&Xc[V.targetEdge]),style:V?Ii({},W):ed,tabIndex:-1,ref:N}),K&&e.createElement("div",{className:J.beak,style:od(V)}),K&&e.createElement("div",{className:J.beakCurtain}),e.createElement(Wc,Ii({role:n.role,"aria-roledescription":n["aria-roledescription"],ariaDescribedBy:o,ariaLabel:s,ariaLabelledBy:l,className:J.calloutMain,onDismiss:n.onDismiss,onMouseDown:G,onMouseUp:j,onRestoreFocus:n.onRestoreFocus,onScroll:E,shouldRestoreFocus:b,style:Y},A,{ref:M}),u)))})),(function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||mo(e,t)}));function od(e){var t,i,n=Ii(Ii({},null===(t=null==e?void 0:e.beakPosition)||void 0===t?void 0:t.elementPosition),{display:(null===(i=null==e?void 0:e.beakPosition)||void 0===i?void 0:i.hideBeak)?"none":void 0});return n.top||n.bottom||n.left||n.right||(n.left=0,n.top=0),n}function ld(e,t){for(var i in t)if(t.hasOwnProperty(i)){var n=e[i],r=t[i];if(void 0===n||void 0===r)return!1;if(n.toFixed(2)!==r.toFixed(2))return!1}return!0}function cd(e){return{height:e,width:e}}sd.displayName="CalloutContentBase";var dd={container:"ms-Callout-container",root:"ms-Callout",beak:"ms-Callout-beak",beakCurtain:"ms-Callout-beakCurtain",calloutMain:"ms-Callout-main"},ud=Ws(sd,(function(e){var t,i=e.theme,n=e.className,r=e.overflowYHidden,a=e.calloutWidth,s=e.beakWidth,o=e.backgroundColor,l=e.calloutMaxWidth,c=e.calloutMinWidth,d=e.doNotLayer,u=Kr(dd,i),h=i.semanticColors,p=i.effects;return{container:[u.container,{position:"relative"}],root:[u.root,i.fonts.medium,{position:"absolute",display:"flex",zIndex:d?Br.Layer:void 0,boxSizing:"border-box",borderRadius:p.roundedCorner2,boxShadow:p.elevation16,selectors:(t={},t[Nr]={borderWidth:1,borderStyle:"solid",borderColor:"WindowText"},t)},{selectors:{"&::-moz-focus-inner":{border:0},"&":{outline:"transparent"}}},n,!!a&&{width:a},!!l&&{maxWidth:l},!!c&&{minWidth:c}],beak:[u.beak,{position:"absolute",backgroundColor:h.menuBackground,boxShadow:"inherit",border:"inherit",boxSizing:"border-box",transform:"rotate(45deg)"},cd(s),o&&{backgroundColor:o}],beakCurtain:[u.beakCurtain,{position:"absolute",top:0,right:0,bottom:0,left:0,backgroundColor:h.menuBackground,borderRadius:p.roundedCorner2}],calloutMain:[u.calloutMain,{backgroundColor:h.menuBackground,overflowX:"hidden",overflowY:"auto",position:"relative",width:"100%",borderRadius:p.roundedCorner2},r&&{overflowY:"hidden"},o&&{backgroundColor:o}]}}),void 0,{scope:"CalloutContent"}),hd=e.createContext(void 0),pd=function(){return function(){}};hd.Provider;var gd=r(2997),md=function(t){var i=t.providerRef,n=t.layerRoot,r=e.useState([])[0],a=e.useContext(No),s=void 0!==a&&!n,o=e.useMemo((function(){return s?void 0:{providerRef:i,registeredProviders:r,registerProvider:function(e){r.push(e),null==a||a.registerProvider(e)},unregisterProvider:function(e){null==a||a.unregisterProvider(e);var t=r.indexOf(e);t>=0&&r.splice(t,1)}}}),[i,r,a,s]);return e.useEffect((function(){if(o)return o.registerProvider(o.providerRef),function(){return o.unregisterProvider(o.providerRef)}}),[o]),o?e.createElement(No.Provider,{value:o},t.children):e.createElement(e.Fragment,null,t.children)};function fd(e,t){void 0===e&&(e={});var i=vd(t)?t:function(e){return function(t){return e?Ii(Ii({},t),e):t}}(t);return i(e)}function vd(e){return"function"==typeof e}var Sd=function(t){function i(){var e=null!==t&&t.apply(this,arguments)||this;return e._onCustomizationChange=function(){return e.forceUpdate()},e}return bi(i,t),i.prototype.componentDidMount=function(){sa.observe(this._onCustomizationChange)},i.prototype.componentWillUnmount=function(){sa.unobserve(this._onCustomizationChange)},i.prototype.render=function(){var t=this,i=this.props.contextTransform;return e.createElement(rs.Consumer,null,(function(n){var r=function(e,t){var i,n,r,a=(t||{}).customizations,s=void 0===a?{settings:{},scopedSettings:{}}:a;return{customizations:{settings:fd(s.settings,e.settings),scopedSettings:(i=s.scopedSettings,n=e.scopedSettings,void 0===i&&(i={}),(vd(n)?n:(void 0===(r=n)&&(r={}),function(e){var t=Ii({},e);for(var i in r)r.hasOwnProperty(i)&&(t[i]=Ii(Ii({},e[i]),r[i]));return t}))(i)),inCustomizerContext:!0}}}(t.props,n);return i&&(r=i(r)),e.createElement(rs.Provider,{value:r},t.props.children)}))},i}(e.Component),yd=Ys(),Cd=vn((function(e,t){return Oa(Ii(Ii({},e),{rtl:t}))})),_d=e.forwardRef((function(t,i){var n=t.className,r=t.theme,a=t.applyTheme,s=t.applyThemeToBody,o=t.styles,l=yd(o,{theme:r,applyTheme:a,className:n}),c=e.useRef(null);return function(t,i,n){var r=i.bodyThemed;e.useEffect((function(){if(t){var e=_n(n.current);if(e)return e.body.classList.add(r),function(){e.body.classList.remove(r)}}}),[r,t,n])}(s,l,c),e.createElement(e.Fragment,null,function(t,i,n,r){var a=i.root,s=t.as,o=void 0===s?"div":s,l=t.dir,c=t.theme,d=Ds(t,ks,["dir"]),u=function(e){var t=e.theme,i=e.dir,n=Rn(t)?"rtl":"ltr",r=Rn()?"rtl":"ltr",a=i||n;return{rootDir:a!==n||a!==r?a:i,needsTheme:a!==n}}(t),h=u.rootDir,p=u.needsTheme,g=e.createElement(md,{providerRef:n},e.createElement(o,Ii({dir:h},d,{className:a,ref:qo(n,r)})));return p&&(g=e.createElement(Sd,{settings:{theme:Cd(c,"rtl"===l)}},g)),g}(t,l,c,i))}));_d.displayName="FabricBase";var Ed={fontFamily:"inherit"},Td={root:"ms-Fabric",bodyThemed:"ms-Fabric-bodyThemed"},bd=Ws(_d,(function(e){var t=e.applyTheme,i=e.className,n=e.preventBlanketFontInheritance,r=e.theme;return{root:[Kr(Td,r).root,r.fonts.medium,{color:r.palette.neutralPrimary},!n&&{"& button":Ed,"& input":Ed,"& textarea":Ed},t&&{color:r.semanticColors.bodyText,backgroundColor:r.semanticColors.bodyBackground},i],bodyThemed:[{backgroundColor:r.semanticColors.bodyBackground}]}}),void 0,{scope:"Fabric"}),Id={},wd={},Rd="fluent-default-layer-host",Ad="#".concat(Rd);function Pd(e){Id[e]&&Id[e].forEach((function(e){return e()}))}var Md,kd=Ys(),Dd=e.forwardRef((function(t,i){var n,r=null!==(n=e.useContext(hd))&&void 0!==n?n:pd,a=e.useRef(null),s=qo(a,i),o=e.useRef(),l=e.useRef(null),c=e.useContext(No),d=e.useState(!1),u=d[0],h=d[1],p=e.useCallback((function(e){var t,i=!!(null==(t=null==c?void 0:c.providerRef)?void 0:t.current)&&t.current.classList.contains(Vr);e&&i&&e.classList.add(Vr)}),[c]),g=t.children,m=t.className,f=t.eventBubblingEnabled,v=t.fabricProps,S=t.hostId,y=t.insertFirst,C=t.onLayerDidMount,_=void 0===C?function(){}:C,E=t.onLayerMounted,T=void 0===E?function(){}:E,b=t.onLayerWillUnmount,I=t.styles,w=t.theme,R=qo(l,null==v?void 0:v.ref,p),A=kd(I,{theme:w,className:m,isNotHost:!S}),P=function(){null==b||b();var e=o.current;o.current=void 0,e&&e.parentNode&&e.parentNode.removeChild(e)},M=function(){var e,t=_n(a.current);if(t){var i=function(e){var t,i;if(S){var n=function(e){var t=wd[e];return t&&t[0]||void 0}(S);return n?null!==(t=n.rootRef.current)&&void 0!==t?t:null:null!==(i=e.getElementById(S))&&void 0!==i?i:null}var r=Ad,a=r?e.querySelector(r):null;return a||(a=function(e){var t=e.createElement("div");return t.setAttribute("id",Rd),t.style.cssText="position:fixed;z-index:1000000",null==e||e.body.appendChild(t),t}(e)),a}(t);if(i){P();var n=(null!==(e=i.ownerDocument)&&void 0!==e?e:t).createElement("div");n.className=A.root,n.setAttribute(no,"true"),function(e,t){var i=e,n=t;i._virtual||(i._virtual={children:[]});var r=i._virtual.parent;if(r&&r!==t){var a=r._virtual.children.indexOf(i);a>-1&&r._virtual.children.splice(a,1)}i._virtual.parent=n||void 0,n&&(n._virtual||(n._virtual={children:[]}),n._virtual.children.push(i))}(n,a.current),y?i.insertBefore(n,i.firstChild):i.appendChild(n),o.current=n,h(!0)}}};return Wo((function(){M(),S&&function(e,t){Id[e]||(Id[e]=[]),Id[e].push(t);var i=wd[e];if(i)for(var n=0,r=i;n<r.length;n++)r[n].notifyLayersChanged()}(S,M);var e=o.current?r(o.current):void 0;return function(){e&&e(),P(),S&&function(e,t){var i=Id[e];if(i){var n=i.indexOf(t);n>=0&&(i.splice(n,1),0===i.length&&delete Id[e])}var r=wd[e];if(r)for(var a=0,s=r;a<s.length;a++)s[a].notifyLayersChanged()}(S,M)}}),[S]),e.useEffect((function(){o.current&&u&&(null==T||T(),null==_||_(),h(!1))}),[u,T,_]),e.createElement("span",{className:"ms-layer",ref:s},o.current&&gd.createPortal(e.createElement(md,{layerRoot:!0,providerRef:R},e.createElement(bd,Ii({},!f&&(Md||(Md={},["onClick","onContextMenu","onDoubleClick","onDrag","onDragEnd","onDragEnter","onDragExit","onDragLeave","onDragOver","onDragStart","onDrop","onMouseDown","onMouseEnter","onMouseLeave","onMouseMove","onMouseOver","onMouseOut","onMouseUp","onTouchMove","onTouchStart","onTouchCancel","onTouchEnd","onKeyDown","onKeyPress","onKeyUp","onFocus","onBlur","onChange","onInput","onInvalid","onSubmit"].forEach((function(e){return Md[e]=Od}))),Md),v,{className:Os(A.content,null==v?void 0:v.className),ref:R}),g)),o.current))}));Dd.displayName="LayerBase";var Od=function(e){e.eventPhase===Event.BUBBLING_PHASE&&"mouseenter"!==e.type&&"mouseleave"!==e.type&&"touchstart"!==e.type&&"touchend"!==e.type&&e.stopPropagation()},Nd={root:"ms-Layer",rootNoHost:"ms-Layer--fixed",content:"ms-Layer-content"},Ld=Ws(Dd,(function(e){var t=e.className,i=e.isNotHost,n=e.theme,r=Kr(Nd,n);return{root:[r.root,n.fonts.medium,i&&[r.rootNoHost,{position:"fixed",zIndex:Br.Layer,top:0,left:0,bottom:0,right:0,visibility:"hidden"}],t],content:[r.content,{visibility:"visible"}]}}),void 0,{scope:"Layer",fields:["hostId","theme","styles"]}),xd=e.forwardRef((function(t,i){var n=t.layerProps,r=t.doNotLayer,a=wi(t,["layerProps","doNotLayer"]),s=e.createElement(ud,Ii({},a,{doNotLayer:r,ref:i}));return r?s:e.createElement(Ld,Ii({},n),s)}));xd.displayName="Callout";var Fd,Ud=function(t){var i=t.item,n=t.classNames,r=i.iconProps;return e.createElement(al,Ii({},r,{className:n.icon}))},Bd=function(e){var t=e.item;return e.hasIcons?t.onRenderIcon?t.onRenderIcon(e,Ud):Ud(e):null},Vd=function(t){var i=t.onCheckmarkClick,n=t.item,r=t.classNames,a=rc(n);return i?e.createElement(al,{iconName:!1!==n.canCheck&&a?"CheckMark":"",className:r.checkmarkIcon,onClick:function(e){return i(n,e)}}):null},Hd=function(t){var i=t.item,n=t.classNames;return i.text||i.name?e.createElement("span",{className:n.label},i.text||i.name):null},$d=function(t){var i=t.item,n=t.classNames;return i.secondaryText?e.createElement("span",{className:n.secondaryText},i.secondaryText):null},Gd=function(t){var i=t.item,n=t.classNames,r=t.theme;return ac(i)?e.createElement(al,Ii({iconName:Rn(r)?"ChevronLeft":"ChevronRight"},i.submenuIconProps,{className:n.subMenuIcon})):null},jd=function(t){function i(e){var i=t.call(this,e)||this;return i.openSubMenu=function(){var e=i.props,t=e.item,n=e.openSubMenu,r=e.getSubmenuTarget;if(r){var a=r();ac(t)&&n&&a&&n(t,a)}},i.dismissSubMenu=function(){var e=i.props,t=e.item,n=e.dismissSubMenu;ac(t)&&n&&n()},i.dismissMenu=function(e){var t=i.props.dismissMenu;t&&t(void 0,e)},lo(i),i}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.item,n=t.classNames,r=i.onRenderContent||this._renderLayout;return e.createElement("div",{className:i.split?n.linkContentMenu:n.linkContent},r(this.props,{renderCheckMarkIcon:Vd,renderItemIcon:Bd,renderItemName:Hd,renderSecondaryText:$d,renderSubMenuIcon:Gd}))},i.prototype._renderLayout=function(t,i){return e.createElement(e.Fragment,null,i.renderCheckMarkIcon(t),i.renderItemIcon(t),i.renderItemName(t),i.renderSecondaryText(t),i.renderSubMenuIcon(t))},i}(e.Component),zd=vn((function(e){return Xa({wrapper:{display:"inline-flex",height:"100%",alignItems:"center"},divider:{width:1,height:"100%",backgroundColor:e.palette.neutralTertiaryAlt}})})),Wd=36,qd=Ur(0,639),Kd=vn((function(e){var t,i,n,r,a,s=e.semanticColors,o=e.fonts,l=e.palette,c=s.menuItemBackgroundHovered,d=s.menuItemTextHovered,u=s.menuItemBackgroundPressed,h=s.bodyDivider;return Qa({item:[o.medium,{color:s.bodyText,position:"relative",boxSizing:"border-box"}],divider:{display:"block",height:"1px",backgroundColor:h,position:"relative"},root:[jr(e),o.medium,{color:s.bodyText,backgroundColor:"transparent",border:"none",width:"100%",height:Wd,lineHeight:Wd,display:"block",cursor:"pointer",padding:"0px 8px 0 4px",textAlign:"left"}],rootDisabled:{color:s.disabledBodyText,cursor:"default",pointerEvents:"none",selectors:(t={},t[Nr]={color:"GrayText",opacity:1},t)},rootHovered:{backgroundColor:c,color:d,selectors:{".ms-ContextualMenu-icon":{color:l.themeDarkAlt},".ms-ContextualMenu-submenuIcon":{color:l.neutralPrimary}}},rootFocused:{backgroundColor:l.white},rootChecked:{selectors:{".ms-ContextualMenu-checkmarkIcon":{color:l.neutralPrimary}}},rootPressed:{backgroundColor:u,selectors:{".ms-ContextualMenu-icon":{color:l.themeDark},".ms-ContextualMenu-submenuIcon":{color:l.neutralPrimary}}},rootExpanded:{backgroundColor:u,color:s.bodyTextChecked,selectors:(i={".ms-ContextualMenu-submenuIcon":(n={},n[Nr]={color:"inherit"},n)},i[Nr]=Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i)},linkContent:{whiteSpace:"nowrap",height:"inherit",display:"flex",alignItems:"center",maxWidth:"100%"},anchorLink:{padding:"0px 8px 0 4px",textRendering:"auto",color:"inherit",letterSpacing:"normal",wordSpacing:"normal",textTransform:"none",textIndent:"0px",textShadow:"none",textDecoration:"none",boxSizing:"border-box"},label:{margin:"0 4px",verticalAlign:"middle",display:"inline-block",flexGrow:"1",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"},secondaryText:{color:e.palette.neutralSecondary,paddingLeft:"20px",textAlign:"right"},icon:{display:"inline-block",minHeight:"1px",maxHeight:Wd,fontSize:kr.medium,width:kr.medium,margin:"0 4px",verticalAlign:"middle",flexShrink:"0",selectors:(r={},r[qd]={fontSize:kr.large,width:kr.large},r)},iconColor:{color:s.menuIcon},iconDisabled:{color:s.disabledBodyText},checkmarkIcon:{color:s.bodySubtext},subMenuIcon:{height:Wd,lineHeight:Wd,color:l.neutralSecondary,textAlign:"center",display:"inline-block",verticalAlign:"middle",flexShrink:"0",fontSize:kr.small,selectors:(a={":hover":{color:l.neutralPrimary},":active":{color:l.neutralPrimary}},a[qd]={fontSize:kr.medium},a)},splitButtonFlexContainer:[jr(e),{display:"flex",height:Wd,flexWrap:"nowrap",justifyContent:"center",alignItems:"flex-start"}]})})),Jd="28px",Yd=Ur(0,639),Qd=vn((function(e){var t;return Xa(zd(e),{wrapper:{position:"absolute",right:28,selectors:(t={},t[Yd]={right:32},t)},divider:{height:16,width:1}})})),Zd={item:"ms-ContextualMenu-item",divider:"ms-ContextualMenu-divider",root:"ms-ContextualMenu-link",isChecked:"is-checked",isExpanded:"is-expanded",isDisabled:"is-disabled",linkContent:"ms-ContextualMenu-linkContent",linkContentMenu:"ms-ContextualMenu-linkContent",icon:"ms-ContextualMenu-icon",iconColor:"ms-ContextualMenu-iconColor",checkmarkIcon:"ms-ContextualMenu-checkmarkIcon",subMenuIcon:"ms-ContextualMenu-submenuIcon",label:"ms-ContextualMenu-itemText",secondaryText:"ms-ContextualMenu-secondaryText",splitMenu:"ms-ContextualMenu-splitMenu",screenReaderText:"ms-ContextualMenu-screenReaderText"},Xd=vn((function(e,t,i,n,r,a,s,o,l,c,d,u){var h,p,g,m,f=Kd(e),v=Kr(Zd,e);return Xa({item:[v.item,f.item,s],divider:[v.divider,f.divider,o],root:[v.root,f.root,n&&[v.isChecked,f.rootChecked],r&&f.anchorLink,i&&[v.isExpanded,f.rootExpanded],t&&[v.isDisabled,f.rootDisabled],!t&&!i&&[{selectors:(h={":hover":f.rootHovered,":active":f.rootPressed},h[".".concat(Vr," &:focus, .").concat(Vr," &:focus:hover")]=f.rootFocused,h[".".concat(Vr," &:hover")]={background:"inherit;"},h)}],u],splitPrimary:[f.root,{width:"calc(100% - ".concat(Jd,")")},n&&["is-checked",f.rootChecked],(t||d)&&["is-disabled",f.rootDisabled],!(t||d)&&!n&&[{selectors:(p={":hover":f.rootHovered},p[":hover ~ .".concat(v.splitMenu)]=f.rootHovered,p[":active"]=f.rootPressed,p[".".concat(Vr," &:focus, .").concat(Vr," &:focus:hover")]=f.rootFocused,p[".".concat(Vr," &:hover")]={background:"inherit;"},p)}]],splitMenu:[v.splitMenu,f.root,{flexBasis:"0",padding:"0 8px",minWidth:Jd},i&&["is-expanded",f.rootExpanded],t&&["is-disabled",f.rootDisabled],!t&&!i&&[{selectors:(g={":hover":f.rootHovered,":active":f.rootPressed},g[".".concat(Vr," &:focus, .").concat(Vr," &:focus:hover")]=f.rootFocused,g[".".concat(Vr," &:hover")]={background:"inherit;"},g)}]],anchorLink:f.anchorLink,linkContent:[v.linkContent,f.linkContent],linkContentMenu:[v.linkContentMenu,f.linkContent,{justifyContent:"center"}],icon:[v.icon,a&&f.iconColor,f.icon,l,t&&[v.isDisabled,f.iconDisabled]],iconColor:f.iconColor,checkmarkIcon:[v.checkmarkIcon,a&&f.checkmarkIcon,f.icon,l],subMenuIcon:[v.subMenuIcon,f.subMenuIcon,c,i&&{color:e.palette.neutralPrimary},t&&[f.iconDisabled]],label:[v.label,f.label],secondaryText:[v.secondaryText,f.secondaryText],splitContainer:[f.splitButtonFlexContainer,!t&&!n&&[{selectors:(m={},m[".".concat(Vr," &:focus, .").concat(Vr," &:focus:hover")]=f.rootFocused,m)}]],screenReaderText:[v.screenReaderText,f.screenReaderText,Wr,{visibility:"hidden"}]})})),eu=function(e){var t=e.theme,i=e.disabled,n=e.expanded,r=e.checked,a=e.isAnchorLink,s=e.knownIcon,o=e.itemClassName,l=e.dividerClassName,c=e.iconClassName,d=e.subMenuClassName,u=e.primaryDisabled,h=e.className;return Xd(t,i,n,r,a,s,o,l,c,d,u,h)},tu=Ws(jd,eu,void 0,{scope:"ContextualMenuItem"}),iu=function(e){function t(t){var i=e.call(this,t)||this;return i._onItemMouseEnter=function(e){var t=i.props,n=t.item,r=t.onItemMouseEnter;r&&r(n,e,e.currentTarget)},i._onItemClick=function(e){var t=i.props,n=t.item,r=t.onItemClickBase;r&&r(n,e,e.currentTarget)},i._onItemMouseLeave=function(e){var t=i.props,n=t.item,r=t.onItemMouseLeave;r&&r(n,e)},i._onItemKeyDown=function(e){var t=i.props,n=t.item,r=t.onItemKeyDown;r&&r(n,e)},i._onItemMouseMove=function(e){var t=i.props,n=t.item,r=t.onItemMouseMove;r&&r(n,e,e.currentTarget)},i._getSubmenuTarget=function(){},lo(i),i}return bi(t,e),t.prototype.shouldComponentUpdate=function(e){return!mo(e,this.props)},t}(e.Component),nu="ktp",ru="-";function au(t){var i=(0,e.useRef)();return(0,e.useEffect)((function(){i.current=t})),i.current}!function(e){e.KEYTIP_ADDED="keytipAdded",e.KEYTIP_REMOVED="keytipRemoved",e.KEYTIP_UPDATED="keytipUpdated",e.PERSISTED_KEYTIP_ADDED="persistedKeytipAdded",e.PERSISTED_KEYTIP_REMOVED="persistedKeytipRemoved",e.PERSISTED_KEYTIP_EXECUTE="persistedKeytipExecute",e.ENTER_KEYTIP_MODE="enterKeytipMode",e.EXIT_KEYTIP_MODE="exitKeytipMode"}(Fd||(Fd={}));var su=function(){function e(){this.keytips={},this.persistedKeytips={},this.sequenceMapping={},this.inKeytipMode=!1,this.shouldEnterKeytipMode=!0,this.delayUpdatingKeytipChange=!1}return e.getInstance=function(){return this._instance},e.prototype.init=function(e){this.delayUpdatingKeytipChange=e},e.prototype.register=function(e,t){void 0===t&&(t=!1);var i=e;t||(i=this.addParentOverflow(e),this.sequenceMapping[i.keySequences.toString()]=i);var n=this._getUniqueKtp(i);if(t?this.persistedKeytips[n.uniqueID]=n:this.keytips[n.uniqueID]=n,this.inKeytipMode||!this.delayUpdatingKeytipChange){var r=t?Fd.PERSISTED_KEYTIP_ADDED:Fd.KEYTIP_ADDED;So.raise(this,r,{keytip:i,uniqueID:n.uniqueID})}return n.uniqueID},e.prototype.update=function(e,t){var i=this.addParentOverflow(e),n=this._getUniqueKtp(i,t),r=this.keytips[t];r&&(n.keytip.visible=r.keytip.visible,this.keytips[t]=n,delete this.sequenceMapping[r.keytip.keySequences.toString()],this.sequenceMapping[n.keytip.keySequences.toString()]=n.keytip,!this.inKeytipMode&&this.delayUpdatingKeytipChange||So.raise(this,Fd.KEYTIP_UPDATED,{keytip:n.keytip,uniqueID:n.uniqueID}))},e.prototype.unregister=function(e,t,i){void 0===i&&(i=!1),i?delete this.persistedKeytips[t]:delete this.keytips[t],!i&&delete this.sequenceMapping[e.keySequences.toString()];var n=i?Fd.PERSISTED_KEYTIP_REMOVED:Fd.KEYTIP_REMOVED;!this.inKeytipMode&&this.delayUpdatingKeytipChange||So.raise(this,n,{keytip:e,uniqueID:t})},e.prototype.enterKeytipMode=function(){So.raise(this,Fd.ENTER_KEYTIP_MODE)},e.prototype.exitKeytipMode=function(){So.raise(this,Fd.EXIT_KEYTIP_MODE)},e.prototype.getKeytips=function(){var e=this;return Object.keys(this.keytips).map((function(t){return e.keytips[t].keytip}))},e.prototype.addParentOverflow=function(e){var t=Ai([],e.keySequences,!0);if(t.pop(),0!==t.length){var i=this.sequenceMapping[t.toString()];if(i&&i.overflowSetSequence)return Ii(Ii({},e),{overflowSetSequence:i.overflowSetSequence})}return e},e.prototype.menuExecute=function(e,t){So.raise(this,Fd.PERSISTED_KEYTIP_EXECUTE,{overflowButtonSequences:e,keytipSequences:t})},e.prototype._getUniqueKtp=function(e,t){return void 0===t&&(t=bo()),{keytip:Ii({},e),uniqueID:t}},e._instance=new e,e}();function ou(e){return e.reduce((function(e,t){return e+ru+t.split("").join(ru)}),nu)}var lu=function(t){var i,n=t.children,r=function(t){var i=e.useRef(),n=t.keytipProps?Ii({disabled:t.disabled},t.keytipProps):void 0,r=qc(su.getInstance()),a=au(t);Wo((function(){i.current&&n&&((null==a?void 0:a.keytipProps)!==t.keytipProps||(null==a?void 0:a.disabled)!==t.disabled)&&r.update(n,i.current)})),Wo((function(){return n&&(i.current=r.register(n)),function(){n&&r.unregister(n,i.current)}}),[]);var s={ariaDescribedBy:void 0,keytipId:void 0};return n&&(s=function(e,t,i){var n=e.addParentOverflow(t),r=zo(i,function(e){var t=" ktp-layer-id";return e.length?t+" "+ou(e):t}(n.keySequences)),a=Ai([],n.keySequences,!0);return n.overflowSetSequence&&(a=function(e,t){var i,n,r;return i=t.length-1,n=Ai([],t,!0).pop(),(r=Ai([],e,!0).slice()).splice(i,0,n),r}(a,n.overflowSetSequence)),{ariaDescribedBy:r,keytipId:ou(a)}}(r,n,t.ariaDescribedBy)),s}(wi(t,["children"])),a=r.keytipId,s=r.ariaDescribedBy;return n(((i={})["data-ktp-target"]=a,i["data-ktp-execute-target"]=a,i["aria-describedby"]=s,i))},cu=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._anchor=e.createRef(),i._getMemoizedMenuButtonKeytipProps=vn((function(e){return Ii(Ii({},e),{hasMenu:!0})})),i._getSubmenuTarget=function(){return i._anchor.current?i._anchor.current:void 0},i._onItemClick=function(e){var t=i.props,n=t.item,r=t.onItemClick;r&&r(n,e)},i._renderAriaDescription=function(t,n){return t?e.createElement("span",{id:i._ariaDescriptionId,className:n},t):null},i}return bi(i,t),i.prototype.render=function(){var t=this,i=this.props,n=i.item,r=i.classNames,a=i.index,s=i.focusableElementIndex,o=i.totalItemCount,l=i.hasCheckmarks,c=i.hasIcons,d=i.expandedMenuItemKey,u=i.onItemClick,h=i.openSubMenu,p=i.dismissSubMenu,g=i.dismissMenu,m=tu;this.props.item.contextualMenuItemAs&&(m=nc(this.props.item.contextualMenuItemAs,m)),this.props.contextualMenuItemAs&&(m=nc(this.props.contextualMenuItemAs,m));var f=n.rel;n.target&&"_blank"===n.target.toLowerCase()&&(f=f||"nofollow noopener noreferrer");var v=ac(n),S=Ds(n,fs),y=sc(n),C=n.itemProps,_=n.ariaDescription,E=n.keytipProps;E&&v&&(E=this._getMemoizedMenuButtonKeytipProps(E)),_&&(this._ariaDescriptionId=bo());var T=zo(n.ariaDescribedBy,_?this._ariaDescriptionId:void 0,S["aria-describedby"]),b={"aria-describedby":T};return e.createElement("div",null,e.createElement(lu,{keytipProps:n.keytipProps,ariaDescribedBy:T,disabled:y},(function(i){return e.createElement("a",Ii({},b,S,i,{ref:t._anchor,href:n.href,target:n.target,rel:f,className:r.root,role:"menuitem","aria-haspopup":v||void 0,"aria-expanded":v?n.key===d:void 0,"aria-posinset":s+1,"aria-setsize":o,"aria-disabled":sc(n),style:n.style,onClick:t._onItemClick,onMouseEnter:t._onItemMouseEnter,onMouseLeave:t._onItemMouseLeave,onMouseMove:t._onItemMouseMove,onKeyDown:v?t._onItemKeyDown:void 0}),e.createElement(m,Ii({componentRef:n.componentRef,item:n,classNames:r,index:a,onCheckmarkClick:l&&u?u:void 0,hasIcons:c,openSubMenu:h,dismissSubMenu:p,dismissMenu:g,getSubmenuTarget:t._getSubmenuTarget},C)),t._renderAriaDescription(_,r.screenReaderText))})))},i}(iu),du=Ys(),uu=e.forwardRef((function(t,i){var n=t.styles,r=t.theme,a=t.getClassNames,s=t.className,o=du(n,{theme:r,getClassNames:a,className:s});return e.createElement("span",{className:o.wrapper,ref:i},e.createElement("span",{className:o.divider}))}));uu.displayName="VerticalDividerBase";var hu,pu=Ws(uu,(function(e){var t=e.theme,i=e.getClassNames,n=e.className;if(!t)throw new Error("Theme is undefined or null.");if(i){var r=i(t);return{wrapper:[r.wrapper],divider:[r.divider]}}return{wrapper:[{display:"inline-flex",height:"100%",alignItems:"center"},n],divider:[{width:1,height:"100%",backgroundColor:t.palette.neutralTertiaryAlt}]}}),void 0,{scope:"VerticalDivider"}),gu=function(t){function i(i){var n=t.call(this,i)||this;return n._getMemoizedMenuButtonKeytipProps=vn((function(e){return Ii(Ii({},e),{hasMenu:!0})})),n._onItemKeyDown=function(e){var t=n.props,i=t.item,r=t.onItemKeyDown;e.which===ao.enter?(n._executeItemClick(e),e.preventDefault(),e.stopPropagation()):r&&r(i,e)},n._getSubmenuTarget=function(){return n._splitButton},n._renderAriaDescription=function(t,i){return t?e.createElement("span",{id:n._ariaDescriptionId,className:i},t):null},n._onItemMouseEnterPrimary=function(e){var t=n.props,i=t.item,r=t.onItemMouseEnter;r&&r(Ii(Ii({},i),{subMenuProps:void 0,items:void 0}),e,n._splitButton)},n._onItemMouseEnterIcon=function(e){var t=n.props,i=t.item,r=t.onItemMouseEnter;r&&r(i,e,n._splitButton)},n._onItemMouseMovePrimary=function(e){var t=n.props,i=t.item,r=t.onItemMouseMove;r&&r(Ii(Ii({},i),{subMenuProps:void 0,items:void 0}),e,n._splitButton)},n._onItemMouseMoveIcon=function(e){var t=n.props,i=t.item,r=t.onItemMouseMove;r&&r(i,e,n._splitButton)},n._onIconItemClick=function(e){var t=n.props,i=t.item,r=t.onItemClickBase;r&&r(i,e,n._splitButton?n._splitButton:e.currentTarget)},n._executeItemClick=function(e){var t=n.props,i=t.item,r=t.executeItemClick,a=t.onItemClick;if(!i.disabled&&!i.isDisabled)return n._processingTouch&&!i.canCheck&&a?a(i,e):void(r&&r(i,e))},n._onTouchStart=function(e){n._splitButton&&!("onpointerdown"in n._splitButton)&&n._handleTouchAndPointerEvent(e)},n._onPointerDown=function(e){"touch"===e.pointerType&&(n._handleTouchAndPointerEvent(e),e.preventDefault(),e.stopImmediatePropagation())},n._async=new go(n),n._events=new So(n),n._dismissLabelId=bo(),n}return bi(i,t),i.prototype.componentDidMount=function(){this._splitButton&&"onpointerdown"in this._splitButton&&this._events.on(this._splitButton,"pointerdown",this._onPointerDown,!0)},i.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},i.prototype.render=function(){var t,i=this,n=this.props,r=n.item,a=n.classNames,s=n.index,o=n.focusableElementIndex,l=n.totalItemCount,c=n.hasCheckmarks,d=n.hasIcons,u=n.onItemMouseLeave,h=n.expandedMenuItemKey,p=ac(r),g=r.keytipProps;g&&(g=this._getMemoizedMenuButtonKeytipProps(g));var m=r.ariaDescription;m&&(this._ariaDescriptionId=bo());var f=null!==(t=rc(r))&&void 0!==t?t:void 0;return e.createElement(lu,{keytipProps:g,disabled:sc(r)},(function(t){return e.createElement("div",{"data-ktp-target":t["data-ktp-target"],ref:function(e){return i._splitButton=e},role:oc(r),"aria-label":r.ariaLabel,className:a.splitContainer,"aria-disabled":sc(r),"aria-expanded":p?r.key===h:void 0,"aria-haspopup":!0,"aria-describedby":zo(r.ariaDescribedBy,m?i._ariaDescriptionId:void 0,t["aria-describedby"]),"aria-checked":f,"aria-posinset":o+1,"aria-setsize":l,onMouseEnter:i._onItemMouseEnterPrimary,onMouseLeave:u?u.bind(i,Ii(Ii({},r),{subMenuProps:null,items:null})):void 0,onMouseMove:i._onItemMouseMovePrimary,onKeyDown:i._onItemKeyDown,onClick:i._executeItemClick,onTouchStart:i._onTouchStart,tabIndex:0,"data-is-focusable":!0,"aria-roledescription":r["aria-roledescription"]},i._renderSplitPrimaryButton(r,a,s,c,d),i._renderSplitDivider(r),i._renderSplitIconButton(r,a,s,t),i._renderAriaDescription(m,a.screenReaderText))}))},i.prototype._renderSplitPrimaryButton=function(t,i,n,r,a){var s=this.props,o=s.contextualMenuItemAs,l=void 0===o?tu:o,c=s.onItemClick,d={key:t.key,disabled:sc(t)||t.primaryDisabled,name:t.name,text:t.text||t.name,secondaryText:t.secondaryText,className:i.splitPrimary,canCheck:t.canCheck,isChecked:t.isChecked,checked:t.checked,iconProps:t.iconProps,id:this._dismissLabelId,onRenderIcon:t.onRenderIcon,data:t.data,"data-is-focusable":!1},u=t.itemProps;return e.createElement("button",Ii({},Ds(d,vs)),e.createElement(l,Ii({"data-is-focusable":!1,item:d,classNames:i,index:n,onCheckmarkClick:r&&c?c:void 0,hasIcons:a},u)))},i.prototype._renderSplitDivider=function(t){var i=t.getSplitButtonVerticalDividerClassNames||Qd;return e.createElement(pu,{getClassNames:i})},i.prototype._renderSplitIconButton=function(t,i,n,r){var a=this.props,s=a.onItemMouseLeave,o=a.onItemMouseDown,l=a.openSubMenu,c=a.dismissSubMenu,d=a.dismissMenu,u=tu;this.props.item.contextualMenuItemAs&&(u=nc(this.props.item.contextualMenuItemAs,u)),this.props.contextualMenuItemAs&&(u=nc(this.props.contextualMenuItemAs,u));var h={onClick:this._onIconItemClick,disabled:sc(t),className:i.splitMenu,subMenuProps:t.subMenuProps,submenuIconProps:t.submenuIconProps,split:!0,key:t.key,"aria-labelledby":this._dismissLabelId},p=Ii(Ii({},Ds(h,vs)),{onMouseEnter:this._onItemMouseEnterIcon,onMouseLeave:s?s.bind(this,t):void 0,onMouseDown:function(e){return o?o(t,e):void 0},onMouseMove:this._onItemMouseMoveIcon,"data-is-focusable":!1,"data-ktp-execute-target":r["data-ktp-execute-target"],"aria-haspopup":!0}),g=t.itemProps;return e.createElement("button",Ii({},p),e.createElement(u,Ii({componentRef:t.componentRef,item:h,classNames:i,index:n,hasIcons:!1,openSubMenu:l,dismissSubMenu:c,dismissMenu:d,getSubmenuTarget:this._getSubmenuTarget},g)))},i.prototype._handleTouchAndPointerEvent=function(e){var t=this,i=this.props.onTap;i&&i(e),this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout((function(){t._processingTouch=!1,t._lastTouchTimeoutId=void 0}),500)},i}(iu),mu=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._btn=e.createRef(),i._getMemoizedMenuButtonKeytipProps=vn((function(e){return Ii(Ii({},e),{hasMenu:!0})})),i._renderAriaDescription=function(t,n){return t?e.createElement("span",{id:i._ariaDescriptionId,className:n},t):null},i._getSubmenuTarget=function(){return i._btn.current?i._btn.current:void 0},i}return bi(i,t),i.prototype.render=function(){var t=this,i=this.props,n=i.item,r=i.classNames,a=i.index,s=i.focusableElementIndex,o=i.totalItemCount,l=i.hasCheckmarks,c=i.hasIcons,d=i.contextualMenuItemAs,u=i.expandedMenuItemKey,h=i.onItemMouseDown,p=i.onItemClick,g=i.openSubMenu,m=i.dismissSubMenu,f=i.dismissMenu,v=tu;n.contextualMenuItemAs&&(v=nc(n.contextualMenuItemAs,v)),d&&(v=nc(d,v));var S=rc(n),y=null!==S,C=oc(n),_=ac(n),E=n.itemProps,T=n.ariaLabel,b=n.ariaDescription,I=Ds(n,vs);delete I.disabled;var w=n.role||C;b&&(this._ariaDescriptionId=bo());var R=zo(n.ariaDescribedBy,b?this._ariaDescriptionId:void 0,I["aria-describedby"]),A={className:r.root,onClick:this._onItemClick,onKeyDown:_?this._onItemKeyDown:void 0,onMouseEnter:this._onItemMouseEnter,onMouseLeave:this._onItemMouseLeave,onMouseDown:function(e){return h?h(n,e):void 0},onMouseMove:this._onItemMouseMove,href:n.href,title:n.title,"aria-label":T,"aria-describedby":R,"aria-haspopup":_||void 0,"aria-expanded":_?n.key===u:void 0,"aria-posinset":s+1,"aria-setsize":o,"aria-disabled":sc(n),"aria-checked":"menuitemcheckbox"!==w&&"menuitemradio"!==w||!y?void 0:!!S,"aria-selected":"menuitem"===w&&y?!!S:void 0,role:w,style:n.style},P=n.keytipProps;return P&&_&&(P=this._getMemoizedMenuButtonKeytipProps(P)),e.createElement(lu,{keytipProps:P,ariaDescribedBy:R,disabled:sc(n)},(function(i){return e.createElement("button",Ii({ref:t._btn},I,A,i),e.createElement(v,Ii({componentRef:n.componentRef,item:n,classNames:r,index:a,onCheckmarkClick:l&&p?p:void 0,hasIcons:c,openSubMenu:g,dismissSubMenu:m,dismissMenu:f,getSubmenuTarget:t._getSubmenuTarget},E)),t._renderAriaDescription(b,r.screenReaderText))}))},i}(iu);function fu(t,i){var n=e.useRef(i);return n.current||(n.current=bo(t)),n.current}!function(e){e[e.small=0]="small",e[e.medium=1]="medium",e[e.large=2]="large",e[e.xLarge=3]="xLarge",e[e.xxLarge=4]="xxLarge",e[e.xxxLarge=5]="xxxLarge",e[e.unknown=999]="unknown"}(hu||(hu={}));var vu,Su,yu=[479,639,1023,1365,1919,99999999];function Cu(){var e;return null!==(e=null!=vu?vu:Su)&&void 0!==e?e:hu.large}function _u(e){try{return e.document.documentElement.clientWidth}catch(t){return e.innerWidth}}var Eu=function(t,i){var n=e.useState(Cu()),r=n[0],a=n[1],s=e.useCallback((function(){var e=function(e){var t=hu.small;if(e){try{for(;_u(e)>yu[t];)t++}catch(e){t=Cu()}Su=t}else{if(void 0===vu)throw new Error("Content was rendered in a server environment without providing a default responsive mode. Call setResponsiveMode to define what the responsive mode is.");t=vu}return t}(Tn(t.current));r!==e&&a(e)}),[t,r]);return Hc(Gc(),"resize",s),e.useEffect((function(){void 0===i&&s()}),[i]),null!=i?i:r},Tu=e.createContext({}),bu=Ys(),Iu=Ys(),wu={items:[],shouldFocusOnMount:!0,gapSpace:0,directionalHint:ll.bottomAutoEdge,beakWidth:16};function Ru(e){for(var t=0,i=0,n=e;i<n.length;i++){var r=n[i];r.itemType!==sl.Divider&&r.itemType!==sl.Header&&(t+=r.customOnRenderListLength?r.customOnRenderListLength:1)}return t}function Au(e,t){var i=null==t?void 0:t.target,n=e.subMenuProps?e.subMenuProps.items:e.items;if(n){for(var r=[],a=0,s=n;a<s.length;a++){var o=s[a];if(o.preferMenuTargetAsEventTarget){var l=o.onClick,c=wi(o,["onClick"]);r.push(Ii(Ii({},c),{onClick:Fu(l,i)}))}else r.push(o)}return r}}var Pu="ContextualMenu",Mu=vn((function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){return Za.apply(void 0,Ai([t,eu],e,!1))}}));function ku(t,i){var n=t.hidden,r=t.items,a=t.theme,s=t.className,o=t.id,l=t.target,c=e.useState(),d=c[0],u=c[1],h=e.useState(),p=h[0],g=h[1],m=e.useState(),f=m[0],v=m[1],S=fu(Pu,o),y=e.useCallback((function(){v(void 0),u(void 0),g(void 0)}),[]),C=e.useCallback((function(e,t,i){var n=e.key;d!==n&&(t.focus(),v(i),u(n),g(t))}),[d]);e.useEffect((function(){n&&y()}),[n,y]);var _=function(t,i){var n=e.useRef(!1);e.useEffect((function(){return n.current=!0,function(){n.current=!1}}),[]);return function(e,r){r?t(e,r):n.current&&i()}}(i,y);return[d,C,function(){var e=xu(d,r),t=null;if(e&&(t={items:Au(e,{target:l}),target:p,onDismiss:_,isSubMenu:!0,id:S,shouldFocusOnMount:!0,shouldFocusOnContainer:f,directionalHint:Rn(a)?ll.leftTopEdge:ll.rightTopEdge,className:s,gapSpace:0,isBeakVisible:!1},e.subMenuProps&&fo(t,e.subMenuProps),e.preferMenuTargetAsEventTarget)){var i=e.onItemClick;t.onItemClick=Fu(i,l)}return t},_]}var Du=e.memo(e.forwardRef((function(t,i){var n,r=Xl(wu,t),a=(r.ref,wi(r,["ref"])),s=e.useRef(null),o=Vc(),l=fu(Pu,a.id),c=function(e,t){var i;return null===(i=a.onDismiss)||void 0===i?void 0:i.call(a,e,t)},d=Kc(a.target,s),u=d[0],h=d[1],p=function(t,i,n){var r=t.hidden,a=t.onRestoreFocus,s=e.useRef(),o=e.useCallback((function(e){var t,i;a?a(e):(null==e?void 0:e.documentContainsFocus)&&(null===(i=null===(t=s.current)||void 0===t?void 0:t.focus)||void 0===i||i.call(t))}),[a]);return Wo((function(){var e,t;if(r)s.current&&(o({originalElement:s.current,containsFocus:!0,documentContainsFocus:(null===(t=_n())||void 0===t?void 0:t.hasFocus())||!1}),s.current=void 0);else{var a=null==i?void 0:i.document.activeElement;(null===(e=n.current)||void 0===e?void 0:e.contains(a))||"BODY"===a.tagName||(s.current=a)}}),[r,null==i?void 0:i.document.activeElement,o,n]),[o]}(a,h,s)[0],g=ku(a,c),m=g[0],f=g[1],v=g[2],S=g[3],y=function(t){var i=t.delayUpdateFocusOnHover,n=t.hidden,r=e.useRef(!i),a=e.useRef(!1);e.useEffect((function(){r.current=!i,a.current=!n&&!i&&a.current}),[i,n]);var s=e.useCallback((function(){i&&(r.current=!1)}),[i]);return[r,a,s]}(a),C=y[0],_=y[1],E=y[2],T=function(t){var i=e.useRef(!0),n=e.useRef();return[function(){i.current||void 0===n.current?i.current=!1:(t.clearTimeout(n.current),n.current=void 0),n.current=t.setTimeout((function(){i.current=!0}),250)},i]}(o),b=T[0],I=T[1],w=function(t,i){var n=t.subMenuHoverDelay,r=void 0===n?250:n,a=e.useRef(void 0),s=function(){void 0!==a.current&&(i.clearTimeout(a.current),a.current=void 0)};return[s,function(e){a.current=i.setTimeout((function(){e(),s()}),r)},a]}(a,o),R=w[0],A=w[1],P=w[2],M=Eu(s,a.responsiveMode);!function(t,i){var n=t.hidden,r=void 0!==n&&n,a=t.onMenuDismissed,s=t.onMenuOpened,o=au(r),l=e.useRef(s),c=e.useRef(a),d=e.useRef(t);l.current=s,c.current=a,d.current=t,e.useEffect((function(){var e,t;r&&!1===o?null===(e=c.current)||void 0===e||e.call(c,d.current):r||!1===o||null===(t=l.current)||void 0===t||t.call(l,d.current)}),[r,o]),e.useEffect((function(){return function(){var e;return null===(e=c.current)||void 0===e?void 0:e.call(c,d.current)}}),[])}(a);var k,D=function(t,i,n,r){var a=t.theme,s=t.isSubMenu,o=t.focusZoneProps,l=void 0===o?{}:o,c=l.checkForNoWrap,d=l.direction,u=void 0===d?dl.vertical:d,h=e.useRef(),p=function(e,t,n){var r=!1;return t(e)&&(i(e,n),e.preventDefault(),e.stopPropagation(),r=!0),r},g=function(e){return e.which===ao.escape||function(e){var t=Rn(a)?ao.right:ao.left;return!(e.which!==t||!s||u!==dl.vertical&&(!c||Il(e.target,"data-no-horizontal-wrap")))}(e)||e.which===ao.up&&(e.altKey||e.metaKey)},m=function(e){h.current=Ou(e);var t=e.which===ao.escape&&(Ql()||Zl());return p(e,g,t)},f=function(e){var t=h.current&&Ou(e);return h.current=!1,!!t&&!(Zl()||Ql())};return[m,function(e){return p(e,f,!0)},function(e){if(!m(e)&&n.current){var t=!(!e.altKey&&!e.metaKey),i=e.which===ao.up,r=e.which===ao.down;if(!t&&(i||r)){var a=i?vl(n.current,n.current.lastChild,!0):fl(n.current,n.current.firstChild,!0);a&&(a.focus(),e.preventDefault(),e.stopPropagation())}}},function(e,t){var i=Rn(a)?ao.left:ao.right;e.disabled||t.which!==i&&t.which!==ao.enter&&(t.which!==ao.down||!t.altKey&&!t.metaKey)||(r(e,t.currentTarget),t.preventDefault())}]}(a,c,s,f),O=D[0],N=D[1],L=D[2],x=D[3],F=function(e,t,i,n,r,a,s,o,l,c,d,u,h){var p=e.target,g=function(){return!t.current||!a.current},m=function(e,t,i){var n=i||t.currentTarget;e.key!==s&&(c(),void 0===s&&n.focus(),ac(e)?(t.stopPropagation(),l((function(){n.focus(),d(e,n,!0)}))):l((function(){u(t),n.focus()})))},f=function(t,i,n){var r=Au(t,{target:p});if(c(),ac(t)||r&&r.length){if(t.key!==s){var a="boolean"==typeof e.shouldFocusOnContainer?e.shouldFocusOnContainer:"mouse"===i.nativeEvent.pointerType;d(t,n,a)}}else v(t,i);i.stopPropagation(),i.preventDefault()},v=function(t,i){if(!t.disabled&&!t.isDisabled){t.preferMenuTargetAsEventTarget&&Uu(i,p);var n=!1;t.onClick?n=!!t.onClick(i,t):e.onItemClick&&(n=!!e.onItemClick(i,t)),!n&&i.defaultPrevented||h(i,!0)}};return[function(e,t,i){r.current&&(a.current=!0),g()||m(e,t,i)},function(e,s,o){var l=s.currentTarget;r.current&&(a.current=!0,t.current&&void 0===i.current&&l!==(null==n?void 0:n.document.activeElement)&&m(e,s,o))},function(e,t){var i;if(!g()&&(c(),void 0===s))if(o.current.setActive)try{o.current.setActive()}catch(e){}else null===(i=o.current)||void 0===i||i.focus()},function(e,t){f(e,t,t.currentTarget)},function(e,t){v(e,t),t.stopPropagation()},v,f]}(a,I,P,h,C,_,m,s,A,R,f,S,c),U=F[0],B=F[1],V=F[2],H=F[3],$=F[4],G=F[5],j=F[6],z=function(t,i,n){var r=0,a=t.items,s=t.totalItemCount,o=t.hasCheckmarks,l=t.hasIcons;return e.createElement("ul",{className:i.list,onKeyDown:O,onKeyUp:N,role:"presentation"},a.map((function(e,t){var n=W(e,t,r,s,o,l,i);if(e.itemType!==sl.Divider&&e.itemType!==sl.Header){var a=e.customOnRenderListLength?e.customOnRenderListLength:1;r+=a}return n})))},W=function(t,i,n,r,s,o,l){var c,d,u=[],h=t.iconProps||{iconName:"None"},p=t.getItemClassNames,g=t.itemProps,f=g?g.styles:void 0,v=t.itemType===sl.Divider?t.className:void 0,S=t.submenuIconProps?t.submenuIconProps.className:"";if(p)d=p(a.theme,sc(t),m===t.key,!!rc(t),!!t.href,"None"!==h.iconName,t.className,v,h.className,S,t.primaryDisabled);else{var y={theme:a.theme,disabled:sc(t),expanded:m===t.key,checked:!!rc(t),isAnchorLink:!!t.href,knownIcon:"None"!==h.iconName,itemClassName:t.className,dividerClassName:v,iconClassName:h.className,subMenuClassName:S,primaryDisabled:t.primaryDisabled};d=Iu(Mu(null===(c=l.subComponentStyles)||void 0===c?void 0:c.menuItem,f),y)}switch("-"!==t.text&&"-"!==t.name||(t.itemType=sl.Divider),t.itemType){case sl.Divider:u.push(J(i,d));break;case sl.Header:u.push(J(i,d));var C=Q(t,d,l,i,s,o);u.push(K(C,t.key||i,d,t.title));break;case sl.Section:u.push(q(t,d,l,i,s,o));break;default:var _=function(){return Y(t,d,i,n,r,s,o)},E=a.onRenderContextualMenuItem?a.onRenderContextualMenuItem(t,_):_();u.push(K(E,t.key||i,d,t.title))}return e.createElement(e.Fragment,{key:t.key},u)},q=function(t,i,n,r,a,s){var o=t.sectionProps;if(o){var c,d;if(o.title){var u=void 0,h="";if("string"==typeof o.title){var p=l+o.title.replace(/\s/g,"");u={key:"section-".concat(o.title,"-title"),itemType:sl.Header,text:o.title,id:p},h=p}else{var g=o.title.id||l+o.title.key.replace(/\s/g,"");u=Ii(Ii({},o.title),{id:g}),h=g}u&&(d={role:"group","aria-labelledby":h},c=Q(u,i,n,r,a,s))}if(o.items&&o.items.length>0){var m=0;return e.createElement("li",{role:"presentation",key:o.key||t.key||"section-".concat(r)},e.createElement("div",Ii({},d),e.createElement("ul",{className:n.list,role:"presentation"},o.topDivider&&J(r,i,!0,!0),c&&K(c,t.key||r,i,t.title),o.items.map((function(e,t){var i=W(e,t,m,Ru(o.items),a,s,n);if(e.itemType!==sl.Divider&&e.itemType!==sl.Header){var r=e.customOnRenderListLength?e.customOnRenderListLength:1;m+=r}return i})),o.bottomDivider&&J(r,i,!1,!0))))}}},K=function(t,i,n,r){return e.createElement("li",{role:"presentation",title:r,key:i,className:n.item},t)},J=function(t,i,n,r){return r||t>0?e.createElement("li",{role:"separator",key:"separator-"+t+(void 0===n?"":n?"-top":"-bottom"),className:i.divider,"aria-hidden":"true"}):null},Y=function(t,i,n,r,s,o,l){if(t.onRender)return t.onRender(Ii({"aria-posinset":r+1,"aria-setsize":s},t),c);var d={item:t,classNames:i,index:n,focusableElementIndex:r,totalItemCount:s,hasCheckmarks:o,hasIcons:l,contextualMenuItemAs:a.contextualMenuItemAs,onItemMouseEnter:U,onItemMouseLeave:V,onItemMouseMove:B,onItemMouseDown:Nu,executeItemClick:G,onItemKeyDown:x,expandedMenuItemKey:m,openSubMenu:f,dismissSubMenu:S,dismissMenu:c};if(t.href){var u=cu;return t.contextualMenuItemWrapperAs&&(u=nc(t.contextualMenuItemWrapperAs,u)),e.createElement(u,Ii({},d,{onItemClick:$}))}if(t.split&&ac(t)){var h=gu;return t.contextualMenuItemWrapperAs&&(h=nc(t.contextualMenuItemWrapperAs,h)),e.createElement(h,Ii({},d,{onItemClick:H,onItemClickBase:j,onTap:R}))}var p=mu;return t.contextualMenuItemWrapperAs&&(p=nc(t.contextualMenuItemWrapperAs,p)),e.createElement(p,Ii({},d,{onItemClick:H,onItemClickBase:j}))},Q=function(t,i,n,r,s,o){var l=tu;t.contextualMenuItemAs&&(l=nc(t.contextualMenuItemAs,l)),a.contextualMenuItemAs&&(l=nc(a.contextualMenuItemAs,l));var c=t.itemProps,d=t.id,u=c&&Ds(c,ks);return e.createElement("div",Ii({id:d,className:n.header},u,{style:t.style}),e.createElement(l,Ii({item:t,classNames:i,index:r,onCheckmarkClick:s?H:void 0,hasIcons:o},c)))},Z=a.isBeakVisible,X=a.items,ee=a.labelElementId,te=a.id,ie=a.className,ne=a.beakWidth,re=a.directionalHint,ae=a.directionalHintForRTL,se=a.alignTargetEdge,oe=a.gapSpace,le=a.coverTarget,ce=a.ariaLabel,de=a.doNotLayer,ue=a.target,he=a.bounds,pe=a.useTargetWidth,ge=a.useTargetAsMinWidth,me=a.directionalHintFixed,fe=a.shouldFocusOnMount,ve=a.shouldFocusOnContainer,Se=a.title,ye=a.styles,Ce=a.theme,_e=a.calloutProps,Ee=a.onRenderSubMenu,Te=void 0===Ee?Lu:Ee,be=a.onRenderMenuList,Ie=void 0===be?function(e,t){return z(e,Ae)}:be,we=a.focusZoneProps,Re=a.getMenuClassNames,Ae=Re?Re(Ce,ie):bu(ye,{theme:Ce,className:ie}),Pe=function e(t){for(var i=0,n=t;i<n.length;i++){var r=n[i];if(r.iconProps)return!0;if(r.itemType===sl.Section&&r.sectionProps&&e(r.sectionProps.items))return!0}return!1}(X),Me=Ii(Ii({direction:dl.vertical,handleTabKey:1,isCircularNavigation:!0},we),{className:Os(Ae.root,null===(n=a.focusZoneProps)||void 0===n?void 0:n.className)}),ke=function(e){return e.some((function(e){return!!e.canCheck||!(!e.sectionProps||!e.sectionProps.items.some((function(e){return!0===e.canCheck})))}))}(X),De=m&&!0!==a.hidden?v():null;Z=void 0===Z?M<=hu.medium:Z;var Oe=u.current;if((pe||ge)&&Oe&&Oe.offsetWidth){var Ne=Oe.getBoundingClientRect().width-2;pe?k={width:Ne}:ge&&(k={minWidth:Ne})}if(X&&X.length>0){var Le=Ru(X),xe=Ae.subComponentStyles?Ae.subComponentStyles.callout:void 0;return e.createElement(Tu.Consumer,null,(function(t){return e.createElement(xd,Ii({styles:xe,onRestoreFocus:p},_e,{target:ue||t.target,isBeakVisible:Z,beakWidth:ne,directionalHint:re,directionalHintForRTL:ae,gapSpace:oe,coverTarget:le,doNotLayer:de,className:Os("ms-ContextualMenu-Callout",_e&&_e.className),setInitialFocus:fe,onDismiss:a.onDismiss||t.onDismiss,onScroll:b,bounds:he,directionalHintFixed:me,alignTargetEdge:se,hidden:a.hidden||t.hidden,ref:i}),e.createElement("div",{style:k,ref:s,id:te,className:Ae.container,tabIndex:ve?0:-1,onKeyDown:L,onKeyUp:N,onFocusCapture:E,"aria-label":ce,"aria-labelledby":ee,role:"menu"},Se&&e.createElement("div",{className:Ae.title}," ",Se," "),X&&X.length?function(t,i){var n=a.focusZoneAs,r=void 0===n?Yl:n;return e.createElement(r,Ii({},i),t)}(Ie({ariaLabel:ce,items:X,totalItemCount:Le,hasCheckmarks:ke,hasIcons:Pe,defaultMenuItemRenderer:function(e){return function(e,t){var i=e.index,n=e.focusableElementIndex,r=e.totalItemCount,a=e.hasCheckmarks,s=e.hasIcons;return W(e,i,n,r,a,s,t)}(e,Ae)},labelElementId:ee},(function(e,t){return z(e,Ae)})),Me):null,De&&Te(De,Lu)),e.createElement(Vo,null))}))}return null})),(function(e,t){return!(t.shouldUpdateWhenHidden||!e.hidden||!t.hidden)||mo(e,t)}));function Ou(e){return e.which===ao.alt||"Meta"===e.key}function Nu(e,t){var i;null===(i=e.onMouseDown)||void 0===i||i.call(e,e,t)}function Lu(e,t){throw Error("ContextualMenuBase: onRenderSubMenu callback is null or undefined. Please ensure to set `onRenderSubMenu` property either manually or with `styled` helper.")}function xu(e,t){for(var i=0,n=t;i<n.length;i++){var r=n[i];if(r.itemType===sl.Section&&r.sectionProps){var a=xu(e,r.sectionProps.items);if(a)return a}else if(r.key&&r.key===e)return r}}function Fu(e,t){return e?function(i,n){return Uu(i,t),e(i,n)}:e}function Uu(e,t){e&&t&&(e.persist(),t instanceof Event?e.target=t.target:t instanceof Element&&(e.target=t))}Du.displayName="ContextualMenuBase";var Bu={root:"ms-ContextualMenu",container:"ms-ContextualMenu-container",list:"ms-ContextualMenu-list",header:"ms-ContextualMenu-header",title:"ms-ContextualMenu-title",isopen:"is-open"};function Vu(t){return e.createElement(Hu,Ii({},t))}var Hu=Ws(Du,(function(e){var t=e.className,i=e.theme,n=Kr(Bu,i),r=i.fonts,a=i.semanticColors,s=i.effects;return{root:[i.fonts.medium,n.root,n.isopen,{backgroundColor:a.menuBackground,minWidth:"180px"},t],container:[n.container,{selectors:{":focus":{outline:0}}}],list:[n.list,n.isopen,{listStyleType:"none",margin:"0",padding:"0"}],header:[n.header,r.small,{fontWeight:Mr.semibold,color:a.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:Wd,lineHeight:Wd,cursor:"default",padding:"0px 6px",userSelect:"none",textAlign:"left"}],title:[n.title,{fontSize:r.mediumPlus.fontSize,paddingRight:"14px",paddingLeft:"14px",paddingBottom:"5px",paddingTop:"5px",backgroundColor:a.menuItemBackgroundPressed}],subComponentStyles:{callout:{root:{boxShadow:s.elevation8}},menuItem:{}}}}),(function(e){return{onRenderSubMenu:e.onRenderSubMenu?(t=e.onRenderSubMenu,i=Vu,cl(t)(i)):Vu};var t,i}),{scope:"ContextualMenu"}),$u=Hu;$u.displayName="ContextualMenu";var Gu={msButton:"ms-Button",msButtonHasMenu:"ms-Button--hasMenu",msButtonIcon:"ms-Button-icon",msButtonMenuIcon:"ms-Button-menuIcon",msButtonLabel:"ms-Button-label",msButtonDescription:"ms-Button-description",msButtonScreenReaderText:"ms-Button-screenReaderText",msButtonFlexContainer:"ms-Button-flexContainer",msButtonTextContainer:"ms-Button-textContainer"},ju=vn((function(e,t,i,n,r,a,s,o,l,c,d){var u,h,p=Kr(Gu,e||{}),g=c&&!d;return Xa({root:[p.msButton,t.root,n,l&&["is-checked",t.rootChecked],g&&["is-expanded",t.rootExpanded,{selectors:(u={},u[":hover .".concat(p.msButtonIcon)]=t.iconExpandedHovered,u[":hover .".concat(p.msButtonMenuIcon)]=t.menuIconExpandedHovered||t.rootExpandedHovered,u[":hover"]=t.rootExpandedHovered,u)}],o&&[Gu.msButtonHasMenu,t.rootHasMenu],s&&["is-disabled",t.rootDisabled],!s&&!g&&!l&&{selectors:(h={":hover":t.rootHovered},h[":hover .".concat(p.msButtonLabel)]=t.labelHovered,h[":hover .".concat(p.msButtonIcon)]=t.iconHovered,h[":hover .".concat(p.msButtonDescription)]=t.descriptionHovered,h[":hover .".concat(p.msButtonMenuIcon)]=t.menuIconHovered,h[":focus"]=t.rootFocused,h[":active"]=t.rootPressed,h[":active .".concat(p.msButtonIcon)]=t.iconPressed,h[":active .".concat(p.msButtonDescription)]=t.descriptionPressed,h[":active .".concat(p.msButtonMenuIcon)]=t.menuIconPressed,h)},s&&l&&[t.rootCheckedDisabled],!s&&l&&{selectors:{":hover":t.rootCheckedHovered,":active":t.rootCheckedPressed}},i],flexContainer:[p.msButtonFlexContainer,t.flexContainer],textContainer:[p.msButtonTextContainer,t.textContainer],icon:[p.msButtonIcon,r,t.icon,g&&t.iconExpanded,l&&t.iconChecked,s&&t.iconDisabled],label:[p.msButtonLabel,t.label,l&&t.labelChecked,s&&t.labelDisabled],menuIcon:[p.msButtonMenuIcon,a,t.menuIcon,l&&t.menuIconChecked,s&&!d&&t.menuIconDisabled,!s&&!g&&!l&&{selectors:{":hover":t.menuIconHovered,":active":t.menuIconPressed}},g&&["is-expanded",t.menuIconExpanded]],description:[p.msButtonDescription,t.description,l&&t.descriptionChecked,s&&t.descriptionDisabled],screenReaderText:[p.msButtonScreenReaderText,t.screenReaderText]})})),zu=vn((function(e,t,i,n,r){return{root:cn(e.splitButtonMenuButton,i&&[e.splitButtonMenuButtonExpanded],t&&[e.splitButtonMenuButtonDisabled],n&&!t&&[e.splitButtonMenuButtonChecked],r&&!t&&[{selectors:{":focus":e.splitButtonMenuFocused}}]),splitButtonContainer:cn(e.splitButtonContainer,!t&&n&&[e.splitButtonContainerChecked,{selectors:{":hover":e.splitButtonContainerCheckedHovered}}],!t&&!n&&[{selectors:{":hover":e.splitButtonContainerHovered,":focus":e.splitButtonContainerFocused}}],t&&e.splitButtonContainerDisabled),icon:cn(e.splitButtonMenuIcon,t&&e.splitButtonMenuIconDisabled,!t&&r&&e.splitButtonMenuIcon),flexContainer:cn(e.splitButtonFlexContainer),divider:cn(e.splitButtonDivider,(r||t)&&e.splitButtonDividerDisabled)}})),Wu=function(t){function i(i){var n=t.call(this,i)||this;return n._buttonElement=e.createRef(),n._splitButtonContainer=e.createRef(),n._mergedRef=eo(),n._renderedVisibleMenu=!1,n._getMemoizedMenuButtonKeytipProps=vn((function(e){return Ii(Ii({},e),{hasMenu:!0})})),n._onRenderIcon=function(t,i){var r=n.props.iconProps;if(r&&(void 0!==r.iconName||r.imageProps)){var a=r.className,s=r.imageProps,o=wi(r,["className","imageProps"]);if(r.styles)return e.createElement(al,Ii({className:Os(n._classNames.icon,a),imageProps:s},o));if(r.iconName)return e.createElement(il,Ii({className:Os(n._classNames.icon,a)},o));if(s)return e.createElement(ol,Ii({className:Os(n._classNames.icon,a),imageProps:s},o))}return null},n._onRenderTextContents=function(){var t=n.props,i=t.text,r=t.children,a=t.secondaryText,s=void 0===a?n.props.description:a,o=t.onRenderText,l=void 0===o?n._onRenderText:o,c=t.onRenderDescription,d=void 0===c?n._onRenderDescription:c;return i||"string"==typeof r||s?e.createElement("span",{className:n._classNames.textContainer},l(n.props,n._onRenderText),d(n.props,n._onRenderDescription)):[l(n.props,n._onRenderText),d(n.props,n._onRenderDescription)]},n._onRenderText=function(){var t=n.props.text,i=n.props.children;return void 0===t&&"string"==typeof i&&(t=i),n._hasText()?e.createElement("span",{key:n._labelId,className:n._classNames.label,id:n._labelId},t):null},n._onRenderChildren=function(){var e=n.props.children;return"string"==typeof e?null:e},n._onRenderDescription=function(t){var i=t.secondaryText,r=void 0===i?n.props.description:i;return r?e.createElement("span",{key:n._descriptionId,className:n._classNames.description,id:n._descriptionId},r):null},n._onRenderAriaDescription=function(){var t=n.props.ariaDescription;return t?e.createElement("span",{className:n._classNames.screenReaderText,id:n._ariaDescriptionId},t):null},n._onRenderMenuIcon=function(t){var i=n.props.menuIconProps;return e.createElement(il,Ii({iconName:"ChevronDown"},i,{className:n._classNames.menuIcon}))},n._onRenderMenu=function(t){var i=n.props.menuAs?nc(n.props.menuAs,$u):$u;return e.createElement(i,Ii({},t))},n._onDismissMenu=function(e){var t=n.props.menuProps;t&&t.onDismiss&&t.onDismiss(e),e&&e.defaultPrevented||n._dismissMenu()},n._dismissMenu=function(){n._menuShouldFocusOnMount=void 0,n._menuShouldFocusOnContainer=void 0,n.setState({menuHidden:!0})},n._openMenu=function(e,t){void 0===t&&(t=!0),n.props.menuProps&&(n._menuShouldFocusOnContainer=e,n._menuShouldFocusOnMount=t,n._renderedVisibleMenu=!0,n.setState({menuHidden:!1}))},n._onToggleMenu=function(e){var t=!0;n.props.menuProps&&!1===n.props.menuProps.shouldFocusOnMount&&(t=!1),n.state.menuHidden?n._openMenu(e,t):n._dismissMenu()},n._onSplitContainerFocusCapture=function(e){var t=n._splitButtonContainer.current;!t||e.target&&ro(e.target,t)||t.focus()},n._onSplitButtonPrimaryClick=function(e){n.state.menuHidden||n._dismissMenu();var t=n._processingTouch&&!n.props.toggle;!t&&n.props.onClick?n.props.onClick(e):t&&n._onMenuClick(e)},n._onKeyDown=function(e){!n.props.disabled||e.which!==ao.enter&&e.which!==ao.space?n.props.disabled||(n.props.menuProps?n._onMenuKeyDown(e):void 0!==n.props.onKeyDown&&n.props.onKeyDown(e)):(e.preventDefault(),e.stopPropagation())},n._onKeyUp=function(e){n.props.disabled||void 0===n.props.onKeyUp||n.props.onKeyUp(e)},n._onKeyPress=function(e){n.props.disabled||void 0===n.props.onKeyPress||n.props.onKeyPress(e)},n._onMouseUp=function(e){n.props.disabled||void 0===n.props.onMouseUp||n.props.onMouseUp(e)},n._onMouseDown=function(e){n.props.disabled||void 0===n.props.onMouseDown||n.props.onMouseDown(e)},n._onClick=function(e){n.props.disabled||(n.props.menuProps?n._onMenuClick(e):void 0!==n.props.onClick&&n.props.onClick(e))},n._onSplitButtonContainerKeyDown=function(e){e.which===ao.enter||e.which===ao.space?n._buttonElement.current&&(n._buttonElement.current.click(),e.preventDefault(),e.stopPropagation()):n._onMenuKeyDown(e)},n._onMenuKeyDown=function(e){var t;if(!n.props.disabled){n.props.onKeyDown&&n.props.onKeyDown(e);var i=e.which===ao.up,r=e.which===ao.down;if(!e.defaultPrevented&&n._isValidMenuOpenKey(e)){var a=n.props.onMenuClick;a&&a(e,n.props),n._onToggleMenu(!1),e.preventDefault(),e.stopPropagation()}e.which!==ao.enter&&e.which!==ao.space||Gr(!0,e.target,null===(t=n.context)||void 0===t?void 0:t.registeredProviders),e.altKey||e.metaKey||!i&&!r||!n.state.menuHidden&&n.props.menuProps&&((void 0!==n._menuShouldFocusOnMount?n._menuShouldFocusOnMount:n.props.menuProps.shouldFocusOnMount)||(e.preventDefault(),e.stopPropagation(),n._menuShouldFocusOnMount=!0,n.forceUpdate()))}},n._onTouchStart=function(){n._isSplitButton&&n._splitButtonContainer.current&&!("onpointerdown"in n._splitButtonContainer.current)&&n._handleTouchAndPointerEvent()},n._onMenuClick=function(e){var t=n.props,i=t.onMenuClick,r=t.menuProps;i&&i(e,n.props);var a="boolean"==typeof(null==r?void 0:r.shouldFocusOnContainer)?r.shouldFocusOnContainer:"mouse"===e.nativeEvent.pointerType;e.defaultPrevented||(n._onToggleMenu(a),e.preventDefault(),e.stopPropagation())},lo(n),n._async=new go(n),n._events=new So(n),n.props.split,n._labelId=bo(),n._descriptionId=bo(),n._ariaDescriptionId=bo(),n.state={menuHidden:!0},n}return bi(i,t),Object.defineProperty(i.prototype,"_isSplitButton",{get:function(){return!!this.props.menuProps&&!!this.props.onClick&&!0===this.props.split},enumerable:!1,configurable:!0}),i.prototype.render=function(){var e,t=this.props,i=t.ariaDescription,n=t.ariaLabel,r=t.ariaHidden,a=t.className,s=t.disabled,o=t.allowDisabledFocus,l=t.primaryDisabled,c=t.secondaryText,d=void 0===c?this.props.description:c,u=t.href,h=t.iconProps,p=t.menuIconProps,g=t.styles,m=t.checked,f=t.variantClassName,v=t.theme,S=t.toggle,y=t.getClassNames,C=t.role,_=this.state.menuHidden,E=s||l;this._classNames=y?y(v,a,f,h&&h.className,p&&p.className,E,m,!_,!!this.props.menuProps,this.props.split,!!o):ju(v,g,a,f,h&&h.className,p&&p.className,E,!!this.props.menuProps,m,!_,this.props.split);var T=this,b=T._ariaDescriptionId,I=T._labelId,w=T._descriptionId,R=!E&&!!u,A=R?"a":"button",P=Ds(fo(R?{}:{type:"button"},this.props.rootProps,this.props),R?fs:vs,["disabled"]),M=n||P["aria-label"],k=void 0;i?k=b:d&&this.props.onRenderDescription!==Ro?k=w:P["aria-describedby"]&&(k=P["aria-describedby"]);var D=void 0;P["aria-labelledby"]?D=P["aria-labelledby"]:k&&!M&&(D=this._hasText()?I:void 0);var O=!(!1===this.props["data-is-focusable"]||s&&!o||this._isSplitButton),N="menuitemcheckbox"===C||"checkbox"===C,L=N||!0===S?!!m:void 0,x=fo(P,((e={className:this._classNames.root,ref:this._mergedRef(this.props.elementRef,this._buttonElement),disabled:E&&!o,onKeyDown:this._onKeyDown,onKeyPress:this._onKeyPress,onKeyUp:this._onKeyUp,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onClick:this._onClick,"aria-label":M,"aria-labelledby":D,"aria-describedby":k,"aria-disabled":E,"data-is-focusable":O})[N?"aria-checked":"aria-pressed"]=L,e));if(r&&(x["aria-hidden"]=!0),this._isSplitButton)return this._onRenderSplitButtonContent(A,x);if(this.props.menuProps){var F=this.props.menuProps.id,U=void 0===F?"".concat(this._labelId,"-menu"):F;fo(x,{"aria-expanded":!_,"aria-controls":_?null:U,"aria-haspopup":!0})}return this._onRenderContent(A,x)},i.prototype.componentDidMount=function(){this._isSplitButton&&this._splitButtonContainer.current&&("onpointerdown"in this._splitButtonContainer.current&&this._events.on(this._splitButtonContainer.current,"pointerdown",this._onPointerDown,!0),"onpointerup"in this._splitButtonContainer.current&&this.props.onPointerUp&&this._events.on(this._splitButtonContainer.current,"pointerup",this.props.onPointerUp,!0))},i.prototype.componentDidUpdate=function(e,t){this.props.onAfterMenuDismiss&&!t.menuHidden&&this.state.menuHidden&&this.props.onAfterMenuDismiss()},i.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},i.prototype.focus=function(){var e,t;this._isSplitButton&&this._splitButtonContainer.current?(Gr(!0,void 0,null===(e=this.context)||void 0===e?void 0:e.registeredProviders),this._splitButtonContainer.current.focus()):this._buttonElement.current&&(Gr(!0,void 0,null===(t=this.context)||void 0===t?void 0:t.registeredProviders),this._buttonElement.current.focus())},i.prototype.dismissMenu=function(){this._dismissMenu()},i.prototype.openMenu=function(e,t){this._openMenu(e,t)},i.prototype._onRenderContent=function(t,i){var n=this,r=this.props,a=t,s=r.menuIconProps,o=r.menuProps,l=r.onRenderIcon,c=void 0===l?this._onRenderIcon:l,d=r.onRenderAriaDescription,u=void 0===d?this._onRenderAriaDescription:d,h=r.onRenderChildren,p=void 0===h?this._onRenderChildren:h,g=r.onRenderMenu,m=void 0===g?this._onRenderMenu:g,f=r.onRenderMenuIcon,v=void 0===f?this._onRenderMenuIcon:f,S=r.disabled,y=r.keytipProps;y&&o&&(y=this._getMemoizedMenuButtonKeytipProps(y));var C=function(t){return e.createElement(a,Ii({},i,t),e.createElement("span",{className:n._classNames.flexContainer,"data-automationid":"splitbuttonprimary"},c(r,n._onRenderIcon),n._onRenderTextContents(),u(r,n._onRenderAriaDescription),p(r,n._onRenderChildren),!n._isSplitButton&&(o||s||n.props.onRenderMenuIcon)&&v(n.props,n._onRenderMenuIcon),o&&!o.doNotLayer&&n._shouldRenderMenu()&&m(n._getMenuProps(o),n._onRenderMenu)))},_=y?e.createElement(lu,{keytipProps:this._isSplitButton?void 0:y,ariaDescribedBy:i["aria-describedby"],disabled:S},(function(e){return C(e)})):C();return o&&o.doNotLayer?e.createElement(e.Fragment,null,_,this._shouldRenderMenu()&&m(this._getMenuProps(o),this._onRenderMenu)):e.createElement(e.Fragment,null,_,e.createElement(Vo,null))},i.prototype._shouldRenderMenu=function(){var e=this.state.menuHidden,t=this.props,i=t.persistMenu,n=t.renderPersistedMenuHiddenOnMount;return!e||!(!i||!this._renderedVisibleMenu&&!n)},i.prototype._hasText=function(){return null!==this.props.text&&(void 0!==this.props.text||"string"==typeof this.props.children)},i.prototype._getMenuProps=function(e){var t=this.props.persistMenu,i=this.state.menuHidden;return e.ariaLabel||e.labelElementId||!this._hasText()||(e=Ii(Ii({},e),{labelElementId:this._labelId})),Ii(Ii({id:this._labelId+"-menu",directionalHint:ll.bottomLeftEdge},e),{shouldFocusOnContainer:this._menuShouldFocusOnContainer,shouldFocusOnMount:this._menuShouldFocusOnMount,hidden:t?i:void 0,className:Os("ms-BaseButton-menuhost",e.className),target:this._isSplitButton?this._splitButtonContainer.current:this._buttonElement.current,onDismiss:this._onDismissMenu})},i.prototype._onRenderSplitButtonContent=function(t,i){var n=this,r=this.props,a=r.styles,s=void 0===a?{}:a,o=r.disabled,l=r.allowDisabledFocus,c=r.checked,d=r.getSplitButtonClassNames,u=r.primaryDisabled,h=r.menuProps,p=r.toggle,g=r.role,m=r.primaryActionButtonProps,f=this.props.keytipProps,v=this.state.menuHidden,S=d?d(!!o,!v,!!c,!!l):s&&zu(s,!!o,!v,!!c,!!u);fo(i,{onClick:void 0,onPointerDown:void 0,onPointerUp:void 0,tabIndex:-1,"data-is-focusable":!1}),f&&h&&(f=this._getMemoizedMenuButtonKeytipProps(f));var y=Ds(i,[],["disabled"]);m&&fo(i,m);var C=function(r){return e.createElement("div",Ii({},y,{"data-ktp-target":r?r["data-ktp-target"]:void 0,role:g||"button","aria-disabled":o,"aria-haspopup":!0,"aria-expanded":!v,"aria-pressed":p?!!c:void 0,"aria-describedby":zo(i["aria-describedby"],r?r["aria-describedby"]:void 0),className:S&&S.splitButtonContainer,onKeyDown:n._onSplitButtonContainerKeyDown,onTouchStart:n._onTouchStart,ref:n._splitButtonContainer,"data-is-focusable":!0,onClick:o||u?void 0:n._onSplitButtonPrimaryClick,tabIndex:!o&&!u||l?0:void 0,"aria-roledescription":i["aria-roledescription"],onFocusCapture:n._onSplitContainerFocusCapture}),e.createElement("span",{style:{display:"flex",width:"100%"}},n._onRenderContent(t,i),n._onRenderSplitButtonMenuButton(S,r),n._onRenderSplitButtonDivider(S)))};return f?e.createElement(lu,{keytipProps:f,disabled:o},(function(e){return C(e)})):C()},i.prototype._onRenderSplitButtonDivider=function(t){return t&&t.divider?e.createElement("span",{className:t.divider,"aria-hidden":!0,onClick:function(e){e.stopPropagation()}}):null},i.prototype._onRenderSplitButtonMenuButton=function(t,n){var r=this.props,a=r.allowDisabledFocus,s=r.checked,o=r.disabled,l=r.splitButtonMenuProps,c=r.splitButtonAriaLabel,d=r.primaryDisabled,u=this.state.menuHidden,h=this.props.menuIconProps;void 0===h&&(h={iconName:"ChevronDown"});var p=Ii(Ii({},l),{styles:t,checked:s,disabled:o,allowDisabledFocus:a,onClick:this._onMenuClick,menuProps:void 0,iconProps:Ii(Ii({},h),{className:this._classNames.menuIcon}),ariaLabel:c,"aria-haspopup":!0,"aria-expanded":!u,"data-is-focusable":!1});return e.createElement(i,Ii({},p,{"data-ktp-execute-target":n?n["data-ktp-execute-target"]:n,onMouseDown:this._onMouseDown,tabIndex:d&&!a?0:-1}))},i.prototype._onPointerDown=function(e){var t=this.props.onPointerDown;t&&t(e),"touch"===e.pointerType&&(this._handleTouchAndPointerEvent(),e.preventDefault(),e.stopImmediatePropagation())},i.prototype._handleTouchAndPointerEvent=function(){var e=this;void 0!==this._lastTouchTimeoutId&&(this._async.clearTimeout(this._lastTouchTimeoutId),this._lastTouchTimeoutId=void 0),this._processingTouch=!0,this._lastTouchTimeoutId=this._async.setTimeout((function(){e._processingTouch=!1,e._lastTouchTimeoutId=void 0,e.state.menuHidden&&e.focus()}),500)},i.prototype._isValidMenuOpenKey=function(e){return this.props.menuTriggerKeyCode?e.which===this.props.menuTriggerKeyCode:!!this.props.menuProps&&e.which===ao.down&&(e.altKey||e.metaKey)},i.defaultProps={baseClassName:"ms-Button",styles:{},split:!1},i.contextType=No,i}(e.Component);function qu(t,i,n){return function(r){var a,s=((a=function(a){function s(e){var t=a.call(this,e)||this;return t._styleCache={},t._onSettingChanged=t._onSettingChanged.bind(t),t}return bi(s,a),s.prototype.componentDidMount=function(){sa.observe(this._onSettingChanged)},s.prototype.componentWillUnmount=function(){sa.unobserve(this._onSettingChanged)},s.prototype.render=function(){var a=this;return e.createElement(rs.Consumer,null,(function(s){var o=sa.getSettings(i,t,s.customizations),l=a.props;if(o.styles&&"function"==typeof o.styles&&(o.styles=o.styles(Ii(Ii({},o),l))),n&&o.styles){if(a._styleCache.default!==o.styles||a._styleCache.component!==l.styles){var c=Qa(o.styles,l.styles);a._styleCache.default=o.styles,a._styleCache.component=l.styles,a._styleCache.merged=c}return e.createElement(r,Ii({},o,l,{styles:a._styleCache.merged}))}return e.createElement(r,Ii({},o,l))}))},s.prototype._onSettingChanged=function(){this.forceUpdate()},s}(e.Component)).displayName="Customized"+t,a);return function(e,t){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t}(r,s)}}var Ku,Ju,Yu={outline:0},Qu=function(e){return{fontSize:e,margin:"0 4px",height:"16px",lineHeight:"16px",textAlign:"center",flexShrink:0}},Zu=vn((function(e){var t,i,n=e.semanticColors,r=e.effects,a=e.fonts,s=n.buttonBorder,o=n.disabledBackground,l=n.disabledText,c={left:-2,top:-2,bottom:-2,right:-2,outlineColor:"ButtonText"};return{root:[jr(e,{inset:1,highContrastStyle:c,borderColor:"transparent"}),e.fonts.medium,{border:"1px solid "+s,borderRadius:r.roundedCorner2,boxSizing:"border-box",cursor:"pointer",display:"inline-block",padding:"0 16px",textDecoration:"none",textAlign:"center",userSelect:"none",selectors:{":active > span":{position:"relative",left:0,top:0}}}],rootDisabled:[jr(e,{inset:1,highContrastStyle:c,borderColor:"transparent"}),{backgroundColor:o,borderColor:o,color:l,cursor:"default",selectors:{":hover":Yu,":focus":Yu}}],iconDisabled:{color:l,selectors:(t={},t[Nr]={color:"GrayText"},t)},menuIconDisabled:{color:l,selectors:(i={},i[Nr]={color:"GrayText"},i)},flexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},description:{display:"block"},textContainer:{flexGrow:1,display:"block"},icon:Qu(a.mediumPlus.fontSize),menuIcon:Qu(a.small.fontSize),label:{margin:"0 4px",lineHeight:"100%",display:"block"},screenReaderText:Wr}})),Xu=vn((function(e,t){var i,n,r,a,s,o,l,c,d,u,h,p,g,m=e.effects,f=e.palette,v=e.semanticColors,S={left:-2,top:-2,bottom:-2,right:-2,border:"none"},y={position:"absolute",width:1,right:31,top:8,bottom:8};return Qa({splitButtonContainer:[jr(e,{highContrastStyle:S,inset:2,pointerEvents:"none"}),{display:"inline-flex",selectors:{".ms-Button--default":{borderTopRightRadius:"0",borderBottomRightRadius:"0",borderRight:"none",flexGrow:"1"},".ms-Button--primary":{borderTopRightRadius:"0",borderBottomRightRadius:"0",border:"none",flexGrow:"1",selectors:(i={},i[Nr]=Ii({color:"WindowText",backgroundColor:"Window",border:"1px solid WindowText",borderRightWidth:"0"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),i[":hover"]={border:"none"},i[":active"]={border:"none"},i)},".ms-Button--primary + .ms-Button":{border:"none",selectors:(n={},n[Nr]={border:"1px solid WindowText",borderLeftWidth:"0"},n)}}}],splitButtonContainerHovered:{selectors:{".ms-Button--primary":{selectors:(r={},r[Nr]={color:"Window",backgroundColor:"Highlight"},r)},".ms-Button.is-disabled":{color:v.buttonTextDisabled,selectors:(a={},a[Nr]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},a)}}},splitButtonContainerChecked:{selectors:{".ms-Button--primary":{selectors:(s={},s[Nr]=Ii({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)}}},splitButtonContainerCheckedHovered:{selectors:{".ms-Button--primary":{selectors:(o={},o[Nr]=Ii({color:"Window",backgroundColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o)}}},splitButtonContainerFocused:{outline:"none!important"},splitButtonMenuButton:(l={padding:6,height:"auto",boxSizing:"border-box",borderRadius:0,borderTopRightRadius:m.roundedCorner2,borderBottomRightRadius:m.roundedCorner2,border:"1px solid ".concat(f.neutralSecondaryAlt),borderLeft:"none",outline:"transparent",userSelect:"none",display:"inline-block",textDecoration:"none",textAlign:"center",cursor:"pointer",verticalAlign:"top",width:32,marginLeft:-1,marginTop:0,marginRight:0,marginBottom:0},l[Nr]={".ms-Button-menuIcon":{color:"WindowText"}},l),splitButtonDivider:Ii(Ii({},y),{selectors:(c={},c[Nr]={backgroundColor:"WindowText"},c)}),splitButtonDividerDisabled:Ii(Ii({},y),{selectors:(d={},d[Nr]={backgroundColor:"GrayText"},d)}),splitButtonMenuButtonDisabled:{pointerEvents:"none",border:"none",selectors:(u={":hover":{cursor:"default"},".ms-Button--primary":{selectors:(h={},h[Nr]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},h)},".ms-Button-menuIcon":{selectors:(p={},p[Nr]={color:"GrayText"},p)}},u[Nr]={color:"GrayText",border:"1px solid GrayText",backgroundColor:"Window"},u)},splitButtonFlexContainer:{display:"flex",height:"100%",flexWrap:"nowrap",justifyContent:"center",alignItems:"center"},splitButtonContainerDisabled:{outline:"none",border:"none",selectors:(g={},g[Nr]=Ii({color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),g)},splitButtonMenuFocused:Ii({},jr(e,{highContrastStyle:S,inset:2}))},t)})),eh=vn((function(e,t){var i,n=Zu(e),r=Xu(e),a=e.palette;return Qa(n,{root:{padding:"0 4px",width:"32px",height:"32px",backgroundColor:"transparent",border:"none",color:e.semanticColors.link},rootHovered:{color:a.themeDarkAlt,backgroundColor:a.neutralLighter,selectors:(i={},i[Nr]={borderColor:"Highlight",color:"Highlight"},i)},rootHasMenu:{width:"auto"},rootPressed:{color:a.themeDark,backgroundColor:a.neutralLight},rootExpanded:{color:a.themeDark,backgroundColor:a.neutralLight},rootChecked:{color:a.themeDark,backgroundColor:a.neutralLight},rootCheckedHovered:{color:a.themeDark,backgroundColor:a.neutralQuaternaryAlt},rootDisabled:{color:a.neutralTertiaryAlt}},r,t)})),th=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(Wu,Ii({},this.props,{variantClassName:"ms-Button--icon",styles:eh(n,i),onRenderText:Ro,onRenderDescription:Ro}))},Ri([qu("IconButton",["theme","styles"],!0)],i)}(e.Component);function ih(t){var i=e.useState(t),n=i[0],r=i[1];return[n,{setTrue:qc((function(){return function(){r(!0)}})),setFalse:qc((function(){return function(){r(!1)}})),toggle:qc((function(){return function(){r((function(e){return!e}))}}))}]}!function(e){e[e.info=0]="info",e[e.error=1]="error",e[e.blocked=2]="blocked",e[e.severeWarning=3]="severeWarning",e[e.success=4]="success",e[e.warning=5]="warning"}(Ku||(Ku={}));var nh,rh,ah,sh,oh=((Ju={})[Ku.info]="Info",Ju[Ku.warning]="Info",Ju[Ku.error]="ErrorBadge",Ju[Ku.blocked]="Blocked2",Ju[Ku.severeWarning]="Warning",Ju[Ku.success]="Completed",Ju),lh=Ys(),ch=function(e){switch(e){case Ku.blocked:case Ku.error:case Ku.severeWarning:return"assertive"}return"polite"},dh=function(e){switch(e){case Ku.blocked:case Ku.error:case Ku.severeWarning:return"alert"}return"status"},uh=e.forwardRef((function(t,i){var n=ih(!1),r=n[0],a=n[1].toggle,s=fu("MessageBar"),o=t.actions,l=t.className,c=t.children,d=t.overflowButtonAriaLabel,u=t.dismissIconProps,h=t.styles,p=t.theme,g=t.messageBarType,m=void 0===g?Ku.info:g,f=t.onDismiss,v=void 0===f?void 0:f,S=t.isMultiline,y=void 0===S||S,C=t.truncated,_=t.dismissButtonAriaLabel,E=t.messageBarIconProps,T=t.role,b=t.delayedRender,I=void 0===b||b,w=t.expandButtonProps,R=t.onExpandButtonToggled,A=void 0===R?void 0:R,P=e.useCallback((function(){a(),A&&A(!r)}),[r,A,a]),M=Ds(t,ds,["className","role"]),k=lh(h,{theme:p,messageBarType:m||Ku.info,onDismiss:void 0!==v,actions:void 0!==o,truncated:C,isMultiline:y,expandSingleLine:r,className:l}),D={iconName:r?"DoubleChevronUp":"DoubleChevronDown"},O=o||v?{"aria-describedby":s,role:"region"}:{},N=o?e.createElement("div",{className:k.actions},o):null,L=v?e.createElement(th,{disabled:!1,className:k.dismissal,onClick:v,iconProps:u||{iconName:"Clear"},title:_,ariaLabel:_}):null;return e.createElement("div",Ii({ref:i,className:k.root},O),e.createElement("div",{className:k.content},e.createElement("div",{className:k.iconContainer,"aria-hidden":!0},E?e.createElement(al,Ii({},E,{className:Os(k.icon,E.className)})):e.createElement(al,{iconName:oh[m],className:k.icon})),e.createElement("div",{className:k.text,id:s,role:T||dh(m),"aria-live":ch(m)},e.createElement("span",Ii({className:k.innerText},M),I?e.createElement(Xs,null,e.createElement("span",null,c)):e.createElement("span",null,c))),!y&&!N&&C&&e.createElement("div",{className:k.expandSingleLine},e.createElement(th,Ii({disabled:!1,className:k.expand,onClick:P,iconProps:D,ariaLabel:d,"aria-expanded":r},w))),!y&&N,!y&&L&&e.createElement("div",{className:k.dismissSingleLine},L),y&&L),y&&N)}));uh.displayName="MessageBar";var hh={root:"ms-MessageBar",error:"ms-MessageBar--error",blocked:"ms-MessageBar--blocked",severeWarning:"ms-MessageBar--severeWarning",success:"ms-MessageBar--success",warning:"ms-MessageBar--warning",multiline:"ms-MessageBar-multiline",singleline:"ms-MessageBar-singleline",dismissalSingleLine:"ms-MessageBar-dismissalSingleLine",expandingSingleLine:"ms-MessageBar-expandingSingleLine",content:"ms-MessageBar-content",iconContainer:"ms-MessageBar-icon",text:"ms-MessageBar-text",innerText:"ms-MessageBar-innerText",dismissSingleLine:"ms-MessageBar-dismissSingleLine",expandSingleLine:"ms-MessageBar-expandSingleLine",dismissal:"ms-MessageBar-dismissal",expand:"ms-MessageBar-expand",actions:"ms-MessageBar-actions",actionsSingleline:"ms-MessageBar-actionsSingleLine"},ph=((nh={})[Ku.error]="errorBackground",nh[Ku.blocked]="errorBackground",nh[Ku.success]="successBackground",nh[Ku.warning]="warningBackground",nh[Ku.severeWarning]="severeWarningBackground",nh[Ku.info]="infoBackground",nh),gh=((rh={})[Ku.error]="errorIcon",rh[Ku.blocked]="errorIcon",rh[Ku.success]="successIcon",rh[Ku.warning]="warningIcon",rh[Ku.severeWarning]="severeWarningIcon",rh[Ku.info]="infoIcon",rh),mh=((ah={})[Ku.error]="#ff0000",ah[Ku.blocked]="#ff0000",ah[Ku.success]="#bad80a",ah[Ku.warning]="#fff100",ah[Ku.severeWarning]="#ff0000",ah[Ku.info]="WindowText",ah),fh=((sh={})[Ku.error]="#e81123",sh[Ku.blocked]="#e81123",sh[Ku.success]="#107c10",sh[Ku.warning]="#966400",sh[Ku.severeWarning]="#d83b01",sh[Ku.info]="WindowText",sh),vh=Ws(uh,(function(e){var t,i,n,r,a,s,o,l,c,d,u,h=e.theme,p=e.className,g=e.onDismiss,m=e.truncated,f=e.isMultiline,v=e.expandSingleLine,S=e.messageBarType,y=void 0===S?Ku.info:S,C=h.semanticColors,_=h.fonts,E=Ur(0,479),T=Kr(hh,h),b={fontSize:kr.xSmall,height:10,lineHeight:"10px",color:C.messageText,selectors:(t={},t[Nr]=Ii(Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),t)},I=[jr(h,{inset:1,highContrastStyle:{outlineOffset:"-6px",outline:"1px solid Highlight"},borderColor:"transparent"}),{flexShrink:0,width:32,height:32,padding:"8px 12px",selectors:{"& .ms-Button-icon":b,":hover":{backgroundColor:"transparent"},":active":{backgroundColor:"transparent"}}}];return{root:[T.root,_.medium,y===Ku.error&&T.error,y===Ku.blocked&&T.blocked,y===Ku.severeWarning&&T.severeWarning,y===Ku.success&&T.success,y===Ku.warning&&T.warning,f?T.multiline:T.singleline,!f&&g&&T.dismissalSingleLine,!f&&m&&T.expandingSingleLine,{background:C[ph[y]],boxSizing:"border-box",color:C.messageText,minHeight:32,width:"100%",display:"flex",wordBreak:"break-word",selectors:(i={".ms-Link":{color:C.messageLink,selectors:{":hover":{color:C.messageLinkHovered}}}},i[Nr]=Ii(Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{background:"transparent",border:"1px solid ".concat(mh[y]),color:"WindowText"}),i[Lr]={border:"1px solid ".concat(fh[y])},i)},f&&{flexDirection:"column"},p],content:[T.content,(n={display:"flex",width:"100%",lineHeight:"normal"},n[E]={display:"grid",gridTemplateColumns:"auto 1fr auto",gridTemplateRows:"1fr auto",gridTemplateAreas:'\n            "icon text close"\n            "action action action"\n          '},n)],iconContainer:[T.iconContainer,(r={fontSize:kr.medium,minWidth:16,minHeight:16,display:"flex",flexShrink:0,margin:"8px 0 8px 12px"},r[E]={gridArea:"icon"},r)],icon:{color:C[gh[y]],selectors:(a={},a[Nr]=Ii(Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText"}),a)},text:[T.text,Ii(Ii({minWidth:0,display:"flex",flexGrow:1,margin:8},_.small),(s={},s[E]={gridArea:"text"},s.selectors=(o={},o[Nr]=Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o),s)),!g&&{marginRight:12}],innerText:[T.innerText,{lineHeight:16,selectors:{"& span a:last-child":{paddingLeft:4}}},m&&{overflow:"visible",whiteSpace:"pre-wrap"},!f&&{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},!f&&!m&&{selectors:(l={},l[E]={overflow:"visible",whiteSpace:"pre-wrap"},l)},v&&{overflow:"visible",whiteSpace:"pre-wrap"}],dismissSingleLine:[T.dismissSingleLine,(c={},c[E]={gridArea:"close"},c)],expandSingleLine:T.expandSingleLine,dismissal:[T.dismissal,I],expand:[T.expand,I],actions:[f?T.actions:T.actionsSingleline,(d={display:"flex",flexGrow:0,flexShrink:0,flexBasis:"auto",flexDirection:"row-reverse",alignItems:"center",margin:"0 12px 0 8px",forcedColorAdjust:"auto",MsHighContrastAdjust:"auto"},d[E]={gridArea:"action",marginRight:8,marginBottom:8},d.selectors={"& button:nth-child(n+2)":(u={marginLeft:8},u[E]={marginBottom:0},u)},d),f&&{marginBottom:8},g&&!f&&{marginRight:0}]}}),void 0,{scope:"MessageBar"});const Sh={strings:JSON.parse('{"participantItem":{"isMeText":"(you)","menuTitle":"More Options","removeButtonLabel":"Remove","sharingIconLabel":"Sharing","mutedIconLabel":"Muted","displayNamePlaceholder":"Unnamed participant","participantStateRinging":"Calling...","participantStateHold":"On hold","attendeeRole":"Attendee"},"ParticipantList":{"overflowParticipantCount":"+{overflowCount} more"},"typingIndicator":{"singleUser":"{user} is typing ...","multipleUsers":"{users} are typing ...","multipleUsersAbbreviateOne":"{users} and 1 other are typing ...","multipleUsersAbbreviateMany":"{users} and {numOthers} others are typing ...","delimiter":", "},"sendBox":{"placeholderText":"Enter a message","textTooLong":"Your message length is over the maximum limit.","sendButtonAriaLabel":"Send message","attachmentUploadsPendingError":"Uploading... Please wait.","removeAttachment":"Remove file","uploading":"Uploading","uploadCompleted":"Upload completed","attachmentMoreMenu":"More Options"},"richTextSendBox":{"placeholderText":"Enter a message","textTooLong":"Your message length is over the maximum limit.","sendButtonAriaLabel":"Send message","attachmentUploadsPendingError":"Uploading... Please wait.","removeAttachment":"Remove file","uploading":"Uploading","uploadCompleted":"Upload completed","boldTooltip":"Bold","italicTooltip":"Italic","underlineTooltip":"Underline","bulletListTooltip":"Bulleted list","numberListTooltip":"Numbered list","increaseIndentTooltip":"Increase indent","decreaseIndentTooltip":"Decrease indent","insertTableTooltip":"Insert table","richTextFormatButtonTooltip":"Format","insertRowOrColumnMenu":"Insert","insertTableMenuTitle":"Insert {column} x {row} table","insertRowAboveMenu":"Insert above","insertRowBelowMenu":"Insert below","insertColumnLeftMenu":"Insert left","insertColumnRightMenu":"Insert right","deleteRowOrColumnMenu":"Delete","deleteColumnMenu":"Delete column","deleteRowMenu":"Delete row","deleteTableMenu":"Delete table","attachmentMoreMenu":"More Options"},"mentionPopover":{"mentionPopoverHeader":"Suggestions"},"imageOverlay":{"downloadButtonLabel":"Download","dismissButtonAriaLabel":"Close"},"messageStatusIndicator":{"deliveredAriaLabel":"Message sent","deliveredTooltipText":"Sent","seenAriaLabel":"Message seen by others","seenTooltipText":"Seen","readByTooltipText":"Read by {messageThreadReadCount} of {remoteParticipantsCount}","sendingAriaLabel":"Message sending","sendingTooltipText":"Sending","failedToSendAriaLabel":"Message failed to send","failedToSendTooltipText":"Failed to send"},"endCallButton":{"label":"Leave","tooltipContent":"Leave call","leaveOption":"Leave","endCallOption":"End call for everyone"},"cameraButton":{"onLabel":"Camera","offLabel":"Camera","tooltipDisabledContent":"Camera is disabled","tooltipOnContent":"Turn off camera","tooltipOffContent":"Turn on camera","tooltipVideoLoadingContent":"Video is loading","cameraMenuTitle":"Camera","cameraMenuTooltip":"Choose camera","cameraButtonSplitRoleDescription":"Split button","onSplitButtonAriaLabel":"Turn off camera and camera options","offSplitButtonAriaLabel":"Turn on camera and camera options","cameraActionTurnedOnAnnouncement":"Your camera has been turned on","cameraActionTurnedOffAnnouncement":"Your camera has been turned off","onSplitButtonPrimaryActionCamera":"Turn off camera","offSplitButtonPrimaryActionCamera":"Turn on camera","cameraPrimaryActionSplitButtonTitle":"Use camera","videoEffectsMenuItemTitle":"Effects"},"microphoneButton":{"onLabel":"Mic","offLabel":"Mic","tooltipDisabledContent":"Microphone is disabled","tooltipOnContent":"Mute microphone","tooltipOffContent":"Unmute microphone","microphoneMenuTitle":"Microphone","microphoneMenuTooltip":"Choose microphone","speakerMenuTitle":"Speaker","speakerMenuTooltip":"Choose speaker","microphoneButtonSplitRoleDescription":"Split button","onSplitButtonAriaLabel":"Mute microphone and audio options","offSplitButtonAriaLabel":"Unmute microphone and audio options","microphoneActionTurnedOnAnnouncement":"Your microphone has been turned on","microphoneActionTurnedOffAnnouncement":"Your microphone has been turned off","offSplitButtonMicrophonePrimaryAction":"Unmute microphone","onSplitButtonMicrophonePrimaryAction":"Mute microphone","microphonePrimaryActionSplitButtonTitle":"Use microphone"},"devicesButton":{"label":"Devices","tooltipContent":"Manage devices","cameraMenuTitle":"Camera","cameraMenuTooltip":"Choose camera","audioDeviceMenuTitle":"Audio Device","audioDeviceMenuTooltip":"Choose audio device","microphoneMenuTitle":"Microphone","microphoneMenuTooltip":"Choose microphone","speakerMenuTitle":"Speaker","speakerMenuTooltip":"Choose speaker"},"participantsButton":{"label":"People","tooltipContent":"Show participants","menuHeader":"In this call","participantsListButtonLabel":"{numParticipants} people","muteAllButtonLabel":"Mute all","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkActionedAriaLabel":"Invite link copied"},"screenShareButton":{"onLabel":"Stop presenting","offLabel":"Present","tooltipDisabledContent":"Presenting is disabled","tooltipOnContent":"Presenting your screen","tooltipOffContent":"Present your screen"},"raiseHandButton":{"offLabel":"Raise","onLabel":"Lower","tooltipDisabledContent":"Raise Hand action is disabled","tooltipOnContent":"Lower Hand","tooltipOffContent":"Raise Hand"},"reactionButton":{"label":"React","ariaLabel":"React Button, Send a reaction","tooltipDisabledContent":"Reaction action is disabled","tooltipContent":"Send a reaction","likeReactionTooltipContent":"Like","heartReactionTooltipContent":"Love","laughReactionTooltipContent":"Laugh","applauseReactionTooltipContent":"Applause","surprisedReactionTooltipContent":"Surprised"},"messageThread":{"yesterday":"Yesterday","sunday":"Sunday","monday":"Monday","tuesday":"Tuesday","wednesday":"Wednesday","thursday":"Thursday","friday":"Friday","saturday":"Saturday","participantJoined":"joined the chat.","participantLeft":"left the chat.","editMessage":"Edit","removeMessage":"Delete","resendMessage":"Try sending again","failToSendTag":"Failed to send","editedTag":"Edited","liveAuthorIntro":"{author} says","messageContentAriaText":"{author} said {message}","messageContentMineAriaText":"You said {message}","editBoxTextLimit":"Your message is over the limit of {limitNumber} characters","editBoxPlaceholderText":"Edit your message","newMessagesIndicator":"New messages","noDisplayNameSub":"No name","editBoxCancelButton":"Cancel","editBoxSubmitButton":"Done","messageReadCount":"Read by {messageReadByCount} of {remoteParticipantsCount}","actionMenuMoreOptions":"More Options","downloadAttachment":"Download file","openAttachment":"Open file","blockedWarningText":"This message was deleted due to organizational policy.","blockedWarningLinkText":"Details","attachmentCardGroupMessage":"The message has {attachmentCount} attachment","messageDeletedAnnouncementAriaLabel":"The message is deleted"},"errorBar":{"unableToReachChatService":"You are offline","accessDenied":"Unable to access chat services - please check the user credentials provided","userNotInChatThread":"You are no longer in this chat thread","sendMessageNotInChatThread":"Failed to send message because you are no longer in this chat thread","sendMessageGeneric":"Failed to send message","callingNetworkFailure":"Troubling connecting call - you seem to be offline","startVideoGeneric":"Failed to start video","stopVideoGeneric":"Failed to stop video","muteGeneric":"Failed to mute microphone","unmuteGeneric":"Failed to unmute microphone","speakingWhileMuted":"Your microphone is muted","startScreenShareGeneric":"There was an issue starting screen share.","stopScreenShareGeneric":"Failed to stop screen sharing","callNetworkQualityLow":"Network quality is low.","callNoSpeakerFound":"No speakers or headphones found. Connect an audio device to hear the call.","callNoMicrophoneFound":"No microphones found. Connect an audio input device.","callMicrophoneAccessDenied":"Unable to access microphone. Click the lock in the address bar to grant permission to this webpage.","callMicrophoneAccessDeniedSafari":"Unable to access microphone. Refresh the page to allow permissions, or check this browser’s settings and verify permissions are enabled for this website.","callMicrophoneMutedBySystem":"You are muted by your system.","callMicrophoneUnmutedBySystem":"Your microphone recovered and you were unmuted by your system.","callMacOsMicrophoneAccessDenied":"Unable to access microphone. Grant microphone permission in your macOS privacy settings.","callLocalVideoFreeze":"Network bandwidth is poor. Your video may appear paused for others on the call.","callCameraAccessDenied":"Unable to access camera. Click the lock in the address bar to grant permission to this webpage.","callCameraAccessDeniedSafari":"Unable to access camera. Refresh the page to allow permissions, or check this browser’s settings and verify permissions are enabled for this website.","callCameraAlreadyInUse":"Unable to access camera. It may already be in use by another application.","callVideoStoppedBySystem":"Your video has been stopped by your system.","callVideoRecoveredBySystem":"Your video has resumed.","callMacOsCameraAccessDenied":"MacOS is blocking access to your camera. Update your privacy settings to allow this browser to access your camera.","callMacOsScreenShareAccessDenied":"MacOS is blocking screen sharing. Update your privacy settings to allow this browser to record your screen.","dismissButtonAriaLabel":"Close","failedToJoinCallGeneric":"Failed to join call.","failedToJoinCallInvalidMeetingLink":"Unable to join Meeting. Invalid Link.","cameraFrozenForRemoteParticipants":"Users in the call are having issues seeing your video. Please check your devices and network.","unableToStartVideoEffect":"Unable to apply video effect.","startSpotlightWhileMaxParticipantsAreSpotlighted":"Cannot start spotlight on participant(s) because the maximum number of participants are already spotlighted."},"videoGallery":{"screenIsBeingSharedMessage":"You are sharing your screen","screenShareLoadingMessage":"Loading {participant}\'s screen","localVideoLabel":"You","localVideoCameraSwitcherLabel":"Switch camera","localVideoMovementLabel":"Movable Local Video Tile","localVideoSelectedDescription":"{cameraName} selected","displayNamePlaceholder":"Unnamed participant","fitRemoteParticipantToFrame":"Fit to frame","fillRemoteParticipantFrame":"Fill frame","pinParticipantForMe":"Pin for me","pinParticipantForMeLimitReached":"Pin (limit reached)","unpinParticipantForMe":"Unpin","pinParticipantMenuItemAriaLabel":"Pin {participantName}","unpinParticipantMenuItemAriaLabel":"Unpin {participantName}","pinnedParticipantAnnouncementAriaLabel":"Pinned {participantName}","unpinnedParticipantAnnouncementAriaLabel":"Unpinned {participantName}","startSpotlightVideoTileMenuLabel":"Spotlight for everyone","addSpotlightVideoTileMenuLabel":"Add spotlight","spotlightLimitReachedMenuTitle":"Spotlight limit reached","stopSpotlightVideoTileMenuLabel":"Stop spotlighting","stopSpotlightOnSelfVideoTileMenuLabel":"Exit spotlight","attendeeRole":"Attendee"},"dialpad":{"placeholderText":"Enter phone number","deleteButtonAriaLabel":"Delete"},"holdButton":{"onLabel":"Resume","offLabel":"Hold","tooltipOnContent":"Resume call","tooltipOffContent":"Hold call"},"videoTile":{"participantStateRinging":"Calling...","participantStateHold":"On hold"},"CameraAndMicrophoneSitePermissionsRequest":{"primaryText":"Allow {appName} to use your camera and microphone","secondaryText":"This is so participants can see and hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera and microphone","ariaLabel":"Allow camera and microphone access"},"CameraSitePermissionsRequest":{"primaryText":"Allow {appName} to use your camera","secondaryText":"This is so participants can see you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera","ariaLabel":"Allow camera access"},"MicrophoneSitePermissionsRequest":{"primaryText":"Allow {appName} to use your microphone","secondaryText":"This is so participants can hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without microphone","ariaLabel":"Allow microphone access"},"CameraAndMicrophoneSitePermissionsCheck":{"primaryText":"Checking for camera and microphone access","secondaryText":"Allow access if prompted. This is so participants can see and hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera and microphone","ariaLabel":"Checking for camera and microphone access. Allow access if prompted."},"CameraSitePermissionsCheck":{"primaryText":"Checking for camera access","secondaryText":"Allow access if prompted. This is so participants can see you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without camera","ariaLabel":"Checking for camera access. Allow access if prompted."},"MicrophoneSitePermissionsCheck":{"primaryText":"Checking for microphone access","secondaryText":"Allow access if prompted. This is so participants can hear you.","linkText":"Need help? Get troubleshooting help","primaryButtonText":"Continue without microphone","ariaLabel":"Checking for microphone access. Allow access if prompted."},"CameraAndMicrophoneSitePermissionsDenied":{"primaryText":"Unable to access camera and microphone","secondaryText":"Click the lock icon in the address bar to grant microphone permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without camera and microphone","linkText":"Need help? Get troubleshooting help"},"CameraAndMicrophoneSitePermissionsDeniedSafari":{"primaryText":"Unable to access camera and microphone","secondaryText":"Refresh the page to allow permissions, or check this browser’s settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without camera and microphone","linkText":"Need help? Get troubleshooting help"},"CameraSitePermissionsDenied":{"primaryText":"Unable to access camera","secondaryText":"Click the lock icon in the address bar to grant camera permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without camera","linkText":"Need help? Get troubleshooting help"},"MicrophoneSitePermissionsDenied":{"primaryText":"Unable to access microphone","secondaryText":"Click the lock icon in the address bar to grant microphone permissions to this webpage. A page refresh may be required.","primaryButtonText":"Continue without microphone","linkText":"Need help? Get troubleshooting help"},"CameraSitePermissionsDeniedSafari":{"primaryText":"Unable to access camera","secondaryText":"Refresh the page to allow permissions, or check this browser’s settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without camera","linkText":"Need help? Get troubleshooting help"},"MicrophoneSitePermissionsDeniedSafari":{"primaryText":"Unable to access microphone","secondaryText":"Refresh the page to allow permissions, or check this browser’s settings and verify permissions are enabled for this website.","primaryButtonText":"Continue without microphone","linkText":"Need help? Get troubleshooting help"},"UnsupportedBrowser":{"primaryText":"Browser not supported","secondaryText":"Please join this call using a compatible browser.","moreHelpLinkText":"See compatibility requirements"},"UnsupportedBrowserVersion":{"primaryText":"Browser update needed","secondaryText":"To ensure the best call possible, please update your browser and then try joining the call again.","moreHelpLinkText":"See compatibility requirements","continueAnywayButtonText":"Start call without updating"},"UnsupportedOperatingSystem":{"primaryText":"Operating system not supported","secondaryText":"Please join this call using a device with a compatible operating system.","moreHelpLinkText":"See compatibility requirements"},"BrowserPermissionDenied":{"primaryText":"Can\'t use your camera or microphone","secondaryText":"Your browser might not have access to your camera or microphone. To fix this, open System Preferences.","primaryButtonText":"Try again","linkText":"Need help? Get troubleshooting help"},"BrowserPermissionDeniedIOS":{"primaryText":"Allow microphone access to continue","secondaryText":"So other participants can hear you.","primaryButtonText":"Try again","imageAltText":"Microphone and camera device permission location for iOS","linkText":"Need help? Get troubleshooting help","step1Text":"Go to the Settings app","step2Text":"Scroll down to settings for this browser","step3Text":"Turn on Microphone (Camera optional)","step4Text":"Try joining the call again","step1DigitText":"1","step2DigitText":"2","step3DigitText":"3","step4DigitText":"4"},"verticalGallery":{"leftNavButtonAriaLabel":"previous page","rightNavButtonAriaLabel":"next page"}}')},yh=(0,e.createContext)(Sh),Ch=t=>{const{locale:i,children:n}=t;return e.createElement(yh.Provider,{value:i},n)},_h=()=>(0,e.useContext)(yh),Eh=(e,t)=>{var i;const n=new Date(Date.now());for(const i of e)if(i.type===t.type)return i.dismissedAt=n,i.activeSince=t.timestamp,Array.from(e);const r=null!==(i=t.timestamp)&&void 0!==i?i:n;return[...e,{type:t.type,dismissedAt:n>r?n:r,activeSince:t.timestamp}]},Th=(e,t)=>{const i=new Map;for(const t of e)i.set(t.type,t);const n=e=>void 0===e.activeSince&&void 0===i.get(e.type);return t.some((e=>n(e)))?t.filter((e=>!n(e))):t},bh=(e,t,i)=>{const n=new Map;for(const e of t)n.set(e.type,e);return e.filter((e=>{if(i&&e.timestamp&&i>e.timestamp)return!1;const t=n.get(e.type);return!t||!!e.timestamp&&e.timestamp>t.dismissedAt}))},Ih=e=>{switch(e){case"callNetworkQualityLow":case"callNoSpeakerFound":case"callNoMicrophoneFound":case"callMicrophoneAccessDenied":case"callMicrophoneAccessDeniedSafari":case"callMicrophoneMutedBySystem":case"callMicrophoneUnmutedBySystem":case"callMacOsMicrophoneAccessDenied":case"callLocalVideoFreeze":case"callCameraAccessDenied":case"callCameraAccessDeniedSafari":case"callCameraAlreadyInUse":case"callVideoStoppedBySystem":case"callVideoRecoveredBySystem":case"callMacOsCameraAccessDenied":case"callMacOsScreenShareAccessDenied":case"startScreenShareGeneric":case"cameraFrozenForRemoteParticipants":return Ku.warning;default:return Ku.error}},wh=e=>{const t=Rh[e];return t?{iconName:t}:void 0},Rh={callNetworkQualityLow:"ErrorBarCallNetworkQualityLow",callNoSpeakerFound:"ErrorBarCallNoSpeakerFound",callNoMicrophoneFound:"ErrorBarCallNoMicrophoneFound",callMicrophoneAccessDenied:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneAccessDeniedSafari:"ErrorBarCallMicrophoneAccessDenied",callMicrophoneMutedBySystem:"ErrorBarCallMicrophoneMutedBySystem",callMicrophoneUnmutedBySystem:"ErrorBarCallMicrophoneUnmutedBySystem",callMacOsMicrophoneAccessDenied:"ErrorBarCallMacOsMicrophoneAccessDenied",callLocalVideoFreeze:"ErrorBarCallLocalVideoFreeze",callCameraAccessDenied:"ErrorBarCallCameraAccessDenied",callCameraAccessDeniedSafari:"ErrorBarCallCameraAccessDenied",callCameraAlreadyInUse:"ErrorBarCallCameraAlreadyInUse",callVideoStoppedBySystem:"ErrorBarCallVideoStoppedBySystem",callVideoRecoveredBySystem:"ErrorBarCallVideoRecoveredBySystem",callMacOsCameraAccessDenied:"ErrorBarCallMacOsCameraAccessDenied"},Ah=e=>!!e&&e.length>0,Ph="en-us",Mh=t=>{var i;const n=_h().strings.errorBar,r=null!==(i=t.strings)&&void 0!==i?i:n,a=!t.onDismissError,s=(0,e.useRef)(new Date(Date.now())),[o,l]=(0,e.useState)([]);(0,e.useEffect)((()=>{a&&l(Th(t.activeErrorMessages,o))}),[t.activeErrorMessages,o,a]);const c=bh(t.activeErrorMessages,o,t.ignorePremountErrors?s.current:void 0);return e.createElement(Gs,{"data-ui-id":"error-bar-stack"},c.map((i=>e.createElement(vh,Object.assign({},t,{styles:{innerText:{alignSelf:"center"},icon:{height:0},content:{lineHeight:"inherit"},dismissal:{height:0,paddingTop:"0.8rem"}},key:i.type,messageBarType:Ih(i.type),messageBarIconProps:wh(i.type),onDismiss:()=>{var e;return a?l(Eh(o,i)):null===(e=t.onDismissError)||void 0===e?void 0:e.call(t,i)},dismissButtonAriaLabel:r.dismissButtonAriaLabel,dismissIconProps:{iconName:"ErrorBarClear"}}),r[i.type]))))};var kh,Dh,Oh,Nh,Lh=e.createContext(void 0),xh=function(){var t=(0,e.useContext)(Lh),i=js(["theme"]).theme;return t||i||Oa({})},Fh=0,Uh=function(){return Fh},Bh=function(e,t){return es(Array.isArray(e)?e:[e],t)},Vh=(kh=function(e){var t=e.semanticColors,i=e.fonts;return{body:[{color:t.bodyText,background:t.bodyBackground,fontFamily:i.medium.fontFamily,fontWeight:i.medium.fontWeight,fontSize:i.medium.fontSize,MozOsxFontSmoothing:i.medium.MozOsxFontSmoothing,WebkitFontSmoothing:i.medium.WebkitFontSmoothing}]}},Dh=new Map,Oh=new Set,Nh=function(e){var t=e.currentTarget,i=t.__id__;Dh.delete(i),t.removeEventListener("unload",Nh),Oh.delete(i)},function(t){void 0===t&&(t={});var i,n=t.theme,r=Gc();r&&(r.__id__=r.__id__||bo(),i=r.__id__,Oh.has(i)||(Oh.add(i),r.addEventListener("unload",Nh)));var a=xh();n=n||a;var s=Uh(),o=[i,s,n],l=function(e,t){var i,n,r,a=t[0],s=t[1],o=t[2];return null===(r=null===(n=null===(i=e.get(a))||void 0===i?void 0:i.get(s))||void 0===n?void 0:n.get(o))||void 0===r?void 0:r.classMap}(Dh,o);if((0,e.useEffect)((function(){return function(e,t){var i,n,r=t[0],a=t[1],s=t[2],o=null===(n=null===(i=e.get(r))||void 0===i?void 0:i.get(a))||void 0===n?void 0:n.get(s);o&&o.refCount++}(Dh,[i,s,n]),function(){return function(e,t){var i,n,r,a,s,o,l,c,d=t[0],u=t[1],h=t[2],p=null===(n=null===(i=e.get(d))||void 0===i?void 0:i.get(u))||void 0===n?void 0:n.get(h);p&&(p.refCount--,0===p.refCount&&(null===(a=null===(r=e.get(d))||void 0===r?void 0:r.get(u))||void 0===a||a.delete(h),0===(null===(o=null===(s=e.get(d))||void 0===s?void 0:s.get(u))||void 0===o?void 0:o.size)&&(null===(l=e.get(d))||void 0===l||l.delete(u),0===(null===(c=e.get(d))||void 0===c?void 0:c.size)&&e.delete(d))))}(Dh,[i,s,n])}}),[i,s,n]),!l){var c=function(e){return"function"==typeof e}(kh)?kh(n):kh;l=Bh(c,{targetWindow:r,rtl:!!n.rtl}),function(e,t,i){var n,r,a=t[0],s=t[1],o=t[2],l=null!==(n=e.get(a))&&void 0!==n?n:new Map;e.set(a,l);var c=null!==(r=l.get(s))&&void 0!==r?r:new Map;l.set(s,c),c.set(o,{classMap:i,refCount:0})}(Dh,o,l)}return l});var Hh={label:us,audio:hs,video:ps,ol:gs,li:ms,a:fs,button:vs,input:Ss,textarea:ys,select:Cs,option:_s,table:Es,tr:Ts,th:bs,td:Is,colGroup:ws,col:Rs,form:As,iframe:Ps,img:Ms},$h=function(t){var i,n=t.customizerContext,r=t.ref,a=t.theme,s=t.as||"div",o="string"==typeof t.as?Ds(t,(i=t.as)&&Hh[i]||ds,undefined):t.as===e.Fragment?{children:t.children}:function(e,t){var i={};for(var n in e)-1===t.indexOf(n)&&e.hasOwnProperty(n)&&(i[n]=e[n]);return i}(t,["as"]);return e.createElement(Lh.Provider,{value:a},e.createElement(rs.Provider,{value:n},e.createElement(md,{providerRef:r},e.createElement(s,Ii({},o)))))},Gh=new Map,jh=e.forwardRef((function(t,i){var n=function(t,i){var n,r,a,s,o=Xl(i,t);return r=(n=o).theme,a=xh(),s=n.theme=e.useMemo((function(){var e=ka(a,r);return e.id=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var i=[],n=0,r=e;n<r.length;n++){var a=r[n];if(a){var s=a.id||Gh.get(a);s||(s=bo(""),Gh.set(a,s)),i.push(s)}}return i.join("-")}(a,r),e}),[a,r]),n.customizerContext=e.useMemo((function(){return{customizations:{inCustomizerContext:!0,settings:{theme:s},scopedSettings:s.components||{}}}}),[s]),n.theme.rtl!==a.rtl&&(n.dir=n.theme.rtl?"rtl":"ltr"),{state:o,render:$h}}(t,{ref:qo(i,e.useRef(null)),as:"div",applyTo:"element"}),r=n.render,a=n.state;return function(t){var i=Vh(t),n=t.className,r=t.applyTo;!function(t,i){var n,r="body"===t.applyTo,a=null===(n=jc())||void 0===n?void 0:n.body;e.useEffect((function(){if(r&&a){for(var e=0,t=i;e<t.length;e++){var n=t[e];n&&a.classList.add(n)}return function(){if(r&&a)for(var e=0,t=i;e<t.length;e++){var n=t[e];n&&a.classList.remove(n)}}}}),[r,a,i])}(t,[i.root,i.body]),t.className=Os(n,i.root,"element"===r&&i.body)}(a),r(a)}));jh.displayName="ThemeProvider";const zh={palette:{themePrimary:"#0078d4",themeLighterAlt:"#eff6fc",themeLighter:"#deecf9",themeLight:"#c7e0f4",themeTertiary:"#71afe5",themeSecondary:"#2b88d8",themeDarkAlt:"#106ebe",themeDark:"#59b0f7",themeDarker:"#004578",neutralLighterAlt:"#faf9f8",neutralLighter:"#f3f2f1",neutralLight:"#edebe9",neutralQuaternaryAlt:"#e1dfdd",neutralQuaternary:"#d0d0d0",neutralTertiaryAlt:"#c8c6c4",neutralTertiary:"#a19f9d",neutralSecondary:"#605e5c",neutralPrimaryAlt:"#3b3a39",neutralPrimary:"#323130",neutralDark:"#201f1e",black:"#000000",white:"#ffffff",whiteTranslucent40:"rgba(255, 255, 255, 0.4)"},callingPalette:{callRed:"#a42e43",callRedDark:"#8b2c3d",callRedDarker:"#772a38",iconWhite:"#ffffff",raiseHandGold:"#eaa300",videoTileLabelBackgroundLight:"rgba(255,255,255,0.8)"},semanticColors:{errorText:"#a80000"}},Wh={palette:{themePrimary:"#2899f5",themeLighterAlt:"#02060a",themeLighter:"#061827",themeLight:"#0c2e49",themeTertiary:"#185b93",themeSecondary:"#2286d7",themeDarkAlt:"#3ca2f6",themeDark:"#59b0f7",themeDarker:"#84c5f9",neutralLighterAlt:"#302e2d",neutralLighter:"#383735",neutralLight:"#464443",neutralQuaternaryAlt:"#4e4d4b",neutralQuaternary:"#4d4b49",neutralTertiaryAlt:"#72706e",neutralTertiary:"#c8c8c8",neutralSecondary:"#d0d0d0",neutralPrimaryAlt:"#dadada",neutralPrimary:"#ffffff",neutralDark:"#f4f4f4",black:"#f8f8f8",white:"#252423",whiteTranslucent40:"rgba(0, 0, 0, 0.4)"},callingPalette:{callRed:"#c4314b",callRedDark:"#a42e43",callRedDarker:"#8b2c3d",iconWhite:"#ffffff",raiseHandGold:"#eaa300",videoTileLabelBackgroundLight:"rgba(37,36,35,0.8)"},semanticColors:{errorText:"#f1707b"}},qh=(Object.assign(Object.assign({},Wh.semanticColors),{bodyBackground:"rgba(0, 0, 0, 0.85)"}),cn({height:"100%",width:"100%",overflow:"auto","*":{boxSizing:"border-box"},"*:before":{boxSizing:"border-box"},"*:after":{boxSizing:"border-box"},"[hidden]":{display:"none!important"}})),Kh=Object.assign({},ka(Ua(),zh)),Jh=(0,e.createContext)(Kh),Yh=t=>{const{fluentTheme:i,rtl:n,children:r,rootStyle:a}=t,s=(0,e.useMemo)((()=>{const e=ka(Kh,i);return ka(e,{rtl:n})}),[i,n]);return e.createElement(Jh.Provider,{value:s},e.createElement(jh,{theme:s,className:qh,style:a},r))},Qh=()=>(0,e.useContext)(Jh);var Zh=function(t){var i=e.useRef(t);i.current=t,e.useEffect((function(){return function(){var e;null===(e=i.current)||void 0===e||e.call(i)}}),[])},Xh=function(t){var i=t.className,n=e.useState((function(){return bo()}))[0],r=t.id,a=void 0===r?n:r,s=e.useRef({hostId:a,rootRef:e.useRef(null),notifyLayersChanged:function(){}});return e.useImperativeHandle(t.componentRef,(function(){return s.current})),e.useEffect((function(){!function(e,t){(wd[e]||(wd[e]=[])).unshift(t)}(a,s.current),Pd(a)}),[]),Zh((function(){!function(e,t){var i=wd[e];if(i){var n=i.indexOf(t);n>=0&&i.splice(n,1),0===i.length&&delete wd[e]}}(a,s.current),Pd(a)})),e.createElement("div",Ii({},t,{className:Os("ms-LayerHost",i),ref:s.current.rootRef}))};const ep={component:Sh,strings:JSON.parse('{"call":{"cameraLabel":"Camera","noCamerasLabel":"No cameras found","cameraPermissionDenied":"Your browser is blocking access to your camera","cameraTurnedOff":"Your camera is turned off","chatButtonLabel":"Chat","close":"Close","complianceBannerNowOnlyRecording":"You are now only recording this meeting.","complianceBannerNowOnlyTranscription":"You are now only transcribing this meeting.","complianceBannerRecordingAndTranscriptionSaved":"Recording and transcription are being saved.","complianceBannerRecordingAndTranscriptionStarted":"Recording and transcription have started.","complianceBannerRecordingAndTranscriptionStopped":"Recording and transcription have stopped.","complianceBannerRecordingSaving":"Recording is being saved.","complianceBannerRecordingStarted":"Recording has started.","complianceBannerRecordingStopped":"Recording has stopped.","complianceBannerTranscriptionStarted":"Transcription has started.","complianceBannerTranscriptionConsent":"By joining, you are giving consent for this meeting to be transcribed.","complianceBannerTranscriptionSaving":"Transcription is being saved.","complianceBannerTranscriptionStopped":"Transcription has stopped.","configurationPageTitle":"Start a call","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkActionedAriaLabel":"Invite link copied","defaultPlaceHolder":"Select an option","dismissSidePaneButtonLabel":"Close","videoEffectsPaneTitle":"Effects","videoEffectsPaneBackgroundSelectionTitle":"Background","configurationPageVideoEffectsButtonLabel":"Effects","unableToStartVideoEffect":"Unable to apply video effect.","blurBackgroundEffectButtonLabel":"Blur","blurBackgroundTooltip":"Blur Background","removeBackgroundEffectButtonLabel":"None","removeBackgroundTooltip":"Remove Background","cameraOffBackgroundEffectWarningText":"Your camera is off. Turn on camera to see video effect.","failedToJoinCallDueToNoNetworkMoreDetails":"Call was disconnected due to a network issue. Check your connection and join again.","failedToJoinCallDueToNoNetworkTitle":"Call disconnected","failedToJoinTeamsMeetingReasonAccessDeniedMoreDetails":"You were not granted entry in the call. If this was a mistake, re-join the call.","failedToJoinTeamsMeetingReasonAccessDeniedTitle":"Dismissed from lobby","learnMore":"Learn more","leavingCallTitle":"Leaving...","leftCallMoreDetails":"If this was a mistake, re-join the call.","leftCallTitle":"You left the call","lobbyScreenConnectingToCallTitle":"Joining call","lobbyScreenWaitingToBeAdmittedTitle":"Waiting to be admitted","microphonePermissionDenied":"Your browser is blocking access to your microphone","microphoneToggleInLobbyNotAllowed":"Cannot mute or unmute while in lobby.","mutedMessage":"You\'re muted","networkReconnectMoreDetails":"Looks like something went wrong. We\'re trying to get back into the call.","networkReconnectTitle":"Hold on","notInvitedToRoomDetails":"You are not able to join this room because you do not have an invite.","notInvitedToRoomTitle":"Not invited to room","peopleButtonLabel":"People","selectedPeopleButtonLabel":"People Button Selected","peoplePaneTitle":"People","peoplePaneMoreButtonAriaLabel":"More","peopleButtonTooltipOpen":"Show participants","peopleButtonTooltipClose":"Hide participants","peoplePaneSubTitle":"In this call {numberOfPeople}","privacyPolicy":"Privacy policy","rejoinCallButtonLabel":"Re-join call","removedFromCallMoreDetails":"Another participant removed you from the call.","removedFromCallTitle":"You were removed","removeMenuLabel":"Remove","startSpotlightMenuLabel":"Spotlight for everyone","addSpotlightMenuLabel":"Add spotlight","stopSpotlightMenuLabel":"Stop spotlighting","stopSpotlightOnSelfMenuLabel":"Exit spotlight","spotlightLimitReachedMenuTitle":"Spotlight limit reached","stopAllSpotlightMenuLabel":"Stop all spotlights","returnToCallButtonAriaDescription":"Return to Call","returnToCallButtonAriaLabel":"Back","roomNotFoundDetails":"The room ID provided could not be found.","roomNotFoundTitle":"Room not found","roomNotValidDetails":"This room is not valid at this current time.","roomNotValidTitle":"Room not valid","inviteToRoomRemovedDetails":"Your invite to join this room was removed.","inviteToRoomRemovedTitle":"Invite to room removed","soundLabel":"Sound","noMicrophonesLabel":"No microphones found","noSpeakersLabel":"No speakers found","startCallButtonLabel":"Start call","openDialpadButtonLabel":"Dial phone number","peoplePaneAddPeopleButtonLabel":"Add People","dialpadStartCallButtonLabel":"Call","dialpadModalTitle":"Dial Phone Number","dialpadModalAriaLabel":"Dialpad","dialpadCloseModalButtonAriaLabel":"Close dialpad","moreButtonCallingLabel":"More","resumeCallButtonLabel":"Resume","resumingCallButtonLabel":"Resuming...","resumeCallButtonAriaLabel":"Resume call","resumingCallButtonAriaLabel":"Resume call","holdScreenLabel":"You\'re on hold","openDtmfDialpadLabel":"Show dialpad","dtmfDialpadPlaceholderText":"Enter number","outboundCallingNoticeString":"Calling...","participantJoinedNoticeString":"{displayName} joined","twoParticipantJoinedNoticeString":"{displayName1} and {displayName2} have joined","threeParticipantJoinedNoticeString":"{displayName1}, {displayName2} and {displayName3} have joined","participantLeftNoticeString":"{displayName} left","twoParticipantLeftNoticeString":"{displayName1} and {displayName2} have left","threeParticipantLeftNoticeString":"{displayName1}, {displayName2} and {displayName3} have left","unnamedParticipantString":"unnamed participant","manyUnnamedParticipantsJoined":"unnamed participant and {numOfParticipants} other participants joined","manyUnnamedParticipantsLeft":"unnamed participant and {numOfParticipants} other participants left","manyParticipantsJoined":"{displayName1}, {displayName2}, {displayName3} and {numOfParticipants} other participants joined","manyParticipantsLeft":"{displayName1}, {displayName2}, {displayName3} and {numOfParticipants} other participants left","liveCaptionsLabel":"Live captions","captionsSettingsLabel":"Caption settings","startCaptionsButtonOnLabel":"Turn on captions","startCaptionsButtonOffLabel":"Turn off captions","startCaptionsButtonTooltipOnContent":"Turn off captions","startCaptionsButtonTooltipOffContent":"Turn on captions","captionsSettingsModalTitle":"Captions Settings","captionsSettingsSpokenLanguageDropdownLabel":"Spoken language","captionsSettingsCaptionLanguageDropdownLabel":"Captions language","captionsSettingsSpokenLanguageDropdownInfoText":"Language that everyone on this call is speaking.","captionsSettingsCaptionLanguageDropdownInfoText":"Captions will appear in this langugage.","captionsSettingsConfirmButtonLabel":"Confirm","captionsSettingsCancelButtonLabel":"Cancel","captionsSettingsModalAriaLabel":"Captions Setting Modal","captionsSettingsCloseModalButtonAriaLabel":"Close Captions Setting","captionsBannerMoreButtonCallingLabel":"More","captionsBannerMoreButtonTooltip":"More options","dismissModalAriaLabel":"Local and remote picture and picture, press enter to return to call","callRejectedTitle":"The call could not be completed","callRejectedMoreDetails":"The person you are trying to reach is unavailable. Please try again later.","callTimeoutTitle":"The call could not be completed","callTimeoutDetails":"The person you are trying to reach is unavailable. Please try again later.","callTimeoutBotTitle":"The call could not be completed","callTimeoutBotDetails":"The service that you are trying to reach is unavailable. Please try again later.","dtmfDialerButtonLabel":"Dialpad","dtmfDialerButtonTooltipOn":"Show dialpad","dtmfDialerButtonTooltipOff":"Hide dialpad","dtmfDialerMoreButtonLabelOn":"Show dialpad","dtmfDialerMoreButtonLabelOff":"Hide dialpad","spokenLanguageStrings":{"ar-ae":"Arabic - U.A.E.","ar-sa":"Arabic - Saudi Arabia","da-dk":"Danish","de-de":"German - Germany","en-au":"English - Australia","en-ca":"English - Canada","en-gb":"English - United Kingdom","en-in":"English - India","en-nz":"English - New Zealand","en-us":"English - United States","es-es":"Spanish - Spain (Modern Sort)","es-mx":"Spanish - Mexico","fi-fi":"Finnish","fr-ca":"French - Canada","fr-fr":"French - France","hi-in":"Hindi","it-it":"Italian - Italy","ja-jp":"Japanese","ko-kr":"Korean","nb-no":"Norwegian (Bokmål)","nl-be":"Dutch - Belgium","nl-nl":"Dutch - Netherlands","pl-pl":"Polish","pt-br":"Portuguese - Brazil","ru-ru":"Russian","sv-se":"Swedish","zh-cn":"Chinese - People\'s Republic of China","zh-hk":"Chinese - Hong Kong SAR","cs-cz":"Czech","pt-pt":"Portuguese - Portugal","tr-tr":"Turkish","vi-vn":"Vietnamese","th-th":"Thai","he-il":"Hebrew","cy-gb":"Welsh","uk-ua":"Ukrainian","el-gr":"Greek","hu-hu":"Hungarian","ro-ro":"Romanian","sk-sk":"Slovak","zh-tw":"Chinese - Taiwan"},"captionLanguageStrings":{"ar":"Arabic","da":"Danish","de":"German","en":"English","es":"Spanish","fi":"Finnish","fr-ca":"French - Canada","fr":"French - France","hi":"Hindi","it":"Italian","ja":"Japanese","ko":"Korean","nb":"Norwegian (Bokmål)","nl":"Dutch","pl":"Polish","pt":"Portuguese - Brazil","ru":"Russian","sv":"Swedish","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)","cs":"Czech","pt-pt":"Portuguese - Portugal","tr":"Turkish","vi":"Vietnamese","th":"Thai","he":"Hebrew","cy":"Welsh","uk":"Ukrainian","el":"Greek","hu":"Hungarian","ro":"Romanian","sk":"Slovak"},"captionsBannerSpinnerText":"Starting captions...","transferPageTransferorText":"Transferring...","transferPageTransferTargetText":"Connecting...","transferPageUnknownTransferorDisplayName":"Unknown","transferPageUnknownTransferTargetDisplayName":"Unknown","transferPageNoticeString":"You are being transferred","participantCouldNotBeReachedTitle":"Target participant is currently not available","participantCouldNotBeReachedMoreDetails":"Please contact participant when they are available","permissionToReachTargetParticipantNotAllowedTitle":"Permission to reach target participant is not allowed","permissionToReachTargetParticipantNotAllowedMoreDetails":"Please check that the target participant is in the same tenant","unableToResolveTenantTitle":"Unable to resolve tenant id for the target participant","unableToResolveTenantMoreDetails":"Please check the participant id is entered correctly","participantIdIsMalformedTitle":"Participant id is not in the correct format","participantIdIsMalformedMoreDetails":"Please check that the participant id is in the correct format","moreButtonGalleryControlLabel":"View","moreButtonGalleryPositionToggleLabel":"Move gallery to top","moreButtonGallerySpeakerLayoutLabel":"Speaker","moreButtonGalleryFloatingLocalLayoutLabel":"Dynamic","moreButtonGalleryDefaultLayoutLabel":"Gallery view","moreButtonGalleryFocusedContentLayoutLabel":"Focus on content","moreButtonLargeGalleryDefaultLayoutLabel":"Large Gallery","capabilityChangedNotification":{"turnVideoOn":{"lostDueToMeetingOption":"Your camera has been disabled. You can no longer share video.","grantedDueToMeetingOption":"Your camera has been enabled. Turn it on if you\'d like to share video."},"unmuteMic":{"lostDueToMeetingOption":"Your mic has been disabled. You can no longer unmute.","grantedDueToMeetingOption":"Your mic has been enabled. Unmute if you\'d like to speak."},"shareScreen":{"lostDueToRoleChangeToAttendee":"Your role has been changed. Some actions, like sharing content, won\'t be available to you.","grantedDueToRoleChangeToPresenter":"You\'re a presenter. You can share content and facilitate the meeting."}},"surveyTitle":"Help us improve","starSurveyHelperText":"How was the quality of the call?","starSurveyOneStarText":"The quality was bad.","starSurveyTwoStarText":"The quality was poor.","starSurveyThreeStarText":"The quality was good.","starSurveyFourStarText":"The quality was great.","starSurveyFiveStarText":"The quality was excellent.","surveyConfirmButtonLabel":"Send Feedback","starRatingAriaLabel":"Select {0} of {1} stars","surveySkipButtonLabel":"Skip","tagsSurveyQuestion":"What could have been better?","tagsSurveyTextFieldDefaultText":"Other, please specify","tagsSurveyHelperText":"Check any issues you experienced","endOfSurveyText":"Thank you for your feedback!","surveyIssues":{"overallRating":{"callCannotJoin":"I could not join call","callCannotInvite":"I could not invite others into the call","hadToRejoin":"I had to rejoin the call","callEndedUnexpectedly":"Call ended for me unexpectedly","otherIssues":"I was having other issues with the call"},"audioRating":{"noLocalAudio":"The other side could not hear any sound","noRemoteAudio":"I could not hear any sound","echo":"I heard echos on the call","audioNoise":"I heard noise on the call","lowVolume":"Volume was low","audioStoppedUnexpectedly":"Audio stopped unexpectedly","distortedSpeech":"Audio was distorted","audioInterruption":"Audio was interrupted","otherIssues":"I was having other audio issues in this call"},"videoRating":{"noVideoReceived":"I could not see any video","noVideoSent":"Others could not see me","lowQuality":"Video quality was low","freezes":"Video frozen","stoppedUnexpectedly":"Video stopped unexpectedly","darkVideoReceived":"I can only see dark screens when others turn on their camera","audioVideoOutOfSync":"Audio and Video was out of sync","otherIssues":"I was having other video issues in this call"},"screenshareRating":{"noContentLocal":"Other people could not see my screenshare","noContentRemote":"I could not see other people\'s screenshare","cannotPresent":"I could not present my screen","lowQuality":"Screen share quality was low","freezes":"Screen share frozen","stoppedUnexpectedly":"Screen share stopped unexpectedly","largeDelay":"Screen share has a large delay","otherIssues":"I was having other screen share issues in this call"}},"surveyIssuesHeadingStrings":{"overallRating":"Overall","audioRating":"Audio","videoRating":"Video","screenshareRating":"Presenting"},"spotlightPrompt":{"startSpotlightHeading":"Spotlight for everyone?","startSpotlightText":"You\'ll highlight this video for everyone in the meeting.","startSpotlightOnSelfText":"You\'ll highlight your video for everyone in the meeting.","startSpotlightConfirmButtonLabel":"Spotlight for everyone","startSpotlightCancelButtonLabel":"Cancel","stopSpotlightHeading":"Stop spotlighting this video?","stopSpotlightOnSelfHeading":"Exit spotlight?","stopAllSpotlightHeading":"Stop spotlighting all videos?","stopSpotlightText":"This video will no longer be highlighted for everyone in the meeting.","stopSpotlightOnSelfText":"Your video will no longer be highlighted for everyone in the meeting.","stopAllSpotlightText":"The videos will no longer be highlighted for everyone in the meeting.","stopSpotlightConfirmButtonLabel":"Stop spotlighting","stopSpotlightOnSelfConfirmButtonLabel":"Exit spotlight","stopSpotlightCancelButtonLabel":"Cancel"},"exitSpotlightButtonLabel":"Exit spotlight","exitSpotlightButtonTooltip":"Exit spotlight","leaveConfirmButtonLabel":"Leave","endCallConfirmButtonLabel":"End call","hangUpCancelButtonLabel":"Cancel","leaveConfirmDialogTitle":"Leave the call?","leaveConfirmDialogContent":"Are you sure you want to leave the call?","endCallConfirmDialogTitle":"End the call?","endCallConfirmDialogContent":"You\'ll end the call for everyone.","invalidMeetingIdentifier":"Invalid meeting ID or passcode"},"chat":{"chatListHeader":"In this chat","uploadAttachment":"Upload Attachment"},"callWithChat":{"chatButtonLabel":"Chat","chatButtonNewMessageNotificationLabel":"New Message","chatButtonTooltipClosedWithMessageCount":"Show chat ({unreadMessagesCount} unread)","chatButtonTooltipClose":"Hide chat","chatButtonTooltipOpen":"Show chat","chatPaneTitle":"Chat","copyInviteLinkButtonLabel":"Copy invite link","copyInviteLinkActionedAriaLabel":"Invite link copied","dismissSidePaneButtonLabel":"Close","moreDrawerAudioDeviceMenuTitle":"Audio Device","moreDrawerButtonLabel":"More options","moreDrawerButtonTooltip":"More options","moreDrawerMicrophoneMenuTitle":"Microphone","moreDrawerSpeakerMenuTitle":"Speaker","moreDrawerCaptionsMenuTitle":"Live captions","moreDrawerSpokenLanguageMenuTitle":"Spoken language","moreDrawerCaptionLanguageMenuTitle":"Caption language","moreDrawerGalleryOptionsMenuTitle":"Gallery options","peopleButtonLabel":"People","selectedPeopleButtonLabel":"People Button Selected","peopleButtonTooltipOpen":"Show participants","peopleButtonTooltipClose":"Hide participants","peoplePaneSubTitle":"In this call","peoplePaneTitle":"People","pictureInPictureTileAriaLabel":"Video Feeds. Click to return to call screen.","removeMenuLabel":"Remove","openDialpadButtonLabel":"Dial phone number","returnToCallButtonAriaDescription":"Return to Call","returnToCallButtonAriaLabel":"Back","peoplePaneAddPeopleButtonLabel":"Add People","dialpadStartCallButtonLabel":"Call","dialpadModalTitle":"Dial Phone Number","dialpadModalAriaLabel":"Dialpad","dialpadCloseModalButtonAriaLabel":"Close dialpad","openDtmfDialpadLabel":"Show dialpad","dtmfDialpadPlaceholderText":"Enter number"}}')},tp=(0,e.createContext)(ep),ip=()=>(0,e.useContext)(tp),np=e.createContext(void 0),rp={},ap=(np.Provider,()=>{const e={};return function(t,i){void 0===e[t.id]&&(t.insertCSSRules(i),e[t.id]=!0)}}),sp="undefined"==typeof window?r.g:window,op="@griffel/";function lp(e,t){return sp[Symbol.for(op+e)]||(sp[Symbol.for(op+e)]=t),sp[Symbol.for(op+e)]}const cp=lp("DEFINITION_LOOKUP_TABLE",{}),dp="data-make-styles-bucket",up=7,hp="___",pp=hp.length+up;function gp(e,t,i=[]){return hp+function(e){const t=e.length;if(t===up)return e;for(let i=t;i<up;i++)e+="0";return e}(function(e){for(var t,i=0,n=0,r=e.length;r>=4;++n,r-=4)t=1540483477*(65535&(t=255&e.charCodeAt(n)|(255&e.charCodeAt(++n))<<8|(255&e.charCodeAt(++n))<<16|(255&e.charCodeAt(++n))<<24))+(59797*(t>>>16)<<16),i=1540483477*(65535&(t^=t>>>24))+(59797*(t>>>16)<<16)^1540483477*(65535&i)+(59797*(i>>>16)<<16);switch(r){case 3:i^=(255&e.charCodeAt(n+2))<<16;case 2:i^=(255&e.charCodeAt(n+1))<<8;case 1:i=1540483477*(65535&(i^=255&e.charCodeAt(n)))+(59797*(i>>>16)<<16)}return(((i=1540483477*(65535&(i^=i>>>13))+(59797*(i>>>16)<<16))^i>>>15)>>>0).toString(36)}(e+t))}function mp(e,t){let i="";for(const n in e){const r=e[n];if(r){const e=Array.isArray(r);i+="rtl"===t?(e?r[1]:r)+" ":(e?r[0]:r)+" "}}return i.slice(0,-1)}function fp(e,t){const i={};for(const n in e){const r=mp(e[n],t);if(""===r){i[n]="";continue}const a=gp(r,t),s=a+" "+r;cp[a]=[e[n],t],i[n]=s}return i}const vp=t.useInsertionEffect?t.useInsertionEffect:void 0,Sp=()=>{const e={};return function(t,i){vp&&"undefined"!=typeof window&&window.document&&window.document.createElement?vp((()=>{t.insertCSSRules(i)}),[t,i]):void 0===e[t.id]&&(t.insertCSSRules(i),e[t.id]=!0)}};const yp=["r","d","l","v","w","f","i","h","a","s","k","t","m","c"].reduce(((e,t,i)=>(e[t]=i,e)),{});function Cp(e,t,i,n,r={}){const a="m"===e,s=a?e+r.m:e;if(!n.stylesheets[s]){const o=t&&t.createElement("style"),l=function(e,t,i){const n=[];if(i[dp]=t,e)for(const t in i)e.setAttribute(t,i[t]);return{elementAttributes:i,insertRule:function(t){return null!=e&&e.sheet?e.sheet.insertRule(t,e.sheet.cssRules.length):n.push(t)},element:e,bucketName:t,cssRules:()=>null!=e&&e.sheet?Array.from(e.sheet.cssRules).map((e=>e.cssText)):n}}(o,e,Object.assign({},n.styleElementAttributes,a&&{media:r.m}));n.stylesheets[s]=l,t&&o&&t.head.insertBefore(o,function(e,t,i,n,r){const a=yp[i];let s=e=>a-yp[e.getAttribute(dp)],o=e.head.querySelectorAll(`[${dp}]`);if("m"===i&&r){const t=e.head.querySelectorAll(`[${dp}="${i}"]`);t.length&&(o=t,s=e=>n.compareMediaQueries(r.m,e.media))}const l=o.length;let c=l-1;for(;c>=0;){const e=o.item(c);if(s(e)>0)return e.nextSibling;c--}return l>0?o.item(0):t?t.nextSibling:null}(t,i,e,n,r))}return n.stylesheets[s]}function _p(e,t){try{e.insertRule(t)}catch(e){}}let Ep=0;const Tp=(e,t)=>e<t?-1:e>t?1:0;function bp(e=("undefined"==typeof document?void 0:document),t={}){const{unstable_filterCSSRule:i,insertionPoint:n,styleElementAttributes:r,compareMediaQueries:a=Tp}=t,s={insertionCache:{},stylesheets:{},styleElementAttributes:Object.freeze(r),compareMediaQueries:a,id:"d"+Ep++,insertCSSRules(t){for(const a in t){const o=t[a];for(let t=0,l=o.length;t<l;t++){const[l,c]=(r=o[t],Array.isArray(r)?r:[r]),d=Cp(a,e,n||null,s,c);s.insertionCache[l]||(s.insertionCache[l]=a,i?i(l)&&_p(d,l):_p(d,l))}}var r}};return s}const Ip=e.createContext(bp()),wp=e.createContext("ltr"),Rp={},Ap=function(t,i){const n=function(e,t,i=ap){const n=i();let r=null,a=null;return function(i){const{dir:s,renderer:o}=i,l="ltr"===s;return l?null===r&&(r=fp(e,s)):null===a&&(a=fp(e,s)),n(o,t),l?r:a}}({root:{mc9l5x:"f1w7gpdv",Bg96gwp:"fez10in",ycbfsm:"fg4l7m0"},rtl:{Bz10aip:"f13rod7r"}},{d:[".f1w7gpdv{display:inline;}",".fez10in{line-height:0;}",".f13rod7r{-webkit-transform:scaleX(-1);-moz-transform:scaleX(-1);-ms-transform:scaleX(-1);transform:scaleX(-1);}"],t:["@media (forced-colors: active){.fg4l7m0{forced-color-adjust:auto;}}"]},Sp);return function(){const t=e.useContext(wp),i=e.useContext(Ip);return n({dir:t,renderer:i})}}(),Pp=(t,i)=>{const{title:n,primaryFill:r="currentColor",...a}=t,s={...a,title:void 0,fill:r},o=Ap(),l=e.useContext(np)?e.useContext(np):rp;return s.className=function(){let e=null,t="",i="";const n=new Array(arguments.length);for(let e=0;e<arguments.length;e++){const r=arguments[e];if("string"==typeof r&&""!==r){const a=r.indexOf(hp);if(-1===a)t+=r+" ";else{const s=r.substr(a,pp);a>0&&(t+=r.slice(0,a)),i+=s,n[e]=s}}}if(""===i)return t.slice(0,-1);const r=Rp[i];if(void 0!==r)return t+r;const a=[];for(let t=0;t<arguments.length;t++){const i=n[t];if(i){const t=cp[i];t&&(a.push(t[0]),e=t[1])}}const s=Object.assign.apply(Object,[{}].concat(a));let o=mp(s,e);const l=gp(o,e,n);return o=l+" "+o,Rp[i]=o,cp[l]=[s,e],t+o}(o.root,(null==i?void 0:i.flipInRtl)&&"rtl"===(null==l?void 0:l.textDirection)&&o.rtl,s.className),n&&(s["aria-label"]=n),s["aria-label"]||s["aria-labelledby"]?s.role="img":s["aria-hidden"]=!0,s},Mp=(t,i,n,r)=>{const a="1em"===i?"20":i,s=e.forwardRef(((t,s)=>{const o={...Pp(t,{flipInRtl:null==r?void 0:r.flipInRtl}),ref:s,width:i,height:i,viewBox:`0 0 ${a} ${a}`,xmlns:"http://www.w3.org/2000/svg"};return e.createElement("svg",o,...n.map((t=>e.createElement("path",{d:t,fill:o.fill}))))}));return s.displayName=t,s},kp=Mp("Video16Filled","16",["M1 5.5A2.5 2.5 0 0 1 3.5 3h4A2.5 2.5 0 0 1 10 5.5v5A2.5 2.5 0 0 1 7.5 13h-4A2.5 2.5 0 0 1 1 10.5v-5Zm12.04 6.28L10.9 10.3l.02-.28V5.98c0-.1 0-.19-.02-.28l2.14-1.48c.82-.57 1.96.02 1.96 1.03v5.5c0 1-1.14 1.6-1.96 1.03Z"]),Dp=Mp("Video20Filled","20",["M2 7a3 3 0 0 1 3-3h5a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V7Zm14.04 7.78L14 13.37V6.63l2.04-1.4c.83-.58 1.96.01 1.96 1.02v7.5c0 1-1.13 1.6-1.96 1.03Z"]),Op=Mp("Video20Regular","20",["M5 4a3 3 0 0 0-3 3v6a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3v-.32l3.04 2.1c.83.57 1.96-.03 1.96-1.03v-7.5c0-1-1.13-1.6-1.96-1.03L13 7.32V7a3 3 0 0 0-3-3H5Zm8 4.54 3.6-2.5c.17-.1.4.01.4.21v7.5c0 .2-.23.32-.4.2L13 11.46V8.54ZM3 7c0-1.1.9-2 2-2h5a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"]),Np=Mp("VideoBackgroundEffect20Filled","20",["M6.2 4 2 8.2V6.8L4.8 4h1.4Zm7 0-1.46 1.46a3.48 3.48 0 0 0-1.02-.39L11.79 4h1.42Zm-1.08 3.17a2.51 2.51 0 0 0-2.34-1.16 2.5 2.5 0 1 0 2.34 1.16Zm.72-.72c.2.29.37.6.48.94L16.69 4 16.5 4h-1.2l-2.46 2.45ZM7.5 12c-.08 0-.15 0-.22.02A1.5 1.5 0 0 0 6 13.5V16h8v-2.5a1.5 1.5 0 0 0-1.5-1.5h-5Zm5-1c.22 0 .43.03.63.08L18 6.2V5.5c0-.2-.04-.4-.12-.59l-4.5 4.5a3.5 3.5 0 0 1-.93 1.59h.05Zm1.9.88c.23.27.4.58.5.93L18 9.7V8.29l-3.6 3.6ZM15 16v-1.2l3-3v1.4L15.2 16H15Zm-10-.3v-1.4l-1.7 1.69.2.01h1.2l.3-.3Zm1.57-6.48c.08.36.21.7.4 1.02L2.11 15.1A1.5 1.5 0 0 1 2 14.5v-.7l4.57-4.58ZM9.71 4 2 11.7v-1.4L8.3 4h1.4Z"]),Lp=Mp("VideoBackgroundEffect20Regular","20",["M6.2 4 2 8.2V6.8L4.8 4h1.4ZM3.5 16H5v-1.7l-1.7 1.69.2.01Zm11.7 0H15v-1.2l3-3v1.4L15.2 16ZM18 9.7l-3.1 3.1a2.5 2.5 0 0 0-.5-.92L18 8.3v1.42ZM12.5 12a1.5 1.5 0 0 1 1.5 1.5V16h-1v-2.5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0-.5.5V16H6v-2.5c0-.08 0-.15.02-.22A1.5 1.5 0 0 1 7.5 12h5Zm-2.78-1.02a2.49 2.49 0 0 1-2.21-2.7 2.5 2.5 0 1 1 2.21 2.7ZM10 10a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm-7.88 5.09 4.84-4.85a3.48 3.48 0 0 1-.39-1.02L2 13.79v.71c0 .2.04.4.12.59Zm9.62-9.63a3.48 3.48 0 0 0-1.02-.39L11.79 4h1.42l-1.47 1.46Zm1.58 1.93a3.49 3.49 0 0 0-.48-.94L15.29 4h1.21l.2.01-3.38 3.38ZM12.45 11c.44-.43.76-.98.93-1.59l4.5-4.5c.08.18.12.38.12.59v.7l-4.87 4.88a2.5 2.5 0 0 0-.63-.08h-.05ZM2 11.7 9.7 4H8.3L2 10.3v1.4Z"]),xp=Mp("VideoOff20Filled","20",["M2.85 2.15a.5.5 0 1 0-.7.7l1.48 1.48A3 3 0 0 0 2 7v6a3 3 0 0 0 3 3h5a3 3 0 0 0 2.93-2.36l4.22 4.21a.5.5 0 0 0 .7-.7l-15-15ZM14 11.88l3.08 3.07c.5-.14.92-.6.92-1.2v-7.5c0-1-1.13-1.6-1.96-1.03L14 6.63v5.25ZM6.12 4 13 10.88V7a3 3 0 0 0-3-3H6.12Z"]),Fp=Mp("VideoPerson20Filled","20",["M12.5 8.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0ZM2 5.5C2 4.67 2.67 4 3.5 4h13c.83 0 1.5.67 1.5 1.5v9c0 .83-.67 1.5-1.5 1.5h-13A1.5 1.5 0 0 1 2 14.5v-9ZM14 15h2.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-13a.5.5 0 0 0-.5.5v9c0 .28.22.5.5.5H6v-1.5c0-.83.67-1.5 1.5-1.5h5c.83 0 1.5.67 1.5 1.5V15Z"]),Up=Mp("VideoPersonStar20Filled","20",["M2 5.5C2 4.67 2.67 4 3.5 4h13c.83 0 1.5.67 1.5 1.5v4.76a5.5 5.5 0 0 0-1-.66V5.5a.5.5 0 0 0-.5-.5h-13a.5.5 0 0 0-.5.5v9c0 .28.22.5.5.5H6v-1.5c0-.83.67-1.5 1.5-1.5h2.1a5.48 5.48 0 0 0-.4 4H3.5A1.5 1.5 0 0 1 2 14.5v-9Zm10.5 3c0 .34-.07.66-.19.95-.8.35-1.5.88-2.04 1.54L10 11a2.5 2.5 0 1 1 2.5-2.5Zm6.5 6a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-4.02-2.64a.5.5 0 0 0-.96 0l-.47 1.53H12c-.48 0-.69.65-.3.95l1.26.94-.48 1.53c-.15.49.38.89.77.59l1.25-.95 1.25.95c.4.3.92-.1.77-.59l-.48-1.53 1.25-.94c.4-.3.2-.95-.3-.95h-1.54l-.47-1.53Z"]),Bp=Mp("VideoPersonStarOff20Filled","20",["M2.85 2.15a.5.5 0 1 0-.7.7L3.3 4.01C2.57 4.11 2 4.74 2 5.5v9c0 .83.67 1.5 1.5 1.5h5.7a5.5 5.5 0 0 1 .4-4H7.5c-.83 0-1.5.67-1.5 1.5V15H3.5a.5.5 0 0 1-.5-.5v-9c0-.28.22-.5.5-.5h.8l3.22 3.22-.02.28a2.5 2.5 0 0 0 2.77 2.49v-.01l.71.71a4.5 4.5 0 0 0 6.37 6.29.5.5 0 0 0 .5-.83l-15-15ZM16.5 17.2c-.13.27-.47.4-.75.2l-1.25-.95-1.25.95c-.4.3-.92-.1-.77-.59l.48-1.53-1.25-.94c-.4-.3-.2-.95.3-.95h.68l3.8 3.81ZM8.57 6.45l3.25 3.25c.16-.1.32-.17.5-.25A2.5 2.5 0 0 0 10 6c-.53 0-1.02.17-1.43.45Zm3.99 3.99 1.45 1.45.01-.03a.5.5 0 0 1 .96 0l.45 1.45.08.08H17c.48 0 .68.65.3.95l-.48.36 1.74 1.74a4.5 4.5 0 0 0-6-6ZM6.12 4l1 1h9.38c.28 0 .5.22.5.5v4.1c.36.18.7.4 1 .66V5.5c0-.83-.67-1.5-1.5-1.5H6.12Z"]),Vp=Mp("VideoProhibited16Filled","16",["M1 5a2.5 2.5 0 0 1 2.5-2.5h5A2.5 2.5 0 0 1 11 5v1.02a5.5 5.5 0 0 0-4.63 7.48H3.5A2.5 2.5 0 0 1 1 11V5Zm11 1.02c1.13.1 2.17.55 3 1.24V4.5a.5.5 0 0 0-.82-.39L12 5.9v.13ZM7 11.5a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm1 0a3.5 3.5 0 0 1 5.6-2.8l-4.9 4.9a3.48 3.48 0 0 1-.7-2.1Zm3.5 3.5c-.79 0-1.51-.26-2.1-.7l4.9-4.9a3.5 3.5 0 0 1-2.8 5.6Z"]),Hp=Mp("VideoProhibited20Filled","20",["M13 6.5A2.5 2.5 0 0 0 10.5 4h-6A2.5 2.5 0 0 0 2 6.5v7A2.5 2.5 0 0 0 4.5 16h4.7A5.5 5.5 0 0 1 13 9.2V6.5Zm5-.3v4.06a5.48 5.48 0 0 0-4-1.24V7.93l2.77-2.31a.75.75 0 0 1 1.23.57Zm-8 8.3a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm1 0a3.5 3.5 0 0 1 5.6-2.8l-4.9 4.9a3.48 3.48 0 0 1-.7-2.1Zm3.5 3.5c-.79 0-1.51-.26-2.1-.7l4.9-4.9a3.5 3.5 0 0 1-2.8 5.6Z"]),$p=Mp("Warning20Filled","20",["M8.68 2.79a1.5 1.5 0 0 1 2.64 0l6.5 12A1.5 1.5 0 0 1 16.5 17h-13a1.5 1.5 0 0 1-1.32-2.21l6.5-12ZM10.5 7.5a.5.5 0 0 0-1 0v4a.5.5 0 0 0 1 0v-4Zm.25 6.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"]),Gp=Mp("WifiWarning20Filled","20",["M16.73 7.56c.4.4.78.87 1.11 1.35a.75.75 0 0 1-1.23.85 7.97 7.97 0 0 0-13.14 0 .75.75 0 1 1-1.23-.86 9.47 9.47 0 0 1 14.5-1.34ZM5.48 9.46a6.44 6.44 0 0 1 8.65-.43c-.52.1-1 .4-1.31.9a4.94 4.94 0 0 0-7.2 1.84.75.75 0 0 1-1.33-.67c.3-.61.7-1.16 1.19-1.65Zm4.3 6.51 1.08-2.15a1.24 1.24 0 1 0-1.08 2.15Zm1.7-3.4.68-1.35a4.13 4.13 0 0 0-5.9 1.9.75.75 0 0 0 1.37.6c.13-.32.32-.6.54-.82.9-.9 2.3-1.01 3.31-.33Zm2.12-2.02-3.5 7A1 1 0 0 0 11 19h7a1 1 0 0 0 .9-1.45l-3.5-7a1 1 0 0 0-1.8 0ZM15 12.5v3a.5.5 0 1 1-1 0v-3a.5.5 0 1 1 1 0Zm-.5 5.5a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1Z"]),jp=Mp("WindowHeaderHorizontal20Regular","20",["M5.5 3A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h9a2.5 2.5 0 0 0 2.5-2.5v-9A2.5 2.5 0 0 0 14.5 3h-9ZM4 14.5V7h12v7.5c0 .83-.67 1.5-1.5 1.5h-9A1.5 1.5 0 0 1 4 14.5Z"]),zp=Mp("Mic16Filled","16",["M8 2a2.5 2.5 0 0 0-2.5 2.5V8a2.5 2.5 0 0 0 5 0V4.5A2.5 2.5 0 0 0 8 2ZM4 7.5c.28 0 .5.22.5.5a3.5 3.5 0 1 0 7 0 .5.5 0 0 1 1 0 4.5 4.5 0 0 1-4 4.47v1.03a.5.5 0 0 1-1 0v-1.03A4.5 4.5 0 0 1 3.5 8c0-.28.22-.5.5-.5Z"]),Wp=Mp("Mic20Filled","20",["M5.5 10a.5.5 0 0 0-1 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0v-2.02c2.8-.26 5-2.61 5-5.48a.5.5 0 0 0-1 0 4.5 4.5 0 1 1-9 0Zm7.5 0a3 3 0 0 1-6 0V5a3 3 0 0 1 6 0v5Z"]),qp=Mp("Mic20Regular","20",["M10 13a3 3 0 0 0 3-3V5a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3Zm0-1a2 2 0 0 1-2-2V5a2 2 0 1 1 4 0v5a2 2 0 0 1-2 2ZM5 9.5c.28 0 .5.22.5.5a4.5 4.5 0 1 0 9 0 .5.5 0 0 1 1 0 5.5 5.5 0 0 1-5 5.48v2.02a.5.5 0 0 1-1 0v-2.02a5.5 5.5 0 0 1-5-5.48c0-.28.22-.5.5-.5Z"]),Kp=Mp("MicOff16Filled","16",["m10.8 11.52 3.35 3.33a.5.5 0 0 0 .7-.7l-13-13a.5.5 0 1 0-.7.7L5.5 6.21V8a2.5 2.5 0 0 0 3.88 2.09l.72.71A3.5 3.5 0 0 1 4.5 8a.5.5 0 1 0-1 0 4.5 4.5 0 0 0 4 4.47v1.03a.5.5 0 1 0 1 0v-1.03c.87-.1 1.66-.44 2.3-.95Zm1.26-1.58-.76-.76c.13-.37.2-.77.2-1.18a.5.5 0 0 1 1 0c0 .7-.16 1.35-.44 1.94Zm-1.58-1.59-4.8-4.79a2.5 2.5 0 0 1 4.82.94V8c0 .12 0 .24-.02.35Z"]),Jp=Mp("MicOff16Regular","16",["m10.8 11.52 3.35 3.33a.5.5 0 0 0 .7-.7l-13-13a.5.5 0 1 0-.7.7L5.5 6.21V8a2.5 2.5 0 0 0 3.88 2.09l.72.71A3.5 3.5 0 0 1 4.5 8a.5.5 0 1 0-1 0 4.5 4.5 0 0 0 4 4.47v1.03a.5.5 0 1 0 1 0v-1.03c.87-.1 1.66-.44 2.3-.95ZM8.66 9.35A1.5 1.5 0 0 1 6.5 8v-.8l2.15 2.15Zm.85-1.97V4.5a1.5 1.5 0 0 0-3-.12l-.82-.82a2.5 2.5 0 0 1 4.82.94V8c0 .12 0 .24-.02.35l-.98-.97Zm2.56 2.56-.76-.76c.13-.37.2-.77.2-1.18a.5.5 0 0 1 1 0c0 .7-.16 1.35-.44 1.94Z"]),Yp=Mp("MicOff20Filled","20",["M13 10a3 3 0 0 1-.1.78L7 4.88A3 3 0 0 1 13 5v5ZM7 7.7V10a3 3 0 0 0 4.74 2.45l1.07 1.07A4.5 4.5 0 0 1 5.5 10a.5.5 0 0 0-1.01 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0v-2.02a5.48 5.48 0 0 0 3.02-1.25l3.63 3.62a.5.5 0 0 0 .7-.7l-15-15a.5.5 0 1 0-.7.7L7 7.71Zm7.8 4.98c.45-.8.7-1.7.7-2.68a.5.5 0 0 0-1 0c0 .7-.16 1.35-.44 1.94l.74.74Z"]),Qp=Mp("MicProhibited16Filled","16",["M4 4.5a2.5 2.5 0 0 1 5 0v.7a5.5 5.5 0 0 0-3.98 4.82A2.5 2.5 0 0 1 4 8V4.5Zm1.04 6.68A3.5 3.5 0 0 1 3 8a.5.5 0 0 0-1 0 4.5 4.5 0 0 0 3.32 4.34 5.47 5.47 0 0 1-.28-1.16ZM6 10.5a4.5 4.5 0 1 0 9 0 4.5 4.5 0 0 0-9 0Zm2.4 2.8 4.9-4.9a3.5 3.5 0 0 1-4.9 4.9Zm-.7-.7a3.5 3.5 0 0 1 4.9-4.9l-4.9 4.9Z"]),Zp=Mp("MicProhibited20Filled","20",["M9.2 13A5.51 5.51 0 0 1 12 9.6V5a3 3 0 1 0-6 0v5a3 3 0 0 0 3.2 3Zm.3 4.5v-.7c-.32-.7-.5-1.48-.5-2.3A4.5 4.5 0 0 1 4.5 10a.5.5 0 0 0-1 0 5.5 5.5 0 0 0 5 5.48v2.02a.5.5 0 0 0 1 0Zm5 1.5a4.5 4.5 0 1 1 0-9 4.5 4.5 0 0 1 0 9Zm0-8a3.5 3.5 0 0 0-2.8 5.6l4.9-4.9a3.48 3.48 0 0 0-2.1-.7Zm-2.1 6.3a3.5 3.5 0 0 0 4.9-4.9l-4.9 4.9Z"]),Xp=Mp("ShareScreenStart20Filled","20",["M4 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h12a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H4Zm6 10a.5.5 0 0 1-.5-.5V7.7L7.85 9.36a.5.5 0 1 1-.7-.7l2.5-2.5c.2-.2.5-.2.7 0l2.5 2.5a.5.5 0 0 1-.7.7L10.5 7.71v5.79a.5.5 0 0 1-.5.5Z"]),eg=Mp("ShareScreenStop20Filled","20",["M4.5 4A2.5 2.5 0 0 0 2 6.5v7A2.5 2.5 0 0 0 4.5 16h11a2.5 2.5 0 0 0 2.5-2.5v-7A2.5 2.5 0 0 0 15.5 4h-11Zm2.65 3.15c.2-.2.5-.2.7 0L10 9.29l2.15-2.14a.5.5 0 0 1 .7.7L10.71 10l2.14 2.15a.5.5 0 0 1-.7.7L10 10.71l-2.15 2.14a.5.5 0 0 1-.7-.7L9.29 10 7.15 7.85a.5.5 0 0 1 0-.7Z"]),tg=Mp("Sparkle20Filled","20",["M7.4 12.8a1.04 1.04 0 0 0 1.59-.51l.45-1.37a2.34 2.34 0 0 1 1.47-1.48l1.4-.45A1.04 1.04 0 0 0 12.25 7l-1.37-.45A2.34 2.34 0 0 1 9.4 5.08L8.95 3.7a1.03 1.03 0 0 0-.82-.68 1.04 1.04 0 0 0-1.15.7l-.46 1.4a2.34 2.34 0 0 1-1.44 1.45L3.7 7a1.04 1.04 0 0 0 .02 1.97l1.37.45a2.33 2.33 0 0 1 1.48 1.48l.46 1.4c.07.2.2.37.38.5Zm6.14 4.05a.8.8 0 0 0 1.22-.4l.25-.76a1.09 1.09 0 0 1 .68-.68l.77-.25a.8.8 0 0 0-.02-1.52l-.77-.25a1.08 1.08 0 0 1-.68-.68l-.25-.77a.8.8 0 0 0-1.52.01l-.24.76a1.1 1.1 0 0 1-.67.68l-.77.25a.8.8 0 0 0 0 1.52l.77.25a1.09 1.09 0 0 1 .68.68l.25.77c.06.16.16.3.3.4Z"]),ig=Mp("Speaker220Filled","20",["M12 3a1 1 0 0 0-1.68-.73l-3.87 3.6A.5.5 0 0 1 6.1 6H3.5C2.67 6 2 6.67 2 7.5v5c0 .83.67 1.5 1.5 1.5h2.6a.5.5 0 0 1 .35.13l3.87 3.6a1 1 0 0 0 1.68-.74V3.01Zm3.25 1.63a.5.5 0 0 1 .71.04 8 8 0 0 1 0 10.66.5.5 0 1 1-.75-.66 7 7 0 0 0 0-9.34.5.5 0 0 1 .04-.7Zm-1.17 8.3a.5.5 0 0 1-.19-.68 4.5 4.5 0 0 0 0-4.5.5.5 0 1 1 .87-.5 5.5 5.5 0 0 1 0 5.5.5.5 0 0 1-.68.18Z"]),ng=Mp("Speaker220Regular","20",["M12 3a1 1 0 0 0-1.68-.73l-3.88 3.6A.5.5 0 0 1 6.1 6H3.5C2.67 6 2 6.67 2 7.5v5c0 .83.67 1.5 1.5 1.5h2.6a.5.5 0 0 1 .34.13l3.88 3.6a1 1 0 0 0 1.68-.74V3.01ZM7.12 6.6 11 3v14l-3.88-3.6A1.5 1.5 0 0 0 6.1 13H3.5a.5.5 0 0 1-.5-.5v-5c0-.28.22-.5.5-.5h2.6c.38 0 .75-.14 1.02-.4Zm8.14-1.97a.5.5 0 0 1 .7.04 8 8 0 0 1 0 10.66.5.5 0 0 1-.74-.66 7 7 0 0 0 0-9.34.5.5 0 0 1 .04-.7Zm-1.18 8.3a.5.5 0 0 1-.18-.68 4.5 4.5 0 0 0 0-4.5.5.5 0 1 1 .86-.5 5.5 5.5 0 0 1 0 5.5.5.5 0 0 1-.68.18Z"]),rg=Mp("SpeakerMute16Filled","16",["M9 2.5a.5.5 0 0 0-.85-.36L5.22 5H3.5C2.67 5 2 5.66 2 6.5v3c0 .82.67 1.5 1.5 1.5h1.72l2.93 2.87A.5.5 0 0 0 9 13.5v-11Zm1.15 3.65c.2-.2.5-.2.7 0L12 7.29l1.15-1.14a.5.5 0 1 1 .7.7L12.71 8l1.14 1.15a.5.5 0 1 1-.7.7L12 8.71l-1.15 1.14a.5.5 0 0 1-.7-.7L11.29 8l-1.14-1.15a.5.5 0 0 1 0-.7Z"]),ag=Mp("Star28Filled","28",["M12.7 3.9a1.45 1.45 0 0 1 2.6 0L18 9.37l6.01.87a1.45 1.45 0 0 1 .8 2.48l-4.35 4.24 1.03 6a1.45 1.45 0 0 1-2.1 1.52L14 21.64l-5.38 2.83a1.45 1.45 0 0 1-2.1-1.52l1.02-6-4.35-4.24c-.86-.84-.39-2.3.8-2.48l6.02-.87 2.7-5.45Z"]),sg=Mp("Star28Regular","28",["M12.7 3.9a1.45 1.45 0 0 1 2.6 0L18 9.37l6.01.87a1.45 1.45 0 0 1 .8 2.48l-4.35 4.24 1.03 6a1.45 1.45 0 0 1-2.1 1.52L14 21.64l-5.38 2.83a1.45 1.45 0 0 1-2.1-1.52l1.02-6-4.35-4.24c-.86-.84-.39-2.3.8-2.48l6.02-.87 2.7-5.45Zm1.3.76-2.66 5.39c-.2.43-.62.72-1.09.8l-5.94.85 4.3 4.2c.34.33.5.8.42 1.28L8 23.1l5.32-2.8c.42-.22.92-.22 1.35 0l5.31 2.8-1.01-5.92c-.08-.47.07-.95.41-1.28l4.3-4.2-5.94-.86a1.45 1.45 0 0 1-1.1-.8L14 4.67Z"]),og=Mp("Call20Regular","20",["m6.99 2.07-.72.21a3.5 3.5 0 0 0-2.45 2.86c-.3 2.06.36 4.48 1.96 7.25 1.6 2.77 3.36 4.55 5.3 5.33a3.5 3.5 0 0 0 3.7-.7l.55-.52a2 2 0 0 0 .25-2.62L14.22 12a1.5 1.5 0 0 0-1.65-.56l-2.05.63-.06.01c-.22.04-.74-.45-1.4-1.58-.67-1.18-.82-1.87-.63-2.04l1.05-.98a2.5 2.5 0 0 0 .57-2.85l-.66-1.47a2 2 0 0 0-2.4-1.1Zm1.49 1.5.66 1.47a1.5 1.5 0 0 1-.35 1.71l-1.04.98c-.67.63-.45 1.71.45 3.27.85 1.47 1.62 2.19 2.45 2.06l.12-.02 2.09-.64a.5.5 0 0 1 .55.19l1.36 1.88a1 1 0 0 1-.13 1.3l-.54.52a2.5 2.5 0 0 1-2.65.5c-1.7-.68-3.3-2.3-4.8-4.9-1.5-2.59-2.1-4.8-1.84-6.61a2.5 2.5 0 0 1 1.75-2.04l.72-.22a1 1 0 0 1 1.2.55Z"]),lg=Mp("CallEnd20Filled","20",["m17.96 10.94-.16.83c-.15.78-.87 1.3-1.7 1.22l-1.63-.16c-.72-.07-1.25-.59-1.47-1.33-.3-1-.5-1.75-.5-1.75a6.63 6.63 0 0 0-5 0s-.2.75-.5 1.75c-.2.67-.5 1.26-1.2 1.33l-1.63.16c-.81.08-1.6-.43-1.82-1.2l-.25-.84c-.25-.82-.03-1.7.58-2.28C4.1 7.3 6.67 6.51 9.99 6.5c3.33 0 5.6.78 7.16 2.16.66.58.97 1.46.8 2.28Z"]),cg=Mp("CallMissed20Filled","20",["m17.8 7.77.16-.83c.16-.82-.15-1.7-.8-2.28-1.57-1.38-3.84-2.16-7.17-2.16-3.32 0-5.89.79-7.31 2.17-.6.59-.83 1.46-.58 2.28l.25.83A1.74 1.74 0 0 0 4.17 9l1.63-.16c.7-.07 1-.66 1.2-1.33.3-1 .5-1.75.5-1.75a6.63 6.63 0 0 1 5 0s.2.75.5 1.75c.22.74.75 1.26 1.47 1.33l1.63.16c.83.08 1.55-.44 1.7-1.22ZM9.5 11.5c.28 0 .5.22.5.5v1.5h1a.5.5 0 1 1 0 1H9.5A.5.5 0 0 1 9 14v-2c0-.28.22-.5.5-.5Zm-4 2a4.5 4.5 0 1 1 9 0 4.5 4.5 0 0 1-9 0ZM10 10a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7Z"]),dg=Mp("CallPause20Filled","20",["M3.55 2.44a4.1 4.1 0 0 1 2.99-.32c.5.12.94.45 1.2.9l.9 1.57a2.5 2.5 0 0 1-.84 3.36l-.79.5c-.32.2-.44.52-.37.77.27.9.86 1.9 1.52 2.58.19.2.54.25.9.05l.43-.26a2.5 2.5 0 0 1 3.44.94l.8 1.44c.27.47.31 1.03.12 1.53a3.9 3.9 0 0 1-1.96 2.22c-.9.41-1.94.4-2.88-.24-1.5-1-3.3-2.68-4.94-5.48a13.27 13.27 0 0 1-2.03-7.06 2.87 2.87 0 0 1 1.51-2.5ZM13 2.5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Zm3 0a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Z"]),ug=Mp("CallPause20Regular","20",["M3.55 2.44a4.1 4.1 0 0 1 2.99-.32c.5.12.94.45 1.2.9l.97 1.7a2.5 2.5 0 0 1-.67 3.24l-.6.45c-.28.22-.4.52-.34.77.18.82.59 1.57 1.15 2.13.17.16.47.22.8.1l.66-.26a2.5 2.5 0 0 1 3.07 1.11l.95 1.7c.27.48.31 1.04.12 1.54a3.9 3.9 0 0 1-1.96 2.22c-.9.41-1.94.4-2.88-.24-1.5-1-3.3-2.68-4.94-5.48a13.27 13.27 0 0 1-2.03-7.06 2.87 2.87 0 0 1 1.51-2.5Zm.49.87c-.59.33-.98.89-1 1.66-.04 1.61.33 3.85 1.9 6.53a15.3 15.3 0 0 0 4.62 5.15 1.9 1.9 0 0 0 1.91.16 2.91 2.91 0 0 0 1.45-1.65.84.84 0 0 0-.06-.7l-.95-1.7a1.5 1.5 0 0 0-1.85-.68l-.66.26c-.58.22-1.33.2-1.85-.32A5.32 5.32 0 0 1 6.13 9.4c-.17-.72.2-1.4.71-1.78l.6-.46c.6-.45.78-1.29.4-1.94l-.97-1.7a.93.93 0 0 0-.58-.43 3.1 3.1 0 0 0-2.25.22ZM13 2.5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Zm3 0a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0v-6Z"]),hg=Mp("CameraSwitch24Regular","24",["M21.25 7.5c.38 0 .7.28.74.65l.01.1v8.5a3.25 3.25 0 0 1-3.07 3.24l-.18.01H6.06l.72.72c.27.27.3.68.07.98l-.07.08a.75.75 0 0 1-.98.07l-.08-.07-2-2-.06-.07-.01-.01.07.08a.75.75 0 0 1 0-1.06l2-2a.75.75 0 0 1 1.13.98l-.07.08-.72.72h12.69c.92 0 1.67-.7 1.74-1.6l.01-.15v-8.5c0-.41.34-.75.75-.75ZM18.2 2.15l.08.07 2 2 .07.08-.07-.08a.75.75 0 0 1 0 1.06l-2 2a.75.75 0 0 1-1.13-.98l.07-.08.72-.72H5.25c-.92 0-1.67.7-1.74 1.6l-.01.15v8.5a.75.75 0 0 1-1.5.1v-8.6a3.25 3.25 0 0 1 3.07-3.24L5.25 4h12.69l-.72-.72a.75.75 0 0 1-.07-.98l.07-.08a.75.75 0 0 1 .98-.07ZM12 8a4 4 0 1 1 0 8 4 4 0 0 1 0-8Zm0 1.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"]),pg=Mp("Chat20Filled","20",["M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm.5 9H7.41a.5.5 0 0 0 0 1H10.59a.5.5 0 0 0 0-1h-.09Zm2-3H7.41a.5.5 0 0 0 0 1h5.18a.5.5 0 0 0 0-1h-.09Z"]),gg=Mp("Chat20Regular","20",["M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"]),mg=Mp("Checkmark20Regular","20",["M3.37 10.17a.5.5 0 0 0-.74.66l4 4.5c.19.22.52.23.72.02l10.5-10.5a.5.5 0 0 0-.7-.7L7.02 14.27l-3.65-4.1Z"]),fg=Mp("CheckmarkCircle16Regular","16",["M8 2a6 6 0 1 1 0 12A6 6 0 0 1 8 2Zm0 1a5 5 0 1 0 0 10A5 5 0 0 0 8 3Zm-.75 6.04 2.87-2.88a.5.5 0 0 1 .77.64l-.06.07L7.6 10.1a.5.5 0 0 1-.63.06l-.07-.06-1.75-1.75a.5.5 0 0 1 .63-.76l.07.06 1.4 1.4 2.87-2.89-2.87 2.88Z"]),vg=Mp("ChevronLeft20Regular","20",["M12.35 15.85a.5.5 0 0 1-.7 0L6.16 10.4a.55.55 0 0 1 0-.78l5.49-5.46a.5.5 0 1 1 .7.7L7.2 10l5.16 5.15c.2.2.2.5 0 .7Z"]),Sg=Mp("ChevronRight20Regular","20",["M7.65 4.15c.2-.2.5-.2.7 0l5.49 5.46c.21.22.21.57 0 .78l-5.49 5.46a.5.5 0 0 1-.7-.7L12.8 10 7.65 4.85a.5.5 0 0 1 0-.7Z"]),yg=Mp("Circle16Regular","16",["M8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12Zm0-1A5 5 0 1 1 8 3a5 5 0 0 1 0 10Z"]),Cg=Mp("Circle20Regular","20",["M10 3a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm-8 7a8 8 0 1 1 16 0 8 8 0 0 1-16 0Z"]),_g=Mp("ClosedCaption20Regular","20",["M6.4 7.24c.82-.41 1.8-.24 2.45.4a.5.5 0 0 1-.7.71 1.12 1.12 0 0 0-1.3-.22C6.44 8.34 6 8.9 6 10s.44 1.66.85 1.87c.43.21.95.13 1.3-.22a.5.5 0 0 1 .7.7c-.65.65-1.63.82-2.45.41C5.56 12.34 5 11.39 5 10c0-1.39.56-2.34 1.4-2.76Zm7.95.4a2.12 2.12 0 0 0-2.45-.4c-.84.42-1.4 1.37-1.4 2.76 0 1.39.56 2.34 1.4 2.76.82.41 1.8.24 2.45-.4a.5.5 0 0 0-.7-.71c-.35.35-.87.43-1.3.22-.41-.21-.85-.76-.85-1.87s.44-1.66.85-1.87c.43-.21.95-.13 1.3.22a.5.5 0 0 0 .7-.7ZM2 7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H5a3 3 0 0 1-3-3V7Zm3-2a2 2 0 0 0-2 2v6c0 1.1.9 2 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H5Z"]),Eg=Mp("ClosedCaptionOff20Regular","20",["M2.85 2.15a.5.5 0 1 0-.7.7l1.48 1.48A3 3 0 0 0 2 7v6a3 3 0 0 0 3 3h10l.28-.01 1.87 1.86a.5.5 0 0 0 .7-.7l-1.48-1.48-.76-.77-2.93-2.93-1.06-1.05L10.5 9.8 8.94 8.23 7.77 7.06 4.72 4.01 2.85 2.15ZM14.3 15H5a2 2 0 0 1-2-2V7a2 2 0 0 1 1.39-1.9l2.1 2.1-.09.04C5.56 7.66 5 8.61 5 10c0 1.39.56 2.34 1.4 2.76.82.41 1.8.24 2.45-.4a.5.5 0 1 0-.7-.71c-.35.35-.87.43-1.3.22C6.44 11.66 6 11.1 6 10s.44-1.66.85-1.87c.15-.07.3-.1.46-.11L14.3 15Zm2.9.06-.72-.7A2 2 0 0 0 17 13V7a2 2 0 0 0-2-2H7.12l-1-1H15a3 3 0 0 1 3 3v6c0 .8-.31 1.52-.82 2.06Zm-5.65-5.64-.81-.81c.24-.65.65-1.11 1.17-1.37.82-.41 1.8-.24 2.45.4a.5.5 0 0 1-.7.71 1.12 1.12 0 0 0-1.3-.22c-.33.17-.68.56-.8 1.3Z"]),Tg=Mp("People20Filled","20",["M6.75 10a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5Zm5.69 5.14c.53.22 1.2.36 2.06.36 4 0 4-3 4-3 0-.83-.67-1.5-1.5-1.5h-4.63c.4.48.63 1.09.63 1.75v.36a2.94 2.94 0 0 1-.02.25 4.62 4.62 0 0 1-.54 1.78ZM17 7.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0ZM1.5 13c0-1.1.9-2 2-2H10a2 2 0 0 1 2 2s0 4-5.25 4-5.25-4-5.25-4Zm11.5.1v.07Z"]),bg=Mp("People20Regular","20",["M4.5 6.75a2.25 2.25 0 1 1 4.5 0 2.25 2.25 0 0 1-4.5 0ZM6.75 3.5a3.25 3.25 0 1 0 0 6.5 3.25 3.25 0 0 0 0-6.5Zm5.69 11.65c.53.21 1.21.35 2.06.35 1.88 0 2.92-.67 3.47-1.43a2.92 2.92 0 0 0 .53-1.5v-.07c0-.83-.67-1.5-1.5-1.5h-4.63c.24.29.42.63.53 1H17c.28 0 .5.22.5.5v.1l-.04.22c-.04.18-.13.42-.3.66-.33.46-1.04 1.02-2.66 1.02-.73 0-1.28-.11-1.69-.28-.08.28-.2.6-.37.93ZM1.5 13c0-1.1.9-2 2-2H10a2 2 0 0 1 2 2V13.08a1.43 1.43 0 0 1-.01.18 3.95 3.95 0 0 1-.67 1.8C10.62 16.09 9.26 17 6.75 17c-2.51 0-3.87-.92-4.57-1.93a3.95 3.95 0 0 1-.68-1.99V13Zm1 .06v.1l.06.33c.07.27.2.64.45 1C3.49 15.2 4.5 16 6.75 16s3.26-.8 3.74-1.5a2.95 2.95 0 0 0 .5-1.42l.01-.02V13a1 1 0 0 0-1-1H3.5a1 1 0 0 0-1 1v.06ZM13 7.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0ZM14.5 5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"]),Ig=Mp("PersonAdd20Regular","20",["M9 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8ZM6 6a3 3 0 1 1 6 0 3 3 0 0 1-6 0Zm-2 5a2 2 0 0 0-2 2c0 1.7.83 2.97 2.13 3.8A9.14 9.14 0 0 0 9 18c.41 0 .82-.02 1.21-.06A5.5 5.5 0 0 1 9.6 17 12 12 0 0 1 9 17a8.16 8.16 0 0 1-4.33-1.05A3.36 3.36 0 0 1 3 13a1 1 0 0 1 1-1h5.6c.18-.36.4-.7.66-1H4Zm10.5 8a4.5 4.5 0 1 0 0-9 4.5 4.5 0 0 0 0 9Zm0-7c.28 0 .5.22.5.5V14h1.5a.5.5 0 0 1 0 1H15v1.5a.5.5 0 0 1-1 0V15h-1.5a.5.5 0 0 1 0-1H14v-1.5c0-.28.22-.5.5-.5Z"]),wg=Mp("PersonDelete20Filled","20",["M5 6a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm-3 7a2 2 0 0 1 2-2h6.26a5.48 5.48 0 0 0-.05 6.94c-.4.04-.8.06-1.21.06a9.14 9.14 0 0 1-4.87-1.2A4.35 4.35 0 0 1 2 13Zm17 1.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-2.65-1.15a.5.5 0 0 0-.7-.7l-1.15 1.14-1.15-1.14a.5.5 0 0 0-.7.7l1.14 1.15-1.14 1.15a.5.5 0 0 0 .7.7l1.15-1.14 1.15 1.14a.5.5 0 0 0 .7-.7l-1.14-1.15 1.14-1.15Z"]),Rg=Mp("PersonSquare20Regular","20",["M10 5a2 2 0 1 0 0 4 2 2 0 0 0 0-4Zm2.5 5h-5c-.83 0-1.5.67-1.5 1.5 0 1.12.46 2.01 1.21 2.61.74.6 1.74.89 2.79.89s2.05-.29 2.79-.89c.75-.6 1.21-1.5 1.21-2.61 0-.83-.67-1.5-1.5-1.5ZM6 3a3 3 0 0 0-3 3v8a3 3 0 0 0 3 3h8a3 3 0 0 0 3-3V6a3 3 0 0 0-3-3H6ZM4 6c0-1.1.9-2 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6Z"]),Ag=Mp("PersonVoice20Regular","20",["M17.13 1.06a.5.5 0 0 1 .68.2 9.96 9.96 0 0 1 0 9.48.5.5 0 1 1-.88-.48 8.96 8.96 0 0 0 0-8.52.5.5 0 0 1 .2-.68Zm-2.32 1.97a.5.5 0 0 1 .65.27 6.98 6.98 0 0 1 0 5.4.5.5 0 1 1-.92-.39 5.98 5.98 0 0 0 0-4.62.5.5 0 0 1 .27-.66ZM5 6a4 4 0 1 1 8 0 4 4 0 0 1-8 0Zm4-3a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM2 13a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2c0 1.7-.83 2.97-2.13 3.8A9.14 9.14 0 0 1 9 18a9.14 9.14 0 0 1-4.87-1.2A4.35 4.35 0 0 1 2 13Zm2-1a1 1 0 0 0-1 1c0 1.3.62 2.28 1.67 2.95A8.16 8.16 0 0 0 9 17c1.74 0 3.26-.36 4.33-1.05A3.36 3.36 0 0 0 15 13a1 1 0 0 0-1-1H4Z"]),Pg=Mp("Pin16Filled","16",["M10.06 2.45a1.5 1.5 0 0 0-2.39.35L5.65 6.59l-2.8.94a.5.5 0 0 0-.2.82l2.14 2.15-2.64 2.65L2 14l.85-.15 2.65-2.64 2.15 2.14a.5.5 0 0 0 .82-.2l.94-2.8 3.78-2.03a1.5 1.5 0 0 0 .35-2.38l-3.48-3.5Z"]),Mg=Mp("Pin16Regular","16",["M10.06 2.45a1.5 1.5 0 0 0-2.39.35L5.65 6.59l-2.8.94a.5.5 0 0 0-.2.82l2.14 2.15-2.64 2.65L2 14l.85-.15 2.65-2.64 2.15 2.14a.5.5 0 0 0 .82-.2l.94-2.8 3.78-2.03a1.5 1.5 0 0 0 .35-2.38l-3.48-3.5Zm-1.5.82a.5.5 0 0 1 .8-.12l3.48 3.5a.5.5 0 0 1-.12.8l-3.96 2.1a.5.5 0 0 0-.23.3l-.75 2.22-3.85-3.85 2.23-.75a.5.5 0 0 0 .28-.23l2.12-3.97Z"]),kg=Mp("PinOff16Regular","16",["m9.56 10.27 4.59 4.58a.5.5 0 0 0 .7-.7l-13-13a.5.5 0 1 0-.7.7l4.58 4.59-.08.15-2.8.94a.5.5 0 0 0-.2.82l2.14 2.15-2.64 2.65L2 14l.85-.15 2.65-2.64 2.15 2.14a.5.5 0 0 0 .82-.2l.94-2.8.15-.08Zm-.74-.74-.06.03a.5.5 0 0 0-.23.28l-.75 2.23-3.85-3.85 2.23-.75a.5.5 0 0 0 .28-.23l.03-.06 2.35 2.35Zm3.9-2.09-2.06 1.1.74.74 1.79-.96a1.5 1.5 0 0 0 .35-2.38l-3.48-3.5a1.5 1.5 0 0 0-2.39.36l-.95 1.8.73.73 1.1-2.06a.5.5 0 0 1 .8-.12l3.49 3.5a.5.5 0 0 1-.12.8Z"]),Dg=Mp("Play20Regular","20",["M17.22 8.69a1.5 1.5 0 0 1 0 2.62l-10 5.5A1.5 1.5 0 0 1 5 15.5v-11A1.5 1.5 0 0 1 7.22 3.2l10 5.5Zm-.48 1.75a.5.5 0 0 0 0-.88l-10-5.5A.5.5 0 0 0 6 4.5v11c0 .38.4.62.74.44l10-5.5Z"]),Og=Mp("Grid20Regular","20",["M7.5 11c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4A1.5 1.5 0 0 1 2 16.5v-4c0-.83.67-1.5 1.5-1.5h4Zm9 0c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4a1.5 1.5 0 0 1-1.5-1.5v-4c0-.83.67-1.5 1.5-1.5h4Zm-9 1h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm9 0h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm-9-10C8.33 2 9 2.67 9 3.5v4C9 8.33 8.33 9 7.5 9h-4A1.5 1.5 0 0 1 2 7.5v-4C2 2.67 2.67 2 3.5 2h4Zm9 0c.83 0 1.5.67 1.5 1.5v4c0 .83-.67 1.5-1.5 1.5h-4A1.5 1.5 0 0 1 11 7.5v-4c0-.83.67-1.5 1.5-1.5h4Zm-9 1h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Zm9 0h-4a.5.5 0 0 0-.5.5v4c0 .28.22.5.5.5h4a.5.5 0 0 0 .5-.5v-4a.5.5 0 0 0-.5-.5Z"]),Ng=Mp("HandRight20Regular","20",["M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z"]),Lg=Mp("HandRightOff20Regular","20",["M4 6c0-.36.13-.7.34-.95l-2.2-2.2a.5.5 0 1 1 .71-.7l15 15a.5.5 0 0 1-.7.7l-3.57-3.56-.21.22c-.7.72-1.22 1.56-1.72 2.43a2.16 2.16 0 0 1-1.87 1.08H7.23c-.3 0-.6-.07-.86-.21a2.55 2.55 0 0 1-1.18-1.3l-.58-1.41c-.4-.98-.61-2.02-.61-3.08V6Zm8.87 7.58L7 7.7V9.5a.5.5 0 0 1-1 0V6.7l-.94-.93A.5.5 0 0 0 5 6v6.02c0 .93.18 1.84.53 2.7l.59 1.42c.14.34.4.61.71.78.13.07.27.1.4.1h2.55c.42 0 .8-.22 1-.58.55-.94 1.11-1.84 1.86-2.63l.23-.23ZM10 3.5v4.38l.9.9a.5.5 0 0 0 .1-.28v-4a.5.5 0 0 1 1 0v5.38l.92.92c.2-.2.4-.38.66-.51.7-.35 2.22-.57 2.4.5l-.53.4c-.4.3-.81.61-1.18.95l.7.71c.38-.34.8-.65 1.2-.96l.6-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0 1.5 1.5 0 0 0-1.96.87l.91.9V4.5a.5.5 0 0 1 1 0v1.38l1 1V3.5a.5.5 0 0 1 1 0Z"]),xg=Mp("Important20Filled","20",["M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"]),Fg=Mp("Info20Filled","20",["M18 10a8 8 0 1 0-16 0 8 8 0 0 0 16 0ZM9.5 8.91a.5.5 0 0 1 1 0V13.6a.5.5 0 0 1-1 0V8.9Zm-.25-2.16a.75.75 0 1 1 1.5 0 .75.75 0 0 1-1.5 0Z"]),Ug=Mp("MoreHorizontal20Filled","20",["M6.75 10a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0Zm5 0a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0ZM15 11.75a1.75 1.75 0 1 0 0-3.5 1.75 1.75 0 0 0 0 3.5Z"]),Bg=Mp("MoreHorizontal20Regular","20",["M6.25 10a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0Zm5 0a1.25 1.25 0 1 1-2.5 0 1.25 1.25 0 0 1 2.5 0ZM15 11.25a1.25 1.25 0 1 0 0-2.5 1.25 1.25 0 0 0 0 2.5Z"]),Vg=Mp("Open20Regular","20",["M6 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2v-2.5a.5.5 0 0 1 1 0V14a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h2.5a.5.5 0 0 1 0 1H6Zm5-.5c0-.28.22-.5.5-.5h5c.28 0 .5.22.5.5v5a.5.5 0 0 1-1 0V4.7l-4.15 4.15a.5.5 0 0 1-.7-.7L15.29 4H11.5a.5.5 0 0 1-.5-.5Z"]),Hg=Mp("ContentView20Regular","20",["M5 7a1 1 0 0 1 1-1h8a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V7Zm9 0H6v2h8V7Zm-2 4a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-1a1 1 0 0 0-1-1h-2Zm0 1h2v1h-2v-1Zm-7-.5c0-.28.22-.5.5-.5h4a.5.5 0 0 1 0 1h-4a.5.5 0 0 1-.5-.5Zm.5 1.5a.5.5 0 0 0 0 1h4a.5.5 0 0 0 0-1h-4ZM3 6a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6Zm3-2a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H6Z"]),$g=Mp("Delete20Regular","20",["M8.5 4h3a1.5 1.5 0 0 0-3 0Zm-1 0a2.5 2.5 0 0 1 5 0h5a.5.5 0 0 1 0 1h-1.05l-1.2 10.34A3 3 0 0 1 12.27 18H7.73a3 3 0 0 1-2.98-2.66L3.55 5H2.5a.5.5 0 0 1 0-1h5ZM5.74 15.23A2 2 0 0 0 7.73 17h4.54a2 2 0 0 0 1.99-1.77L15.44 5H4.56l1.18 10.23ZM8.5 7.5c.28 0 .5.22.5.5v6a.5.5 0 0 1-1 0V8c0-.28.22-.5.5-.5ZM12 8a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V8Z"]),Gg=Mp("Dialpad20Regular","20",["M6 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm0 4a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm3-7a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm3-11a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm1 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1 5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"]),jg=Mp("Prohibited16Regular","16",["M11.87 3.42a6 6 0 0 0-8.45 8.45l8.45-8.45Zm.71.7-8.45 8.46a6 6 0 0 0 8.45-8.45ZM3.05 3.06a7 7 0 1 1 9.9 9.9 7 7 0 0 1-9.9-9.9Z"]),zg=Mp("ScaleFill20Regular","20",["M6 6.5a.5.5 0 0 1 .14-.35A.5.5 0 0 1 6.5 6h2a.5.5 0 0 1 0 1h-.8l1.15 1.15a.5.5 0 1 1-.7.7L7 7.71v.79a.5.5 0 0 1-1 0v-2Zm.04 7.2a.5.5 0 0 1-.04-.2v-2a.5.5 0 0 1 1 0v.8l1.15-1.15a.5.5 0 0 1 .7.7L7.71 13h.79a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.46-.3Zm7.65-7.66a.5.5 0 0 1 .3.46v2a.5.5 0 0 1-.99 0v-.8l-1.15 1.15a.5.5 0 0 1-.7-.7L12.29 7h-.79a.5.5 0 0 1 0-1h2a.5.5 0 0 1 .2.04Zm.16 7.82a.5.5 0 0 1-.35.14h-2a.5.5 0 0 1 0-1h.8l-1.15-1.15a.5.5 0 0 1 .7-.7L13 12.29v-.79a.5.5 0 0 1 1 0v2a.5.5 0 0 1-.14.35ZM3 5c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm2-1a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1H5Z"]),Wg=Mp("ScaleFit20Regular","20",["M6.88 7.92a.5.5 0 0 1-.05.7l-1 .88H8.5a.5.5 0 0 1 0 1H5.83l1 .87a.5.5 0 1 1-.66.76l-2-1.75a.5.5 0 0 1 0-.76l2-1.75a.5.5 0 0 1 .7.05Zm7.29 2.58-1 .87a.5.5 0 0 0 .66.76l2-1.75a.5.5 0 0 0 0-.76l-2-1.75a.5.5 0 0 0-.66.76l1 .87H11.5a.5.5 0 0 0 0 1h2.67ZM2 6c0-1.1.9-2 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6Zm2-1a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H4Z"]),qg=Mp("Send20Filled","20",["M2.72 2.05a.5.5 0 0 0-.7.58l1.5 5.62c.05.19.2.33.4.36l6.85 1.14c.28.05.28.45 0 .5l-6.85 1.14a.5.5 0 0 0-.4.36l-1.5 5.62a.5.5 0 0 0 .7.58l15-7.5a.5.5 0 0 0 0-.9l-15-7.5Z"],{flipInRtl:!0}),Kg=Mp("Send20Regular","20",["M2.18 2.11a.5.5 0 0 1 .54-.06l15 7.5a.5.5 0 0 1 0 .9l-15 7.5a.5.5 0 0 1-.7-.58L3.98 10 2.02 2.63a.5.5 0 0 1 .16-.52Zm2.7 8.39-1.61 6.06L16.38 10 3.27 3.44 4.88 9.5h6.62a.5.5 0 1 1 0 1H4.88Z"],{flipInRtl:!0}),Jg=Mp("Settings20Filled","20",["M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54ZM8 10a2 2 0 1 0 4 0 2 2 0 0 0-4 0Z"]),Yg=Mp("Settings20Regular","20",["M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54Zm1.06 0 1.3 1.1a2 2 0 0 1 0 3.04l-1.3 1.1c.3.79.72 1.51 1.25 2.16l1.6-.58a2 2 0 0 1 2.63 1.53l.3 1.67a7.56 7.56 0 0 0 2.5 0l.3-1.67a2 2 0 0 1 2.64-1.53l1.6.58a7.5 7.5 0 0 0 1.24-2.16l-1.3-1.1a2 2 0 0 1 0-3.04l1.3-1.1a7.5 7.5 0 0 0-1.25-2.16l-1.6.58a2 2 0 0 1-2.63-1.53l-.3-1.67a7.55 7.55 0 0 0-2.5 0l-.3 1.67A2 2 0 0 1 5.81 5.8l-1.6-.58a7.5 7.5 0 0 0-1.24 2.16ZM7.5 10a2.5 2.5 0 1 1 5 0 2.5 2.5 0 0 1-5 0Zm1 0a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0Z"]),Qg=Mp("Dismiss16Regular","16",["m2.59 2.72.06-.07a.5.5 0 0 1 .63-.06l.07.06L8 7.29l4.65-4.64a.5.5 0 0 1 .7.7L8.71 8l4.64 4.65c.18.17.2.44.06.63l-.06.07a.5.5 0 0 1-.63.06l-.07-.06L8 8.71l-4.65 4.64a.5.5 0 0 1-.7-.7L7.29 8 2.65 3.35a.5.5 0 0 1-.06-.63l.06-.07-.06.07Z"]),Zg=Mp("Dismiss20Regular","20",["m4.09 4.22.06-.07a.5.5 0 0 1 .63-.06l.07.06L10 9.29l5.15-5.14a.5.5 0 0 1 .63-.06l.07.06c.18.17.2.44.06.63l-.06.07L10.71 10l5.14 5.15c.18.17.2.44.06.63l-.06.07a.5.5 0 0 1-.63.06l-.07-.06L10 10.71l-5.15 5.14a.5.5 0 0 1-.63.06l-.07-.06a.5.5 0 0 1-.06-.63l.06-.07L9.29 10 4.15 4.85a.5.5 0 0 1-.06-.63l.06-.07-.06.07Z"]),Xg=Mp("DividerTall24Regular","24",["M11.25 2.75v18.5a.75.75 0 0 0 1.5 0V2.75a.75.75 0 0 0-1.5 0Z"]),em=Mp("Edit20Regular","20",["M17.18 2.93a2.97 2.97 0 0 0-4.26-.06l-9.37 9.38c-.33.33-.56.74-.66 1.2l-.88 3.94a.5.5 0 0 0 .6.6l3.93-.87c.46-.1.9-.34 1.23-.68l9.36-9.36a2.97 2.97 0 0 0 .05-4.15Zm-3.55.65a1.97 1.97 0 1 1 2.8 2.8l-.68.66-2.8-2.79.68-.67Zm-1.38 1.38 2.8 2.8-7.99 7.97c-.2.2-.46.35-.74.41l-3.16.7.7-3.18c.07-.27.2-.51.4-.7l8-8Z"]),tm=Mp("Emoji20Regular","20",["M18 10a8 8 0 1 0-16 0 8 8 0 0 0 16 0ZM3 10a7 7 0 1 1 14 0 7 7 0 0 1-14 0Zm10.5-1.5a1 1 0 1 0-2 0 1 1 0 0 0 2 0Zm-5 0a1 1 0 1 0-2 0 1 1 0 0 0 2 0Zm-1.61 4.01a.5.5 0 1 0-.78.63 5 5 0 0 0 7.78 0 .5.5 0 1 0-.78-.63 4 4 0 0 1-6.22 0Z"]),im=Mp("ErrorCircle16Regular","16",["M8 2a6 6 0 1 1 0 12A6 6 0 0 1 8 2Zm0 1a5 5 0 1 0 0 10A5 5 0 0 0 8 3Zm0 7a.75.75 0 1 1 0 1.5.75.75 0 0 1 0-1.5Zm0-5.5a.5.5 0 0 1 .5.41V8.5a.5.5 0 0 1-1 .09V5c0-.28.22-.5.5-.5Z"]),nm=Mp("Eye16Regular","16",["M2.98 8.62a.5.5 0 0 1-.6.36c-.44-.11-.36-.6-.36-.6l.01-.07.05-.14A6.7 6.7 0 0 1 3.2 6.19C4.1 5.08 5.6 4 8 4s3.9 1.09 4.8 2.18a6.7 6.7 0 0 1 1.18 2.17v.02a.5.5 0 0 1-.96.26L13 8.6a3.05 3.05 0 0 0-.2-.52 5.7 5.7 0 0 0-.78-1.26A4.96 4.96 0 0 0 8 5c-2.04 0-3.29.91-4.03 1.82A5.7 5.7 0 0 0 3 8.6v.02ZM8 7a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5ZM6.5 9.5a1.5 1.5 0 1 1 3 0 1.5 1.5 0 0 1-3 0Z"]),rm=Mp("ArrowClockwise16Regular","16",["M3 8a5 5 0 0 1 9-3h-2a.5.5 0 0 0 0 1h3a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-1 0v1.53A5.99 5.99 0 0 0 2 8a6 6 0 0 0 11.98.54.5.5 0 0 0-1-.08A5 5 0 0 1 3 8Z"]),am=Mp("ArrowDownload20Regular","20",["M15.5 17a.5.5 0 0 1 .09 1H4.5a.5.5 0 0 1-.09-1H15.5ZM10 2a.5.5 0 0 1 .5.41V14.3l3.64-3.65a.5.5 0 0 1 .64-.06l.07.06c.17.17.2.44.06.63l-.06.07-4.5 4.5a.5.5 0 0 1-.25.14L10 16a.5.5 0 0 1-.4-.2l-4.46-4.45a.5.5 0 0 1 .64-.76l.07.06 3.65 3.64V2.5c0-.27.22-.5.5-.5Z"]),sm=Mp("Table20Filled","20",["M13 17h1.5a2.5 2.5 0 0 0 2.5-2.5V13h-4v4Zm0-5V8h4v4h-4Zm-1 0H8V8h4v4Zm-4 1h4v4H8v-4Zm-1-1V8H3v4h4Zm-4 1h4v4H5.5A2.5 2.5 0 0 1 3 14.5V13Zm10-6h4V5.5A2.5 2.5 0 0 0 14.5 3H13v4Zm-1-4v4H8V3h4ZM7 3v4H3V5.5A2.5 2.5 0 0 1 5.5 3H7Z"]),om=Mp("Table20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h9a2.5 2.5 0 0 0 2.5-2.5v-9Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5Zm8-1.5v3H8v-3h4Zm2.5 3H13v-3h3V14.64A1.5 1.5 0 0 1 14.5 16ZM12 8v4H8V8h4Zm1 0h3v4h-3V8Zm-1-4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Z"]),lm=Mp("TableAdd20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h4.1c-.16-.32-.3-.65-.4-1H8v-3h1.2c.1-.35.24-.68.4-1H8V8h4v1.6c.32-.16.65-.3 1-.4V8h3v1.2c.35.1.68.24 1 .4V5.5Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5ZM12 4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Zm12 6.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-4-2a.5.5 0 0 0-1 0V14h-1.5a.5.5 0 0 0 0 1H14v1.5a.5.5 0 0 0 1 0V15h1.5a.5.5 0 0 0 0-1H15v-1.5Z"]),cm=Mp("TableDismiss20Regular","20",["M17 5.5A2.5 2.5 0 0 0 14.5 3h-9A2.5 2.5 0 0 0 3 5.5v9A2.5 2.5 0 0 0 5.5 17h4.1c-.16-.32-.3-.65-.4-1H8v-3h1.2c.1-.35.24-.68.4-1H8V8h4v1.6c.32-.16.65-.3 1-.4V8h3v1.2c.35.1.68.24 1 .4V5.5Zm-13 9V13h3v3H5.36A1.5 1.5 0 0 1 4 14.5ZM12 4v3H8V4h4Zm1 0H14.64A1.5 1.5 0 0 1 16 5.5V7h-3V4ZM7 4v3H4V5.36A1.5 1.5 0 0 1 5.5 4H7Zm0 4v4H4V8h3Zm12 6.5a4.5 4.5 0 1 1-9 0 4.5 4.5 0 0 1 9 0Zm-3.8 0 1.15-1.15a.5.5 0 0 0-.7-.7l-1.15 1.14-1.15-1.14a.5.5 0 0 0-.7.7l1.14 1.15-1.14 1.15a.5.5 0 0 0 .7.7l1.15-1.14 1.15 1.14a.5.5 0 0 0 .7-.7l-1.14-1.15Z"]),dm=Mp("TableSimple20Regular","20",["M3 5.5A2.5 2.5 0 0 1 5.5 3h9A2.5 2.5 0 0 1 17 5.5v9a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 3 14.5v-9Zm1 5v4c0 .83.67 1.5 1.5 1.5h4v-5.5H4Zm5.5-1V4h-4C4.67 4 4 4.67 4 5.5v4h5.5Zm1 1V16h4c.83 0 1.5-.67 1.5-1.5v-4h-5.5Zm5.5-1v-4c0-.83-.67-1.5-1.5-1.5h-4v5.5H16Z"]),um=Mp("TextBold20Regular","20",["M5.5 4.25C5.5 3.56 6.06 3 6.75 3h3.5a4 4 0 0 1 3.17 6.44c.9.7 1.58 1.8 1.58 3.31A4.23 4.23 0 0 1 10.75 17h-4c-.69 0-1.25-.56-1.25-1.25V4.25ZM8 11v3.5h2.75c.81 0 1.75-.62 1.75-1.75S11.56 11 10.75 11H8Zm0-2.5h2.25a1.5 1.5 0 1 0 0-3H8v3Z"]),hm=Mp("TextBulletList20Regular","20",["M3 5.5a1 1 0 1 0 0-2 1 1 0 0 0 0 2Zm3-1c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h11a.5.5 0 0 0 0-1h-11Zm-2.5.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Zm-1-4a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"]),pm=Mp("TextEditStyle20Filled","20",["M14.09 6.7a2.26 2.26 0 0 1 3.07-.12l.13.12.12.13c.73.85.73 2.1 0 2.96l-.12.13-6.87 6.9a1.5 1.5 0 0 1-.55.35l-.16.05-3.08.76a.5.5 0 0 1-.62-.53l.01-.08.8-3.07c.05-.21.15-.4.28-.57l.1-.12 6.89-6.9ZM6.42 2.23l.05.08 2.98 7.63-.77.78L8 9H4l-1.03 2.68a.5.5 0 0 1-.56.3l-.1-.02a.5.5 0 0 1-.3-.56l.02-.08 3.5-9a.5.5 0 0 1 .9-.1ZM6 3.87 4.4 8H7.6l-1.6-4.13Z"]),gm=Mp("TextEditStyle20Regular","20",["M14.09 6.7a2.26 2.26 0 0 1 3.07-.12l.13.12.12.13c.73.85.73 2.1 0 2.96l-.12.13-6.87 6.9a1.5 1.5 0 0 1-.55.35l-.16.05-3.08.76a.5.5 0 0 1-.62-.53l.01-.08.8-3.07c.05-.21.15-.4.28-.57l.1-.12 6.89-6.9Zm2.5.7a1.26 1.26 0 0 0-1.7-.08l-.1.09-6.88 6.9a.5.5 0 0 0-.1.15l-.03.08-.58 2.27 2.27-.56a.5.5 0 0 0 .12-.05l.05-.03.07-.06 6.87-6.9c.5-.5.5-1.3 0-1.8ZM6.41 2.24l.05.08 2.98 7.63-.77.78L8 9H4l-1.03 2.68a.5.5 0 0 1-.56.3l-.1-.02a.5.5 0 0 1-.3-.56l.02-.08 3.5-9a.5.5 0 0 1 .9-.1ZM6 3.87 4.4 8H7.6l-1.6-4.13Z"]),mm=Mp("TextIndentDecrease20Regular","20",["M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5ZM3.56 7.73a.5.5 0 0 1 .7.7L3.22 9.5l1.06 1.06a.5.5 0 1 1-.7.7l-1.42-1.4a.5.5 0 0 1 0-.71l1.41-1.42ZM6.5 9a.5.5 0 0 0 0 1h11a.5.5 0 1 0 0-1h-11ZM6 14.5c0-.28.22-.5.5-.5h6a.5.5 0 1 1 0 1h-6a.5.5 0 0 1-.5-.5Z"],{flipInRtl:!0}),fm=Mp("TextIndentIncrease20Regular","20",["M6 4.5c0-.28.22-.5.5-.5h8a.5.5 0 0 1 0 1h-8a.5.5 0 0 1-.5-.5Zm0 5c0-.28.22-.5.5-.5h11a.5.5 0 0 1 0 1h-11a.5.5 0 0 1-.5-.5Zm.5 4.5a.5.5 0 0 0 0 1h6a.5.5 0 0 0 0-1h-6ZM2.85 7.73a.5.5 0 1 0-.7.7L3.2 9.5l-1.06 1.06a.5.5 0 1 0 .7.7l1.42-1.4a.5.5 0 0 0 0-.71L2.85 7.73Z"],{flipInRtl:!0}),vm=Mp("TextItalic20Regular","20",["M16 3a.5.5 0 0 1 0 1h-3.16L8.23 16h3.27a.5.5 0 0 1 0 1H4a.5.5 0 0 1 0-1h3.16l4.61-12H8.5a.5.5 0 0 1 0-1H16Z"]),Sm=Mp("TextNumberListLtr20Regular","20",["M5 1.5a.5.5 0 0 0-.39-.49.5.5 0 0 0-.56.27l-.07.12a2.96 2.96 0 0 1-1.2 1.15.5.5 0 1 0 .44.9c.3-.15.56-.34.78-.53V5.5a.5.5 0 0 0 1 0v-4ZM2.65 7.65a.5.5 0 0 0 .7.7l.05-.04.2-.12C3.76 8.09 4 8 4.3 8c.23 0 .41.06.53.15.1.07.16.17.16.35a.5.5 0 0 1-.21.44c-.15.12-.35.22-.62.35l-.14.08c-.32.15-.7.36-1 .7-.33.35-.53.81-.53 1.43 0 .28.22.5.5.5h2.5a.5.5 0 0 0 0-1H3.59c.04-.1.1-.2.17-.27a2.38 2.38 0 0 1 .83-.53c.27-.13.59-.29.84-.5.33-.27.57-.65.57-1.2 0-.5-.22-.9-.57-1.15A1.92 1.92 0 0 0 4.33 7h-.01a2.5 2.5 0 0 0-1.66.63v.01h-.01Zm.01-.02-.01.02s.1-.1.01-.02ZM4.25 15a.5.5 0 1 0 0 1c.34 0 .53.1.63.18.1.09.13.2.13.3-.01.2-.19.52-.76.52-.41 0-.63-.1-.72-.17a.42.42 0 0 1-.1-.07.5.5 0 0 0-.88.46v.01l.02.02a.8.8 0 0 0 .1.15c.07.08.17.17.3.27.28.18.7.33 1.28.33 1.03 0 1.73-.67 1.76-1.48.01-.37-.12-.74-.4-1.02.28-.28.41-.65.4-1.02-.03-.8-.73-1.48-1.76-1.48-.59 0-1 .15-1.28.33a1.4 1.4 0 0 0-.4.42l-.01.01v.01a.5.5 0 0 0 .87.48.42.42 0 0 1 .1-.08c.1-.07.3-.17.72-.17.57 0 .75.33.76.52 0 .1-.04.21-.13.3-.1.08-.29.18-.63.18Zm-.82-.75.01-.02v.02ZM8.5 4a.5.5 0 1 0 0 1h8a.5.5 0 0 0 0-1h-8Zm0 5a.5.5 0 1 0 0 1h8a.5.5 0 0 0 0-1h-8ZM8 14.5c0-.28.22-.5.5-.5h8a.5.5 0 1 1 0 1h-8a.5.5 0 0 1-.5-.5Z"]),ym=Mp("TextUnderlineCharacterU20Regular","20",["M7 3.5a.5.5 0 0 0-1 0V10a4 4 0 0 0 8 0V3.5a.5.5 0 0 0-1 0V10a3 3 0 1 1-6 0V3.5ZM5.5 16a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9Z"]),Cm=Mp("Translate20Regular","20",["M4.08 4.22c.7-.21 1.7-.34 2.84 0 1.01.3 1.56.9 1.83 1.56.26.63.26 1.27.26 1.67v5.05a.5.5 0 0 1-1 0v-.53c-.31.19-.67.38-1.05.55-.78.34-1.74.6-2.64.42a2.97 2.97 0 0 1-2.25-2.09c-.29-.97-.08-2.1.8-2.84a4.57 4.57 0 0 1 3.21-1c.71.03 1.38.17 1.93.32 0-.37-.03-.79-.18-1.17-.16-.4-.48-.77-1.19-.98a4.04 4.04 0 0 0-3.15.37h-.01a.5.5 0 0 1-.57-.82h.01l.02-.02a2.45 2.45 0 0 1 .3-.17c.2-.1.48-.22.84-.32ZM6.04 8a3.58 3.58 0 0 0-2.52.77 1.66 1.66 0 0 0-.5 1.79c.2.66.73 1.23 1.5 1.39.6.12 1.33-.04 2.04-.35.58-.26 1.1-.6 1.45-.85V8.37a8.27 8.27 0 0 0-1.97-.36Zm8.43-1.34a.5.5 0 0 0-.94-.34c-.18.5-.37 1.22-.47 1.65-.5.03-1 .03-1.53 0a.5.5 0 1 0-.06 1c.47.02.92.03 1.36 0-.11.58-.2 1.1-.25 1.56a4.71 4.71 0 0 0-2.3 2.3c-.44 1.02-.4 2.17.25 2.85.43.46 1.06.53 1.64.4.42-.1.86-.31 1.28-.61l.08.2a.5.5 0 0 0 .93-.36 8.18 8.18 0 0 0-.23-.53 6.7 6.7 0 0 0 1.68-3.6c.77.26 1.28.8 1.5 1.38.38 1.04-.04 2.55-2.11 3.47a.5.5 0 1 0 .4.92c2.43-1.08 3.26-3.07 2.64-4.73A3.37 3.37 0 0 0 16 10.17V10a.5.5 0 1 0-1 0v.02c-.43-.01-.88.03-1.36.13l.23-1.25a21.3 21.3 0 0 0 2.24-.41.5.5 0 0 0-.22-.98c-.62.15-1.2.27-1.77.35.1-.38.23-.85.35-1.2Zm-3.27 6.57c.23-.52.64-1.06 1.3-1.5-.01.63.04 1.16.13 1.61.1.48.24.87.38 1.2-.38.3-.75.49-1.06.56-.39.09-.6 0-.69-.1-.27-.3-.4-.97-.06-1.77Zm3.73-2.22a5.83 5.83 0 0 1-1.15 2.76l-.17-.62a7.2 7.2 0 0 1-.09-1.94l.13-.04c.46-.12.89-.17 1.28-.16Z"]),_m=Mp("Attach20Regular","20",["m4.83 10.48 5.65-5.65a3 3 0 0 1 4.25 4.24L8 15.8a1.5 1.5 0 0 1-2.12-2.12l6-6.01a.5.5 0 1 0-.7-.71l-6 6.01a2.5 2.5 0 0 0 3.53 3.54l6.71-6.72a4 4 0 1 0-5.65-5.66L4.12 9.78a.5.5 0 0 0 .7.7Z"]),Em=Mp("Backspace20Regular","20",["M9.15 7.15c.2-.2.5-.2.7 0L12 9.29l2.15-2.14a.5.5 0 0 1 .7.7L12.71 10l2.14 2.15a.5.5 0 0 1-.7.7L12 10.71l-2.15 2.14a.5.5 0 0 1-.7-.7L11.29 10 9.15 7.85a.5.5 0 0 1 0-.7ZM6.59 4.66A2.5 2.5 0 0 1 8.29 4h7.21A2.5 2.5 0 0 1 18 6.5v7a2.5 2.5 0 0 1-2.5 2.5H8.28a2.5 2.5 0 0 1-1.7-.66l-3.78-3.5a2.5 2.5 0 0 1 0-3.68l3.79-3.5Zm1.7.34c-.38 0-.75.14-1.03.4L3.48 8.9a1.5 1.5 0 0 0 0 2.2l3.78 3.5c.28.26.65.4 1.02.4h7.22c.83 0 1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5H8.28Z"]),Tm=Mp("BoardSplit20Regular","20",["M3 6a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6Zm1 4v4c0 1.1.9 2 2 2h5v-6H4Zm7-1V4H6a2 2 0 0 0-2 2v3h7Zm1 7h2a2 2 0 0 0 2-2v-1h-4v3Zm4-9V6a2 2 0 0 0-2-2h-2v3h4Zm0 1h-4v4h4V8Z"]),bm=e=>e/16+"rem",Im=e=>({transform:"scale(2)",display:"flex",justifyContent:"center",alignItems:"center",lineHeight:"0.2rem",color:e.palette.themePrimary,zIndex:1}),wm=e=>({root:{borderRadius:"100%",background:e.palette.themeLighterAlt,padding:"2rem"}}),Rm=()=>e.createElement("div",{className:cn({transform:"scale(0.8)"})},e.createElement(Gp,null)),Am=()=>Qh().rtl?e.createElement(Sg,null):e.createElement(vg,null),Pm=()=>Qh().rtl?e.createElement(vg,null):e.createElement(Sg,null),Mm={ChatMessageOptions:e.createElement((()=>e.createElement("div",{className:cn({transform:"scale(0.9)"})},e.createElement(Bg,null))),null),ControlButtonCameraOff:e.createElement(xp,null),ControlButtonCameraOn:e.createElement(Dp,null),ControlButtonEndCall:e.createElement(lg,null),ControlButtonMicOff:e.createElement(Yp,null),ControlButtonMicOn:e.createElement(Wp,null),ControlButtonOptions:e.createElement(Jg,null),ControlButtonParticipants:e.createElement(Tg,null),ControlButtonParticipantsContextualMenuItem:e.createElement(bg,null),ControlButtonScreenShareStart:e.createElement(Xp,null),ControlButtonScreenShareStop:e.createElement(eg,null),ControlButtonRaiseHand:e.createElement((()=>e.createElement(Ng,null)),null),ControlButtonLowerHand:e.createElement((()=>e.createElement(Lg,null)),null),RaiseHandContextualMenuItem:e.createElement(Ng,null),LowerHandContextualMenuItem:e.createElement(Lg,null),ReactionButtonIcon:e.createElement(tm,null),CancelAttachmentUpload:e.createElement(Qg,null),DownloadAttachment:e.createElement(am,null),OpenAttachment:e.createElement(Vg,null),AttachmentMoreMenu:e.createElement(Ug,null),DataLossPreventionProhibited:e.createElement((()=>e.createElement(jg,null)),null),EditBoxCancel:e.createElement(Zg,null),EditBoxSubmit:e.createElement(mg,null),ErrorBarCallCameraAccessDenied:e.createElement(Vp,null),ErrorBarCallCameraAlreadyInUse:e.createElement(Vp,null),ErrorBarCallLocalVideoFreeze:e.createElement(Rm,null),ErrorBarCallMacOsCameraAccessDenied:e.createElement(Vp,null),ErrorBarCallMacOsMicrophoneAccessDenied:e.createElement(Qp,null),ErrorBarCallMicrophoneAccessDenied:e.createElement(Qp,null),ErrorBarCallMicrophoneMutedBySystem:e.createElement(Kp,null),ErrorBarCallMicrophoneUnmutedBySystem:e.createElement(zp,null),ErrorBarCallNetworkQualityLow:e.createElement(Rm,null),ErrorBarCallNoMicrophoneFound:e.createElement(Qp,null),ErrorBarCallNoSpeakerFound:e.createElement(rg,null),ErrorBarClear:e.createElement(Qg,null),ErrorBarCallVideoRecoveredBySystem:e.createElement(kp,null),ErrorBarCallVideoStoppedBySystem:e.createElement(Vp,null),HorizontalGalleryLeftButton:e.createElement(Am,null),HorizontalGalleryRightButton:e.createElement(Pm,null),MessageDelivered:e.createElement(fg,null),MessageEdit:e.createElement(em,null),MessageFailed:e.createElement(im,null),MessageRemove:e.createElement($g,null),MessageResend:e.createElement(rm,null),MessageSeen:e.createElement(nm,null),MessageSending:e.createElement(yg,null),OptionsCamera:e.createElement(Op,null),OptionsMic:e.createElement(qp,null),OptionsSpeaker:e.createElement(ng,null),ParticipantItemMicOff:e.createElement(Jp,null),ParticipantItemOptions:e.createElement(e.Fragment,null),ParticipantItemOptionsHovered:e.createElement(Ug,null),ParticipantItemScreenShareStart:e.createElement(Xp,null),ParticipantItemSpotlighted:e.createElement(Up,null),HoldCallContextualMenuItem:e.createElement(ug,null),HoldCallButton:e.createElement(dg,null),ResumeCall:e.createElement(Dg,null),SendBoxSend:e.createElement(Kg,null),SendBoxSendHovered:e.createElement(qg,null),VideoTileMicOff:e.createElement(Kp,null),DialpadBackspace:e.createElement(Em,null),SitePermissionsSparkle:e.createElement((()=>e.createElement("div",{className:cn({transform:"scale(2)"})},e.createElement(tg,null))),null),SitePermissionCamera:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:wm(t)},e.createElement("div",{className:cn(Im(t))},e.createElement(Dp,null)))}),null),SitePermissionMic:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:wm(t)},e.createElement("div",{className:cn(Im(t))},e.createElement(Wp,null)))}),null),SitePermissionCameraDenied:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:wm(t)},e.createElement("div",{className:cn(Im(t))},e.createElement(Hp,null)))}),null),SitePermissionMicDenied:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:wm(t)},e.createElement("div",{className:cn(Im(t))},e.createElement(Zp,null)))}),null),UnsupportedEnvironmentWarning:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:{root:{width:bm(84),borderRadius:"100%",background:t.palette.themeLighterAlt,padding:"2rem",margin:"auto"}}},e.createElement("div",{className:cn(Im(t))},e.createElement($p,null)))}),null),BrowserPermissionDeniedError:e.createElement((()=>{const t=Qh();return e.createElement(Gs,{horizontalAlign:"center",styles:wm(t)},e.createElement("div",{className:cn(Im(t))},e.createElement(xg,null)))}),null),VideoTilePinned:e.createElement(Pg,null),VideoTileMoreOptions:e.createElement(Ug,null),VideoTileScaleFit:e.createElement(Wg,null),VideoTileScaleFill:e.createElement(zg,null),PinParticipant:e.createElement(Mg,null),UnpinParticipant:e.createElement(kg,null),SplitButtonPrimaryActionCameraOn:e.createElement(Dp,null),SplitButtonPrimaryActionCameraOff:e.createElement(xp,null),SplitButtonPrimaryActionMicUnmuted:e.createElement(Wp,null),SplitButtonPrimaryActionMicMuted:e.createElement(Yp,null),VerticalGalleryLeftButton:e.createElement(Am,null),VerticalGalleryRightButton:e.createElement(Pm,null),ControlButtonVideoEffectsOption:e.createElement(Lp,null),ConfigurationScreenVideoEffectsButton:e.createElement(Np,null),CaptionsIcon:e.createElement(_g,null),CaptionsOffIcon:e.createElement(Eg,null),CaptionsSettingsIcon:e.createElement(Yg,null),ChangeSpokenLanguageIcon:e.createElement(Ag,null),ChangeCaptionLanguageIcon:e.createElement(Cm,null),ContextMenuCameraIcon:e.createElement(Op,null),ContextMenuMicIcon:e.createElement(qp,null),ContextMenuSpeakerIcon:e.createElement(ng,null),SurveyStarIcon:e.createElement(sg,null),SurveyStarIconFilled:e.createElement(ag,null),StartSpotlightContextualMenuItem:e.createElement(Up,null),StopSpotlightContextualMenuItem:e.createElement(Bp,null),VideoTileSpotlighted:e.createElement(Up,{style:{height:"16px",width:"16px"}}),RichTextBoldButtonIcon:e.createElement(um,null),RichTextItalicButtonIcon:e.createElement(vm,null),RichTextUnderlineButtonIcon:e.createElement(ym,null),RichTextBulletListButtonIcon:e.createElement(hm,null),RichTextNumberListButtonIcon:e.createElement(Sm,null),RichTextIndentDecreaseButtonIcon:e.createElement(mm,null),RichTextIndentIncreaseButtonIcon:e.createElement(fm,null),RichTextDividerIcon:e.createElement(Xg,null),RichTextEditorButtonIcon:e.createElement(gm,null),RichTextEditorButtonIconFilled:e.createElement(pm,null),RichTextInsertTableRegularIcon:e.createElement(om,null),RichTextInsertTableFilledIcon:e.createElement(sm,null),RichTextTableInsertMenuIcon:e.createElement(lm,null),RichTextTableDeleteMenuIcon:e.createElement(cm,null)};var km,Dm;!function(e){e[e.xSmall=0]="xSmall",e[e.small=1]="small",e[e.medium=2]="medium",e[e.large=3]="large"}(km||(km={})),function(e){e[e.normal=0]="normal",e[e.large=1]="large"}(Dm||(Dm={}));var Om=Ys(),Nm=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.type,n=t.size,r=t.ariaLabel,a=t.ariaLive,s=t.styles,o=t.label,l=t.theme,c=t.className,d=t.labelPosition,u=r,h=Ds(this.props,ks,["size"]),p=n;void 0===p&&void 0!==i&&(p=i===Dm.large?km.large:km.medium);var g=Om(s,{theme:l,size:p,className:c,labelPosition:d});return e.createElement("div",Ii({},h,{className:g.root}),e.createElement("div",{className:g.circle}),o&&e.createElement("div",{className:g.label},o),u&&e.createElement("div",{role:"status","aria-live":a},e.createElement(Xs,null,e.createElement("div",{className:g.screenReaderText},u))))},i.defaultProps={size:km.medium,ariaLive:"polite",labelPosition:"bottom"},i}(e.Component),Lm={root:"ms-Spinner",circle:"ms-Spinner-circle",label:"ms-Spinner-label"},xm=vn((function(){return On({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}})})),Fm=Ws(Nm,(function(e){var t,i=e.theme,n=e.size,r=e.className,a=e.labelPosition,s=i.palette,o=Kr(Lm,i);return{root:[o.root,{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},"top"===a&&{flexDirection:"column-reverse"},"right"===a&&{flexDirection:"row"},"left"===a&&{flexDirection:"row-reverse"},r],circle:[o.circle,{boxSizing:"border-box",borderRadius:"50%",border:"1.5px solid "+s.themeLight,borderTopColor:s.themePrimary,animationName:xm(),animationDuration:"1.3s",animationIterationCount:"infinite",animationTimingFunction:"cubic-bezier(.53,.21,.29,.67)",selectors:(t={},t[Nr]=Ii({borderTopColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},n===km.xSmall&&["ms-Spinner--xSmall",{width:12,height:12}],n===km.small&&["ms-Spinner--small",{width:16,height:16}],n===km.medium&&["ms-Spinner--medium",{width:20,height:20}],n===km.large&&["ms-Spinner--large",{width:28,height:28}]],label:[o.label,i.fonts.small,{color:s.themePrimary,margin:"8px 0 0",textAlign:"center"},"top"===a&&{margin:"0 0 8px"},"right"===a&&{margin:"0 0 0 8px"},"left"===a&&{margin:"0 8px 0 0"}],screenReaderText:Wr}}),void 0,{scope:"Spinner"});const Um=()=>e.createElement(Fm,{size:km.large}),Bm={ChevronLeft:void 0,Link:void 0,LobbyScreenConnectingToCall:e.createElement(Um,null),LobbyScreenWaitingToBeAdmitted:e.createElement(Um,null),LocalDeviceSettingsCamera:e.createElement(Dp,null),LocalDeviceSettingsMic:e.createElement(Wp,null),LocalDeviceSettingsSpeaker:e.createElement(ig,null),LocalPreviewPlaceholder:e.createElement(xp,null),LocalCameraSwitch:e.createElement(hg,null),ControlBarChatButtonActive:e.createElement(pg,null),ControlBarChatButtonInactive:e.createElement(gg,null),ControlButtonCameraProhibited:e.createElement(Hp,null),ControlButtonMicProhibited:e.createElement(Zp,null),ControlButtonExitSpotlight:e.createElement(Bp,null),ControlBarPeopleButton:e.createElement(bg,null),MoreDrawerMicrophones:e.createElement(qp,null),MoreDrawerPeople:e.createElement(bg,null),MoreDrawerSpeakers:e.createElement(ng,null),MoreDrawerSelectedMicrophone:e.createElement(Wp,null),MoreDrawerSelectedSpeaker:e.createElement(ig,null),Muted:e.createElement(Yp,null),NetworkReconnectIcon:e.createElement(cg,null),NoticePageAccessDeniedTeamsMeeting:e.createElement(wg,null),NoticePageJoinCallFailedDueToNoNetwork:e.createElement(Gp,null),NoticePageLeftCall:e.createElement(lg,null),NoticePageRemovedFromCall:e.createElement(Fg,null),NoticePageNotInvitedToRoom:e.createElement(Fg,null),NoticePageRoomNotFound:e.createElement(Fg,null),NoticePageRoomNotValid:e.createElement(Fg,null),NoticePageCallRejected:e.createElement(Fg,null),NoticePageCallTimeout:e.createElement(Fg,null),SendBoxAttachFile:e.createElement(_m,null),PeoplePaneAddPerson:e.createElement(Ig,null),PeoplePaneOpenDialpad:e.createElement(Gg,null),DialpadStartCall:e.createElement(og,null),NoticePageInviteToRoomRemoved:e.createElement(Fg,null),BlurVideoBackground:e.createElement(Lp,null),RemoveVideoBackgroundEffect:e.createElement(Fp,null),GalleryOptions:e.createElement(Og,null),OverflowGalleryTop:e.createElement(jp,null),SpeakerGalleryLayout:e.createElement(Rg,null),DefaultGalleryLayout:e.createElement(dm,null),FloatingLocalVideoGalleryLayout:e.createElement(Tm,null),FocusedContentGalleryLayout:e.createElement(Hg,null),LargeGalleryLayout:e.createElement(om,null),DefaultCustomButton:e.createElement(Cg,null),DtmfDialpadButton:e.createElement(Gg,null),PeoplePaneMoreButton:e.createElement(Ug,null),StopAllSpotlightMenuButton:e.createElement(Bp,null)},Vm=Object.assign(Object.assign({},Mm),Bm),Hm=t=>e.createElement(il,Object.assign({},t)),$m=t=>e.createElement(il,Object.assign({},t)),Gm={position:"fixed",zIndex:1e6,inset:"0px",visibility:"hidden"},jm=t=>{const{audioContext:i,children:n}=t;return Wm()?e.createElement(e.Fragment,null,n):e.createElement(zm.Provider,{value:i},t.children)},zm=(0,e.createContext)(new AudioContext),Wm=()=>(0,e.useContext)(zm),qm=t=>{const{fluentTheme:i,rtl:n,locale:r}=t,a=fu("composite-global-hostId");if(Jm())return e.createElement(e.Fragment,null,t.children);const s={};Object.entries(Vm).forEach((([e,t])=>{t&&(s[e]=t)})),Wa({icons:Object.assign(Object.assign({},s),t.icons)});const o=new AudioContext,l=e.createElement(Yh,{fluentTheme:i,rtl:n},e.createElement("meta",{name:"viewport",content:"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"}),e.createElement(Sd,{scopedSettings:{Layer:{hostId:a}}},e.createElement(jm,{audioContext:o},e.createElement(Ym,null,t.children))),e.createElement(Xh,{id:a,className:cn(Gm)})),c=r?(t=>{const{locale:i,children:n}=t;return e.createElement(tp.Provider,{value:i},e.createElement(Ch,{locale:i.component},n))})({locale:r,children:l}):l;return e.createElement(Km.Provider,{value:!0},c)},Km=(0,e.createContext)(!1),Jm=()=>(0,e.useContext)(Km),Ym=t=>{const{children:i}=t,n=cn({background:xh().semanticColors.bodyBackground,height:"100%",width:"100%",position:"relative"});return e.createElement(Gs,{className:n},i)},Qm=(0,e.createContext)(void 0),Zm=t=>{const{adapter:i}=t;return e.createElement(Qm.Provider,{value:i},t.children)},Xm=()=>{const t=(0,e.useContext)(Qm);if(!t)throw"Cannot find adapter please initialize before usage.";return t},ef=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),tf=e=>e/parseFloat(getComputedStyle(document.documentElement).fontSize),nf=e=>"resize"===e.type||"scroll"===e.type;function rf(e){return Object.keys(e)}const af=t=>{const[i,n]=(0,e.useState)(void 0),r=(0,e.useRef)(new ResizeObserver((e=>{const{width:t}=e[0].contentRect;n(t)})));return(0,e.useEffect)((()=>{t.current&&r.current.observe(t.current);const e=r.current;return()=>{e.disconnect()}}),[t,r]),i},sf=t=>{const[i,n]=(0,e.useState)(void 0),r=(0,e.useRef)(new ResizeObserver((e=>{const{height:t}=e[0].contentRect;n(t)})));return(0,e.useEffect)((()=>{t.current&&r.current.observe(t.current);const e=r.current;return()=>{e.disconnect()}}),[t,r]),i},of=e=>e<=ef(30),lf=e=>e<=ef(23.75);var cf=Ys(),df=function(e,t){t.as;var i=t.disabled,n=t.target,r=t.href,a=(t.theme,t.getStyles,t.styles,t.componentRef,t.underline,wi(t,["as","disabled","target","href","theme","getStyles","styles","componentRef","underline"]));return"string"==typeof e?"a"===e?Ii({target:n,href:i?void 0:r},a):"button"===e?Ii({type:"button",disabled:i},a):Ii(Ii({},a),{disabled:i}):Ii({target:n,href:r,disabled:i},a)},uf=e.forwardRef((function(t,i){var n=function(t,i){var n=t.as,r=t.className,a=t.disabled,s=t.href,o=t.onClick,l=t.styles,c=t.theme,d=t.underline,u=e.useRef(null),h=qo(u,i);(function(t,i){e.useImperativeHandle(t.componentRef,(function(){return{focus:function(){i.current&&i.current.focus()}}}),[i])})(t,u),Lo(u);var p=cf(l,{className:r,isButton:!s,isDisabled:a,isUnderlined:d,theme:c}),g=n||(s?"a":"button");return{state:{},slots:{root:g},slotProps:{root:Ii(Ii({},df(g,t)),{"aria-disabled":a,className:p.root,onClick:function(e){a?e.preventDefault():o&&o(e)},ref:h})}}}(t,i),r=n.slots,a=n.slotProps;return e.createElement(r.root,Ii({},a.root))}));uf.displayName="LinkBase";var hf={root:"ms-Link"},pf=Ws(uf,(function(e){var t,i,n,r,a,s,o,l=e.className,c=e.isButton,d=e.isDisabled,u=e.isUnderlined,h=e.theme,p=h.semanticColors,g=p.link,m=p.linkHovered,f=p.disabledText,v=p.focusBorder,S=Kr(hf,h);return{root:[S.root,h.fonts.medium,{color:g,outline:"none",fontSize:"inherit",fontWeight:"inherit",textDecoration:u?"underline":"none",selectors:(t={".ms-Fabric--isFocusVisible &:focus":{boxShadow:"0 0 0 1px ".concat(v," inset"),outline:"1px auto ".concat(v),selectors:(i={},i[Nr]={outline:"1px solid WindowText"},i)}},t[Nr]={borderBottom:"none"},t)},c&&{background:"none",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"inline",margin:0,overflow:"inherit",padding:0,textAlign:"left",textOverflow:"inherit",userSelect:"text",borderBottom:"1px solid transparent",selectors:(n={},n[Nr]={color:"LinkText",forcedColorAdjust:"none"},n)},!c&&{selectors:(r={},r[Nr]={MsHighContrastAdjust:"auto",forcedColorAdjust:"auto"},r)},d&&["is-disabled",{color:f,cursor:"default"},{selectors:(a={"&:link, &:visited":{pointerEvents:"none"}},a[Nr]={color:"GrayText"},a)}],!d&&{selectors:{"&:active, &:hover, &:active:hover":{color:m,textDecoration:"underline",selectors:(s={},s[Nr]={color:"LinkText"},s)},"&:focus":{color:g,selectors:(o={},o[Nr]={color:"LinkText"},o)}}},S.root,l]}}),void 0,{scope:"Link"});function gf(t){const{variant:i,strings:n}=t;switch(i){case"TRANSCRIPTION_STOPPED_STILL_RECORDING":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerTranscriptionStopped),` ${n.complianceBannerNowOnlyRecording}`,e.createElement(mf,{linkText:n.privacyPolicy}));case"RECORDING_STOPPED_STILL_TRANSCRIBING":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerRecordingStopped),` ${n.complianceBannerNowOnlyTranscription}`,e.createElement(mf,{linkText:n.privacyPolicy}));case"RECORDING_AND_TRANSCRIPTION_STOPPED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerRecordingAndTranscriptionSaved),` ${n.complianceBannerRecordingAndTranscriptionStopped}`,e.createElement(ff,{linkText:n.learnMore}));case"RECORDING_AND_TRANSCRIPTION_STARTED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerRecordingAndTranscriptionStarted),` ${n.complianceBannerTranscriptionConsent}`,e.createElement(mf,{linkText:n.privacyPolicy}));case"TRANSCRIPTION_STARTED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerTranscriptionStarted),` ${n.complianceBannerTranscriptionConsent}`,e.createElement(mf,{linkText:n.privacyPolicy}));case"RECORDING_STOPPED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerRecordingSaving),` ${n.complianceBannerRecordingStopped}`,e.createElement(ff,{linkText:n.learnMore}));case"RECORDING_STARTED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerRecordingStarted),` ${n.complianceBannerTranscriptionConsent}`,e.createElement(mf,{linkText:n.privacyPolicy}));case"TRANSCRIPTION_STOPPED":return e.createElement(e.Fragment,null,e.createElement("b",null,n.complianceBannerTranscriptionSaving),` ${n.complianceBannerTranscriptionStopped}`,e.createElement(ff,{linkText:n.learnMore}))}return e.createElement(e.Fragment,null)}function mf(t){return e.createElement(pf,{href:"https://privacy.microsoft.com/privacystatement#mainnoticetoendusersmodule",target:"_blank",underline:!0},t.linkText)}function ff(t){return e.createElement(pf,{href:"https://support.microsoft.com/office/record-a-meeting-in-teams-34dfbe7f-b07d-4a27-b4c6-de62f1348c24",target:"_blank",underline:!0},t.linkText)}function vf(t){const{variant:i,lastUpdated:n}=t.variant,[r,a]=(0,e.useState)({variant:i,lastUpdated:Date.now()}),s=(0,e.useRef)(null);if(i!==r.variant&&n>r.lastUpdated){s.current&&clearTimeout(s.current);const e=Date.now(),t=3e3-(e-r.lastUpdated);"NO_STATE"===i||t<=0?a({variant:i,lastUpdated:e}):s.current=setTimeout((()=>{a({variant:i,lastUpdated:Date.now()})}),t)}return"NO_STATE"===r.variant?e.createElement(e.Fragment,null):e.createElement(vh,{messageBarType:Ku.warning,onDismiss:()=>{a({variant:"NO_STATE",lastUpdated:Date.now()}),t.onDismiss()},dismissButtonAriaLabel:t.strings.close},e.createElement(gf,{variant:r.variant,strings:t.strings}))}const Sf=t=>{const i=(0,e.useRef)({latestBooleanState:{callTranscribeState:!1,callRecordState:!1},latestStringState:{callTranscribeState:"off",callRecordState:"off"},lastUpdated:Date.now()}),n=t.callRecordState!==i.current.latestBooleanState.callRecordState||t.callTranscribeState!==i.current.latestBooleanState.callTranscribeState;n&&(i.current={latestBooleanState:t,latestStringState:{callRecordState:yf(i.current.latestStringState.callRecordState,t.callRecordState),callTranscribeState:yf(i.current.latestStringState.callTranscribeState,t.callTranscribeState)},lastUpdated:Date.now()});const r=(a=i.current.latestStringState.callRecordState,s=i.current.latestStringState.callTranscribeState,"on"===a&&"on"===s?"RECORDING_AND_TRANSCRIPTION_STARTED":"on"===a&&"off"===s?"RECORDING_STARTED":"off"===a&&"on"===s?"TRANSCRIPTION_STARTED":"on"===a&&"stopped"===s?"TRANSCRIPTION_STOPPED_STILL_RECORDING":"stopped"===a&&"on"===s?"RECORDING_STOPPED_STILL_TRANSCRIBING":"off"===a&&"stopped"===s?"TRANSCRIPTION_STOPPED":"stopped"===a&&"off"===s?"RECORDING_STOPPED":"stopped"===a&&"stopped"===s?"RECORDING_AND_TRANSCRIPTION_STOPPED":"NO_STATE");var a,s;return n&&"stopped"===i.current.latestStringState.callRecordState&&"stopped"===i.current.latestStringState.callTranscribeState&&(i.current.latestStringState.callRecordState="off",i.current.latestStringState.callTranscribeState="off"),e.createElement(vf,{variant:{variant:r,lastUpdated:i.current.lastUpdated},strings:t.strings,onDismiss:()=>{"stopped"===i.current.latestStringState.callRecordState&&(i.current.latestStringState.callRecordState="off"),"stopped"===i.current.latestStringState.callTranscribeState&&(i.current.latestStringState.callTranscribeState="off")}})};function yf(e,t){return t?"on":"on"===e?"stopped":e}var Cf=as((function(e){if(null==e.children)return null;e.block,e.className;var t=e.as,i=void 0===t?"span":t,n=(e.variant,e.nowrap,wi(e,["block","className","as","variant","nowrap"]));return Pn(Dn(e,{root:i}).root,Ii({},Ds(n,ds)))}),{displayName:"Text",styles:function(e,t){var i=e.as,n=e.className,r=e.block,a=e.nowrap,s=e.variant,o=t.fonts,l=t.semanticColors,c=o[s||"medium"];return{root:[c,{color:c.color||l.bodyText,display:r?"td"===i?"table-cell":"block":"inline",mozOsxFontSmoothing:c.MozOsxFontSmoothing,webkitFontSmoothing:c.WebkitFontSmoothing},a&&{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},n]}}});const _f=(e,t)=>{"Enter"!==e.key&&" "!==e.key||t(e)},Ef=t=>{var i;const n=Qh(),r=e=>t.onItemClick&&t.onItemClick(e,t.itemKey),a=t.secondaryIconProps?e.createElement(Tf,Object.assign({},t.secondaryIconProps)):t.subMenuProps?e.createElement(Tf,{iconName:"ChevronRight"}):void 0;return e.createElement(Yl,{shouldFocusOnMount:t.shouldFocusOnMount},e.createElement(Gs,{tabIndex:0,role:"menuitem",horizontal:!0,className:cn(If(n.palette.neutralLight,n.fonts.small),t.disabled?wf(n.palette.neutralQuaternaryAlt):void 0,null===(i=t.styles)||void 0===i?void 0:i.root),onKeyPress:t.disabled?void 0:e=>r&&_f(e,r),onClick:t.disabled?void 0:r,tokens:bf,id:t.id},t.iconProps&&e.createElement(Gs.Item,{role:"presentation",styles:t.disabled?{root:{color:n.palette.neutralTertiaryAlt}}:void 0},e.createElement(Tf,Object.assign({},t.iconProps))),e.createElement(Gs.Item,{styles:Rf,grow:!0},e.createElement(Cf,{styles:t.disabled?{root:{color:n.palette.neutralTertiaryAlt}}:void 0},t.text)),t.secondaryText&&e.createElement(Gs.Item,{styles:Rf,className:cn(Pf)},e.createElement(Cf,{styles:{root:{color:t.disabled?n.palette.neutralTertiaryAlt:n.palette.neutralSecondary}}},t.secondaryText)),t.secondaryComponent&&e.createElement(Gs.Item,null,t.secondaryComponent),a&&e.createElement(Gs.Item,null,a)))},Tf=t=>e.createElement(il,Object.assign({className:cn(Af)},t)),bf={childrenGap:"0.5rem"},If=(e,t)=>Object.assign(Object.assign({},t),{height:"3rem",lineHeight:"3rem",padding:"0rem 0.75rem",cursor:"pointer",":hover, :focus":{background:e}}),wf=e=>({pointerEvents:"none",background:e,":hover, :focus":{background:e}}),Rf={root:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},Af={display:"flex",alignItems:"center",height:"100%"," span":{display:"flex",alignItems:"center",height:"100%"}},Pf={maxWidth:"50%"};function Mf(t){var i=e.useRef((function(){throw new Error("Cannot call an event handler while rendering")}));return Wo((function(){i.current=t}),[t]),qc((function(){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i.current.apply(void 0,e)}}))}var kf={disabled:!1,disableFirstFocus:!1,forceFocusInsideTrap:!0,isClickableOutsideFocusTrap:!1,"data-tabster":'{"uncontrolled": {"completely": true}}'},Df=e.forwardRef((function(t,i){var n,r=e.useRef(null),a=e.useRef(null),s=e.useRef(null),o=qo(r,i),l=jc(),c=Yc(),d=null===(n=au(!1))||void 0===n||n,u=Xl(kf,t),h=qc({hasFocus:!1,focusStackId:fu("ftz-",u.id)}),p=u.children,g=u.componentRef,m=u.disabled,f=u.disableFirstFocus,v=u.forceFocusInsideTrap,S=u.focusPreviouslyFocusedInnerElement,y=u.firstFocusableSelector,C=u.firstFocusableTarget,_=u.disableRestoreFocus,E=void 0===_?u.ignoreExternalFocusing:_,T=u.isClickableOutsideFocusTrap,b=u.enableAriaHiddenSiblings,I={"aria-hidden":!0,style:{pointerEvents:"none",position:"fixed"},tabIndex:m?-1:0,"data-is-visible":!0,"data-is-focus-trap-zone-bumper":!0},w=e.useCallback((function(e){e!==a.current&&e!==s.current&&Al(e)}),[]),R=Mf((function(){if(r.current){var e=h.previouslyFocusedElementInTrapZone;if(S&&e&&ul(r.current,e))w(e);else{var t=null;if("string"==typeof C)t=r.current.querySelector(C);else if(C)t=C(r.current);else if(y){var i="string"==typeof y?y:y();t=r.current.querySelector("."+i)}t||(t=yl(r.current,r.current.firstChild,!1,!1,!1,!0)),t&&w(t)}}})),A=function(e){if(!m&&r.current){var t,i=e===h.hasFocus?(void 0===(t=!1)&&(t=!0),Sl(r.current,s.current,t,!1,!0,!0,!1,!0)):function(e,t,i,n){return void 0===n&&(n=!0),yl(e,t,n,!1,!1,!0,!1,!0)}(r.current,a.current,0,!1);i&&(i===a.current||i===s.current?R():i.focus())}},P=Mf((function(e){if(Df.focusStack=Df.focusStack.filter((function(e){return h.focusStackId!==e})),l){var t=l.activeElement;E||"function"!=typeof(null==e?void 0:e.focus)||!ul(r.current,t)&&t!==l.body||w(e)}})),M=Mf((function(e){if(!m&&h.focusStackId===Df.focusStack.slice(-1)[0]){var t=e.target;t&&!ul(r.current,t)&&(l&&l.activeElement===l.body?setTimeout((function(){l&&l.activeElement===l.body&&(R(),h.hasFocus=!0)}),0):(R(),h.hasFocus=!0),e.preventDefault(),e.stopPropagation())}}));return e.useEffect((function(){var e=[];return v&&e.push(lc(c,"focus",M,!0)),T||e.push(lc(c,"click",M,!0)),function(){e.forEach((function(e){return e()}))}}),[v,T,c]),e.useEffect((function(){if(!m&&(d||v)&&r.current){Df.focusStack.push(h.focusStackId);var e=u.elementToFocusOnDismiss||l.activeElement;return f||ul(r.current,e)||R(),function(){return P(e)}}}),[v,m]),e.useEffect((function(){if(!m&&b)return Bc(r.current)}),[m,b,r]),Zh((function(){delete h.previouslyFocusedElementInTrapZone})),function(t,i,n){e.useImperativeHandle(t,(function(){return{get previouslyFocusedElement(){return i},focus:n}}),[n,i])}(g,h.previouslyFocusedElementInTrapZone,R),e.createElement("div",Ii({"aria-labelledby":u.ariaLabelledBy},Ds(u,ks),{ref:o,onFocusCapture:function(e){var t;null===(t=u.onFocusCapture)||void 0===t||t.call(u,e),e.target===a.current?A(!0):e.target===s.current&&A(!1),h.hasFocus=!0,e.target!==e.currentTarget&&e.target!==a.current&&e.target!==s.current&&(h.previouslyFocusedElementInTrapZone=e.target)},onBlurCapture:function(e){var t;null===(t=u.onBlurCapture)||void 0===t||t.call(u,e);var i=e.relatedTarget;null===e.relatedTarget&&(i=l.activeElement),ul(r.current,i)||(h.hasFocus=!1)}}),e.createElement("div",Ii({},I,{ref:a})),p,e.createElement("div",Ii({},I,{ref:s})))}));Df.displayName="FocusTrapZone",Df.focusStack=[];const Of=t=>{var i;const n=xh(),r=n.palette.white,a=n.effects.roundedCorner4,s=cn(Nf(r,a),null===(i=t.styles)||void 0===i?void 0:i.root);return e.createElement(Gs,{className:s},t.heading&&e.createElement(Gs,{className:cn(Lf)},e.createElement(Cf,{className:cn(xf(n))},t.heading)),t.children)},Nf=(e,t)=>Object.assign({background:e,borderTopRightRadius:t,borderTopLeftRadius:t},_r.slideUpIn10),Lf={textAlign:"center",width:"100%",padding:"0.5rem"},xf=e=>({color:e.palette.neutralSecondary,fontSize:e.fonts.smallPlus.fontSize,lineHeight:"1rem",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}),Ff=t=>e.createElement(Gs,{className:cn(Uf,t.styles),grow:!0,onClick:()=>t.onDismiss()}),Uf={root:{height:"100%"}},Bf=t=>{var i,n,r,a;const s=t.disableMaxHeight?cn(Vf,null===(i=t.styles)||void 0===i?void 0:i.root):cn(Vf,Hf,null===(n=t.styles)||void 0===n?void 0:n.root),o=Xa($f,null===(r=t.styles)||void 0===r?void 0:r.drawerContentContainer);return e.createElement(Gs,{className:s},e.createElement(Ff,{styles:null===(a=t.styles)||void 0===a?void 0:a.lightDismissRoot,onDismiss:t.onLightDismiss}),e.createElement(Df,{onKeyDown:e=>{"Escape"!==e.key&&"Esc"!==e.key||t.onLightDismiss&&t.onLightDismiss()},isClickableOutsideFocusTrap:!0},e.createElement(Of,{styles:o,heading:t.heading},t.children)))},Vf={width:"100%",height:"100%",background:"rgba(0,0,0,0.4)"},Hf={"> div:nth-child(2)":{maxHeight:"75%",overflow:"auto"}},$f={root:{height:"auto"}},Gf=e=>void 0===e.onRendererContent,jf=t=>{var i,n;const[r,a]=(0,e.useState)([]),s=(0,e.useMemo)((()=>{var e;let i=t.items;for(const t of r)i=null===(e=null==i?void 0:i.find((e=>Gf(e)&&e.itemKey===t)))||void 0===e?void 0:e.subMenuProps;return i}),[t.items,r]),o=(0,e.useCallback)(((e,t,i)=>{var n;e.subMenuProps&&a([...r,e.itemKey]),null===(n=e.onItemClick)||void 0===n||n.call(e,t,i)}),[r]),l=Qh().effects.roundedCorner4,c=(null==s?void 0:s[0])&&(null===(i=s[0])||void 0===i?void 0:i.styles),d=(0,e.useMemo)((()=>Ra(null!=c?c:{},{root:{borderTopRightRadius:l,borderTopLeftRadius:l}})),[c,l]);return e.createElement(Bf,{disableMaxHeight:t.disableMaxHeight,styles:null===(n=t.styles)||void 0===n?void 0:n.drawerSurfaceStyles,onLightDismiss:t.onLightDismiss,heading:t.heading},e.createElement(Gs,{styles:t.styles,role:"menu","data-ui-id":"drawer-menu"},null==s?void 0:s.slice(0,1).map((t=>{var i;return Gf(t)?e.createElement(Ef,Object.assign({},t,{key:`${t.itemKey}0`,shouldFocusOnMount:"reactions"!==t.itemKey,styles:d,onItemClick:"reactions"===t.itemKey?void 0:(e,i)=>{o(t,e,i)}})):null===(i=t.onRendererContent)||void 0===i?void 0:i.call(t)})),null==s?void 0:s.slice(1).map(((t,i)=>{var n;return Gf(t)?e.createElement(Ef,Object.assign({},t,{key:`${t.itemKey}${i+1}`,onItemClick:(e,i)=>{o(t,e,i)}})):null===(n=t.onRendererContent)||void 0===n?void 0:n.call(t)}))))},zf=t=>{const{announcementString:i,ariaLive:n}=t;return e.createElement(Gs,{"aria-label":i,"aria-live":n,styles:Wf})},Wf={root:{position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0}},qf={root:{height:"100%"},circle:{maxHeight:"5rem",height:"50%",width:"unset",aspectRatio:"1 / 1",borderWidth:"0.25em"}},Kf=e=>cn({position:"relative",height:"100%",width:"100%",background:"transparent",display:"flex","& video":{borderRadius:e.effects.roundedCorner4}}),Jf=e=>cn(Kf(e),{transform:"rotateY(180deg)","& video:picture-in-picture":{transform:"rotateY(180deg)"}}),Yf=t=>{const i=(0,e.useRef)(null),n=Qh(),{isMirrored:r,videoStreamElement:a,styles:s,loadingState:o="none"}=t,[l,c]=(0,e.useState)(!1);return(0,e.useEffect)((()=>{const e=i.current;if(e)return e.innerHTML="",c(!1),a&&(a.addEventListener("enterpictureinpicture",(()=>{c(!0)})),a.addEventListener("leavepictureinpicture",(()=>{c(!1)})),e.appendChild(a)),()=>{e.innerHTML="",c(!1)}}),[a]),e.createElement("div",{className:cn({position:"relative",display:"contents"})},e.createElement("div",{"data-ui-id":"stream-media-container",className:cn(r&&l?Jf(n):Kf(n),null==s?void 0:s.root),ref:i}),"loading"===o&&e.createElement("div",{className:cn({position:"absolute",top:"50%",bottom:"0",left:"50%",right:"0",transform:"translate(-50%, -50%)"})},e.createElement(Fm,{"data-ui-id":"stream-media-loading-spinner",styles:qf})))},Qf={height:"100%",width:"100%",position:"relative"},Zf={root:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:2}},Xf=t=>{const{isMirrored:i,isScreenSharingOn:n,isStreamAvailable:r,onCreateStreamView:a,onDisposeStreamView:s,renderElementExists:o,scalingMode:l,streamId:c}=t,[d,u]=(0,e.useState)();return(0,e.useEffect)((()=>{var e;return r&&!o&&(null===(e=null==a?void 0:a({isMirrored:i,scalingMode:l}))||void 0===e||e.then((e=>{e&&u(e)}))),()=>{o&&(n||null==s||s())}}),[i,n,r,a,s,o,l,c]),(0,e.useEffect)((()=>()=>{n||null==s||s()}),[n,s]),d},ev=(e,t)=>e?t?e.replace(/{(\w+)}/g,((e,i)=>t[i]||`{${i}}`)):e:"",tv=t=>{var i;const{participant:n,view:r,strings:a,isPinned:s,onPinParticipant:o,onUnpinParticipant:l,onUpdateScalingMode:c,disablePinMenuItem:d,toggleAnnouncerString:u,spotlightedParticipantUserIds:h=[],isSpotlighted:p,onStartSpotlight:g,onStopSpotlight:m,maxParticipantsToSpotlight:f,myUserId:v}=t,S=(0,e.useMemo)((()=>{var e;return null===(e=t.participant.videoStream)||void 0===e?void 0:e.scalingMode}),[null===(i=t.participant.videoStream)||void 0===i?void 0:i.scalingMode]);return(0,e.useMemo)((()=>{const e=[];if(void 0!==s){if(s&&l&&(null==a?void 0:a.unpinParticipantForMe)){let t;u&&a.unpinParticipantMenuItemAriaLabel&&n.displayName&&(t=ev(null==a?void 0:a.unpinParticipantMenuItemAriaLabel,{participantName:n.displayName})),e.push({key:"unpin",text:a.unpinParticipantForMe,iconProps:{iconName:"UnpinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{l(n.userId),t&&(null==u||u(t))},"data-ui-id":"video-tile-unpin-participant-button",ariaLabel:t})}if(!s&&o&&(null==a?void 0:a.pinParticipantForMe)){let t;u&&a.pinnedParticipantAnnouncementAriaLabel&&n.displayName&&(t=ev(null==a?void 0:a.pinnedParticipantAnnouncementAriaLabel,{participantName:n.displayName})),e.push({key:"pin",text:d?a.pinParticipantForMeLimitReached:a.pinParticipantForMe,iconProps:{iconName:"PinParticipant",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{o(n.userId),t&&(null==u||u(t))},"data-ui-id":"video-tile-pin-participant-button",disabled:d||p,ariaLabel:t})}}if(p){const t=v===n.userId?null==a?void 0:a.stopSpotlightOnSelfVideoTileMenuLabel:null==a?void 0:a.stopSpotlightVideoTileMenuLabel;m&&n.userId&&(null==a?void 0:a.stopSpotlightVideoTileMenuLabel)&&e.push({key:"stopSpotlight",text:t,iconProps:{iconName:"StopSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},onClick:()=>m([n.userId]),ariaLabel:a.stopSpotlightVideoTileMenuLabel})}else{const t=h&&h.length>0?null==a?void 0:a.addSpotlightVideoTileMenuLabel:null==a?void 0:a.startSpotlightVideoTileMenuLabel,i=!!f&&h.length>=f;g&&n.userId&&t&&e.push({key:"startSpotlight",text:t,iconProps:{iconName:"StartSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},onClick:()=>g([n.userId]),ariaLabel:t,disabled:i,title:i?null==a?void 0:a.spotlightLimitReachedMenuTitle:void 0})}if(S&&("Crop"===S&&(null==a?void 0:a.fitRemoteParticipantToFrame)?e.push({key:"fitRemoteParticipantToFrame",text:a.fitRemoteParticipantToFrame,iconProps:{iconName:"VideoTileScaleFit",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{null==c||c(n.userId,"Fit"),null==r||r.updateScalingMode("Fit")},"data-ui-id":"video-tile-fit-to-frame",ariaLabel:a.fitRemoteParticipantToFrame}):"Fit"===S&&(null==a?void 0:a.fillRemoteParticipantFrame)&&e.push({key:"fillRemoteParticipantFrame",text:a.fillRemoteParticipantFrame,iconProps:{iconName:"VideoTileScaleFill",styles:{root:{lineHeight:"1rem",textAlign:"center"}}},onClick:()=>{null==c||c(n.userId,"Crop"),null==r||r.updateScalingMode("Crop")},"data-ui-id":"video-tile-fill-frame",ariaLabel:a.fillRemoteParticipantFrame})),0!==e.length)return{items:e,styles:{},calloutProps:{preventDismissOnEvent:nf}}}),[S,a,r,s,o,l,c,n.userId,n.displayName,d,u,h,p,g,m,f,v])};var iv;!function(e){e[e.Parent=0]="Parent",e[e.Self=1]="Self"}(iv||(iv={}));var nv,rv=Ys(),av=function(t){function i(){var i=null!==t&&t.apply(this,arguments)||this;return i._onRenderContent=function(t){return"string"==typeof t.content?e.createElement("p",{className:i._classNames.subText},t.content):e.createElement("div",{className:i._classNames.subText},t.content)},i}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.className,n=t.calloutProps,r=t.directionalHint,a=t.directionalHintForRTL,s=t.styles,o=t.id,l=t.maxWidth,c=t.onRenderContent,d=void 0===c?this._onRenderContent:c,u=t.targetElement,h=t.theme;return this._classNames=rv(s,{theme:h,className:i||n&&n.className,beakWidth:n&&n.isBeakVisible?n.beakWidth:0,gapSpace:n&&n.gapSpace,maxWidth:l}),e.createElement(xd,Ii({target:u,directionalHint:r,directionalHintForRTL:a},n,Ds(this.props,ks,["id"]),{className:this._classNames.root}),e.createElement("div",{className:this._classNames.content,id:o,onFocus:this.props.onFocus,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave},d(this.props,this._onRenderContent)))},i.defaultProps={directionalHint:ll.topCenter,maxWidth:"364px",calloutProps:{isBeakVisible:!0,beakWidth:16,gapSpace:0,setInitialFocus:!0,doNotLayer:!1}},i}(e.Component),sv=Ws(av,(function(e){var t=e.className,i=e.beakWidth,n=void 0===i?16:i,r=e.gapSpace,a=void 0===r?0:r,s=e.maxWidth,o=e.theme,l=o.semanticColors,c=o.fonts,d=o.effects,u=-(Math.sqrt(n*n/2)+a)+1/window.devicePixelRatio;return{root:["ms-Tooltip",o.fonts.medium,Dr.fadeIn200,{background:l.menuBackground,boxShadow:d.elevation8,padding:"8px",maxWidth:s,selectors:{":after":{content:"''",position:"absolute",bottom:u,left:u,right:u,top:u,zIndex:0}}},t],content:["ms-Tooltip-content",c.small,{position:"relative",zIndex:1,color:l.menuItemText,wordWrap:"break-word",overflowWrap:"break-word",overflow:"hidden"}],subText:["ms-Tooltip-subtext",{fontSize:"inherit",fontWeight:"inherit",color:"inherit",margin:0}]}}),void 0,{scope:"Tooltip"});!function(e){e[e.zero=0]="zero",e[e.medium=1]="medium",e[e.long=2]="long"}(nv||(nv={}));var ov,lv,cv,dv,uv,hv,pv=Ys(),gv=function(t){function i(n){var r=t.call(this,n)||this;return r._tooltipHost=e.createRef(),r._defaultTooltipId=bo("tooltip"),r.show=function(){r._toggleTooltip(!0)},r.dismiss=function(){r._hideTooltip()},r._getTargetElement=function(){if(r._tooltipHost.current){var e=r.props.overflowMode;if(void 0!==e)switch(e){case iv.Parent:return r._tooltipHost.current.parentElement;case iv.Self:return r._tooltipHost.current}return r._tooltipHost.current}},r._onTooltipFocus=function(e){r._ignoreNextFocusEvent?r._ignoreNextFocusEvent=!1:r._onTooltipMouseEnter(e)},r._onTooltipContentFocus=function(e){i._currentVisibleTooltip&&i._currentVisibleTooltip!==r&&i._currentVisibleTooltip.dismiss(),i._currentVisibleTooltip=r,r._clearDismissTimer(),r._clearOpenTimer()},r._onTooltipBlur=function(e){var t;r._ignoreNextFocusEvent=(null===(t=Qc(r.context))||void 0===t?void 0:t.activeElement)===e.target,r._dismissTimerId=r._async.setTimeout((function(){r._hideTooltip()}),0)},r._onTooltipMouseEnter=function(e){var t,n=r.props,a=n.overflowMode,s=n.delay,o=Qc(r.context);if(i._currentVisibleTooltip&&i._currentVisibleTooltip!==r&&i._currentVisibleTooltip.dismiss(),i._currentVisibleTooltip=r,void 0!==a){var l=r._getTargetElement();if(l&&!function(e){return e.clientWidth<e.scrollWidth}(t=l)&&!function(e){return e.clientHeight<e.scrollHeight}(t))return}if(!e.target||!ro(e.target,r._getTargetElement(),o))if(r._clearDismissTimer(),r._clearOpenTimer(),s!==nv.zero){var c=r._getDelayTime(s);r._openTimerId=r._async.setTimeout((function(){r._toggleTooltip(!0)}),c)}else r._toggleTooltip(!0)},r._onTooltipMouseLeave=function(e){var t=r.props.closeDelay;r._clearDismissTimer(),r._clearOpenTimer(),t?r._dismissTimerId=r._async.setTimeout((function(){r._toggleTooltip(!1)}),t):r._toggleTooltip(!1),i._currentVisibleTooltip===r&&(i._currentVisibleTooltip=void 0)},r._onTooltipKeyDown=function(e){(e.which===ao.escape||e.ctrlKey)&&r.state.isTooltipVisible&&(r._hideTooltip(),e.stopPropagation())},r._clearDismissTimer=function(){r._async.clearTimeout(r._dismissTimerId)},r._clearOpenTimer=function(){r._async.clearTimeout(r._openTimerId)},r._hideTooltip=function(){r._clearOpenTimer(),r._clearDismissTimer(),r._toggleTooltip(!1)},r._toggleTooltip=function(e){r.state.isTooltipVisible!==e&&r.setState({isTooltipVisible:e},(function(){return r.props.onTooltipToggle&&r.props.onTooltipToggle(e)}))},r._getDelayTime=function(e){switch(e){case nv.medium:return 300;case nv.long:return 500;default:return 0}},lo(r),r.state={isAriaPlaceholderRendered:!1,isTooltipVisible:!1},r}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.calloutProps,n=t.children,r=t.content,a=t.directionalHint,s=t.directionalHintForRTL,o=t.hostClassName,l=t.id,c=t.setAriaDescribedBy,d=void 0===c||c,u=t.tooltipProps,h=t.styles,p=t.theme;this._classNames=pv(h,{theme:p,className:o});var g=this.state.isTooltipVisible,m=l||this._defaultTooltipId,f=Ii(Ii({id:"".concat(m,"--tooltip"),content:r,targetElement:this._getTargetElement(),directionalHint:a,directionalHintForRTL:s,calloutProps:fo({},i,{onDismiss:this._hideTooltip,onFocus:this._onTooltipContentFocus,onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave}),onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave},Ds(this.props,ks,["id"])),u),v=(null==u?void 0:u.onRenderContent)?u.onRenderContent(f,(function(t){return(null==t?void 0:t.content)?e.createElement(e.Fragment,null,t.content):null})):r,S=g&&!!v,y=d&&g&&v?m:void 0;return e.createElement("div",Ii({className:this._classNames.root,ref:this._tooltipHost},{onFocusCapture:this._onTooltipFocus},{onBlurCapture:this._onTooltipBlur},{onMouseEnter:this._onTooltipMouseEnter,onMouseLeave:this._onTooltipMouseLeave,onKeyDown:this._onTooltipKeyDown,role:"none","aria-describedby":y}),n,S&&e.createElement(sv,Ii({},f)),e.createElement("div",{hidden:!0,id:m,style:Wr},v))},i.prototype.componentDidMount=function(){this._async=new go(this)},i.prototype.componentWillUnmount=function(){i._currentVisibleTooltip&&i._currentVisibleTooltip===this&&(i._currentVisibleTooltip=void 0),this._async.dispose()},i.defaultProps={delay:nv.medium},i.contextType=$c,i}(e.Component),mv={root:"ms-TooltipHost",ariaPlaceholder:"ms-TooltipHost-aria-placeholder"},fv=Ws(gv,(function(e){var t=e.className,i=e.theme;return{root:[Kr(mv,i).root,{display:"inline"},t]}}),void 0,{scope:"TooltipHost"}),vv=/[\(\[\{\<][^\)\]\}\>]*[\)\]\}\>]/g,Sv=/[\0-\u001F\!-/:-@\[-`\{-\u00BF\u0250-\u036F\uD800-\uFFFF]/g,yv=/^\d+[\d\s]*(:?ext|x|)\s*\d+$/i,Cv=/\s+/g,_v=/[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uAC00-\uD7AF\uD7B0-\uD7FF\u3040-\u309F\u30A0-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF]|[\uD840-\uD869][\uDC00-\uDED6]/;!function(e){e[e.tiny=0]="tiny",e[e.extraExtraSmall=1]="extraExtraSmall",e[e.extraSmall=2]="extraSmall",e[e.small=3]="small",e[e.regular=4]="regular",e[e.large=5]="large",e[e.extraLarge=6]="extraLarge",e[e.size8=17]="size8",e[e.size10=9]="size10",e[e.size16=8]="size16",e[e.size24=10]="size24",e[e.size28=7]="size28",e[e.size32=11]="size32",e[e.size40=12]="size40",e[e.size48=13]="size48",e[e.size56=16]="size56",e[e.size72=14]="size72",e[e.size100=15]="size100",e[e.size120=18]="size120"}(ov||(ov={})),function(e){e[e.none=0]="none",e[e.offline=1]="offline",e[e.online=2]="online",e[e.away=3]="away",e[e.dnd=4]="dnd",e[e.blocked=5]="blocked",e[e.busy=6]="busy"}(lv||(lv={})),function(e){e[e.lightBlue=0]="lightBlue",e[e.blue=1]="blue",e[e.darkBlue=2]="darkBlue",e[e.teal=3]="teal",e[e.lightGreen=4]="lightGreen",e[e.green=5]="green",e[e.darkGreen=6]="darkGreen",e[e.lightPink=7]="lightPink",e[e.pink=8]="pink",e[e.magenta=9]="magenta",e[e.purple=10]="purple",e[e.black=11]="black",e[e.orange=12]="orange",e[e.red=13]="red",e[e.darkRed=14]="darkRed",e[e.transparent=15]="transparent",e[e.violet=16]="violet",e[e.lightRed=17]="lightRed",e[e.gold=18]="gold",e[e.burgundy=19]="burgundy",e[e.warmGray=20]="warmGray",e[e.coolGray=21]="coolGray",e[e.gray=22]="gray",e[e.cyan=23]="cyan",e[e.rust=24]="rust"}(cv||(cv={})),function(e){e.size8="20px",e.size10="20px",e.size16="16px",e.size24="24px",e.size28="28px",e.size32="32px",e.size40="40px",e.size48="48px",e.size56="56px",e.size72="72px",e.size100="100px",e.size120="120px"}(uv||(uv={})),function(e){e.size6="6px",e.size8="8px",e.size12="12px",e.size16="16px",e.size20="20px",e.size28="28px",e.size32="32px",e.border="2px"}(hv||(hv={}));var Ev=function(e){return{isSize8:e===ov.size8,isSize10:e===ov.size10||e===ov.tiny,isSize16:e===ov.size16,isSize24:e===ov.size24||e===ov.extraExtraSmall,isSize28:e===ov.size28||e===ov.extraSmall,isSize32:e===ov.size32,isSize40:e===ov.size40||e===ov.small,isSize48:e===ov.size48||e===ov.regular,isSize56:e===ov.size56,isSize72:e===ov.size72||e===ov.large,isSize100:e===ov.size100||e===ov.extraLarge,isSize120:e===ov.size120}},Tv=((dv={})[ov.tiny]=10,dv[ov.extraExtraSmall]=24,dv[ov.extraSmall]=28,dv[ov.small]=40,dv[ov.regular]=48,dv[ov.large]=72,dv[ov.extraLarge]=100,dv[ov.size8]=8,dv[ov.size10]=10,dv[ov.size16]=16,dv[ov.size24]=24,dv[ov.size28]=28,dv[ov.size32]=32,dv[ov.size40]=40,dv[ov.size48]=48,dv[ov.size56]=56,dv[ov.size72]=72,dv[ov.size100]=100,dv[ov.size120]=120,dv),bv=function(e){return{isAvailable:e===lv.online,isAway:e===lv.away,isBlocked:e===lv.blocked,isBusy:e===lv.busy,isDoNotDisturb:e===lv.dnd,isOffline:e===lv.offline}},Iv=Ys({cacheSize:100}),wv=e.forwardRef((function(t,i){var n=t.coinSize,r=t.isOutOfOffice,a=t.styles,s=t.presence,o=t.theme,l=t.presenceTitle,c=t.presenceColors,d=qo(i,e.useRef(null)),u=Ev(t.size),h=!(u.isSize8||u.isSize10||u.isSize16||u.isSize24||u.isSize28||u.isSize32)&&(!n||n>32),p=n?n/3<40?n/3+"px":"40px":"",g=n?{fontSize:n?n/6<20?n/6+"px":"20px":"",lineHeight:p}:void 0,m=n?{width:p,height:p}:void 0,f=Iv(a,{theme:o,presence:s,size:t.size,isOutOfOffice:r,presenceColors:c});return s===lv.none?null:e.createElement("div",{role:"presentation",className:f.presence,style:m,title:l,ref:d},h&&e.createElement(al,{className:f.presenceIcon,iconName:Rv(t.presence,t.isOutOfOffice),style:g}))}));function Rv(e,t){if(e){var i="SkypeArrow";switch(lv[e]){case"online":return"SkypeCheck";case"away":return t?i:"SkypeClock";case"dnd":return"SkypeMinus";case"offline":return t?i:""}return""}}wv.displayName="PersonaPresenceBase";var Av={presence:"ms-Persona-presence",presenceIcon:"ms-Persona-presenceIcon"};function Pv(e){return{color:e,borderColor:e}}function Mv(e,t){return{selectors:{":before":{border:"".concat(e," solid ").concat(t)}}}}function kv(e){return{height:e,width:e}}function Dv(e){return{backgroundColor:e}}var Ov=Ws(wv,(function(e){var t,i,n,r,a,s,o=e.theme,l=e.presenceColors,c=o.semanticColors,d=o.fonts,u=Kr(Av,o),h=Ev(e.size),p=bv(e.presence),g=l&&l.available||"#6BB700",m=l&&l.away||"#FFAA44",f=l&&l.busy||"#C43148",v=l&&l.dnd||"#C50F1F",S=l&&l.offline||"#8A8886",y=l&&l.oof||"#B4009E",C=l&&l.background||c.bodyBackground,_=p.isOffline||e.isOutOfOffice&&(p.isAvailable||p.isBusy||p.isAway||p.isDoNotDisturb),E=h.isSize72||h.isSize100?"2px":"1px";return{presence:[u.presence,Ii(Ii({position:"absolute",height:hv.size12,width:hv.size12,borderRadius:"50%",top:"auto",right:"-2px",bottom:"-2px",border:"2px solid ".concat(C),textAlign:"center",boxSizing:"content-box",backgroundClip:"border-box"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{selectors:(t={},t[Nr]={borderColor:"Window",backgroundColor:"WindowText"},t)}),(h.isSize8||h.isSize10)&&{right:"auto",top:"7px",left:0,border:0,selectors:(i={},i[Nr]={top:"9px",border:"1px solid WindowText"},i)},(h.isSize8||h.isSize10||h.isSize24||h.isSize28||h.isSize32)&&kv(hv.size8),(h.isSize40||h.isSize48)&&kv(hv.size12),h.isSize16&&{height:hv.size6,width:hv.size6,borderWidth:"1.5px"},h.isSize56&&kv(hv.size16),h.isSize72&&kv(hv.size20),h.isSize100&&kv(hv.size28),h.isSize120&&kv(hv.size32),p.isAvailable&&{backgroundColor:g,selectors:(n={},n[Nr]=Dv("Highlight"),n)},p.isAway&&Dv(m),p.isBlocked&&[{selectors:(r={":after":h.isSize40||h.isSize48||h.isSize72||h.isSize100?{content:'""',width:"100%",height:E,backgroundColor:f,transform:"translateY(-50%) rotate(-45deg)",position:"absolute",top:"50%",left:0}:void 0},r[Nr]={selectors:{":after":{width:"calc(100% - 4px)",left:"2px",backgroundColor:"Window"}}},r)}],p.isBusy&&Dv(f),p.isDoNotDisturb&&Dv(v),p.isOffline&&Dv(S),(_||p.isBlocked)&&[{backgroundColor:C,selectors:(a={":before":{content:'""',width:"100%",height:"100%",position:"absolute",top:0,left:0,border:"".concat(E," solid ").concat(f),borderRadius:"50%",boxSizing:"border-box"}},a[Nr]={backgroundColor:"WindowText",selectors:{":before":{width:"calc(100% - 2px)",height:"calc(100% - 2px)",top:"1px",left:"1px",borderColor:"Window"}}},a)}],_&&p.isAvailable&&Mv(E,g),_&&p.isBusy&&Mv(E,f),_&&p.isAway&&Mv(E,y),_&&p.isDoNotDisturb&&Mv(E,v),_&&p.isOffline&&Mv(E,S),_&&p.isOffline&&e.isOutOfOffice&&Mv(E,y)],presenceIcon:[u.presenceIcon,{color:C,fontSize:"6px",lineHeight:hv.size12,verticalAlign:"top",selectors:(s={},s[Nr]={color:"Window"},s)},h.isSize56&&{fontSize:"8px",lineHeight:hv.size16},h.isSize72&&{fontSize:d.small.fontSize,lineHeight:hv.size20},h.isSize100&&{fontSize:d.medium.fontSize,lineHeight:hv.size28},h.isSize120&&{fontSize:d.medium.fontSize,lineHeight:hv.size32},p.isAway&&{position:"relative",left:_?void 0:"1px"},_&&p.isAvailable&&Pv(g),_&&p.isBusy&&Pv(f),_&&p.isAway&&Pv(y),_&&p.isDoNotDisturb&&Pv(v),_&&p.isOffline&&Pv(S),_&&p.isOffline&&e.isOutOfOffice&&Pv(y)]}}),void 0,{scope:"PersonaPresence"}),Nv=[cv.lightBlue,cv.blue,cv.darkBlue,cv.teal,cv.green,cv.darkGreen,cv.lightPink,cv.pink,cv.magenta,cv.purple,cv.orange,cv.lightRed,cv.darkRed,cv.violet,cv.gold,cv.burgundy,cv.warmGray,cv.cyan,cv.rust,cv.coolGray],Lv=Nv.length;function xv(e){var t=e.primaryText,i=e.text,n=e.initialsColor;return"string"==typeof n?n:function(e){switch(e){case cv.lightBlue:return"#4F6BED";case cv.blue:return"#0078D4";case cv.darkBlue:return"#004E8C";case cv.teal:return"#038387";case cv.lightGreen:case cv.green:return"#498205";case cv.darkGreen:return"#0B6A0B";case cv.lightPink:return"#C239B3";case cv.pink:return"#E3008C";case cv.magenta:return"#881798";case cv.purple:return"#5C2E91";case cv.orange:return"#CA5010";case cv.red:return"#EE1111";case cv.lightRed:return"#D13438";case cv.darkRed:return"#A4262C";case cv.transparent:return"transparent";case cv.violet:return"#8764B8";case cv.gold:return"#986F0B";case cv.burgundy:return"#750B1C";case cv.warmGray:return"#7A7574";case cv.cyan:return"#005B70";case cv.rust:return"#8E562E";case cv.coolGray:return"#69797E";case cv.black:return"#1D1D1D";case cv.gray:return"#393939"}}(n=void 0!==n?n:function(e){var t=cv.blue;if(!e)return t;for(var i=0,n=e.length-1;n>=0;n--){var r=e.charCodeAt(n),a=n%8;i^=(r<<a)+(r>>8-a)}return Nv[i%Lv]}(i||t))}var Fv=Ys({cacheSize:100}),Uv=vn((function(e,t,i,n,r,a){return cn(e,!a&&{backgroundColor:xv({text:n,initialsColor:t,primaryText:r}),color:i})})),Bv={size:ov.size48,presence:lv.none,imageAlt:""},Vv=e.forwardRef((function(t,i){var n=Xl(Bv,t),r=function(t){var i=t.onPhotoLoadingStateChange,n=t.imageUrl,r=e.useState(Bo.notLoaded),a=r[0],s=r[1];return e.useEffect((function(){s(Bo.notLoaded)}),[n]),[a,function(e){s(e),null==i||i(e)}]}(n),a=r[0],s=r[1],o=Hv(s),l=n.className,c=n.coinProps,d=n.showUnknownPersonaCoin,u=n.coinSize,h=n.styles,p=n.imageUrl,g=n.initialsColor,m=n.initialsTextColor,f=n.isOutOfOffice,v=n.onRenderCoin,S=void 0===v?o:v,y=n.onRenderPersonaCoin,C=void 0===y?S:y,_=n.onRenderInitials,E=void 0===_?$v:_,T=n.presence,b=n.presenceTitle,I=n.presenceColors,w=n.primaryText,R=n.showInitialsUntilImageLoads,A=n.text,P=n.theme,M=n.size,k=Ds(n,ks),D=Ds(c||{},ks),O=u?{width:u,height:u}:void 0,N=d,L={coinSize:u,isOutOfOffice:f,presence:T,presenceTitle:b,presenceColors:I,size:M,theme:P},x=Fv(h,{theme:P,className:c&&c.className?c.className:l,size:M,coinSize:u,showUnknownPersonaCoin:d}),F=Boolean(a!==Bo.loaded&&(R&&p||!p||a===Bo.error||N));return e.createElement("div",Ii({role:"presentation"},k,{className:x.coin,ref:i}),M!==ov.size8&&M!==ov.size10&&M!==ov.tiny?e.createElement("div",Ii({role:"presentation"},D,{className:x.imageArea,style:O}),F&&e.createElement("div",{className:Uv(x.initials,g,m,A,w,d),style:O,"aria-hidden":"true"},E(n,$v)),!N&&C(n,o),e.createElement(Ov,Ii({},L))):n.presence?e.createElement(Ov,Ii({},L)):e.createElement(al,{iconName:"Contact",className:x.size10WithoutPresenceIcon}),n.children)}));Vv.displayName="PersonaCoinBase";var Hv=function(t){return function(i){var n=i.coinSize,r=i.styles,a=i.imageUrl,s=i.imageAlt,o=i.imageShouldFadeIn,l=i.imageShouldStartVisible,c=i.theme,d=i.showUnknownPersonaCoin,u=i.size,h=void 0===u?Bv.size:u;if(!a)return null;var p=Fv(r,{theme:c,size:h,showUnknownPersonaCoin:d}),g=n||Tv[h];return e.createElement(Zo,{className:p.image,imageFit:Fo.cover,src:a,width:g,height:g,alt:s,shouldFadeIn:o,shouldStartVisible:l,onLoadingStateChange:t})}},$v=function(t){var i=t.imageInitials,n=t.allowPhoneInitials,r=t.showUnknownPersonaCoin,a=t.text,s=t.primaryText,o=t.theme;if(r)return e.createElement(al,{iconName:"Help"});var l=Rn(o);return""!==(i=i||function(e,t,i){return e?(e=function(e){return(e=(e=(e=e.replace(vv,"")).replace(Sv,"")).replace(Cv," ")).trim()}(e),_v.test(e)||!i&&yv.test(e)?"":function(e,t){var i="",n=e.split(" ");return 2===n.length?(i+=n[0].charAt(0).toUpperCase(),i+=n[1].charAt(0).toUpperCase()):3===n.length?(i+=n[0].charAt(0).toUpperCase(),i+=n[2].charAt(0).toUpperCase()):0!==n.length&&(i+=n[0].charAt(0).toUpperCase()),t&&i.length>1?i.charAt(1)+i.charAt(0):i}(e,t)):""}(a||s||"",l,n))?e.createElement("span",null,i):e.createElement(al,{iconName:"Contact"})},Gv={coin:"ms-Persona-coin",imageArea:"ms-Persona-imageArea",image:"ms-Persona-image",initials:"ms-Persona-initials",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120"},jv=Ws(Vv,(function(e){var t,i=e.className,n=e.theme,r=e.coinSize,a=n.palette,s=n.fonts,o=Ev(e.size),l=Kr(Gv,n),c=r||e.size&&Tv[e.size]||48;return{coin:[l.coin,s.medium,o.isSize8&&l.size8,o.isSize10&&l.size10,o.isSize16&&l.size16,o.isSize24&&l.size24,o.isSize28&&l.size28,o.isSize32&&l.size32,o.isSize40&&l.size40,o.isSize48&&l.size48,o.isSize56&&l.size56,o.isSize72&&l.size72,o.isSize100&&l.size100,o.isSize120&&l.size120,i],size10WithoutPresenceIcon:{fontSize:s.xSmall.fontSize,position:"absolute",top:"5px",right:"auto",left:0},imageArea:[l.imageArea,{position:"relative",textAlign:"center",flex:"0 0 auto",height:c,width:c},c<=10&&{overflow:"visible",background:"transparent",height:0,width:0}],image:[l.image,{marginRight:"10px",position:"absolute",top:0,left:0,width:"100%",height:"100%",border:0,borderRadius:"50%",perspective:"1px"},c<=10&&{overflow:"visible",background:"transparent",height:0,width:0},c>10&&{height:c,width:c}],initials:[l.initials,{borderRadius:"50%",color:e.showUnknownPersonaCoin?"rgb(168, 0, 0)":a.white,fontSize:s.large.fontSize,fontWeight:Mr.semibold,lineHeight:48===c?46:c,height:c,selectors:(t={},t[Nr]=Ii(Ii({border:"1px solid WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),{color:"WindowText",boxSizing:"border-box",backgroundColor:"Window !important"}),t.i={fontWeight:Mr.semibold},t)},e.showUnknownPersonaCoin&&{backgroundColor:"rgb(234, 234, 234)"},c<32&&{fontSize:s.xSmall.fontSize},c>=32&&c<40&&{fontSize:s.medium.fontSize},c>=40&&c<56&&{fontSize:s.mediumPlus.fontSize},c>=56&&c<72&&{fontSize:s.xLarge.fontSize},c>=72&&c<100&&{fontSize:s.xxLarge.fontSize},c>=100&&{fontSize:s.superLarge.fontSize}]}}),void 0,{scope:"PersonaCoin"}),zv=Ys(),Wv={size:ov.size48,presence:lv.none,imageAlt:"",showOverflowTooltip:!0},qv=e.forwardRef((function(t,i){var n=Xl(Wv,t),r=qo(i,e.useRef(null)),a=function(){return n.text||n.primaryText||""},s=function(t,i,r){var a=i&&i(n,r);return a?e.createElement("div",{dir:"auto",className:t},a):void 0},o=function(t,i){return void 0===i&&(i=!0),t?i?function(){return e.createElement(fv,{content:t,overflowMode:iv.Parent,directionalHint:ll.topLeftEdge},t)}:function(){return e.createElement(e.Fragment,null,t)}:void 0},l=o(a(),n.showOverflowTooltip),c=o(n.secondaryText,n.showOverflowTooltip),d=o(n.tertiaryText,n.showOverflowTooltip),u=o(n.optionalText,n.showOverflowTooltip),h=n.hidePersonaDetails,p=n.onRenderOptionalText,g=void 0===p?u:p,m=n.onRenderPrimaryText,f=void 0===m?l:m,v=n.onRenderSecondaryText,S=void 0===v?c:v,y=n.onRenderTertiaryText,C=void 0===y?d:y,_=n.onRenderPersonaCoin,E=void 0===_?function(t){return e.createElement(jv,Ii({},t))}:_,T=n.size,b=n.allowPhoneInitials,I=n.className,w=n.coinProps,R=n.showUnknownPersonaCoin,A=n.coinSize,P=n.styles,M=n.imageAlt,k=n.imageInitials,D=n.imageShouldFadeIn,O=n.imageShouldStartVisible,N=n.imageUrl,L=n.initialsColor,x=n.initialsTextColor,F=n.isOutOfOffice,U=n.onPhotoLoadingStateChange,B=n.onRenderCoin,V=n.onRenderInitials,H=n.presence,$=n.presenceTitle,G=n.presenceColors,j=n.showInitialsUntilImageLoads,z=n.showSecondaryText,W=n.theme,q=Ii({allowPhoneInitials:b,showUnknownPersonaCoin:R,coinSize:A,imageAlt:M,imageInitials:k,imageShouldFadeIn:D,imageShouldStartVisible:O,imageUrl:N,initialsColor:L,initialsTextColor:x,onPhotoLoadingStateChange:U,onRenderCoin:B,onRenderInitials:V,presence:H,presenceTitle:$,showInitialsUntilImageLoads:j,size:T,text:a(),isOutOfOffice:F,presenceColors:G},w),K=zv(P,{theme:W,className:I,showSecondaryText:z,presence:H,size:T}),J=Ds(n,ks),Y=e.createElement("div",{className:K.details},s(K.primaryText,f,l),s(K.secondaryText,S,c),s(K.tertiaryText,C,d),s(K.optionalText,g,u),n.children);return e.createElement("div",Ii({},J,{ref:r,className:K.root,style:A?{height:A,minWidth:A}:void 0}),E(q,E),(!h||T===ov.size8||T===ov.size10||T===ov.tiny)&&Y)}));qv.displayName="PersonaBase";var Kv={root:"ms-Persona",size8:"ms-Persona--size8",size10:"ms-Persona--size10",size16:"ms-Persona--size16",size24:"ms-Persona--size24",size28:"ms-Persona--size28",size32:"ms-Persona--size32",size40:"ms-Persona--size40",size48:"ms-Persona--size48",size56:"ms-Persona--size56",size72:"ms-Persona--size72",size100:"ms-Persona--size100",size120:"ms-Persona--size120",available:"ms-Persona--online",away:"ms-Persona--away",blocked:"ms-Persona--blocked",busy:"ms-Persona--busy",doNotDisturb:"ms-Persona--donotdisturb",offline:"ms-Persona--offline",details:"ms-Persona-details",primaryText:"ms-Persona-primaryText",secondaryText:"ms-Persona-secondaryText",tertiaryText:"ms-Persona-tertiaryText",optionalText:"ms-Persona-optionalText",textContent:"ms-Persona-textContent"},Jv=Ws(qv,(function(e){var t=e.className,i=e.showSecondaryText,n=e.theme,r=n.semanticColors,a=n.fonts,s=Kr(Kv,n),o=Ev(e.size),l=bv(e.presence),c="16px",d={color:r.bodySubtext,fontWeight:Mr.regular,fontSize:a.small.fontSize};return{root:[s.root,n.fonts.medium,Ba,{color:r.bodyText,position:"relative",height:uv.size48,minWidth:uv.size48,display:"flex",alignItems:"center",selectors:{".contextualHost":{display:"none"}}},o.isSize8&&[s.size8,{height:uv.size8,minWidth:uv.size8}],o.isSize10&&[s.size10,{height:uv.size10,minWidth:uv.size10}],o.isSize16&&[s.size16,{height:uv.size16,minWidth:uv.size16}],o.isSize24&&[s.size24,{height:uv.size24,minWidth:uv.size24}],o.isSize24&&i&&{height:"36px"},o.isSize28&&[s.size28,{height:uv.size28,minWidth:uv.size28}],o.isSize28&&i&&{height:"32px"},o.isSize32&&[s.size32,{height:uv.size32,minWidth:uv.size32}],o.isSize40&&[s.size40,{height:uv.size40,minWidth:uv.size40}],o.isSize48&&s.size48,o.isSize56&&[s.size56,{height:uv.size56,minWidth:uv.size56}],o.isSize72&&[s.size72,{height:uv.size72,minWidth:uv.size72}],o.isSize100&&[s.size100,{height:uv.size100,minWidth:uv.size100}],o.isSize120&&[s.size120,{height:uv.size120,minWidth:uv.size120}],l.isAvailable&&s.available,l.isAway&&s.away,l.isBlocked&&s.blocked,l.isBusy&&s.busy,l.isDoNotDisturb&&s.doNotDisturb,l.isOffline&&s.offline,t],details:[s.details,{padding:"0 24px 0 16px",minWidth:0,width:"100%",textAlign:"left",display:"flex",flexDirection:"column",justifyContent:"space-around"},(o.isSize8||o.isSize10)&&{paddingLeft:17},(o.isSize24||o.isSize28||o.isSize32)&&{padding:"0 8px"},(o.isSize40||o.isSize48)&&{padding:"0 12px"}],primaryText:[s.primaryText,Va,{color:r.bodyText,fontWeight:Mr.regular,fontSize:a.medium.fontSize,selectors:{":hover":{color:r.inputTextHovered}}},i&&{height:c,lineHeight:c,overflowX:"hidden"},(o.isSize8||o.isSize10)&&{fontSize:a.small.fontSize,lineHeight:uv.size8},o.isSize16&&{lineHeight:uv.size28},(o.isSize24||o.isSize28||o.isSize32||o.isSize40||o.isSize48)&&i&&{height:18},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&{fontSize:a.xLarge.fontSize},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&i&&{height:22}],secondaryText:[s.secondaryText,Va,d,(o.isSize8||o.isSize10||o.isSize16||o.isSize24||o.isSize28||o.isSize32)&&{display:"none"},i&&{display:"block",height:c,lineHeight:c,overflowX:"hidden"},o.isSize24&&i&&{height:18},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&{fontSize:a.medium.fontSize},(o.isSize56||o.isSize72||o.isSize100||o.isSize120)&&i&&{height:18}],tertiaryText:[s.tertiaryText,Va,d,{display:"none",fontSize:a.medium.fontSize},(o.isSize72||o.isSize100||o.isSize120)&&{display:"block"}],optionalText:[s.optionalText,Va,d,{display:"none",fontSize:a.medium.fontSize},(o.isSize100||o.isSize120)&&{display:"block"}],textContent:[s.textContent,Va]}}),void 0,{scope:"Persona"});const Yv=(0,e.createContext)({sendboxTextField:"sendbox-textfield",participantButtonPeopleMenuItem:"participant-button-people-menu-item",participantItemMenuButton:"participant-item-menu-button",participantList:"participant-list",participantListPeopleButton:"participant-list-people-button",participantListRemoveParticipantButton:"participant-list-remove-participant-button",messageContent:"message-content",messageTimestamp:"message-timestamp",typingIndicator:"typing-indicator",videoGallery:"video-gallery",videoTile:"video-tile",overflowGalleryLeftNavButton:"overflow-gallery-left-nav-button",overflowGalleryRightNavButton:"overflow-gallery-right-nav-button",verticalGalleryVideoTile:"vertical-gallery-video-tile",horizontalGalleryVideoTile:"horizontal-gallery-video-tile",verticalGalleryPageCounter:"vertical-gallery-page-counter",mentionSuggestionList:"mention-suggestion-list",mentionSuggestionItem:"mention-suggestion-item"}),Qv=()=>(0,e.useContext)(Yv),Zv=()=>e.createElement("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e.createElement("defs",null,e.createElement("radialGradient",{id:"paint0_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(16.6796 10.8658) rotate(161.935) scale(13.4702 20.3408)"},e.createElement("stop",{offset:"0.817521",stopColor:"#E99329",stopOpacity:"0"}),e.createElement("stop",{offset:"0.961397",stopColor:"#E99329"})),e.createElement("radialGradient",{id:"paint1_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7464 4.86265) rotate(103.662) scale(15.5522 10.8511)"},e.createElement("stop",{offset:"0.750766",stopColor:"#F88456",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#F88456"})),e.createElement("radialGradient",{id:"paint2_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(10.8862 4.86067) rotate(98.3094) scale(14.3189 9.99881)"},e.createElement("stop",{offset:"0.937186",stopColor:"#F27A74",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#F27A74"})),e.createElement("radialGradient",{id:"paint3_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.3363 11.238) rotate(-144.906) scale(1.08553 4.6268)"},e.createElement("stop",{offset:"0.0636767",stopColor:"#EAB170"}),e.createElement("stop",{offset:"1",stopColor:"#F6B44B",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint4_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.1484 8.75) rotate(129.452) scale(4.85649 1.57945)"},e.createElement("stop",{stopColor:"#FFC748"}),e.createElement("stop",{offset:"1",stopColor:"#FFC64A",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint5_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(17.6953 8.75) rotate(135) scale(1.1601 1.07723)"},e.createElement("stop",{stopColor:"#FFE964"}),e.createElement("stop",{offset:"1",stopColor:"#FFE65F",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint6_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(15.7422 8.47656) rotate(128.853) scale(3.61154 0.774997)"},e.createElement("stop",{offset:"0.251132",stopColor:"#EDB019"}),e.createElement("stop",{offset:"1",stopColor:"#EEB018",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint7_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(15.6055 8.04687) rotate(125.92) scale(3.06292 0.505665)"},e.createElement("stop",{offset:"0.0171863",stopColor:"#D29E4C"}),e.createElement("stop",{offset:"1",stopColor:"#DAA23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint8_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.2578 9.47266) rotate(-56.3099) scale(1.05631 0.227513)"},e.createElement("stop",{offset:"0.297381",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint9_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.4609 9.62891) rotate(107.216) scale(1.45176 3.15212)"},e.createElement("stop",{offset:"0.251132",stopColor:"#FFCF48"}),e.createElement("stop",{offset:"1",stopColor:"#FFD04B",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint10_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.3242 9.02344) rotate(144.638) scale(0.742444 1.38192)"},e.createElement("stop",{offset:"0.420068",stopColor:"#F2AA23"}),e.createElement("stop",{offset:"1",stopColor:"#F2AA23",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint11_linear_10246_159312",x1:"5.72266",y1:"10.9399",x2:"5.07979",y2:"9.68081",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.376446",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint12_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(3.32031 8.28125) rotate(85.0032) scale(7.17571 2.51091)"},e.createElement("stop",{stopColor:"#E6943A"}),e.createElement("stop",{offset:"1",stopColor:"#E7943A",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint13_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.46875 6.17188) rotate(87.0391) scale(6.80596 1.61557)"},e.createElement("stop",{stopColor:"#FFCF50"}),e.createElement("stop",{offset:"0.741378",stopColor:"#FFB847"}),e.createElement("stop",{offset:"1",stopColor:"#FFB848",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint14_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(6.69922 6.95312) rotate(85.2393) scale(4.00062 0.583904)"},e.createElement("stop",{stopColor:"#E79F08"}),e.createElement("stop",{offset:"1",stopColor:"#E79F08",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint15_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.82031 7.76306) rotate(83.1071) scale(3.90579 0.814298)"},e.createElement("stop",{stopColor:"#FFD14D"}),e.createElement("stop",{offset:"1",stopColor:"#FFD04E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint16_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(6.69922 9.17969) rotate(136.548) scale(1.53355 0.783563)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint17_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.46875 5.48828) rotate(80.3401) scale(0.931172 0.709009)"},e.createElement("stop",{stopColor:"#FFDA62"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA60",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint18_linear_10246_159312",x1:"6.05957",y1:"7.05618",x2:"7.26562",y2:"7.03125",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#DE890D"}),e.createElement("stop",{offset:"1",stopColor:"#F9B23D"})),e.createElement("linearGradient",{id:"paint19_linear_10246_159312",x1:"11.7919",y1:"10.3872",x2:"11.5711",y2:"7.83625",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.405208",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint20_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.90363 2.31009) rotate(56.3221) scale(2.85335 11.4486)"},e.createElement("stop",{stopColor:"#E1AE3F"}),e.createElement("stop",{offset:"1",stopColor:"#E8AD3C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint21_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.35938 5.19531) rotate(86.2538) scale(6.57655 1.44733)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.621882",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint22_linear_10246_159312",x1:"8.0957",y1:"9.0918",x2:"7.91992",y2:"7.06055",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.168836",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint23_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(5.82031 5.97656) rotate(78.518) scale(5.10211 0.93429)"},e.createElement("stop",{offset:"0.425088",stopColor:"#BD6606"}),e.createElement("stop",{offset:"1",stopColor:"#C77122",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint24_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.24219 5.89844) rotate(83.5653) scale(5.22825 0.629818)"},e.createElement("stop",{stopColor:"#FFCB4F"}),e.createElement("stop",{offset:"1",stopColor:"#FFCD4C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint25_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.29687 8.20313) rotate(154.799) scale(1.46784 0.851345)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint26_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(9.33594 4.98047) rotate(88.915) scale(5.15717 0.762321)"},e.createElement("stop",{offset:"0.342657",stopColor:"#E29E07"}),e.createElement("stop",{offset:"1",stopColor:"#DF9906",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint27_linear_10246_159312",x1:"9.14062",y1:"6.25",x2:"8.80978",y2:"6.26984",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#B76001"}),e.createElement("stop",{offset:"0.647059",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint28_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(8.125 3.51562) rotate(86.1859) scale(1.17448 1.07205)"},e.createElement("stop",{stopColor:"#FFDA62"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA60",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint29_linear_10246_159312",x1:"9.0625",y1:"5.68143",x2:"10.5816",y2:"5.72531",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#D5850A"}),e.createElement("stop",{offset:"1",stopColor:"#F9B343",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint30_linear_10246_159312",x1:"9.0625",y1:"5.68143",x2:"9.55093",y2:"5.6712",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#B76001"}),e.createElement("stop",{offset:"1",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint31_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.3014 4.55861) rotate(90) scale(5.01272 0.983716)"},e.createElement("stop",{stopColor:"#FFCB45"}),e.createElement("stop",{offset:"1",stopColor:"#FFC44A",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint32_linear_10246_159312",x1:"10.0391",y1:"8.40332",x2:"10.0195",y2:"7.2461",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.210964",stopColor:"#FFC23E"}),e.createElement("stop",{offset:"0.80669",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint33_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7188 8.04687) rotate(166.996) scale(1.16638 0.888873)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFCA5B"}),e.createElement("stop",{offset:"1",stopColor:"#FFCF60",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint34_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.9922 4.76563) rotate(92.1409) scale(4.18261 0.38546)"},e.createElement("stop",{offset:"0.342657",stopColor:"#E29E07"}),e.createElement("stop",{offset:"1",stopColor:"#DF9906",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint35_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(10.9766 4.51172) rotate(90) scale(9.27734 1.28906)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.621882",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint36_linear_10246_159312",x1:"12.3828",y1:"5.9375",x2:"11.6797",y2:"5.93971",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#E59714"}),e.createElement("stop",{offset:"1",stopColor:"#E59714",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint37_linear_10246_159312",x1:"10.0195",y1:"8.82935",x2:"10.2318",y2:"8.00715",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{stopColor:"#FFC23E"}),e.createElement("stop",{offset:"1",stopColor:"#FFC23E",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint38_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(12.2847 7.66848) rotate(-113.448) scale(6.85723 7.32906)"},e.createElement("stop",{offset:"0.869582",stopColor:"#D8A13D",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#D8A13D"})),e.createElement("radialGradient",{id:"paint39_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.2891 1.91406) rotate(93.0128) scale(1.48643 1.29895)"},e.createElement("stop",{stopColor:"#FFE763"}),e.createElement("stop",{offset:"1",stopColor:"#FFE55D",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint40_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.8164 8.53516) rotate(168.022) scale(1.41758 0.903842)"},e.createElement("stop",{offset:"0.426346",stopColor:"#FFD260"}),e.createElement("stop",{offset:"1",stopColor:"#FFD361",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint41_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(13.4766 5.89844) rotate(92.6574) scale(9.26778 2.30713)"},e.createElement("stop",{stopColor:"#FFCE4C"}),e.createElement("stop",{offset:"0.431711",stopColor:"#FFBA49"}),e.createElement("stop",{offset:"1",stopColor:"#FEB848",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint42_linear_10246_159312",x1:"11.5863",y1:"6.2696",x2:"13.5726",y2:"6.42645",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0662431",stopColor:"#E08F13"}),e.createElement("stop",{offset:"0.602743",stopColor:"#E7981B",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint43_linear_10246_159312",x1:"11.5863",y1:"6.2696",x2:"13.259",y2:"6.33379",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0662431",stopColor:"#C2681D"}),e.createElement("stop",{offset:"0.602743",stopColor:"#E69717",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint44_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.9907 8.54439) rotate(-115.482) scale(6.44971 7.3339)"},e.createElement("stop",{offset:"0.869582",stopColor:"#D8A13D",stopOpacity:"0"}),e.createElement("stop",{offset:"1",stopColor:"#D8A13D"})),e.createElement("radialGradient",{id:"paint45_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.0625 5.66406) rotate(91.8841) scale(5.94071 1.40501)"},e.createElement("stop",{stopColor:"#FFDC3F"}),e.createElement("stop",{offset:"1",stopColor:"#FFDA3C",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint46_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.1016 3.51563) rotate(99.1412) scale(1.27667 1.12346)"},e.createElement("stop",{stopColor:"#FFE966"}),e.createElement("stop",{offset:"1",stopColor:"#FFE966",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint47_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(11.7139 8.84766) rotate(124.509) scale(0.853264 2.02461)"},e.createElement("stop",{offset:"0.251132",stopColor:"#F0A623"}),e.createElement("stop",{offset:"1",stopColor:"#F2AA23",stopOpacity:"0"})),e.createElement("linearGradient",{id:"paint48_linear_10246_159312",x1:"13.877",y1:"10.0293",x2:"13.5547",y2:"9.05273",gradientUnits:"userSpaceOnUse"},e.createElement("stop",{offset:"0.0912498",stopColor:"#FFCD47"}),e.createElement("stop",{offset:"1",stopColor:"#FFCD52",stopOpacity:"0"})),e.createElement("radialGradient",{id:"paint49_radial_10246_159312",cx:"0",cy:"0",r:"1",gradientUnits:"userSpaceOnUse",gradientTransform:"translate(14.8059 9.14063) rotate(99.1613) scale(2.21576 0.860587)"},e.createElement("stop",{offset:"0.251132",stopColor:"#D69211"}),e.createElement("stop",{offset:"1",stopColor:"#DAA23E",stopOpacity:"0"}))),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"#FFC23E"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint0_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint1_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint2_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint3_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint4_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint5_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint6_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint7_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint8_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint9_radial_10246_159312)"}),e.createElement("path",{d:"M10.4435 1.23817C11.6481 1.06813 12.2265 2.26542 12.08 3.30216C12.3425 2.83259 12.7902 2.56116 13.3593 2.57808C14.1793 2.60246 14.83 3.32606 14.8046 4.15738L14.5986 9.26659L15.4927 8.14205C16.0297 7.46657 17.0049 7.3596 17.6721 7.90298C18.3408 8.44763 18.4466 9.43906 17.9083 10.1161L17.5242 10.5991L17.5205 10.6047C17.1674 11.0632 16.4446 12.0018 15.5377 13.5195C15.2451 13.9644 14.991 14.4396 14.7373 14.9139C14.3755 15.5904 14.0146 16.2651 13.5446 16.8478C12.6103 18.0157 11.2012 18.7207 9.41406 18.7207C7.46969 18.7207 5.96858 17.7407 5.06836 16.2598C4.39645 15.1544 4.09135 13.756 4.01367 12.3535C3.90459 10.384 3.64472 8.30425 3.52479 6.33789C3.46522 5.36133 4.03401 4.62819 4.82415 4.58984C5.43983 4.55997 5.83432 4.75144 6.11318 5.06836C6.11318 5.06836 6.05957 4.77051 6.05957 4.15738C6.05957 3.54425 6.58827 2.73728 7.41201 2.67578C8.7206 2.57808 8.93545 3.65234 9.0624 4.15738C9.08953 3.10816 8.83779 1.46464 10.4435 1.23817Z",fill:"url(#paint10_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"#FFC23E"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint11_linear_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint12_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint13_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint14_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint15_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint16_radial_10246_159312)"}),e.createElement("path",{d:"M3.52479 6.33728C3.46522 5.36072 4.03401 4.62758 4.82415 4.58924C5.43983 4.55936 5.83432 4.75084 6.11318 5.06775C6.20599 5.20142 6.40332 5.6084 6.4502 6.16699C6.49707 6.72559 6.63574 8.10547 6.69922 8.72559C6.66584 9.373 6.06222 10.7221 3.91477 10.9394C3.78945 9.4056 3.61634 7.8384 3.52479 6.33728Z",fill:"url(#paint17_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"#FFC23E"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint18_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint19_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint20_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint21_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint22_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint23_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint24_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint25_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint26_radial_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint27_linear_10246_159312)"}),e.createElement("path",{d:"M6.11318 5.0685C6.11318 5.0685 6.05957 4.77065 6.05957 4.15752C6.05957 3.54439 6.58827 2.73742 7.41201 2.67592C8.7206 2.57821 8.93545 3.65248 9.0624 4.15752L9.19922 7.71484C9.08203 8.04036 8.67578 8.74219 7.98828 8.94531C7.30078 9.14844 6.82943 8.86068 6.67969 8.69141C6.60156 7.89062 6.4375 6.20312 6.40625 5.85938C6.375 5.51562 6.19785 5.18889 6.11318 5.0685Z",fill:"url(#paint28_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"#FFC23E"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint29_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint30_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint31_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint32_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint33_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint34_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint35_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint36_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint37_linear_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint38_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint39_radial_10246_159312)"}),e.createElement("path",{d:"M10.4437 1.23817C11.6483 1.06813 12.2267 2.26542 12.0802 3.30216C11.9943 3.45951 11.9337 3.79649 11.9141 3.94531L11.6992 8.10547C10.8008 9.25781 9.53125 8.96484 9.17969 7.71484L9.0626 4.15738C9.08973 3.10816 8.83799 1.46464 10.4437 1.23817Z",fill:"url(#paint40_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"#FFC23E"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint41_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint42_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint43_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint44_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint45_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint46_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint47_radial_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint48_linear_10246_159312)"}),e.createElement("path",{d:"M11.8994 4.15737C11.9482 2.8956 12.7903 2.56181 13.3594 2.57873C14.1794 2.60311 14.8301 3.32672 14.8047 4.15803L14.5987 8.92578C14.5501 9.1505 14.207 9.94531 13.2227 9.96094C12.2383 9.97656 11.8066 8.711 11.7139 8.07626L11.8994 4.15737Z",fill:"url(#paint49_radial_10246_159312)"})),Xv=44,eS=e=>e.getTime(),tS={position:"relative",height:"100%",width:"100%"},iS={position:"absolute",top:"0",left:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",objectPosition:"center",objectFit:"cover",zIndex:0},nS={width:"100%",height:"100%",zIndex:5},rS=cn({position:"absolute",bottom:"0",left:"0",padding:"0.5rem",width:"100%"}),aS=cn({backgroundColor:"inherit",boxShadow:"none",textAlign:"left",overflow:"hidden",whiteSpace:"nowrap",alignItems:"center",padding:"0.15rem",maxWidth:"100%"}),sS={padding:"0.1rem",fontSize:"0.75rem",fontWeight:600,color:"inherit",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%"},oS={padding:"0.125rem"},lS={margin:"auto",alignItems:"center","& svg":{display:"block",color:"inherit"}},cS=e=>({minWidth:"max-content",color:e.palette.black,fontSize:"0.75rem",lineHeight:"normal",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"0.1rem"}),dS={root:{zIndex:1,color:"inherit",top:"-0.125rem",height:"100%",padding:"0rem"},rootHovered:{background:"none"},rootPressed:{background:"none"},rootExpanded:{background:"none"}},uS=(e,t)=>cn({alignItems:"center",padding:"0.2rem 0.3rem",backgroundColor:e.palette.white,opacity:.9,borderRadius:"1rem",margin:"0.5rem",width:"fit-content",position:"absolute",top:0},t&&hS),hS={marginLeft:"auto",marginRight:"auto",left:0,right:0,bottom:0},pS=vn(((e,t)=>On({from:{backgroundPosition:"0px 0px"},to:{backgroundPosition:`0px ${t*-e}px`}})));function gS(t){const{onClick:i,onLongPress:n,touchEventsOnly:r=!1}=t,a=(0,e.useRef)(),[s,o]=(0,e.useState)(!1),[l,c]=(0,e.useState)(!1);(0,e.useEffect)((()=>(a.current&&clearTimeout(a.current),()=>{a.current&&clearTimeout(a.current)})),[i,n,r]);const d=(0,e.useCallback)((()=>{o(!1),a.current=setTimeout((()=>{o(!0),n()}),500)}),[n]),u=(0,e.useCallback)((()=>{!r&&i&&(s||i())}),[s,i,r]),h=(0,e.useCallback)((()=>{r||l&&(c(!1),d())}),[l,d,r]),p=(0,e.useCallback)((()=>{r||(c(!0),a.current&&clearTimeout(a.current))}),[r]),g=(0,e.useCallback)((()=>{r||d()}),[d,r]),m=(0,e.useCallback)((()=>{r||a.current&&clearTimeout(a.current)}),[r]),f=(0,e.useCallback)((()=>{d()}),[d]),v=(0,e.useCallback)((()=>{!s&&i&&i(),a.current&&clearTimeout(a.current)}),[i,s]),S=(0,e.useCallback)((()=>{a.current&&clearTimeout(a.current)}),[]);return(0,e.useMemo)((()=>({onClick:u,onMouseDown:g,onMouseUp:m,onTouchStart:f,onTouchEnd:v,onKeyDown:h,onKeyUp:p,onTouchMove:S})),[u,h,p,g,m,v,f,S])}const mS=100,fS=32,vS=t=>{const{text:i,noVideoAvailableAriaLabel:n,coinSize:r,hidePersonaDetails:a}=t;return e.createElement(Gs,{className:cn({position:"absolute",height:"100%",width:"100%"})},e.createElement(Gs,{styles:SS},r&&e.createElement(Jv,{coinSize:r,hidePersonaDetails:a,text:null!=i?i:"",initialsTextColor:"white","aria-label":null!=n?n:"",showOverflowTooltip:!1})))},SS={root:{margin:"auto",maxHeight:"100%"}},yS={iconName:void 0,style:{display:"none"}},CS={directionalHint:ll.topLeftEdge,isBeakVisible:!1,styles:{container:{maxWidth:"8rem"}}},_S=t=>{const{contextualMenu:i,canShowContextMenuButton:n}=t;if(!i)return e.createElement(e.Fragment,null);const r=n?"VideoTileMoreOptions":void 0;return e.createElement(th,{"data-ui-id":"video-tile-more-options-button",styles:dS,menuIconProps:yS,menuProps:Object.assign(Object.assign({},CS),i),iconProps:{iconName:r}})},ES=t=>{const{children:i,displayName:n,initialsName:r,isMirrored:a,isMuted:s,isSpotlighted:o,isPinned:l,onRenderPlaceholder:c,renderElement:d,overlay:u,showLabel:h=!0,showMuteIndicator:p=!0,styles:g,userId:m,noVideoAvailableAriaLabel:f,isSpeaking:v,raisedHand:S,personaMinSize:y=fS,personaMaxSize:C=mS,contextualMenu:_}=t,[E,T]=(0,e.useState)(!1),[b,I]=(0,e.useState)(!1),[w,R]=(0,e.useState)(1),A=(0,e.useRef)(null),P=_h(),M=Qh(),k=M.callingPalette,D=!!d,O=(0,e.useRef)(new ResizeObserver((e=>{const{width:t,height:i}=e[0].contentRect,n=Math.min(t,i)/3;n!==w&&R(Math.max(Math.min(n,C),y))})));(0,e.useLayoutEffect)((()=>{A.current&&O.current.observe(A.current);const e=O.current;return()=>e.disconnect()}),[A]),(0,e.useEffect)((()=>{if(void 0!==n)return;let e;return A.current&&(e=new MutationObserver((e=>{for(const t of e)if("childList"===t.type){const e=document.querySelector("iframe");e&&(e.getAttribute("tabIndex")||e.setAttribute("tabIndex","-1"))}})),e.observe(A.current,{childList:!0,subtree:!0})),()=>{null==e||e.disconnect()}}),[n,d]);const N=(0,e.useMemo)((()=>({onLongPress:()=>{var e;null===(e=t.onLongTouch)||void 0===e||e.call(t)},touchEventsOnly:!0})),[t.onLongTouch]),L=gS(N),x=(0,e.useMemo)((()=>({onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),onFocus:()=>I(!0),onBlur:()=>I(!1)})),[]),F={userId:m,text:null!=r?r:n,noVideoAvailableAriaLabel:f,coinSize:w,styles:SS,hidePersonaDetails:!0},U=cn(aS,{borderRadius:M.effects.roundedCorner4,backgroundColor:k.videoTileLabelBackgroundLight}),B=(0,e.useMemo)((()=>cn(D||t.alwaysShowLabelBackground?U:aS,null==g?void 0:g.displayNameContainer)),[D,U,null==g?void 0:g.displayNameContainer,t.alwaysShowLabelBackground]),V=Qv(),H=h&&(n||p&&s),$=TS(t,P),G=E||b;let j="";return j=k.raiseHandGold,e.createElement(Gs,Object.assign({"data-ui-id":V.videoTile,className:cn(tS,{background:M.palette.neutralLighter,borderRadius:M.effects.roundedCorner4},(v||S)&&{"&::after":{content:"''",position:"absolute",border:`0.25rem solid ${v?M.palette.themePrimary:j}`,borderRadius:M.effects.roundedCorner4,width:"100%",height:"100%",pointerEvents:"none"}},null==g?void 0:g.root)},L),e.createElement("div",Object.assign({ref:A,style:{width:"100%",height:"100%"}},x,{"data-is-focusable":!0}),D?e.createElement(Gs,{className:cn(iS,a&&{transform:"scaleX(-1)"},null==g?void 0:g.videoContainer)},d):e.createElement(Gs,{className:cn(iS,{opacity:$||"Idle"===t.participantState?.4:1})},c?c(null!=m?m:"",F,vS):e.createElement(vS,Object.assign({},F))),u,(H||$)&&e.createElement(Gs,{horizontal:!0,className:rS,tokens:bS},e.createElement(Gs,{horizontal:!0,className:B},H&&e.createElement(Cf,{className:cn(sS),title:n,style:{color:$?M.palette.neutralSecondary:"inherit"},"data-ui-id":"video-tile-display-name"},n),$&&e.createElement(Cf,{className:cn(cS(M))},IS($,!!H)),p&&s&&e.createElement(Gs,{className:cn(lS)},e.createElement(al,{iconName:"VideoTileMicOff"})),o&&e.createElement(Gs,{className:cn(lS)},e.createElement(al,{iconName:"VideoTileSpotlighted"})),l&&e.createElement(Gs,{className:cn(lS)},e.createElement(al,{iconName:"VideoTilePinned",className:cn(oS)})),e.createElement(_S,{contextualMenu:_,canShowContextMenuButton:G}))),i&&e.createElement(Gs,{className:cn(nS,null==g?void 0:g.overlayContainer)},i),S&&e.createElement(Gs,{horizontal:!0,tokens:{childrenGap:"0.2rem"},className:uS(M,!H)},e.createElement(Gs.Item,null,e.createElement(Cf,null,S.raisedHandOrderPosition)),e.createElement(Gs.Item,null,e.createElement(Zv,null)))))},TS=(e,t)=>{const i=Object.assign(Object.assign({},t.strings.videoTile),e.strings);return"EarlyMedia"===e.participantState||"Ringing"===e.participantState?null==i?void 0:i.participantStateRinging:"Hold"===e.participantState?null==i?void 0:i.participantStateHold:void 0},bS={childrenGap:"none"},IS=(e,t)=>t?`(${e})`:e,wS=e=>{const{participants:t,dominantSpeakers:i=[],currentParticipants:n=[],maxDominantSpeakers:r}=e;if(t.length<=r)return t;const a=RS(t),s=i.filter((e=>!!a[e])).slice(0,r),o=n.map((e=>e.userId)).slice(0,r),l=s.filter((e=>!o.includes(e)));for(let e=0;e<r;e++){const t=o[e];if(void 0===t||!s.includes(t)){const t=l.shift();if(!t)break;o[e]=t}}let c=o.map((e=>a[e])).filter((e=>void 0!==e));const d=new Set(o),u=t.filter((e=>!d.has(e.userId)));return c=c.concat(u),c},RS=e=>{const t={};return e.forEach((e=>t[e.userId]=e)),t},AS=6,PS=4,MS=t=>{var i,n;const r=t.remoteParticipants.reduce(((e,t)=>(e[t.userId]=t,e)),{}),a=null!==(i=t.spotlightedParticipantUserIds)&&void 0!==i?i:[],s=null!==(n=t.pinnedParticipantUserIds)&&void 0!==n?n:[],o=new Set(a.concat(s).filter((e=>r[e]))),l=[...o].map((e=>r[e])),c=(0,e.useRef)([]),d=(0,e.useRef)([]),u=t.remoteParticipants.filter((e=>!o.has(e.userId))),h=(e=>{const{remoteParticipants:t=[],dominantSpeakers:i=[],maxGridParticipants:n=PS,maxOverflowGalleryDominantSpeakers:r=AS,isScreenShareActive:a=!1,layout:s,previousGridParticipants:o=[],previousOverflowParticipants:l=[]}=e,c=OS(t),d=t.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})),u="floatingLocalVideo"===s&&d.length>0?d:c;let h=wS({participants:u,dominantSpeakers:i,currentParticipants:o,maxDominantSpeakers:n}).slice(0,n);const p="speaker"===s?i&&i[0]?h.filter((e=>e.userId===i[0])):[h[0]]:[];p[0]&&(h=p);const g=new Set(h.map((e=>e.userId))),m=c.filter((e=>"Connecting"===e.state)),f=new Set(m.map((e=>e.userId))),v=wS({participants:c.filter((e=>!g.has(e.userId)&&!f.has(e.userId))),dominantSpeakers:i,currentParticipants:l,maxDominantSpeakers:r});return{gridParticipants:kS({isScreenShareActive:a,gridParticipants:h,overflowGalleryParticipants:v,maxGridParticipants:n,callingParticipants:m}),overflowGalleryParticipants:DS({isScreenShareActive:a,gridParticipants:h,overflowGalleryParticipants:v,maxGridParticipants:n,callingParticipants:m})}})(Object.assign(Object.assign({},t),{maxGridParticipants:l.length>0||t.isScreenShareActive?0:t.maxGridParticipants,remoteParticipants:u,previousGridParticipants:c.current,previousOverflowParticipants:d.current}));return c.current=h.gridParticipants,d.current=h.overflowGalleryParticipants,l.length>0?{gridParticipants:t.isScreenShareActive?[]:l,overflowGalleryParticipants:t.isScreenShareActive?l.concat(h.overflowGalleryParticipants):h.overflowGalleryParticipants}:h},kS=e=>e.isScreenShareActive?[]:e.gridParticipants.length>0?e.gridParticipants:e.overflowGalleryParticipants.length>e.maxGridParticipants?e.overflowGalleryParticipants.slice(0,e.maxGridParticipants):e.overflowGalleryParticipants.slice(0,e.maxGridParticipants).concat(e.callingParticipants),DS=e=>e.isScreenShareActive?e.gridParticipants.concat(e.overflowGalleryParticipants.concat(e.callingParticipants)):e.gridParticipants.length>0?e.overflowGalleryParticipants.concat(e.callingParticipants):e.overflowGalleryParticipants.length>e.maxGridParticipants?e.overflowGalleryParticipants.slice(e.maxGridParticipants).concat(e.callingParticipants):[],OS=e=>{const t=[],i=[];return e.forEach((e=>{var n;(null===(n=e.videoStream)||void 0===n?void 0:n.isAvailable)?t.push(e):i.push(e)})),t.concat(i)},NS=(e,t)=>{var i,n,r,a,s;switch(e){case"like":return null===(i=t.likeReaction)||void 0===i?void 0:i.url;case"heart":return null===(n=t.heartReaction)||void 0===n?void 0:n.url;case"laugh":return null===(r=t.laughReaction)||void 0===r?void 0:r.url;case"applause":return null===(a=t.applauseReaction)||void 0===a?void 0:a.url;case"surprised":return null===(s=t.surprisedReaction)||void 0===s?void 0:s.url}},LS=(e,t)=>{var i,n,r,a,s,o,l,c,d,u;switch(e){case"like":return null!==(n=null===(i=t.likeReaction)||void 0===i?void 0:i.frameCount)&&void 0!==n?n:0;case"heart":return null!==(a=null===(r=t.heartReaction)||void 0===r?void 0:r.frameCount)&&void 0!==a?a:0;case"laugh":return null!==(o=null===(s=t.laughReaction)||void 0===s?void 0:s.frameCount)&&void 0!==o?o:0;case"applause":return null!==(c=null===(l=t.applauseReaction)||void 0===l?void 0:l.frameCount)&&void 0!==c?c:0;case"surprised":return null!==(u=null===(d=t.surprisedReaction)||void 0===d?void 0:d.frameCount)&&void 0!==u?u:0;default:return 0}},xS=e.memo((t=>{const{reaction:i,reactionResources:n,emojiSize:r=Xv}=t,[a,s]=(0,e.useState)(!1),o=void 0!==i&&void 0!==n?NS(null==i?void 0:i.reactionType,n):void 0,l=void 0!==i&&void 0!==n?LS(null==i?void 0:i.reactionType,n):void 0,c=Date.now(),d=i?eS(i.receivedOn):void 0,u=!!d&&c-d<4133&&void 0!==o;(0,e.useEffect)((()=>{if(o&&0!==o.length)return fetch(`${o}`).then((e=>{s(e.ok)})).catch((e=>console.warn(`Sprite image for animation rendering failed with warning: ${e}`))),()=>s(!1)}),[o]);const h=null!=o?o:void 0,p=(0,e.useCallback)((()=>(e=>{var t;const i=`url(${e.spriteImageUrl})`,n=null!==(t=e.frameCount)&&void 0!==t?t:0,r=e.rawFrameSize;return cn({height:`${r}px`,width:`${r}px`,overflow:"hidden",animationName:pS(r,n),backgroundImage:i,animationDuration:"4.133s",animationTimingFunction:`steps(${n})`,animationPlayState:"running",animationIterationCount:"infinite",transform:`scale(${e.emojiSize/r})`,transformOrigin:"top left"})})({spriteImageUrl:null!=h?h:"",emojiSize:r,frameCount:null!=l?l:51,rawFrameSize:128})),[h,r,l]);return e.createElement(Gs,{className:cn(iS,{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:u?"rgba(0, 0, 0, 0.5)":"transparent",borderRadius:"0.25rem"})},e.createElement("div",{style:{height:"33.33%"}}),u&&a&&e.createElement("div",{style:{minHeight:`${r}px`,height:`${r}px`,width:`${r}px`}},e.createElement("div",{className:p()})))})),FS={bottom:"0",height:"50%",pointerEvents:"none",position:"absolute",width:"100%"},US=[{sizeScale:.9,heightMaxScale:.7*.95,opacityMax:.9}];function BS(){return US[0]}const VS=vn(((e,t)=>On({"0%":{transform:`translateY(${e}px)`},"100%":{transform:`translateY(${t}px)`}}))),HS=vn((e=>On({"0%":{opacity:0},"31.2%":{opacity:e},"67.2%":{opacity:e},"100%":{opacity:0,display:"none",visibility:"hidden"}}))),$S=vn(((e,t)=>On({from:{backgroundPosition:"0px 0px"},to:{backgroundPosition:`0px -${e*t}px`}}))),GS=(e,t,i)=>({height:`${t}px`,width:`${t}px`,backgroundImage:`url(${i})`,backgroundRepeat:"no-repeat",animationName:$S(e,t),animationDuration:e/24+"s",animationFillMode:"forwards",animationIterationCount:"infinite",animationTimingFunction:`steps(${e})`,backgroundSize:`${t}px ${e*t}px`,transform:`scale(${t}/128)`}),jS=e.memo((t=>{const{reactionResources:i,localParticipant:n,remoteParticipants:r,hostDivHeight:a,hostDivWidth:s}=t,[o,l]=(0,e.useState)([]),c=(0,e.useRef)({}),d=(0,e.useRef)({like:0,heart:0,laugh:0,applause:0,surprised:0}),u=(0,e.useRef)(new Array(55).fill(!1)),h=(0,e.useMemo)((()=>{var e;return null!==(e=null==r?void 0:r.map((e=>e.reaction)).filter((e=>!!e)))&&void 0!==e?e:[]}),[r]),p=(0,e.useCallback)(((e,t)=>{var i;const n=((e,t,i)=>e+t+i.toISOString())(t,e.reactionType,e.receivedOn);if((null===(i=c.current[t])||void 0===i?void 0:i.id)===n)return;if(d.current[e.reactionType]>=10)return void(c.current[t]={id:n,status:"ignored"});d.current[e.reactionType]+=1,c.current[t]={id:n,status:"animating"};const r=u.current.findIndex((e=>!1===e));u.current[r]=!0,l([...o,{reaction:e,id:n,reactionMovementIndex:r,styleBucket:BS()}])}),[d,o]),g=(e,t,i)=>{l(o.filter((e=>e.id!==t))),u.current[i]=!1,d.current[e]-=1,Object.entries(c.current).forEach((([e,i])=>{i.id===t&&(c.current[e].status="completedAnimating")}))};(0,e.useEffect)((()=>{(null==n?void 0:n.reaction)&&p(n.reaction,n.userId)}),[n,p]),(0,e.useEffect)((()=>{null==r||r.map((e=>{(null==e?void 0:e.reaction)&&p(e.reaction,e.userId)}))}),[h,r,p]);const m=()=>Xv*BS().sizeScale,f=null!=a?a:0,v=(null!=s?s:0)-m();return e.createElement(Gs,{className:cn(iS,{display:"flex",justifyContent:"center",alignItems:"center",backgroundColor:"transparent"})},o.map((t=>{var n,r,a,s,o,l;return e.createElement("div",{key:t.id,style:FS},e.createElement("div",{className:"reaction-item"},((e,t,i)=>{const n=Date.now()-eS(e.receivedOn)<4133;return n||g(null==e?void 0:e.reactionType,t,i),n})(t.reaction,t.id,t.reactionMovementIndex)&&e.createElement("div",{style:(a=f/2,s=f/2*(1-t.styleBucket.heightMaxScale),{animationName:VS(a,s),animationFillMode:"forwards",animationDuration:"4.133s",animationTimingFunction:"cubic-bezier(0, 0.83, 0.19, 1.09)"})},e.createElement("div",{onAnimationEnd:()=>{g(t.reaction.reactionType,t.id,t.reactionMovementIndex)},style:(r=t.styleBucket.opacityMax,{animationName:HS(r),animationFillMode:"forwards",animationDuration:"4.133s"})},e.createElement("div",{style:(o=t.reactionMovementIndex,l=(e=>function(e,t,i=!0){const n=i?t:0,r=0===e?0:e%2*2-1;if(0===r)return n;const a=function(e){switch(e){case 1:case 2:return.3;case 3:case 4:return.6;case 5:case 6:return.9;case 7:case 8:return.75;case 9:case 18:return.375;case 10:case 23:return.525;case 11:case 16:return.15;case 12:case 15:return.225;case 13:case 14:return.075;case 17:case 24:return.45;case 19:case 20:return.675;case 21:case 22:return.825;default:return 0}}(e);return n+r*a*t}(e,v/2,!0))(o),{position:"absolute",left:`${l}px`})},e.createElement("div",{style:GS(51,m(),null!==(n=NS(null==t?void 0:t.reaction.reactionType,i))&&void 0!==n?n:"")}))))))})))})),zS=t=>{const{overlayMode:i,reaction:n,reactionResources:r,localParticipant:a,remoteParticipants:s}=t,[o,l]=(0,e.useState)(0),[c,d]=(0,e.useState)(0),[u,h]=(0,e.useState)(0),p=(0,e.useRef)(null),g=(0,e.useRef)(new ResizeObserver((e=>{var t;const i=null===(t=e.at(0))||void 0===t?void 0:t.contentRect,n=void 0!==i?i.width:0,r=void 0!==i?i.height:0,a=Math.min(n,r)/3;a!==o&&l(Math.max(Math.min(a,70),32)),r!==c&&d(r),n!==u&&h(n)})));return(0,e.useLayoutEffect)((()=>{p.current&&g.current.observe(p.current);const e=g.current;return()=>e.disconnect()}),[p]),"grid-tiles"===i?e.createElement("div",{ref:p,style:{width:"100%",height:"100%",pointerEvents:"none"}},e.createElement(xS,{emojiSize:o,reaction:n,reactionResources:r})):"screen-share"===t.overlayMode||"content-share"===t.overlayMode?e.createElement("div",{ref:p,style:{width:"100%",height:"100%",pointerEvents:"none"}},e.createElement(jS,{hostDivHeight:c,hostDivWidth:u,reactionResources:r,localParticipant:a,remoteParticipants:s})):e.createElement(e.Fragment,null)},WS=e.memo((t=>{var i;const{isAvailable:n,isReceiving:r=!0,isScreenSharingOn:a,onCreateRemoteStreamView:s,onDisposeRemoteStreamView:o,remoteVideoViewOptions:l,renderElement:c,userId:d,onRenderAvatar:u,showMuteIndicator:h,remoteParticipant:p,participantState:g,menuKind:m,isPinned:f,onPinParticipant:v,onUnpinParticipant:S,spotlightedParticipantUserIds:y,isSpotlighted:C,onStartSpotlight:_,onStopSpotlight:E,maxParticipantsToSpotlight:T,onUpdateScalingMode:b,disablePinMenuItem:I,toggleAnnouncerString:w,strings:R,reactionResources:A,streamId:P}=t,M=(t=>{const{remoteParticipantId:i,onCreateRemoteStreamView:n,onDisposeRemoteStreamView:r}=t,a=(0,e.useMemo)((()=>e=>null==n?void 0:n(i,e)),[n,i]),s=(0,e.useMemo)((()=>()=>{null==r||r(i)}),[r,i]);return Xf(Object.assign(Object.assign({},t),{onCreateStreamView:a,onDisposeStreamView:s}))})((0,e.useMemo)((()=>({isMirrored:null==l?void 0:l.isMirrored,isScreenSharingOn:a,isStreamAvailable:n,isStreamReceiving:r,onCreateRemoteStreamView:s,onDisposeRemoteStreamView:o,remoteParticipantId:d,renderElementExists:!!c,scalingMode:null==l?void 0:l.scalingMode,streamId:P})),[n,r,a,s,o,null==l?void 0:l.isMirrored,null==l?void 0:l.scalingMode,c,d,P])),k=tv({participant:p,view:null==M?void 0:M.view,strings:Object.assign({},t.strings),isPinned:f,onPinParticipant:v,onUnpinParticipant:S,onUpdateScalingMode:b,disablePinMenuItem:I,toggleAnnouncerString:w,spotlightedParticipantUserIds:y,isSpotlighted:C,onStartSpotlight:_,onStopSpotlight:E,maxParticipantsToSpotlight:T}),D=(0,e.useMemo)((()=>"contextual"===m&&k?{contextualMenu:k}:{}),[k,m]),O=n&&!1===r&&"Disconnected"!==g,[N,L]=e.useState([]),x=(0,e.useMemo)((()=>{if(c&&c.childElementCount)return e.createElement(Yf,{videoStreamElement:c,loadingState:O?"loading":"none"})}),[c,O]),F=(0,e.useCallback)((e=>{"Enter"===e.key&&L(qS(k,(()=>L([]))))}),[L,k]);let U=p.displayName||R.displayNamePlaceholder;const B=e.createElement(zS,{overlayMode:"grid-tiles",reaction:p.reaction,reactionResources:A});return e.createElement(Gs,{tabIndex:"drawer"===m?0:void 0,onKeyDown:"drawer"===m?F:void 0,style:Qf},e.createElement(ES,Object.assign({key:d,userId:d,initialsName:null!==(i=p.displayName)&&void 0!==i?i:"",renderElement:x,displayName:U,onRenderPlaceholder:u,isMuted:p.isMuted,raisedHand:p.raisedHand,isSpeaking:p.isSpeaking,showMuteIndicator:h,personaMinSize:t.personaMinSize,showLabel:t.showLabel,alwaysShowLabelBackground:t.alwaysShowLabelBackground,participantState:g},D,{isPinned:t.isPinned,onLongTouch:()=>L(qS(k,(()=>L([])))),isSpotlighted:C,overlay:B})),N.length>0&&e.createElement(Ld,{hostId:t.drawerMenuHostId},e.createElement(Gs,{styles:Zf},e.createElement(jf,{onLightDismiss:()=>L([]),items:N,heading:p.displayName}))))})),qS=(e,t)=>e?e.items.map((e=>({itemKey:e.key,text:e.text,iconProps:e.iconProps,disabled:e.disabled,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),null==t||t()}}))):[],KS=cn({width:"100%",height:"100%"}),JS=e=>cn({backgroundColor:"inherit",padding:"1rem",maxWidth:"95%",borderRadius:e.effects.roundedCorner4,color:e.palette.neutralSecondary}),YS=cn({height:"2rem",lineHeight:0}),QS=e=>cn({transform:"scale(2.5)",color:e.palette.neutralTertiary}),ZS=cn({fontSize:"1rem",color:"inherit"}),XS=e.memo((t=>{const{localParticipant:i}=t,n=Qh(),r=_h();if(!i||!i.isScreenSharingOn)return null;const a=e.createElement(Gs,{horizontalAlign:"center",verticalAlign:"center",className:KS},e.createElement(Gs,{horizontalAlign:"center",verticalAlign:"center",className:JS(n),tokens:{childrenGap:"1rem"}},e.createElement(Gs,{horizontal:!0,verticalAlign:"center",className:YS},e.createElement(al,{iconName:"ControlButtonScreenShareStart",className:QS(n)})),e.createElement(Cf,{className:ZS,"aria-live":"polite"},r.strings.videoGallery.screenIsBeingSharedMessage))),s=(null==i?void 0:i.displayName)?null==i?void 0:i.displayName:r.strings.videoGallery.displayNamePlaceholder;return e.createElement(ES,{displayName:s,isMuted:null==i?void 0:i.isMuted,onRenderPlaceholder:()=>e.createElement(e.Fragment,null)},a)})),ey=cn({height:"100%",width:"100%"}),ty=e.memo((t=>{const{userId:i,displayName:n,isMuted:r,renderElement:a,onCreateRemoteStreamView:s,onDisposeRemoteStreamView:o,isReceiving:l,participantVideoScalingMode:c,reactionResources:d,localParticipant:u,remoteParticipants:h,isPPTLive:p}=t,g=_h();a||s&&s(i,c),(0,e.useEffect)((()=>()=>{o&&o(i)}),[o,i]);const m=n?ev(g.strings.videoGallery.screenShareLoadingMessage,{participant:n}):"";return p?e.createElement(ES,{renderElement:a?e.createElement(Yf,{videoStreamElement:a,loadingState:!1===l?"loading":"none"}):void 0,onRenderPlaceholder:()=>e.createElement(iy,{loadingMessage:m}),overlay:e.createElement(zS,{reactionResources:d,localParticipant:u,remoteParticipants:h,overlayMode:"screen-share"})}):e.createElement(ES,{displayName:n,isMuted:r,renderElement:a?e.createElement(Yf,{videoStreamElement:a,loadingState:!1===l?"loading":"none"}):void 0,onRenderPlaceholder:()=>e.createElement(iy,{loadingMessage:m}),overlay:e.createElement(zS,{reactionResources:d,localParticipant:u,remoteParticipants:h,overlayMode:"screen-share"})})})),iy=t=>e.createElement(Gs,{verticalAlign:"center",className:ey},e.createElement(Fm,{label:t.loadingMessage,size:km.xSmall,"aria-live":"assertive"})),ny=cn({position:"relative",width:"100%",height:"100%"}),ry=(e,t)=>({root:{position:"absolute",width:bm("large"===t?40:32),height:bm("large"===t?40:32),right:"0rem",top:"0rem",color:"#FFFFFF",zIndex:2,background:"rgba(0,0,0,0.4)",borderRadius:e.effects.roundedCorner2},rootFocused:{color:"#FFFFFF",background:"rgba(0,0,0,0.4)"},rootDisabled:{position:"absolute"},icon:{paddingLeft:bm(3),paddingRight:bm(3),margin:0},flexContainer:{paddingBottom:bm(8),height:"unset"}}),ay={root:{width:"100%",height:"100%"}};const sy=t=>{const{cameras:i,selectedCamera:n,onSelectCamera:r,label:a,ariaDescription:s,size:o}=t,l=xh(),[c,d]=(0,e.useState)(!1),u=(0,e.useCallback)((e=>{return t=void 0,i=void 0,a=function*(){if(r){d(!0);try{yield r(e)}finally{d(!1)}}},new((n=void 0)||(n=Promise))((function(e,r){function s(e){try{l(a.next(e))}catch(e){r(e)}}function o(e){try{l(a.throw(e))}catch(e){r(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(s,o)}l((a=a.apply(t,i||[])).next())}));var t,i,n,a}),[r]),h=!!c,p=_h().strings.cameraButton.tooltipVideoLoadingContent;return e.createElement(th,{"data-ui-id":"local-camera-switcher-button",styles:ry(l,o),disabled:h,iconProps:{iconName:"LocalCameraSwitch"},ariaLabel:a,ariaDescription:h?p:s,"aria-live":"polite",onClick:()=>{if(i&&i.length>1&&void 0!==n){const e=i.findIndex((e=>n.id===e.id)),t=i[(e+1)%i.length];u(t)}}})},oy=e.memo((t=>{const{isAvailable:i,isMuted:n,onCreateLocalStreamView:r,onDisposeLocalStreamView:a,localVideoViewOptions:s,renderElement:o,userId:l,showLabel:c,alwaysShowLabelBackground:d,displayName:u,initialsName:h,onRenderAvatar:p,showMuteIndicator:g,styles:m,showCameraSwitcherInLocalPreview:f,localVideoCameraCycleButtonProps:v,localVideoCameraSwitcherLabel:S,localVideoSelectedDescription:y,raisedHand:C,reaction:_,isSpotlighted:E,spotlightedParticipantUserIds:T,onStartSpotlight:b,onStopSpotlight:I,maxParticipantsToSpotlight:w,menuKind:R,strings:A,reactionResources:P}=t,M=Qh();(t=>{const{onCreateLocalStreamView:i,onDisposeLocalStreamView:n}=t,r=(0,e.useMemo)((()=>e=>null==i?void 0:i(e)),[i]),a=(0,e.useMemo)((()=>()=>{null==n||n()}),[n]);Xf(Object.assign(Object.assign({},t),{onCreateStreamView:r,onDisposeStreamView:a}))})((0,e.useMemo)((()=>({isMirrored:null==s?void 0:s.isMirrored,isStreamAvailable:i,onCreateLocalStreamView:r,onDisposeLocalStreamView:a,renderElementExists:!!o,scalingMode:null==s?void 0:s.scalingMode})),[i,null==s?void 0:s.isMirrored,null==s?void 0:s.scalingMode,r,a,o]));const k=tv({participant:{userId:null!=l?l:""},strings:Object.assign({},A),spotlightedParticipantUserIds:T,isSpotlighted:E,onStartSpotlight:b,onStopSpotlight:I,maxParticipantsToSpotlight:w,myUserId:l}),D=(0,e.useMemo)((()=>"contextual"===R&&k?{contextualMenu:k}:{}),[k,R]),O=(0,e.useMemo)((()=>E?Qa({root:{outline:`0.25rem solid ${M.palette.neutralTertiaryAlt}`,outlineOffset:"-0.25rem"}},m):m),[E,M.palette.neutralTertiaryAlt,m]),[N,L]=e.useState([]),x=(0,e.useCallback)((e=>{"Enter"===e.key&&L(cy(k,(()=>L([]))))}),[L,k]),F=(0,e.useMemo)((()=>{if(o&&o.childElementCount)return e.createElement(e.Fragment,null,e.createElement(ly,{showCameraSwitcherInLocalPreview:null!=f&&f,localVideoCameraCycleButtonProps:v,localVideoCameraSwitcherLabel:S,localVideoSelectedDescription:y}),e.createElement(Yf,{videoStreamElement:o,isMirrored:!0}))}),[v,S,y,o,f]),U=void 0!==P?e.createElement(zS,{overlayMode:"grid-tiles",reaction:_,reactionResources:P}):void 0;return e.createElement(Gs,{className:cn({width:"100%",height:"100%"}),onKeyDown:"drawer"===R?x:void 0},e.createElement(ES,Object.assign({key:null!=l?l:"local-video-tile",userId:l,renderElement:F,showLabel:c,alwaysShowLabelBackground:d,displayName:u,initialsName:h,styles:O,onRenderPlaceholder:p,isMuted:n,showMuteIndicator:g,personaMinSize:t.personaMinSize,raisedHand:C,isSpotlighted:E},D,{onLongTouch:()=>L(cy(k,(()=>L([])))),overlay:U}),N.length>0&&e.createElement(Ld,{hostId:t.drawerMenuHostId},e.createElement(Gs,{styles:Zf},e.createElement(jf,{onLightDismiss:()=>L([]),items:N})))))})),ly=t=>{const{showCameraSwitcherInLocalPreview:i,localVideoCameraCycleButtonProps:n,localVideoCameraSwitcherLabel:r,localVideoSelectedDescription:a}=t,s=(null==n?void 0:n.selectedCamera)&&a&&ev(a,{cameraName:n.selectedCamera.name});return e.createElement(Gs,{horizontalAlign:"end"},i&&void 0!==(null==n?void 0:n.cameras)&&void 0!==(null==n?void 0:n.selectedCamera)&&void 0!==(null==n?void 0:n.onSelectCamera)&&e.createElement(sy,{cameras:n.cameras,selectedCamera:n.selectedCamera,onSelectCamera:n.onSelectCamera,label:r,ariaDescription:s}))},cy=(e,t)=>e?e.items.map((e=>({itemKey:e.key,text:e.text,iconProps:e.iconProps,disabled:e.disabled,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),null==t||t()}}))):[],dy=cn({width:"100%",height:"100%",display:"grid",gridGap:"0.5rem"}),uy=t=>{const{children:i,styles:n}=t,r=e.Children.count(i),[a,s]=(0,e.useState)(0),[o,l]=(0,e.useState)(0),c=(0,e.useRef)(null),d=(0,e.useRef)(new ResizeObserver((e=>{const{width:t,height:i}=e[0].contentRect;s(t),l(i)})));(0,e.useEffect)((()=>{c.current&&d.current.observe(c.current);const e=d.current;return()=>e.disconnect()}),[d,c]);const u=(0,e.useMemo)((()=>gy(r,a,o)),[r,a,o]),h=(0,e.useMemo)((()=>my(r,u)),[r,u]);return e.createElement("div",{ref:c,className:cn(dy,h,null==n?void 0:n.root),"data-ui-id":"grid-layout"},i)},hy=16/9,py=8/9,gy=(e,t,i)=>{if(e<=0)return{fillDirection:"horizontal",rows:0,columns:0};if(t<=0||i<=0)return{fillDirection:"horizontal",rows:Math.ceil(Math.sqrt(e)),columns:Math.ceil(Math.sqrt(e))};const n=t/i;let r=Math.floor(Math.sqrt(hy/n*e))||1;r=Math.min(r,e);let a=Math.ceil(e/r),s="horizontal";for(;r<e;){if(!(r/a*n<py)){if(e<r*a){const t=e>=r+(a-1)*(r-1),i=e>=a+(r-1)*(a-1);if(!t&&!i){r+=1,a=Math.ceil(e/r);continue}if(!t)break;if(!i){s="vertical";break}const d=(r-1)/a*n;d>=py&&(o=d,l=r/(a-1)*n,c=hy,Math.abs(c-o)<Math.abs(c-l)&&(s="vertical"))}break}r+=1,a=Math.ceil(e/r)}var o,l,c;return{fillDirection:s,rows:r,columns:a}},my=(e,t)=>{const i="horizontal"===t.fillDirection,n=i?t.rows:t.columns,r=Math.ceil(e/n),a=Math.floor(e/n),s=(t.rows*t.columns-e)*a,o=r*a;return cn(i?{gridTemplateColumns:`repeat(${o}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${n}, minmax(0, 1fr))`,gridAutoFlow:"row"}:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`,gridTemplateRows:`repeat(${o}, minmax(0, 1fr))`,gridAutoFlow:"column"},i?{"> *":{gridColumn:"auto / span "+o/r}}:{"> *":{gridRow:"auto / span "+o/r}},s?{[`> *:nth-last-child(-n + ${s})`]:i?{gridColumn:"auto / span "+o/a}:{gridRow:"auto / span "+o/a}}:{})},fy={root:{position:"relative",height:"100%",width:"100%",padding:"0.5rem"}},vy={childrenGap:"0.5rem"};var Sy=vn((function(e,t,i){var n=Zu(e),r=Xu(e);return Qa(n,{root:{minWidth:"80px",height:"32px"},label:{fontWeight:Mr.semibold}},i?function(e){var t,i,n,r,a,s,o,l,c,d=e.palette,u=e.semanticColors;return{root:{backgroundColor:u.primaryButtonBackground,border:"1px solid ".concat(u.primaryButtonBackground),color:u.primaryButtonText,selectors:(t={},t[Nr]=Ii({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t[".".concat(Vr," &:focus")]={selectors:{":after":{border:"none",outlineColor:d.white}}},t)},rootHovered:{backgroundColor:u.primaryButtonBackgroundHovered,border:"1px solid ".concat(u.primaryButtonBackgroundHovered),color:u.primaryButtonTextHovered,selectors:(i={},i[Nr]={color:"Window",backgroundColor:"Highlight",borderColor:"Highlight"},i)},rootPressed:{backgroundColor:u.primaryButtonBackgroundPressed,border:"1px solid ".concat(u.primaryButtonBackgroundPressed),color:u.primaryButtonTextPressed,selectors:(n={},n[Nr]=Ii({color:"Window",backgroundColor:"WindowText",borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)},rootExpanded:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootChecked:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootCheckedHovered:{backgroundColor:u.primaryButtonBackgroundPressed,color:u.primaryButtonTextPressed},rootDisabled:{color:u.primaryButtonTextDisabled,backgroundColor:u.primaryButtonBackgroundDisabled,selectors:(r={},r[Nr]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},r)},splitButtonContainer:{selectors:(a={},a[Nr]={border:"none"},a)},splitButtonDivider:Ii(Ii({},{position:"absolute",width:1,right:31,top:8,bottom:8}),{backgroundColor:d.white,selectors:(s={},s[Nr]={backgroundColor:"Window"},s)}),splitButtonMenuButton:{backgroundColor:u.primaryButtonBackground,color:u.primaryButtonText,selectors:(o={},o[Nr]={backgroundColor:"Canvas"},o[":hover"]={backgroundColor:u.primaryButtonBackgroundHovered,selectors:(l={},l[Nr]={color:"Highlight"},l)},o)},splitButtonMenuButtonDisabled:{backgroundColor:u.primaryButtonBackgroundDisabled,selectors:{":hover":{backgroundColor:u.primaryButtonBackgroundDisabled}}},splitButtonMenuButtonChecked:{backgroundColor:u.primaryButtonBackgroundPressed,selectors:{":hover":{backgroundColor:u.primaryButtonBackgroundPressed}}},splitButtonMenuButtonExpanded:{backgroundColor:u.primaryButtonBackgroundPressed,selectors:{":hover":{backgroundColor:u.primaryButtonBackgroundPressed}}},splitButtonMenuIcon:{color:u.primaryButtonText},splitButtonMenuIconDisabled:{color:d.neutralTertiary,selectors:(c={},c[Nr]={color:"GrayText"},c)}}}(e):function(e){var t,i,n,r,a,s=e.semanticColors,o=e.palette,l=s.buttonBackground,c=s.buttonBackgroundPressed,d=s.buttonBackgroundHovered,u=s.buttonBackgroundDisabled,h=s.buttonText,p=s.buttonTextHovered,g=s.buttonTextDisabled,m=s.buttonTextChecked,f=s.buttonTextCheckedHovered;return{root:{backgroundColor:l,color:h},rootHovered:{backgroundColor:d,color:p,selectors:(t={},t[Nr]={borderColor:"Highlight",color:"Highlight"},t)},rootPressed:{backgroundColor:c,color:m},rootExpanded:{backgroundColor:c,color:m},rootChecked:{backgroundColor:c,color:m},rootCheckedHovered:{backgroundColor:c,color:f},rootDisabled:{color:g,backgroundColor:u,selectors:(i={},i[Nr]={color:"GrayText",borderColor:"GrayText",backgroundColor:"Window"},i)},splitButtonContainer:{selectors:(n={},n[Nr]={border:"none"},n)},splitButtonMenuButton:{color:o.white,backgroundColor:"transparent",selectors:{":hover":{backgroundColor:o.neutralLight,selectors:(r={},r[Nr]={color:"Highlight"},r)}}},splitButtonMenuButtonDisabled:{backgroundColor:s.buttonBackgroundDisabled,selectors:{":hover":{backgroundColor:s.buttonBackgroundDisabled}}},splitButtonDivider:Ii(Ii({},{position:"absolute",width:1,right:31,top:8,bottom:8}),{backgroundColor:o.neutralTertiaryAlt,selectors:(a={},a[Nr]={backgroundColor:"WindowText"},a)}),splitButtonDividerDisabled:{backgroundColor:e.palette.neutralTertiaryAlt},splitButtonMenuButtonChecked:{backgroundColor:o.neutralQuaternaryAlt,selectors:{":hover":{backgroundColor:o.neutralQuaternaryAlt}}},splitButtonMenuButtonExpanded:{backgroundColor:o.neutralQuaternaryAlt,selectors:{":hover":{backgroundColor:o.neutralQuaternaryAlt}}},splitButtonMenuIcon:{color:s.buttonText},splitButtonMenuIconDisabled:{color:s.buttonTextDisabled}}}(e),r,t)})),yy=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.primary,n=void 0!==i&&i,r=t.styles,a=t.theme;return e.createElement(Wu,Ii({},this.props,{variantClassName:n?"ms-Button--primary":"ms-Button--default",styles:Sy(a,r,n),onRenderDescription:Ro}))},Ri([qu("DefaultButton",["theme","styles"],!0)],i)}(e.Component);const Cy=e=>({background:"none",padding:0,height:"auto",minWidth:"1.75rem",maxWidth:"1.75rem",border:`1px solid ${e.palette.neutralLight}`,borderRadius:e.effects.roundedCorner4}),_y={height:"100%",width:"100%",gap:"0.5rem"},Ey={height:"100%",width:"100%",gap:"0.5rem"};function Ty(e,t){const i=[];if(t<=0)return i;for(let n=0;n<e.length;n+=t)i.push(e.slice(n,n+t));return i}const by=5,Iy=t=>{var i;const{children:n,childrenPerPage:r=by,styles:a,onFetchTilesToRender:s}=t,o=Qv(),[l,c]=(0,e.useState)(0),d=e.Children.count(n),u=Math.ceil(d/r)-1,h=(0,e.useMemo)((()=>Ty([...Array(d).keys()],r)),[d,r]);(0,e.useEffect)((()=>{s&&h&&s(h[l])}),[h,s,l]);const p=l*r<d-1?l:u,g=(0,e.useMemo)((()=>void 0!==h[0]?h[p].map((t=>e.Children.toArray(n)[t])):[]),[h,p,n]),m=d>r,f=0===l,v=l===u,S=(0,e.useMemo)((()=>({root:null==a?void 0:a.children})),[null==a?void 0:a.children]);return r<=0?e.createElement(e.Fragment,null):e.createElement(Gs,{horizontal:!0,className:cn(_y,null===(i=t.styles)||void 0===i?void 0:i.root)},m&&e.createElement(wy,{key:"previous-nav-button",icon:e.createElement(al,{iconName:"HorizontalGalleryLeftButton"}),styles:null==a?void 0:a.previousButton,onClick:()=>c(Math.max(0,Math.min(u,l-1))),disabled:f,identifier:o.overflowGalleryLeftNavButton}),e.createElement(Gs,{horizontal:!0,className:cn(Ey)},g.map(((t,i)=>e.createElement(Gs.Item,{styles:S,key:i,"data-ui-id":o.horizontalGalleryVideoTile},t)))),m&&e.createElement(wy,{key:"next-nav-button",icon:e.createElement(al,{iconName:"HorizontalGalleryRightButton"}),styles:null==a?void 0:a.nextButton,onClick:()=>c(Math.min(u,l+1)),disabled:v,identifier:o.overflowGalleryRightNavButton}))},wy=t=>{const i=Qh();return e.createElement(yy,{className:cn(Cy(i),t.styles),onClick:t.onClick,disabled:t.disabled,"data-ui-id":t.identifier},t.icon)},Ry=(cn({position:"relative",width:"100%",height:"100%"}),{width:3.625,height:6.5}),Ay={width:13.438,height:7.5},Py={width:9,height:5.063},My={width:11,height:6.25},ky=(e,t,i,n)=>({width:i?`${t.width}rem`:"",height:i?`${t.height}rem`:"",minWidth:i?"":`${t.width}rem`,minHeight:i?"":`${t.height}rem`,position:"absolute",bottom:"horizontalTop"!==n?`${Oy}rem`:"unset",top:"horizontalTop"===n?`${Oy}rem`:"unset",borderRadius:e.effects.roundedCorner4,overflow:"hidden",right:`${Oy}rem`}),Dy=(e,t)=>Qa(ky(e,t),{root:{boxShadow:e.effects.elevation8}}),Oy=.5,Ny={root:{position:"absolute",zIndex:2,height:"100%",width:"100%"}},Ly={keyboardMoveIconContainer:{zIndex:3}},xy=6.5,Fy=6.5,Uy=7.5,By=7.5,Vy={minHeight:`${xy}rem`,minWidth:`${Fy}rem`,maxHeight:`${xy}rem`,maxWidth:`${Fy}rem`},Hy={minHeight:`${Uy}rem`,minWidth:`${By}rem`,maxHeight:`${Uy}rem`,maxWidth:`${13.43}rem`,width:"100%",height:"100%"},$y={minHeight:"5.625rem",minWidth:"9rem",maxHeight:"9rem",maxWidth:"9rem",width:"100%",height:"100%"},Gy={minHeight:"6.75rem",minWidth:"11rem",maxHeight:"11rem",maxWidth:"11rem",width:"100%",height:"100%"},jy=t=>{const{gapWidthRem:i,buttonWidthRem:n=0,onFetchTilesToRender:r,onChildrenPerPageChange:a}=t,s=(0,e.useRef)(null),o=af(s),l=s.current?parseFloat(getComputedStyle(s.current).paddingLeft):0,c=s.current?parseFloat(getComputedStyle(s.current).paddingRight):0,d=(e=>{const{numberOfChildren:t,containerWidth:i,buttonWidthRem:n,gapWidthRem:r}=e,a=ef(By),s=ef(r),o=Math.floor((i+s)/(a+s));if(t<=o)return o;const l=i-2*ef(n)-2*s;return Math.max(Math.floor((l+s)/(a+s)),1)})({numberOfChildren:e.Children.count(t.children),containerWidth:(null!=o?o:0)-l-c,gapWidthRem:i,buttonWidthRem:n});return null==a||a(d),e.createElement("div",{"data-ui-id":"responsive-horizontal-gallery",ref:s,className:cn(t.containerStyles)},e.createElement(Iy,{childrenPerPage:d,styles:t.horizontalGalleryStyles,onFetchTilesToRender:r},t.children))},zy={height:"100%",width:"inherit",gap:"0.5rem",position:"relative"},Wy={height:"2rem",width:"100%",position:"absolute",bottom:"0"},qy=e=>({background:"none",padding:0,height:"auto",borderRadius:e.effects.roundedCorner4,border:"none",minWidth:"2rem"}),Ky={lineHeight:"2rem",width:"100%",textAlign:"center"},Jy={root:{lineHeight:"0"}},Yy=t=>{const{children:i,styles:n,childrenPerPage:r,onFetchTilesToRender:a}=t,[s,o]=(0,e.useState)(1),[l,c]=(0,e.useState)({previous:!0,next:!0}),d=Qv(),u=e.Children.count(i),h=Math.ceil(u/r),p=(0,e.useMemo)((()=>Ty([...Array(u).keys()],r)),[u,r]);(0,e.useEffect)((()=>{a&&p&&a(p[s-1])}),[p,a,s]);const g=(s-1)*r<u-1?s:h,m=(0,e.useMemo)((()=>{if(void 0!==p[0])return p[g-1].map((t=>e.Children.toArray(i)[t]))}),[p,g,i]),f=u>r;s>h&&h>0&&o(h),(0,e.useEffect)((()=>{s>1&&s<h&&f?c({previous:!1,next:!1}):1===s&&f?c({previous:!0,next:!1}):s===h&&f&&c({previous:!1,next:!0})}),[s,u,h,f]);const v=(0,e.useMemo)((()=>({root:(2,{width:"100%",height:"calc(100% - 2.5rem)",gap:"0.5rem"})})),[]),S=(0,e.useMemo)((()=>({root:null==n?void 0:n.children})),[null==n?void 0:n.children]);return r<=0?e.createElement(e.Fragment,null):e.createElement(Gs,{className:cn(zy,null==n?void 0:n.root)},e.createElement(Gs,{styles:v},null==m?void 0:m.map(((t,i)=>e.createElement(Gs.Item,{key:i,styles:S,"data-ui-id":d.verticalGalleryVideoTile},t)))),f&&e.createElement(Qy,{buttonsDisabled:l,onPreviousButtonClick:()=>{o(s-1)},onNextButtonClick:()=>{o(s+1)},totalPages:h,currentPage:s}))},Qy=t=>{const{onNextButtonClick:i,onPreviousButtonClick:n,buttonsDisabled:r,currentPage:a,totalPages:s,styles:o}=t,l=Qh(),c=Qv(),d=_h().strings.verticalGallery,u=(0,e.useMemo)((()=>cn(Wy,null==o?void 0:o.root)),[null==o?void 0:o.root]),h=(0,e.useMemo)((()=>cn(qy(l),null==o?void 0:o.previousButton)),[null==o?void 0:o.previousButton,l]),p=(0,e.useMemo)((()=>cn(Ky,null==o?void 0:o.counter)),[null==o?void 0:o.counter]),g=(0,e.useMemo)((()=>cn(qy(l),null==o?void 0:o.nextButton)),[null==o?void 0:o.nextButton,l]);return e.createElement(Gs,{horizontalAlign:"center",tokens:{childrenGap:"0.5rem"},horizontal:!0,className:u},e.createElement(yy,{className:h,onClick:n,disabled:null==r?void 0:r.previous,ariaLabel:d.leftNavButtonAriaLabel,"data-ui-id":c.overflowGalleryLeftNavButton},e.createElement(al,{iconName:"VerticalGalleryLeftButton",styles:Jy})),e.createElement(Cf,{"data-ui-id":c.verticalGalleryPageCounter,className:p},`${a} / ${s}`),e.createElement(yy,{className:g,onClick:i,disabled:null==r?void 0:r.next,ariaLabel:d.rightNavButtonAriaLabel,"data-ui-id":c.overflowGalleryRightNavButton},e.createElement(al,{iconName:"VerticalGalleryRightButton",styles:Jy})))},Zy=t=>{var i;const{children:n,containerStyles:r,verticalGalleryStyles:a,gapHeightRem:s,controlBarHeightRem:o,isShort:l,onFetchTilesToRender:c,onChildrenPerPageChange:d}=t,u=(0,e.useRef)(null),h=sf(u),p=u.current?parseFloat(getComputedStyle(u.current).paddingTop):0,g=u.current?parseFloat(getComputedStyle(u.current).paddingBottom):0,m=(e=>{const{numberOfChildren:t,containerHeight:i,gapHeightRem:n,controlBarHeight:r,isShort:a}=e,s=ef(a?5.625:6.75),o=ef(n),l=ef(r),c=Math.floor((i+o)/(s+o));if(t<=c)return c;const d=i-l-2*o;return Math.max(Math.floor((d+o)/(s+o)),1)})({numberOfChildren:null!==(i=e.Children.count(n))&&void 0!==i?i:0,containerHeight:(null!=h?h:0)-p-g,gapHeightRem:s,controlBarHeight:null!=o?o:2,isShort:null!=l&&l});return null==d||d(m),e.createElement("div",{"data-ui-id":"responsive-vertical-gallery",ref:u,className:cn(r)},e.createElement(Yy,{childrenPerPage:m,styles:a,onFetchTilesToRender:c},n))};var Xy="undefined"!=typeof window?e.useLayoutEffect:e.useEffect;const eC={root:{width:"100%",minHeight:`${xy}rem`,paddingRight:"0.5rem","> *":Vy}},tC={display:"flex",minHeight:`${xy}rem`,overflow:"scroll","-ms-overflow-style":"none","scrollbar-width":"none","::-webkit-scrollbar":{display:"none"}},iC=t=>{const{horizontalGalleryElements:i,onFetchTilesToRender:n,containerStyles:r}=t;(0,e.useEffect)((()=>{const e=[...Array(null==i?void 0:i.length).keys()];n&&e&&n(e)}),[n,null==i?void 0:i.length]);const a=(0,e.useRef)(),{events:s}=function(t,i){var n,r,a,s,o=void 0===i?{}:i,l=o.decayRate,c=void 0===l?.95:l,d=o.safeDisplacement,u=void 0===d?10:d,h=o.applyRubberBandEffect,p=void 0!==h&&h,g=o.activeMouseButton,m=void 0===g?"Left":g,f=o.isMounted,v=void 0===f||f,S=(0,e.useRef)({isMouseDown:!1,isDraggingX:!1,isDraggingY:!1,initialMouseX:0,initialMouseY:0,lastMouseX:0,lastMouseY:0,scrollSpeedX:0,scrollSpeedY:0,lastScrollX:0,lastScrollY:0}),y=!1,C=!1,_=0,E=0,T=1/60*1e3;Xy((function(){v&&(y="scroll"===window.getComputedStyle(t.current).overflowX,C="scroll"===window.getComputedStyle(t.current).overflowY,_=t.current.scrollWidth-t.current.clientWidth,E=t.current.scrollHeight-t.current.clientHeight,n=window.getComputedStyle(t.current).cursor,r=[],a=[],s=[],t.current.childNodes.forEach((function(e){r.push(window.getComputedStyle(e).cursor),a.push("none"===window.getComputedStyle(e).transform?"":window.getComputedStyle(e).transform),s.push("none"===window.getComputedStyle(e).transition?"":window.getComputedStyle(e).transition)})))}),[v]);var b,I,w,R=function(){var e=S.current.scrollSpeedX*T,i=S.current.scrollSpeedY*T,n=t.current.scrollLeft+e,r=t.current.scrollTop+i;t.current.scrollLeft=n,t.current.scrollTop=r,S.current.lastScrollX=n,S.current.lastScrollY=r},A=function(){t.current.childNodes.forEach((function(e,t){e.style.transform=a[t],e.style.transition=s[t]}))},P=function(e){e.preventDefault(),e.stopImmediatePropagation()},M=function(e){var i=S.current.isDraggingX||S.current.isDraggingY,a=S.current.initialMouseX-e.clientX,s=S.current.initialMouseY-e.clientY,o=Math.abs(a)>u||Math.abs(s)>u,l=i&&o;l?t.current.childNodes.forEach((function(e){e.addEventListener("click",P)})):t.current.childNodes.forEach((function(e){e.removeEventListener("click",P)})),S.current.isMouseDown=!1,S.current.lastMouseX=0,S.current.lastMouseY=0,t.current.style.cursor=n,t.current.childNodes.forEach((function(e,t){e.style.cursor=r[t]})),l&&(I=setInterval((function(){var e=S.current.scrollSpeedX*c;S.current.scrollSpeedX=e;var i=t.current.scrollLeft<=0,n=t.current.scrollLeft>=_,r=i||n;R(),(Math.abs(e)<.05||S.current.isMouseDown||r)&&(S.current.scrollSpeedX=0,clearInterval(I))}),T),w=setInterval((function(){var e=S.current.scrollSpeedY*c;S.current.scrollSpeedY=e;var i=t.current.scrollTop<=0,n=t.current.scrollTop>=E,r=i||n;R(),(Math.abs(e)<.05||S.current.isMouseDown||r)&&(S.current.scrollSpeedY=0,clearInterval(w))}),T),S.current.isDraggingX=!1,S.current.isDraggingY=!1,p&&(t.current.childNodes.forEach((function(e){e.style.transform="translate3d(0px, 0px, 0px)",e.style.transition="transform 250ms"})),b=setTimeout(A,250)))},k=function(e){if(S.current.isMouseDown){e.preventDefault();var i=S.current.lastMouseX-e.clientX;S.current.lastMouseX=e.clientX,S.current.scrollSpeedX=i/T,S.current.isDraggingX=!0;var n=S.current.lastMouseY-e.clientY;S.current.lastMouseY=e.clientY,S.current.scrollSpeedY=n/T,S.current.isDraggingY=!0,t.current.style.cursor="grabbing",t.current.childNodes.forEach((function(e){e.style.cursor="grabbing"}));var r=t.current.scrollLeft<=0&&y,a=t.current.scrollLeft>=_&&y,s=t.current.scrollTop<=0&&C,o=t.current.scrollTop>=E&&C;(r||a||s||o)&&p&&function(e){var i=e.clientX-S.current.initialMouseX,n=e.clientY-S.current.initialMouseY,r=t.current,a=r.clientWidth,s=r.clientHeight,o=0,l=0;y&&C?(o=.3*a*Math.sign(i)*Math.log10(1+.5*Math.abs(i)/a),l=.3*s*Math.sign(n)*Math.log10(1+.5*Math.abs(n)/s)):y?o=.3*a*Math.sign(i)*Math.log10(1+.5*Math.abs(i)/a):C&&(l=.3*s*Math.sign(n)*Math.log10(1+.5*Math.abs(n)/s)),t.current.childNodes.forEach((function(e){e.style.transform="translate3d("+o+"px, "+l+"px, 0px)",e.style.transition="transform 0ms"}))}(e),R()}},D=function(){_=t.current.scrollWidth-t.current.clientWidth,E=t.current.scrollHeight-t.current.clientHeight};return(0,e.useEffect)((function(){return v&&(window.addEventListener("mouseup",M),window.addEventListener("mousemove",k),window.addEventListener("resize",D)),function(){window.removeEventListener("mouseup",M),window.removeEventListener("mousemove",k),window.removeEventListener("resize",D),clearInterval(I),clearInterval(w),clearTimeout(b)}}),[v]),{events:{onMouseDown:function(e){var t;t=e.buttons,("Left"===m&&1===t||"Middle"===m&&4===t||"Right"===m&&2===t)&&(S.current.isMouseDown=!0,S.current.lastMouseX=e.clientX,S.current.lastMouseY=e.clientY,S.current.initialMouseX=e.clientX,S.current.initialMouseY=e.clientY)}}}}(a);return e.createElement("div",Object.assign({ref:a},s,{className:cn(tC,r)}),e.createElement(Gs,{"data-ui-id":"scrollable-horizontal-gallery",horizontal:!0,styles:eC,tokens:{childrenGap:"0.5rem"}},i))},nC=t=>{const{shouldFloatLocalVideo:i=!1,onFetchTilesToRender:n,isNarrow:r=!1,isShort:a=!1,overflowGalleryElements:s,horizontalGalleryStyles:o,overflowGalleryPosition:l="horizontalBottom",verticalGalleryStyles:c,onChildrenPerPageChange:d,parentWidth:u}=t,h=(0,e.useMemo)((()=>"verticalRight"===l?((e,t,i)=>t&&i?{width:"9rem",height:e?`calc(100% - ${Ry.height}rem)`:"100%",paddingBottom:"0.5rem"}:!t&&i?{width:"9rem",height:e?`calc(100% - ${Py.height}rem)`:"100%",paddingBottom:"0.5rem"}:{width:"11rem",height:e?`calc(100% - ${My.height}rem)`:"100%",paddingBottom:"0.5rem"})(i,r,a):((e,t)=>({minHeight:t?`${xy}rem`:`${Uy}rem`,width:e?t?`calc(100% - ${Ry.width}rem)`:`calc(100% - ${Ay.width}rem)`:"100%",paddingRight:"0.5rem"}))(i,r)),[i,a,r,l]),p=(0,e.useMemo)((()=>"verticalRight"===l?Qa((e=>e?{children:$y}:{children:Gy})(a),c):Qa((e=>({children:e?Vy:Hy}))(r),o)),[r,a,o,l,c]),g=(0,e.useMemo)((()=>{if(r&&u)return{width:i?tf(u)-Ry.width-1+"rem":tf(u)-1+"rem"}}),[r,u,i]);return"verticalRight"===l?e.createElement(Zy,{key:"responsive-vertical-gallery",containerStyles:h,verticalGalleryStyles:p,controlBarHeightRem:1.75,gapHeightRem:.5,isShort:a,onFetchTilesToRender:n,onChildrenPerPageChange:d},s||[e.createElement(e.Fragment,null)]):r?(null==d||d(3),e.createElement(iC,{horizontalGalleryElements:s||[e.createElement(e.Fragment,null)],onFetchTilesToRender:n,key:"scrollable-horizontal-gallery",containerStyles:g})):e.createElement(jy,{key:"responsive-horizontal-gallery",containerStyles:h,onFetchTilesToRender:n,horizontalGalleryStyles:p,buttonWidthRem:1.75,gapWidthRem:.5,onChildrenPerPageChange:d},s||[e.createElement(e.Fragment,null)])},rC=t=>{const{remoteParticipants:i=[],localParticipant:n,dominantSpeakers:r,localVideoComponent:a,screenShareComponent:s,onRenderRemoteParticipant:o,styles:l,maxRemoteVideoStreams:c,parentWidth:d,parentHeight:u,pinnedParticipantUserIds:h=[],overflowGalleryPosition:p="horizontalBottom",spotlightedParticipantUserIds:g=[]}=t,m=!!d&&of(d),f=!!u&&lf(u),v=(0,e.useRef)(4),S=i.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})).length>0,{gridParticipants:y,overflowGalleryParticipants:C}=MS({remoteParticipants:i,localParticipant:n,dominantSpeakers:r,maxGridParticipants:S?c:9,isScreenShareActive:!!s,maxOverflowGalleryDominantSpeakers:s?v.current-(h.length+1)%v.current:v.current,pinnedParticipantUserIds:h,layout:"default",spotlightedParticipantUserIds:g});let _=0,E=y.map((e=>{var t,i;return o(e,c&&c>=0?(null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable)&&_++<c:null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)}));const[T,b]=(0,e.useState)([]);let I=C.map(((e,t)=>{var i,n;return o(e,c&&c>=0?(null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)&&T.includes(t)&&_++<c:null===(n=e.videoStream)||void 0===n?void 0:n.isAvailable)}));a&&(s||g.length>0?I=[a].concat(I):E=[a].concat(E));const w=(0,e.useMemo)((()=>0===I.length?null:e.createElement(nC,{isNarrow:m,isShort:f,shouldFloatLocalVideo:!1,overflowGalleryElements:I,horizontalGalleryStyles:null==l?void 0:l.horizontalGallery,verticalGalleryStyles:null==l?void 0:l.verticalGallery,overflowGalleryPosition:p,onFetchTilesToRender:b,onChildrenPerPageChange:e=>{v.current=e},parentWidth:d})),[m,f,I,null==l?void 0:l.horizontalGallery,p,b,null==l?void 0:l.verticalGallery,d]);return e.createElement(Gs,{horizontal:"verticalRight"===p,styles:fy,tokens:vy},"horizontalTop"===t.overflowGalleryPosition?w:e.createElement(e.Fragment,null),s||e.createElement(uy,{key:"grid-layout",styles:null==l?void 0:l.gridLayout},E),aC(w,t.overflowGalleryPosition))},aC=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null);var sC=function(){var t=qc({});return e.useEffect((function(){return function(){for(var e=0,i=Object.keys(t);e<i.length;e++){var n=i[e];clearTimeout(n)}}}),[t]),qc({setTimeout:function(e,i){var n=setTimeout(e,i);return t[n]=1,n},clearTimeout:function(e){delete t[e],clearTimeout(e)}})},oC=Ys(),lC=function(t){function i(e){var i=t.call(this,e)||this;lo(i);var n=i.props.allowTouchBodyScroll,r=void 0!==n&&n;return i._allowTouchBodyScroll=r,i}return bi(i,t),i.prototype.componentDidMount=function(){var e;!this._allowTouchBodyScroll&&((e=_n())&&e.body&&!Pl&&(e.body.classList.add(Ml),e.body.addEventListener("touchmove",Nl,{passive:!1,capture:!1})),Pl++)},i.prototype.componentWillUnmount=function(){!this._allowTouchBodyScroll&&function(){if(Pl>0){var e=_n();e&&e.body&&1===Pl&&(e.body.classList.remove(Ml),e.body.removeEventListener("touchmove",Nl)),Pl--}}()},i.prototype.render=function(){var t=this.props,i=t.isDarkThemed,n=t.className,r=t.theme,a=t.styles,s=Ds(this.props,ks),o=oC(a,{theme:r,className:n,isDark:i});return e.createElement("div",Ii({},s,{className:o.root}))},i}(e.Component),cC={root:"ms-Overlay",rootDark:"ms-Overlay--dark"},dC=Ws(lC,(function(e){var t,i=e.className,n=e.theme,r=e.isNone,a=e.isDark,s=n.palette,o=Kr(cC,n);return{root:[o.root,n.fonts.medium,{backgroundColor:s.whiteTranslucent40,top:0,right:0,bottom:0,left:0,position:"absolute",selectors:(t={},t[Nr]={border:"1px solid WindowText",opacity:0},t)},r&&{visibility:"hidden"},a&&[o.rootDark,{backgroundColor:s.blackTranslucent40}],i]}}),void 0,{scope:"Overlay"}),uC=e.createContext({window:"object"==typeof window?window:void 0});const hC=yr,pC={x:0,y:0},gC={isOpen:!1,isDarkOverlay:!0,className:"",containerClassName:"",enableAriaHiddenSiblings:!0},mC=Ys(),fC=e.forwardRef(((t,i)=>{const n=Xl(gC,t),{allowTouchBodyScroll:r,className:a,children:s,containerClassName:o,scrollableContentClassName:l,elementToFocusOnDismiss:c,firstFocusableSelector:d,forceFocusInsideTrap:u,ignoreExternalFocusing:h,isBlocking:p,isAlert:g,isClickableOutsideFocusTrap:m,isDarkOverlay:f,onDismiss:v,layerProps:S,overlay:y,isOpen:C,titleAriaId:_,styles:E,subtitleAriaId:T,theme:b,topOffsetFixed:I,responsiveMode:w,onLayerDidMount:R,isModeless:A,dragOptions:P,onDismissed:M,minDragPosition:k,maxDragPosition:D}=n,O=e.useRef(null),N=e.useRef(null),L=e.useRef(null),x=qo(O,i),F=Eu(x),U=fu("ModalFocusTrapZone"),B=e.useContext(uC).window,{setTimeout:V,clearTimeout:H}=sC(),[$,G]=e.useState(C),[j,z]=e.useState(C),[W,q]=e.useState(pC),[K,J]=e.useState(),[Y,{toggle:Q,setFalse:Z}]=ih(!1),X=qc((()=>({onModalCloseTimer:0,allowTouchBodyScroll:r,scrollableContent:null,lastSetCoordinates:pC,events:new So({})}))),{keepInBounds:ee}=P||{},te=null!=g?g:p&&!A,ie=void 0===S?"":S.className,ne=mC(E,{theme:b,className:a,containerClassName:o,scrollableContentClassName:l,isOpen:C,isVisible:j,hasBeenOpened:X.hasBeenOpened,modalRectangleTop:K,topOffsetFixed:I,isModeless:A,layerClassName:ie,windowInnerHeight:null==B?void 0:B.innerHeight,isDefaultDragHandle:P&&!P.dragHandleSelector}),re=Object.assign(Object.assign({eventBubblingEnabled:!1},S),{onLayerDidMount:S&&S.onLayerDidMount?S.onLayerDidMount:R,insertFirst:A,className:ne.layer}),ae=e.useCallback((e=>{e?X.allowTouchBodyScroll?Ol(e,X.events):Dl(e,X.events):X.events.off(X.scrollableContent),X.scrollableContent=e}),[X]),se=()=>{const e=L.current,t=null==e?void 0:e.getBoundingClientRect();t&&(I&&J(t.top),ee&&(X.minPosition=null!=k?k:{x:-t.left,y:-t.top},X.maxPosition=null!=D?D:{x:t.left,y:t.top},q({x:oe("x",W.x),y:oe("y",W.y)})))},oe=e.useCallback(((e,t)=>{const{minPosition:i,maxPosition:n}=X;return ee&&i&&n&&(t=Math.max(i[e],t),t=Math.min(n[e],t)),t}),[ee,X]),le=()=>{var e;X.lastSetCoordinates=pC,Z(),X.isInKeyboardMoveMode=!1,G(!1),q(pC),null===(e=X.disposeOnKeyUp)||void 0===e||e.call(X),null==M||M()},ce=e.useCallback((()=>{Z(),X.isInKeyboardMoveMode=!1}),[X,Z]),de=e.useCallback(((e,t)=>{q((e=>({x:oe("x",e.x+t.delta.x),y:oe("y",e.y+t.delta.y)})))}),[oe]),ue=e.useCallback((()=>{N.current&&N.current.focus()}),[]);e.useEffect((()=>{H(X.onModalCloseTimer),C&&(requestAnimationFrame((()=>V(se,0))),G(!0),P&&(()=>{const e=e=>{e.altKey&&e.ctrlKey&&e.keyCode===ao.space&&ul(X.scrollableContent,e.target)&&(Q(),e.preventDefault(),e.stopPropagation())};X.disposeOnKeyUp||(X.events.on(B,"keyup",e,!0),X.disposeOnKeyUp=()=>{X.events.off(B,"keyup",e,!0),X.disposeOnKeyUp=void 0})})(),X.hasBeenOpened=!0,z(!0)),!C&&$&&(X.onModalCloseTimer=V(le,1e3*parseFloat(hC)),z(!1))}),[$,C,k,D]),Zh((()=>{X.events.dispose()})),((t,i)=>{e.useImperativeHandle(t.componentRef,(()=>({focus(){i.current&&i.current.focus()}})),[i])})(n,N);const he=e.createElement(Df,{disabled:!0,id:U,ref:L,componentRef:N,className:ne.main,elementToFocusOnDismiss:c,isClickableOutsideFocusTrap:A||m||!p,ignoreExternalFocusing:h,forceFocusInsideTrap:u&&!A,firstFocusableSelector:d,focusPreviouslyFocusedInnerElement:!0,onBlur:X.isInKeyboardMoveMode?()=>{var e;X.lastSetCoordinates=pC,X.isInKeyboardMoveMode=!1,null===(e=X.disposeOnKeyDown)||void 0===e||e.call(X)}:void 0,"data-ui-id":n["data-ui-id"]},P&&X.isInKeyboardMoveMode&&e.createElement("div",{className:ne.keyboardMoveIconContainer},P.keyboardMoveIconProps?e.createElement(al,Object.assign({},P.keyboardMoveIconProps)):e.createElement(al,{iconName:"move",className:ne.keyboardMoveIcon})),e.createElement("div",{ref:ae,className:ne.scrollableContent,"data-is-scrollable":!0},P&&Y&&e.createElement(P.menu,{items:[{key:"move",text:P.moveMenuItemText,onClick:()=>{const e=e=>{if(e.altKey&&e.ctrlKey&&e.keyCode===ao.space)return e.preventDefault(),void e.stopPropagation();const t=e.altKey||e.keyCode===ao.escape;if(Y&&t&&Z(),!X.isInKeyboardMoveMode||e.keyCode!==ao.escape&&e.keyCode!==ao.enter||(X.isInKeyboardMoveMode=!1,e.preventDefault(),e.stopPropagation()),X.isInKeyboardMoveMode){let t=!0;const i=(e=>{let t=10;return e.shiftKey?e.ctrlKey||(t=50):e.ctrlKey&&(t=1),t})(e);switch(e.keyCode){case ao.escape:q(X.lastSetCoordinates);case ao.enter:X.lastSetCoordinates=pC;break;case ao.up:q((e=>({x:e.x,y:oe("y",e.y-i)})));break;case ao.down:q((e=>({x:e.x,y:oe("y",e.y+i)})));break;case ao.left:q((e=>({x:oe("x",e.x-i),y:e.y})));break;case ao.right:q((e=>({x:oe("x",e.x+i),y:e.y})));break;default:t=!1}t&&(e.preventDefault(),e.stopPropagation())}};X.lastSetCoordinates=W,Z(),X.isInKeyboardMoveMode=!0,X.events.on(B,"keydown",e,!0),X.disposeOnKeyDown=()=>{X.events.off(B,"keydown",e,!0),X.disposeOnKeyDown=void 0}}},{key:"close",text:P.closeMenuItemText,onClick:le}],onDismiss:Z,alignTargetEdge:!0,coverTarget:!0,directionalHint:ll.topLeftEdge,directionalHintFixed:!0,shouldFocusOnMount:!0,target:X.scrollableContent}),s));return $&&F>=(w||hu.small)&&e.createElement(Ld,Object.assign({ref:x},re),e.createElement(Wc,{role:te?"alertdialog":"dialog",ariaLabelledBy:_,ariaDescribedBy:T,shouldRestoreFocus:!h,"aria-modal":!A},e.createElement("div",{className:ne.root,role:A?void 0:"document"},!A&&e.createElement(dC,Object.assign({"aria-hidden":!0,isDarkThemed:f,onClick:p?void 0:v,allowTouchBodyScroll:r},y)),P?e.createElement(CC,{handleSelector:P.dragHandleSelector||`#${U}`,preventDragSelector:"button",onStart:ce,onDragChange:de,onStop:ue,position:W},he):he)))||null}));fC.displayName="ModalBase";const vC=vn(((e,t)=>({root:cn(e,t&&{touchAction:"none",selectors:{"& *":{userSelect:"none"}}})}))),SC={start:"touchstart",move:"touchmove",stop:"touchend"},yC={start:"mousedown",move:"mousemove",stop:"mouseup"};class CC extends e.Component{constructor(t){super(t),this._currentEventType=yC,this._events=[],this._onMouseDown=t=>{const i=e.Children.only(this.props.children).props.onMouseDown;return i&&i(t),this._currentEventType=yC,this._onDragStart(t)},this._onMouseUp=t=>{const i=e.Children.only(this.props.children).props.onMouseUp;return i&&i(t),this._currentEventType=yC,this._onDragStop(t)},this._onTouchStart=t=>{const i=e.Children.only(this.props.children).props.onTouchStart;return i&&i(t),this._currentEventType=SC,this._onDragStart(t)},this._onTouchEnd=t=>{const i=e.Children.only(this.props.children).props.onTouchEnd;i&&i(t),this._currentEventType=SC,this._onDragStop(t)},this._onDragStart=e=>{if("number"==typeof e.button&&0!==e.button)return!1;if(this.props.handleSelector&&!this._matchesSelector(e.target,this.props.handleSelector)||this.props.preventDragSelector&&this._matchesSelector(e.target,this.props.preventDragSelector))return;this._touchId=this._getTouchId(e);const t=this._getControlPosition(e);if(void 0===t)return;const i=this._createDragDataFromPosition(t);this.props.onStart&&this.props.onStart(e,i),this.setState({isDragging:!0,lastPosition:t}),this._events=[lc(document.body,this._currentEventType.move,this._onDrag,!0),lc(document.body,this._currentEventType.stop,this._onDragStop,!0)]},this._onDrag=e=>{"touchmove"===e.type&&e.preventDefault();const t=this._getControlPosition(e);if(!t)return;const i=this._createUpdatedDragData(this._createDragDataFromPosition(t)),n=i.position;this.props.onDragChange&&this.props.onDragChange(e,i),this.setState({position:n,lastPosition:t})},this._onDragStop=e=>{if(!this.state.isDragging)return;const t=this._getControlPosition(e);if(!t)return;const i=this._createDragDataFromPosition(t);this.setState({isDragging:!1,lastPosition:void 0}),this.props.onStop&&this.props.onStop(e,i),this.props.position&&this.setState({position:this.props.position}),this._events.forEach((e=>e()))},this.state={isDragging:!1,position:this.props.position||{x:0,y:0},lastPosition:void 0}}componentDidUpdate(e){!this.props.position||e.position&&this.props.position===e.position||this.setState({position:this.props.position})}componentWillUnmount(){this._events.forEach((e=>e()))}render(){const t=e.Children.only(this.props.children),{props:i}=t,{position:n}=this.props,{position:r,isDragging:a}=this.state;let s=r.x,o=r.y;return n&&!a&&(s=n.x,o=n.y),e.cloneElement(t,{style:Object.assign(Object.assign({},i.style),{transform:`translate(${s}px, ${o}px)`}),className:vC(i.className,this.state.isDragging).root,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onTouchStart:this._onTouchStart,onTouchEnd:this._onTouchEnd})}_getControlPosition(e){const t=this._getActiveTouch(e);if(void 0!==this._touchId&&!t)return;const i=t||e;return{x:i.clientX,y:i.clientY}}_getActiveTouch(e){return e.targetTouches&&this._findTouchInTouchList(e.targetTouches)||e.changedTouches&&this._findTouchInTouchList(e.changedTouches)}_getTouchId(e){const t=e.targetTouches&&e.targetTouches[0]||e.changedTouches&&e.changedTouches[0];if(t)return t.identifier}_matchesSelector(e,t){if(!e||e===document.body)return!1;const i=e.matches||e.webkitMatchesSelector||e.msMatchesSelector;return!!i&&(i.call(e,t)||this._matchesSelector(e.parentElement,t))}_findTouchInTouchList(e){if(void 0!==this._touchId)for(let t=0;t<e.length;t++)if(e[t].identifier===this._touchId)return e[t]}_createDragDataFromPosition(e){const{lastPosition:t}=this.state;return void 0===t?{delta:{x:0,y:0},lastPosition:e,position:e}:{delta:{x:e.x-t.x,y:e.y-t.y},lastPosition:t,position:e}}_createUpdatedDragData(e){const{position:t}=this.state;return{position:{x:t.x+e.delta.x,y:t.y+e.delta.y},delta:e.delta,lastPosition:t}}}const _C={root:"ms-Modal",main:"ms-Dialog-main",scrollableContent:"ms-Modal-scrollableContent",isOpen:"is-open",layer:"ms-Modal-Layer"},EC=Ws(fC,(e=>{const{className:t,containerClassName:i,scrollableContentClassName:n,isOpen:r,isVisible:a,hasBeenOpened:s,modalRectangleTop:o,theme:l,topOffsetFixed:c,isModeless:d,layerClassName:u,isDefaultDragHandle:h,windowInnerHeight:p}=e,{palette:g,effects:m,fonts:f}=l,v=Kr(_C,l);return{root:[v.root,f.medium,{backgroundColor:"transparent",position:d?"absolute":"fixed",height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",opacity:0,pointerEvents:"none",transition:`opacity ${hC}`},c&&"number"==typeof o&&s&&{alignItems:"flex-start"},r&&v.isOpen,a&&{opacity:1,pointerEvents:"auto"},t],main:[v.main,{boxShadow:m.elevation64,borderRadius:m.roundedCorner2,backgroundColor:g.white,boxSizing:"border-box",position:"relative",textAlign:"left",outline:"3px solid transparent",maxHeight:"calc(100% - 32px)",maxWidth:"calc(100% - 32px)",minHeight:"176px",minWidth:"288px",overflowY:"auto",zIndex:d?Br.Layer:void 0},c&&"number"==typeof o&&s&&{top:o},h&&{cursor:"move"},i],scrollableContent:[v.scrollableContent,{overflowY:"auto",flexGrow:1,maxHeight:"100vh",selectors:{"@supports (-webkit-overflow-scrolling: touch)":{maxHeight:p}}},n],layer:d&&[u,v.layer,{position:"static",width:"unset",height:"unset"}],keyboardMoveIconContainer:{position:"absolute",display:"flex",justifyContent:"center",width:"100%",padding:"3px 0px"},keyboardMoveIcon:{fontSize:f.xLargePlus.fontSize,width:"24px"}}}),void 0,{scope:"Modal",fields:["theme","styles","enableAriaHiddenSiblings"]});EC.displayName="Modal";const TC={moveMenuItemText:"Move",closeMenuItemText:"Close",menu:$u,keepInBounds:!0},bC={x:ef(1),y:ef(1)},IC=t=>{const{localVideoComponent:i,layerHostId:n,localVideoSizeRem:r,parentWidth:a,parentHeight:s}=t,o=Qh(),l=(0,e.useMemo)((()=>a&&s?{x:-a+ef(r.width)+ef(1),y:-s+ef(r.height)+ef(1)}:void 0),[s,a,r.width,r.height]),c=(0,e.useMemo)((()=>((e,t)=>Qa({main:cn(ky(e,t),{bottom:"1rem",right:"1rem"})},{main:{boxShadow:e.effects.elevation8,":focus-within":{boxShadow:e.effects.elevation16,border:`${bm(2)} solid ${e.palette.neutralPrimary}`}}},Ly))(o,r)),[o,r]),d=(0,e.useMemo)((()=>({hostId:n})),[n]);return e.createElement(EC,{isOpen:!0,isModeless:!0,dragOptions:TC,styles:c,layerProps:d,maxDragPosition:bC,minDragPosition:l,"data-ui-id":"floating-local-video-host"},i)},wC={root:{position:"relative",height:"100%",width:"100%"}},RC={root:{position:"relative",height:"100%",width:"100%",padding:"0.5rem"}},AC={position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden",pointerEvents:"none"},PC=t=>{const{remoteParticipants:i=[],dominantSpeakers:n,localVideoComponent:r,screenShareComponent:a,onRenderRemoteParticipant:s,styles:o,maxRemoteVideoStreams:l,showCameraSwitcherInLocalPreview:c,parentWidth:d,parentHeight:u,overflowGalleryPosition:h="horizontalBottom",pinnedParticipantUserIds:p=[],localVideoTileSize:g,spotlightedParticipantUserIds:m}=t,f=Qh(),v=!!d&&of(d),S=!!u&&lf(u),y=(0,e.useRef)(4),C=i.filter((e=>{var t;return null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable})).length>0,{gridParticipants:_,overflowGalleryParticipants:E}=MS({remoteParticipants:i,dominantSpeakers:n,maxGridParticipants:C?l:9,isScreenShareActive:!!a,maxOverflowGalleryDominantSpeakers:a?y.current-p.length%y.current:y.current,pinnedParticipantUserIds:p,layout:"floatingLocalVideo",spotlightedParticipantUserIds:m});let T=0;const b=_.map((e=>{var t,i;return s(e,l&&l>=0?(null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable)&&T++<l:null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)})),I=i.length>0;!I&&r&&b.push(r);const[w,R]=(0,e.useState)([]),A=E.map(((e,t)=>{var i,n;return s(e,l&&l>=0?(null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)&&w&&w.includes(t)&&T++<l:null===(n=e.videoStream)||void 0===n?void 0:n.isAvailable)})),P=fu("layerhost"),M=(0,e.useMemo)((()=>v||"9:16"===g?Ry:(A.length>0||a)&&"verticalRight"===h?v?Ry:S?Py:My:(A.length>0||a)&&"horizontalBottom"===h&&"16:9"!==g&&v?Ry:Ay),[A.length,v,a,S,h,g]),k=r&&I||a&&r?c?e.createElement(Gs,{className:cn(Dy(f,M),{boxShadow:f.effects.elevation8,zIndex:2})},r):A.length>0||a?e.createElement(Gs,{className:cn(ky(f,M,!!a,h))},r):e.createElement(IC,{localVideoComponent:r,layerHostId:P,localVideoSizeRem:M,parentWidth:d,parentHeight:u}):void 0,D=(0,e.useMemo)((()=>0!==A.length||a?e.createElement(nC,{isShort:S,onFetchTilesToRender:R,isNarrow:v,shouldFloatLocalVideo:!!r,overflowGalleryElements:A,horizontalGalleryStyles:null==o?void 0:o.horizontalGallery,verticalGalleryStyles:null==o?void 0:o.verticalGallery,overflowGalleryPosition:h,onChildrenPerPageChange:e=>{y.current=e},parentWidth:d}):null),[v,S,a,A,null==o?void 0:o.horizontalGallery,h,R,null==o?void 0:o.verticalGallery,d,r]);return e.createElement(Gs,{styles:wC},k,e.createElement(Xh,{id:P,className:cn(AC)}),e.createElement(Gs,{horizontal:"verticalRight"===h,styles:RC,tokens:vy},"horizontalTop"===t.overflowGalleryPosition?D:e.createElement(e.Fragment,null),a||e.createElement(uy,{key:"grid-layout",styles:null==o?void 0:o.gridLayout},b),MC(D,t.overflowGalleryPosition)))},MC=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null),kC=t=>{const{remoteParticipants:i=[],dominantSpeakers:n,localVideoComponent:r,screenShareComponent:a,onRenderRemoteParticipant:s,styles:o,maxRemoteVideoStreams:l,parentWidth:c,parentHeight:d,overflowGalleryPosition:u="horizontalBottom",pinnedParticipantUserIds:h=[],localVideoTileSize:p}=t,g=xh(),m=!!c&&of(c),f=!!d&&lf(d),v=(0,e.useRef)(4),{gridParticipants:S,overflowGalleryParticipants:y}=MS({remoteParticipants:i,dominantSpeakers:n,maxGridParticipants:l,isScreenShareActive:!!a,maxOverflowGalleryDominantSpeakers:a?v.current-h.length%v.current:v.current,pinnedParticipantUserIds:h,layout:"speaker"});let C=0;const _=S.map((e=>{var t,i;return s(e,l&&l>=0?(null===(t=e.videoStream)||void 0===t?void 0:t.isAvailable)&&C++<l:null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)}));!(i.length>0)&&r&&_.push(r);const[E,T]=(0,e.useState)([]),b=y.map(((e,t)=>{var i,n;return s(e,l&&l>=0?(null===(i=e.videoStream)||void 0===i?void 0:i.isAvailable)&&E&&E.includes(t)&&C++<l:null===(n=e.videoStream)||void 0===n?void 0:n.isAvailable)})),I=fu("layerhost"),w=(0,e.useMemo)((()=>m||"9:16"===p?Ry:(b.length>0||a)&&"verticalRight"===u?m?Ry:f?Py:My:(b.length>0||a)&&"horizontalBottom"===u&&"16:9"!==p&&m?Ry:Ay),[b.length,m,a,f,u,p]),R=r||a&&r?e.createElement(Gs,{className:cn(ky(g,w,!!a,u))},r):void 0,A=(0,e.useMemo)((()=>0!==b.length||a?e.createElement(nC,{isShort:f,onFetchTilesToRender:T,isNarrow:m,shouldFloatLocalVideo:!!r,overflowGalleryElements:b,horizontalGalleryStyles:null==o?void 0:o.horizontalGallery,verticalGalleryStyles:null==o?void 0:o.verticalGallery,overflowGalleryPosition:u,onChildrenPerPageChange:e=>{v.current=e},parentWidth:c}):null),[m,f,a,b,null==o?void 0:o.horizontalGallery,u,T,null==o?void 0:o.verticalGallery,c,r]);return e.createElement(Gs,{styles:wC},R,e.createElement(Xh,{id:I,className:cn(AC)}),e.createElement(Gs,{horizontal:"verticalRight"===u,styles:RC,tokens:vy},"horizontalTop"===t.overflowGalleryPosition?A:e.createElement(e.Fragment,null),a||e.createElement(uy,{key:"grid-layout",styles:null==o?void 0:o.gridLayout},_),DC(A,t.overflowGalleryPosition)))},DC=(t,i)=>"horizontalTop"!==i?t:e.createElement(e.Fragment,null),OC=t=>{const{screenShareComponent:i}=t,n=fu("layerhost");return e.createElement(Gs,{styles:wC},e.createElement(Xh,{id:n,className:cn(AC)}),e.createElement(Gs,{styles:RC,tokens:vy},i||e.createElement(e.Fragment,null)))},NC=4,LC={"-webkit-user-select":"none","-webkit-touch-callout":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"},xC={kind:"contextual"},FC=t=>{var i,n,r,a;const{localParticipant:s,remoteParticipants:o=[],localVideoViewOptions:l,remoteVideoViewOptions:c,dominantSpeakers:d,onRenderLocalVideoTile:u,onRenderRemoteVideoTile:h,onCreateLocalStreamView:p,onDisposeLocalStreamView:g,onCreateRemoteStreamView:m,onDisposeRemoteScreenShareStreamView:f,onDisposeRemoteVideoStreamView:v,styles:S,layout:y,onRenderAvatar:C,showMuteIndicator:_,maxRemoteVideoStreams:E=NC,showCameraSwitcherInLocalPreview:T,localVideoCameraCycleButtonProps:b,onPinParticipant:I,onUnpinParticipant:w,remoteVideoTileMenu:R=xC,overflowGalleryPosition:A="horizontalBottom",localVideoTileSize:P="followDeviceOrientation",spotlightedParticipants:M,onStartLocalSpotlight:k,onStartRemoteSpotlight:D,onStopLocalSpotlight:O,onStopRemoteSpotlight:N,maxParticipantsToSpotlight:L,reactionResources:x,videoTilesOptions:F}=t,U=Qv(),B=Qh(),V=_h().strings.videoGallery,H=(0,e.useMemo)((()=>Object.assign(Object.assign({},V),t.strings)),[V,t.strings]),$=R&&"drawer"===R.kind?R.hostId:void 0,G=fu("drawerMenuHost",$),j=("floatingLocalVideo"===y||"speaker"===y)&&o.length>0,z=(0,e.useRef)(null),W=af(z),q=sf(z),K=!!W&&of(W),[J,Y]=e.useState([]),[Q,Z]=e.useState({}),X=(0,e.useCallback)(((e,t)=>{Z((i=>Object.assign(Object.assign({},i),{[e]:{scalingMode:t,isMirrored:null==c?void 0:c.isMirrored}})))}),[null==c?void 0:c.isMirrored]);(0,e.useEffect)((()=>{var e;null===(e=t.pinnedParticipants)||void 0===e||e.forEach((e=>{var i;(null===(i=t.remoteParticipants)||void 0===i?void 0:i.find((t=>t.userId===e)))||console.warn("Invalid pinned participant UserId :"+e)}))}),[t.pinnedParticipants,t.remoteParticipants]);const ee=null!==(i=t.pinnedParticipants)&&void 0!==i?i:J,te=!(j&&K||"9:16"===P)||"default"===y,ie=(0,e.useMemo)((()=>{var t,i;if("hidden"===P)return;if(u)return u(s);const n=!!s.spotlight,r=Qa(j?Ny:{},{root:{borderRadius:B.effects.roundedCorner4}},null==S?void 0:S.localVideo),a=s.displayName?s.displayName:"";return e.createElement(Gs,{styles:ay,key:"local-video-tile-key",tabIndex:0,"aria-label":H.localVideoMovementLabel,role:"dialog"},e.createElement(oy,{alwaysShowLabelBackground:null==F?void 0:F.alwaysShowLabelBackground,userId:s.userId,onCreateLocalStreamView:p,onDisposeLocalStreamView:g,isAvailable:null===(t=null==s?void 0:s.videoStream)||void 0===t?void 0:t.isAvailable,isMuted:s.isMuted,renderElement:null===(i=null==s?void 0:s.videoStream)||void 0===i?void 0:i.renderElement,displayName:"default"===y?H.localVideoLabel:K?"":H.localVideoLabel,initialsName:a,localVideoViewOptions:l,onRenderAvatar:C,showLabel:te,showMuteIndicator:_,showCameraSwitcherInLocalPreview:T,localVideoCameraCycleButtonProps:b,localVideoCameraSwitcherLabel:H.localVideoCameraSwitcherLabel,localVideoSelectedDescription:H.localVideoSelectedDescription,styles:r,raisedHand:s.raisedHand,reaction:s.reaction,spotlightedParticipantUserIds:M,isSpotlighted:n,onStartSpotlight:k,onStopSpotlight:O,maxParticipantsToSpotlight:L,menuKind:R?"drawer"===R.kind?"drawer":"contextual":void 0,drawerMenuHostId:G,strings:H,reactionResources:x}))}),[K,s,b,l,p,g,C,u,j,T,_,null==S?void 0:S.localVideo,B.effects.roundedCorner4,P,y,te,M,k,O,L,R,H,G,x,F]),ne=(0,e.useCallback)((e=>{ee.length>=4||(J.includes(e)||Y(J.concat(e)),null==I||I(e))}),[ee.length,J,Y,I]),re=(0,e.useCallback)((e=>{Y(J.filter((t=>t!==e))),null==w||w(e)}),[J,Y,w]),[ae,se]=e.useState(""),oe=(0,e.useCallback)((e=>{se(e),setTimeout((()=>{se("")}),3e3)}),[se]),le=(0,e.useCallback)(((t,i)=>{const n=t.videoStream,r=n?Q[t.userId]:void 0;let a=null==ee?void 0:ee.includes(t.userId);const o=!!t.spotlight;return a=!o&&a,e.createElement(WS,{alwaysShowLabelBackground:null==F?void 0:F.alwaysShowLabelBackground,streamId:null==n?void 0:n.id,key:t.userId,userId:t.userId,remoteParticipant:t,onCreateRemoteStreamView:i?m:void 0,onDisposeRemoteStreamView:i?v:void 0,isAvailable:!!i&&(null==n?void 0:n.isAvailable),isReceiving:!!i&&(null==n?void 0:n.isReceiving),renderElement:i?null==n?void 0:n.renderElement:void 0,remoteVideoViewOptions:(()=>{var e,t;return r||((null==n?void 0:n.streamSize)&&(null===(e=n.streamSize)||void 0===e?void 0:e.height)>(null===(t=n.streamSize)||void 0===t?void 0:t.width)?{scalingMode:"Fit",isMirrored:null==c?void 0:c.isMirrored}:c)})(),onRenderAvatar:C,showMuteIndicator:_,strings:H,participantState:t.state,menuKind:t.userId===s.userId?void 0:R?"drawer"===R.kind?"drawer":"contextual":void 0,drawerMenuHostId:G,onPinParticipant:ne,onUnpinParticipant:re,onUpdateScalingMode:X,isPinned:a,disablePinMenuItem:ee.length>=4,toggleAnnouncerString:oe,spotlightedParticipantUserIds:M,isSpotlighted:o,onStartSpotlight:D,onStopSpotlight:N,maxParticipantsToSpotlight:L,reactionResources:x})}),[m,v,c,s,C,_,H,G,R,Q,ee,ne,re,oe,X,M,D,N,L,x,F]),ce=o.find((e=>{var t;return null===(t=e.screenShareStream)||void 0===t?void 0:t.isAvailable})),de=e.createElement(XS,{localParticipant:s}),ue=ce&&e.createElement(ty,Object.assign({},ce,{renderElement:null===(n=ce.screenShareStream)||void 0===n?void 0:n.renderElement,onCreateRemoteStreamView:m,onDisposeRemoteStreamView:f,isReceiving:null===(r=ce.screenShareStream)||void 0===r?void 0:r.isReceiving,participantVideoScalingMode:Q[ce.userId],localParticipant:s,remoteParticipants:o,reactionResources:x,isPPTLive:!(null===(a=ce.screenShareStream)||void 0===a?void 0:a.id)}))||(s.isScreenSharingOn?de:void 0),he=(0,e.useMemo)((()=>({remoteParticipants:o,localParticipant:s,screenShareComponent:ue,showCameraSwitcherInLocalPreview:T,maxRemoteVideoStreams:E,dominantSpeakers:d,styles:S,onRenderRemoteParticipant:null!=h?h:le,localVideoComponent:ie,parentWidth:W,parentHeight:q,pinnedParticipantUserIds:ee,overflowGalleryPosition:A,localVideoTileSize:P,spotlightedParticipantUserIds:M})),[o,s,ue,T,E,d,S,ie,W,q,h,le,ee,A,P,M]),pe=(0,e.useMemo)((()=>ce&&"focusedContent"===y?e.createElement(OC,Object.assign({},he)):"floatingLocalVideo"===y?e.createElement(PC,Object.assign({},he)):"speaker"===y?e.createElement(kC,Object.assign({},he)):e.createElement(rC,Object.assign({},he))),[y,he,ce]);return e.createElement("div",{id:$?void 0:G,"data-ui-id":U.videoGallery,ref:z,className:cn(ny,null==S?void 0:S.root,LC)},pe,e.createElement(zf,{announcementString:ae,ariaLive:"polite"}))},UC={"::-webkit-scrollbar, *::-webkit-scrollbar":{width:"0.3rem",height:"0.3rem"},"::-webkit-scrollbar-thumb, *::-webkit-scrollbar-thumb":{borderRadius:"10px",background:"rgba(150, 150, 150)"}},BC=cn({marginRight:bm(8)}),VC=cn({fontWeight:400,fontSize:bm(12),lineHeight:bm(16)}),HC=cn({fontWeight:400,fontSize:bm(16),lineHeight:bm(22),width:"100%"}),$C=cn({height:"100%",margin:0,overflow:"auto",padding:0}),GC=cn({marginTop:bm(6),marginBottom:bm(6),overflowAnchor:"auto"}),jC=e=>cn(Object.assign({overflowX:"hidden",height:"compact"===e?"4.5rem":"8.75rem",overflowY:"auto"},UC)),zC=e=>({root:{height:"compact"===e?"4.5rem":"8.75rem"}}),WC=cn({width:"100%"}),qC=cn({overflow:"hidden",textOverflow:"ellipsis"}),KC=t=>{const{displayName:i,userId:n,captionText:r,onRenderAvatar:a}=t,s={hidePersonaDetails:!0,size:ov.size32,text:i,showOverflowTooltip:!1,imageShouldStartVisible:!0,initialsTextColor:"white",styles:{root:{margin:"0.25rem"}}},o=a?a(null!=n?n:"",s):e.createElement(Jv,Object.assign({},s));return e.createElement(Gs,{horizontal:!0,verticalAlign:"start",horizontalAlign:"start"},e.createElement(Gs.Item,{className:BC},o),e.createElement(Gs,{verticalAlign:"start",className:WC},e.createElement(Gs.Item,{className:qC},e.createElement(Cf,{className:VC},i)),e.createElement(Gs.Item,{className:HC,dir:"auto"},r)))},JC=t=>{const{captions:i,isCaptionsOn:n,startCaptionsInProgress:r,onRenderAvatar:a,strings:s,formFactor:o="default"}=t,l=(0,e.useRef)(null),[c,d]=(0,e.useState)(!0),u=(0,e.useCallback)((()=>{if(!l.current)return;const e=Math.ceil(l.current.scrollTop)>=l.current.scrollHeight-l.current.clientHeight;d(e)}),[]);return(0,e.useEffect)((()=>{const e=l.current;return null==e||e.addEventListener("scroll",u),()=>{null==e||e.removeEventListener("scroll",u)}}),[u,n]),(0,e.useEffect)((()=>{c&&l.current&&(l.current.scrollTop=l.current.scrollHeight)}),[i,c]),e.createElement(e.Fragment,null,r&&e.createElement(Yl,{as:"ul",className:$C},n&&e.createElement("div",{ref:l,className:jC(o)},i.map((t=>e.createElement("div",{key:t.id,className:GC,"data-is-focusable":!0},e.createElement(KC,Object.assign({},t,{onRenderAvatar:a})))))),!n&&e.createElement(Gs,{verticalAlign:"center",styles:zC(o),"data-is-focusable":!0},e.createElement(Fm,{label:null==s?void 0:s.captionsBannerSpinnerText,ariaLive:"assertive",labelPosition:"right"}))))};var YC,QC=vn((function(e,t){var i,n,r;return Qa(Zu(e),{root:{padding:"0 4px",height:"40px",color:e.palette.neutralPrimary,backgroundColor:"transparent",border:"1px solid transparent",selectors:(i={},i[Nr]={borderColor:"Window"},i)},rootHovered:{color:e.palette.themePrimary,selectors:(n={},n[Nr]={color:"Highlight"},n)},iconHovered:{color:e.palette.themePrimary},rootPressed:{color:e.palette.black},rootExpanded:{color:e.palette.themePrimary},iconPressed:{color:e.palette.themeDarker},rootDisabled:{color:e.palette.neutralTertiary,backgroundColor:"transparent",borderColor:"transparent",selectors:(r={},r[Nr]={color:"GrayText"},r)},rootChecked:{color:e.palette.black},iconChecked:{color:e.palette.themeDarker},flexContainer:{justifyContent:"flex-start"},icon:{color:e.palette.themeDarkAlt},iconDisabled:{color:"inherit"},menuIcon:{color:e.palette.neutralSecondary},textContainer:{flexGrow:0}},t)})),ZC=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(Wu,Ii({},this.props,{variantClassName:"ms-Button--action ms-Button--command",styles:QC(n,i),onRenderDescription:Ro}))},Ri([qu("ActionButton",["theme","styles"],!0)],i)}(e.Component),XC=ZC;!function(e){e[e.Normal=0]="Normal",e[e.Divider=1]="Divider",e[e.Header=2]="Header",e[e.SelectAll=3]="SelectAll"}(YC||(YC={}));var e_,t_=function(){function e(){this._size=0}return e.prototype.updateOptions=function(e){for(var t=[],i=[],n=0,r=0;r<e.length;r++){var a=e[r],s=a.itemType,o=a.hidden;s===YC.Divider||s===YC.Header?(t.push(r),i.push(r)):o?i.push(r):n++}this._size=n,this._displayOnlyOptionsCache=t,this._notSelectableOptionsCache=i,this._cachedOptions=Ai([],e,!0)},Object.defineProperty(e.prototype,"optionSetSize",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cachedOptions",{get:function(){return this._cachedOptions},enumerable:!1,configurable:!0}),e.prototype.positionInSet=function(e){if(void 0!==e){for(var t=0;e>this._notSelectableOptionsCache[t];)t++;if(this._displayOnlyOptionsCache[t]===e)throw new Error("Unexpected: Option at index ".concat(e," is not a selectable element."));if(this._notSelectableOptionsCache[t]!==e)return e-t+1}},e}(),i_=Ys({cacheSize:100}),n_=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.as,n=void 0===i?"label":i,r=t.children,a=t.className,s=t.disabled,o=t.styles,l=t.required,c=t.theme,d=i_(o,{className:a,disabled:s,required:l,theme:c});return e.createElement(n,Ii({},Ds(this.props,ks),{className:d.root}),r)},i}(e.Component),r_=Ws(n_,(function(e){var t,i=e.theme,n=e.className,r=e.disabled,a=e.required,s=i.semanticColors,o=Mr.semibold,l=s.bodyText,c=s.disabledBodyText,d=s.errorText;return{root:["ms-Label",i.fonts.medium,{fontWeight:o,color:l,boxSizing:"border-box",boxShadow:"none",margin:0,display:"block",padding:"5px 0",wordWrap:"break-word",overflowWrap:"break-word"},r&&{color:c,selectors:(t={},t[Nr]=Ii({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)},a&&{selectors:{"::after":{content:"' *'",color:d,paddingRight:12}}},n]}}),void 0,{scope:"Label"});!function(e){e[e.smallFluid=0]="smallFluid",e[e.smallFixedFar=1]="smallFixedFar",e[e.smallFixedNear=2]="smallFixedNear",e[e.medium=3]="medium",e[e.large=4]="large",e[e.largeFixed=5]="largeFixed",e[e.extraLarge=6]="extraLarge",e[e.custom=7]="custom",e[e.customNear=8]="customNear"}(e_||(e_={}));var a_,s_=Ys();!function(e){e[e.closed=0]="closed",e[e.animatingOpen=1]="animatingOpen",e[e.open=2]="open",e[e.animatingClosed=3]="animatingClosed"}(a_||(a_={}));var o_,l_,c_,d_,u_,h_=function(t){function i(i){var n=t.call(this,i)||this;n._panel=e.createRef(),n._animationCallback=null,n._hasCustomNavigation=!(!n.props.onRenderNavigation&&!n.props.onRenderNavigationContent),n.dismiss=function(e){n.props.onDismiss&&n.isActive&&n.props.onDismiss(e),(!e||e&&!e.defaultPrevented)&&n.close()},n._allowScrollOnPanel=function(e){e?n._allowTouchBodyScroll?Ol(e,n._events):Dl(e,n._events):n._events.off(n._scrollableContent),n._scrollableContent=e},n._onRenderNavigation=function(t){if(!n.props.onRenderNavigationContent&&!n.props.onRenderNavigation&&!n.props.hasCloseButton)return null;var i=n.props.onRenderNavigationContent,r=void 0===i?n._onRenderNavigationContent:i;return e.createElement("div",{className:n._classNames.navigation},r(t,n._onRenderNavigationContent))},n._onRenderNavigationContent=function(t){var i,r=t.closeButtonAriaLabel,a=t.hasCloseButton,s=t.onRenderHeader,o=void 0===s?n._onRenderHeader:s;if(a){var l=null===(i=n._classNames.subComponentStyles)||void 0===i?void 0:i.closeButton();return e.createElement(e.Fragment,null,!n._hasCustomNavigation&&o(n.props,n._onRenderHeader,n._headerTextId),e.createElement(th,{styles:l,className:n._classNames.closeButton,onClick:n._onPanelClick,ariaLabel:r,title:r,"data-is-visible":!0,iconProps:{iconName:"Cancel"}}))}return null},n._onRenderHeader=function(t,i,r){var a=t.headerText,s=t.headerTextProps,o=void 0===s?{}:s;return a?e.createElement("div",{className:n._classNames.header},e.createElement("div",Ii({id:r,role:"heading","aria-level":1},o,{className:Os(n._classNames.headerText,o.className)}),a)):null},n._onRenderBody=function(t){return e.createElement("div",{className:n._classNames.content},t.children)},n._onRenderFooter=function(t){var i=n.props.onRenderFooterContent,r=void 0===i?null:i;return r?e.createElement("div",{className:n._classNames.footer},e.createElement("div",{className:n._classNames.footerInner},r())):null},n._animateTo=function(e){e===a_.open&&n.props.onOpen&&n.props.onOpen(),n._animationCallback=n._async.setTimeout((function(){n.setState({visibility:e}),n._onTransitionComplete(e)}),200)},n._clearExistingAnimationTimer=function(){null!==n._animationCallback&&n._async.clearTimeout(n._animationCallback)},n._onPanelClick=function(e){n.dismiss(e)},n._onTransitionComplete=function(e){n._updateFooterPosition(),e===a_.open&&n.props.onOpened&&n.props.onOpened(),e===a_.closed&&n.props.onDismissed&&n.props.onDismissed()};var r=n.props.allowTouchBodyScroll,a=void 0!==r&&r;return n._allowTouchBodyScroll=a,lo(n),n.state={isFooterSticky:!1,visibility:a_.closed,id:bo("Panel")},n}return bi(i,t),i.getDerivedStateFromProps=function(e,t){return void 0===e.isOpen?null:!e.isOpen||t.visibility!==a_.closed&&t.visibility!==a_.animatingClosed?e.isOpen||t.visibility!==a_.open&&t.visibility!==a_.animatingOpen?null:{visibility:a_.animatingClosed}:{visibility:a_.animatingOpen}},i.prototype.componentDidMount=function(){this._async=new go(this),this._events=new So(this);var e=Zc(this.context),t=Qc(this.context);this._events.on(e,"resize",this._updateFooterPosition),this._shouldListenForOuterClick(this.props)&&this._events.on(null==t?void 0:t.body,"mousedown",this._dismissOnOuterClick,!0),this.props.isOpen&&this.setState({visibility:a_.animatingOpen})},i.prototype.componentDidUpdate=function(e,t){var i=this._shouldListenForOuterClick(this.props),n=this._shouldListenForOuterClick(e);this.state.visibility!==t.visibility&&(this._clearExistingAnimationTimer(),this.state.visibility===a_.animatingOpen?this._animateTo(a_.open):this.state.visibility===a_.animatingClosed&&this._animateTo(a_.closed));var r=Qc(this.context);i&&!n?this._events.on(null==r?void 0:r.body,"mousedown",this._dismissOnOuterClick,!0):!i&&n&&this._events.off(null==r?void 0:r.body,"mousedown",this._dismissOnOuterClick,!0)},i.prototype.componentWillUnmount=function(){this._async.dispose(),this._events.dispose()},i.prototype.render=function(){var t=this.props,i=t.className,n=void 0===i?"":i,r=t.elementToFocusOnDismiss,a=t.firstFocusableSelector,s=t.focusTrapZoneProps,o=t.forceFocusInsideTrap,l=t.hasCloseButton,c=t.headerText,d=t.headerClassName,u=void 0===d?"":d,h=t.ignoreExternalFocusing,p=t.isBlocking,g=t.isFooterAtBottom,m=t.isLightDismiss,f=t.isHiddenOnDismiss,v=t.layerProps,S=t.overlayProps,y=t.popupProps,C=t.type,_=t.styles,E=t.theme,T=t.customWidth,b=t.onLightDismissClick,I=void 0===b?this._onPanelClick:b,w=t.onRenderNavigation,R=void 0===w?this._onRenderNavigation:w,A=t.onRenderHeader,P=void 0===A?this._onRenderHeader:A,M=t.onRenderBody,k=void 0===M?this._onRenderBody:M,D=t.onRenderFooter,O=void 0===D?this._onRenderFooter:D,N=this.state,L=N.isFooterSticky,x=N.visibility,F=N.id,U=C===e_.smallFixedNear||C===e_.customNear,B=Rn(E)?U:!U,V=C===e_.custom||C===e_.customNear?{width:T}:{},H=Ds(this.props,ks),$=this.isActive,G=x===a_.animatingClosed||x===a_.animatingOpen;if(this._headerTextId=c&&F+"-headerText",!$&&!G&&!f)return null;this._classNames=s_(_,{theme:E,className:n,focusTrapZoneClassName:s?s.className:void 0,hasCloseButton:l,headerClassName:u,isAnimating:G,isFooterSticky:L,isFooterAtBottom:g,isOnRightSide:B,isOpen:$,isHiddenOnDismiss:f,type:C,hasCustomNavigation:this._hasCustomNavigation});var j,z=this._classNames,W=this._allowTouchBodyScroll;return p&&$&&(j=e.createElement(dC,Ii({className:z.overlay,isDarkThemed:!1,onClick:m?I:void 0,allowTouchBodyScroll:W},S))),e.createElement(Ld,Ii({},v),e.createElement(Wc,Ii({role:"dialog","aria-modal":p?"true":void 0,ariaLabelledBy:this._headerTextId?this._headerTextId:void 0,onDismiss:this.dismiss,className:z.hiddenPanel,enableAriaHiddenSiblings:!!$},y),e.createElement("div",Ii({"aria-hidden":!$&&G},H,{ref:this._panel,className:z.root}),j,e.createElement(Df,Ii({ignoreExternalFocusing:h,forceFocusInsideTrap:!(!p||f&&!$)&&o,firstFocusableSelector:a,isClickableOutsideFocusTrap:!0},s,{className:z.main,style:V,elementToFocusOnDismiss:r}),e.createElement("div",{className:z.contentInner},e.createElement("div",{ref:this._allowScrollOnPanel,className:z.scrollableContent,"data-is-scrollable":!0},e.createElement("div",{className:z.commands,"data-is-visible":!0},R(this.props,this._onRenderNavigation)),(this._hasCustomNavigation||!l)&&P(this.props,this._onRenderHeader,this._headerTextId),k(this.props,this._onRenderBody),O(this.props,this._onRenderFooter)))))))},i.prototype.open=function(){void 0===this.props.isOpen&&(this.isActive||this.setState({visibility:a_.animatingOpen}))},i.prototype.close=function(){void 0===this.props.isOpen&&this.isActive&&this.setState({visibility:a_.animatingClosed})},Object.defineProperty(i.prototype,"isActive",{get:function(){return this.state.visibility===a_.open||this.state.visibility===a_.animatingOpen},enumerable:!1,configurable:!0}),i.prototype._shouldListenForOuterClick=function(e){return!!e.isBlocking&&!!e.isOpen},i.prototype._updateFooterPosition=function(){var e=this._scrollableContent;if(e){var t=e.clientHeight,i=e.scrollHeight;this.setState({isFooterSticky:t<i})}},i.prototype._dismissOnOuterClick=function(e){var t=this._panel.current;this.isActive&&t&&!e.defaultPrevented&&(ul(t,e.target)||(this.props.onOuterClick?this.props.onOuterClick(e):this.dismiss(e)))},i.defaultProps={isHiddenOnDismiss:!1,isOpen:void 0,isBlocking:!0,hasCloseButton:!0,type:e_.smallFixedFar},i.contextType=$c,i}(e.Component),p_={root:"ms-Panel",main:"ms-Panel-main",commands:"ms-Panel-commands",contentInner:"ms-Panel-contentInner",scrollableContent:"ms-Panel-scrollableContent",navigation:"ms-Panel-navigation",closeButton:"ms-Panel-closeButton ms-PanelAction-close",header:"ms-Panel-header",headerText:"ms-Panel-headerText",content:"ms-Panel-content",footer:"ms-Panel-footer",footerInner:"ms-Panel-footerInner",isOpen:"is-open",hasCloseButton:"ms-Panel--hasCloseButton",smallFluid:"ms-Panel--smFluid",smallFixedNear:"ms-Panel--smLeft",smallFixedFar:"ms-Panel--sm",medium:"ms-Panel--md",large:"ms-Panel--lg",largeFixed:"ms-Panel--fixed",extraLarge:"ms-Panel--xl",custom:"ms-Panel--custom",customNear:"ms-Panel--customLeft"},g_="auto",m_=((o_={})["@media (min-width: ".concat(xr,"px)")]={width:340},o_),f_=((l_={})["@media (min-width: ".concat(640,"px)")]={width:592},l_["@media (min-width: ".concat(1024,"px)")]={width:644},l_),v_=((c_={})["@media (min-width: ".concat(768,"px)")]={left:48,width:"auto"},c_["@media (min-width: ".concat(Fr,"px)")]={left:428},c_),S_=((d_={})["@media (min-width: ".concat(Fr,"px)")]={left:g_,width:940},d_),y_=((u_={})["@media (min-width: ".concat(Fr,"px)")]={left:176},u_),C_=function(e){var t;switch(e){case e_.smallFixedFar:t=Ii({},m_);break;case e_.medium:t=Ii(Ii({},m_),f_);break;case e_.large:t=Ii(Ii(Ii({},m_),f_),v_);break;case e_.largeFixed:t=Ii(Ii(Ii(Ii({},m_),f_),v_),S_);break;case e_.extraLarge:t=Ii(Ii(Ii(Ii({},m_),f_),v_),y_)}return t},__={paddingLeft:"24px",paddingRight:"24px"},E_=Ws(h_,(function(e){var t,i,n,r,a=e.className,s=e.focusTrapZoneClassName,o=e.hasCloseButton,l=e.headerClassName,c=e.isAnimating,d=e.isFooterSticky,u=e.isFooterAtBottom,h=e.isOnRightSide,p=e.isOpen,g=e.isHiddenOnDismiss,m=e.hasCustomNavigation,f=e.theme,v=e.type,S=void 0===v?e_.smallFixedFar:v,y=f.effects,C=f.fonts,_=f.semanticColors,E=Kr(p_,f),T=S===e_.custom||S===e_.customNear;return{root:[E.root,f.fonts.medium,p&&E.isOpen,o&&E.hasCloseButton,{pointerEvents:"none",position:"absolute",top:0,left:0,right:0,bottom:0},T&&h&&E.custom,T&&!h&&E.customNear,a],overlay:[{pointerEvents:"auto",cursor:"pointer"},p&&c&&Dr.fadeIn100,!p&&c&&Dr.fadeOut100],hiddenPanel:[!p&&!c&&g&&{visibility:"hidden"}],main:[E.main,{backgroundColor:_.bodyBackground,boxShadow:y.elevation64,pointerEvents:"auto",position:"absolute",display:"flex",flexDirection:"column",overflowX:"hidden",overflowY:"auto",WebkitOverflowScrolling:"touch",bottom:0,top:0,left:g_,right:0,width:"100%",selectors:Ii((t={},t[Nr]={borderLeft:"3px solid ".concat(_.variantBorder),borderRight:"3px solid ".concat(_.variantBorder)},t),C_(S))},S===e_.smallFluid&&{left:0},S===e_.smallFixedNear&&{left:0,right:g_,width:272},S===e_.customNear&&{right:"auto",left:0},T&&{maxWidth:"100vw"},p&&c&&!h&&Dr.slideRightIn40,p&&c&&h&&Dr.slideLeftIn40,!p&&c&&!h&&Dr.slideLeftOut40,!p&&c&&h&&Dr.slideRightOut40,s],commands:[E.commands,{backgroundColor:_.bodyBackground,paddingTop:18,selectors:(i={},i["@media (min-height: ".concat(xr,"px)")]={position:"sticky",top:0,zIndex:1},i)},m&&{paddingTop:"inherit"}],navigation:[E.navigation,{display:"flex",justifyContent:"flex-end"},m&&{height:"44px"}],contentInner:[E.contentInner,{display:"flex",flexDirection:"column",flexGrow:1,overflowY:"hidden"}],header:[E.header,__,{alignSelf:"flex-start"},o&&!m&&{flexGrow:1},m&&{flexShrink:0}],headerText:[E.headerText,C.xLarge,{color:_.bodyText,lineHeight:"27px",overflowWrap:"break-word",wordWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},l],scrollableContent:[E.scrollableContent,{overflowY:"auto"},u&&{flexGrow:1,display:"inherit",flexDirection:"inherit"}],content:[E.content,__,{paddingBottom:20},u&&{selectors:(n={},n["@media (min-height: ".concat(xr,"px)")]={flexGrow:1},n)}],footer:[E.footer,{flexShrink:0,borderTop:"1px solid transparent",transition:"opacity ".concat(Cr," ").concat(Sr),selectors:(r={},r["@media (min-height: ".concat(xr,"px)")]={position:"sticky",bottom:0},r)},d&&{backgroundColor:_.bodyBackground,borderTopColor:_.variantBorder}],footerInner:[E.footerInner,__,{paddingBottom:16,paddingTop:16}],subComponentStyles:{closeButton:{root:[E.closeButton,{marginRight:14,color:f.palette.neutralSecondary,fontSize:kr.large},m&&{marginRight:0,height:"auto",width:"44px"}],rootHovered:{color:f.palette.neutralPrimary}}}}}),void 0,{scope:"Panel"});function T_(e,t){for(var i=[],n=0,r=t;n<r.length;n++){var a=e[r[n]];a&&i.push(a)}return i}function b_(t,i,n){var r=e.useState(i),a=r[0],s=r[1],o=qc(void 0!==t),l=o?t:a,c=e.useRef(l),d=e.useRef(n);e.useEffect((function(){c.current=l,d.current=n}));var u=qc((function(){return function(e,t){var i="function"==typeof e?e(c.current):e;d.current&&d.current(t,i),o||s(i)}}));return[l,u]}var I_=Ys(),w_=e.forwardRef((function(t,i){var n=t.disabled,r=t.required,a=t.inputProps,s=t.name,o=t.ariaLabel,l=t.ariaLabelledBy,c=t.ariaDescribedBy,d=t.ariaPositionInSet,u=t.ariaSetSize,h=t.title,p=t.checkmarkIconProps,g=t.styles,m=t.theme,f=t.className,v=t.boxSide,S=void 0===v?"start":v,y=fu("checkbox-",t.id),C=e.useRef(null),_=qo(C,i),E=e.useRef(null),T=b_(t.checked,t.defaultChecked,t.onChange),b=T[0],I=T[1],w=b_(t.indeterminate,t.defaultIndeterminate),R=w[0],A=w[1];Lo(C);var P=I_(g,{theme:m,className:f,disabled:n,indeterminate:R,checked:b,reversed:"start"!==S,isUsingCustomLabelRender:!!t.onRenderLabel}),M=e.useCallback((function(e){R?(I(!!b,e),A(!1)):I(!b,e)}),[I,A,R,b]),k=e.useCallback((function(t){return t&&t.label?e.createElement("span",{className:P.text,title:t.title},t.label):null}),[P.text]),D=e.useCallback((function(e){if(E.current){var t=!!e;E.current.indeterminate=t,A(t)}}),[A]);!function(t,i,n,r,a){e.useImperativeHandle(t.componentRef,(function(){return{get checked(){return!!i},get indeterminate(){return!!n},set indeterminate(e){r(e)},focus:function(){a.current&&a.current.focus()}}}),[a,i,n,r])}(t,b,R,D,E),e.useEffect((function(){return D(R)}),[D,R]);var O=t.onRenderLabel||k,N=R?"mixed":void 0,L=Ii(Ii({className:P.input,type:"checkbox"},a),{checked:!!b,disabled:n,required:r,name:s,id:y,title:h,onChange:M,"aria-disabled":n,"aria-label":o,"aria-labelledby":l,"aria-describedby":c,"aria-posinset":d,"aria-setsize":u,"aria-checked":N});return e.createElement("div",{className:P.root,title:h,ref:_},e.createElement("input",Ii({},L,{ref:E,title:h,"data-ktp-execute-target":!0})),e.createElement("label",{className:P.label,htmlFor:y},e.createElement("div",{className:P.checkbox,"data-ktp-target":!0},e.createElement(al,Ii({iconName:"CheckMark"},p,{className:P.checkmark}))),O(t,k)))}));w_.displayName="CheckboxBase";var R_={root:"ms-Checkbox",label:"ms-Checkbox-label",checkbox:"ms-Checkbox-checkbox",checkmark:"ms-Checkbox-checkmark",text:"ms-Checkbox-text"},A_="20px",P_="200ms",M_="cubic-bezier(.4, 0, .23, 1)",k_=Ws(w_,(function(e){var t,i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S,y=e.className,C=e.theme,_=e.reversed,E=e.checked,T=e.disabled,b=e.isUsingCustomLabelRender,I=e.indeterminate,w=C.semanticColors,R=C.effects,A=C.palette,P=C.fonts,M=Kr(R_,C),k=w.inputForegroundChecked,D=A.neutralSecondary,O=A.neutralPrimary,N=w.inputBackgroundChecked,L=w.inputBackgroundChecked,x=w.disabledBodySubtext,F=w.inputBorderHovered,U=w.inputBackgroundCheckedHovered,B=w.inputBackgroundChecked,V=w.inputBackgroundCheckedHovered,H=w.inputBackgroundCheckedHovered,$=w.inputTextHovered,G=w.disabledBodySubtext,j=w.bodyText,z=w.disabledText,W=[(t={content:'""',borderRadius:R.roundedCorner2,position:"absolute",width:10,height:10,top:4,left:4,boxSizing:"border-box",borderWidth:5,borderStyle:"solid",borderColor:T?x:N,transitionProperty:"border-width, border, border-color",transitionDuration:P_,transitionTimingFunction:M_},t[Nr]={borderColor:"WindowText"},t)];return{root:[M.root,{position:"relative",display:"flex"},_&&"reversed",E&&"is-checked",!T&&"is-enabled",T&&"is-disabled",!T&&[!E&&(i={},i[":hover .".concat(M.checkbox)]=(n={borderColor:F},n[Nr]={borderColor:"Highlight"},n),i[":focus .".concat(M.checkbox)]={borderColor:F},i[":hover .".concat(M.checkmark)]=(r={color:D,opacity:"1"},r[Nr]={color:"Highlight"},r),i),E&&!I&&(a={},a[":hover .".concat(M.checkbox)]={background:V,borderColor:H},a[":focus .".concat(M.checkbox)]={background:V,borderColor:H},a[Nr]=(s={},s[":hover .".concat(M.checkbox)]={background:"Highlight",borderColor:"Highlight"},s[":focus .".concat(M.checkbox)]={background:"Highlight"},s[":focus:hover .".concat(M.checkbox)]={background:"Highlight"},s[":focus:hover .".concat(M.checkmark)]={color:"Window"},s[":hover .".concat(M.checkmark)]={color:"Window"},s),a),I&&(o={},o[":hover .".concat(M.checkbox,", :hover .").concat(M.checkbox,":after")]=(l={borderColor:U},l[Nr]={borderColor:"WindowText"},l),o[":focus .".concat(M.checkbox)]={borderColor:U},o[":hover .".concat(M.checkmark)]={opacity:"0"},o),(c={},c[":hover .".concat(M.text,", :focus .").concat(M.text)]=(d={color:$},d[Nr]={color:T?"GrayText":"WindowText"},d),c)],y],input:(u={position:"absolute",background:"none",opacity:0},u[".".concat(Vr," &:focus + label::before")]=(h={outline:"1px solid "+C.palette.neutralSecondary,outlineOffset:"2px"},h[Nr]={outline:"1px solid WindowText"},h),u),label:[M.label,C.fonts.medium,{display:"flex",alignItems:b?"center":"flex-start",cursor:T?"default":"pointer",position:"relative",userSelect:"none"},_&&{flexDirection:"row-reverse",justifyContent:"flex-end"},{"&::before":{position:"absolute",left:0,right:0,top:0,bottom:0,content:'""',pointerEvents:"none"}}],checkbox:[M.checkbox,(p={position:"relative",display:"flex",flexShrink:0,alignItems:"center",justifyContent:"center",height:A_,width:A_,border:"1px solid ".concat(O),borderRadius:R.roundedCorner2,boxSizing:"border-box",transitionProperty:"background, border, border-color",transitionDuration:P_,transitionTimingFunction:M_,overflow:"hidden",":after":I?W:null},p[Nr]=Ii({borderColor:"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),p),I&&{borderColor:N},_?{marginLeft:4}:{marginRight:4},!T&&!I&&E&&(g={background:B,borderColor:L},g[Nr]={background:"Highlight",borderColor:"Highlight"},g),T&&(m={borderColor:x},m[Nr]={borderColor:"GrayText"},m),E&&T&&(f={background:G,borderColor:x},f[Nr]={background:"Window"},f)],checkmark:[M.checkmark,(v={opacity:E&&!I?"1":"0",color:k},v[Nr]=Ii({color:T?"GrayText":"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),v)],text:[M.text,(S={color:T?z:j,fontSize:P.medium.fontSize,lineHeight:"20px"},S[Nr]=Ii({color:T?"GrayText":"WindowText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),S),_?{marginRight:4}:{marginLeft:4}]}}),void 0,{scope:"Checkbox"}),D_=Ys(),O_={options:[]},N_=e.forwardRef((function(t,i){var n=Xl(O_,t),r=e.useRef(null),a=qo(i,r),s=Eu(r,n.responsiveMode),o=function(t){var i,n=t.defaultSelectedKeys,r=t.selectedKeys,a=t.defaultSelectedKey,s=t.selectedKey,o=t.options,l=t.multiSelect,c=au(o),d=e.useState([]),u=d[0],h=d[1],p=o!==c,g=au(i=l?p&&void 0!==n?n:r:p&&void 0!==a?a:s);return e.useEffect((function(){var e=function(e){return function(e,t,i){void 0===i&&(i=0);for(var n=-1,r=i;e&&r<e.length;r++)if(t(e[r],r)){n=r;break}return n}(o,(function(t){return null!=e?t.key===e:!!t.selected||!!t.isSelected}))};void 0===i&&c||i===g&&!p||h(function(){if(void 0===i)return l?o.map((function(e,t){return e.selected?t:-1})).filter((function(e){return-1!==e})):-1!==(a=e(null))?[a]:[];if(!Array.isArray(i))return-1!==(a=e(i))?[a]:[];for(var t=[],n=0,r=i;n<r.length;n++){var a,s=r[n];-1!==(a=e(s))&&t.push(a)}return t}())}),[p,l,c,g,o,i]),[u,h]}(n),l=o[0],c=o[1];return e.createElement(V_,Ii({},n,{responsiveMode:s,hoisted:{rootRef:a,selectedIndices:l,setSelectedIndices:c}}))}));N_.displayName="DropdownBase";var L_,x_,F_,U_,B_,V_=function(t){function i(i){var n,r,a=t.call(this,i)||this;a._host=e.createRef(),a._focusZone=e.createRef(),a._dropDown=e.createRef(),a._scrollIdleDelay=250,a._sizePosCache=new t_,a._requestAnimationFrame=(n=a,function(e){r||(r=new Set,oo(n,{componentWillUnmount:function(){r.forEach((function(e){return cancelAnimationFrame(e)}))}}));var t=requestAnimationFrame((function(){r.delete(t),e()}));r.add(t)}),a.dismissMenu=function(){a.state.isOpen&&a.setState({isOpen:!1})},a._onChange=function(e,t,i,n,r){var s=a.props,o=s.onChange,l=s.onChanged;if(o||l){var c=r?Ii(Ii({},t[i]),{selected:!n}):t[i];o&&o(Ii(Ii({},e),{target:a._dropDown.current}),c,i),l&&l(c,i)}},a._getPlaceholder=function(){return a.props.placeholder||a.props.placeHolder},a._getTitle=function(e,t){var i=a.props.multiSelectDelimiter,n=void 0===i?", ":i;return e.map((function(e){return e.text})).join(n)},a._onRenderTitle=function(t){return e.createElement(e.Fragment,null,a._getTitle(t))},a._onRenderPlaceholder=function(t){return a._getPlaceholder()?e.createElement(e.Fragment,null,a._getPlaceholder()):null},a._onRenderContainer=function(t){var i=t.calloutProps,n=t.panelProps,r=a.props,s=r.responsiveMode,o=r.dropdownWidth,l=s<=hu.medium,c={firstFocusableTarget:"#".concat(a._listId,"1")},d=a._classNames.subComponentStyles?a._classNames.subComponentStyles.panel:void 0,u=void 0,h=void 0;return"auto"===o?h=a._dropDown.current?a._dropDown.current.clientWidth:0:u=o||(a._dropDown.current?a._dropDown.current.clientWidth:0),l?e.createElement(E_,Ii({closeButtonAriaLabel:"Close",focusTrapZoneProps:c,hasCloseButton:!0,isOpen:!0,isLightDismiss:!0,onDismiss:a._onDismiss,styles:d},n),a._renderFocusableList(t)):e.createElement(xd,Ii({isBeakVisible:!1,gapSpace:0,doNotLayer:!1,directionalHintFixed:!1,directionalHint:ll.bottomLeftEdge,calloutWidth:u,calloutMinWidth:h},i,{className:a._classNames.callout,target:a._dropDown.current,onDismiss:a._onDismiss,onScroll:a._onScroll,onPositioned:a._onPositioned}),a._renderFocusableList(t))},a._onRenderCaretDown=function(t){return e.createElement(al,{className:a._classNames.caretDown,iconName:"ChevronDown","aria-hidden":!0})},a._onRenderList=function(t){var i=t.onRenderItem,n=void 0===i?a._onRenderItem:i,r={items:[]},s=[],o=function(){var t=r.id?[e.createElement("div",{role:"group",key:r.id,"aria-labelledby":r.id},r.items)]:r.items;s=Ai(Ai([],s,!0),t,!0),r={items:[]}};return t.options.forEach((function(e,t){!function(e,t){switch(e.itemType){case YC.Header:r.items.length>0&&o();var i=a._id+e.key;r.items.push(n(Ii(Ii({id:i},e),{index:t}),a._onRenderItem)),r.id=i;break;case YC.Divider:t>0&&r.items.push(n(Ii(Ii({},e),{index:t}),a._onRenderItem)),r.items.length>0&&o();break;default:r.items.push(n(Ii(Ii({},e),{index:t}),a._onRenderItem))}}(e,t)})),r.items.length>0&&o(),e.createElement(e.Fragment,null,s)},a._onRenderItem=function(e){switch(e.itemType){case YC.Divider:return a._renderSeparator(e);case YC.Header:return a._renderHeader(e);default:return a._renderOption(e)}},a._renderOption=function(t){var i,n=a.props,r=n.onRenderOption,s=void 0===r?a._onRenderOption:r,o=n.hoisted.selectedIndices,l=void 0===o?[]:o,c=!(void 0===t.index||!l)&&l.indexOf(t.index)>-1,d=t.hidden?a._classNames.dropdownItemHidden:c&&!0===t.disabled?a._classNames.dropdownItemSelectedAndDisabled:c?a._classNames.dropdownItemSelected:!0===t.disabled?a._classNames.dropdownItemDisabled:a._classNames.dropdownItem,u=t.title,h=a._listId+t.index,p=null!==(i=t.id)&&void 0!==i?i:h+"-label",g=a._classNames.subComponentStyles?a._classNames.subComponentStyles.multiSelectItem:void 0;return a.props.multiSelect?e.createElement(k_,{id:h,key:t.key,disabled:t.disabled,onChange:a._onItemClick(t),inputProps:Ii({"aria-selected":c,onMouseEnter:a._onItemMouseEnter.bind(a,t),onMouseLeave:a._onMouseItemLeave.bind(a,t),onMouseMove:a._onItemMouseMove.bind(a,t),role:"option"},{"data-index":t.index,"data-is-focusable":!(t.disabled||t.hidden)}),label:t.text,title:u,onRenderLabel:a._onRenderItemLabel.bind(a,Ii(Ii({},t),{id:p})),className:Os(d,"is-multi-select"),checked:c,styles:g,ariaPositionInSet:t.hidden?void 0:a._sizePosCache.positionInSet(t.index),ariaSetSize:t.hidden?void 0:a._sizePosCache.optionSetSize,ariaLabel:t.ariaLabel,ariaLabelledBy:t.ariaLabel?void 0:p}):e.createElement(XC,{id:h,key:t.key,"data-index":t.index,"data-is-focusable":!t.disabled,disabled:t.disabled,className:d,onClick:a._onItemClick(t),onMouseEnter:a._onItemMouseEnter.bind(a,t),onMouseLeave:a._onMouseItemLeave.bind(a,t),onMouseMove:a._onItemMouseMove.bind(a,t),role:"option","aria-selected":c?"true":"false",ariaLabel:t.ariaLabel,title:u,"aria-posinset":a._sizePosCache.positionInSet(t.index),"aria-setsize":a._sizePosCache.optionSetSize},s(t,a._onRenderOption))},a._onRenderOption=function(t){return e.createElement("span",{className:a._classNames.dropdownOptionText},t.text)},a._onRenderMultiselectOption=function(t){return e.createElement("span",{id:t.id,"aria-hidden":"true",className:a._classNames.dropdownOptionText},t.text)},a._onRenderItemLabel=function(e){var t=a.props.onRenderOption;return(void 0===t?a._onRenderMultiselectOption:t)(e,a._onRenderMultiselectOption)},a._onPositioned=function(e){a._focusZone.current&&a._requestAnimationFrame((function(){var e=a.props.hoisted.selectedIndices;if(a._focusZone.current)if(!a._hasBeenPositioned&&e&&e[0]&&!a.props.options[e[0]].disabled){var t=_n().getElementById("".concat(a._id,"-list").concat(e[0]));t&&a._focusZone.current.focusElement(t),a._hasBeenPositioned=!0}else a._focusZone.current.focus()})),a.state.calloutRenderEdge&&a.state.calloutRenderEdge===e.targetEdge||a.setState({calloutRenderEdge:e.targetEdge})},a._onItemClick=function(e){return function(t){e.disabled||(a.setSelectedIndex(t,e.index),a.props.multiSelect||a.setState({isOpen:!1}))}},a._onScroll=function(){var e=Zc(a.context);a._isScrollIdle||void 0===a._scrollIdleTimeoutId?a._isScrollIdle=!1:(e.clearTimeout(a._scrollIdleTimeoutId),a._scrollIdleTimeoutId=void 0),a._scrollIdleTimeoutId=e.setTimeout((function(){a._isScrollIdle=!0}),a._scrollIdleDelay)},a._onMouseItemLeave=function(e,t){if(!a._shouldIgnoreMouseEvent()&&a._host.current)if(a._host.current.setActive)try{a._host.current.setActive()}catch(e){}else a._host.current.focus()},a._onDismiss=function(){a.setState({isOpen:!1})},a._onDropdownBlur=function(e){a._isDisabled()||a.state.isOpen||(a.setState({hasFocus:!1}),a.props.onBlur&&a.props.onBlur(e))},a._onDropdownKeyDown=function(e){if(!a._isDisabled()&&(a._lastKeyDownWasAltOrMeta=a._isAltOrMeta(e),!a.props.onKeyDown||(a.props.onKeyDown(e),!e.defaultPrevented))){var t,i=a.props.hoisted.selectedIndices.length?a.props.hoisted.selectedIndices[0]:-1,n=e.altKey||e.metaKey,r=a.state.isOpen;switch(e.which){case ao.enter:a.setState({isOpen:!r});break;case ao.escape:if(!r)return;a.setState({isOpen:!1});break;case ao.up:if(n){if(r){a.setState({isOpen:!1});break}return}a.props.multiSelect?a.setState({isOpen:!0}):a._isDisabled()||(t=a._moveIndex(e,-1,i-1,i));break;case ao.down:n&&(e.stopPropagation(),e.preventDefault()),n&&!r||a.props.multiSelect?a.setState({isOpen:!0}):a._isDisabled()||(t=a._moveIndex(e,1,i+1,i));break;case ao.home:a.props.multiSelect||(t=a._moveIndex(e,1,0,i));break;case ao.end:a.props.multiSelect||(t=a._moveIndex(e,-1,a.props.options.length-1,i));break;case ao.space:break;default:return}t!==i&&(e.stopPropagation(),e.preventDefault())}},a._onDropdownKeyUp=function(e){if(!a._isDisabled()){var t=a._shouldHandleKeyUp(e),i=a.state.isOpen;a.props.onKeyUp&&(a.props.onKeyUp(e),e.defaultPrevented)||(e.which===ao.space?(a.setState({isOpen:!i}),e.stopPropagation(),e.preventDefault()):t&&i&&a.setState({isOpen:!1}))}},a._onZoneKeyDown=function(e){var t,i,n;a._lastKeyDownWasAltOrMeta=a._isAltOrMeta(e);var r=e.altKey||e.metaKey;switch(e.which){case ao.up:r?a.setState({isOpen:!1}):a._host.current&&(n=vl(a._host.current,a._host.current.lastChild,!0));break;case ao.home:case ao.end:case ao.pageUp:case ao.pageDown:break;case ao.down:!r&&a._host.current&&(n=fl(a._host.current,a._host.current.firstChild,!0));break;case ao.escape:a.setState({isOpen:!1});break;case ao.tab:a.setState({isOpen:!1});var s=_n();s&&(e.shiftKey?null===(t=Sl(s.body,a._dropDown.current,!1,!1,!0,!0))||void 0===t||t.focus():null===(i=yl(s.body,a._dropDown.current,!1,!1,!0,!0))||void 0===i||i.focus());break;default:return}n&&n.focus(),e.stopPropagation(),e.preventDefault()},a._onZoneKeyUp=function(e){a._shouldHandleKeyUp(e)&&a.state.isOpen&&(a.setState({isOpen:!1}),e.preventDefault())},a._onDropdownClick=function(e){if(!a.props.onClick||(a.props.onClick(e),!e.defaultPrevented)){var t=a.state.isOpen;a._isDisabled()||a._shouldOpenOnFocus()||a.setState({isOpen:!t}),a._isFocusedByClick=!1}},a._onDropdownMouseDown=function(){a._isFocusedByClick=!0},a._onFocus=function(e){if(!a._isDisabled()){a.props.onFocus&&a.props.onFocus(e);var t={hasFocus:!0};a._shouldOpenOnFocus()&&(t.isOpen=!0),a.setState(t)}},a._isDisabled=function(){var e=a.props.disabled,t=a.props.isDisabled;return void 0===e&&(e=t),e},a._onRenderLabel=function(t){var i=t.label,n=t.required,r=t.disabled,s=a._classNames.subComponentStyles?a._classNames.subComponentStyles.label:void 0;return i?e.createElement(r_,{className:a._classNames.label,id:a._labelId,required:n,styles:s,disabled:r},i):null},lo(a),i.multiSelect,i.selectedKey,i.selectedKeys,i.defaultSelectedKey,i.defaultSelectedKeys;var s=i.options;return a._id=i.id||bo("Dropdown"),a._labelId=a._id+"-label",a._listId=a._id+"-list",a._optionId=a._id+"-option",a._isScrollIdle=!0,a._hasBeenPositioned=!1,a._sizePosCache.updateOptions(s),a.state={isOpen:!1,hasFocus:!1,calloutRenderEdge:void 0},a}return bi(i,t),Object.defineProperty(i.prototype,"selectedOptions",{get:function(){var e=this.props;return T_(e.options,e.hoisted.selectedIndices)},enumerable:!1,configurable:!0}),i.prototype.componentWillUnmount=function(){clearTimeout(this._scrollIdleTimeoutId)},i.prototype.componentDidUpdate=function(e,t){!0===t.isOpen&&!1===this.state.isOpen&&(this._gotMouseMove=!1,this._hasBeenPositioned=!1,this.props.onDismiss&&this.props.onDismiss())},i.prototype.render=function(){var t=this._id,i=this.props,n=i.className,r=i.label,a=i.options,s=i.ariaLabel,o=i.required,l=i.errorMessage,c=i.styles,d=i.theme,u=i.panelProps,h=i.calloutProps,p=i.onRenderTitle,g=void 0===p?this._getTitle:p,m=i.onRenderContainer,f=void 0===m?this._onRenderContainer:m,v=i.onRenderCaretDown,S=void 0===v?this._onRenderCaretDown:v,y=i.onRenderLabel,C=void 0===y?this._onRenderLabel:y,_=i.onRenderItem,E=void 0===_?this._onRenderItem:_,T=i.hoisted.selectedIndices,b=this.state,I=b.isOpen,w=b.calloutRenderEdge,R=b.hasFocus,A=i.onRenderPlaceholder||i.onRenderPlaceHolder||this._getPlaceholder;a!==this._sizePosCache.cachedOptions&&this._sizePosCache.updateOptions(a);var P=T_(a,T),M=Ds(i,ks),k=this._isDisabled(),D=t+"-errorMessage";this._classNames=D_(c,{theme:d,className:n,hasError:!!(l&&l.length>0),hasLabel:!!r,isOpen:I,required:o,disabled:k,isRenderingPlaceholder:!P.length,panelClassName:u?u.className:void 0,calloutClassName:h?h.className:void 0,calloutRenderEdge:w});var O=!!l&&l.length>0;return e.createElement("div",{className:this._classNames.root,ref:this.props.hoisted.rootRef,"aria-owns":I?this._listId:void 0},C(this.props,this._onRenderLabel),e.createElement("div",Ii({"data-is-focusable":!k,"data-ktp-target":!0,ref:this._dropDown,id:t,tabIndex:k?-1:0,role:"combobox","aria-haspopup":"listbox","aria-expanded":I?"true":"false","aria-label":s,"aria-labelledby":r&&!s?zo(this._labelId,this._optionId):void 0,"aria-describedby":O?this._id+"-errorMessage":void 0,"aria-required":o,"aria-disabled":k,"aria-controls":I?this._listId:void 0},M,{className:this._classNames.dropdown,onBlur:this._onDropdownBlur,onKeyDown:this._onDropdownKeyDown,onKeyUp:this._onDropdownKeyUp,onClick:this._onDropdownClick,onMouseDown:this._onDropdownMouseDown,onFocus:this._onFocus}),e.createElement("span",{id:this._optionId,className:this._classNames.title,"aria-live":R?"polite":void 0,"aria-atomic":!!R||void 0,"aria-invalid":O},P.length?g(P,this._onRenderTitle):A(i,this._onRenderPlaceholder)),e.createElement("span",{className:this._classNames.caretDownWrapper},S(i,this._onRenderCaretDown))),I&&f(Ii(Ii({},i),{onDismiss:this._onDismiss,onRenderItem:E}),this._onRenderContainer),O&&e.createElement("div",{role:"alert",id:D,className:this._classNames.errorMessage},l))},i.prototype.focus=function(e){this._dropDown.current&&(this._dropDown.current.focus(),e&&this.setState({isOpen:!0}))},i.prototype.setSelectedIndex=function(e,t){var i=this.props,n=i.options,r=i.selectedKey,a=i.selectedKeys,s=i.multiSelect,o=i.notifyOnReselect,l=i.hoisted.selectedIndices,c=void 0===l?[]:l,d=!!c&&c.indexOf(t)>-1,u=[];if(t=Math.max(0,Math.min(n.length-1,t)),void 0===r&&void 0===a){if(s||o||t!==c[0]){if(s)if(u=c?this._copyArray(c):[],d){var h=u.indexOf(t);h>-1&&u.splice(h,1)}else u.push(t);else u=[t];e.persist(),this.props.hoisted.setSelectedIndices(u),this._onChange(e,n,t,d,s)}}else this._onChange(e,n,t,d,s)},i.prototype._copyArray=function(e){for(var t=[],i=0,n=e;i<n.length;i++){var r=n[i];t.push(r)}return t},i.prototype._moveIndex=function(e,t,i,n){var r=this.props.options;if(n===i||0===r.length)return n;i>=r.length?i=0:i<0&&(i=r.length-1);for(var a=0;r[i].itemType===YC.Header||r[i].itemType===YC.Divider||r[i].disabled;){if(a>=r.length)return n;i+t<0?i=r.length:i+t>=r.length&&(i=-1),i+=t,a++}return this.setSelectedIndex(e,i),i},i.prototype._renderFocusableList=function(t){var i=t.onRenderList,n=void 0===i?this._onRenderList:i,r=t.label,a=t.ariaLabel,s=t.multiSelect;return e.createElement("div",{className:this._classNames.dropdownItemsWrapper,onKeyDown:this._onZoneKeyDown,onKeyUp:this._onZoneKeyUp,ref:this._host,tabIndex:0},e.createElement(Yl,{ref:this._focusZone,direction:dl.vertical,id:this._listId,className:this._classNames.dropdownItems,role:"listbox","aria-label":a,"aria-labelledby":r&&!a?this._labelId:void 0,"aria-multiselectable":s},n(t,this._onRenderList)))},i.prototype._renderSeparator=function(t){var i=t.index,n=t.key,r=t.hidden?this._classNames.dropdownDividerHidden:this._classNames.dropdownDivider;return i>0?e.createElement("div",{role:"presentation",key:n,className:r}):null},i.prototype._renderHeader=function(t){var i=this.props.onRenderOption,n=void 0===i?this._onRenderOption:i,r=t.key,a=t.id,s=t.hidden?this._classNames.dropdownItemHeaderHidden:this._classNames.dropdownItemHeader;return e.createElement("div",{id:a,key:r,className:s},n(t,this._onRenderOption))},i.prototype._onItemMouseEnter=function(e,t){this._shouldIgnoreMouseEvent()||t.currentTarget.focus()},i.prototype._onItemMouseMove=function(e,t){var i=Qc(this.context),n=t.currentTarget;this._gotMouseMove=!0,this._isScrollIdle&&i.activeElement!==n&&n.focus()},i.prototype._shouldIgnoreMouseEvent=function(){return!this._isScrollIdle||!this._gotMouseMove},i.prototype._isAltOrMeta=function(e){return e.which===ao.alt||"Meta"===e.key},i.prototype._shouldHandleKeyUp=function(e){var t=this._lastKeyDownWasAltOrMeta&&this._isAltOrMeta(e);return this._lastKeyDownWasAltOrMeta=!1,!!t&&!(Ql()||Zl())},i.prototype._shouldOpenOnFocus=function(){var e=this.state.hasFocus,t=this.props.openOnKeyboardFocus;return!this._isFocusedByClick&&!0===t&&!e},i.defaultProps={options:[]},i.contextType=$c,i}(e.Component),H_={root:"ms-Dropdown-container",label:"ms-Dropdown-label",dropdown:"ms-Dropdown",title:"ms-Dropdown-title",caretDownWrapper:"ms-Dropdown-caretDownWrapper",caretDown:"ms-Dropdown-caretDown",callout:"ms-Dropdown-callout",panel:"ms-Dropdown-panel",dropdownItems:"ms-Dropdown-items",dropdownItem:"ms-Dropdown-item",dropdownDivider:"ms-Dropdown-divider",dropdownOptionText:"ms-Dropdown-optionText",dropdownItemHeader:"ms-Dropdown-header",titleIsPlaceHolder:"ms-Dropdown-titleIsPlaceHolder",titleHasError:"ms-Dropdown-title--hasError"},$_=((L_={})["".concat(Nr,", ").concat(Lr.replace("@media ",""))]=Ii({},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),L_),G_={selectors:Ii((x_={},x_[Nr]=(F_={backgroundColor:"Highlight",borderColor:"Highlight",color:"HighlightText"},F_[".".concat(Vr," &:focus:after")]={borderColor:"HighlightText"},F_),x_[".ms-Checkbox-checkbox"]=(U_={},U_[Nr]={borderColor:"HighlightText"},U_),x_),$_)},j_={selectors:(B_={},B_[Nr]={borderColor:"Highlight"},B_)},z_=Ur(0,xr),W_=Ws(N_,(function(e){var t,i,n,r,a,s,o,l,c,d,u,h,p=e.theme,g=e.hasError,m=e.hasLabel,f=e.className,v=e.isOpen,S=e.disabled,y=e.required,C=e.isRenderingPlaceholder,_=e.panelClassName,E=e.calloutClassName,T=e.calloutRenderEdge;if(!p)throw new Error("theme is undefined or null in base Dropdown getStyles function.");var b=Kr(H_,p),I=p.palette,w=p.semanticColors,R=p.effects,A=p.fonts,P={color:w.menuItemTextHovered},M={color:w.menuItemText},k={borderColor:w.errorText},D=[b.dropdownItem,{backgroundColor:"transparent",boxSizing:"border-box",cursor:"pointer",display:"flex",alignItems:"center",padding:"0 8px",width:"100%",minHeight:36,lineHeight:20,height:0,position:"relative",border:"1px solid transparent",borderRadius:0,wordWrap:"break-word",overflowWrap:"break-word",textAlign:"left",".ms-Button-flexContainer":{width:"100%"}}],O=[b.dropdownItemHeader,Ii(Ii({},A.medium),{fontWeight:Mr.semibold,color:w.menuHeader,background:"none",backgroundColor:"transparent",border:"none",height:36,lineHeight:36,cursor:"default",padding:"0 8px",userSelect:"none",textAlign:"left",selectors:(t={},t[Nr]=Ii({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),t)})],N=w.menuItemBackgroundPressed,L=function(e){var t,i;return void 0===e&&(e=!1),{selectors:(t={"&:hover":[{color:w.menuItemTextHovered,backgroundColor:e?N:w.menuItemBackgroundHovered},G_],"&.is-multi-select:hover":[{backgroundColor:e?N:"transparent"},G_],"&:active:hover":[{color:w.menuItemTextHovered,backgroundColor:e?w.menuItemBackgroundHovered:w.menuItemBackgroundPressed},G_]},t[".".concat(Vr," &:focus:after")]=(i={left:0,top:0,bottom:0,right:0},i[Nr]={inset:"2px"},i),t[Nr]={border:"none"},t)}},x=Ai(Ai([],D,!0),[{backgroundColor:N,color:w.menuItemTextHovered},L(!0),G_],!1),F=Ai(Ai([],D,!0),[{color:w.disabledText,cursor:"default",selectors:(i={},i[Nr]={color:"GrayText",border:"none"},i)}],!1),U=T===ec.bottom?"".concat(R.roundedCorner2," ").concat(R.roundedCorner2," 0 0"):"0 0 ".concat(R.roundedCorner2," ").concat(R.roundedCorner2),B=T===ec.bottom?"0 0 ".concat(R.roundedCorner2," ").concat(R.roundedCorner2):"".concat(R.roundedCorner2," ").concat(R.roundedCorner2," 0 0");return{root:[b.root,f],label:b.label,dropdown:[b.dropdown,Ba,A.medium,{color:w.menuItemText,borderColor:w.focusBorder,position:"relative",outline:0,userSelect:"none",selectors:(n={},n["&:hover ."+b.title]=[!S&&P,{borderColor:v?I.neutralSecondary:I.neutralPrimary},j_],n["&:focus ."+b.title]=[!S&&P,{selectors:(r={},r[Nr]={color:"Highlight"},r)}],n["&:focus:after"]=[{pointerEvents:"none",content:"''",position:"absolute",boxSizing:"border-box",top:"0px",left:"0px",width:"100%",height:"100%",border:S?"none":"2px solid ".concat(I.themePrimary),borderRadius:"2px",selectors:(a={},a[Nr]={color:"Highlight"},a)}],n["&:active ."+b.title]=[!S&&P,{borderColor:I.themePrimary},j_],n["&:hover ."+b.caretDown]=!S&&M,n["&:focus ."+b.caretDown]=[!S&&M,{selectors:(s={},s[Nr]={color:"Highlight"},s)}],n["&:active ."+b.caretDown]=!S&&M,n["&:hover ."+b.titleIsPlaceHolder]=!S&&M,n["&:focus ."+b.titleIsPlaceHolder]=!S&&M,n["&:active ."+b.titleIsPlaceHolder]=!S&&M,n["&:hover ."+b.titleHasError]=k,n["&:active ."+b.titleHasError]=k,n)},v&&"is-open",S&&"is-disabled",y&&"is-required",y&&!m&&{selectors:(o={":before":{content:"'*'",color:w.errorText,position:"absolute",top:-5,right:-10}},o[Nr]={selectors:{":after":{right:-14}}},o)}],title:[b.title,Ba,{backgroundColor:w.inputBackground,borderWidth:1,borderStyle:"solid",borderColor:w.inputBorder,borderRadius:v?U:R.roundedCorner2,cursor:"pointer",display:"block",height:32,lineHeight:30,padding:"0 28px 0 8px",position:"relative",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},C&&[b.titleIsPlaceHolder,{color:w.inputPlaceholderText}],g&&[b.titleHasError,k],S&&{backgroundColor:w.disabledBackground,border:"none",color:w.disabledText,cursor:"default",selectors:(l={},l[Nr]=Ii({border:"1px solid GrayText",color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),l)}],caretDownWrapper:[b.caretDownWrapper,{height:32,lineHeight:30,paddingTop:1,position:"absolute",right:8,top:0},!S&&{cursor:"pointer"}],caretDown:[b.caretDown,{color:I.neutralSecondary,fontSize:A.small.fontSize,pointerEvents:"none"},S&&{color:w.disabledText,selectors:(c={},c[Nr]=Ii({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),c)}],errorMessage:Ii(Ii({color:w.errorText},p.fonts.small),{paddingTop:5}),callout:[b.callout,{boxShadow:R.elevation8,borderRadius:B,selectors:(d={},d[".ms-Callout-main"]={borderRadius:B},d)},E],dropdownItemsWrapper:{selectors:{"&:focus":{outline:0}}},dropdownItems:[b.dropdownItems,{display:"block"}],dropdownItem:Ai(Ai([],D,!0),[L()],!1),dropdownItemSelected:x,dropdownItemDisabled:F,dropdownItemSelectedAndDisabled:[x,F,{backgroundColor:"transparent"}],dropdownItemHidden:Ai(Ai([],D,!0),[{display:"none"}],!1),dropdownDivider:[b.dropdownDivider,{height:1,backgroundColor:w.bodyDivider}],dropdownDividerHidden:[b.dropdownDivider,{display:"none"}],dropdownOptionText:[b.dropdownOptionText,{overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",minWidth:0,maxWidth:"100%",wordWrap:"break-word",overflowWrap:"break-word",margin:"1px"}],dropdownItemHeader:O,dropdownItemHeaderHidden:Ai(Ai([],O,!0),[{display:"none"}],!1),subComponentStyles:{label:{root:{display:"inline-block"}},multiSelectItem:{root:{padding:0},label:{alignSelf:"stretch",padding:"0 8px",width:"100%"},input:{selectors:(u={},u[".".concat(Vr," &:focus + label::before")]={outlineOffset:"0px"},u)}},panel:{root:[_],main:{selectors:(h={},h[z_]={width:272},h)},contentInner:{padding:"0 0 20px"}}}}}),void 0,{scope:"Dropdown"});W_.displayName="Dropdown";var q_=yr,K_={root:"ms-Modal",main:"ms-Dialog-main",scrollableContent:"ms-Modal-scrollableContent",isOpen:"is-open",layer:"ms-Modal-Layer"},J_=vn((function(e,t){return{root:cn(e,t&&{touchAction:"none",selectors:{"& *":{userSelect:"none"}}})}})),Y_={start:"touchstart",move:"touchmove",stop:"touchend"},Q_={start:"mousedown",move:"mousemove",stop:"mouseup"},Z_=function(t){function i(i){var n=t.call(this,i)||this;return n._currentEventType=Q_,n._events=[],n._onMouseDown=function(t){var i=e.Children.only(n.props.children).props.onMouseDown;return i&&i(t),n._currentEventType=Q_,n._onDragStart(t)},n._onMouseUp=function(t){var i=e.Children.only(n.props.children).props.onMouseUp;return i&&i(t),n._currentEventType=Q_,n._onDragStop(t)},n._onTouchStart=function(t){var i=e.Children.only(n.props.children).props.onTouchStart;return i&&i(t),n._currentEventType=Y_,n._onDragStart(t)},n._onTouchEnd=function(t){var i=e.Children.only(n.props.children).props.onTouchEnd;i&&i(t),n._currentEventType=Y_,n._onDragStop(t)},n._onDragStart=function(e){if("number"==typeof e.button&&0!==e.button)return!1;if(!(n.props.handleSelector&&!n._matchesSelector(e.target,n.props.handleSelector)||n.props.preventDragSelector&&n._matchesSelector(e.target,n.props.preventDragSelector))){n._touchId=n._getTouchId(e);var t=n._getControlPosition(e);if(void 0!==t){var i=n._createDragDataFromPosition(t);n.props.onStart&&n.props.onStart(e,i),n.setState({isDragging:!0,lastPosition:t});var r=Qc(n.context);n._events=[lc(r.body,n._currentEventType.move,n._onDrag,!0),lc(r.body,n._currentEventType.stop,n._onDragStop,!0)]}}},n._onDrag=function(e){"touchmove"===e.type&&e.preventDefault();var t=n._getControlPosition(e);if(t){var i=n._createUpdatedDragData(n._createDragDataFromPosition(t)),r=i.position;n.props.onDragChange&&n.props.onDragChange(e,i),n.setState({position:r,lastPosition:t})}},n._onDragStop=function(e){if(n.state.isDragging){var t=n._getControlPosition(e);if(t){var i=n._createDragDataFromPosition(t);n.setState({isDragging:!1,lastPosition:void 0}),n.props.onStop&&n.props.onStop(e,i),n.props.position&&n.setState({position:n.props.position}),n._events.forEach((function(e){return e()}))}}},n.state={isDragging:!1,position:n.props.position||{x:0,y:0},lastPosition:void 0},n}return bi(i,t),i.prototype.componentDidUpdate=function(e){!this.props.position||e.position&&this.props.position===e.position||this.setState({position:this.props.position})},i.prototype.componentWillUnmount=function(){this._events.forEach((function(e){return e()}))},i.prototype.render=function(){var t=e.Children.only(this.props.children),i=t.props,n=this.props.position,r=this.state,a=r.position,s=r.isDragging,o=a.x,l=a.y;return n&&!s&&(o=n.x,l=n.y),e.cloneElement(t,{style:Ii(Ii({},i.style),{transform:"translate(".concat(o,"px, ").concat(l,"px)")}),className:J_(i.className,this.state.isDragging).root,onMouseDown:this._onMouseDown,onMouseUp:this._onMouseUp,onTouchStart:this._onTouchStart,onTouchEnd:this._onTouchEnd})},i.prototype._getControlPosition=function(e){var t=this._getActiveTouch(e);if(void 0===this._touchId||t){var i=t||e;return{x:i.clientX,y:i.clientY}}},i.prototype._getActiveTouch=function(e){return e.targetTouches&&this._findTouchInTouchList(e.targetTouches)||e.changedTouches&&this._findTouchInTouchList(e.changedTouches)},i.prototype._getTouchId=function(e){var t=e.targetTouches&&e.targetTouches[0]||e.changedTouches&&e.changedTouches[0];if(t)return t.identifier},i.prototype._matchesSelector=function(e,t){var i;if(!e||e===(null===(i=Qc(this.context))||void 0===i?void 0:i.body))return!1;var n=e.matches||e.webkitMatchesSelector||e.msMatchesSelector;return!!n&&(n.call(e,t)||this._matchesSelector(e.parentElement,t))},i.prototype._findTouchInTouchList=function(e){if(void 0!==this._touchId)for(var t=0;t<e.length;t++)if(e[t].identifier===this._touchId)return e[t]},i.prototype._createDragDataFromPosition=function(e){var t=this.state.lastPosition;return void 0===t?{delta:{x:0,y:0},lastPosition:e,position:e}:{delta:{x:e.x-t.x,y:e.y-t.y},lastPosition:t,position:e}},i.prototype._createUpdatedDragData=function(e){var t=this.state.position;return{position:{x:t.x+e.delta.x,y:t.y+e.delta.y},delta:e.delta,lastPosition:t}},i.contextType=$c,i}(e.Component),X_={x:0,y:0},eE={isOpen:!1,isDarkOverlay:!0,className:"",containerClassName:"",enableAriaHiddenSiblings:!0},tE=Ys(),iE=e.forwardRef((function(t,i){var n,r,a,s,o,l=Xl(eE,t),c=l.allowTouchBodyScroll,d=l.className,u=l.children,h=l.containerClassName,p=l.scrollableContentClassName,g=l.elementToFocusOnDismiss,m=l.firstFocusableSelector,f=l.focusTrapZoneProps,v=l.forceFocusInsideTrap,S=l.disableRestoreFocus,y=void 0===S?l.ignoreExternalFocusing:S,C=l.isBlocking,_=l.isAlert,E=l.isClickableOutsideFocusTrap,T=l.isDarkOverlay,b=l.onDismiss,I=l.layerProps,w=l.overlay,R=l.isOpen,A=l.titleAriaId,P=l.styles,M=l.subtitleAriaId,k=l.theme,D=l.topOffsetFixed,O=l.responsiveMode,N=l.onLayerDidMount,L=l.isModeless,x=l.dragOptions,F=l.onDismissed,U=l.enableAriaHiddenSiblings,B=l.popupProps,V=e.useRef(null),H=e.useRef(null),$=qo(H,null==f?void 0:f.componentRef),G=e.useRef(null),j=qo(V,i),z=Eu(j),W=fu("ModalFocusTrapZone",null==f?void 0:f.id),q=Gc(),K=sC(),J=K.setTimeout,Y=K.clearTimeout,Q=e.useState(R),Z=Q[0],X=Q[1],ee=e.useState(R),te=ee[0],ie=ee[1],ne=e.useState(X_),re=ne[0],ae=ne[1],se=e.useState(),oe=se[0],le=se[1],ce=ih(!1),de=ce[0],ue=ce[1],he=ue.toggle,pe=ue.setFalse,ge=qc((function(){return{onModalCloseTimer:0,allowTouchBodyScroll:c,scrollableContent:null,lastSetCoordinates:X_,events:new So({})}})),me=(x||{}).keepInBounds,fe=null!=_?_:C&&!L,ve=void 0===I?"":I.className,Se=tE(P,{theme:k,className:d,containerClassName:h,scrollableContentClassName:p,isOpen:R,isVisible:te,hasBeenOpened:ge.hasBeenOpened,modalRectangleTop:oe,topOffsetFixed:D,isModeless:L,layerClassName:ve,windowInnerHeight:null==q?void 0:q.innerHeight,isDefaultDragHandle:x&&!x.dragHandleSelector}),ye=Ii(Ii({eventBubblingEnabled:!1},I),{onLayerDidMount:I&&I.onLayerDidMount?I.onLayerDidMount:N,insertFirst:(null==I?void 0:I.insertFirst)||L,className:Se.layer}),Ce=e.useCallback((function(e){e?ge.allowTouchBodyScroll?Ol(e,ge.events):Dl(e,ge.events):ge.events.off(ge.scrollableContent),ge.scrollableContent=e}),[ge]),_e=function(){var e=G.current,t=null==e?void 0:e.getBoundingClientRect();t&&(D&&le(t.top),me&&(ge.minPosition={x:-t.left,y:-t.top},ge.maxPosition={x:t.left,y:t.top}))},Ee=e.useCallback((function(e,t){var i=ge.minPosition,n=ge.maxPosition;return me&&i&&n&&(t=Math.max(i[e],t),t=Math.min(n[e],t)),t}),[me,ge]),Te=function(){var e;ge.lastSetCoordinates=X_,pe(),ge.isInKeyboardMoveMode=!1,X(!1),ae(X_),null===(e=ge.disposeOnKeyUp)||void 0===e||e.call(ge),null==F||F()},be=e.useCallback((function(){pe(),ge.isInKeyboardMoveMode=!1}),[ge,pe]),Ie=e.useCallback((function(e,t){ae((function(e){return{x:Ee("x",e.x+t.delta.x),y:Ee("y",e.y+t.delta.y)}}))}),[Ee]),we=e.useCallback((function(){H.current&&H.current.focus()}),[]);e.useEffect((function(){var e;Y(ge.onModalCloseTimer),R&&(requestAnimationFrame((function(){return J(_e,0)})),X(!0),x&&(e=function(e){e.altKey&&e.ctrlKey&&e.keyCode===ao.space&&ul(ge.scrollableContent,e.target)&&(he(),e.preventDefault(),e.stopPropagation())},ge.disposeOnKeyUp||(ge.events.on(q,"keyup",e,!0),ge.disposeOnKeyUp=function(){ge.events.off(q,"keyup",e,!0),ge.disposeOnKeyUp=void 0})),ge.hasBeenOpened=!0,ie(!0)),!R&&Z&&(ge.onModalCloseTimer=J(Te,1e3*parseFloat(q_)),ie(!1))}),[Z,R]),Zh((function(){ge.events.dispose()})),function(t,i){e.useImperativeHandle(t.componentRef,(function(){return{focus:function(){i.current&&i.current.focus()}}}),[i])}(l,H);var Re=e.createElement(Df,Ii({},f,{id:W,ref:G,componentRef:$,className:Os(Se.main,null==f?void 0:f.className),elementToFocusOnDismiss:null!==(n=null==f?void 0:f.elementToFocusOnDismiss)&&void 0!==n?n:g,isClickableOutsideFocusTrap:null!==(r=null==f?void 0:f.isClickableOutsideFocusTrap)&&void 0!==r?r:L||E||!C,disableRestoreFocus:null!==(a=null==f?void 0:f.disableRestoreFocus)&&void 0!==a?a:y,forceFocusInsideTrap:(null!==(s=null==f?void 0:f.forceFocusInsideTrap)&&void 0!==s?s:v)&&!L,firstFocusableSelector:(null==f?void 0:f.firstFocusableSelector)||m,focusPreviouslyFocusedInnerElement:null===(o=null==f?void 0:f.focusPreviouslyFocusedInnerElement)||void 0===o||o,onBlur:ge.isInKeyboardMoveMode?function(e){var t,i;null===(t=null==f?void 0:f.onBlur)||void 0===t||t.call(f,e),ge.lastSetCoordinates=X_,ge.isInKeyboardMoveMode=!1,null===(i=ge.disposeOnKeyDown)||void 0===i||i.call(ge)}:void 0}),x&&ge.isInKeyboardMoveMode&&e.createElement("div",{className:Se.keyboardMoveIconContainer},x.keyboardMoveIconProps?e.createElement(al,Ii({},x.keyboardMoveIconProps)):e.createElement(al,{iconName:"move",className:Se.keyboardMoveIcon})),e.createElement("div",{ref:Ce,className:Se.scrollableContent,"data-is-scrollable":!0},x&&de&&e.createElement(x.menu,{items:[{key:"move",text:x.moveMenuItemText,onClick:function(){var e=function(e){if(e.altKey&&e.ctrlKey&&e.keyCode===ao.space)return e.preventDefault(),void e.stopPropagation();var t=e.altKey||e.keyCode===ao.escape;if(de&&t&&pe(),!ge.isInKeyboardMoveMode||e.keyCode!==ao.escape&&e.keyCode!==ao.enter||(ge.isInKeyboardMoveMode=!1,e.preventDefault(),e.stopPropagation()),ge.isInKeyboardMoveMode){var i=!0,n=function(e){var t=10;return e.shiftKey?e.ctrlKey||(t=50):e.ctrlKey&&(t=1),t}(e);switch(e.keyCode){case ao.escape:ae(ge.lastSetCoordinates);case ao.enter:ge.lastSetCoordinates=X_;break;case ao.up:ae((function(e){return{x:e.x,y:Ee("y",e.y-n)}}));break;case ao.down:ae((function(e){return{x:e.x,y:Ee("y",e.y+n)}}));break;case ao.left:ae((function(e){return{x:Ee("x",e.x-n),y:e.y}}));break;case ao.right:ae((function(e){return{x:Ee("x",e.x+n),y:e.y}}));break;default:i=!1}i&&(e.preventDefault(),e.stopPropagation())}};ge.lastSetCoordinates=re,pe(),ge.isInKeyboardMoveMode=!0,ge.events.on(q,"keydown",e,!0),ge.disposeOnKeyDown=function(){ge.events.off(q,"keydown",e,!0),ge.disposeOnKeyDown=void 0}}},{key:"close",text:x.closeMenuItemText,onClick:Te}],onDismiss:pe,alignTargetEdge:!0,coverTarget:!0,directionalHint:ll.topLeftEdge,directionalHintFixed:!0,shouldFocusOnMount:!0,target:ge.scrollableContent}),u));return Z&&z>=(O||hu.small)&&e.createElement(Ld,Ii({ref:j},ye),e.createElement(Wc,Ii({role:fe?"alertdialog":"dialog",ariaLabelledBy:A,ariaDescribedBy:M,onDismiss:b,shouldRestoreFocus:!y,enableAriaHiddenSiblings:U,"aria-modal":!L},B),e.createElement("div",{className:Se.root,role:L?void 0:"document"},!L&&e.createElement(dC,Ii({"aria-hidden":!0,isDarkThemed:T,onClick:C?void 0:b,allowTouchBodyScroll:c},w)),x?e.createElement(Z_,{handleSelector:x.dragHandleSelector||"#".concat(W),preventDragSelector:"button",onStart:be,onDragChange:Ie,onStop:we,position:re},Re):Re)))||null}));iE.displayName="Modal";var nE=Ws(iE,(function(e){var t,i=e.className,n=e.containerClassName,r=e.scrollableContentClassName,a=e.isOpen,s=e.isVisible,o=e.hasBeenOpened,l=e.modalRectangleTop,c=e.theme,d=e.topOffsetFixed,u=e.isModeless,h=e.layerClassName,p=e.isDefaultDragHandle,g=e.windowInnerHeight,m=c.palette,f=c.effects,v=c.fonts,S=Kr(K_,c);return{root:[S.root,v.medium,{backgroundColor:"transparent",position:"fixed",height:"100%",width:"100%",display:"flex",alignItems:"center",justifyContent:"center",opacity:0,pointerEvents:"none",transition:"opacity ".concat(q_)},d&&"number"==typeof l&&o&&{alignItems:"flex-start"},a&&S.isOpen,s&&{opacity:1},s&&!u&&{pointerEvents:"auto"},i],main:[S.main,{boxShadow:f.elevation64,borderRadius:f.roundedCorner2,backgroundColor:m.white,boxSizing:"border-box",position:"relative",textAlign:"left",outline:"3px solid transparent",maxHeight:"calc(100% - 32px)",maxWidth:"calc(100% - 32px)",minHeight:"176px",minWidth:"288px",overflowY:"auto",zIndex:u?Br.Layer:void 0},u&&{pointerEvents:"auto"},d&&"number"==typeof l&&o&&{top:l},p&&{cursor:"move"},n],scrollableContent:[S.scrollableContent,{overflowY:"auto",flexGrow:1,maxHeight:"100vh",selectors:(t={},t["@supports (-webkit-overflow-scrolling: touch)"]={maxHeight:g},t)},r],layer:u&&[h,S.layer,{pointerEvents:"none"}],keyboardMoveIconContainer:{position:"absolute",display:"flex",justifyContent:"center",width:"100%",padding:"3px 0px"},keyboardMoveIcon:{fontSize:v.xLargePlus.fontSize,width:"24px"}}}),void 0,{scope:"Modal",fields:["theme","styles","enableAriaHiddenSiblings"]});nE.displayName="Modal";var rE=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){return e.createElement(yy,Ii({},this.props,{primary:!0,onRenderDescription:Ro}))},Ri([qu("PrimaryButton",["theme","styles"],!0)],i)}(e.Component);const aE=cn({fontWeight:600,fontSize:bm(20),lineHeight:bm(28)}),sE=cn({paddingBottom:bm(20)}),oE=cn({paddingTop:bm(16)}),lE=e=>cn({fontWeight:400,fontSize:bm(12),lineHeight:bm(16),color:e.palette.neutralSecondary,paddingBottom:bm(24)}),cE=cn({paddingTop:bm(16)}),dE=e=>({root:{borderRadius:bm(2),margin:bm(8)},rootHovered:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white},rootFocused:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white},rootPressed:{backgroundColor:e.palette.themePrimary,borderColor:e.palette.themePrimary,color:e.palette.white}}),uE={callout:Object.assign({height:bm(300),overflow:"auto"},UC)},hE={"ar-ae":"ar","ar-sa":"ar","da-dk":"da","de-de":"de","en-au":"en","en-ca":"en","en-gb":"en","en-in":"en","en-nz":"en","en-us":"en","es-es":"es","es-mx":"es","fi-fi":"fi","fr-ca":"fr-ca","fr-fr":"fr","hi-in":"hi","it-it":"it","ja-jp":"ja","ko-kr":"ko","nb-no":"nb","nl-be":"nl","nl-nl":"nl","pl-pl":"pl","pt-br":"pt","ru-ru":"ru","sv-se":"sv","zh-cn":"zh-Hans","zh-hk":"zh-Hant","cs-cz":"cs","pt-pt":"pt-pt","tr-tr":"tr","vi-vn":"vi","th-th":"th","he-il":"he","cy-gb":"cy","uk-ua":"uk","el-gr":"el","hu-hu":"hu","ro-ro":"ro","sk-sk":"sk","zh-tw":"zh-Hant"};const pE=t=>{const{supportedSpokenLanguages:i,supportedCaptionLanguages:n,currentSpokenLanguage:r,currentCaptionLanguage:a,isCaptionsFeatureActive:s,showModal:o,onSetSpokenLanguage:l,onSetCaptionLanguage:c,onDismissCaptionsSettings:d,onStartCaptions:u,strings:h,spokenLanguageStrings:p,captionLanguageStrings:g,changeCaptionLanguage:m=!1}=t,f=xh(),[v,S]=(0,e.useState)(!1),[y,C]=(0,e.useState)({key:r||Ph,text:r||Ph}),[_,E]=(0,e.useState)({key:a||hE[y.key],text:a||hE[y.key]});(0,e.useEffect)((()=>{s&&!v&&(l(y.key),S(!0))}),[s,l,y.key,v]);const T=(0,e.useCallback)((()=>{d&&d()}),[d]),b=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){const e=y.key,t=_.key;s?(l(e),m&&c(t)):yield u({spokenLanguage:e}),T()},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[T,s,l,c,u,y.key,_.key,m]),I=(0,e.useMemo)((()=>i.map((e=>({key:e,text:p?p[e]:e})))),[i,p]),w=(0,e.useMemo)((()=>n.map((e=>({key:e,text:g?g[e]:e})))),[n,g]),R=(0,e.useMemo)((()=>[...I].sort(((e,t)=>e.text>t.text?1:-1))),[I]),A=(0,e.useMemo)((()=>[...w].sort(((e,t)=>e.text>t.text?1:-1))),[w]),P=(0,e.useMemo)((()=>({preventDismissOnEvent:nf})),[]),M=(0,e.useCallback)((()=>{const t=null!=r?r:Ph,i=null!=a?a:hE[t];return e.createElement(Gs,null,e.createElement(W_,{label:null==h?void 0:h.captionsSettingsSpokenLanguageDropdownLabel,selectedKey:y?y.key:void 0,onChange:(e,t)=>((e,t)=>{t&&C(t)})(0,t),calloutProps:P,placeholder:t,options:R,styles:uE}),e.createElement(Cf,{className:lE(f)},null==h?void 0:h.captionsSettingsSpokenLanguageDropdownInfoText),m&&e.createElement(e.Fragment,null,e.createElement(W_,{label:null==h?void 0:h.captionsSettingsCaptionLanguageDropdownLabel,selectedKey:_?_.key:void 0,onChange:(e,t)=>((e,t)=>{t&&E(t)})(0,t),calloutProps:P,placeholder:i,options:A,styles:uE}),e.createElement(Cf,{className:lE(f)},null==h?void 0:h.captionsSettingsCaptionLanguageDropdownInfoText)))}),[P,r,a,R,A,_,y,null==h?void 0:h.captionsSettingsSpokenLanguageDropdownInfoText,null==h?void 0:h.captionsSettingsCaptionLanguageDropdownLabel,null==h?void 0:h.captionsSettingsSpokenLanguageDropdownLabel,null==h?void 0:h.captionsSettingsCaptionLanguageDropdownInfoText,f,m]),k=(0,e.useMemo)((()=>(e=>({main:{borderRadius:e.effects.roundedCorner6,padding:bm(24),width:bm(440),height:"fit-content",overflow:"hidden"}}))(f)),[f]);return e.createElement(e.Fragment,null,e.createElement(nE,{titleAriaId:null==h?void 0:h.captionsSettingsModalAriaLabel,isOpen:o,onDismiss:T,isBlocking:!0,styles:k},e.createElement(Gs,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center",className:sE},e.createElement(Cf,{className:aE},null==h?void 0:h.captionsSettingsModalTitle),e.createElement(th,{iconProps:{iconName:"Cancel"},ariaLabel:null==h?void 0:h.captionsSettingsCloseModalButtonAriaLabel,onClick:T,style:{color:f.palette.black}})),e.createElement(Gs,{className:oE},M()),e.createElement(Gs,{horizontal:!0,horizontalAlign:"end",className:cE},e.createElement(rE,{styles:dE(f),onClick:b},e.createElement("span",null,null==h?void 0:h.captionsSettingsConfirmButtonLabel)),e.createElement(yy,{onClick:T,styles:dE(f)},e.createElement("span",null,null==h?void 0:h.captionsSettingsCancelButtonLabel)))))},gE=(e,t)=>mE(e,SE,t),mE=(t,i,n)=>{var r;const a=Xm(),s=(0,e.useRef)(!1);(0,e.useEffect)((()=>(s.current=!0,()=>{s.current=!1})));const o=null===(r=a.getState().call)||void 0===r?void 0:r.id,l=(0,e.useMemo)((()=>({callId:o})),[o]),[c,d]=(0,e.useState)(t(i(a.getState()),null!=n?n:l)),u=(0,e.useRef)(c);return u.current=c,(0,e.useEffect)((()=>{const e=e=>{if(!s.current)return;const r=t(i(e),null!=n?n:l);u.current!==r&&d(r)};return a.onStateChange(e),()=>{a.offStateChange(e)}}),[i,a,t,n,l]),c},fE=ri(((e,t,i,n,r,a,s)=>({userId:e,incomingCalls:{},incomingCallsEnded:{},callsEnded:{},deviceManager:t,callAgent:{displayName:r},calls:i,latestErrors:n,alternateCallerId:a,environmentInfo:s}))),vE=ri((e=>e?{[e.id]:e}:{})),SE=e=>fE(e.userId,e.devices,vE(e.call),e.latestErrors,e.displayName,e.alternateCallerId,e.environmentInfo);var yE=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const CE=e=>{var t,i;const n=Xm(),r=null===(i=null===(t=n.getState().call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.capabilities;return _E(n,r)},_E=ri(((e,t)=>({onCreateLocalStreamView:t=>yE(void 0,void 0,void 0,(function*(){return yield e.createStreamView(void 0,t)})),onCreateRemoteStreamView:(t,i)=>yE(void 0,void 0,void 0,(function*(){return yield e.createStreamView(t,i)})),onHangUp:t=>yE(void 0,void 0,void 0,(function*(){yield e.leaveCall(t)})),onToggleHold:()=>yE(void 0,void 0,void 0,(function*(){var t;return"LocalHold"===(null===(t=e.getState().call)||void 0===t?void 0:t.state)?yield e.resumeCall():yield e.holdCall()})),onAddParticipant:(t,i)=>yE(void 0,void 0,void 0,(function*(){return"communicationUserId"in t?yield e.addParticipant(t):"phoneNumber"in t?yield e.addParticipant(t,i):void 0})),onSendDtmfTone:t=>yE(void 0,void 0,void 0,(function*(){yield e.sendDtmfTone(t)})),onRemoveParticipant:t=>yE(void 0,void 0,void 0,(function*(){"string"==typeof t?yield e.removeParticipant(t):yield e.removeParticipant(T(t))})),onRaiseHand:()=>yE(void 0,void 0,void 0,(function*(){yield e.raiseHand()})),onLowerHand:()=>yE(void 0,void 0,void 0,(function*(){yield e.lowerHand()})),onToggleRaiseHand:()=>yE(void 0,void 0,void 0,(function*(){var t;(null===(t=e.getState().call)||void 0===t?void 0:t.raiseHand.localParticipantRaisedHand)?yield e.lowerHand():yield e.raiseHand()})),onReactionClick:t=>yE(void 0,void 0,void 0,(function*(){yield e.onReactionClick(t)})),onSelectCamera:(t,i)=>yE(void 0,void 0,void 0,(function*(){yield e.setCamera(t,i)})),onSelectMicrophone:t=>yE(void 0,void 0,void 0,(function*(){yield e.setMicrophone(t)})),onSelectSpeaker:t=>yE(void 0,void 0,void 0,(function*(){yield e.setSpeaker(t)})),onStartCall:(t,i)=>{const n=t.map((e=>_(e)));return e.startCall(n,i)},onStartScreenShare:()=>yE(void 0,void 0,void 0,(function*(){yield e.startScreenShare()})),onStopScreenShare:()=>yE(void 0,void 0,void 0,(function*(){yield e.stopScreenShare()})),onToggleCamera:t=>yE(void 0,void 0,void 0,(function*(){jt(e.getState())?yield e.stopCamera():yield e.startCamera(t)})),onToggleMicrophone:()=>yE(void 0,void 0,void 0,(function*(){var t;return(null===(t=e.getState().call)||void 0===t?void 0:t.isMuted)?yield e.unmute():yield e.mute()})),onToggleScreenShare:()=>yE(void 0,void 0,void 0,(function*(){var t;return(null===(t=e.getState().call)||void 0===t?void 0:t.isScreenSharingOn)?yield e.stopScreenShare():yield e.startScreenShare()})),onStartLocalVideo:()=>yE(void 0,void 0,void 0,(function*(){if(e.getState().call)return e.startCamera()})),onDisposeLocalStreamView:()=>yE(void 0,void 0,void 0,(function*(){return e.disposeLocalVideoStreamView()})),onDisposeRemoteStreamView:t=>yE(void 0,void 0,void 0,(function*(){return e.disposeStreamView(t)})),onDisposeRemoteScreenShareStreamView:t=>yE(void 0,void 0,void 0,(function*(){return e.disposeScreenShareStreamView(t)})),onDisposeRemoteVideoStreamView:t=>yE(void 0,void 0,void 0,(function*(){return e.disposeRemoteVideoStreamView(t)})),askDevicePermission:t=>yE(void 0,void 0,void 0,(function*(){return e.askDevicePermission(t)})),onRemoveVideoBackgroundEffects:()=>yE(void 0,void 0,void 0,(function*(){return yield e.stopVideoBackgroundEffects()})),onBlurVideoBackground:t=>yE(void 0,void 0,void 0,(function*(){const i=Object.assign({effectName:"blur"},t);return yield e.startVideoBackgroundEffect(i)})),onReplaceVideoBackground:t=>yE(void 0,void 0,void 0,(function*(){const i=Object.assign({effectName:"replacement"},t);return yield e.startVideoBackgroundEffect(i)})),onStartCaptions:t=>yE(void 0,void 0,void 0,(function*(){yield e.startCaptions(t)})),onStopCaptions:()=>yE(void 0,void 0,void 0,(function*(){yield e.stopCaptions()})),onSetSpokenLanguage:t=>yE(void 0,void 0,void 0,(function*(){yield e.setSpokenLanguage(t)})),onSetCaptionLanguage:t=>yE(void 0,void 0,void 0,(function*(){yield e.setCaptionLanguage(t)})),onSubmitSurvey:t=>yE(void 0,void 0,void 0,(function*(){return yield e.submitSurvey(t)})),onStartSpotlight:t=>yE(void 0,void 0,void 0,(function*(){yield e.startSpotlight(t)})),onStopSpotlight:t=>yE(void 0,void 0,void 0,(function*(){yield e.stopSpotlight(t)})),onStopAllSpotlight:()=>yE(void 0,void 0,void 0,(function*(){yield e.stopAllSpotlight()})),onStartLocalSpotlight:(null==t?void 0:t.spotlightParticipant.isPresent)?()=>yE(void 0,void 0,void 0,(function*(){yield e.startSpotlight()})):void 0,onStopLocalSpotlight:()=>yE(void 0,void 0,void 0,(function*(){yield e.stopSpotlight()})),onStartRemoteSpotlight:(null==t?void 0:t.spotlightParticipant.isPresent)?t=>yE(void 0,void 0,void 0,(function*(){yield e.startSpotlight(t)})):void 0,onStopRemoteSpotlight:(null==t?void 0:t.removeParticipantsSpotlight.isPresent)?t=>yE(void 0,void 0,void 0,(function*(){yield e.stopSpotlight(t)})):void 0}))),EE=e=>e.deviceManager,TE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.role},bE=(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.capabilitiesFeature)||void 0===n?void 0:n.capabilities},IE=(e,t)=>{var i,n;return null===(n=null===(i=e.calls[t.callId])||void 0===i?void 0:i.raiseHand)||void 0===n?void 0:n.localParticipantRaisedHand},wE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.spotlight},RE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.localParticipantReaction},AE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.isScreenSharingOn},PE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.isMuted},ME=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.localVideoStreams},kE=e=>{var t;return null===(t=e.callAgent)||void 0===t?void 0:t.displayName},DE=e=>_(e.userId),OE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.state},NE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.isCaptionsFeatureActive},LE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.currentCaptionLanguage},xE=(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.currentSpokenLanguage};var FE="NOT_FOUND",UE=function(e,t){return e===t};function BE(e,t){var i,n,r="object"==typeof t?t:{equalityCheck:t},a=r.equalityCheck,s=void 0===a?UE:a,o=r.maxSize,l=void 0===o?1:o,c=r.resultEqualityCheck,d=function(e){return function(t,i){if(null===t||null===i||t.length!==i.length)return!1;for(var n=t.length,r=0;r<n;r++)if(!e(t[r],i[r]))return!1;return!0}}(s),u=1===l?(i=d,{get:function(e){return n&&i(n.key,e)?n.value:FE},put:function(e,t){n={key:e,value:t}},getEntries:function(){return n?[n]:[]},clear:function(){n=void 0}}):function(e,t){var i=[];function n(e){var n=i.findIndex((function(i){return t(e,i.key)}));if(n>-1){var r=i[n];return n>0&&(i.splice(n,1),i.unshift(r)),r.value}return FE}return{get:n,put:function(t,r){n(t)===FE&&(i.unshift({key:t,value:r}),i.length>e&&i.pop())},getEntries:function(){return i},clear:function(){i=[]}}}(l,d);function h(){var t=u.get(arguments);if(t===FE){if(t=e.apply(null,arguments),c){var i=u.getEntries().find((function(e){return c(e.value,t)}));i&&(t=i.value)}u.put(arguments,t)}return t}return h.clearCache=function(){return u.clear()},h}function VE(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var a,s=0,o={memoizeOptions:void 0},l=n.pop();if("object"==typeof l&&(o=l,l=n.pop()),"function"!=typeof l)throw new Error("createSelector expects an output function after the inputs, but received: ["+typeof l+"]");var c=o.memoizeOptions,d=void 0===c?i:c,u=Array.isArray(d)?d:[d],h=function(e){var t=Array.isArray(e[0])?e[0]:e;if(!t.every((function(e){return"function"==typeof e}))){var i=t.map((function(e){return"function"==typeof e?"function "+(e.name||"unnamed")+"()":typeof e})).join(", ");throw new Error("createSelector expects all input-selectors to be functions, but received the following types: ["+i+"]")}return t}(n),p=e.apply(void 0,[function(){return s++,l.apply(null,arguments)}].concat(u)),g=e((function(){for(var e=[],t=h.length,i=0;i<t;i++)e.push(h[i].apply(null,arguments));return a=p.apply(null,e)}));return Object.assign(g,{resultFunc:l,memoizedResultFunc:p,dependencies:h,lastResult:function(){return a},recomputations:function(){return s},resetRecomputations:function(){return s=0}}),g}}var HE=VE(BE);const $E=HE([NE,LE,xE],((e,t,i)=>({checked:null!=e&&e,currentCaptionLanguage:null!=t?t:"",currentSpokenLanguage:null!=i?i:"en-us"}))),GE=HE([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.supportedCaptionLanguages},LE,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.supportedSpokenLanguages},xE,NE],((e,t,i,n,r)=>({supportedCaptionLanguages:null!=e?e:[],currentCaptionLanguage:null!=t?t:"en",supportedSpokenLanguages:null!=i?i:["en-us"],currentSpokenLanguage:null!=n?n:"en-us",isCaptionsFeatureActive:null!=r&&r}))),jE=HE([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.captions},NE,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.captionsFeature.startCaptionsInProgress}],((e,t,i)=>{const n=null==e?void 0:e.map(((e,t)=>{var i,n,r;const a=zE(e);return{id:(null!==(i=e.speaker.displayName)&&void 0!==i?i:"Unnamed Participant")+t,displayName:null!==(n=e.speaker.displayName)&&void 0!==n?n:"Unnamed Participant",captionText:null!==(r=e.captionText)&&void 0!==r?r:"",userId:a}}));return{captions:null!=n?n:[],isCaptionsOn:null!=t&&t,startCaptionsInProgress:null!=i&&i}})),zE=e=>e.speaker.identifier?_(e.speaker.identifier):"",WE=t=>{const i=gE(GE),n=CE(),r=ip().strings.call,a={captionsSettingsModalTitle:r.captionsSettingsModalTitle,captionsSettingsSpokenLanguageDropdownLabel:r.captionsSettingsSpokenLanguageDropdownLabel,captionsSettingsCaptionLanguageDropdownLabel:r.captionsSettingsCaptionLanguageDropdownLabel,captionsSettingsSpokenLanguageDropdownInfoText:r.captionsSettingsSpokenLanguageDropdownInfoText,captionsSettingsCaptionLanguageDropdownInfoText:r.captionsSettingsCaptionLanguageDropdownInfoText,captionsSettingsConfirmButtonLabel:r.captionsSettingsConfirmButtonLabel,captionsSettingsCancelButtonLabel:r.captionsSettingsCancelButtonLabel,captionsSettingsModalAriaLabel:r.captionsSettingsModalAriaLabel,captionsSettingsCloseModalButtonAriaLabel:r.captionsSettingsCloseModalButtonAriaLabel},s=r.spokenLanguageStrings,o=r.captionLanguageStrings;return e.createElement(pE,Object.assign({},i,n,{strings:a,spokenLanguageStrings:s,captionLanguageStrings:o,showModal:t.showCaptionsSettingsModal,onDismissCaptionsSettings:t.onDismissCaptionsSettings,changeCaptionLanguage:t.changeCaptionLanguage}))},qE={horizontal:{flexFlow:"row nowrap"},vertical:{flexFlow:"column nowrap",width:"fit-content",maxWidth:"8rem"},dockedTop:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:0,left:0,width:"100%",minWidth:"fit-content"},dockedBottom:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",bottom:0,left:0,width:"100%",minWidth:"fit-content"},dockedLeft:{justifyContent:"center",overflow:"hidden",position:"absolute",top:0,left:0,height:"100%"},dockedRight:{justifyContent:"center",overflow:"hidden",position:"absolute",top:0,right:0,height:"100%"},floatingTop:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"1rem",left:"50%",transform:"translateX(-50%)",minWidth:"fit-content",zIndex:10},floatingBottom:{flexFlow:"row nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",bottom:"1rem",left:"50%",transform:"translateX(-50%)",minWidth:"fit-content",zIndex:10},floatingLeft:{flexFlow:"column nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"50%",left:"1rem",transform:"translateY(-50%)",zIndex:10},floatingRight:{flexFlow:"column nowrap",justifyContent:"center",overflow:"hidden",position:"absolute",top:"50%",right:"1rem",transform:"translateY(-50%)",zIndex:10}},KE={root:{background:"none",border:"none",borderRadius:0,minHeight:"3.5rem",minWidth:"3.5rem",width:"100%",maxWidth:"8rem",svg:{verticalAlign:"text-top"}},splitButtonMenuButton:{border:"none"},flexContainer:{flexFlow:"column",display:"contents"},label:{fontSize:"0.625rem",fontWeight:"400",lineHeight:"1rem",cursor:"pointer",display:"block",margin:"0rem 0.25rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},JE={title:{background:"initial",paddingLeft:".5rem",fontWeight:600,fontSize:".75rem"}},YE={icon:{lineHeight:0},checkmarkIcon:{lineHeight:0}},QE=e=>{const t=ZE(e.palette.black),i=ZE(e.palette.white);return!Number.isNaN(t)&&!Number.isNaN(i)&&t>i},ZE=e=>/^#[0-9A-Fa-f]{6}$/i.test(e)?(parseInt(e.substring(1,3),16)+parseInt(e.substring(3,5),16)+parseInt(e.substring(5,7),16))/3:NaN,XE={root:{display:"inline-block"}},eT=t=>{const i=xh(),n={gapSpace:4,styles:{root:{padding:0},calloutMain:{padding:"0.5rem"}},backgroundColor:QE(i)?i.palette.neutralLighter:""};return e.createElement(fv,Object.assign({},t,{"data-ui-id":t.id,calloutProps:Object.assign(Object.assign({},n),t.calloutProps),styles:Xa(XE,t.styles)}),t.children)},tT=e=>(null==e?void 0:e.checked)?(null==e?void 0:e.onRenderOnIcon)?null==e?void 0:e.onRenderOnIcon():null:(null==e?void 0:e.onRenderOffIcon)?null==e?void 0:e.onRenderOffIcon():null,iT=t=>{var i,n,r,a,s,o,l,c,d,u,h,p,g,m,f,v,S;const y=Qa(KE,null!==(i=t.styles)&&void 0!==i?i:{}),C=null!==(a=null!==(n=null==t?void 0:t.text)&&void 0!==n?n:null===(r=null==t?void 0:t.strings)||void 0===r?void 0:r.label)&&void 0!==a?a:(null==t?void 0:t.checked)?null===(s=null==t?void 0:t.strings)||void 0===s?void 0:s.onLabel:null===(o=null==t?void 0:t.strings)||void 0===o?void 0:o.offLabel,_=null!==(c=null===(l=null==t?void 0:t.strings)||void 0===l?void 0:l.tooltipContent)&&void 0!==c?c:(null==t?void 0:t.disabled)?null===(d=null==t?void 0:t.strings)||void 0===d?void 0:d.tooltipDisabledContent:(null==t?void 0:t.checked)?null===(u=null==t?void 0:t.strings)||void 0===u?void 0:u.tooltipOnContent:null===(h=null==t?void 0:t.strings)||void 0===h?void 0:h.tooltipOffContent,E=(null!==(p=t.tooltipId)&&void 0!==p?p:t.labelKey)?t.labelKey+"-tooltip":void 0;return e.createElement(eT,{hidden:t.disableTooltip,content:_,id:E},e.createElement(yy,Object.assign({},t,{styles:y,onRenderText:t.showLabel&&t.onRenderText?t.onRenderText:void 0,onRenderIcon:null!==(g=t.onRenderIcon)&&void 0!==g?g:tT,ariaLabel:null!==(v=null!==(f=null!==(m=t.splitButtonAriaLabel)&&void 0!==m?m:t.ariaLabel)&&void 0!==f?f:_)&&void 0!==v?v:C,allowDisabledFocus:null===(S=t.allowDisabledFocus)||void 0===S||S,menuTriggerKeyCode:ao.down,text:void 0}),t.showLabel?C:e.createElement(e.Fragment,null)))},nT=t=>{const{iconName:i,disabled:n}=t,r=Qh();return e.createElement(al,{iconName:i,className:cn({svg:{fill:n?r.palette.neutralTertiary:r.palette.neutralPrimaryAlt,"@media (forced-colors: active) and (prefers-color-scheme: dark)":{fill:n?r.palette.neutralPrimaryAlt:r.palette.neutralTertiary}}})})},rT={root:{border:"0.125rem",borderRadius:2,height:"2.1875rem",width:"6.5625rem"},flexContainer:{flexFlow:"row"}},aT={root:{border:"0",borderRadius:"0.5rem"},flexContainer:{flexFlow:"row"}},sT={root:{height:"3rem",lineHeight:"3rem",maxHeight:"unset",overflow:"hidden"},linkContent:{height:"3rem",lineHeight:"3rem",maxHeight:"unset"},icon:{maxHeight:"unset",textAlign:"center"},checkmarkIcon:{lineHeight:"2rem"}},oT={menuStyles:{menuItemStyles:sT,participantListStyles:{participantItemStyles:{root:{height:"3rem"},participantSubMenuItemsStyles:sT}}}},lT={menuStyles:{menuItemStyles:sT}},cT={label:{minWidth:"1.25rem"}},dT=(...e)=>{let t=cT;return e.forEach((e=>{t=Qa(t,e)})),t},uT=()=>e.createElement(Ug,{key:"chatOnIconKey",primaryFill:"currentColor"}),hT=t=>e.createElement(iT,Object.assign({},t,{labelKey:"optionsButtonLabelKey",showLabel:t.showLabel,onRenderOnIcon:uT,onRenderOffIcon:uT,onClick:t.onClick,"data-ui-id":t["data-ui-id"]}));const pT=t=>{const i=ip(),n=gE($E),r=CE(),a=(0,e.useMemo)((()=>({label:i.strings.call.captionsBannerMoreButtonCallingLabel,tooltipOffContent:i.strings.call.captionsBannerMoreButtonTooltip})),[i]),s=[],o=(0,e.useCallback)((()=>{return e=void 0,t=void 0,a=function*(){yield r.onStartCaptions({spokenLanguage:n.currentSpokenLanguage})},new((i=void 0)||(i=Promise))((function(n,r){function s(e){try{l(a.next(e))}catch(e){r(e)}}function o(e){try{l(a.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((a=a.apply(e,t||[])).next())}));var e,t,i,a}),[r,n.currentSpokenLanguage]);return s.push({key:"ToggleCaptionsKey",text:n.checked?i.strings.call.startCaptionsButtonTooltipOnContent:i.strings.call.startCaptionsButtonTooltipOffContent,onClick:()=>{n.checked?r.onStopCaptions():""!==n.currentSpokenLanguage?o():t.onCaptionsSettingsClick&&t.onCaptionsSettingsClick()},iconProps:{iconName:n.checked?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:sT}}),t.onCaptionsSettingsClick&&s.push({key:"openCaptionsSettingsKey",id:"common-call-composite-captions-settings-button",text:i.strings.call.captionsSettingsLabel,onClick:t.onCaptionsSettingsClick,iconProps:{iconName:"CaptionsSettingsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:!n.checked}),e.createElement(hT,Object.assign({},t,{"data-ui-id":"captions-banner-more-button",strings:a,menuIconProps:{hidden:!0},menuProps:{items:s,calloutProps:{preventDismissOnEvent:nf}}}))};const gT=t=>{var i,n,r,a,s,o,l,c;const{userId:d,dataProvider:u,text:h,imageUrl:p,imageInitials:g,initialsColor:m,initialsTextColor:f,showOverflowTooltip:v}=t,[S,y]=(0,e.useState)();(0,e.useEffect)((()=>{var e,t,i,n;e=void 0,t=void 0,n=function*(){if(u&&d){const e=yield u(d);mT(S,e)&&y(e)}},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))}),[S,u,d]);let C="";return t.allowActiveBorder&&(C=cn({border:"solid 2px",borderColor:"transparent",borderRadius:"50%",padding:"2px",boxSizing:"content-box",margin:"-4px"}),cn(C,t.styles)),e.createElement(Jv,Object.assign({},t,{className:C,text:null!==(i=null==S?void 0:S.text)&&void 0!==i?i:h,imageUrl:null!==(n=null==S?void 0:S.imageUrl)&&void 0!==n?n:p,imageInitials:null!==(r=null==S?void 0:S.imageInitials)&&void 0!==r?r:g,initialsColor:null!==(a=null==S?void 0:S.initialsColor)&&void 0!==a?a:m,initialsTextColor:null!==(o=null!==(s=null==S?void 0:S.initialsTextColor)&&void 0!==s?s:f)&&void 0!==o?o:"white",showOverflowTooltip:null!=v&&v,showUnknownPersonaCoin:null!==(c=null!==(l=null==S?void 0:S.showUnknownPersonaCoin)&&void 0!==l?l:t.showUnknownPersonaCoin)&&void 0!==c&&c}))},mT=(e,t)=>(null==e?void 0:e.text)!==(null==t?void 0:t.text)||(null==e?void 0:e.imageUrl)!==(null==t?void 0:t.imageUrl)||(null==e?void 0:e.initialsColor)!==(null==t?void 0:t.initialsColor)||(null==e?void 0:e.imageInitials)!==(null==t?void 0:t.imageInitials)||(null==e?void 0:e.initialsTextColor)!==(null==t?void 0:t.initialsTextColor),fT=t=>{const i=gE(jE),n=CE(),[r,a]=(0,e.useState)(!1),s=cn({position:"relative"}),o=cn({position:"absolute",right:0,top:0}),l={captionsBannerSpinnerText:ip().strings.call.captionsBannerSpinnerText},c=(0,e.useCallback)(((i,n)=>e.createElement(gT,Object.assign({userId:i},n,{dataProvider:t.onFetchAvatarPersonaData}))),[t.onFetchAvatarPersonaData]),{innerWidth:d}=window,[u,h]=(0,e.useState)(d);(0,e.useEffect)((()=>{function e(){h(window.innerWidth)}return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)}),[]);const p=u>620?"35rem":"80%";return e.createElement(e.Fragment,null,r&&e.createElement(WE,{showCaptionsSettingsModal:r,onDismissCaptionsSettings:()=>{a(!1)},changeCaptionLanguage:t.useTeamsCaptions}),e.createElement("div",{className:s},e.createElement(Gs,{horizontalAlign:"center"},e.createElement(Gs.Item,{style:{width:t.isMobile?"90%":p}},e.createElement(JC,Object.assign({},i,n,{onRenderAvatar:c,formFactor:t.isMobile?"compact":"default",strings:l})))),!t.isMobile&&i.isCaptionsOn&&e.createElement("div",{className:o},e.createElement(pT,{onCaptionsSettingsClick:()=>{a(!0)}}))))},vT={position:"relative",width:"100%",height:"100%"},ST=(e,t,i,n=!0,r=!0)=>{var a,s;const{microphones:o,speakers:l,cameras:c,selectedMicrophone:d,selectedSpeaker:u,selectedCamera:h,onSelectCamera:p,onSelectMicrophone:g,onSelectSpeaker:m}=e,f={items:[],styles:e.styles,calloutProps:{styles:{root:{maxWidth:"95%"}},preventDismissOnEvent:nf}},v=Ra(YE,null!==(s=null===(a=e.styles)||void 0===a?void 0:a.menuItemStyles)&&void 0!==s?s:{});if(c&&h&&p&&n&&(f.items.push({key:"cameras",itemType:sl.Section,sectionProps:{title:t.cameraMenuTitle,items:[{key:"sectionCamera",title:t.cameraMenuTooltip,subMenuProps:{calloutProps:{preventDismissOnEvent:nf},items:c.map((e=>({key:e.id,text:e.name,title:e.name,iconProps:{iconName:"ContextMenuCameraIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:v},canCheck:!0,isChecked:e.id===(null==h?void 0:h.id),onClick:()=>{e.id!==(null==h?void 0:h.id)&&p(e)}})))},text:h.name}]}}),i&&f.items.push(i)),o&&d&&g&&r){const e=l&&l.length>0,i=e?"sectionMicrophone":"sectionAudioDevice",n=e?t.microphoneMenuTooltip:t.audioDeviceMenuTooltip;f.items.push({key:"microphones",itemType:sl.Section,sectionProps:{title:t.microphoneMenuTitle,items:[{key:i,title:n,subMenuProps:{calloutProps:{preventDismissOnEvent:nf},items:o.map((e=>({key:e.id,text:e.name,title:e.name,itemProps:{styles:v},iconProps:{iconName:"ContextMenuMicIcon",styles:{root:{lineHeight:0}}},canCheck:!0,isChecked:e.id===(null==d?void 0:d.id),onClick:()=>{e.id!==(null==d?void 0:d.id)&&g(e)}})))},text:d.name}]}})}if(l&&u&&m&&f.items.push({key:"speakers",itemType:sl.Section,sectionProps:{title:t.speakerMenuTitle,items:[{key:"sectionSpeaker",subMenuProps:{calloutProps:{preventDismissOnEvent:nf},items:l.map((e=>({key:e.id,text:e.name,title:e.name,itemProps:{styles:v},iconProps:{iconName:"ContextMenuSpeakerIcon",styles:{root:{lineHeight:0}}},canCheck:!0,isChecked:e.id===(null==u?void 0:u.id),onClick:()=>{e.id!==(null==u?void 0:u.id)&&m(e)}})))},text:u.name}]}}),o&&d&&g&&r&&i&&f.items.push(i),0!==f.items.length)return f},yT=t=>{var i,n,r;const{onRenderIcon:a}=t,s=_h().strings.devicesButton,o=Object.assign(Object.assign({},s),t.strings),l=null!==(i=t.menuProps)&&void 0!==i?i:ST(Object.assign(Object.assign({},t),{styles:null===(n=t.styles)||void 0===n?void 0:n.menuStyles}),o);return e.createElement(iT,Object.assign({},t,{menuProps:l,menuIconProps:{hidden:!0},onRenderIcon:null!=a?a:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ControlButtonOptions"}),strings:o,labelKey:null!==(r=t.labelKey)&&void 0!==r?r:"devicesButtonLabel"}))},CT={position:"relative",height:"100%",width:"100%"},_T=t=>{const{styles:i,layout:n}=t,r=Qh(),a=(0,e.useMemo)((()=>cn(qE[null!=n?n:"horizontal"],{background:QE(r)&&(null==n?void 0:n.startsWith("floating"))?r.palette.neutralQuaternaryAlt:r.palette.white},(null==n?void 0:n.startsWith("floating"))?{boxShadow:r.effects.elevation16,borderRadius:r.effects.roundedCorner6}:{},!r.rtl||"floatingTop"!==n&&"floatingBottom"!==n?{}:{transform:"translateX(50%)"},null==i?void 0:i.root)),[n,null==i?void 0:i.root,r]);return e.createElement("div",{className:cn(CT)},e.createElement(Gs,{className:a},t.children))},ET=t=>{const{onToggleHold:i,strings:n}=t;return e.createElement(iT,Object.assign({},t,{strings:n,onClick:null!=i?i:t.onClick,onRenderOnIcon:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ResumeCall"}),onRenderOffIcon:()=>e.createElement(nT,{disabled:t.disabled,iconName:"HoldCallButton"})}))};var TT=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const bT={scalingMode:"Crop",isMirrored:!0},IT=t=>{var i,n,r,a,s,o,l;const{localVideoViewOptions:c,onToggleCamera:d,onSelectCamera:u}=t,[h,p]=(0,e.useState)(!1),g=_h().strings.cameraButton,m=Object.assign(Object.assign({},g),t.strings),[f,v]=(0,e.useState)(void 0),S=t.disabled||h;h&&m.tooltipVideoLoadingContent&&(m.tooltipDisabledContent=m.tooltipVideoLoadingContent);const y=t.checked,C=y?m.onSplitButtonAriaLabel:m.offSplitButtonAriaLabel,_=(0,e.useCallback)((e=>{v(e?m.cameraActionTurnedOnAnnouncement:m.cameraActionTurnedOffAnnouncement)}),[m.cameraActionTurnedOffAnnouncement,m.cameraActionTurnedOnAnnouncement]),E=(0,e.useCallback)((()=>TT(void 0,void 0,void 0,(function*(){if(d){p(!0);try{yield d(null!=c?c:bT),_(!y)}finally{p(!1)}}}))),[y,c,d,_]),T=(0,e.useCallback)((e=>TT(void 0,void 0,void 0,(function*(){if(u){p(!0);try{yield u(e)}finally{p(!1)}}}))),[u]),b=[];t.onClickVideoEffects&&b.push({key:"effects","data-ui-id":"camera-split-button-video-effects",text:m.videoEffectsMenuItemTitle,iconProps:{iconName:"ControlButtonVideoEffectsOption",styles:{root:{lineHeight:0}}},onClick:()=>{t.onClickVideoEffects&&t.onClickVideoEffects(!0)}}),b.push({key:"cameraPrimaryAction",text:t.checked?m.onSplitButtonPrimaryActionCamera:m.offSplitButtonPrimaryActionCamera,onClick:()=>{E()},iconProps:{iconName:t.checked?"SplitButtonPrimaryActionCameraOn":"SplitButtonPrimaryActionCameraOff",styles:{root:{lineHeight:0}}}});const I={key:"primaryAction",title:"toggle camera",itemType:sl.Section,sectionProps:{topDivider:!0,items:b}},w=(0,e.useMemo)((()=>Object.assign(Object.assign({},t.splitButtonMenuProps),{className:"camera-split-button"})),[t.splitButtonMenuProps]);return e.createElement(e.Fragment,null,e.createElement(zf,{announcementString:f,ariaLive:"polite"}),e.createElement(iT,Object.assign({},t,{disabled:S,onClick:d?E:t.onClick,onRenderOnIcon:null!==(i=t.onRenderOnIcon)&&void 0!==i?i:()=>e.createElement(nT,{disabled:S,iconName:"ControlButtonCameraOn"}),onRenderOffIcon:null!==(n=t.onRenderOffIcon)&&void 0!==n?n:()=>e.createElement(nT,{disabled:S,iconName:"ControlButtonCameraOff"}),strings:m,labelKey:null!==(r=t.labelKey)&&void 0!==r?r:"cameraButtonLabel",menuProps:null!==(a=t.menuProps)&&void 0!==a?a:t.enableDeviceSelectionMenu?ST(Object.assign(Object.assign({},t),{onSelectCamera:T,styles:null===(s=t.styles)||void 0===s?void 0:s.menuStyles}),m,I):void 0,menuIconProps:(null!==(o=t.menuIconProps)&&void 0!==o?o:!t.enableDeviceSelectionMenu)?{hidden:!0}:void 0,split:null!==(l=t.split)&&void 0!==l?l:t.enableDeviceSelectionMenu,"aria-roledescription":t.enableDeviceSelectionMenu?m.cameraButtonSplitRoleDescription:void 0,splitButtonAriaLabel:t.enableDeviceSelectionMenu?C:void 0,splitButtonMenuProps:w})))};const wT=t=>{var i,n,r,a,s,o,l,c,d,u,h,p;const{onToggleMicrophone:g}=t,m=_h().strings.microphoneButton,f=Object.assign(Object.assign({},m),t.strings),[v,S]=(0,e.useState)(void 0),y=null!==(i=t.split)&&void 0!==i?i:t.enableDeviceSelectionMenu,C=t.primaryDisabled||!(!y||(null===(n=t.microphones)||void 0===n?void 0:n.length))||void 0,_=t.disabled||y&&!(null===(r=t.microphones)||void 0===r?void 0:r.length)&&!(null===(a=t.speakers)||void 0===a?void 0:a.length)||!y&&t.microphones&&0===(null===(s=t.microphones)||void 0===s?void 0:s.length),E=t.checked,T=E?f.onSplitButtonAriaLabel:f.offSplitButtonAriaLabel,b=(0,e.useCallback)((e=>{S(e?f.microphoneActionTurnedOnAnnouncement:f.microphoneActionTurnedOffAnnouncement)}),[f.microphoneActionTurnedOffAnnouncement,f.microphoneActionTurnedOnAnnouncement]),I=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){if(g)try{yield g(),b(!E)}finally{}},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[E,g,b]),w={key:"primaryAction",title:"toggle mic",itemType:sl.Section,sectionProps:{topDivider:!0,items:[{key:"microphonePrimaryAction",text:t.checked?f.onSplitButtonMicrophonePrimaryAction:f.offSplitButtonMicrophonePrimaryAction,onClick:()=>{I()},iconProps:{iconName:t.checked?"SplitButtonPrimaryActionMicUnmuted":"SplitButtonPrimaryActionMicMuted",styles:{root:{lineHeight:0}}}}]}};return e.createElement(e.Fragment,null,e.createElement(zf,{announcementString:v,ariaLive:"polite"}),e.createElement(iT,Object.assign({},t,{onClick:t.onToggleMicrophone?I:t.onClick,onRenderOnIcon:null!==(o=t.onRenderOnIcon)&&void 0!==o?o:()=>e.createElement(nT,{disabled:_,iconName:"ControlButtonMicOn"}),onRenderOffIcon:null!==(l=t.onRenderOffIcon)&&void 0!==l?l:()=>e.createElement(nT,{disabled:_,iconName:"ControlButtonMicOff"}),strings:f,labelKey:null!==(c=t.labelKey)&&void 0!==c?c:"microphoneButtonLabel",menuProps:null!==(d=t.menuProps)&&void 0!==d?d:t.enableDeviceSelectionMenu?ST(Object.assign(Object.assign({},t),{styles:null===(u=t.styles)||void 0===u?void 0:u.menuStyles}),f,w):void 0,menuIconProps:(null!==(h=t.menuIconProps)&&void 0!==h?h:!t.enableDeviceSelectionMenu)?{hidden:!0}:void 0,split:null!==(p=t.split)&&void 0!==p?p:t.enableDeviceSelectionMenu,"aria-roledescription":t.enableDeviceSelectionMenu?f.microphoneButtonSplitRoleDescription:void 0,splitButtonAriaLabel:t.enableDeviceSelectionMenu?T:void 0,disabled:_,primaryDisabled:C})))},RT=t=>{var i,n,r,a;const s=_h().strings.screenShareButton,o=Object.assign(Object.assign({},s),t.strings),l=xh(),c=AT(l);return e.createElement(iT,Object.assign({},t,{className:cn(c,t.styles),onClick:null!==(i=t.onToggleScreenShare)&&void 0!==i?i:t.onClick,onRenderOnIcon:null!==(n=t.onRenderOnIcon)&&void 0!==n?n:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ControlButtonScreenShareStop"}),onRenderOffIcon:null!==(r=t.onRenderOffIcon)&&void 0!==r?r:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ControlButtonScreenShareStart"}),strings:o,labelKey:null!==(a=t.labelKey)&&void 0!==a?a:"screenShareButtonLabel",disabled:t.disabled}))},AT=e=>({rootChecked:{background:e.palette.themePrimary,color:Or.white,":focus::after":{outlineColor:`${Or.white} !important`},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},rootCheckedHovered:{background:e.palette.themePrimary,color:Or.white,":focus::after":{outlineColor:`${Or.white} !important`},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},labelChecked:{color:Or.white}}),PT={width:"1.5rem"},MT="5rem",kT={maxWidth:MT,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",lineHeight:"normal",marginLeft:"0.5rem",marginRight:0},DT={display:"flex",alignItems:"center",height:"100%",paddingTop:"0.2rem"},OT=cn({display:"flex",lineHeight:0,alignItems:"center"}),NT={paddingRight:"0.5rem"},LT=t=>{const{userId:i,displayName:n,onRenderAvatar:r,menuItems:a,onRenderIcon:s,presence:o,styles:l,me:c,onClick:d,showParticipantOverflowTooltip:u}=t,[h,p]=(0,e.useState)(!1),[g,m]=(0,e.useState)(!1),[f,v]=(0,e.useState)(!0),S=(0,e.useRef)(null),y=Qh(),C=_h().strings.participantItem,_=Qv(),E=fu(),T=Object.assign(Object.assign({},C),t.strings),b=(null==n?void 0:n.trim())||"",I={text:c?b:(null==n?void 0:n.trim())||T.displayNamePlaceholder,size:ov.size32,presence:o,initialsTextColor:"white",showOverflowTooltip:u,showUnknownPersonaCoin:!(c||(null==n?void 0:n.trim())&&n!==T.displayNamePlaceholder)},w=r?r(null!=i?i:"",I):e.createElement(Jv,Object.assign({className:cn({lineHeight:"1.15rem"},null==l?void 0:l.avatar)},I)),R=(0,e.useMemo)((()=>cn(NT,{color:y.palette.neutralSecondary},null==l?void 0:l.me)),[y.palette.neutralSecondary,null==l?void 0:l.me]),A=(0,e.useMemo)((()=>cn({background:y.palette.neutralLighterAlt},null==l?void 0:l.menu)),[y.palette.neutralLighterAlt,null==l?void 0:l.menu]),P=(0,e.useMemo)((()=>cn(DT,{color:y.palette.neutralTertiary,marginLeft:"auto"},null==l?void 0:l.iconContainer)),[y.palette.neutralTertiary,null==l?void 0:l.iconContainer]),M=()=>{p(!1),m(!1),v(!0)},k=(0,e.useMemo)((()=>e.createElement(Gs,{horizontal:!0,horizontalAlign:"end",className:cn(PT),title:T.menuTitle,"data-ui-id":_.participantItemMenuButton},e.createElement(al,{iconName:h||g||!f?"ParticipantItemOptionsHovered":"ParticipantItemOptions",className:OT}))),[T.menuTitle,_.participantItemMenuButton,h,g,f]),D=xT(t,T);return e.createElement("div",{ref:S,role:"menuitem","data-is-focusable":!0,"data-ui-id":"participant-item",className:cn((O={clickable:!!a&&a.length>0},{paddingTop:"0.25rem",paddingBottom:"0.25rem",display:"flex",maxWidth:"100%",minWidth:"8rem",cursor:O.clickable?"pointer":"default",alignItems:"center"}),null==l?void 0:l.root),onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onFocus:()=>m(!0),onBlur:()=>m(!1),onClick:()=>{D||(p(!0),m(!1),v(!1),null==d||d(t)),f||M()},tabIndex:0},e.createElement(Gs,{horizontal:!0,className:cn({width:`calc(100% - ${!c&&D?MT:PT.width})`,alignItems:"center"}),id:E,"aria-labelledby":`${t.ariaLabelledBy} ${E}`},w,c&&e.createElement(Cf,{className:R},T.isMeText),e.createElement(Gs,{horizontal:!0,className:cn(P)},s&&s(t))),!c&&D?e.createElement(Cf,{"data-ui-id":"participant-item-state-string",className:cn(kT)},D):e.createElement("div",null,a&&a.length>0&&e.createElement(e.Fragment,null,k,e.createElement($u,{items:a,hidden:f,target:S,onItemClick:M,onDismiss:M,directionalHint:ll.bottomRightEdge,className:A,calloutProps:{preventDismissOnEvent:nf}}))));var O},xT=(e,t)=>"EarlyMedia"===e.participantState||"Ringing"===e.participantState?null==t?void 0:t.participantStateRinging:"Hold"===e.participantState?null==t?void 0:t.participantStateHold:void 0,FT=cn({height:"100%",padding:"0.125rem"}),UT={root:{paddingLeft:"1rem",paddingRight:"1rem",":focus-visible":{margin:"0.125rem"}}},BT=cn({display:"flex",lineHeight:0,alignItems:"center"}),VT=t=>{var i,n,r,a,s;const{excludeMe:o=!1,myUserId:l,participants:c,onRemoveParticipant:d,onRenderAvatar:u,onRenderParticipant:h,onFetchParticipantMenuItems:p,showParticipantOverflowTooltip:g,totalParticipantCount:m,strings:f,participantAriaLabelledBy:v}=t,S=Qh(),y=Qv(),C=_h().strings.participantItem,_=_h().strings.ParticipantList,E=(0,e.useMemo)((()=>h?c:((e,t,i)=>{if(!t||!i)return[...e];const n=e.map((e=>e.userId)).indexOf(i);if(-1===n)return[...e];const r=[...e];return r.splice(n,1),r})(c,o,l)),[c,o,l,h]);(e=>{const t=function(e){return"raisedHand"in e};e.sort(((e,i)=>{if(!t(e)||!t(i))return 0;const n=e,r=i;return n.raisedHand&&r.raisedHand?n.raisedHand.raisedHandOrderPosition-r.raisedHand.raisedHandOrderPosition:n.raisedHand?-1:r.raisedHand?1:0}))})(E);const T=(0,e.useCallback)((e=>{var i,n;let r=[];const a=e.isRemovable;return e.userId!==l&&d&&a&&r.push({key:"remove",text:C.removeButtonLabel,onClick:()=>d(e.userId),itemProps:{styles:null===(n=null===(i=t.styles)||void 0===i?void 0:i.participantItemStyles)||void 0===n?void 0:n.participantSubMenuItemsStyles},"data-ui-id":y.participantListRemoveParticipantButton}),p&&(r=p(e.userId,l,r)),r}),[y.participantListRemoveParticipantButton,l,p,d,null===(n=null===(i=t.styles)||void 0===i?void 0:i.participantItemStyles)||void 0===n?void 0:n.participantSubMenuItemsStyles,C.removeButtonLabel]),b=(0,e.useMemo)((()=>{var e;return Ra(UT,null===(e=t.styles)||void 0===e?void 0:e.participantItemStyles)}),[null===(r=t.styles)||void 0===r?void 0:r.participantItemStyles]),I=null!==(a=null==f?void 0:f.overflowParticipantCount)&&void 0!==a?a:null==_?void 0:_.overflowParticipantCount;return e.createElement(Gs,{"data-ui-id":y.participantList,className:cn(FT,null===(s=t.styles)||void 0===s?void 0:s.root),role:"menu"},E.map((i=>h?h(i):((t,i,n,r,a,s,o,l,c,d)=>{const u=t;let h;u&&(h=lv.none);const p=a&&a(t);let g=t.displayName;const m=d.callingPalette,f=(null==u?void 0:u.isScreenSharing)||(null==u?void 0:u.isMuted)||(null==u?void 0:u.raisedHand)?()=>{var t;return e.createElement(Gs,{horizontal:!0,tokens:{childrenGap:"0.5rem"}},u.raisedHand&&e.createElement(Gs,{horizontal:!0,tokens:{childrenGap:"0.2rem"},style:{alignItems:"center",padding:"0.1rem 0.2rem",backgroundColor:null==d?void 0:d.palette.neutralLighter,borderRadius:"0.3rem"}},u.raisedHand.raisedHandOrderPosition&&e.createElement(Gs.Item,null,e.createElement(Cf,null,null===(t=u.raisedHand)||void 0===t?void 0:t.raisedHandOrderPosition)),e.createElement(Gs.Item,null,e.createElement(Zv,null))),u.isScreenSharing&&e.createElement(al,{iconName:"ParticipantItemScreenShareStart",className:BT,ariaLabel:i.sharingIconLabel}),u.isMuted&&e.createElement(al,{iconName:"ParticipantItemMicOff",className:BT,ariaLabel:i.mutedIconLabel}),u.spotlight&&e.createElement(al,{iconName:"ParticipantItemSpotlighted",className:BT}))}:()=>null,v=(null==u?void 0:u.raisedHand)&&r?(e,t,i)=>r(e,Object.assign(Object.assign({},t),{styles:{root:{border:m.raiseHandGold}}}),i):r;return e.createElement(LT,{styles:s,key:t.userId,userId:t.userId,displayName:g,me:!!n&&t.userId===n,menuItems:p,presence:h,onRenderIcon:f,onRenderAvatar:v,onClick:()=>null==o?void 0:o(t),showParticipantOverflowTooltip:l,participantState:u.state,ariaLabelledBy:c})})(i,C,l,u,T,b,t.onParticipantClick,g,v,S))),I&&m&&m>E.length&&e.createElement(Cf,{style:{fontWeight:400,margin:"0.5rem"}},ev(I,{overflowCount:""+(m-E.length)})))},HT=cn({width:4}),$T=t=>{var i,n;const{styles:r,enableEndCallMenu:a,onHangUp:s}=t,o=_h().strings.endCallButton,l=Object.assign(Object.assign({},o),t.strings),c=Qh(),d=Qa(QE(c)?WT:qT,a?KT:{},null!=r?r:{}),u=(0,e.useCallback)((()=>e.createElement(e.Fragment,null,e.createElement(al,{iconName:"ControlButtonEndCall"}),a&&e.createElement("span",{className:HT}))),[a]),h={items:[{key:"endForSelf",text:o.leaveOption,title:o.leaveOption,onClick:()=>{s&&s(!1)}},{key:"endForEveryone",text:o.endCallOption,title:o.endCallOption,onClick:()=>{s&&s(!0)}}],styles:t.styles,calloutProps:{styles:{root:{maxWidth:"95%"}},preventDismissOnEvent:nf}};return e.createElement(e.Fragment,null,e.createElement(iT,Object.assign({},t,{menuProps:a?h:void 0,onClick:s?()=>s():t.onClick,styles:d,onRenderIcon:null!==(i=t.onRenderIcon)&&void 0!==i?i:u,strings:l,labelKey:null!==(n=t.labelKey)&&void 0!==n?n:"endCallButtonLabel"})))},GT=e=>{var t;return{regular:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRed,"@media (forced-colors: active)":{forcedColorAdjust:"auto",border:`1px ${null===(t=e.palette)||void 0===t?void 0:t.neutralQuaternaryAlt} solid`}," i":{color:e.callingPalette.iconWhite},":focus::after":{outlineColor:`${e.callingPalette.iconWhite} !important`}},pressed:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRedDarker,border:"none"," i":{color:e.callingPalette.iconWhite},"@media (forced-colors: active)":{forcedColorAdjust:"auto"}},hovered:{color:e.callingPalette.iconWhite,background:e.callingPalette.callRedDark,border:"none"," i":{color:e.callingPalette.iconWhite},"@media (forced-colors: active)":{forcedColorAdjust:"auto"}}}},jT=GT(Wh),zT=GT(zh),WT={root:jT.regular,rootHovered:jT.hovered,rootPressed:jT.pressed,label:{color:Wh.callingPalette.iconWhite},splitButtonMenuButton:Object.assign(Object.assign({},jT.regular),{borderTop:"none",borderRight:"none",borderBottom:"none","&:hover":jT.hovered}),splitButtonMenuButtonChecked:jT.hovered,splitButtonMenuButtonExpanded:jT.pressed},qT={root:zT.regular,rootHovered:zT.hovered,rootPressed:zT.pressed,splitButtonMenuButton:Object.assign(Object.assign({},zT.regular),{borderTop:"none",borderRight:"none",borderBottom:"none","&:hover":zT.hovered}),splitButtonMenuButtonChecked:zT.hovered,splitButtonMenuButtonExpanded:zT.pressed,splitButtonMenuFocused:zT.pressed,label:{color:zh.callingPalette.iconWhite}},KT={root:{padding:"0 0.75rem"}};var JT,YT=Ys(),QT="TextField",ZT=function(t){function i(i){var n=t.call(this,i)||this;n._textElement=e.createRef(),n._onFocus=function(e){n.props.onFocus&&n.props.onFocus(e),n.setState({isFocused:!0},(function(){n.props.validateOnFocusIn&&n._validate(n.value)}))},n._onBlur=function(e){n.props.onBlur&&n.props.onBlur(e),n.setState({isFocused:!1},(function(){n.props.validateOnFocusOut&&n._validate(n.value)}))},n._onRenderLabel=function(t){var i=t.label,r=t.required,a=n._classNames.subComponentStyles?n._classNames.subComponentStyles.label:void 0;return i?e.createElement(r_,{required:r,htmlFor:n._id,styles:a,disabled:t.disabled,id:n._labelId},t.label):null},n._onRenderDescription=function(t){return t.description?e.createElement("span",{className:n._classNames.description},t.description):null},n._onRevealButtonClick=function(e){n.setState((function(e){return{isRevealingPassword:!e.isRevealingPassword}}))},n._onInputChange=function(e){var t,i,r=e.target.value,a=XT(n.props,n.state)||"";void 0!==r&&r!==n._lastChangeValue&&r!==a?(n._lastChangeValue=r,null===(i=(t=n.props).onChange)||void 0===i||i.call(t,e,r),n._isControlled||n.setState({uncontrolledValue:r})):n._lastChangeValue=void 0},lo(n),n._async=new go(n),n._fallbackId=bo(QT),n._descriptionId=bo(QT+"Description"),n._labelId=bo(QT+"Label"),n._prefixId=bo(QT+"Prefix"),n._suffixId=bo(QT+"Suffix"),n._warnControlledUsage();var r=i.defaultValue,a=void 0===r?"":r;return"number"==typeof a&&(a=String(a)),n.state={uncontrolledValue:n._isControlled?void 0:a,isFocused:!1,errorMessage:""},n._delayedValidate=n._async.debounce(n._validate,n.props.deferredValidationTime),n._lastValidation=0,n}return bi(i,t),Object.defineProperty(i.prototype,"value",{get:function(){return XT(this.props,this.state)},enumerable:!1,configurable:!0}),i.prototype.componentDidMount=function(){this._adjustInputHeight(),this.props.validateOnLoad&&this._validate(this.value)},i.prototype.componentWillUnmount=function(){this._async.dispose()},i.prototype.getSnapshotBeforeUpdate=function(e,t){return{selection:[this.selectionStart,this.selectionEnd]}},i.prototype.componentDidUpdate=function(e,t,i){var n=this.props,r=(i||{}).selection,a=void 0===r?[null,null]:r,s=a[0],o=a[1];!!e.multiline!=!!n.multiline&&t.isFocused&&(this.focus(),null!==s&&null!==o&&s>=0&&o>=0&&this.setSelectionRange(s,o)),e.value!==n.value&&(this._lastChangeValue=void 0);var l=XT(e,t),c=this.value;l!==c&&(this._warnControlledUsage(e),this.state.errorMessage&&!n.errorMessage&&this.setState({errorMessage:""}),this._adjustInputHeight(),eb(n)&&this._delayedValidate(c))},i.prototype.render=function(){var t=this.props,i=t.borderless,n=t.className,r=t.disabled,a=t.invalid,s=t.iconProps,o=t.inputClassName,l=t.label,c=t.multiline,d=t.required,u=t.underlined,h=t.prefix,p=t.resizable,g=t.suffix,m=t.theme,f=t.styles,v=t.autoAdjustHeight,S=t.canRevealPassword,y=t.revealPasswordAriaLabel,C=t.type,_=t.onRenderPrefix,E=void 0===_?this._onRenderPrefix:_,T=t.onRenderSuffix,b=void 0===T?this._onRenderSuffix:T,I=t.onRenderLabel,w=void 0===I?this._onRenderLabel:I,R=t.onRenderDescription,A=void 0===R?this._onRenderDescription:R,P=this.state,M=P.isFocused,k=P.isRevealingPassword,D=this._errorMessage,O="boolean"==typeof a?a:!!D,N=!!S&&"password"===C&&function(){if("boolean"!=typeof JT){var e=Tn();if(null==e?void 0:e.navigator){var t=/Edg/.test(e.navigator.userAgent||"");JT=!(function(){var e,t=Tn();return!!(null===(e=null==t?void 0:t.navigator)||void 0===e?void 0:e.userAgent)&&t.navigator.userAgent.indexOf("rv:11.0")>-1}()||t)}else JT=!0}return JT}(),L=this._classNames=YT(f,{theme:m,className:n,disabled:r,focused:M,required:d,multiline:c,hasLabel:!!l,hasErrorMessage:O,borderless:i,resizable:p,hasIcon:!!s,underlined:u,inputClassName:o,autoAdjustHeight:v,hasRevealButton:N});return e.createElement("div",{ref:this.props.elementRef,className:L.root},e.createElement("div",{className:L.wrapper},w(this.props,this._onRenderLabel),e.createElement("div",{className:L.fieldGroup},(void 0!==h||this.props.onRenderPrefix)&&e.createElement("div",{className:L.prefix,id:this._prefixId},E(this.props,this._onRenderPrefix)),c?this._renderTextArea():this._renderInput(),s&&e.createElement(al,Ii({className:L.icon},s)),N&&e.createElement("button",{"aria-label":y,className:L.revealButton,onClick:this._onRevealButtonClick,"aria-pressed":!!k,type:"button"},e.createElement("span",{className:L.revealSpan},e.createElement(al,{className:L.revealIcon,iconName:k?"Hide":"RedEye"}))),(void 0!==g||this.props.onRenderSuffix)&&e.createElement("div",{className:L.suffix,id:this._suffixId},b(this.props,this._onRenderSuffix)))),this._isDescriptionAvailable&&e.createElement("span",{id:this._descriptionId},A(this.props,this._onRenderDescription),D&&e.createElement("div",{role:"alert"},e.createElement(Xs,null,this._renderErrorMessage()))))},i.prototype.focus=function(){this._textElement.current&&this._textElement.current.focus()},i.prototype.blur=function(){this._textElement.current&&this._textElement.current.blur()},i.prototype.select=function(){this._textElement.current&&this._textElement.current.select()},i.prototype.setSelectionStart=function(e){this._textElement.current&&(this._textElement.current.selectionStart=e)},i.prototype.setSelectionEnd=function(e){this._textElement.current&&(this._textElement.current.selectionEnd=e)},Object.defineProperty(i.prototype,"selectionStart",{get:function(){return this._textElement.current?this._textElement.current.selectionStart:-1},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"selectionEnd",{get:function(){return this._textElement.current?this._textElement.current.selectionEnd:-1},enumerable:!1,configurable:!0}),i.prototype.setSelectionRange=function(e,t){this._textElement.current&&this._textElement.current.setSelectionRange(e,t)},i.prototype._warnControlledUsage=function(e){this._id,this.props,null!==this.props.value||this._hasWarnedNullValue||(this._hasWarnedNullValue=!0,$a("Warning: 'value' prop on '".concat(QT,"' should not be null. Consider using an ")+"empty string to clear the component or undefined to indicate an uncontrolled component."))},Object.defineProperty(i.prototype,"_id",{get:function(){return this.props.id||this._fallbackId},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"_isControlled",{get:function(){return void 0!==(e=this.props)["value"]&&null!==e.value;var e},enumerable:!1,configurable:!0}),i.prototype._onRenderPrefix=function(t){var i=t.prefix;return e.createElement("span",{style:{paddingBottom:"1px"}},i)},i.prototype._onRenderSuffix=function(t){var i=t.suffix;return e.createElement("span",{style:{paddingBottom:"1px"}},i)},Object.defineProperty(i.prototype,"_errorMessage",{get:function(){var e=this.props.errorMessage;return(void 0===e?this.state.errorMessage:e)||""},enumerable:!1,configurable:!0}),i.prototype._renderErrorMessage=function(){var t=this._errorMessage;return t?"string"==typeof t?e.createElement("p",{className:this._classNames.errorMessage},e.createElement("span",{"data-automation-id":"error-message"},t)):e.createElement("div",{className:this._classNames.errorMessage,"data-automation-id":"error-message"},t):null},Object.defineProperty(i.prototype,"_isDescriptionAvailable",{get:function(){var e=this.props;return!!(e.onRenderDescription||e.description||this._errorMessage)},enumerable:!1,configurable:!0}),i.prototype._renderTextArea=function(){var t=this.props.invalid,i=void 0===t?!!this._errorMessage:t,n=Ds(this.props,ys,["defaultValue"]),r=this.props["aria-labelledby"]||(this.props.label?this._labelId:void 0);return e.createElement("textarea",Ii({id:this._id},n,{ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-labelledby":r,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":i,"aria-label":this.props.ariaLabel,readOnly:this.props.readOnly,onFocus:this._onFocus,onBlur:this._onBlur}))},i.prototype._renderInput=function(){var t=this.props,i=t.ariaLabel,n=t.invalid,r=void 0===n?!!this._errorMessage:n,a=t.onRenderPrefix,s=t.onRenderSuffix,o=t.prefix,l=t.suffix,c=t.type,d=void 0===c?"text":c,u=[];t.label&&u.push(this._labelId),(void 0!==o||a)&&u.push(this._prefixId),(void 0!==l||s)&&u.push(this._suffixId);var h=Ii(Ii({type:this.state.isRevealingPassword?"text":d,id:this._id},Ds(this.props,Ss,["defaultValue","type"])),{"aria-labelledby":this.props["aria-labelledby"]||(u.length>0?u.join(" "):void 0),ref:this._textElement,value:this.value||"",onInput:this._onInputChange,onChange:this._onInputChange,className:this._classNames.field,"aria-label":i,"aria-describedby":this._isDescriptionAvailable?this._descriptionId:this.props["aria-describedby"],"aria-invalid":r,onFocus:this._onFocus,onBlur:this._onBlur}),p=function(t){return e.createElement("input",Ii({},t))};return(this.props.onRenderInput||p)(h,p)},i.prototype._validate=function(e){var t=this;if(this._latestValidateValue!==e||!eb(this.props)){this._latestValidateValue=e;var i=this.props.onGetErrorMessage,n=i&&i(e||"");if(void 0!==n)if("string"!=typeof n&&"then"in n){var r=++this._lastValidation;n.then((function(i){r===t._lastValidation&&t.setState({errorMessage:i}),t._notifyAfterValidate(e,i)}))}else this.setState({errorMessage:n}),this._notifyAfterValidate(e,n);else this._notifyAfterValidate(e,"")}},i.prototype._notifyAfterValidate=function(e,t){e===this.value&&this.props.onNotifyValidationResult&&this.props.onNotifyValidationResult(t,e)},i.prototype._adjustInputHeight=function(){var e,t;if(this._textElement.current&&this.props.autoAdjustHeight&&this.props.multiline){var i=null===(t=null===(e=this.props.scrollContainerRef)||void 0===e?void 0:e.current)||void 0===t?void 0:t.scrollTop,n=this._textElement.current;n.style.height="",n.style.height=n.scrollHeight+"px",i&&(this.props.scrollContainerRef.current.scrollTop=i)}},i.defaultProps={resizable:!0,deferredValidationTime:200,validateOnLoad:!0},i}(e.Component);function XT(e,t){var i=e.value,n=void 0===i?t.uncontrolledValue:i;return"number"==typeof n?String(n):n}function eb(e){return!(e.validateOnFocusIn||e.validateOnFocusOut)}var tb={root:"ms-TextField",description:"ms-TextField-description",errorMessage:"ms-TextField-errorMessage",field:"ms-TextField-field",fieldGroup:"ms-TextField-fieldGroup",prefix:"ms-TextField-prefix",suffix:"ms-TextField-suffix",wrapper:"ms-TextField-wrapper",revealButton:"ms-TextField-reveal",multiline:"ms-TextField--multiline",borderless:"ms-TextField--borderless",underlined:"ms-TextField--underlined",unresizable:"ms-TextField--unresizable",required:"is-required",disabled:"is-disabled",active:"is-active"};function ib(e){var t=e.underlined,i=e.disabled,n=e.focused,r=e.theme,a=r.palette,s=r.fonts;return function(){var e;return{root:[t&&i&&{color:a.neutralTertiary},t&&{fontSize:s.medium.fontSize,marginRight:8,paddingLeft:12,paddingRight:0,lineHeight:"22px",height:32},t&&n&&{selectors:(e={},e[Nr]={height:31},e)}]}}}var nb=Ws(ZT,(function(e){var t,i,n,r,a,s,o,l,c,d,u,h,p=e.theme,g=e.className,m=e.disabled,f=e.focused,v=e.required,S=e.multiline,y=e.hasLabel,C=e.borderless,_=e.underlined,E=e.hasIcon,T=e.resizable,b=e.hasErrorMessage,I=e.inputClassName,w=e.autoAdjustHeight,R=e.hasRevealButton,A=p.semanticColors,P=p.effects,M=p.fonts,k=Kr(tb,p),D={background:A.disabledBackground,color:m?A.disabledText:A.inputPlaceholderText,display:"flex",alignItems:"center",padding:"0 10px",lineHeight:1,whiteSpace:"nowrap",flexShrink:0,selectors:(t={},t[Nr]={background:"Window",color:m?"GrayText":"WindowText"},t)},O=[{color:A.inputPlaceholderText,opacity:1,selectors:(i={},i[Nr]={color:"GrayText"},i)}],N={color:A.disabledText,selectors:(n={},n[Nr]={color:"GrayText"},n)};return{root:[k.root,M.medium,v&&k.required,m&&k.disabled,f&&k.active,S&&k.multiline,C&&k.borderless,_&&k.underlined,Ba,{position:"relative"},g],wrapper:[k.wrapper,_&&[{display:"flex",borderBottom:"1px solid ".concat(b?A.errorText:A.inputBorder),width:"100%"},m&&{borderBottomColor:A.disabledBackground,selectors:(r={},r[Nr]=Ii({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),r)},!m&&{selectors:{":hover":{borderBottomColor:b?A.errorText:A.inputBorderHovered,selectors:(a={},a[Nr]=Ii({borderBottomColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),a)}}},f&&[{position:"relative"},zr(b?A.errorText:A.inputFocusBorderAlt,0,"borderBottom")]]],fieldGroup:[k.fieldGroup,Ba,{border:"1px solid ".concat(A.inputBorder),borderRadius:P.roundedCorner2,background:A.inputBackground,cursor:"text",height:32,display:"flex",flexDirection:"row",alignItems:"stretch",position:"relative"},S&&{minHeight:"60px",height:"auto",display:"flex"},!f&&!m&&{selectors:{":hover":{borderColor:A.inputBorderHovered,selectors:(s={},s[Nr]=Ii({borderColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),s)}}},f&&!_&&zr(b?A.errorText:A.inputFocusBorderAlt,P.roundedCorner2),m&&{borderColor:A.disabledBackground,selectors:(o={},o[Nr]=Ii({borderColor:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),o),cursor:"default"},C&&{border:"none"},C&&f&&{border:"none",selectors:{":after":{border:"none"}}},_&&{flex:"1 1 0px",border:"none",textAlign:"left"},_&&m&&{backgroundColor:"transparent"},b&&!_&&{borderColor:A.errorText,selectors:{"&:hover":{borderColor:A.errorText}}},!y&&v&&{selectors:(l={":before":{content:"'*'",color:A.errorText,position:"absolute",top:-5,right:-10}},l[Nr]={selectors:{":before":{color:"WindowText",right:-14}}},l)}],field:[M.medium,k.field,Ba,{borderRadius:0,border:"none",background:"none",backgroundColor:"transparent",color:A.inputText,padding:"0 8px",width:"100%",minWidth:0,textOverflow:"ellipsis",outline:0,selectors:(c={"&:active, &:focus, &:hover":{outline:0},"::-ms-clear":{display:"none"}},c[Nr]={background:"Window",color:m?"GrayText":"WindowText"},c)},Ha(O),S&&!T&&[k.unresizable,{resize:"none"}],S&&{minHeight:"inherit",lineHeight:17,flexGrow:1,paddingTop:6,paddingBottom:6,overflow:"auto",width:"100%"},S&&w&&{overflow:"hidden"},E&&!R&&{paddingRight:24},S&&E&&{paddingRight:40},m&&[{backgroundColor:A.disabledBackground,color:A.disabledText,borderColor:A.disabledBackground},Ha(N)],_&&{textAlign:"left"},f&&!C&&{selectors:(d={},d[Nr]={paddingLeft:11,paddingRight:11},d)},f&&S&&!C&&{selectors:(u={},u[Nr]={paddingTop:4},u)},I],icon:[S&&{paddingRight:24,alignItems:"flex-end"},{pointerEvents:"none",position:"absolute",bottom:6,right:8,top:"auto",fontSize:kr.medium,lineHeight:18},m&&{color:A.disabledText}],description:[k.description,{color:A.bodySubtext,fontSize:M.xSmall.fontSize}],errorMessage:[k.errorMessage,Dr.slideDownIn20,M.small,{color:A.errorText,margin:0,paddingTop:5,display:"flex",alignItems:"center"}],prefix:[k.prefix,D],suffix:[k.suffix,D],revealButton:[k.revealButton,"ms-Button","ms-Button--icon",jr(p,{inset:1}),{height:30,width:32,border:"none",padding:"0px 4px",backgroundColor:"transparent",color:A.link,selectors:{":hover":{outline:0,color:A.primaryButtonBackgroundHovered,backgroundColor:A.buttonBackgroundHovered,selectors:(h={},h[Nr]={borderColor:"Highlight",color:"Highlight"},h)},":focus":{outline:0}}},E&&{marginRight:28}],revealSpan:{display:"flex",height:"100%",alignItems:"center"},revealIcon:{margin:"0px 4px",pointerEvents:"none",bottom:6,right:8,top:"auto",fontSize:kr.medium,lineHeight:18},subComponentStyles:{label:ib(e)}}}),void 0,{scope:"TextField"});const rb=e=>({maxWidth:"16rem",textAlign:"center",background:`${e.palette.white}`,borderRadius:"0.75rem",margin:"auto"}),ab=e=>({fontSize:"1.25rem",fontWeight:e.fonts.medium.fontWeight,color:`${e.palette.themePrimary}`}),sb=(e,t)=>({field:{padding:0,textAlign:"center",fontSize:`${bm(18)}`,fontWeight:400,width:t?"10rem":"12rem",height:"3rem",borderRadius:"0.5rem",position:"relative",overflowX:"hidden",textOverflow:"clip"},root:{backgroundColor:`${e.palette.neutralLighter}`,marginBottom:"0.625rem",height:"3rem",borderRadius:"0.5rem"},fieldGroup:{border:"none",borderRadius:"0.5rem",width:"12rem",height:"3rem",backgroundColor:`${e.palette.neutralLighter}`,":after":{borderRadius:"0.5rem"}},errorMessage:{color:e.semanticColors.errorText},suffix:{padding:0,position:"absolute",right:"0.25rem",top:"0.55rem",transform:"scale(1.15)",background:"unset"}}),ob=e=>({fontSize:"0.625rem",color:`${e.palette.neutralSecondary}`,fontWeight:400,margin:"0.125rem",minHeight:"0.75rem"}),lb=e=>({root:{color:`${e.palette.black}`,padding:0,background:"transparent"},icon:{height:"auto",background:"transparent","> span":{display:"flex"}}}),cb=e=>{if(!e)return e;let t="";"1"===e[0]?(t="1 ",e=e.slice(1,e.length)):"+"===e[0]&&(t=e.slice(0,2)+" ",e=e.slice(2,e.length));const i=e.length;return i<4||i>10?t.replace(" ","")+e:i<7?`${t}(${e.slice(0,3)}) ${e.slice(3)}`:`${t}(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6,e.length)}`};class db{constructor(e,t,i){this.isPlaying=!1,this.play=()=>{if(this.isPlaying)return;const e=this.context.createGain();e.gain.value=.1,e.connect(this.context.destination),this.oscillatorNode1=this.context.createOscillator(),this.oscillatorNode1.frequency.value=this.frequency1,this.oscillatorNode1.connect(e),this.oscillatorNode2=this.context.createOscillator(),this.oscillatorNode2.frequency.value=this.frequency2,this.oscillatorNode2.connect(e),this.oscillatorNode1.start(),this.oscillatorNode2.start(),this.isPlaying=!0},this.stop=()=>{this.oscillatorNode1&&this.oscillatorNode2&&(this.oscillatorNode1.stop(),this.oscillatorNode2.stop(),this.oscillatorNode1.disconnect(),this.oscillatorNode2.disconnect(),this.isPlaying=!1)},this.context=e,this.frequency1=t,this.frequency2=i}}const ub={1:{f1:697,f2:1209},2:{f1:697,f2:1336},3:{f1:697,f2:1477},4:{f1:770,f2:1209},5:{f1:770,f2:1336},6:{f1:770,f2:1477},7:{f1:852,f2:1209},8:{f1:852,f2:1336},9:{f1:852,f2:1477},"*":{f1:941,f2:1209},0:{f1:941,f2:1336},"#":{f1:941,f2:1477}};var hb=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const pb=[[{digit:"1"},{digit:"2",letter:"ABC"},{digit:"3",letter:"DEF"}],[{digit:"4",letter:"GHI"},{digit:"5",letter:"JKL"},{digit:"6",letter:"MNO"}],[{digit:"7",letter:"PQRS"},{digit:"8",letter:"TUV"},{digit:"9",letter:"WXYZ"}],[{digit:"*"},{digit:"0",letter:"+"},{digit:"#"}]],gb=["Num1","Num2","Num3","Num4","Num5","Num6","Num7","Num8","Num9","Star","Num0","Pound"],mb=t=>{var i,n,r,a;const s=xh(),{digit:o,index:l,onClick:c,onLongPress:d,longPressTrigger:u,dtmfToneAudioContext:h,disableDtmfPlayback:p}=t,[g,m]=(0,e.useState)(!1),f=(0,e.useRef)(new db(h,ub[o].f1,ub[o].f2)),v=gS(e.useMemo((()=>({onClick:()=>hb(void 0,void 0,void 0,(function*(){c(o,l)})),onLongPress:()=>hb(void 0,void 0,void 0,(function*(){d(o,l)})),touchEventsOnly:"touch"===u})),[o,l,u,c,d]));return e.createElement(yy,Object.assign({"data-test-id":`dialpad-button-${t.index}`,styles:Qa({root:{background:"none",fontWeight:600,fontSize:`${bm(20)}`,border:"none",borderRadius:0,width:"3rem",height:"3rem",padding:`${bm(16)}, ${bm(5)}, ${bm(16)}, ${bm(5)}`,minWidth:0,minHeight:0}},null===(i=t.styles)||void 0===i?void 0:i.button)},v,{onKeyDown:e=>{if(("Enter"===e.key||" "===e.key)&&!g)return p||f.current.play(),v.onKeyDown(),void m(!0);"Tab"!==e.key&&"ArrowLeft"!==e.key&&"ArrowRight"!==e.key&&"ArrowUp"!==e.key&&"ArrowDown"!==e.key||f.current.stop(),v.onKeyDown()},onKeyUp:e=>{"Enter"!==e.key&&" "!==e.key||!g||(f.current.stop(),v.onKeyUp(),m(!1)),v.onKeyUp()},onMouseDown:()=>{p||f.current.play(),v.onMouseDown()},onMouseUp:()=>{f.current.stop(),v.onMouseUp()},onMouseLeave:()=>{f.current.stop()},onTouchStart:()=>{p||f.current.play(),v.onTouchStart()},onTouchEnd:()=>{f.current.stop(),v.onTouchEnd()}}),e.createElement(Gs,null,e.createElement(Cf,{className:cn(ab(s),null===(n=t.styles)||void 0===n?void 0:n.digit)},t.digit),e.createElement(Cf,{className:cn(ob(s),null===(r=t.styles)||void 0===r?void 0:r.letter)},null!==(a=t.letter)&&void 0!==a?a:" ")))},fb=t=>{var i,n;const r=xh(),{onSendDtmfTone:a,onClickDialpadButton:s,textFieldValue:o,onChange:l,showDeleteButton:c=!0,longPressTrigger:d="mouseAndTouch",disableDtmfPlayback:u,dialpadMode:h="dialer",dtmfAudioContext:p}=t,g=(0,e.useRef)(p||new AudioContext),[m,f]=(0,e.useState)(null!=o?o:""),v=(0,e.useRef)(m);(0,e.useEffect)((()=>{v.current!==m&&(null==l||l(m)),v.current=m}),[v,m,l]),(0,e.useEffect)((()=>{C(null!=o?o:"")}),[o]);const S=(e,t)=>{C(m+e),a&&a(gb[t]),s&&s(e,t)},y=(e,t)=>{C("0"===e&&10===t?m+"+":m+e),a&&a(gb[t]),s&&s(e,t)},C=e=>{const t=Sb(e);f(t)},_=()=>{const e=m.substring(0,m.length-1);C(e)};return e.createElement(Gs,{className:cn(rb(r),null===(i=t.styles)||void 0===i?void 0:i.root),"data-test-id":"dialpadContainer","data-ui-id":"dialpadContainer",horizontalAlign:"center"},"dialer"===h&&e.createElement(nb,{styles:Qa(sb(r,""!==m),null===(n=t.styles)||void 0===n?void 0:n.textField),value:o||cb(m),onChange:e=>{C(e.target.value)},onClick:e=>{e.preventDefault()},placeholder:t.strings.placeholderText,"data-test-id":"dialpad-input",onRenderSuffix:()=>{var i;return e.createElement(e.Fragment,null,c&&0!==m.length&&e.createElement(th,{ariaLabel:t.strings.deleteButtonAriaLabel,onClick:_,styles:Qa(lb(r),null===(i=t.styles)||void 0===i?void 0:i.deleteIcon),iconProps:{iconName:"DialpadBackspace"}}))}}),e.createElement(Yl,null,pb.map(((i,n)=>e.createElement(Gs,{horizontal:!0,key:`row_${n}`,horizontalAlign:"stretch",tokens:{childrenGap:"1rem"}},i.map(((r,a)=>e.createElement(mb,{key:`button_${a}`,index:a+n*i.length,digit:r.digit,letter:r.letter,styles:t.styles,onClick:S,onLongPress:y,longPressTrigger:d,dtmfToneAudioContext:g.current,disableDtmfPlayback:u}))))))))},vb=t=>{const i=_h().strings.dialpad,n=Object.assign(Object.assign({},i),t.strings);return e.createElement(fb,Object.assign({strings:n},t))},Sb=e=>e.replace(/[^\d*#+]/g,""),yb=t=>{var i,n,r,a;const s=_h().strings.raiseHandButton,o=Object.assign(Object.assign({},s),t.strings),l=xh(),c=Cb(l);return e.createElement(iT,Object.assign({},t,{className:cn(c,t.styles),onClick:null!==(i=t.onToggleRaiseHand)&&void 0!==i?i:t.onClick,onRenderOnIcon:null!==(n=t.onRenderOnIcon)&&void 0!==n?n:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ControlButtonLowerHand"}),onRenderOffIcon:null!==(r=t.onRenderOffIcon)&&void 0!==r?r:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ControlButtonRaiseHand"}),strings:o,labelKey:null!==(a=t.labelKey)&&void 0!==a?a:"raiseHandButtonLabel",disabled:t.disabled}))},Cb=e=>({rootChecked:{background:e.palette.themePrimary,color:Or.white,":focus::after":{outlineColor:`${Or.white}`}},rootCheckedHovered:{background:e.palette.themePrimary,color:Or.white,":focus::after":{outlineColor:`${Or.white}`}},labelChecked:{color:Or.white}}),_b=HE([(e,t)=>!!e.calls[t.callId],PE,EE,bE,TE],((e,t,i,n,r)=>{const a=!i.deviceAccess||i.deviceAccess.audio,s=!1===(null==n?void 0:n.unmuteMic.isPresent)&&"NotInitialized"!==(null==n?void 0:n.unmuteMic.reason)||"Consumer"===r;return{disabled:!e||!a||s,checked:!!e&&!t,microphones:i.microphones,speakers:i.speakers,selectedMicrophone:i.selectedMicrophone,selectedSpeaker:i.selectedSpeaker}})),Eb=HE([ME,EE,bE,TE],((e,t,i,n)=>{const r=R(t),a=null==e?void 0:e.find((e=>"Video"===e.mediaStreamType)),s=!t.deviceAccess||t.deviceAccess.video,o=!1===(null==i?void 0:i.turnVideoOn.isPresent)&&"NotInitialized"!==(null==i?void 0:i.turnVideoOn.reason)||"Consumer"===n;return{disabled:!t.selectedCamera||!s||!t.cameras.length||o,checked:void 0!==e&&e.length>0?!!a:r,cameras:t.cameras,selectedCamera:t.selectedCamera}})),Tb=HE([IE,OE],((e,t)=>{var i;return{checked:!!e,disabled:"InLobby"===t||null!==(i="Connecting"===t)&&void 0!==i&&i}})),bb=HE([RE,OE],((e,t)=>({checked:!!e,disabled:"Connected"!==t}))),Ib=HE([AE,OE,bE,TE],((e,t,i,n)=>{let r;return r=r||!1===(null==i?void 0:i.shareScreen.isPresent)&&"NotInitialized"!==(null==i?void 0:i.shareScreen.reason)||"Consumer"===n||"Attendee"===n,r=r||["InLobby","Connecting","LocalHold"].includes(t),{checked:e,disabled:r}})),wb=HE([EE],(e=>({microphones:Rb(e.microphones),speakers:Rb(e.speakers),cameras:Rb(e.cameras),selectedMicrophone:e.selectedMicrophone,selectedSpeaker:e.selectedSpeaker,selectedCamera:e.selectedCamera})));function Rb(e){return e.filter((e=>""!==e.name))}const Ab=HE([OE],(e=>({checked:"LocalHold"===e}))),Pb=e=>e.isSpeaking&&!e.isMuted,Mb=b(((e,t,i,n,r,a,s,o,l,c)=>((e,t,i,n,r,a,s,o,l,c)=>{const d=E(e);return{userId:e,displayName:t,state:i,isMuted:n,isScreenSharing:r,isSpeaking:a,raisedHand:s,isRemovable:("communicationUser"===S(d).kind||"phoneNumber"===S(d).kind)&&o,reaction:l,spotlight:c}})(e,t,i,n,r,a,s,o,l,c))),kb=ri((e=>e&&e.reactionMessage?{reactionType:e.reactionMessage.reactionType,receivedOn:e.receivedOn}:void 0)),Db=ri(((e,t)=>{const i=null==e?void 0:e.find((e=>_(e.identifier)===t));return i?{spotlightedOrderPosition:i.order}:void 0})),Ob=e=>{var t;return null===(t=null==e?void 0:e.speakersList)||void 0===t?void 0:t.map(_)},Nb=(e,t)=>e?Lb((t=>Object.values(e).filter((e=>!["InLobby","Idle","Connecting","Disconnected"].includes(e.state)||m(e.identifier))).map((e=>{const i=k(e);let n,r=e.displayName;n=e.contentSharingStream;const a=kb(e.reactionState);let s;return s=e.spotlight,t(_(e.identifier),e.isMuted,Pb(e),e.videoStreams,i,r,e.raisedHand,n,a,s)})))):[],Lb=b(((e,t,i,n,r,a,s,o,l,c)=>xb(e,t,i,n,r,a,s,o,l,c))),xb=(e,t,i,n,r,a,s,o,l,c)=>{const d=Object.values(n);let u,h;const p=Object.values(d).findLast((e=>"Video"===e.mediaStreamType&&e.isAvailable))||Object.values(d).findLast((e=>"Video"===e.mediaStreamType)),g=Object.values(d).findLast((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable))||Object.values(d).findLast((e=>"ScreenSharing"===e.mediaStreamType));return p&&(u=Fb(p)),g&&(h=Fb(g)),o&&(h=Ub(o)),{userId:e,displayName:a,isMuted:t,isSpeaking:i,videoStream:u,screenShareStream:h,isScreenSharingOn:void 0!==h&&h.isAvailable,state:r,raisedHand:s,reaction:l,spotlight:c}},Fb=e=>{var t,i,n;return{id:e.id,isAvailable:e.isAvailable,isReceiving:e.isReceiving,isMirrored:null===(t=e.view)||void 0===t?void 0:t.isMirrored,renderElement:null===(i=e.view)||void 0===i?void 0:i.target,scalingMode:null===(n=e.view)||void 0===n?void 0:n.scalingMode,streamSize:e.streamSize}},Ub=e=>({isAvailable:!!e,isReceiving:!0,isMirrored:!1,renderElement:e}),Bb=ri(((e,t,i,n,r,a,s,o,l,c)=>{var d,u;return{userId:e,displayName:null!=t?t:"",isMuted:i,isScreenSharingOn:n,videoStream:{isAvailable:!!r,isMirrored:null===(d=null==r?void 0:r.view)||void 0===d?void 0:d.isMirrored,renderElement:null===(u=null==r?void 0:r.view)||void 0===u?void 0:u.target},role:a,raisedHand:s,reaction:o,spotlight:l,capabilities:c}})),Vb=ri((e=>null==e?void 0:e.map((e=>_(e.identifier))))),Hb=HE([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.remoteParticipants}],(e=>{{const t=Object.assign({},e);return Object.keys(t).forEach((e=>{"Consumer"===t[e].role&&delete t[e]})),t}})),$b=HE([(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.screenShareRemoteParticipant},Hb,ME,PE,AE,kE,DE,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.dominantSpeakers},(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.optimalVideoCount.maxRemoteVideoStreams},TE,IE,RE,wE,bE],((e,t,i,n,r,a,s,o,l,c,d,u,h,p)=>{const g=e&&t?t[e]:void 0,m=null==i?void 0:i.find((e=>"Video"===e.mediaStreamType)),f=Ob(o),v={};null==f||f.forEach(((e,t)=>v[e]=t));const S=kb(u),y=Vb(null==h?void 0:h.spotlightedParticipants);return{screenShareParticipant:g?xb(_(g.identifier),g.isMuted,Pb(g),g.videoStreams,g.state,g.displayName,g.raisedHand,g.contentSharingStream,void 0,g.spotlight):void 0,localParticipant:Bb(s,a,n,r,m,c,d,S,null==h?void 0:h.localParticipantSpotlight,p),remoteParticipants:Nb(Gb(t?Object.values(t):[])),dominantSpeakers:f,maxRemoteVideoStreams:l,spotlightedParticipants:y,maxParticipantsToSpotlight:null==h?void 0:h.maxParticipantsToSpotlight}})),Gb=e=>P(e),jb=HE([DE,kE,Hb,AE,PE,IE,TE,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.totalParticipantCount},RE,wE],((e,t,i,n,r,a,s,o,l,c)=>{const d=Wb(s),u=i?((e,t,i,n,r)=>Mb((i=>e.filter((e=>!v(e.identifier))).filter((e=>!["InLobby","Idle","Connecting","Disconnected"].includes(e.state)||m(e.identifier))).map((e=>{const n=Object.values(e.videoStreams).some((e=>"ScreenSharing"===e.mediaStreamType&&e.isAvailable)),a=k(e);let s=e.displayName;const o=kb(e.reactionState);let l;return l=Db(r,_(e.identifier)),i(_(e.identifier),s,a,e.isMuted,n,e.isSpeaking,e.raisedHand,t,o,l)})).sort(((e,t)=>{var i,n;const r=(null===(i=e.displayName)||void 0===i?void 0:i.toLowerCase())||"",a=(null===(n=t.displayName)||void 0===n?void 0:n.toLowerCase())||"";return r<a?-1:r>a?1:0})))))(zb(Object.values(i)),d,0,0,null==c?void 0:c.spotlightedParticipants):[];return u.push({userId:e,displayName:t,isScreenSharing:n,isMuted:r,raisedHand:a,state:"Connected",isRemovable:!1,reaction:kb(l),spotlight:Db(null==c?void 0:c.spotlightedParticipants,e)}),{participants:u,myUserId:e,totalParticipantCount:o}})),zb=e=>P(e),Wb=e=>"Presenter"===e||"Unknown"===e||void 0===e,qb=HE([jb],(e=>e));var Kb=r(6731),Jb=r.n(Kb);const Yb=t=>{var i,n,r,a;const{callInvitationURL:s,styles:o,onMuteAll:l,onRenderIcon:c,onRenderParticipantList:d,participants:u,myUserId:h,excludeMe:p,onRenderParticipant:g,onRenderAvatar:m,onRemoveParticipant:f,onFetchParticipantMenuItems:v,showParticipantOverflowTooltip:S}=t,y=t.disabled,[C,_]=(0,e.useState)(""),E=Qv(),T=(0,e.useCallback)((()=>{l&&l()}),[l]),b=(0,e.useCallback)((()=>{var t;return e.createElement(VT,{participants:u,myUserId:h,excludeMe:p,onRenderParticipant:g,onRenderAvatar:m,onRemoveParticipant:f,onFetchParticipantMenuItems:v,styles:null===(t=null==o?void 0:o.menuStyles)||void 0===t?void 0:t.participantListStyles,showParticipantOverflowTooltip:S})}),[p,h,f,m,g,u,null===(i=null==o?void 0:o.menuStyles)||void 0===i?void 0:i.participantListStyles,v,S]),I=(0,e.useCallback)((()=>!!s&&Jb()(s)),[s]),w=_h().strings.participantsButton,R=(0,e.useMemo)((()=>Object.assign(Object.assign({},w),t.strings)),[w,t.strings]),A=u.length,P=(0,e.useCallback)((()=>{_(R.copyInviteLinkActionedAriaLabel),setTimeout((()=>{_("")}),3e3)}),[R.copyInviteLinkActionedAriaLabel]),M=(0,e.useCallback)((()=>{var e;const t=[];return A>0&&(t.push({key:"participantListMenuItemKey",onRender:null!=d?d:b}),t.push({key:"participantsDivider1",itemType:sl.Divider}),l&&t.push({key:"muteAllKey",text:R.muteAllButtonLabel,title:R.muteAllButtonLabel,styles:null===(e=null==o?void 0:o.menuStyles)||void 0===e?void 0:e.menuItemStyles,iconProps:{iconName:"MicOff2"},onClick:T})),t}),[A,d,b,l,R.muteAllButtonLabel,null===(n=null==o?void 0:o.menuStyles)||void 0===n?void 0:n.menuItemStyles,T]),k=(0,e.useMemo)((()=>{var e,t;const i={title:R.menuHeader,ariaLabel:R.menuHeader,styles:Ra(JE,null==o?void 0:o.menuStyles),items:[],calloutProps:{preventDismissOnEvent:nf}};if(A>0){let t=u.map((e=>e.userId)).length;p&&(t-=1),i.items.push({key:"participantCountKey",name:ev(R.participantsListButtonLabel,{numParticipants:`${t}`}),itemProps:{styles:null===(e=null==o?void 0:o.menuStyles)||void 0===e?void 0:e.menuItemStyles},iconProps:{iconName:"People"},subMenuProps:{items:M(),calloutProps:{styles:{root:{maxWidth:"100%"}},style:{maxHeight:"20rem"},preventDismissOnEvent:nf}},"data-ui-id":E.participantButtonPeopleMenuItem})}return s&&i.items.push({key:"InviteLinkKey",name:R.copyInviteLinkButtonLabel,title:R.copyInviteLinkButtonLabel,itemProps:{styles:null===(t=null==o?void 0:o.menuStyles)||void 0===t?void 0:t.menuItemStyles},iconProps:{iconName:"Link"},onClick:()=>{I(),P()}}),i}),[R.menuHeader,R.participantsListButtonLabel,R.copyInviteLinkButtonLabel,null==o?void 0:o.menuStyles,A,s,u,p,E.participantButtonPeopleMenuItem,M,I,P]);return e.createElement(e.Fragment,null,e.createElement(zf,{announcementString:C,ariaLive:"polite"}),e.createElement(iT,Object.assign({},t,{disabled:y,menuProps:null!==(r=t.menuProps)&&void 0!==r?r:k,menuIconProps:{hidden:!0},onRenderIcon:null!=c?c:()=>e.createElement(nT,{disabled:y,iconName:"ControlButtonParticipants"}),strings:R,labelKey:null!==(a=t.labelKey)&&void 0!==a?a:"participantsButtonLabel"})))},Qb=HE([e=>e.latestErrors,(e,t)=>{var i;return null===(i=e.calls[t.callId])||void 0===i?void 0:i.diagnostics},EE,e=>e.environmentInfo],((e,t,i,n)=>{var r,a,s,o,l,c,d,u,h,g,m,f,v,S,y,C,_,E;const T=[],b=()=>"safari"===(null==n?void 0:n.environment.browser),I=()=>"mac"===(null==n?void 0:n.environment.platform);(null===(r=null==t?void 0:t.network.latest.networkReceiveQuality)||void 0===r?void 0:r.value)!==p.DiagnosticQuality.Bad&&(null===(a=null==t?void 0:t.network.latest.networkReceiveQuality)||void 0===a?void 0:a.value)!==p.DiagnosticQuality.Poor||T.push({type:"callNetworkQualityLow"}),!0===(null===(s=null==t?void 0:t.media.latest.noSpeakerDevicesEnumerated)||void 0===s?void 0:s.value)&&T.push({type:"callNoSpeakerFound"}),!0===(null===(o=null==t?void 0:t.media.latest.noMicrophoneDevicesEnumerated)||void 0===o?void 0:o.value)&&T.push({type:"callNoMicrophoneFound"}),!1===(null===(l=i.deviceAccess)||void 0===l?void 0:l.audio)&&b()&&T.push({type:"callMicrophoneAccessDeniedSafari"}),!1!==(null===(c=i.deviceAccess)||void 0===c?void 0:c.audio)||b()||T.push({type:"callMicrophoneAccessDenied"}),!0===(null===(d=null==t?void 0:t.media.latest.microphonePermissionDenied)||void 0===d?void 0:d.value)&&I()?T.push({type:"callMacOsMicrophoneAccessDenied"}):!0===(null===(u=null==t?void 0:t.media.latest.microphonePermissionDenied)||void 0===u?void 0:u.value)&&T.push({type:"callMicrophoneAccessDenied"});const w=(null==t?void 0:t.media.latest.microphoneMuteUnexpectedly)||(null==t?void 0:t.media.latest.microphoneNotFunctioning);w&&(w.value===p.DiagnosticQuality.Bad?T.push({type:"callMicrophoneMutedBySystem"}):w.value===p.DiagnosticQuality.Good&&T.push({type:"callMicrophoneUnmutedBySystem"}));const R=null==t?void 0:t.media.latest.cameraStoppedUnexpectedly;return R&&(R.value===p.DiagnosticQuality.Bad?T.push({type:"callVideoStoppedBySystem"}):R.value===p.DiagnosticQuality.Good&&T.push({type:"callVideoRecoveredBySystem"})),!1===(null===(h=i.deviceAccess)||void 0===h?void 0:h.video)&&b()?T.push({type:"callCameraAccessDeniedSafari"}):!1===(null===(g=i.deviceAccess)||void 0===g?void 0:g.video)?T.push({type:"callCameraAccessDenied"}):!0===(null===(m=null==t?void 0:t.media.latest.cameraFreeze)||void 0===m?void 0:m.value)&&T.push({type:"cameraFrozenForRemoteParticipants"}),!0===(null===(f=null==t?void 0:t.media.latest.cameraPermissionDenied)||void 0===f?void 0:f.value)&&I()&&T.push({type:"callMacOsCameraAccessDenied"}),!0===(null===(v=null==t?void 0:t.media.latest.screenshareRecordingDisabled)||void 0===v?void 0:v.value)&&I()?T.push({type:"callMacOsScreenShareAccessDenied"}):!0===(null===(S=null==t?void 0:t.media.latest.screenshareRecordingDisabled)||void 0===S?void 0:S.value)&&T.push({type:"startScreenShareGeneric"}),Zb(T,e,"Call.stopVideo","stopVideoGeneric"),Zb(T,e,"Call.mute","muteGeneric"),Zb(T,e,"Call.stopScreenSharing","stopScreenShareGeneric"),"Call.startVideo: Video operation failure SourceUnavailableError"===(null===(y=e["Call.startVideo"])||void 0===y?void 0:y.message)?Zb(T,e,"Call.startVideo","callCameraAlreadyInUse"):"Call.startVideo: Video operation failure permissionDeniedError"===(null===(C=e["Call.startVideo"])||void 0===C?void 0:C.message)?Zb(T,e,"Call.startVideo","callCameraAccessDenied"):Zb(T,e,"Call.startVideo","startVideoGeneric"),Zb(T,e,"Call.unmute","unmuteGeneric"),Zb(T,e,"VideoEffectsFeature.startEffects","unableToStartVideoEffect"),"CallAgent.join: Invalid meeting link"===(null===(_=e["CallAgent.join"])||void 0===_?void 0:_.message)?Zb(T,e,"CallAgent.join","failedToJoinCallInvalidMeetingLink"):Zb(T,e,"CallAgent.join","failedToJoinCallGeneric"),(null===(E=e["Call.feature"])||void 0===E?void 0:E.message.match(/Call\.feature: startSpotlight failed\. \d+ is the max number of participants that can be Spotlighted/g))&&Zb(T,e,"Call.feature","startSpotlightWhileMaxParticipantsAreSpotlighted"),T.splice(Xb),{activeErrorMessages:T}})),Zb=(e,t,i,n)=>{void 0!==t[i]&&e.push({type:n,timestamp:t[i].timestamp})},Xb=3,eI=vn((()=>On({from:{backgroundPosition:"0px 8568px"},to:{backgroundPosition:"0px 0px"}}))),tI=t=>{var i,n,r,a,s,o,l;const c=_h().strings.reactionButton,d=Object.assign(Object.assign({},c),t.strings),u=xh(),h=iI(u),p=["like","heart","applause","laugh","surprised"],g=new Map([["like",d.likeReactionTooltipContent],["heart",d.heartReactionTooltipContent],["applause",d.applauseReactionTooltipContent],["laugh",d.laughReactionTooltipContent],["surprised",d.surprisedReactionTooltipContent]]),m=new Map([["like",null===(i=t.reactionResources.likeReaction)||void 0===i?void 0:i.url],["heart",null===(n=t.reactionResources.heartReaction)||void 0===n?void 0:n.url],["applause",null===(r=t.reactionResources.applauseReaction)||void 0===r?void 0:r.url],["laugh",null===(a=t.reactionResources.laughReaction)||void 0===a?void 0:a.url],["surprised",null===(s=t.reactionResources.surprisedReaction)||void 0===s?void 0:s.url]]),f={gapSpace:4,styles:{root:{padding:0},calloutMain:{padding:"0.5rem"}},backgroundColor:QE(u)?u.palette.neutralLighter:""},v=cn({display:"flex",justifyContent:"center",alignItems:"center",flexDirection:"row",width:"13.75rem",height:"2.625rem",":hover > :not(:hover)":{opacity:"0.5"}}),S=[{key:"reactions",itemType:sl.Normal,onRender:(i,n)=>e.createElement("div",{"data-ui-id":"reaction-sub-menu",className:v},p.map(((i,r)=>{const a=cn(((e,t)=>{const i=null!=t?t:51;return{display:"flex",flexDirection:"column",height:"100%",width:"100%",backgroundImage:`url(${e})`,justifyContent:"center",alignItems:"center",backgroundSize:"2.75rem 133.875rem",transition:"opacity 2s",backgroundColor:"transparent",transform:"scale(0.6)",":hover":{transform:"scale(0.8)",animationName:eI(),animationDuration:"8.12s",animationTimingFunction:`steps(${i})`,animationIterationCount:"infinite",backgroundColor:"transparent"},":active":{backgroundColor:"transparent"}}})(m.get(i)||"",void 0!==t.reactionResources?LS(i,t.reactionResources):0));return e.createElement(fv,{key:r,"data-ui-id":r,hidden:t.disableTooltip,content:g.get(i),styles:{root:{display:"flex",flexDirection:"column",height:"100%",width:"100%"}},calloutProps:Object.assign({},f)},e.createElement(th,{key:r,onClick:()=>{t.onReactionClick(i),n()},className:a}))})))}];return e.createElement(iT,Object.assign({},t,{className:cn(h,t.styles),menuProps:{shouldFocusOnMount:!0,items:S},onRenderIcon:null!==(o=t.onRenderIcon)&&void 0!==o?o:()=>e.createElement(nT,{disabled:t.disabled,iconName:"ReactionButtonIcon"}),strings:d,labelKey:null!==(l=t.labelKey)&&void 0!==l?l:"reactionButtonLabel",onRenderMenuIcon:()=>e.createElement("div",null),disabled:t.disabled,ariaLabel:d.ariaLabel}))},iI=e=>({rootChecked:{background:e.palette.themePrimary,color:Or.white},rootCheckedHovered:{background:e.palette.themePrimary,color:Or.white},labelChecked:{color:Or.white}}),nI=()=>({}),rI=e=>e===ET?sI(e):aI(e),aI=e=>{if(e===vb)return nI;switch(e){case FC:return $b;case wT:return _b;case IT:return Eb;case RT:return Ib;case yT:return wb;case VT:return jb;case Yb:return qb;case $T:return nI;case Mh:return Qb;case yb:return Tb;case tI:return bb}},sI=e=>{if(e===ET)return Ab},oI=e=>{const t=rI(e);if(!t)throw new Error("Can't find the selector for component, please check supported component list");return Object.assign(Object.assign({},gE(t)),CE())},lI=t=>{var i,n,r;const a=oI(IT),s=(0,e.useMemo)((()=>{var e;return dT(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),o=Xm(),l=o.getState().isRoomsCall,c=null===(n=null===(i=o.getState().call)||void 0===i?void 0:i.capabilitiesFeature)||void 0===n?void 0:n.capabilities.turnVideoOn;return e.createElement(IT,Object.assign({"data-ui-id":"call-composite-camera-button"},a,{showLabel:"compact"!==t.displayType,styles:s,enableDeviceSelectionMenu:t.splitButtonsForDeviceSelection,disableTooltip:t.disableTooltip,disabled:a.disabled||t.disabled||l&&"Unknown"===(null===(r=o.getState().call)||void 0===r?void 0:r.role),onRenderOffIcon:c&&!c.isPresent?()=>e.createElement(nT,{disabled:!0,iconName:"ControlButtonCameraProhibited"}):void 0,onClickVideoEffects:t.onClickVideoEffects,componentRef:t.componentRef}))},cI=t=>{var i,n;const r=oI(yT),a=null!==(n=null===(i=Xm().getState().call)||void 0===i?void 0:i.role)&&void 0!==n?n:"Unknown",s=(0,e.useMemo)((()=>Object.assign(Object.assign({},r),{microphones:"Consumer"===a?[]:r.microphones,cameras:"Consumer"===a?[]:r.cameras})),[r,a]),o=(0,e.useMemo)((()=>{var e;return dT(t.increaseFlyoutItemSize?lT:{},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.increaseFlyoutItemSize,t.styles]),l=ip(),c="Consumer"===a;return e.createElement(yT,Object.assign({persistMenu:!0},s,{showLabel:"compact"!==t.displayType,styles:o,"data-ui-id":"calling-composite-devices-button",disabled:t.disabled,strings:dI(a,l),onRenderIcon:c?()=>e.createElement(nT,{disabled:t.disabled,iconName:"OptionsSpeaker"}):void 0}))},dI=(e,t)=>{if("Consumer"===e)return{label:t.component.strings.microphoneButton.speakerMenuTitle}},uI=t=>{var i;const n=Qh(),r=Qa(pI,null!==(i=t.styles)&&void 0!==i?i:{});return e.createElement(nE,{styles:r,isOpen:t.isOpen,onDismiss:t.onDismiss,isBlocking:!1},e.createElement(Gs,{className:cn({position:"relative"})},e.createElement(Cf,{className:cn({fontWeight:600,fontSize:"1.25rem"})},t.heading),e.createElement(th,{styles:hI(n),iconProps:{iconName:"Cancel"},onClick:t.onCancel})),e.createElement(Gs,{verticalAlign:"center",className:cn({minHeight:"6rem"})},e.createElement(Cf,{className:cn({fontSize:"0.875rem"})},t.text)),e.createElement(Gs,{horizontal:!0,horizontalAlign:"end",tokens:{childrenGap:"0.5rem"}},e.createElement(rE,{styles:gI,text:t.confirmButtonLabel,onClick:t.onConfirm}),e.createElement(yy,{styles:gI,text:t.cancelButtonLabel,onClick:t.onCancel})))},hI=e=>({root:{position:"absolute",top:0,right:0,color:e.palette.neutralPrimary},rootHovered:{color:e.palette.neutralDark}}),pI={main:{padding:"1.5rem ",maxWidth:"30rem"}},gI={label:{fontSize:"0.875rem"}};const mI=t=>{var i;const n="compact"===t.displayType,r=oI($T),a=ip().strings,s=(0,e.useMemo)((()=>({confirmButtonLabel:a.call.endCallConfirmButtonLabel,heading:a.call.endCallConfirmDialogTitle,text:a.call.leaveConfirmDialogContent})),[a.call.endCallConfirmButtonLabel,a.call.endCallConfirmDialogTitle,a.call.leaveConfirmDialogContent]),o=(0,e.useMemo)((()=>({confirmButtonLabel:a.call.leaveConfirmButtonLabel,heading:a.call.leaveConfirmDialogTitle,text:a.call.leaveConfirmDialogContent})),[a.call.leaveConfirmButtonLabel,a.call.leaveConfirmDialogContent,a.call.leaveConfirmDialogTitle]),[l,c]=(0,e.useState)(o),{onHangUp:d}=r,[u,h]=e.useState(!1),p=(0,e.useCallback)((()=>{h(!u)}),[u]),g=(0,e.useCallback)((e=>{d&&d(e),p()}),[d,p]),m=(0,e.useCallback)((e=>{return i=void 0,n=void 0,a=function*(){t.mobileView||!1===e?d():(c(e?s:o),p())},new((r=void 0)||(r=Promise))((function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r((function(e){e(i)}))).then(s,o)}l((a=a.apply(i,n||[])).next())}));var i,n,r,a}),[s,o,d,t.mobileView,p]),f=(0,e.useMemo)((()=>{var e;return Qa(n?aT:rT,null!==(e=t.styles)&&void 0!==e?e:{})}),[n,t.styles]);return e.createElement(e.Fragment,null,e.createElement(uI,Object.assign({},l,{styles:{main:{minWidth:"22.5rem",padding:"1.5rem"}},cancelButtonLabel:a.call.hangUpCancelButtonLabel,onConfirm:()=>g(t.enableEndCallMenu),isOpen:u,onCancel:p})),e.createElement($T,Object.assign({"data-ui-id":"call-composite-hangup-button"},r,{onHangUp:m,styles:f,showLabel:!n,enableEndCallMenu:null!==(i=t.enableEndCallMenu)&&void 0!==i&&i})))},fI=(e,t)=>mE(e,(e=>e),t),vI=e=>e.endedCall,SI=e=>{var t,i;return null!==(i=null===(t=e.call)||void 0===t?void 0:t.state)&&void 0!==i?i:"None"},yI=e=>e.devices,CI=e=>e.page,_I=e=>e.acceptedTransferCallState,EI=e=>e.isLocalPreviewMicrophoneEnabled,TI=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.localVideoStreams},bI=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.diagnostics},II=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.remoteParticipants},wI=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.captionsFeature.captionsKind},RI=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.captionsFeature.isCaptionsFeatureActive},AI=e=>e.isTeamsCall,PI=e=>e.targetCallees,MI=e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.startTime},kI=t=>{var i,n,r;const a=oI(wT),s=fI(SI),o=fI(EI),l=Xm(),c=l.getState().isRoomsCall,d=null===(n=null===(i=l.getState().call)||void 0===i?void 0:i.capabilitiesFeature)||void 0===n?void 0:n.capabilities.unmuteMic;"Connecting"===s&&(a.checked=o);const u=(0,e.useMemo)((()=>{var e;return dT(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]);return e.createElement(wT,Object.assign({"data-ui-id":"call-composite-microphone-button"},a,{showLabel:"compact"!==t.displayType,disableTooltip:t.disableTooltip,styles:u,enableDeviceSelectionMenu:t.splitButtonsForDeviceSelection,disabled:a.disabled||t.disabled||c&&"Unknown"===(null===(r=l.getState().call)||void 0===r?void 0:r.role),onRenderOffIcon:d&&!d.isPresent?()=>e.createElement(nT,{disabled:!0,iconName:"ControlButtonMicProhibited"}):void 0}))},DI=t=>{const i=oI(Yb),n=(0,e.useMemo)((()=>{var e;return dT(t.increaseFlyoutItemSize?oT:{},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.increaseFlyoutItemSize,t.styles]);return e.createElement(Yb,Object.assign({"data-ui-id":"call-composite-participants-button"},i,{showLabel:"compact"!==t.displayType,callInvitationURL:t.callInvitationURL,onFetchParticipantMenuItems:t.onFetchParticipantMenuItems,disabled:OI(t.option)||t.disabled,styles:n,showParticipantOverflowTooltip:!t.isMobile}))},OI=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,NI=t=>{var i;const n=oI(RT),r=(0,e.useMemo)((()=>{var e;return dT(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),a=Xm(),s=a.getState().isRoomsCall;return e.createElement(RT,Object.assign({"data-ui-id":"call-composite-screenshare-button"},n,{showLabel:"compact"!==t.displayType,disabled:(()=>{var e;return null!==(e=null==n?void 0:n.disabled)&&void 0!==e?e:LI(t.option)})()||t.disabled||s&&"Unknown"===(null===(i=a.getState().call)||void 0===i?void 0:i.role),styles:r}))},LI=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,xI=()=>e.createElement(Hm,{iconName:"ControlButtonParticipants"}),FI=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:a}=t,s=Qh(),o=(0,e.useMemo)((()=>{var e;return Qa({rootChecked:{background:s.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{},cT)}),[t.styles,s.palette.neutralLight]);return e.createElement(iT,Object.assign({},t,{"data-ui-id":"call-composite-participants-button",strings:i,labelKey:"peopleButtonLabelKey",onRenderOnIcon:null!=n?n:xI,onRenderOffIcon:null!=r?r:xI,onClick:a,styles:o}))},UI={paddingTop:"0.25rem",paddingBottom:"0.25rem"},BI=Math.max(2,1)+1,VI=BI+1,HI=cn(UI,{zIndex:2}),$I={width:"100%",position:"relative",minHeight:"13rem"},GI=cn(Object.assign(Object.assign({},$I),{minWidth:"30rem"})),jI=cn(Object.assign(Object.assign({},$I),{minWidth:"17.5rem"})),zI={root:{height:"100%"}},WI={root:{width:"100%",position:"absolute",top:0,left:0,padding:"1rem",zIndex:BI,pointerEvents:"none"}},qI={root:{zIndex:BI,pointerEvents:"auto"}},KI=e=>({root:{width:"100%",height:"100%",flexDirection:e?"unset":"column-reverse"}}),JI=t=>{const i=oI(yb),n=fI(SI),r=(0,e.useMemo)((()=>{var e;return dT(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]);let a=YI(t.option);return w(n)&&(a=!0),e.createElement(yb,Object.assign({"data-ui-id":"call-composite-raisehand-button"},i,{showLabel:"compact"!==t.displayType,disabled:a||t.disabled,styles:r}))},YI=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,QI=(e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:ZI("primary",i),secondary:ZI("secondary",i),overflow:ZI("overflow",i)}},ZI=(t,i)=>i?i.filter((e=>e.placement===t)).map(((t,i)=>n=>{var r,a,s,o,l,c,d,u,h,p;return"onRenderButton"in t?t.onRenderButton(n):e.createElement(iT,{ariaDescription:null!==(a=null===(r=t.strings)||void 0===r?void 0:r.ariaDescription)&&void 0!==a?a:n.ariaDescription,ariaLabel:null!==(c=null!==(o=null===(s=t.strings)||void 0===s?void 0:s.ariaLabel)&&void 0!==o?o:null===(l=t.strings)||void 0===l?void 0:l.tooltipContent)&&void 0!==c?c:n.ariaLabel,disabled:null!==(d=t.disabled)&&void 0!==d?d:n.disabled,id:null!==(u=t.id)&&void 0!==u?u:n.id,key:`${t.placement}_${i}`,onClick:null!==(h=t.onItemClick)&&void 0!==h?h:n.onClick,onRenderIcon:()=>{var i,r,a;return e.createElement(al,{iconName:null!==(a=null!==(i=t.iconName)&&void 0!==i?i:null===(r=n.iconProps)||void 0===r?void 0:r.iconName)&&void 0!==a?a:"DefaultCustomButton"})},showLabel:null!==(p=t.showLabel)&&void 0!==p?p:n.showLabel,styles:Xa(n.styles),strings:t.strings})})):[],XI=(e,t)=>t?t.filter((t=>t.placement===e)).map(((e,t)=>{var i,n;return Object.assign(Object.assign({},e),{disabled:e.disabled,iconProps:{iconName:null!==(i=e.iconName)&&void 0!==i?i:"DefaultCustomButton",styles:{root:{lineHeight:0}}},id:e.id,itemKey:`${e.placement}_${t}`,onItemClick:e.onItemClick,text:null===(n=e.strings)||void 0===n?void 0:n.label})})):[],ew=(e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:XI("primary",i).map(tw),secondary:XI("secondary",i).map(tw),overflow:XI("overflow",i).map(tw)}},tw=e=>Object.assign(Object.assign({},e),{key:e.itemKey,onClick:e.onItemClick?t=>{var i;null===(i=e.onItemClick)||void 0===i||i.call(e,t)}:void 0,subMenuProps:e.subMenuProps?{items:e.subMenuProps.map(tw)}:void 0}),iw=e=>{let t;return t=null==e?void 0:e.onFetchCustomButtonProps,t},nw=t=>{const i=oI(tI),n=(0,e.useMemo)((()=>{var e;return dT(null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles]),r=rw(t.option)||i.disabled;return e.createElement(tI,Object.assign({"data-ui-id":"call-composite-reaction-button"},i,{showLabel:"compact"!==t.displayType,disabled:r||t.disabled,styles:n,disableTooltip:t.disableTooltip,persistMenu:!0,reactionResources:t.reactionResource}))},rw=e=>void 0!==e&&!0!==e&&!1!==e&&e.disabled,aw=HE([e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.capabilities}],(e=>({capabilities:e}))),sw=HE([SI,e=>{var t,i;return null!==(i=null===(t=e.call)||void 0===t?void 0:t.isScreenSharingOn)&&void 0!==i&&i}],((e,t)=>({callStatus:e,isScreenShareOn:t}))),ow=vn((e=>({root:{background:e}}))),lw=t=>{var i,n;const r=(0,e.useMemo)((()=>((e,t)=>{if(!1===t)return{};const i=!0===t||void 0===t?{}:t;return e&&(i.screenShareButton=!1),i})(!!t.isMobile,t.options)),[t.isMobile,t.options]),a=Xm(),s=ip(),o=(0,e.useMemo)((()=>({label:s.strings.call.peopleButtonLabel,tooltipOffContent:s.strings.call.peopleButtonTooltipOpen,tooltipOnContent:s.strings.call.peopleButtonTooltipClose})),[s]),l=(0,e.useMemo)((()=>({label:s.strings.call.moreButtonCallingLabel,tooltipOffContent:s.strings.callWithChat.moreDrawerButtonTooltip})),[s]),c=oI(ET),d=oI(yb),u=fI(aw),h="Connected"!==fI(sw).callStatus||!(null==u?void 0:u.capabilities)||u.capabilities.useReactions.isPresent,p=oI(yT);let g=0;const m=cw(null==r?void 0:r.screenShareButton);m&&g++;const f=cw(null==r?void 0:r.microphoneButton);f&&g++;const v=cw(null==r?void 0:r.cameraButton);v&&g++,cw(null==r?void 0:r.endCallButton)&&g++;const S=cw(null==r?void 0:r.participantsButton)&&!t.isMobile;S&&g++;const y=cw(null==r?void 0:r.reactionButton)&&h&&!t.isMobile;y&&g++;const C=(0,e.useMemo)((()=>ew(iw("object"==typeof r?r:void 0),"object"==typeof r?r.displayType:void 0)),[r]),_=(()=>{const e=[];return t.isMobile&&t.onPeopleButtonClicked&&cw(null==r?void 0:r.participantsButton)&&e.push({key:"peopleButtonKey",text:s.component.strings.participantsButton.label,onClick:()=>{t.onPeopleButtonClicked&&t.onPeopleButtonClicked()},iconProps:{iconName:"ControlButtonParticipantsContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:Jt(null==r?void 0:r.participantsButton),"data-ui-id":"call-composite-more-menu-people-button"}),dw(a)||e.push({key:"holdButtonKey",text:s.component.strings.holdButton.tooltipOffContent,onClick:()=>{c.onToggleHold()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:Jt(null==r?void 0:r.holdButton),"data-ui-id":"hold-button"}),e})();let E=cw(null==r?void 0:r.moreButton)&&_.length>0;E&&g++;const T=(0,e.useMemo)((()=>QI(iw(r),null==r?void 0:r.displayType)),[r]);g+=e.Children.count(T.primary)+e.Children.count(T.secondary);let b=cw(null==r?void 0:r.devicesButton);b&&(!t.isMobile||g<5)?g++:(b=!1,E=cw(null==r?void 0:r.moreButton));const I=a.getState().reactions;let w=cw(null==r?void 0:r.raiseHandButton);const R=null===(i=a.getState().call)||void 0===i?void 0:i.role,A=a.getState().isRoomsCall&&R&&["Consumer","Unknown"].includes(R);if(w&&(!t.isMobile||g<5)?g++:(!E&&cw(null==r?void 0:r.moreButton)&&(E=!0,b=!1),w=!1),!b){const e=ST(p,s.component.strings.devicesButton);_.push({key:"devicesButtonKey",text:s.component.strings.devicesButton.label,iconProps:{iconName:"ControlButtonOptions",styles:{root:{lineHeight:0}}},subMenuProps:e,"data-ui-id":"call-composite-more-menu-devices-button"})}w||A||_.push({key:"raiseHandButtonKey",text:d.checked?s.component.strings.raiseHandButton.onLabel:s.component.strings.raiseHandButton.offLabel,onClick:()=>{d.onToggleRaiseHand&&d.onToggleRaiseHand()},iconProps:{iconName:"RaiseHandContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:Jt(null==r?void 0:r.raiseHandButton),"data-ui-id":"call-composite-more-menu-raise-hand-button"}),C.primary&&C.primary.slice(t.isMobile?1:3).forEach((e=>{_.push(Object.assign({itemProps:{styles:sT}},e))})),C.secondary&&C.secondary.forEach((e=>{_.push(Object.assign({itemProps:{styles:sT}},e))})),C.overflow&&C.overflow.forEach((e=>{_.push(Object.assign({itemProps:{styles:sT}},e))}));const P=xh();return!1===t.options?e.createElement(e.Fragment,null):e.createElement(Gs,{horizontalAlign:"center",className:HI},e.createElement(Gs.Item,null,e.createElement(_T,{layout:t.displayVertical?"vertical":"horizontal",styles:ow(P.semanticColors.bodyBackground)},f&&e.createElement(kI,{displayType:null==r?void 0:r.displayType,disabled:Jt(null==r?void 0:r.microphoneButton)}),v&&e.createElement(lI,{displayType:null==r?void 0:r.displayType,disabled:Jt(null==r?void 0:r.cameraButton)}),y&&I&&e.createElement(nw,{displayType:null==r?void 0:r.displayType,reactionResource:I}),w&&!A&&e.createElement(JI,{displayType:null==r?void 0:r.displayType}),m&&e.createElement(NI,{option:null==r?void 0:r.screenShareButton,displayType:null==r?void 0:r.displayType,disabled:Jt(null==r?void 0:r.screenShareButton)}),S&&e.createElement(DI,{option:null==r?void 0:r.participantsButton,callInvitationURL:t.callInvitationURL,onFetchParticipantMenuItems:t.onFetchParticipantMenuItems,displayType:null==r?void 0:r.displayType,increaseFlyoutItemSize:t.increaseFlyoutItemSize,isMobile:t.isMobile,disabled:Jt(null==r?void 0:r.participantsButton)})&&e.createElement(FI,{checked:t.peopleButtonChecked,ariaLabel:null==o?void 0:o.label,showLabel:"compact"!==(null==r?void 0:r.displayType),onClick:t.onPeopleButtonClicked,"data-ui-id":"call-composite-people-button",strings:o,disabled:Jt(null==r?void 0:r.participantsButton),disableTooltip:t.isMobile}),b&&e.createElement(cI,{displayType:null==r?void 0:r.displayType,increaseFlyoutItemSize:t.increaseFlyoutItemSize,disabled:Jt(null==r?void 0:r.devicesButton)}),null===(n=T.primary)||void 0===n?void 0:n.slice(0,t.isMobile?1:3).map(((i,n)=>e.createElement(i,{key:`primary-custom-button-${n}`,showLabel:"compact"!==(null==r?void 0:r.displayType),disableTooltip:t.isMobile}))),E&&e.createElement(hT,{disableTooltip:t.isMobile,"data-ui-id":"common-call-composite-more-button",strings:l,menuIconProps:{hidden:!0},menuProps:{items:_},showLabel:"compact"!==(null==r?void 0:r.displayType)}),cw(null==r?void 0:r.endCallButton)&&e.createElement(mI,{displayType:null==r?void 0:r.displayType}))))},cw=e=>!1!==e,dw=e=>e.getState().isRoomsCall,uw=()=>e.createElement(Hm,{iconName:"ControlBarPeopleButton"}),hw=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:a}=t,s=Qh(),o=(0,e.useMemo)((()=>{var e;return Qa({rootChecked:{background:s.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles,s.palette.neutralLight]);return e.createElement(iT,Object.assign({},t,{strings:i,labelKey:"peopleButtonLabelKey",onRenderOnIcon:null!=n?n:uw,onRenderOffIcon:null!=r?r:uw,onClick:a,styles:o}))},pw=()=>ip().strings.callWithChat,gw=HE([TI],(e=>{var t,i;return{isVideoStreamOn:!!(null===(i=null===(t=null==e?void 0:e.find((e=>"Video"===e.mediaStreamType)))||void 0===t?void 0:t.view)||void 0===i?void 0:i.target)}})),mw=HE([II],(e=>Object.values(null!=e?e:{}).filter((e=>"Connected"===e.state)))),fw=(e,t,i)=>{var n,r,a;if(0===t.length)return"";const s=t.filter((e=>!e.displayName)),o=t.filter((e=>e.displayName)).concat(s);if(0===o.filter((e=>e.displayName)).length&&o.length>1)return ev("joined"===e?i.manyUnnamedParticipantsJoined:i.manyUnnamedParticipantsLeft,{numOfParticipants:(o.length-1).toString()});const l=o.map((e=>{var t;return null!==(t=e.displayName)&&void 0!==t?t:i.unnamedParticipantString}));switch(o.length){case 1:return ev("joined"===e?i.participantJoinedNoticeString:i.participantLeftNoticeString,{displayName:l[0]});case 2:return ev("joined"===e?i.twoParticipantJoinedNoticeString:i.twoParticipantLeftNoticeString,{displayName1:l[0],displayName2:l[1]});case 3:return ev("joined"===e?i.threeParticipantJoinedNoticeString:i.threeParticipantLeftNoticeString,{displayName1:l[0],displayName2:l[1],displayName3:l[2]})}const c=o.length-3;return ev("joined"===e?i.manyParticipantsJoined:i.manyParticipantsLeft,{displayName1:null!==(n=o[0].displayName)&&void 0!==n?n:i.unnamedParticipantString,displayName2:null!==(r=o[1].displayName)&&void 0!==r?r:i.unnamedParticipantString,displayName3:null!==(a=o[2].displayName)&&void 0!==a?a:i.unnamedParticipantString,numOfParticipants:c.toString()})},vw=(e,t)=>{let i=!1;return null==e||e.forEach((e=>{(v(e)||m(e))&&(i=!0)})),t&&t.forEach((e=>{"phoneNumber"in e.identifier||"teamsAppId"in e.identifier||(i=!1)})),i};const Sw=t=>{var i,n;const r=ip(),a=oI(ET),s=gE($E),o=CE(),l=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){yield o.onStartCaptions({spokenLanguage:s.currentSpokenLanguage})},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[o,s.currentSpokenLanguage]),[c,d]=(0,e.useState)(!1),[u,h]=(0,e.useState)(null!==(i=t.userSetGalleryLayout)&&void 0!==i?i:"floatingLocalVideo"),p=fI(PI),g=vw(p),[m,f]=(0,e.useState)(null!==(n=t.dtmfDialerPresent)&&void 0!==n&&n),v=(0,e.useMemo)((()=>({label:r.strings.call.moreButtonCallingLabel,tooltipOffContent:r.strings.callWithChat.moreDrawerButtonTooltip})),[r]),S=[],y={root:{height:"unset",lineHeight:"100%",width:"1.25rem"}};if(S.push({key:"holdButtonKey",text:r.component.strings.holdButton.tooltipOffContent,onClick:()=>{a.onToggleHold()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:t.disableButtonsForHoldScreen}),t.isCaptionsSupported){const e=[];S.push({key:"liveCaptionsKey",id:"common-call-composite-captions-button",text:r.strings.call.liveCaptionsLabel,iconProps:{iconName:"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:t.disableButtonsForHoldScreen,subMenuProps:{id:"captions-contextual-menu",items:e,calloutProps:{preventDismissOnEvent:nf}},submenuIconProps:{iconName:"HorizontalGalleryRightButton",styles:y}}),e.push({key:"ToggleCaptionsKey",id:"common-call-composite-captions-toggle-button",text:s.checked?r.strings.call.startCaptionsButtonTooltipOnContent:r.strings.call.startCaptionsButtonTooltipOffContent,onClick:()=>{s.checked?o.onStopCaptions():""!==s.currentSpokenLanguage?l():t.onCaptionsSettingsClick&&t.onCaptionsSettingsClick()},iconProps:{iconName:s.checked?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:t.disableButtonsForHoldScreen}),t.onCaptionsSettingsClick&&e.push({key:"openCaptionsSettingsKey",id:"common-call-composite-captions-settings-button",text:r.strings.call.captionsSettingsLabel,onClick:t.onCaptionsSettingsClick,iconProps:{iconName:"CaptionsSettingsIcon",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},disabled:t.disableButtonsForHoldScreen||!s.checked})}const C={key:"dtmfDialerScreenKey",itemProps:{styles:sT},text:m?r.strings.call.dtmfDialerMoreButtonLabelOff:r.strings.call.dtmfDialerMoreButtonLabelOn,onClick:()=>{t.onSetDialpadPage&&t.onSetDialpadPage(),f(!m)},iconProps:{iconName:"DtmfDialpadButton",styles:{root:{lineHeight:0}}}};if(t.onSetDialpadPage&&g&&S.push(C),t.onUserSetOverflowGalleryPositionChange){const e={key:"overflowGalleryPositionKey",iconProps:{iconName:"GalleryOptions",styles:{root:{lineHeight:0}}},itemProps:{styles:sT},submenuIconProps:{styles:y},text:r.strings.call.moreButtonGalleryControlLabel,disabled:t.disableButtonsForHoldScreen,subMenuProps:{items:[{key:"dynamicSelectionKey",text:r.strings.call.moreButtonGalleryFloatingLocalLayoutLabel,canCheck:!0,itemProps:{styles:sT},isChecked:"floatingLocalVideo"===t.userSetGalleryLayout,onClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("floatingLocalVideo"),d(!1)},iconProps:{iconName:"FloatingLocalVideoGalleryLayout",styles:{root:{lineHeight:0}}}},{key:"speakerSelectionKey",text:r.strings.call.moreButtonGallerySpeakerLayoutLabel,canCheck:!0,itemProps:{styles:sT},isChecked:"speaker"===t.userSetGalleryLayout,onClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("speaker"),d(!1)},iconProps:{iconName:"SpeakerGalleryLayout",styles:{root:{lineHeight:0}}}},{key:"focusedContentSelectionKey",text:r.strings.call.moreButtonGalleryFocusedContentLayoutLabel,canCheck:!0,itemProps:{styles:sT},isChecked:c,onClick:()=>{var e;!1===c?(h(null!==(e=t.userSetGalleryLayout)&&void 0!==e?e:"floatingLocalVideo"),t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("focusedContent"),d(!0)):(t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout(u),d(!1))},iconProps:{iconName:"FocusedContentGalleryLayout",styles:{root:{lineHeight:0}}}}],calloutProps:{preventDismissOnEvent:nf}}};S.push(e)}const _=(0,e.useMemo)((()=>ew(iw("object"==typeof t.callControls?t.callControls:void 0),"object"==typeof t.callControls?t.callControls.displayType:void 0)),[t.callControls]);return _.primary.slice(3).forEach((e=>{S.push(Object.assign({itemProps:{styles:sT}},e))})),_.secondary.slice(2).forEach((e=>{S.push(Object.assign({itemProps:{styles:sT}},e))})),_.overflow.forEach((e=>{S.push(Object.assign({itemProps:{styles:sT}},e))})),e.createElement(hT,Object.assign({},t,{"data-ui-id":"common-call-composite-more-button",strings:v,menuIconProps:{hidden:!0},menuProps:{items:S,calloutProps:{preventDismissOnEvent:nf}}}))},yw=()=>{const[t,i]=(0,e.useState)(!1);return(0,e.useEffect)((()=>{i(!0)}),[]),e.createElement(yy,{autoFocus:!0,ariaHidden:!0,styles:t?_w:Cw,tabIndex:-1})},Cw={root:{width:"0",height:"0",margin:"0",minHeight:"0",minWidth:"0",maxHeight:"0",maxWidth:"0",opacity:"0",outline:"none",padding:"0",position:"absolute"}},_w={root:{display:"none"}},Ew=()=>e.createElement(Hm,{iconName:"DtmfDialpadButton"}),Tw=t=>{const{strings:i,onRenderOnIcon:n,onRenderOffIcon:r,onClick:a,displayType:s}=t,o=xh(),l=ip(),c={label:l.strings.call.dtmfDialerButtonLabel,tooltipOnContent:l.strings.call.dtmfDialerButtonTooltipOn,tooltipOffContent:l.strings.call.dtmfDialerButtonTooltipOff},d=(0,e.useMemo)((()=>{var e;return Qa({rootChecked:{background:o.palette.neutralLight}},null!==(e=t.styles)&&void 0!==e?e:{})}),[t.styles,o.palette.neutralLight]);return e.createElement(iT,Object.assign({},t,{strings:i||c,showLabel:"compact"!==s,labelKey:"dtmfDialpadButtonLabelKey",onRenderOnIcon:null!=n?n:Ew,onRenderOffIcon:null!=r?r:Ew,onClick:a,styles:d}))},bw=t=>e.createElement(iT,Object.assign({"data-ui-id":"call-composite-exit-spotlight-button",labelKey:"exitSpotlightButtonLabelKey",showLabel:"compact"!==t.displayType,onRenderIcon:()=>e.createElement(nT,{iconName:"ControlButtonExitSpotlight"}),onClick:t.onClick},t)),Iw=16,ww={root:{position:"absolute",width:"100%",height:"100%",pointerEvents:"none",":focus-within":{outline:"1px solid #00000000"}}},Rw=Qa(ww,{root:{display:"none"}}),Aw={main:{minWidth:"min-content",minHeight:"min-content",position:"absolute",overflow:"hidden",pointerEvents:"auto",touchAction:"none"},root:{width:"100%",height:"100%",pointerEvents:"none",":focus-within":{outline:"3px solid #00000000",outlineOffset:"-3px"}}},Pw={display:"flex",position:"absolute",left:0,top:0,width:"100%",height:"100%",overflow:"hidden",zIndex:"100000",pointerEvents:"none"},Mw=e=>null!==e&&"boolean"==typeof e,kw=t=>{var i,n,r,a,s,o,l;const c=xh(),d=c.rtl,u=(0,e.useRef)(null),h=(0,e.useRef)(null),p=(0,e.useRef)(null),[g,m]=(0,e.useState)(0),[f,v]=(0,e.useState)(0),[S,y]=(0,e.useState)(0),[C,_]=(0,e.useState)(0),[E,T]=(0,e.useState)(!1),b=pw(),I=((e,t)=>{if(!1===t)return!1;const i=!0===t||void 0===t?{}:t;return e&&(i.displayType="compact",i.screenShareButton=!1),i})(t.mobileView,t.callControls),[w,R]=(0,e.useState)(!1),A=null===(i=fI((e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.capabilities.hangUpForEveryOne.isPresent})))||void 0===i||i,P=fI(AI),M=(0,e.useCallback)((()=>{m(u.current?u.current.offsetWidth:0),v(h.current?h.current.offsetWidth:0),y(p.current?p.current.offsetWidth:0)}),[]);(0,e.useEffect)((()=>{m(u.current?u.current.offsetWidth:0),v(h.current?h.current.offsetWidth:0),y(p.current?p.current.offsetWidth:0)}),[]),(0,e.useEffect)((()=>(window.addEventListener("resize",M),()=>window.removeEventListener("resize",M))),[M]),(0,e.useEffect)((()=>{_((S-g)/2+g+f)}),[g,f,S]),(0,e.useEffect)((()=>{T(C>S)}),[C,S]);const k=(0,e.useCallback)((()=>{R(!0)}),[]),D=(0,e.useCallback)((()=>{R(!1)}),[]),O=(0,e.useMemo)((()=>({label:b.peopleButtonLabel,selectedLabel:b.selectedPeopleButtonLabel,tooltipOffContent:b.peopleButtonTooltipOpen,tooltipOnContent:b.peopleButtonTooltipClose})),[b]),N=(0,e.useMemo)((()=>({label:b.moreDrawerButtonLabel,tooltipContent:b.moreDrawerButtonTooltip})),[b]),L=ip().strings.call,x=(0,e.useMemo)((()=>({label:L.exitSpotlightButtonLabel,tooltipContent:L.exitSpotlightButtonTooltip})),[L]),F=(0,e.useMemo)((()=>Xa(t.mobileView?{}:Ow,{root:{background:c.semanticColors.bodyBackground}})),[t.mobileView,c.semanticColors.bodyBackground]),U=(0,e.useMemo)((()=>t.mobileView?void 0:Fw(c)),[t.mobileView,c]),B=(0,e.useMemo)((()=>t.mobileView?void 0:xw(c)),[t.mobileView,c]),V=(0,e.useMemo)((()=>t.mobileView?void 0:Uw(c)),[t.mobileView,c]),H=(0,e.useMemo)((()=>t.mobileView||E?{}:d?Lw:Nw),[t.mobileView,d,E]),$=(0,e.useMemo)((()=>t.mobileView||E?{}:{position:"relative",minHeight:"4.5rem",width:"100%"}),[t.mobileView,E]),G=(0,e.useMemo)((()=>QI(iw(!1!==I?I:void 0),!1!==I?null==I?void 0:I.displayType:void 0)),[I]),j=fI(aw),z="Connected"!==fI(sw).callStatus||!(null==j?void 0:j.capabilities)||j.capabilities.useReactions.isPresent;if(!1===I)return e.createElement(e.Fragment,null);const W=Bw(I.peopleButton)||Bw(I.chatButton)||void 0!==G.secondary,q=Bw(null==I?void 0:I.screenShareButton),K=Bw(null==I?void 0:I.microphoneButton),J=Bw(null==I?void 0:I.cameraButton),Y=!1!==(null==I?void 0:I.exitSpotlightButton),Q=t.isCaptionsSupported&&Bw(I.captionsButton),Z=Bw(null==I?void 0:I.moreButton)&&(Bw(null==I?void 0:I.holdButton)||Q||t.onUserSetGalleryLayout),X=null===(n=t.callAdapter.getState().call)||void 0===n?void 0:n.role,ee=t.callAdapter.getState().isRoomsCall&&X&&["Consumer","Unknown"].includes(X),te=t.callAdapter.getState().reactions;return e.createElement("div",{ref:p},e.createElement(Zm,{adapter:t.callAdapter},w&&e.createElement(WE,{showCaptionsSettingsModal:w,onDismissCaptionsSettings:D,changeCaptionLanguage:t.isCaptionsOn&&t.useTeamsCaptions})),e.createElement(Gs,{horizontal:!0,reversed:!t.mobileView&&!E,horizontalAlign:"space-between",className:cn(HI,UI,$)},e.createElement(Gs.Item,{grow:!0,className:cn(H)},e.createElement(Zm,{adapter:t.callAdapter},e.createElement(Gs,{horizontalAlign:"center"},e.createElement(yw,null),e.createElement(Gs.Item,null,e.createElement("div",{ref:u},e.createElement(_T,{layout:t.displayVertical?"vertical":"horizontal",styles:F},K&&e.createElement(kI,{displayType:I.displayType,styles:B,splitButtonsForDeviceSelection:!t.mobileView,disabled:t.disableButtonsForHoldScreen||Jt(I.microphoneButton),disableTooltip:t.mobileView}),J&&e.createElement(lI,{displayType:I.displayType,styles:B,splitButtonsForDeviceSelection:!t.mobileView,disabled:t.disableButtonsForHoldScreen||Jt(I.cameraButton),onClickVideoEffects:t.onClickVideoEffects,componentRef:t.cameraButtonRef,disableTooltip:t.mobileView}),!t.mobileView&&z&&Bw(I.reactionButton)&&te&&e.createElement(nw,{displayType:I.displayType,styles:B,disabled:t.disableButtonsForHoldScreen,reactionResource:te}),!t.mobileView&&Bw(I.raiseHandButton)&&!ee&&e.createElement(JI,{displayType:I.displayType,styles:B,disabled:t.disableButtonsForHoldScreen||Jt(I.microphoneButton)}),Vw(I)&&void 0!==t.onSetDialpadPage&&e.createElement(Tw,{styles:B,displayType:I.displayType,onClick:()=>{void 0!==t.onSetDialpadPage&&t.onSetDialpadPage()}}),Y&&t.onStopLocalSpotlight&&e.createElement(bw,{displayType:I.displayType,onClick:t.onStopLocalSpotlight,styles:B,strings:x}),q&&e.createElement(NI,{option:I.screenShareButton,displayType:I.displayType,styles:U,disabled:t.disableButtonsForHoldScreen||Jt(I.screenShareButton)}),null===(r=G.primary)||void 0===r?void 0:r.slice(0,t.mobileView?1:3).map(((i,n)=>e.createElement(i,{key:`primary-custom-button-${n}`,styles:B,showLabel:"compact"!==I.displayType,disableTooltip:t.mobileView}))),t.mobileView&&e.createElement(hT,{"data-ui-id":"common-call-composite-more-button",strings:N,onClick:t.onMoreButtonClicked,disabled:t.disableButtonsForLobbyPage,disableTooltip:t.mobileView}),!t.mobileView&&Z&&e.createElement(Sw,{disableButtonsForHoldScreen:t.disableButtonsForHoldScreen,styles:B,onClickShowDialpad:t.onClickShowDialpad,callControls:t.callControls,isCaptionsSupported:Q,onCaptionsSettingsClick:k,onUserSetOverflowGalleryPositionChange:t.onUserSetOverflowGalleryPositionChange,onUserSetGalleryLayout:t.onUserSetGalleryLayout,userSetGalleryLayout:t.userSetGalleryLayout,dtmfDialerPresent:t.dtmfDialerPresent,onSetDialpadPage:t.onSetDialpadPage}),e.createElement(mI,{displayType:"compact",mobileView:t.mobileView,styles:V,enableEndCallMenu:!Mw(t.callControls)&&!Mw(null===(a=t.callControls)||void 0===a?void 0:a.endCallButton)&&!t.mobileView&&A&&!P&&"endCallOptions"===(null===(o=null===(s=t.callControls)||void 0===s?void 0:s.endCallButton)||void 0===o?void 0:o.hangUpForEveryone)}))))))),!t.mobileView&&W&&e.createElement(Gs.Item,null,e.createElement("div",{ref:h},e.createElement(Gs,{horizontal:!0,className:t.mobileView?void 0:cn(Dw)},Bw(null==I?void 0:I.peopleButton)&&e.createElement(hw,{checked:t.peopleButtonChecked,ariaLabel:t.peopleButtonChecked?null==O?void 0:O.selectedLabel:null==O?void 0:O.label,showLabel:"compact"!==I.displayType,onClick:t.onPeopleButtonClicked,"data-ui-id":"common-call-composite-people-button",disabled:t.disableButtonsForLobbyPage||t.disableButtonsForHoldScreen||Jt(I.peopleButton),strings:O,styles:B,componentRef:t.peopleButtonRef}),null===(l=G.secondary)||void 0===l?void 0:l.slice(0,2).map(((t,i)=>e.createElement(t,{key:`secondary-custom-button-${i}`,styles:B,showLabel:"compact"!==I.displayType}))))))))},Dw={padding:"0.75rem",columnGap:"0.5rem"},Ow={root:Dw},Nw={position:"absolute",left:"50%",transform:"translate(-50%, 0)"},Lw={position:"absolute",right:"50%",transform:"translate(-50%, 0)"},xw=e=>({root:{border:`solid 1px ${e.palette.neutralQuaternaryAlt}`,borderRadius:e.effects.roundedCorner4,minHeight:"2.5rem",maxWidth:"12rem"},flexContainer:{display:"flex",flexFlow:"row nowrap"},textContainer:{display:"inline",maxWidth:"100%"},label:{fontSize:e.fonts.medium.fontSize,marginLeft:"0.625rem",lineHeight:"1.5rem",display:"block",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"},splitButtonMenuButton:{border:`solid 1px ${e.palette.neutralQuaternaryAlt}`,borderTopRightRadius:e.effects.roundedCorner4,borderBottomRightRadius:e.effects.roundedCorner4,borderTopLeftRadius:"0",borderBottomLeftRadius:"0"},splitButtonMenuButtonChecked:{background:"none"}}),Fw=e=>{const t={border:"none",background:e.palette.themePrimary,color:e.palette.white,"* > svg":{fill:e.palette.white},"@media (forced-colors: active)":{border:"1px solid",borderColor:e.palette.black}},i={rootChecked:t,rootCheckedHovered:t};return Qa(xw(e),i)},Uw=e=>{const t={root:{border:"none"},rootFocused:{"@media (forced-colors: active)":{background:"highlight",color:"highlightText",borderColor:e.palette.black,borderRadius:"unset",outline:`3px solid ${e.palette.black}`}},icon:{"@media (forced-colors: active)":{":focused":{color:e.palette.white}}}};return Qa(xw(e),t)},Bw=e=>!1!==e,Vw=e=>!1===e.moreButton&&!1!==e.dtmfDialerButton;function Hw(t){const i=ip(),n=xh();return e.createElement(Gs,{horizontal:!0,horizontalAlign:"center",className:cn(!0===t.speakingWhileMuted?zw:Ww)},e.createElement(Gs,{horizontal:!0,className:cn($w(n))},e.createElement(Hm,{iconName:"Muted",className:cn(Gw(n))}),e.createElement(Cf,{className:cn(jw(n)),"aria-live":"polite"},i.strings.call.mutedMessage)))}const $w=e=>({background:e.palette.black,gap:"1rem",padding:"1rem",borderRadius:e.effects.roundedCorner4,width:"fit-content",opacity:.8}),Gw=e=>({color:e.palette.white,maxHeight:"1.25rem"}),jw=e=>({color:e.palette.white,fontSize:"1rem"}),zw=Object.assign({},_r.fadeIn100),Ww=Object.assign(Object.assign({},_r.fadeOut200),{display:"none"}),qw=t=>{var i,n,r,a,s;const o=Qh(),l=t.reactionResources,c=new Map([["like",null===(i=null==l?void 0:l.likeReaction)||void 0===i?void 0:i.url],["heart",null===(n=null==l?void 0:l.heartReaction)||void 0===n?void 0:n.url],["laugh",null===(r=null==l?void 0:l.laughReaction)||void 0===r?void 0:r.url],["applause",null===(a=null==l?void 0:l.applauseReaction)||void 0===a?void 0:a.url],["surprised",null===(s=null==l?void 0:l.surprisedReaction)||void 0===s?void 0:s.url]]),d=Qh().effects.roundedCorner4,u={root:{borderTopRightRadius:d,borderTopLeftRadius:d,marginTop:"12px"}};return e.createElement(Gs,{"data-ui-id":"reaction-mobile-drawer-menu-item",id:"reaction",role:"menuitem",horizontal:!0,className:cn(Kw(o.palette.neutralLight,o.fonts.small),t.disabled?Jw(o.palette.neutralQuaternaryAlt):void 0,u.root)},e.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",flexDirection:"row",width:"100%",height:"2.625rem"}},["like","heart","laugh","applause","surprised"].map(((i,n)=>{const r=c.get(i.toString());return e.createElement(th,{key:n,onClick:()=>{var e;null===(e=t.onReactionClick)||void 0===e||e.call(t,i)},style:(a=r||"",s="running",{display:"flex",flexDirection:"column",height:"100%",width:"2.75rem",backgroundImage:`url(${a})`,animationName:eI(),animationDuration:"8.12s",animationTimingFunction:"steps(102)",animationPlayState:s,animationIterationCount:"infinite",justifyContent:"center",alignItems:"center",backgroundPosition:"center",backgroundSize:"2.75rem 133.875rem",transition:"opacity 2s",backgroundColor:"transparent",transform:"scale(0.8)"})});var a,s}))))},Kw=(e,t)=>Object.assign(Object.assign({},t),{height:"3rem",lineHeight:"3rem",padding:"0rem 0.75rem",cursor:"pointer",":hover, :focus":{background:e}}),Jw=e=>({pointerEvents:"none",background:e,":hover, :focus":{background:e}});var Yw=Ys(),Qw="Toggle",Zw=e.forwardRef((function(t,i){var n=t.as,r=void 0===n?"div":n,a=t.ariaLabel,s=t.checked,o=t.className,l=t.defaultChecked,c=void 0!==l&&l,d=t.disabled,u=t.inlineLabel,h=t.label,p=t.offAriaLabel,g=t.offText,m=t.onAriaLabel,f=t.onChange,v=t.onChanged,S=t.onClick,y=t.onText,C=t.role,_=t.styles,E=t.theme,T=b_(s,c,e.useCallback((function(e,t){null==f||f(e,t),null==v||v(t)}),[f,v])),b=T[0],I=T[1],w=Yw(_,{theme:E,className:o,disabled:d,checked:b,inlineLabel:u,onOffMissing:!y&&!g}),R=b?m:p,A=fu(Qw,t.id),P="".concat(A,"-label"),M="".concat(A,"-stateText"),k=b?y:g,D=Ds(t,Ss,["defaultChecked"]),O=void 0;a||R||(h&&(O=P),k&&!O&&(O=M));var N=e.useRef(null);Lo(N),Xw(t,b,N);var L={root:{className:w.root,hidden:D.hidden},label:{children:h,className:w.label,htmlFor:A,id:P},container:{className:w.container},pill:Ii(Ii({},D),{"aria-disabled":d,"aria-checked":b,"aria-label":a||R,"aria-labelledby":O,className:w.pill,"data-is-focusable":!0,"data-ktp-target":!0,disabled:d,id:A,onClick:function(e){d||(I(!b,e),S&&S(e))},ref:N,role:C||"switch",type:"button"}),thumb:{className:w.thumb},stateText:{children:k,className:w.text,htmlFor:A,id:M}};return e.createElement(r,Ii({ref:i},L.root),h&&e.createElement(r_,Ii({},L.label)),e.createElement("div",Ii({},L.container),e.createElement("button",Ii({},L.pill),e.createElement("span",Ii({},L.thumb))),(b&&y||g)&&e.createElement(r_,Ii({},L.stateText))))}));Zw.displayName=Qw+"Base";var Xw=function(t,i,n){e.useImperativeHandle(t.componentRef,(function(){return{get checked(){return!!i},focus:function(){n.current&&n.current.focus()}}}),[i,n])},eR=Ws(Zw,(function(e){var t,i,n,r,a,s,o,l=e.theme,c=e.className,d=e.disabled,u=e.checked,h=e.inlineLabel,p=e.onOffMissing,g=l.semanticColors,m=l.palette,f=g.bodyBackground,v=g.inputBackgroundChecked,S=g.inputBackgroundCheckedHovered,y=m.neutralDark,C=g.disabledBodySubtext,_=g.smallInputBorder,E=g.inputForegroundChecked,T=g.disabledBodySubtext,b=g.disabledBackground,I=g.smallInputBorder,w=g.inputBorderHovered,R=g.disabledBodySubtext,A=g.disabledText;return{root:["ms-Toggle",u&&"is-checked",!d&&"is-enabled",d&&"is-disabled",l.fonts.medium,{marginBottom:"8px"},h&&{display:"flex",alignItems:"center"},c],label:["ms-Toggle-label",{display:"inline-block"},d&&{color:A,selectors:(t={},t[Nr]={color:"GrayText"},t)},h&&!p&&{marginRight:16},p&&h&&{order:1,marginLeft:16},h&&{wordBreak:"break-word"}],container:["ms-Toggle-innerContainer",{display:"flex",position:"relative"}],pill:["ms-Toggle-background",jr(l,{inset:-3}),{fontSize:"20px",boxSizing:"border-box",width:40,height:20,borderRadius:10,transition:"all 0.1s ease",border:"1px solid ".concat(I),background:f,cursor:"pointer",display:"flex",alignItems:"center",padding:"0 3px",overflow:"visible"},!d&&[!u&&{selectors:{":hover":[{borderColor:w}],":hover .ms-Toggle-thumb":[{backgroundColor:y,selectors:(i={},i[Nr]={borderColor:"Highlight"},i)}]}},u&&[{background:v,borderColor:"transparent",justifyContent:"flex-end"},{selectors:(n={":hover":[{backgroundColor:S,borderColor:"transparent",selectors:(r={},r[Nr]={backgroundColor:"Highlight"},r)}]},n[Nr]=Ii({backgroundColor:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),n)}]],d&&[{cursor:"default"},!u&&[{borderColor:R}],u&&[{backgroundColor:C,borderColor:"transparent",justifyContent:"flex-end"}]],!d&&{selectors:{"&:hover":{selectors:(a={},a[Nr]={borderColor:"Highlight"},a)}}}],thumb:["ms-Toggle-thumb",{display:"block",width:12,height:12,borderRadius:"50%",transition:"all 0.1s ease",backgroundColor:_,borderColor:"transparent",borderWidth:6,borderStyle:"solid",boxSizing:"border-box"},!d&&u&&[{backgroundColor:E,selectors:(s={},s[Nr]={backgroundColor:"Window",borderColor:"Window"},s)}],d&&[!u&&[{backgroundColor:T}],u&&[{backgroundColor:b}]]],text:["ms-Toggle-stateText",{selectors:{"&&":{padding:"0",margin:"0 8px",userSelect:"none",fontWeight:Mr.regular}}},d&&{selectors:{"&&":{color:A,selectors:(o={},o[Nr]={color:"GrayText"},o)}}}]}}),void 0,{scope:"Toggle"});const tR=e=>({root:{overflow:"auto"},drawerSurfaceStyles:{drawerContentContainer:{root:{span:{fontWeight:400,fontSize:bm(14),lineHeight:bm(22),color:e.palette.neutralDark}}}}}),iR=t=>{var i;const n=Qh(),r=(0,e.useCallback)((e=>{t.selectLanguage(e)}),[t]),a=(0,e.useMemo)((()=>{var e;return rf(null!==(e=t.supportedLanguageStrings)&&void 0!==e?e:[]).map((e=>({itemKey:e,text:t.supportedLanguageStrings?t.supportedLanguageStrings[e]:e,onItemClick:()=>r(e),secondaryIconProps:t.currentLanguage===e?{iconName:"Accept"}:void 0})))}),[t.currentLanguage,t.supportedLanguageStrings,r]),s=(0,e.useMemo)((()=>[...a].sort(((e,t)=>e.text&&t.text&&e.text>t.text?1:-1))),[a]);return e.createElement(jf,{heading:null===(i=t.strings)||void 0===i?void 0:i.menuTitle,items:null!=s?s:[],onLightDismiss:()=>{t.setCurrentLanguage(t.currentLanguage),t.onLightDismiss()},styles:tR(n)})},nR=(e,t)=>t?{root:{margin:0},pill:{backgroundColor:`${e.palette.themePrimary} !important`},thumb:{backgroundColor:`${e.palette.white} !important`}}:{root:{margin:0}},rR=t=>{var i;const n=Qh(),r=(0,e.useCallback)((e=>{t.selectLanguage(e)}),[t]),a=(0,e.useMemo)((()=>{var e;return rf(null!==(e=t.supportedLanguageStrings)&&void 0!==e?e:[]).map((e=>({itemKey:e,text:t.supportedLanguageStrings?t.supportedLanguageStrings[e]:e,onItemClick:()=>r(e),secondaryIconProps:t.currentLanguage===e?{iconName:"Accept"}:void 0})))}),[t.currentLanguage,t.supportedLanguageStrings,r]),s=(0,e.useMemo)((()=>[...a].sort(((e,t)=>e.text&&t.text&&e.text>t.text?1:-1))),[a]);return e.createElement(jf,{heading:null===(i=t.strings)||void 0===i?void 0:i.menuTitle,items:null!=s?s:[],onLightDismiss:()=>{t.setCurrentLanguage(t.currentLanguage),t.onLightDismiss()},styles:tR(n)})};var aR=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const sR=t=>{var i,n,r,a,s,o;const l=xh(),c=Xm(),d=[],{speakers:u,onSelectSpeaker:h,onLightDismiss:p}=t,g=ip(),m=oI(ET),f=fI(PI),v=vw(f),[S,y]=(0,e.useState)(null!==(i=t.dtmfDialerPresent)&&void 0!==i&&i),C=oI(yb),_=(0,e.useCallback)(((e,t)=>{const i=null==u?void 0:u.find((e=>e.id===t));i&&h(i),p()}),[u,h,p]),E=!1!==(T=t.callControls)&&(!0===T||void 0===T?{}:T);var T;const b=t.isCaptionsSupported&&!1!==E&&lR(E.captionsButton);void 0!==t.reactionResources&&d.push({itemKey:"reactions",onRendererContent:()=>e.createElement(qw,{onReactionClick:e=>aR(void 0,void 0,void 0,(function*(){var i;null===(i=t.onReactionClick)||void 0===i||i.call(t,e),p()})),reactionResources:t.reactionResources})}),t.speakers&&t.speakers.length>0&&d.push({itemKey:"speakers",disabled:t.disableButtonsForHoldScreen,text:t.strings.speakerMenuTitle,iconProps:{iconName:"MoreDrawerSpeakers"},subMenuProps:t.speakers.map((e=>({itemKey:e.id,iconProps:{iconName:oR(e,t.selectedSpeaker)?"MoreDrawerSelectedSpeaker":"MoreDrawerSpeakers"},text:e.name,onItemClick:_,secondaryIconProps:oR(e,t.selectedSpeaker)?{iconName:"Accept"}:void 0}))),secondaryText:null===(n=t.selectedSpeaker)||void 0===n?void 0:n.name});const{microphones:I,onSelectMicrophone:w}=t,R=(0,e.useCallback)(((e,t)=>{const i=null==I?void 0:I.find((e=>e.id===t));i&&w(i),p()}),[I,w,p]);if(t.microphones&&t.microphones.length>0){const e=t.speakers&&t.speakers.length>0,i=e?"microphones":"audioDevices",n=e?t.strings.microphoneMenuTitle:t.strings.audioDeviceMenuTitle,a=e?"MoreDrawerMicrophones":"MoreDrawerSpeakers",s=e?"MoreDrawerSelectedMicrophone":"MoreDrawerSelectedSpeaker";d.push({itemKey:i,disabled:t.disableButtonsForHoldScreen,text:n,iconProps:{iconName:a},subMenuProps:t.microphones.map((e=>({itemKey:e.id,iconProps:{iconName:oR(e,t.selectedMicrophone)?s:a},text:e.name,onItemClick:R,secondaryIconProps:oR(e,t.selectedMicrophone)?{iconName:"Accept"}:void 0,disabled:!1!==E?Jt(E.microphoneButton):void 0}))),secondaryText:null===(r=t.selectedMicrophone)||void 0===r?void 0:r.name})}const A={itemKey:"dtmfDialerScreenKey",text:S?g.strings.call.dtmfDialerMoreButtonLabelOff:g.strings.call.dtmfDialerMoreButtonLabelOn,onItemClick:()=>{t.onSetDialpadPage&&t.onSetDialpadPage(),y(!S),p()},iconProps:{iconName:"DtmfDialpadButton",styles:{root:{lineHeight:0}}}};t.onSetDialpadPage&&v&&d.push(A);const P={itemKey:"galleryPositionKey",iconProps:{iconName:"GalleryOptions",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen,text:g.strings.call.moreButtonGalleryControlLabel,subMenuProps:[{itemKey:"dynamicSelectionKey",text:g.strings.call.moreButtonGalleryFloatingLocalLayoutLabel,onItemClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("floatingLocalVideo"),p()},iconProps:{iconName:"FloatingLocalVideoGalleryLayout",styles:{root:{lineHeight:0}}},secondaryIconProps:"floatingLocalVideo"===t.userSetGalleryLayout?{iconName:"Accept"}:void 0},{itemKey:"focusedContentSelectionKey",text:g.strings.call.moreButtonGalleryFocusedContentLayoutLabel,onItemClick:()=>{t.onUserSetGalleryLayout&&t.onUserSetGalleryLayout("focusedContent"),p()},iconProps:{iconName:"FocusedContentGalleryLayout",styles:{root:{lineHeight:0}}},secondaryIconProps:"focusedContent"===t.userSetGalleryLayout?{iconName:"Accept"}:void 0}]};d.push(P),!1!==E&&lR(null==E?void 0:E.peopleButton)&&d.push({itemKey:"people",id:"call-composite-drawer-people-button",text:t.strings.peopleButtonLabel,iconProps:{iconName:"MoreDrawerPeople"},onItemClick:t.onPeopleButtonClicked,disabled:Jt(E.peopleButton)||t.disableButtonsForHoldScreen}),!1!==E&&lR(null==E?void 0:E.holdButton)&&d.push({itemKey:"holdButtonKey",disabled:t.disableButtonsForHoldScreen||Jt(E.holdButton),text:g.component.strings.holdButton.tooltipOffContent,onItemClick:()=>{m.onToggleHold(),p()},iconProps:{iconName:"HoldCallContextualMenuItem",styles:{root:{lineHeight:0}}}});const M=null===(a=c.getState().call)||void 0===a?void 0:a.role,k=c.getState().isRoomsCall&&M&&["Consumer","Unknown"].includes(M);if(!1!==E&&lR(null==E?void 0:E.raiseHandButton)&&!k){const e=C.checked?"LowerHandContextualMenuItem":"RaiseHandContextualMenuItem";d.push({itemKey:"raiseHandButtonKey",disabled:t.disableButtonsForHoldScreen||Jt(E.raiseHandButton),text:C.checked?g.component.strings.raiseHandButton.onLabel:g.component.strings.raiseHandButton.offLabel,onItemClick:()=>{C.onToggleRaiseHand&&C.onToggleRaiseHand(),p()},iconProps:{iconName:e,styles:{root:{lineHeight:0}}}})}const D=ip().strings.call.spokenLanguageStrings,O=ip().strings.call.captionLanguageStrings,N=gE(GE),L=CE(),x=CE(),[F,U]=(0,e.useState)(!1),[B,V]=(0,e.useState)(!1),[H,$]=(0,e.useState)(null!==(s=N.currentSpokenLanguage)&&void 0!==s?s:"en-us"),[G,j]=(0,e.useState)(null!==(o=N.currentCaptionLanguage)&&void 0!==o?o:hE[H]),z=(0,e.useCallback)((()=>aR(void 0,void 0,void 0,(function*(){N.isCaptionsFeatureActive?L.onStopCaptions():yield L.onStartCaptions({spokenLanguage:H})}))),[N.isCaptionsFeatureActive,L,H]);if(b){const i=[],n=D?D[H]:H;if(d.push({itemKey:"captions",id:"common-call-composite-captions-button",disabled:t.disableButtonsForHoldScreen,text:t.strings.captionsMenuTitle,iconProps:{iconName:"CaptionsIcon"},subMenuProps:i}),i.push({itemKey:"ToggleCaptionsKey",text:N.isCaptionsFeatureActive?g.strings.call.startCaptionsButtonTooltipOnContent:g.strings.call.startCaptionsButtonTooltipOffContent,iconProps:{iconName:N.isCaptionsFeatureActive?"CaptionsOffIcon":"CaptionsIcon",styles:{root:{lineHeight:0}}},onItemClick:z,disabled:t.disableButtonsForHoldScreen,secondaryComponent:e.createElement(Gs,{verticalFill:!0,verticalAlign:"center"},e.createElement(eR,{id:"common-call-composite-captions-toggle-button",checked:N.isCaptionsFeatureActive,styles:nR(l,N.isCaptionsFeatureActive),onChange:z}))}),i.push({itemKey:"ChangeSpokenLanguage",text:t.strings.spokenLanguageMenuTitle,id:"common-call-composite-captions-spoken-settings-button",secondaryText:n,iconProps:{iconName:"ChangeSpokenLanguageIcon",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen||!N.isCaptionsFeatureActive,onItemClick:()=>{U(!0)},secondaryIconProps:{iconName:"ChevronRight",styles:{root:{lineHeight:0}}}}),t.useTeamsCaptions){const e=O?O[G]:G;i.push({itemKey:"ChangeCaptionLanguage",text:t.strings.captionLanguageMenuTitle,id:"common-call-composite-captions-subtitle-settings-button",secondaryText:e,iconProps:{iconName:"ChangeCaptionLanguageIcon",styles:{root:{lineHeight:0}}},disabled:t.disableButtonsForHoldScreen||!N.isCaptionsFeatureActive,onItemClick:()=>{V(!0)},secondaryIconProps:{iconName:"ChevronRight",styles:{root:{lineHeight:0}}}})}}const W=(0,e.useMemo)((()=>((e,t)=>{const i=null==e?void 0:e.map((e=>e({displayType:t})));return{primary:XI("primary",i),secondary:XI("secondary",i),overflow:XI("overflow",i)}})(iw(!1!==E?E:void 0),!1!==E?null==E?void 0:E.displayType:void 0)),[E]);return W.primary.slice(1).forEach((e=>{d.push(e)})),W.secondary.forEach((e=>{d.push(e)})),W.overflow.forEach((e=>{d.push(e)})),e.createElement(e.Fragment,null,F&&b&&e.createElement(rR,{onLightDismiss:t.onLightDismiss,selectLanguage:$,setCurrentLanguage:x.onSetSpokenLanguage,currentLanguage:H,strings:{menuTitle:t.strings.spokenLanguageMenuTitle},supportedLanguageStrings:D}),B&&b&&e.createElement(iR,{onLightDismiss:t.onLightDismiss,selectLanguage:j,setCurrentLanguage:x.onSetCaptionLanguage,currentLanguage:G,strings:{menuTitle:t.strings.captionLanguageMenuTitle},supportedLanguageStrings:O}),!F&&!B&&e.createElement(jf,{items:d,onLightDismiss:t.onLightDismiss}))},oR=(e,t)=>!!t&&e.id===t.id,lR=e=>!1!==e,cR=HE([yI],(e=>({microphones:e.microphones,speakers:e.speakers,selectedMicrophone:e.selectedMicrophone,selectedSpeaker:e.selectedSpeaker}))),dR=t=>{const i=pw(),n=(0,e.useMemo)((()=>({peopleButtonLabel:i.peopleButtonLabel,audioDeviceMenuTitle:i.moreDrawerAudioDeviceMenuTitle,microphoneMenuTitle:i.moreDrawerMicrophoneMenuTitle,speakerMenuTitle:i.moreDrawerSpeakerMenuTitle,captionsMenuTitle:i.moreDrawerCaptionsMenuTitle,spokenLanguageMenuTitle:i.moreDrawerSpokenLanguageMenuTitle,captionLanguageMenuTitle:i.moreDrawerCaptionLanguageMenuTitle,galleryOptionsMenuTitle:i.moreDrawerGalleryOptionsMenuTitle})),[i]),r=fI(cR),a=CE();return e.createElement(sR,Object.assign({},t,r,a,{strings:n}))},uR={height:"100%",width:"100%"},hR=cn(Object.assign(Object.assign({},uR),{minWidth:"30rem",minHeight:"22rem"})),pR=cn(Object.assign(Object.assign({},uR),{minWidth:"17.5rem",minHeight:"13rem"})),gR=(e=1)=>({root:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:e}}),mR=(Object.assign(Object.assign({},{root:{height:"100%",padding:"0.5rem 0.25rem",width:"21.5rem"}}),{display:"none"}),{root:{lineHeight:"1.5rem",fontSize:"1.125rem",padding:"0.75rem 0.75rem 0.75rem 0.25rem",fontWeight:"600"}}),fR={root:{margin:"0 0.25rem"}},vR={root:{flexDirection:"column",display:"flex"}},SR={root:{flexBasis:"0",flexGrow:"1",overflowY:"auto"}},yR={root:{flexGrow:"1",flexBasis:"0",maxWidth:"100%",position:"relative"}},CR={root:{position:"absolute",height:"100%",width:"100%"}},_R={childrenGap:"0.5rem"},ER=cn({height:"100%"}),TR=cn({height:"100%",overflowY:"auto",overflowX:"hidden"}),bR={root:{padding:"0rem"},participantItemStyles:{root:{padding:"0.5rem"}}},IR={root:{padding:"0rem"},participantItemStyles:{root:{padding:"0.5rem 1rem"}}},wR={root:{padding:"0.5rem",textOverflow:"ellipsis",overflow:"hidden"}},RR=e=>({root:{height:"100%",minWidth:"1.5rem",padding:"0.5rem 0.25rem",marginRight:"0.25rem",border:"none",background:"none"},rootHovered:{background:"none"},rootPressed:{background:"none"},rootFocused:{background:"none"},icon:{color:e.palette.neutralSecondary,display:"flex",alignItems:"center"}}),AR=(Qa({root:{width:"100%",height:"100%"}},{root:{display:"none"}}),{root:{height:"3rem"}}),PR={root:{border:"none",minWidth:"2.5rem",maxWidth:"2.875rem",height:"100%",background:"none",padding:"0 1rem"},rootChecked:{background:"none"},rootCheckedHovered:{background:"none"}},MR=Qa(PR,{root:{visibility:"hidden"}}),kR={root:{border:"none",borderBottom:"0.125rem solid transparent",width:"8rem",height:"100%",background:"none",padding:"0"},rootChecked:{background:"none"},rootCheckedHovered:{background:"none"},flexContainer:{flexFlow:"column",display:"contents"},label:{fontSize:"1rem",fontWeight:100,lineHeight:"2rem",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},labelChecked:{fontWeight:600}},DR={root:{display:"none"}},OR={root:{width:"100%",height:"100%"}},NR={childrenGap:"0.5rem"},LR=(0,e.createContext)({}),xR=t=>e.createElement(LR.Provider,{value:t},t.children),FR=()=>(0,e.useContext)(LR),UR=()=>{const{sidePaneRenderer:e,overrideSidePane:t}=FR();return!(!e&&!(null==t?void 0:t.isActive))},BR=e=>{const t=UR(),{sidePaneRenderer:i}=FR();return t&&(null==i?void 0:i.id)===e},VR=t=>{const{onClose:i,onChatButtonClicked:n,onPeopleButtonClicked:r,activeTab:a}=t,s=Qh(),o=ip().strings.call,l=n&&r,c=(0,e.useMemo)((()=>Qa(kR,{root:{width:"100%"},label:{fontSize:s.fonts.medium.fontSize,fontWeight:s.fonts.medium.fontWeight}},l?{rootChecked:{borderBottom:`0.125rem solid ${s.palette.themePrimary}`}}:{})),[s,l]);return e.createElement(Gs,{horizontal:!0,grow:!0,styles:AR},e.createElement(yy,{ariaLabel:o.returnToCallButtonAriaLabel,ariaDescription:o.returnToCallButtonAriaDescription,onClick:i,styles:PR,onRenderIcon:()=>e.createElement($m,{iconName:"ChevronLeft"}),autoFocus:!0}),e.createElement(Gs.Item,{grow:!0,role:"tablist"},e.createElement(Yl,{direction:dl.horizontal,className:cn(OR.root)},e.createElement(Gs,{horizontal:!0,styles:OR},e.createElement(Gs.Item,{grow:!0},n&&e.createElement(yy,{onClick:n,styles:c,checked:"chat"===a,"aria-selected":"chat"===a,role:"tab",disabled:t.disableChatButton},o.chatButtonLabel)),e.createElement(Gs.Item,{grow:!0},r&&e.createElement(yy,{onClick:r,styles:c,checked:"people"===a,"aria-selected":"people"===a,role:"tab",disabled:t.disablePeopleButton},o.peopleButtonLabel))))),e.createElement(yy,{styles:MR,onRenderIcon:()=>e.createElement($m,{iconName:"ChevronLeft"})}))},HR=t=>{var i;const{sidePaneRenderer:n,overrideSidePane:r}=FR(),a=(null==r?void 0:r.renderer.contentRenderer)&&r.persistRenderingWhenClosed&&!r.isActive&&!n,s=(0,e.useMemo)((()=>{return{root:{height:"auto",width:"100%",padding:"0.5rem 0.25rem",maxWidth:null!=(e=t.maxWidth)?e:"21.5rem",minWidth:null!=(i=t.minWidth)?i:"18rem"}};var e,i}),[t.maxWidth,t.minWidth]),o=a?DR:t.mobileView?OR:s,l=null!==(i=(null==r?void 0:r.isActive)?r.renderer.headerRenderer:null==n?void 0:n.headerRenderer)&&void 0!==i?i:GR,c=(null==r?void 0:r.isActive)?r.renderer.id:void 0,{updateSidePaneRenderer:d}=t,u=(0,e.useCallback)((()=>{d(void 0)}),[d]),h=(0,e.useMemo)((()=>{var i;return e.createElement(VR,{onClose:"chat"===c?null!==(i=t.onChatButtonClicked)&&void 0!==i?i:$R:u,activeTab:"people"===(null==n?void 0:n.id)?"people":"chat",disablePeopleButton:t.disablePeopleButton,disableChatButton:t.disableChatButton,onPeopleButtonClicked:"people"===(null==n?void 0:n.id)?$R:t.onPeopleButtonClicked,onChatButtonClicked:"chat"===c?$R:t.onChatButtonClicked})}),[c,t.onChatButtonClicked,t.onPeopleButtonClicked,t.disablePeopleButton,t.disableChatButton,null==n?void 0:n.id,u]),p=!t.mobileView||"chat"!==c&&"people"!==(null==n?void 0:n.id)?l():h,g=(null==r?void 0:r.isActive)||null==n?void 0:n.contentRenderer,m=(null==r?void 0:r.isActive)||(null==r?void 0:r.persistRenderingWhenClosed)?r.renderer.contentRenderer:void 0;return g||m?e.createElement(Gs,{verticalFill:!0,grow:!0,styles:o,"data-ui-id":"SidePane",tokens:t.mobileView?{}:NR},p,e.createElement(Gs.Item,{verticalFill:!0,grow:!0,styles:vR},e.createElement(Gs,{verticalFill:!0,styles:SR},g&&e.createElement(Gs.Item,{verticalFill:!0,styles:yR},e.createElement(Gs,{styles:CR},e.createElement(g,null))),m&&e.createElement(Gs.Item,{verticalFill:!0,styles:!(null==r?void 0:r.isActive)&&(null==r?void 0:r.persistRenderingWhenClosed)?DR:yR},e.createElement(Gs,{styles:CR},e.createElement(m,null)))))):e.createElement(GR,null)},$R=()=>{},GR=()=>e.createElement(e.Fragment,null);var jR=vn((function(e,t,i,n){var r,a,s,o,l,c,d,u,h,p,g,m,f,v=Zu(e),S=Xu(e),y=e.palette,C=e.semanticColors;return Qa(v,S,{root:[jr(e,{inset:2,highContrastStyle:{left:4,top:4,bottom:4,right:4,border:"none"},borderColor:"transparent"}),e.fonts.medium,{minWidth:"40px",backgroundColor:y.white,color:y.neutralPrimary,padding:"0 4px",border:"none",borderRadius:0,selectors:(r={},r[Nr]={border:"none"},r)}],rootHovered:{backgroundColor:y.neutralLighter,color:y.neutralDark,selectors:(a={},a[Nr]={color:"Highlight"},a[".".concat(Gu.msButtonIcon)]={color:y.themeDarkAlt},a[".".concat(Gu.msButtonMenuIcon)]={color:y.neutralPrimary},a)},rootPressed:{backgroundColor:y.neutralLight,color:y.neutralDark,selectors:(s={},s[".".concat(Gu.msButtonIcon)]={color:y.themeDark},s[".".concat(Gu.msButtonMenuIcon)]={color:y.neutralPrimary},s)},rootChecked:{backgroundColor:y.neutralLight,color:y.neutralDark,selectors:(o={},o[".".concat(Gu.msButtonIcon)]={color:y.themeDark},o[".".concat(Gu.msButtonMenuIcon)]={color:y.neutralPrimary},o)},rootCheckedHovered:{backgroundColor:y.neutralQuaternaryAlt,selectors:(l={},l[".".concat(Gu.msButtonIcon)]={color:y.themeDark},l[".".concat(Gu.msButtonMenuIcon)]={color:y.neutralPrimary},l)},rootExpanded:{backgroundColor:y.neutralLight,color:y.neutralDark,selectors:(c={},c[".".concat(Gu.msButtonIcon)]={color:y.themeDark},c[".".concat(Gu.msButtonMenuIcon)]={color:y.neutralPrimary},c)},rootExpandedHovered:{backgroundColor:y.neutralQuaternaryAlt},rootDisabled:{backgroundColor:y.white,selectors:(d={},d[".".concat(Gu.msButtonIcon)]={color:C.disabledBodySubtext,selectors:(u={},u[Nr]=Ii({color:"GrayText"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),u)},d[Nr]=Ii({color:"GrayText",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),d)},splitButtonContainer:{height:"100%",selectors:(h={},h[Nr]={border:"none"},h)},splitButtonDividerDisabled:{selectors:(p={},p[Nr]={backgroundColor:"Window"},p)},splitButtonDivider:{backgroundColor:y.neutralTertiaryAlt},splitButtonMenuButton:{backgroundColor:y.white,border:"none",borderTopRightRadius:"0",borderBottomRightRadius:"0",color:y.neutralSecondary,selectors:{":hover":{backgroundColor:y.neutralLighter,color:y.neutralDark,selectors:(g={},g[Nr]={color:"Highlight"},g[".".concat(Gu.msButtonIcon)]={color:y.neutralPrimary},g)},":active":{backgroundColor:y.neutralLight,selectors:(m={},m[".".concat(Gu.msButtonIcon)]={color:y.neutralPrimary},m)}}},splitButtonMenuButtonDisabled:{backgroundColor:y.white,selectors:(f={},f[Nr]=Ii({color:"GrayText",border:"none",backgroundColor:"Window"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),f)},splitButtonMenuButtonChecked:{backgroundColor:y.neutralLight,color:y.neutralDark,selectors:{":hover":{backgroundColor:y.neutralQuaternaryAlt}}},splitButtonMenuButtonExpanded:{backgroundColor:y.neutralLight,color:y.black,selectors:{":hover":{backgroundColor:y.neutralQuaternaryAlt}}},splitButtonMenuIcon:{color:y.neutralPrimary},splitButtonMenuIconDisabled:{color:y.neutralTertiary},label:{fontWeight:"normal"},icon:{color:y.themePrimary},menuIcon:{color:y.neutralSecondary}},t)})),zR=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(Wu,Ii({},this.props,{variantClassName:"ms-Button--commandBar",styles:jR(n,i),onRenderDescription:Ro}))},Ri([qu("CommandBarButton",["theme","styles"],!0)],i)}(e.Component);const WR=t=>{const i=Qh(),n=(0,e.useMemo)((()=>({root:{minWidth:"1.5rem",padding:"0.5rem 0.25rem",marginRight:"0.25rem",backgroundColor:i.semanticColors.bodyBackground},icon:{color:i.palette.neutralSecondary},iconHovered:{color:i.palette.neutralSecondary},iconPressed:{color:i.palette.neutralSecondary}})),[i.palette.neutralSecondary,i.semanticColors.bodyBackground]);return t.mobileView?e.createElement(qR,Object.assign({},t)):e.createElement(Gs,{horizontal:!0,horizontalAlign:"space-between",styles:fR,verticalAlign:"center"},e.createElement(Gs.Item,{role:"heading",styles:mR,"aria-label":t.headingText},t.headingText),e.createElement(Gs.Item,null,e.createElement(zR,{ariaLabel:t.dismissSidePaneButtonAriaLabel,styles:n,iconProps:{iconName:"cancel"},onClick:t.onClose})))},qR=t=>{const{headingText:i,dismissSidePaneButtonAriaLabel:n,dismissSidePaneButtonAriaDescription:r,onClose:a}=t,s=Qh(),o=(0,e.useMemo)((()=>Qa(kR,{root:{width:"100%"},label:{fontSize:s.fonts.medium.fontSize,fontWeight:s.fonts.medium.fontWeight}})),[s]);return e.createElement(Gs,{horizontal:!0,grow:!0,styles:AR},e.createElement(yy,{ariaLabel:n,ariaDescription:r,onClick:a,styles:PR,onRenderIcon:()=>e.createElement($m,{iconName:"ChevronLeft"}),autoFocus:!0}),e.createElement(Gs.Item,{grow:!0},e.createElement(yy,{checked:!0,styles:o},i)),e.createElement(yy,{styles:MR,ariaHidden:!0,onRenderIcon:()=>e.createElement($m,{iconName:"ChevronLeft"})}))},KR=t=>{const{onFetchAvatarPersonaData:i,onFetchParticipantMenuItems:n,title:r,participantListProps:a,headingMoreButtonAriaLabel:s,onClickHeadingMoreButton:o,headingMoreButtonMenuProps:l}=t,c=fu(),d=xh(),u=a.totalParticipantCount,h=(0,e.useMemo)((()=>({root:{color:d.palette.neutralSecondary,margin:t.isMobile?"0.5rem 1rem":"0.5rem",fontSize:d.fonts.smallPlus.fontSize}})),[d.palette.neutralSecondary,d.fonts.smallPlus.fontSize,t.isMobile]);return e.createElement(Gs,{className:ER},e.createElement(Gs,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center"},e.createElement(Gs.Item,{grow:!0,styles:h,"aria-label":r,id:c},JR(null!=r?r:"",u)),(o||(null==l?void 0:l.items)&&l.items.length>0)&&e.createElement(Gs.Item,null,e.createElement(yy,{ariaLabel:s,styles:RR(d),iconProps:{iconName:"PeoplePaneMoreButton"},onClick:o?()=>o():void 0,menuProps:t.onClickHeadingMoreButton?void 0:t.headingMoreButtonMenuProps,onRenderMenuIcon:()=>null}))),e.createElement(Yl,{className:TR,shouldFocusOnMount:!0},e.createElement(VT,Object.assign({},a,{styles:t.isMobile?IR:bR,onRenderAvatar:(t,n)=>e.createElement(e.Fragment,null,e.createElement(gT,Object.assign({"data-ui-id":"chat-composite-participant-custom-avatar",userId:t},n,{hidePersonaDetails:!!(null==n?void 0:n.text),dataProvider:i,allowActiveBorder:!0})),(null==n?void 0:n.text)&&e.createElement(Cf,{nowrap:!0,styles:wR},null==n?void 0:n.text)),onFetchParticipantMenuItems:n,showParticipantOverflowTooltip:!t.isMobile,participantAriaLabelledBy:c}))))},JR=(e,t)=>ev(e,t?{numberOfPeople:`(${t})`}:{numberOfPeople:" "}),YR={root:{position:"relative",maxHeight:"100%",overflow:"hidden"}},QR={root:{overflowY:"scroll"}},ZR={root:{width:"100%",padding:"0.5rem 1rem"}},XR={root:{marginLeft:"0.5rem",marginRight:"0.5rem"}},eA={root:{height:"2.5rem",width:"100%"},textContainer:{display:"contents"}},tA=(e,t)=>({itemKey:e.key,onItemClick:()=>{var i;null===(i=e.onClick)||void 0===i||i.call(e),t()},iconProps:e.iconProps,text:e.text,disabled:e.disabled}),iA={lineHeight:"0",width:"1.125rem"},nA=t=>{const{strings:i,isMobile:n,showDialpad:r,onDismissDialpad:a,onAddParticipant:s,alternateCallerId:o}=t,[l,c]=(0,e.useState)(""),d=xh(),u=()=>{c(""),a()},h=()=>{if(s){const e={phoneNumber:"+"+l.replace(/\D/g,"").replaceAll(" ","")};s(e,{alternateCallerId:{phoneNumber:o}}),u()}},p=(0,e.useMemo)((()=>(e=>({main:{borderRadius:e.effects.roundedCorner6,padding:"1rem"}}))(d)),[d]),g=(0,e.useMemo)((()=>((e,t)=>({root:{padding:0,marginLeft:0,marginRight:0,maxWidth:"100%"},textField:{root:{borderBottom:`1px solid ${t.palette.neutralTertiaryAlt}`},field:{backgroundColor:t.palette.white,fontSize:t.fonts.large.fontSize,padding:"0 0.5rem",textAlign:e?"center":"left",":active":{padding:"0 0.5rem"}}},deleteIcon:{root:{backgroundColor:t.palette.white}},digit:{color:t.palette.themeDarkAlt}}))(n,d)),[d,n]),m=(0,e.useMemo)((()=>(e=>({root:{fontWeight:e.fonts.medium.fontWeight,fontSize:e.fonts.medium.fontSize,width:"100%",height:"2.5rem",borderRadius:3,padding:"0.625rem"},textContainer:{display:"contents"}}))(d)),[d]),f=()=>e.createElement(e.Fragment,null,e.createElement(vb,{styles:g,onChange:c,longPressTrigger:n?"touch":"mouseAndTouch"}),e.createElement(rE,{text:i.dialpadStartCallButtonLabel,onRenderIcon:()=>e.createElement($m,{iconName:"DialpadStartCall"}),onClick:h,styles:m,disabled:""===l}));return n?e.createElement(Gs,{"data-ui-id":"call-with-chat-composite-dialpad"},r&&e.createElement(Gs,{styles:gR()},e.createElement(Bf,{onLightDismiss:u,disableMaxHeight:!0},e.createElement(Gs,{style:{padding:"1rem"}},f())))):e.createElement(e.Fragment,null,e.createElement(nE,{titleAriaId:i.dialpadModalAriaLabel,isOpen:r,onDismiss:u,isBlocking:!0,styles:p,"data-ui-id":"call-with-chat-composite-dialpad"},e.createElement(Gs,{horizontal:!0,horizontalAlign:"space-between",verticalAlign:"center"},e.createElement(Cf,null,i.dialpadModalTitle),e.createElement(th,{iconProps:{iconName:"Cancel"},ariaLabel:i.dialpadCloseModalButtonAriaLabel,onClick:u,style:{color:d.palette.black}})),e.createElement(Gs,{style:{overflow:"hidden"}},f())))},rA=t=>{const i=xh(),{inviteLink:n,strings:r,mobileView:a,onAddParticipant:s,alternateCallerId:o}=t,[l,c]=(0,e.useState)(!1),[d,u]=(0,e.useState)(),h=(0,e.useMemo)((()=>(e=>({root:{borderRadius:e.effects.roundedCorner6}}))(i)),[i]),p=(0,e.useMemo)((()=>((e,t)=>({root:{minHeight:t?"3rem":"2.5rem",borderRadius:t?e.effects.roundedCorner6:e.effects.roundedCorner4,width:"100%"},textContainer:{display:"contents"}}))(i,a)),[a,i]),g=(0,e.useMemo)((()=>{const e={styles:h,items:[],useTargetWidth:!0,calloutProps:{preventDismissOnEvent:nf},onMenuOpened(e){u(void 0)}};return n&&e.items.push({key:"InviteLinkKey",text:r.copyInviteLinkButtonLabel,itemProps:{styles:p},iconProps:{iconName:"Link",style:iA},onClick:()=>{u(r.copyInviteLinkActionedAriaLabel),Jb()(n)}}),o&&e.items.push({key:"DialpadKey",text:r.openDialpadButtonLabel,itemProps:{styles:p},iconProps:{iconName:"PeoplePaneOpenDialpad",style:iA},onClick:()=>c(!0),"data-ui-id":"call-dial-phone-number-button"}),e}),[h,n,o,r.copyInviteLinkButtonLabel,r.copyInviteLinkActionedAriaLabel,r.openDialpadButtonLabel,p]),m=()=>{c(!1)},[f,v]=(0,e.useState)([]),S=(0,e.useMemo)((()=>()=>{const e=g.items.map((e=>tA(e,(()=>v([])))));v(e)}),[g,v]);return a?e.createElement(Gs,null,e.createElement(zf,{ariaLive:"assertive",announcementString:d}),g.items.length>0&&e.createElement(Gs.Item,{styles:ZR},e.createElement(rE,{onClick:S,styles:p,onRenderIcon:()=>aA(),text:r.peoplePaneAddPeopleButtonLabel,"data-ui-id":"call-add-people-button"})),f.length>0&&e.createElement(Gs,{styles:gR(),"data-ui-id":"call-add-people-dropdown"},e.createElement(jf,{disableMaxHeight:!0,onLightDismiss:()=>v([]),items:f})),o&&e.createElement(nA,{isMobile:!0,strings:r,showDialpad:l,onDismissDialpad:m,onAddParticipant:s,alternateCallerId:o})):e.createElement(e.Fragment,null,e.createElement(Gs,null,e.createElement(zf,{ariaLive:"assertive",announcementString:d}),o&&e.createElement(nA,{isMobile:!1,strings:r,showDialpad:l,onDismissDialpad:m,onAddParticipant:s,alternateCallerId:o}),g.items.length>0&&e.createElement(Gs,{styles:XR},e.createElement(yy,{onRenderIcon:()=>aA(),text:r.peoplePaneAddPeopleButtonLabel,menuProps:g,styles:p,"data-ui-id":"call-add-people-button"}))))};function aA(){return e.createElement($m,{iconName:"PeoplePaneAddPerson"})}const sA=t=>{const{inviteLink:i,mobileView:n,strings:r,participantList:a}=t,s=xh(),[o,l]=(0,e.useState)("");return(0,e.useMemo)((()=>Qa(eA,((e,t)=>({root:{minHeight:e?"3rem":"2.5rem",borderRadius:e?t.effects.roundedCorner6:t.effects.roundedCorner4}}))(n,s))),[n,s]),(0,e.useCallback)((()=>{l(r.copyInviteLinkActionedAriaLabel),setTimeout((()=>{l("")}),3e3)}),[r.copyInviteLinkActionedAriaLabel]),n?e.createElement(rA,{strings:r,mobileView:n,inviteLink:i,onAddParticipant:t.onAddParticipant,alternateCallerId:t.alternateCallerId}):e.createElement(Gs,{tokens:_R,"data-ui-id":"people-pane-content",verticalFill:!0},e.createElement(rA,{strings:r,mobileView:n,inviteLink:i,onAddParticipant:t.onAddParticipant,alternateCallerId:t.alternateCallerId}),e.createElement(Gs.Item,{grow:!0,styles:{root:{overflowY:"hidden"}}},a))};var oA=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const lA=t=>{const{inviteLink:i,onFetchParticipantMenuItems:n,setDrawerMenuItems:r,participantListHeadingMoreButtonProps:a}=t,s=Xm(),o=ip(),l=o.strings.call,c=(0,e.useCallback)((e=>oA(void 0,void 0,void 0,(function*(){yield s.removeParticipant(e)}))),[s]),d=(0,e.useCallback)(((e,t)=>oA(void 0,void 0,void 0,(function*(){yield s.addParticipant(e,t)}))),[s]),u=s.getState().alternateCallerId,h=oI(VT),p=dA(s),g=(0,e.useMemo)((()=>e=>{if(e){let t=cA(e,l,p&&e.isRemovable?h.onRemoveParticipant:void 0,h.myUserId);n&&(t=n(e.userId,h.myUserId,t));const i=t.map((e=>tA(e,(()=>r([])))));r(i)}}),[l,h.onRemoveParticipant,h.myUserId,p,n,r]),m=(0,e.useMemo)((()=>{const e=null==a?void 0:a.items.map((e=>tA(e,(()=>r([])))));return e&&e.length>0?()=>r(e):void 0}),[null==a?void 0:a.items,r]),f=(0,e.useMemo)((()=>Object.assign(Object.assign({},h),{onRemoveParticipant:t.mobileView?void 0:e=>oA(void 0,void 0,void 0,(function*(){return c(e)})),onParticipantClick:t.mobileView?g:void 0})),[h,t.mobileView,g,c]),v=e.createElement(KR,{isMobile:t.mobileView,participantListProps:f,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,onFetchParticipantMenuItems:t.mobileView?void 0:n,title:l.peoplePaneSubTitle,headingMoreButtonAriaLabel:o.strings.call.peoplePaneMoreButtonAriaLabel,onClickHeadingMoreButton:t.mobileView?m:void 0,headingMoreButtonMenuProps:t.participantListHeadingMoreButtonProps});return t.mobileView?e.createElement(Gs,{verticalFill:!0,styles:YR,tokens:_R,"data-ui-id":"people-pane-content"},e.createElement(Gs.Item,{grow:!0,styles:QR},v),e.createElement(sA,{inviteLink:i,mobileView:t.mobileView,participantList:v,strings:l,onAddParticipant:d,alternateCallerId:u})):e.createElement(sA,{inviteLink:i,mobileView:t.mobileView,participantList:v,strings:l,onAddParticipant:d,alternateCallerId:u})},cA=(e,t,i,n)=>{const r=[];return i&&(null==e?void 0:e.userId)!==n&&r.push({key:"remove",text:t.removeMenuLabel,onClick:()=>{(null==e?void 0:e.userId)&&(null==i||i(null==e?void 0:e.userId))},iconProps:{iconName:"UserRemove"},"data-ui-id":"participant-list-remove-participant-button"}),r},dA=e=>{var t;const i=null===(t=e.getState().call)||void 0===t?void 0:t.role;return"Presenter"===i||"Unknown"===i||void 0===i},uA="people",hA="3.375rem",pA="4.83rem",gA={root:{visibility:"hidden",height:hA,width:pA,border:"2px"}},mA=t=>{var i,n,r,a,s,o,l;const c=xh(),d=null!==(i=t.isSelected)&&void 0!==i&&i,u=null!==(n=t.disabled)&&void 0!==n&&n,h=null===(r=t.backgroundProps)||void 0===r?void 0:r.url,p=(0,e.useCallback)((()=>{return{root:{background:(e={theme:c,isSelected:d,disabled:u,backgroundImage:h}).disabled?e.theme.palette.neutralQuaternaryAlt:void 0,backgroundImage:e.backgroundImage?`url(${e.backgroundImage})`:void 0,backgroundPosition:"center",backgroundSize:"cover",borderRadius:"0.25rem",color:e.theme.palette.neutralPrimary,cursor:e.disabled?"default":"pointer",height:hA,width:pA,outlineOffset:"-1px",outline:e.isSelected?`2px solid ${e.theme.palette.themePrimary}`:`1px solid ${e.theme.palette.neutralQuaternaryAlt}`,":hover":{boxSizing:"border-box",width:"4.85rem",height:"3.373rem",outlineOffset:"-1px",outline:e.disabled&&!e.isSelected?`1px solid ${e.theme.palette.neutralQuaternaryAlt}`:`2px solid ${e.theme.palette.themePrimary}`}}};var e}),[h,u,d,c]),g=e.createRef();return(0,e.useEffect)((()=>{t.focusOnMount&&g.current&&g.current.focus()}),[g,t.focusOnMount]),e.createElement(fv,Object.assign({},t.tooltipProps),e.createElement(Gs,{key:t.itemKey,className:cn(null===(a=t.styles)||void 0===a?void 0:a.root),verticalAlign:"center",horizontalAlign:"center","data-ui-id":"video-effects-item","aria-label":null!==(s=t.ariaLabel)&&void 0!==s?s:t.itemKey,"aria-disabled":t.disabled},e.createElement(yy,{styles:p(),onClick:u?void 0:()=>{var e;return null===(e=t.onSelect)||void 0===e?void 0:e.call(t,t.itemKey)},componentRef:g,autoFocus:t.focusOnMount},e.createElement(Gs,{horizontalAlign:"center",tokens:{childrenGap:"0.15rem"}},t.iconProps&&e.createElement(Gs.Item,{styles:{root:null===(o=t.styles)||void 0===o?void 0:o.iconContainer}},e.createElement(al,Object.assign({},t.iconProps))),t.title&&e.createElement(Gs.Item,{styles:{root:null===(l=t.styles)||void 0===l?void 0:l.textContainer}},e.createElement(Cf,{variant:"small"},t.title))))))},fA=t=>{var i,n,r;const[a,s]=e.useState(t.defaultSelectedEffectKey),o=null!==(i=t.selectedEffectKey)&&void 0!==i?i:a,l=t.options.map((e=>Object.assign({isSelected:e.itemKey===o,onSelect:()=>(e=>{var i;s(e),null===(i=t.onChange)||void 0===i||i.call(t,e)})(e.itemKey)},e))),c=null!==(n=t.itemsPerRow)&&void 0!==n?n:3,d="wrap"===c?[l]:function(e,t){const i=[];let n=[];for(const r of e)n.push(r),n.length===t&&(i.push(n),n=[]);return n.length>0&&i.push(n),i}(l,c),u="wrap"===c?0:c-d[d.length-1].length;return e.createElement(Gs,{tokens:{childrenGap:"0.5rem"}},e.createElement(r_,{className:cn(null===(r=t.styles)||void 0===r?void 0:r.label)},t.label),d.map(((i,n)=>{var r;return e.createElement(Gs,{className:cn(null===(r=t.styles)||void 0===r?void 0:r.rowRoot),wrap:"wrap"===t.itemsPerRow,horizontal:!0,key:n,tokens:{childrenGap:"0.5rem"},"data-ui-id":"video-effects-picker-row"},i.map(((i,r)=>0===r&&0===n?e.createElement(mA,Object.assign({},i,{itemKey:i.itemKey,key:i.itemKey,focusOnMount:!t.ignoreFocusOnMount})):e.createElement(mA,Object.assign({},i,{itemKey:i.itemKey,key:i.itemKey})))),u>0&&n===d.length-1&&Array.from({length:u}).map(((t,i)=>e.createElement(Gs,{key:i,styles:gA,"data-ui-id":"video-effects-hidden-item"}))))})))},vA=HE([e=>e.selectedVideoBackgroundEffect],(e=>!e||"blur"!==e.effectName&&"none"!==e.effectName?e&&"replacement"===e.effectName?null==e?void 0:e.key:"none":e.effectName)),SA=HE([sw,yI,TI],((e,t,i)=>{var n,r;let a;return I(e.callStatus)?a=null==i?void 0:i.find((e=>"Video"===e.mediaStreamType)):R(t)&&(a=t.unparentedViews[0]),{isAvailable:!!a,isMirrored:null===(n=null==a?void 0:a.view)||void 0===n?void 0:n.isMirrored,renderElement:null===(r=null==a?void 0:a.view)||void 0===r?void 0:r.target,activeVideoEffects:null==a?void 0:a.videoEffects}}));const yA=t=>{var i;const{onDismissError:n,activeVideoEffectError:r,activeVideoEffectChange:a}=t,s=ip(),o=Xm(),l=s.strings.call,c=null===(i=fI(SA).activeVideoEffects)||void 0===i?void 0:i.activeEffects,d=(0,e.useMemo)((()=>{const e=[{itemKey:"none",iconProps:{iconName:"RemoveVideoBackgroundEffect"},title:l.removeBackgroundEffectButtonLabel,tooltipProps:{content:l.removeBackgroundTooltip}},{itemKey:"blur",iconProps:{iconName:"BlurVideoBackground"},title:l.blurBackgroundEffectButtonLabel,tooltipProps:{content:l.blurBackgroundTooltip}}],t=o.getState().videoBackgroundImages;return t&&t.forEach((t=>{var i;e.push({itemKey:t.key,backgroundProps:{url:t.url},tooltipProps:{content:null!==(i=t.tooltipText)&&void 0!==i?i:""}})})),e}),[l,o]),u=(0,e.useCallback)((e=>{return t=void 0,i=void 0,r=function*(){if("blur"===e){const t={effectName:e};a({type:"blur",timestamp:new Date(Date.now())}),yield o.startVideoBackgroundEffect(t),o.updateSelectedVideoBackgroundEffect(t)}else if("none"===e){const t={effectName:e};yield o.stopVideoBackgroundEffects(),o.updateSelectedVideoBackgroundEffect(t)}else{const t=d.find((t=>t.itemKey===e));if(t&&t.backgroundProps){const i={effectName:"replacement",key:e,backgroundImageUrl:t.backgroundProps.url};a({type:"replacement",timestamp:new Date(Date.now())}),yield o.startVideoBackgroundEffect(i),o.updateSelectedVideoBackgroundEffect(i)}}},new((n=void 0)||(n=Promise))((function(e,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(s,o)}l((r=r.apply(t,i||[])).next())}));var t,i,n,r}),[o,a,d]);if(r&&c&&0===c.length){const e={effectName:"none"};o.updateSelectedVideoBackgroundEffect(e)}return CA(n,r,d,u)},CA=(t,i,n,r)=>{const a=fI(vA),s=fI(SA).isAvailable,o=!s&&"none"!==a,l=ip();return e.createElement(Gs,{tokens:{childrenGap:"0.75rem"},className:cn({paddingLeft:"0.5rem"})},i&&s&&e.createElement(vh,{messageBarType:Ku.error,onDismiss:()=>t(i)},l.strings.call.unableToStartVideoEffect),o&&e.createElement(vh,{messageBarType:Ku.warning},l.strings.call.cameraOffBackgroundEffectWarningText),e.createElement(fA,{label:l.strings.call.videoEffectsPaneBackgroundSelectionTitle,styles:_A,options:null!=n?n:[],onChange:r,selectedEffectKey:a}))},_A={label:{fontSize:"0.75rem",lineHeight:"0.5rem",fontWeight:"400"}},EA="videoeffects",TA=(t,i,n,r,a)=>{const s=(0,e.useCallback)((()=>{var e;t(void 0),null===(e=null==a?void 0:a.current)||void 0===e||e.focus()}),[a,t]),o=ip(),l=(0,e.useCallback)((()=>{var t,n;return e.createElement(WR,{onClose:s,headingText:o.strings.call.videoEffectsPaneTitle,dismissSidePaneButtonAriaLabel:null!==(n=null!==(t=o.strings.call.dismissSidePaneButtonLabel)&&void 0!==t?t:o.strings.callWithChat.dismissSidePaneButtonLabel)&&void 0!==n?n:"Close",mobileView:i})}),[s,o.strings,i]),c=n.find((e=>"unableToStartVideoEffect"===e.type)),d=(0,e.useCallback)((()=>e.createElement(yA,{onDismissError:r,activeVideoEffectError:c,activeVideoEffectChange:()=>{c&&(null==r||r(c))}})),[c,r]),u=(0,e.useMemo)((()=>({headerRenderer:l,contentRenderer:d,id:EA})),[d,l]),h=(0,e.useCallback)((()=>{t(u)}),[u,t]),p=BR(EA);(0,e.useEffect)((()=>{p&&h()}),[p,h]);const g=(0,e.useCallback)((()=>{p?s():h()}),[s,p,h]);return{openVideoEffectsPane:h,closeVideoEffectsPane:s,toggleVideoEffectsPane:g,isVideoEffectsPaneOpen:p}},bA=t=>{const i=Qh().effects.elevation8;return e.createElement(wA,{styles:RA(t.orientation,i)},t.children)},IA=t=>e.createElement(wA,{styles:AA(t.orientation)},t.children),wA=t=>e.createElement(Gs,{styles:t.styles},t.children),RA=vn(((e,t)=>({root:{borderRadius:"0.25rem",height:"landscape"===e?"5.5rem":"8rem",width:"landscape"===e?"8rem":"5.5rem",boxShadow:t,overflow:"hidden"}}))),AA=vn((e=>({root:{borderRadius:"0.25rem",height:"landscape"===e?"1.625rem":"2rem",width:"landscape"===e?"2rem":"1.625rem",overflow:"hidden"}}))),PA=t=>e.createElement(MA,{onClick:t.onClick,primaryView:e.createElement(bA,Object.assign({},t.primaryTile)),secondaryView:t.secondaryTile&&e.createElement(IA,Object.assign({},t.secondaryTile)),ariaLabel:t.strings.rootAriaLabel}),MA=t=>e.createElement("aside",{style:kA,onClick:t.onClick,onKeyPress:e=>t.onClick&&_f(e,t.onClick),"aria-label":t.ariaLabel,tabIndex:t.onClick?0:-1,"data-ui-id":"picture-in-picture-in-picture-root"},t.primaryView,e.createElement("div",{style:DA},t.secondaryView)),kA={display:"flex",width:"min-content",position:"relative",cursor:"pointer"},DA={position:"absolute",bottom:"0.125rem",right:"0.125rem"},OA=t=>{var i,n;const{localParticipant:r,remoteParticipant:a,onCreateLocalStreamView:s,onDisposeLocalStreamView:o,onCreateRemoteStreamView:l,onDisposeRemoteStreamView:c}=t,d=(0,e.useMemo)((()=>{var e,t;return{onCreateLocalStreamView:s,onDisposeLocalStreamView:o,localVideoViewOptions:NA,displayName:r.displayName,showLabel:!1,showMuteIndicator:!1,showCameraSwitcherInLocalPreview:!1,isAvailable:null===(e=r.videoStream)||void 0===e?void 0:e.isAvailable,renderElement:null===(t=r.videoStream)||void 0===t?void 0:t.renderElement,raisedHand:r.raisedHand}}),[r.displayName,null===(i=r.videoStream)||void 0===i?void 0:i.isAvailable,null===(n=r.videoStream)||void 0===n?void 0:n.renderElement,s,o,r.raisedHand]),u=(0,e.useMemo)((()=>{var e,t,i;return a?{remoteParticipant:a,onCreateRemoteStreamView:l,onDisposeRemoteStreamView:c,remoteVideoViewOptions:LA,displayName:null==a?void 0:a.displayName,showLabel:!1,showMuteIndicator:!1,isAvailable:null===(e=a.videoStream)||void 0===e?void 0:e.isAvailable,isReceiving:null===(t=a.videoStream)||void 0===t?void 0:t.isReceiving,renderElement:null===(i=a.videoStream)||void 0===i?void 0:i.renderElement,userId:a.userId,key:a.userId}:void 0}),[a,l,c]),h=ip(),p=h.strings.callWithChat.pictureInPictureTileAriaLabel,g=(0,e.useMemo)((()=>({rootAriaLabel:p})),[p]),m=(0,e.useMemo)((()=>({children:u?e.createElement(WS,Object.assign({},u,{strings:h.component.strings.videoGallery})):e.createElement(oy,Object.assign({},d)),orientation:"portrait"})),[d,u,h.component.strings.videoGallery]),f=(0,e.useMemo)((()=>u?{children:e.createElement(oy,Object.assign({},d,{personaMinSize:20})),orientation:"portrait"}:void 0),[d,u]);return e.createElement(PA,{onClick:t.onClick,strings:g,primaryTile:m,secondaryTile:f})},NA={scalingMode:"Crop",isMirrored:!0},LA={scalingMode:"Crop",isMirrored:!1},xA=HE([II,e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.dominantSpeakers}],((e,t)=>{const i=Ob(t);return e&&Object.keys(e).length>0?FA(e,null!=i?i:[]):void 0})),FA=(e,t)=>{let i=t[0];const n=Object.keys(e);return i&&n.includes(i)||(i=n[0]),e[i]},UA=HE([II,e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.spotlight)||void 0===i?void 0:i.spotlightedParticipants}],((e,t)=>{const i=t?t.map((e=>_(e.identifier))):[];return e?BA(e,i):void 0})),BA=(e,t)=>{const i=Object.keys(e),n=t.filter((e=>i.includes(e)));return n[0]?e[n[0]]:void 0},VA=HE([e=>e.displayName,xA,SA,e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.raiseHand.localParticipantRaisedHand},UA],((e,t,i,n,r)=>{let a=t;return r&&(a=r),{localParticipant:{displayName:e,videoStream:i,raisedHand:n},remoteParticipant:a?Nb(HA([a]))[0]:void 0}})),HA=e=>P(e),$A={moveMenuItemText:"Move",closeMenuItemText:"Close",menu:$u,keepInBounds:!0},GA=t=>{var i,n;const r=t.hidden?Rw:ww,a=null===(i=Xm().getState().call)||void 0===i?void 0:i.role,s=ip(),o=fI(VA),[l,c]=(0,e.useState)(null),d=(0,e.useCallback)((e=>{var i;if(l&&1===l.length&&1===e.changedTouches.length){const n=l[0],r=e.changedTouches[0];Math.abs(n.clientX-r.clientX)<10&&Math.abs(n.clientY-r.clientY)<10&&(null===(i=t.onDismissSidePane)||void 0===i||i.call(t))}}),[t,l]),u=(0,e.useCallback)((e=>{c(e.touches)}),[]),h=(0,e.useCallback)((e=>{var i;"Enter"!==e.key&&" "!==e.key||null===(i=t.onDismissSidePane)||void 0===i||i.call(t)}),[t]),p=CE(),g=o.remoteParticipant,m=(0,e.useMemo)((()=>{var i,n,r,l;return"Consumer"===a&&(null==g?void 0:g.userId)?e.createElement(Gs,{tabIndex:0,"aria-label":null!==(n=null===(i=t.strings)||void 0===i?void 0:i.dismissModalAriaLabel)&&void 0!==n?n:"",onKeyDown:h},e.createElement(WS,Object.assign({strings:s.component.strings.videoGallery},g,{remoteParticipant:g}))):e.createElement(Gs,{tabIndex:0,"aria-label":null!==(l=null===(r=t.strings)||void 0===r?void 0:r.dismissModalAriaLabel)&&void 0!==l?l:"",onKeyDown:h},e.createElement(OA,Object.assign({},o,p,{remoteParticipant:g})))}),[a,h,o,t,p,s.component.strings.videoGallery,g]);if("Consumer"===a&&!g)return null;const f=Qa(Aw,null===(n=t.styles)||void 0===n?void 0:n.modal);return e.createElement(Gs,{styles:r},e.createElement(Gs,{onTouchStart:u,onTouchEnd:d},e.createElement(EC,{isOpen:!0,isModeless:!0,dragOptions:$A,styles:f,layerProps:{hostId:t.modalLayerHostId},minDragPosition:t.minDragPosition,maxDragPosition:t.maxDragPosition},!t.hidden&&m)))},jA=t=>{const i=ip();return e.createElement(Gs,{"data-ui-id":"capabilities-changed-notification-bar-stack"},t.capabilitiesChangedNotifications.map((n=>{const r=zA(n,i.strings.call.capabilityChangedNotification);if(!r)return null;const a=WA(n);return e.createElement(vh,{key:n.capabilityName,styles:qA,messageBarType:Ku.warning,dismissIconProps:{iconName:"ErrorBarClear"},onDismiss:()=>t.onDismissNotification(n),messageBarIconProps:a},r)})))},zA=(e,t)=>{var i,n,r,a,s,o;switch(e.capabilityName){case"turnVideoOn":if("MeetingOptionOrOrganizerPolicyChanged"===e.changedReason)return e.isPresent?null===(i=null==t?void 0:t.turnVideoOn)||void 0===i?void 0:i.grantedDueToMeetingOption:null===(n=null==t?void 0:t.turnVideoOn)||void 0===n?void 0:n.lostDueToMeetingOption;break;case"unmuteMic":if("MeetingOptionOrOrganizerPolicyChanged"===e.changedReason)return e.isPresent?null===(r=null==t?void 0:t.unmuteMic)||void 0===r?void 0:r.grantedDueToMeetingOption:null===(a=null==t?void 0:t.unmuteMic)||void 0===a?void 0:a.lostDueToMeetingOption;break;case"shareScreen":if(e.isPresent&&"RoleChanged"===e.changedReason&&"Presenter"===e.role)return null===(s=null==t?void 0:t.shareScreen)||void 0===s?void 0:s.grantedDueToRoleChangeToPresenter;if(!e.isPresent&&"RoleChanged"===e.changedReason&&"Attendee"===e.role)return null===(o=null==t?void 0:t.shareScreen)||void 0===o?void 0:o.lostDueToRoleChangeToAttendee}},WA=e=>{let t;switch(e.capabilityName){case"turnVideoOn":t=e.isPresent?"ControlButtonCameraOn":"ControlButtonCameraProhibited";break;case"unmuteMic":t=e.isPresent?"ControlButtonMicOn":"ControlButtonMicProhibited";break;default:return}return{iconName:t,styles:{root:{"> *":{height:"1rem",width:"1rem"}}}}},qA={innerText:{alignSelf:"center"},icon:{height:0},content:{lineHeight:"inherit"},dismissal:{height:0,paddingTop:"0.8rem"}};var KA=function(e,t,i,n){return new(i||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))};const JA=(t,i,n,r)=>{const a=ip().strings.call;return(0,e.useMemo)((()=>n&&r?{onStartLocalSpotlightWithPrompt:t?YA(t,n,r,a):void 0,onStopLocalSpotlightWithPrompt:i?QA(i,n,r,a):void 0}:{onStartLocalSpotlightWithPrompt:t,onStopLocalSpotlightWithPrompt:i}),[t,i,n,r,a])},YA=(e,t,i,n)=>()=>KA(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.startSpotlightHeading,text:n.spotlightPrompt.startSpotlightOnSelfText,confirmButtonLabel:n.spotlightPrompt.startSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.startSpotlightCancelButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),QA=(e,t,i,n)=>()=>KA(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.stopSpotlightOnSelfHeading,text:n.spotlightPrompt.stopSpotlightOnSelfText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightOnSelfConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),ZA=(t,i,n,r)=>{const a=ip().strings.call;return(0,e.useMemo)((()=>n&&r?{onStartRemoteSpotlightWithPrompt:t?XA(t,n,r,a):void 0,onStopRemoteSpotlightWithPrompt:i?eP(i,n,r,a):void 0}:{onStartRemoteSpotlightWithPrompt:t,onStopRemoteSpotlightWithPrompt:i}),[t,i,n,r,a])},XA=(e,t,i,n)=>r=>KA(void 0,void 0,void 0,(function*(){r.length>1&&e(r),i({heading:n.spotlightPrompt.startSpotlightHeading,text:n.spotlightPrompt.startSpotlightText,confirmButtonLabel:n.spotlightPrompt.startSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.startSpotlightCancelButtonLabel,onConfirm:()=>{e(r),t(!1)},onCancel:()=>t(!1)}),t(!0)})),eP=(e,t,i,n)=>r=>KA(void 0,void 0,void 0,(function*(){r.length>1&&e(r),i({heading:n.spotlightPrompt.stopSpotlightHeading,text:n.spotlightPrompt.stopSpotlightText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,onConfirm:()=>{e(r),t(!1)},onCancel:()=>t(!1)}),t(!0)})),tP=(e,t,i,n)=>()=>KA(void 0,void 0,void 0,(function*(){i({heading:n.spotlightPrompt.stopAllSpotlightHeading,text:n.spotlightPrompt.stopAllSpotlightText,confirmButtonLabel:n.spotlightPrompt.stopSpotlightConfirmButtonLabel,cancelButtonLabel:n.spotlightPrompt.stopSpotlightCancelButtonLabel,onConfirm:()=>{e(),t(!1)},onCancel:()=>t(!1)}),t(!0)})),iP=t=>{var i,n,r,a,s,o,l,c,d,u,h,p;const g=(0,e.useMemo)((()=>t.mobileView?jI:GI),[t.mobileView]),m=Qh(),f=(0,e.useMemo)((()=>(e=>({root:{zIndex:1,width:"100%",background:e}}))(m.palette.neutralLighterAlt)),[m.palette.neutralLighterAlt]),v=(0,e.useRef)(null),S=(0,e.useRef)(null),y=(0,e.useRef)(null),C=af(y),_=sf(y),E=w(fI(sw).callStatus),{updateSidePaneRenderer:T}=t,b="hold"===fI(CI),I=Xm(),[R,A]=(0,e.useState)([]),P=(0,e.useMemo)((()=>{var e;return{updateSidePaneRenderer:T,setDrawerMenuItems:A,inviteLink:t.callControlProps.callInvitationURL,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,onFetchParticipantMenuItems:null===(e=t.callControlProps)||void 0===e?void 0:e.onFetchParticipantMenuItems,mobileView:t.mobileView,peopleButtonRef:v}}),[T,t.callControlProps.callInvitationURL,null===(i=t.callControlProps)||void 0===i?void 0:i.onFetchParticipantMenuItems,t.onFetchAvatarPersonaData,t.mobileView,v]),M=ip(),k=oI(FC),{setPromptProps:D,setIsPromptOpen:O,hideSpotlightButtons:N}=t,{onStartLocalSpotlight:L,onStopLocalSpotlight:x,onStartRemoteSpotlight:F,onStopRemoteSpotlight:U,spotlightedParticipants:B,maxParticipantsToSpotlight:V,localParticipant:H}=k,{onStartLocalSpotlightWithPrompt:$,onStopLocalSpotlightWithPrompt:G}=JA(L,x,O,D),{onStartRemoteSpotlightWithPrompt:j,onStopRemoteSpotlightWithPrompt:z}=ZA(F,U,O,D),W=null===(r=null===(n=I.getState().call)||void 0===n?void 0:n.capabilitiesFeature)||void 0===r?void 0:r.capabilities.removeParticipantsSpotlight.isPresent,q=(0,e.useMemo)((()=>W?()=>I.stopAllSpotlight():void 0),[W,I]),{stopAllSpotlightWithPrompt:K}=((t,i,n)=>{const r=ip().strings.call;return(0,e.useMemo)((()=>i&&n?{stopAllSpotlightWithPrompt:t?tP(t,i,n,r):void 0}:{stopAllSpotlightWithPrompt:t}),[t,i,n,r])})(q,O,D),J=(0,e.useMemo)((()=>({spotlightedParticipantUserIds:B,onStartLocalSpotlight:N?void 0:$,onStopLocalSpotlight:N?void 0:G,onStartRemoteSpotlight:N?void 0:j,onStopRemoteSpotlight:N?void 0:z,onStopAllSpotlight:N?void 0:K,maxParticipantsToSpotlight:V})),[N,V,$,j,G,z,K,B]),{isPeoplePaneOpen:Y,openPeoplePane:Q,closePeoplePane:Z}=(t=>{const{updateSidePaneRenderer:i,inviteLink:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:a,setDrawerMenuItems:s,mobileView:o,peopleButtonRef:l,spotlightedParticipantUserIds:c,onStartLocalSpotlight:d,onStopLocalSpotlight:u,onStartRemoteSpotlight:h,onStopRemoteSpotlight:p,onStopAllSpotlight:g,maxParticipantsToSpotlight:m}=t,f=(0,e.useCallback)((()=>{var e;i(void 0),null===(e=null==l?void 0:l.current)||void 0===e||e.focus()}),[l,i]),v=ip().strings.call,S=(0,e.useMemo)((()=>{const e=[];return g&&c&&c.length>0&&e.push({key:"stopAllSpotlightKey",text:v.stopAllSpotlightMenuLabel,iconProps:{iconName:"StopAllSpotlightMenuButton",styles:{root:{lineHeight:0}}},onClick:()=>{g()},ariaLabel:v.stopAllSpotlightMenuLabel}),{items:e}}),[g,c,v.stopAllSpotlightMenuLabel]),y=(0,e.useCallback)((()=>e.createElement(WR,{onClose:f,headingText:v.peoplePaneTitle,dismissSidePaneButtonAriaLabel:v.dismissSidePaneButtonLabel,mobileView:null!=o&&o})),[o,f,v]),C=(0,e.useCallback)(((e,t,i)=>{const n=null!=i?i:[],r=null==c?void 0:c.find((t=>t===e)),s=t===e;if(r){const t=s?v.stopSpotlightOnSelfMenuLabel:v.stopSpotlightMenuLabel,i=s?u:p?()=>{p([e])}:void 0;i&&t&&n.push({key:"stop-spotlight",text:t,onClick:i,iconProps:{iconName:"StopSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},ariaLabel:t})}else{const t=c&&c.length>0?v.addSpotlightMenuLabel:v.startSpotlightMenuLabel,i=!!m&&!!c&&c.length>=m,r=s?d:h?()=>{h([e])}:void 0;r&&t&&n.push({key:"start-spotlight",text:t,onClick:r,iconProps:{iconName:"StartSpotlightContextualMenuItem",styles:{root:{lineHeight:0}}},ariaLabel:t,disabled:i,title:i?v.spotlightLimitReachedMenuTitle:void 0})}return a?a(e,t,n):n}),[c,d,u,h,p,a,v.stopSpotlightMenuLabel,v.stopSpotlightOnSelfMenuLabel,v.addSpotlightMenuLabel,v.startSpotlightMenuLabel,v.spotlightLimitReachedMenuTitle,m]);let _=a;_=C;const E=(0,e.useCallback)((()=>e.createElement(lA,{inviteLink:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:_,setDrawerMenuItems:s,mobileView:o,participantListHeadingMoreButtonProps:S})),[n,o,r,_,s,S]),T=(0,e.useMemo)((()=>({headerRenderer:y,contentRenderer:E,id:uA})),[E,y]),b=(0,e.useCallback)((()=>{i(T)}),[T,i]),I=BR(uA);return(0,e.useEffect)((()=>{I&&b()}),[I,b]),{openPeoplePane:b,closePeoplePane:f,isPeoplePaneOpen:I}})(Object.assign(Object.assign({},P),J)),X=(0,e.useCallback)((()=>{Y?Z():Q()}),[Z,Y,Q]);(0,e.useEffect)((()=>{b&&T(void 0)}),[T,b,Y,Z]);const ee=UR(),[te,ie]=(0,e.useState)(!ee&&t.mobileView);(0,e.useEffect)((()=>{ee&&t.mobileView?ie(!1):ie(!0)}),[t.mobileView,ee]);const ne={dismissModalAriaLabel:M.strings.call.dismissModalAriaLabel},re=t.mobileView&&ee,ae=(0,e.useMemo)((()=>({display:re?"none":"flex",minWidth:t.mobileView?"unset":"30rem",width:"100%",height:"100%",position:"relative"})),[re,t.mobileView]),se=I.getState().onResolveVideoEffectDependency,{openVideoEffectsPane:oe}=TA(t.updateSidePaneRenderer,t.mobileView,t.latestErrors,t.onDismissError,S),[le,ce]=(0,e.useState)(!1),de=(0,e.useCallback)((()=>{ce(!0)}),[]),ue=(0,e.useCallback)((()=>{ce(!1)}),[]),he=(0,e.useCallback)((()=>{ce(!1),X()}),[X]),pe=(0,e.useMemo)((()=>gR(VI)),[]),ge=null===(a=I.getState().call)||void 0===a?void 0:a.role,me="Consumer"!==ge;let fe=!1!==t.errorBarProps?t.latestErrors:[];const ve=fI(SA).isAvailable;"Consumer"===ge&&t.errorBarProps&&(fe=fe.filter((e=>"callCameraAccessDenied"!==e.type&&"callCameraAccessDeniedSafari"!==e.type)));const Se=BR(EA);!Se&&ve||!t.errorBarProps||(fe=fe.filter((e=>"unableToStartVideoEffect"!==e.type)));const ye="TeamsCaptions"===fI(wI),Ce=fI(AI)||ye,_e="Connected"===fI(SI),Ee=fI(RI),Te=((t,i)=>{const n=(0,e.useRef)(document.getElementById(t)),r=af(n),a=sf(n);return{minDragPosition:(0,e.useMemo)((()=>void 0===r?void 0:{x:Iw-r+88,y:-52}),[r,i]),maxDragPosition:(0,e.useMemo)((()=>void 0===r||void 0===a?void 0:{x:Iw,y:a-52-128}),[a,r,i])}})(t.modalLayerHostId),be=(0,e.useMemo)((()=>(e=>({modal:{main:Object.assign(Object.assign({borderRadius:e.effects.roundedCorner4,boxShadow:e.effects.elevation8,zIndex:2},e.rtl?{left:bm(Iw)}:{right:bm(Iw)}),{top:bm(52)})}}))(m)),[m]),Ie=!!(t.mobileView&&C&&_&&C/_>1),we=t.mobileView?null===(s=t.capabilitiesChangedNotificationBarProps)||void 0===s?void 0:s.capabilitiesChangedNotifications.filter((e=>"shareScreen"!==e.capabilityName)):null===(o=t.capabilitiesChangedNotificationBarProps)||void 0===o?void 0:o.capabilitiesChangedNotifications;return e.createElement("div",{ref:y,className:cn(vT),id:t.id},e.createElement(Gs,{verticalFill:!0,horizontalAlign:"stretch",className:g,"data-ui-id":t.dataUiId},e.createElement(Gs,{reversed:!0,horizontal:Ie,grow:!0,styles:KI(Ie)},!1!==(null===(l=t.callControlProps)||void 0===l?void 0:l.options)&&!re&&e.createElement(Gs,{verticalAlign:"center",className:cn({zIndex:2,padding:Ie?"0.25rem":"unset"})},nP(null===(c=t.callControlProps)||void 0===c?void 0:c.options)?e.createElement(lw,Object.assign({},t.callControlProps,{containerWidth:C,containerHeight:_,isMobile:t.mobileView,peopleButtonChecked:Y,onPeopleButtonClicked:X,displayVertical:Ie})):e.createElement(kw,Object.assign({},t.callControlProps,{callControls:t.callControlProps.options,callAdapter:I,mobileView:t.mobileView,disableButtonsForLobbyPage:E,disableButtonsForHoldScreen:b,peopleButtonChecked:Y,onPeopleButtonClicked:X,onMoreButtonClicked:de,isCaptionsSupported:Ce&&_e||_e,useTeamsCaptions:Ce,isCaptionsOn:Ee,onClickVideoEffects:se?oe:void 0,displayVertical:Ie,onUserSetOverflowGalleryPositionChange:t.onUserSetOverflowGalleryPositionChange,onUserSetGalleryLayout:t.onUserSetGalleryLayoutChange,userSetGalleryLayout:t.userSetGalleryLayout,onSetDialpadPage:t.onSetDialpadPage,dtmfDialerPresent:t.dtmfDialerPresent,peopleButtonRef:v,cameraButtonRef:S,onStopLocalSpotlight:!N&&H.spotlight?G:void 0}))),!1!==(null===(d=t.callControlProps)||void 0===d?void 0:d.options)&&le&&e.createElement(Gs,{styles:pe},e.createElement(dR,{callControls:t.callControlProps.options,onLightDismiss:ue,onPeopleButtonClicked:he,disableButtonsForHoldScreen:b,isCaptionsSupported:Ce&&_e||_e,useTeamsCaptions:Ce,onUserSetGalleryLayout:t.onUserSetGalleryLayoutChange,userSetGalleryLayout:t.userSetGalleryLayout,onSetDialpadPage:t.onSetDialpadPage,dtmfDialerPresent:t.dtmfDialerPresent,reactionResources:I.getState().reactions})),e.createElement(Gs,{horizontal:!0,grow:!0},e.createElement(Gs.Item,{style:ae},e.createElement(Gs.Item,{styles:f,grow:!0},e.createElement(Gs,{verticalFill:!0,styles:zI},e.createElement(Gs.Item,{styles:WI},e.createElement(Gs,{styles:qI},e.createElement(Sf,Object.assign({},t.complianceBannerProps))),!1!==t.errorBarProps&&e.createElement(Gs,{styles:qI},e.createElement(Mh,Object.assign({},t.errorBarProps,{onDismissError:t.onDismissError,activeErrorMessages:fe}))),t.capabilitiesChangedNotificationBarProps&&t.capabilitiesChangedNotificationBarProps.capabilitiesChangedNotifications.length>0&&e.createElement(Gs,{styles:qI},e.createElement(jA,Object.assign({},t.capabilitiesChangedNotificationBarProps,{capabilitiesChangedNotifications:null!=we?we:[]}))),me&&!!t.mutedNotificationProps&&e.createElement(Hw,Object.assign({},t.mutedNotificationProps))),te&&t.onRenderGalleryContent&&t.onRenderGalleryContent(),!b&&e.createElement(fT,{isMobile:t.mobileView,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData,useTeamsCaptions:Ce})))),e.createElement(HR,{mobileView:t.mobileView,maxWidth:Se?"17.5rem":void 0,minWidth:Se?"17.5rem":void 0,updateSidePaneRenderer:t.updateSidePaneRenderer,onPeopleButtonClicked:t.mobileView&&!rP(t.callControlProps.options)?void 0:X,disablePeopleButton:"boolean"!=typeof t.callControlProps.options&&Jt(null===(u=t.callControlProps.options)||void 0===u?void 0:u.participantsButton),onChatButtonClicked:null===(h=t.mobileChatTabHeader)||void 0===h?void 0:h.onClick,disableChatButton:null===(p=t.mobileChatTabHeader)||void 0===p?void 0:p.disabled}),t.mobileView&&e.createElement(GA,{modalLayerHostId:t.modalLayerHostId,hidden:!ee,styles:be,strings:ne,minDragPosition:Te.minDragPosition,maxDragPosition:Te.maxDragPosition,onDismissSidePane:()=>{Z(),t.onCloseChatPane&&t.onCloseChatPane()}}),R.length>0&&e.createElement(Gs,{styles:gR()},e.createElement(jf,{onLightDismiss:()=>A([]),items:R}))))))},nP=e=>!!e&&!0!==e&&!0===(null==e?void 0:e.legacyControlBarExperience),rP=e=>void 0===e||!0===e||!1!==e&&!1!==e.participantsButton&&!1!==e.peopleButton,aP=HE([yI],(e=>({cameras:e.cameras,selectedCamera:e.selectedCamera}))),sP={root:{height:"100%",minHeight:"10rem",minWidth:"6rem"}},oP={scalingMode:"Crop",isMirrored:!0},lP={scalingMode:"Crop"},cP=t=>{var i,n,r;const{pinnedParticipants:a=[],setPinnedParticipants:s,setIsPromptOpen:o,setPromptProps:l,hideSpotlightButtons:c,videoTilesOptions:d}=t,u=oI(FC),h=fI(aP),p=CE(),g=(()=>{const t=ip().strings.call,i=(0,e.useMemo)((()=>({participantJoinedNoticeString:t.participantJoinedNoticeString,twoParticipantJoinedNoticeString:t.twoParticipantJoinedNoticeString,threeParticipantJoinedNoticeString:t.threeParticipantJoinedNoticeString,participantLeftNoticeString:t.participantLeftNoticeString,twoParticipantLeftNoticeString:t.twoParticipantLeftNoticeString,threeParticipantLeftNoticeString:t.threeParticipantLeftNoticeString,unnamedParticipantString:t.unnamedParticipantString,manyParticipantsJoined:t.manyParticipantsJoined,manyParticipantsLeft:t.manyParticipantsLeft,manyUnnamedParticipantsJoined:t.manyUnnamedParticipantsJoined,manyUnnamedParticipantsLeft:t.manyUnnamedParticipantsLeft})),[t]),[n,r]=(0,e.useState)(""),a=fI(mw),s=(0,e.useRef)(a),o=e=>{r(e)};return(0,e.useMemo)((()=>{const e=a.map((e=>_(e.identifier))),t=s.current.map((e=>_(e.identifier))),n=a.filter((e=>!t.includes(_(e.identifier)))),r=s.current.filter((t=>!e.includes(_(t.identifier))));n.length>0&&o(fw("joined",n,i)),r.length>0&&o(fw("left",r,i)),s.current=a}),[a,i]),n})(),m=Xm(),f=null===(i=m.getState().call)||void 0===i?void 0:i.role,v=m.getState().isRoomsCall,S=(0,e.useRef)(null),y=af(S),C=sf(S),E=y&&C?y/C:0,T=m.getState().reactions,b=uP(null===(n=t.localVideoTileOptions)||void 0===n?void 0:n.position),I=(0,e.useMemo)((()=>Object.assign(Object.assign({},p),h)),[p,h]),w=(0,e.useCallback)(((i,n)=>e.createElement(Gs,{className:cn({position:"absolute",height:"100%",width:"100%"})},e.createElement(Gs,{styles:{root:{margin:"auto",maxHeight:"100%"}}},(null==n?void 0:n.coinSize)&&e.createElement(gT,Object.assign({userId:i},n,{dataProvider:t.onFetchAvatarPersonaData}))))),[t.onFetchAvatarPersonaData]),R=(0,e.useMemo)((()=>{var e;return!(null===(e=t.remoteVideoTileMenuOptions)||void 0===e?void 0:e.isHidden)&&(t.isMobile?{kind:"drawer",hostId:t.drawerMenuHostId}:{kind:"contextual"})}),[null===(r=t.remoteVideoTileMenuOptions)||void 0===r?void 0:r.isHidden,t.isMobile,t.drawerMenuHostId]),A=(0,e.useMemo)((()=>y&&C&&y/C>=16/9?"verticalRight":"horizontalBottom"),[y,C]),{onStartLocalSpotlight:P,onStopLocalSpotlight:M,onStartRemoteSpotlight:k,onStopRemoteSpotlight:D}=u,{onStartLocalSpotlightWithPrompt:O,onStopLocalSpotlightWithPrompt:N}=JA(P,M,o,l),{onStartRemoteSpotlightWithPrompt:L,onStopRemoteSpotlightWithPrompt:x}=ZA(k,D,o,l),F=(0,e.useMemo)((()=>s?e=>{a.includes(e)||s(a.concat(e))}:void 0),[s,a]),U=(0,e.useMemo)((()=>s?e=>{s(a.filter((t=>t!==e)))}:void 0),[s,a]),B=(0,e.useMemo)((()=>e.createElement(FC,Object.assign({},u,{videoTilesOptions:d,localVideoViewOptions:oP,remoteVideoViewOptions:lP,styles:sP,layout:t.localVideoTileOptions?b:t.userSetGalleryLayout,showCameraSwitcherInLocalPreview:t.isMobile,localVideoCameraCycleButtonProps:I,onRenderAvatar:w,remoteVideoTileMenu:R,overflowGalleryPosition:A,localVideoTileSize:!1===t.localVideoTileOptions||"Consumer"===f||v&&"Unknown"===f?"hidden":t.isMobile&&E<1?"9:16":"16:9",pinnedParticipants:a,onPinParticipant:F,onUnpinParticipant:U,reactionResources:T,onStartLocalSpotlight:c?void 0:O,onStopLocalSpotlight:c?void 0:N,onStartRemoteSpotlight:c?void 0:L,onStopRemoteSpotlight:c?void 0:x}))),[u,t.isMobile,t.localVideoTileOptions,I,w,R,A,f,v,E,t.userSetGalleryLayout,a,F,U,b,T,O,N,L,x,c,d]);return e.createElement("div",{ref:S,style:dP},e.createElement(zf,{announcementString:g,ariaLive:"polite"}),B)},dP={width:"100%",height:"100%"},uP=e=>"grid"===e?"default":"floatingLocalVideo",hP={root:{height:"100%",width:"100%",position:"relative"}},pP=(e,t)=>({position:"absolute",height:"100%",width:"100%",background:t?"black":e.neutralLighterAlt,opacity:t?.6:1,zIndex:0}),gP={height:"100%",width:"100%",zIndex:1},mP={root:{height:"100%",width:"100%"}},fP=()=>e.createElement(e.Fragment,null),vP={scalingMode:"Crop",isMirrored:!0},SP=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,a=null==n?void 0:n.renderElement,s=Qh().palette;return(0,e.useEffect)((()=>{n&&r&&t.onCreateLocalStreamView&&t.onCreateLocalStreamView(vP).catch((e=>console.log("Can not render video",e)))}),[r,n,t,a]),e.createElement(Gs,{horizontalAlign:"center",verticalAlign:"center",styles:hP,grow:!0},e.createElement(ES,{styles:mP,renderElement:a?e.createElement(Yf,{videoStreamElement:a}):void 0,onRenderPlaceholder:fP},t.overlayContent&&e.createElement(e.Fragment,null,e.createElement(Gs,{className:cn(pP(s,r))}),e.createElement(Gs,{horizontalAlign:"center",verticalAlign:"center",className:cn(gP)},t.overlayContent))))},yP={margin:"1rem",gap:"1.5rem"},CP={gap:"1rem"},_P=(e,t)=>({fontSize:"1.25rem",fontWeight:Mr.semibold,color:t?"white":e.neutralPrimary,textAlign:"center"}),EP=(e,t)=>({fontSize:"1rem",color:t?"white":e.neutralPrimary,textAlign:"center"}),TP=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,a=Qh().palette,s=ip().strings.call,o=CE();return e.createElement(SP,Object.assign({localParticipantVideoStream:t.localParticipantVideoStream,overlayContent:e.createElement(Gs,{verticalFill:!0,horizontalAlign:"center",verticalAlign:"center",className:cn(yP),"aria-atomic":!0},e.createElement(Gs,{horizontal:!0,className:cn(CP)},e.createElement(Hm,{iconName:"NetworkReconnectIcon",className:cn(_P(a,r))}),e.createElement(Cf,{className:cn(_P(a,r)),"aria-live":"assertive"},s.networkReconnectTitle)),e.createElement(Cf,{className:cn(EP(a,r)),"aria-live":"assertive"},s.networkReconnectMoreDetails))},o))},bP=HE([e=>{var t;return!!(null===(t=e.call)||void 0===t?void 0:t.transcription.isTranscriptionActive)},e=>{var t;return!!(null===(t=e.call)||void 0===t?void 0:t.recording.isRecordingActive)}],((e,t)=>({callTranscribeState:e,callRecordState:t}))),IP=HE([bI],(e=>{var t;return{speakingWhileMuted:!!(null===(t=null==e?void 0:e.media.latest.speakingWhileMicrophoneIsMuted)||void 0===t?void 0:t.value)}})),wP=HE([SA],(e=>({localParticipantVideoStream:e}))),RP=HE([bI,wP],((e,t)=>{var i;return{networkReconnectValue:null===(i=null==e?void 0:e.network.latest.networkReconnect)||void 0===i?void 0:i.value,localParticipantVideoStream:t.localParticipantVideoStream}})),AP=e=>Math.floor(PP(e)/60),PP=e=>Math.floor(e/1e3),MP={root:{color:"inherit",fontWeight:600,fontSize:bm(20),lineHeight:bm(28),margin:"auto"}};const kP=t=>{var i,n;const{adapter:r}=t,a=r.getState(),s=xh(),o=null===(i=a.targetCallees)||void 0===i?void 0:i[0],l=null===(n=a.call)||void 0===n?void 0:n.remoteParticipants;let c;if(l){const e=Object.values(l);c=o&&m(o)?o.phoneNumber:e.find((e=>e.identifier===o))}return e.createElement(Gs,{style:{height:"100%",width:"100%",background:s.palette.white}},e.createElement(Gs,{verticalAlign:"center",style:{margin:"auto"}},e.createElement(DP,null),e.createElement(Cf,{style:{margin:"auto"}},c&&"Unnamed participant"!==c?null==c?void 0:c.toString():""),e.createElement(vb,{onSendDtmfTone:e=>{return t=void 0,i=void 0,a=function*(){yield r.sendDtmfTone(e)},new((n=void 0)||(n=Promise))((function(e,r){function s(e){try{l(a.next(e))}catch(e){r(e)}}function o(e){try{l(a.throw(e))}catch(e){r(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n((function(e){e(i)}))).then(s,o)}l((a=a.apply(t,i||[])).next())}));var t,i,n,a},longPressTrigger:t.mobileView?"touch":"mouseAndTouch",dialpadMode:"dtmf",dtmfAudioContext:t.compositeAudioContext})))},DP=()=>{const[t,i]=(0,e.useState)(0),n=(e=>{const t=(e=>Math.floor(AP(e)/60))(e);return`${t>0?t+":":""}${("0"+AP(e)%60).slice(-2)}:${("0"+PP(e)%60).slice(-2)}`})(t),r=fI(MI),a=(0,e.useMemo)((()=>null!=r?r:new Date(Date.now())),[r]);return(0,e.useEffect)((()=>{const e=setInterval((()=>{var e;i(null!==(e=new Date(Date.now()).getTime()-(null==a?void 0:a.getTime()))&&void 0!==e?e:0)}),10);return()=>{clearInterval(e)}}),[a]),e.createElement(Cf,{styles:MP},n)},OP=t=>{const i=Xm();return e.createElement(kP,Object.assign({adapter:i},t,{mobileView:t.mobileView}))},NP=t=>{var i;const{callInvitationURL:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:a,options:s,mobileView:o,galleryLayout:l="floatingLocalVideo",onUserSetGalleryLayoutChange:c,userSetOverflowGalleryPosition:d="Responsive",onSetUserSetOverflowGalleryPosition:u,onCloseChatPane:h,pinnedParticipants:p,setPinnedParticipants:g,compositeAudioContext:m}=t,{callStatus:f}=fI(sw),v=fI(gw),S=CE(),y=fI(bP),C=oI(Mh),_=fI(IP),E=fI(RP),T=fI(mw),b=fI(PI),w=vw(b,T),[R,A]=(0,e.useState)(w),P=ip().strings.call,M=o?zt(null==s?void 0:s.callControls):null==s?void 0:s.callControls,k=fu("drawerMenuHost"),[D,O]=(0,e.useState)(!1),[N,L]=(0,e.useState)();return e.createElement(e.Fragment,null,e.createElement(iP,{id:k,complianceBannerProps:Object.assign(Object.assign({},y),{strings:P}),errorBarProps:!1!==(null==s?void 0:s.errorBar)&&C,mutedNotificationProps:_,callControlProps:{callInvitationURL:n,onFetchParticipantMenuItems:a,options:M,increaseFlyoutItemSize:o},onFetchAvatarPersonaData:r,mobileView:o,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>I(f)?LP(E.networkReconnectValue)?(()=>{var i;return R?e.createElement(OP,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError,capabilitiesChangedNotificationBarProps:t.capabilitiesChangedNotificationBarProps,onSetDialpadPage:()=>A(!R),dtmfDialerPresent:R,compositeAudioContext:m}):e.createElement(cP,Object.assign({isMobile:o},v,S,{onFetchAvatarPersonaData:r,remoteVideoTileMenuOptions:null==s?void 0:s.remoteVideoTileMenuOptions,drawerMenuHostId:k,localVideoTileOptions:null==s?void 0:s.localVideoTile,userSetOverflowGalleryPosition:d,userSetGalleryLayout:l,pinnedParticipants:p,setPinnedParticipants:g,setIsPromptOpen:O,setPromptProps:L,hideSpotlightButtons:null===(i=null==s?void 0:s.spotlight)||void 0===i?void 0:i.hideSpotlightButtons,videoTilesOptions:null==s?void 0:s.videoTilesOptions}))})():e.createElement(TP,Object.assign({},E)):e.createElement(e.Fragment,null),updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:h,dataUiId:"call-page",latestErrors:t.latestErrors,onDismissError:t.onDismissError,onUserSetOverflowGalleryPositionChange:u,onUserSetGalleryLayoutChange:c,userSetGalleryLayout:l,capabilitiesChangedNotificationBarProps:t.capabilitiesChangedNotificationBarProps,onSetDialpadPage:()=>A(!R),dtmfDialerPresent:R,setIsPromptOpen:O,setPromptProps:L,hideSpotlightButtons:null===(i=null==s?void 0:s.spotlight)||void 0===i?void 0:i.hideSpotlightButtons}),e.createElement(uI,Object.assign({isOpen:D,onDismiss:()=>O(!1)},N)))},LP=e=>!0===e||!1===e||void 0===e||e===p.DiagnosticQuality.Good,xP=t=>{const{icon:i,askDevicePermission:n,onClick:r,constrain:a,strings:s,options:o,styles:l}=t;return e.createElement(W_,{"data-ui-id":"permission-dropdown",placeholder:null==s?void 0:s.placeHolderText,label:null==s?void 0:s.label,onRenderPlaceholder:()=>e.createElement(Gs,{horizontal:!0,verticalAlign:"center"},i,e.createElement(Cf,null,null==s?void 0:s.placeHolderText)),onRenderCaretDown:()=>e.createElement(Cf,null,null==s?void 0:s.actionButtonContent),onClick:()=>{n&&n(null!=a?a:{video:!0,audio:!0}),null==r||r()},options:null!=o?o:[],styles:l})},FP={childrenGap:"0.5rem"},UP={childrenGap:"0.5rem"},BP=e=>({caretDownWrapper:{height:"2.25rem",lineHeight:"2.25rem"},dropdownItem:{fontSize:"0.875rem",height:"2.25rem",background:e.palette.white},dropdown:{height:"2.25rem",width:"100%",svg:{verticalAlign:"top"}},title:{fontSize:"0.875rem",height:"2.25rem",lineHeight:"2rem",borderRadius:"0.25rem",border:`1px solid ${e.palette.neutralQuaternaryAlt}`},label:{fontWeight:600,fontSize:"0.875rem",zIndex:1},errorMessage:{fontSize:"0.875rem"}}),VP=cn({overflow:"hidden",textOverflow:"ellipsis",minWidth:"0",maxWidth:"100%",overflowWrap:"break-word",margin:".063rem"}),HP=cn({marginRight:"8px",verticalAlign:"text-top"}),$P={root:{zIndex:1}},GP=t=>{const i=Qh(),n=e.createElement(xP,Object.assign({},t.dropdownProps,{styles:BP(i),constrain:{video:!0,audio:!1},strings:{placeHolderText:"Enable Camera (optional)",actionButtonContent:"Allow"},icon:e.createElement(Hm,{iconName:"ControlButtonCameraOn",style:{height:"1.25rem",marginRight:"0.625rem"}}),onClick:t.onClickEnableDevicePermission}));return t.cameraPermissionGranted?t.cameraGrantedDropdown:n},jP=t=>{const i=Qh(),n=e.createElement(xP,Object.assign({},t.dropdownProps,{styles:BP(i),constrain:{video:!1,audio:!0},strings:{placeHolderText:"Enable Microphone (required)",actionButtonContent:"Allow"},icon:e.createElement(Hm,{iconName:"ControlButtonMicOn",style:{height:"1.25rem",marginRight:"0.625rem"}}),onClick:t.onClickEnableDevicePermission}));return t.micPermissionGranted?t.micGrantedDropdown:n},zP={childrenGap:"1.5rem"},WP={childrenGap:"0.5rem"},qP={childrenGap:"1.5rem"},KP={root:{width:"100%",minWidth:"11rem",maxWidth:"20.625rem"}},JP=(e,t)=>cn({width:"100%",minHeight:t?"auto":"13.625rem",padding:"1rem",borderRadius:e.effects.roundedCorner6,border:`0.0625rem solid ${e.palette.neutralLight}`,overflow:"hidden",boxShadow:e.effects.elevation4,position:"relative",":before":{content:'""',position:"absolute",top:0,bottom:0,left:0,right:0,zIndex:0,background:e.palette.white,opacity:.9}}),YP=e=>cn({fontSize:"1.2rem",lineHeight:"1rem",fontWeight:600},ZP(e)),QP=e=>cn({fontSize:"1.0625rem",lineHeight:"1.375rem",fontWeight:600,textAlign:"center"},ZP(e)),ZP=e=>({textShadow:`0px 0px 8px ${e.palette.whiteTranslucent40}`,fill:e.semanticColors.bodyText,stroke:e.palette.whiteTranslucent40,paintOrder:"stroke fill",strokeWidth:bm(1.5),text:{letterSpacing:"-0.02rem"},"@media (forced-colors: active)":{forcedColorAdjust:"auto",fill:e.palette.neutralQuaternaryAlt,textShadow:"none",stroke:"none"}}),XP={root:{textAlign:"center",maxWidth:bm(700),alignSelf:"center"}},eM=e=>({fontSize:"0.9375",lineHeight:"1.25rem",textShadow:`0px 0px 8px ${e.palette.whiteTranslucent40}`,marginTop:"-0.33rem"}),tM=e=>cn(eM(e)),iM=e=>cn(eM(e),{marginBottom:"0.5rem",textAlign:"center"}),nM={root:{paddingTop:"1.125rem"}},rM={root:{textAlign:"center"}},aM=cn({width:"100%",maxWidth:"unset",borderRadius:"0.25rem"}),sM=cn({borderRadius:"0.25rem",width:"auto",height:"2.25rem"}),oM={root:{alignItems:"center"}},lM=(e,t)=>({root:{background:"transparent",border:"none",color:e.palette.themePrimary,padding:"5px 0.25rem",":hover, :focus":t?{}:{color:e.palette.themePrimary},svg:{height:"1rem",width:"1rem"}},labelHovered:t?{}:{color:e.palette.themePrimary},rootChecked:t?{}:{color:e.palette.themePrimary},rootHovered:t?{}:{color:e.palette.themePrimary},rootPressed:t?{}:{color:e.palette.themePrimary},rootFocused:t?{}:{color:e.palette.themePrimary}}),cM=cn({width:"100%",position:"relative"}),dM={content:{display:"flex",flexBasis:"100%",paddingLeft:"0rem",paddingRight:"0rem"},commands:{paddingTop:"0rem"},scrollableContent:{display:"flex",flexDirection:"column",height:"100%"}},uM={forceFocusInsideTrap:!1},hM=e=>{const t=new Map;for(const i of e)t.set(i.id,i);const i=[];for(const e of t.values())i.push({key:e.id,text:""===e.name?e.deviceType:e.name});return i},pM=(t,i)=>{const n=i&&("Camera"===(r=t)?e.createElement(Hm,{iconName:"LocalDeviceSettingsCamera",className:HP}):"Microphone"===r?e.createElement(Hm,{iconName:"LocalDeviceSettingsMic",className:HP}):"Speaker"===r?e.createElement(Hm,{iconName:"LocalDeviceSettingsSpeaker",className:HP}):void 0);var r;return i?e.createElement("div",{className:VP},n,e.createElement("span",null,i[0].text)):e.createElement(e.Fragment,null)},gM={scalingMode:"Crop",isMirrored:!0},mM=t=>{var i,n,r;const a=Qh(),s=ip(),o=Xm(),l=o.getState().onResolveVideoEffectDependency,c=s.strings.call.defaultPlaceHolder,d=s.strings.call.cameraLabel,u=s.strings.call.soundLabel,h=s.strings.call.noSpeakersLabel,p=s.strings.call.noCamerasLabel,g=s.strings.call.noMicrophonesLabel,m=null===(i=o.getState().call)||void 0===i?void 0:i.role,f=t.cameraPermissionGranted,v=t.microphonePermissionGranted,S="Consumer"!==m,y="Consumer"!==m;(0,e.useEffect)((()=>{f&&o.queryCameras(),v&&o.queryMicrophones(),o.querySpeakers()}),[o,f,v]);const C=CE(),_=t.cameras.length>0,E=t.microphones.length>0,T=t.speakers.length>0,b="safari"===(null===(n=o.getState().environmentInfo)||void 0===n?void 0:n.environment.browser.toLowerCase())&&!T,I=e.createElement(W_,{"data-ui-id":"call-composite-local-camera-settings","aria-labelledby":"call-composite-local-camera-settings-label",placeholder:_?c:p,options:f?hM(t.cameras):[{key:"deniedOrUnknown",text:""}],styles:BP(a),disabled:!f||!_,errorMessage:void 0===t.cameraPermissionGranted||t.cameraPermissionGranted?void 0:s.strings.call.cameraPermissionDenied,defaultSelectedKey:v?t.selectedCamera?t.selectedCamera.id:t.cameras?null===(r=t.cameras[0])||void 0===r?void 0:r.id:"":"deniedOrUnknown",onChange:(e,i,n)=>{t.onSelectCamera(t.cameras[null!=n?n:0],gM)},onRenderTitle:e=>pM("Camera",e)}),w=e.createElement(e.Fragment,null,y&&e.createElement(W_,{"aria-labelledby":"call-composite-local-sound-settings-label",placeholder:E?c:g,styles:BP(a),disabled:!v||!E,errorMessage:void 0===t.microphonePermissionGranted||t.microphonePermissionGranted?void 0:s.strings.call.microphonePermissionDenied,options:v?hM(t.microphones):[{key:"deniedOrUnknown",text:""}],defaultSelectedKey:v?t.selectedMicrophone?t.selectedMicrophone.id:fM(t.microphones):"deniedOrUnknown",onChange:(e,i,n)=>{t.onSelectMicrophone(t.microphones[null!=n?n:0])},onRenderTitle:e=>pM("Microphone",e)})),R=e.createElement(W_,{"aria-labelledby":"call-composite-local-sound-settings-label",placeholder:T?c:h,styles:BP(a),disabled:0===t.speakers.length,options:hM(t.speakers),defaultSelectedKey:t.selectedSpeaker?t.selectedSpeaker.id:fM(t.speakers),onChange:(e,i,n)=>{t.onSelectSpeaker(t.speakers[null!=n?n:0])},onRenderTitle:e=>pM("Speaker",e)});return e.createElement(Gs,{"data-ui-id":"call-composite-device-settings",tokens:FP,styles:$P},S&&e.createElement(Gs,null,e.createElement(Gs,{horizontal:!0,horizontalAlign:"space-between",styles:oM},e.createElement(r_,{id:"call-composite-local-camera-settings-label",className:cn(BP(a).label),disabled:!f},d),l&&e.createElement(yy,{iconProps:{iconName:"ConfigurationScreenVideoEffectsButton"},styles:lM(a,!f),onClick:t.onClickVideoEffects,disabled:!f,"data-ui-id":"call-config-video-effects-button"},s.strings.call.configurationPageVideoEffectsButtonLabel)),e.createElement(GP,{cameraGrantedDropdown:I,cameraPermissionGranted:null!=f&&f,dropdownProps:C,onClickEnableDevicePermission:t.onClickEnableDevicePermission})),e.createElement(Gs,null,e.createElement(r_,{id:"call-composite-local-sound-settings-label",className:cn(BP(a).label),disabled:!v},u),e.createElement(Gs,{"data-ui-id":"call-composite-sound-settings",tokens:UP},e.createElement(jP,{micGrantedDropdown:w,micPermissionGranted:null!=v&&v,dropdownProps:C,onClickEnableDevicePermission:t.onClickEnableDevicePermission}),e.createElement((()=>b?e.createElement(e.Fragment,null):R),null))))},fM=e=>{if(0===e.length)return"";const t=e.find((e=>e.isSystemDefault));return t?t.id:e[0].id},vM=cn({marginRight:"0.375rem",fontSize:"1.375rem"}),SM=cn({fontWeight:600,fontSize:"0.875rem",height:"2.75rem",width:"100%"}),yM={textContainer:{display:"contents"}},CM=t=>{const{rejoinCall:i}=t,n=ip();return e.createElement(rE,Object.assign({},t,{"data-ui-id":"call-composite-start-call-button",className:cn(SM,t.className),styles:yM,text:i?n.strings.call.rejoinCallButtonLabel:n.strings.call.startCallButtonLabel,onRenderIcon:t.hideIcon?void 0:()=>e.createElement(Dp,{className:vM})}))},_M=HE([yI],(e=>({video:e.deviceAccess?e.deviceAccess.video:void 0,audio:e.deviceAccess?e.deviceAccess.audio:void 0}))),EM=HE([yI],(e=>{const t=e.cameras.length>0&&e.unparentedViews.length>0&&e.unparentedViews[0].view;return{videoStreamElement:t?t.target:null}})),TM=e=>({borderRadius:e.effects.roundedCorner6,overflow:"hidden"}),bM=e=>cn(TM(e),{width:"100%",height:"13.625rem",minWidth:"11rem",maxWidth:"20.625rem",border:`0.0625rem solid ${e.palette.neutralLight}`,borderRadius:e.effects.roundedCorner6,boxShadow:e.effects.elevation4}),IM=e=>cn(TM(e),{width:"100%",height:"100%",minHeight:"13.625rem"}),wM=cn({fontSize:"0.75rem"}),RM={root:{"@media (forced-colors: active)":{borderColor:"#FFFFFF",border:"1px solid"}}},AM=e=>({root:{minWidth:e?"unset":bm(75),"@media (forced-colors: active)":{":focus":{border:"1px solid !important"},":focus::after":{border:"unset !important",outline:"unset !important"}}}});const PM=t=>{const i=ip(),n=oI(IT),r=fI(EM),a=oI(yT),{audio:s,video:o}=fI(_M),l=fI(EI),c=Xm(),d=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){l?c.mute():c.unmute()},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[c,l]),u=!a.speakers.length,h=0===a.cameras.length&&0===a.microphones.length&&0===a.speakers.length,p=a.cameras.length>0,g=a.microphones.length>0,m=Qh(),f=(0,e.useCallback)((()=>e.createElement(Gs,{className:cn({width:"100%",height:"100%",marginTop:"-0.8rem"}),verticalAlign:"center"},e.createElement(Gs.Item,{align:"center"},e.createElement(Hm,{iconName:"LocalPreviewPlaceholder",className:cn(wM,{color:m.palette.neutralTertiary})})),e.createElement(Gs.Item,{align:"center"},e.createElement(Cf,{className:cn(wM,{color:m.palette.neutralSecondary})},i.strings.call.cameraTurnedOff)))),[m,i.strings.call.cameraTurnedOff]),v=t.mobileView?{menuStyles:{menuItemStyles:sT}}:void 0;return e.createElement(Gs,{"data-ui-id":"call-composite-local-preview",className:t.mobileView?IM(m):bM(m)},e.createElement(ES,{styles:RM,renderElement:(null==r?void 0:r.videoStreamElement)?e.createElement(Yf,{videoStreamElement:r.videoStreamElement}):void 0,onRenderPlaceholder:f},e.createElement(_T,{layout:"floatingBottom"},e.createElement(wT,{"data-ui-id":"call-composite-local-device-settings-microphone-button",checked:l,onToggleMicrophone:d,disabled:!s||!g,showLabel:!0,strings:t.mobileView?{tooltipOnContent:"",tooltipOffContent:"",tooltipDisabledContent:""}:{},styles:AM(t.mobileView)}),e.createElement(IT,Object.assign({"data-ui-id":"call-composite-local-device-settings-camera-button"},n,{showLabel:!0,disabled:!o||!p,strings:t.mobileView?{tooltipOnContent:"",tooltipOffContent:"",tooltipDisabledContent:"",tooltipVideoLoadingContent:""}:{},styles:AM(t.mobileView)})),t.showDevicesButton&&e.createElement(yT,Object.assign({"data-ui-id":"call-composite-local-device-settings-options-button"},a,{disabled:!s&&!o&&u||h,showLabel:!0,strings:t.mobileView?{tooltipContent:""}:{},styles:v})))))};var MM=vn((function(e,t){return Qa({root:[jr(e,{inset:1,highContrastStyle:{outlineOffset:"-4px",outline:"1px solid Window"},borderColor:"transparent"}),{height:24}]},t)})),kM=function(t){function i(){return null!==t&&t.apply(this,arguments)||this}return bi(i,t),i.prototype.render=function(){var t=this.props,i=t.styles,n=t.theme;return e.createElement(yy,Ii({},this.props,{styles:MM(n,i),onRenderDescription:Ro}))},Ri([qu("MessageBarButton",["theme","styles"],!0)],i)}(e.Component);const DM=e=>({root:{padding:"0.375rem 1.25rem",width:"3.75rem",height:"2rem",background:e.palette.white,border:`1px solid ${e.palette.neutralQuaternaryAlt}`,borderRadius:"0.063rem",color:e.palette.black}}),OM=t=>{var i;const n=xh(),r=_h().strings.errorBar,a=null!==(i=t.strings)&&void 0!==i?i:r,[s,o]=(0,e.useState)([]),{onPermissionsTroubleshootingClick:l,onNetworkingTroubleshootingClick:c,permissionsState:d={camera:"denied",microphone:"denied"},troubleshootingGuideStrings:u}=t;(0,e.useEffect)((()=>o(Th(t.activeErrorMessages,s))),[t.activeErrorMessages,s]);const h=bh(t.activeErrorMessages,s);return e.createElement(Gs,{"data-ui-id":"error-bar-stack"},h.map((i=>{const r=e.createElement("div",null,a[i.type]," ",l&&e.createElement(pf,{onClick:()=>{l(d)},underline:!0},e.createElement("span",null,u.devicePermissionLinkText))),h=e.createElement("div",null,a[i.type]," ",c&&e.createElement(pf,{onClick:c,underline:!0},e.createElement("span",null,u.networkTroubleshootingLinkText)));return e.createElement(vh,Object.assign({},t,{styles:(p=Ih(i.type),{innerText:{paddingTop:p===Ku.warning?"0.15rem":"0.1rem",lineHeight:"none",alignSelf:"center",whiteSpace:"normal"},icon:{marginTop:"0.375rem",marginBottom:"0.375rem",paddingTop:"0.25rem"},content:{lineHeight:"inherit"},dismissal:{height:0,paddingTop:"0.8rem"}}),key:i.type,messageBarType:Ih(i.type),messageBarIconProps:wh(i.type),actions:e.createElement(kM,{text:u.dismissButtonText,styles:DM(n),onClick:()=>{o(Eh(s,i))},ariaLabel:a.dismissButtonAriaLabel}),isMultiline:!1}),NM(i.type,r,h));var p})))},NM=(e,t,i)=>"callNetworkQualityLow"===e?i:t,LM=t=>{const{errorBarProps:i,showTroubleShootingErrorBar:n=!1,onPermissionsTroubleshootingClick:r,onNetworkingTroubleShootingClick:a,permissionsState:s}=t;return n?e.createElement(OM,Object.assign({troubleshootingGuideStrings:{devicePermissionLinkText:"Troubleshooting Camera and Microphone Permissions",networkTroubleshootingLinkText:"Troubleshooting Network Connection",dismissButtonText:"OK"},onPermissionsTroubleshootingClick:r,onNetworkingTroubleshootingClick:a,permissionsState:s},i,{onDismissError:t.onDismissError})):e.createElement(Mh,Object.assign({},i,{onDismissError:t.onDismissError}))},xM={root:{marginTop:"auto",marginBottom:"auto",position:"relative"}},FM={root:{paddingBottom:"1rem"}},UM={root:{margin:"auto",textAlign:"center"}},BM={root:{zIndex:1,margin:"auto"}},VM=e=>({root:{color:e.palette.themeLighterAlt}}),HM={root:{fontWeight:600,fontSize:bm(20),lineHeight:bm(28),paddingBottom:"1rem"}},$M={root:{margin:"auto",fontWeight:400,paddingBottom:bm(22)}},GM={root:{margin:"auto",fontWeight:600,textAlign:"inherit"}},jM={root:{paddingTop:"1.5rem",paddingBottom:"1.5rem",borderRadius:"0.5rem",marginBottom:bm(22)}},zM={childrenGap:"2rem"},WM=t=>{var i,n;const{appName:r,onTroubleshootingClick:a,onPrimaryButtonClick:s,strings:o}=t,l=xh();return e.createElement(Gs,{style:{padding:"2rem",maxWidth:"25.375rem",alignSelf:"center"},"aria-label":null==o?void 0:o.ariaLabel},e.createElement(Gs,{styles:FM,horizontal:!0,horizontalAlign:"center",verticalFill:!0,tokens:zM},t.cameraIconName&&e.createElement(Gs,null,e.createElement(al,{styles:BM,iconName:t.cameraIconName})),t.connectorIconName&&e.createElement(Gs,{styles:xM,horizontal:!0},e.createElement(al,{styles:VM(l),iconName:t.connectorIconName})),t.microphoneIconName&&e.createElement(Gs,null,e.createElement(al,{styles:BM,iconName:t.microphoneIconName}))),e.createElement(Gs,{styles:UM},o&&Ah(null==o?void 0:o.primaryText)&&e.createElement(Cf,{styles:HM},r?ev(o.primaryText,{appName:r}):o.primaryText),o&&Ah(null==o?void 0:o.secondaryText)&&e.createElement(Cf,{styles:$M},null==o?void 0:o.secondaryText),s&&Ah(null==o?void 0:o.primaryButtonText)&&e.createElement(rE,{styles:Xa(jM,null===(i=t.styles)||void 0===i?void 0:i.primaryButton),text:null==o?void 0:o.primaryButtonText,onClick:s}),a&&Ah(null==o?void 0:o.linkText)&&e.createElement(pf,{styles:Xa(GM,null===(n=t.styles)||void 0===n?void 0:n.troubleshootingLink),onClick:a},null==o?void 0:o.linkText)))};function qM(t,i){const n=(0,e.useMemo)((()=>Object.assign(Object.assign({},t||{}),i||{})),[t,i]);if(t||i)return n}const KM=t=>{var i,n,r;const a=_h().strings,s=qM("denied"===t.kind?"safari"===t.browserHint?a.CameraAndMicrophoneSitePermissionsDeniedSafari:a.CameraAndMicrophoneSitePermissionsDenied:"request"===t.kind?a.CameraAndMicrophoneSitePermissionsRequest:a.CameraAndMicrophoneSitePermissionsCheck,t.strings),o=(null!==(i=t.microphoneIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionCameraDenied":"SitePermissionCamera",l=(null!==(n=t.microphoneIconName)&&void 0!==n?n:"denied"===t.kind)?"SitePermissionMicDenied":"SitePermissionMic",c=null!==(r=t.microphoneIconName)&&void 0!==r?r:"SitePermissionsSparkle";return e.createElement(WM,Object.assign({},t,{strings:s,cameraIconName:o,connectorIconName:c,microphoneIconName:l,onPrimaryButtonClick:t.onContinueAnywayClick}))},JM=t=>{var i;const n=_h().strings,r=qM("denied"===t.kind?"safari"===t.browserHint?n.MicrophoneSitePermissionsDeniedSafari:n.MicrophoneSitePermissionsDenied:"request"===t.kind?n.MicrophoneSitePermissionsRequest:n.MicrophoneSitePermissionsCheck,t.strings),a=(null!==(i=t.microphoneIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionMicDenied":"SitePermissionMic";return e.createElement(WM,Object.assign({},t,{strings:r,cameraIconName:a,onPrimaryButtonClick:t.onContinueAnywayClick}))},YM=t=>{var i;const n=_h().strings,r=qM("denied"===t.kind?"safari"===t.browserHint?n.CameraSitePermissionsDeniedSafari:n.CameraSitePermissionsDenied:"request"===t.kind?n.CameraSitePermissionsRequest:n.CameraSitePermissionsCheck,t.strings),a=(null!==(i=t.cameraIconName)&&void 0!==i?i:"denied"===t.kind)?"SitePermissionCameraDenied":"SitePermissionCamera";return e.createElement(WM,Object.assign({},t,{strings:r,microphoneIconName:a,onPrimaryButtonClick:t.onContinueAnywayClick}))},QM=t=>{const{mobileView:i,permissionsState:n,environmentInfo:r,isPermissionsModalDismissed:a,setIsPermissionsModalDismissed:s,onPermissionsTroubleshootingClick:o}=t,l=n.camera,c=n.microphone,d="denied"===l||"prompt"===l||"denied"===c||"prompt"===c,u=Qt(r),h=d?()=>"prompt"===l&&"prompt"===c?e.createElement(KM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"request"}):"prompt"===l?e.createElement(YM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,onContinueAnywayClick:()=>{s(!1)},kind:"request"}):"prompt"===c?e.createElement(JM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"request"}):"denied"===l&&"denied"===c?e.createElement(KM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"denied"}):"denied"===l?e.createElement(YM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,onContinueAnywayClick:()=>{s(!1)},kind:"denied"}):e.createElement(JM,{appName:"app",browserHint:u?"safari":"unset",onTroubleshootingClick:o?()=>{o(n)}:void 0,kind:"denied"}):void 0;return i&&void 0!==h?e.createElement(e.Fragment,null,a&&e.createElement(Bf,{disableMaxHeight:!0,onLightDismiss:()=>{},styles:gR(99)},h())):i||void 0===h?e.createElement(e.Fragment,null):e.createElement(EC,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:a,isBlocking:!1,onDismiss:()=>{s(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}}},h())},ZM=t=>{const{mobileView:i,checkPermissionModalShowing:n,permissionsState:r,environmentInfo:a,isPermissionsModalDismissed:s,setIsPermissionsModalDismissed:o,onPermissionsTroubleshootingClick:l}=t,c=()=>{},d=r.camera,u=r.microphone,h="denied"===d||"denied"===u,p=Qt(a),g=h?()=>"denied"===d&&"denied"===u?e.createElement(KM,{appName:"app",browserHint:p?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"denied"}):"denied"===d&&"granted"===u?e.createElement(YM,{appName:"app",browserHint:p?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,onContinueAnywayClick:()=>{o(!1)},kind:"denied"}):e.createElement(JM,{appName:"app",browserHint:p?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"denied"}):void 0;return i?e.createElement(e.Fragment,null,(n||"prompt"===u||"prompt"===d)&&e.createElement(Bf,{disableMaxHeight:!0,onLightDismiss:c,styles:gR(99)},e.createElement(KM,{appName:"app",browserHint:p?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"check"})),s&&!n&&void 0!==g&&e.createElement(Bf,{disableMaxHeight:!0,onLightDismiss:c,styles:gR(99)},g())):e.createElement(e.Fragment,null,(n||"prompt"===u||"prompt"===d)&&e.createElement(EC,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:s,isBlocking:!1,onDismiss:()=>{o(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}}},e.createElement(KM,{appName:"app",browserHint:p?"safari":"unset",onTroubleshootingClick:l?()=>{l(r)}:void 0,kind:"check"})),!n&&void 0!==g&&e.createElement(EC,{styles:{root:{position:"unset"},main:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)"}},layerProps:{hostId:t.modalLayerHostId},isOpen:s,isBlocking:!1,onDismiss:()=>{o(!1)},overlay:{styles:{root:{background:"rgba(0,0,0,0.4)"}}}},g()))},XM=t=>{const{width:i,text:n,lineHeightPx:r,bufferHeightPx:a}=t,s=(0,e.useRef)(null),o=(0,e.useRef)(null),l=(0,e.useRef)(null),[c,d]=(0,e.useState)(0);return(0,e.useLayoutEffect)((()=>{if(n&&o.current&&l.current){const e=ek(o.current,l.current,i,r);d(e*r)}}),[i,r,n]),e.createElement("svg",{width:i,height:c+a,ref:s,xmlns:"http://www.w3.org/2000/svg"},e.createElement("text",{height:0,ref:o,style:{visibility:"hidden"}},n),e.createElement("text",{ref:l,x:"0",y:a/4,role:"heading","aria-level":1}))},ek=(e,t,i,n)=>{var r,a;const s=null!==(a=null===(r=e.textContent)||void 0===r?void 0:r.split(" "))&&void 0!==a?a:[];if(0===s.length||""===s[0])throw new Error("Text element must contain text");let o="",l=0;t.textContent="";for(let r=0;r<s.length;r++){const a=o+s[r]+" ";if(e.getSubStringLength(0,a.length)>i&&r>0){const e=tk(o,n);t.appendChild(e),o=s[r]+" ",l++}else o=a}const c=tk(o,n);return t.appendChild(c),l++,l},tk=(e,t)=>{const i=document.createElementNS("http://www.w3.org/2000/svg","tspan");return i.textContent=e,i.setAttribute("x","50%"),i.setAttribute("dy",`${t}px`),i.setAttribute("text-anchor","middle"),i};const ik=t=>{var i,n,r,a;const{startCallHandler:s,mobileView:o,modalLayerHostId:l,deviceChecks:c,onPermissionsTroubleshootingClick:d,onNetworkingTroubleShootingClick:u}=t,h=Qh(),p=gE(rI(yT)),g=CE(),{video:m,audio:f}=fI(_M),[v,S]=(0,e.useState)(void 0),[y,C]=(0,e.useState)(void 0);((e,t)=>{Ht(void 0,void 0,void 0,(function*(){const[i,n]=yield Promise.all([Ht(void 0,void 0,void 0,(function*(){try{return(yield navigator.permissions.query({name:"camera"})).state}catch(e){return console.info("permissions API is not supported by browser",e),"unsupported"}})),Ht(void 0,void 0,void 0,(function*(){try{return(yield navigator.permissions.query({name:"microphone"})).state}catch(e){return console.info("permissions API is not supported by browser",e),"unsupported"}}))]);e(i),t(n)}))})(S,C);const _=oI(Mh),E=Xm(),T=E.getState().devices,b=E.getState().environmentInfo;let I=!f||0===(null===(i=T.microphones)||void 0===i?void 0:i.length);const w=null===(n=E.getState().call)||void 0===n?void 0:n.role,R=fI(SA).isAvailable;let A=t.latestErrors;"Consumer"!==w&&(A=A.filter((e=>"callCameraAccessDenied"!==e.type&&"callCameraAccessDeniedSafari"!==e.type))),!BR("videoeffects")&&R||!_||(A=A.filter((e=>"unableToStartVideoEffect"!==e.type))),"Consumer"===w&&(I=!1),c&&(["doNotPrompt","optional"].includes(c.camera)&&["doNotPrompt","optional"].includes(c.microphone)?I=!1:"required"===c.camera&&(I=!m||0===(null===(r=T.cameras)||void 0===r?void 0:r.length)));const P=ip(),M=P.strings.call.configurationPageTitle.length>0?e.createElement(Gs.Item,{className:o?QP(h):YP(h)},e.createElement(XM,{width:o?325:445,lineHeightPx:24,bufferHeightPx:16,text:P.strings.call.configurationPageTitle})):e.createElement(e.Fragment,null),k=P.strings.call.configurationPageCallDetails&&e.createElement(Gs.Item,{className:o?iM(h):tM(h)},P.strings.call.configurationPageCallDetails),D=o&&"Consumer"!==w,O={camera:v&&"unsupported"!==v?!1!==m?v:"denied":!1!==m?m?"granted":"prompt":"denied",microphone:y&&"unsupported"!==y?!1!==f?y:"denied":!1!==f?f?"granted":"prompt":"denied"},N=_.activeErrorMessages.filter((e=>"callNetworkQualityLow"===e.type)),[L,x]=(0,e.useState)(!0),[F,U]=(0,e.useState)(!1);setTimeout((()=>{U(!0)}),2e3);const B=!F,{toggleVideoEffectsPane:V,closeVideoEffectsPane:H,isVideoEffectsPaneOpen:$}=TA(t.updateSidePaneRenderer,o,t.latestErrors,t.onDismissError),G=(0,e.useCallback)((()=>{return e=void 0,t=void 0,n=function*(){H(),s()},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}));var e,t,i,n}),[s,H]),j=(0,e.useMemo)((()=>({hostId:l})),[l]),z=(0,e.useMemo)((()=>Object.assign(Object.assign({},_),{activeErrorMessages:A})),[_,A]),W=(0,e.useMemo)((()=>{var e,i,n;return{root:{height:"100%",width:"100%",padding:(i=!o)?"2rem 1rem 2rem 1rem":"1rem 1rem 2rem 1rem",minWidth:i?"25rem":"16rem",minHeight:i?"22rem":"13rem","::before":(n=null===(e=t.backgroundImage)||void 0===e?void 0:e.url)?Object.assign({content:'""',position:"absolute",top:0,left:0,zIndex:0,width:"100%",height:"100%",backgroundImage:`url(${n})`,backgroundSize:"cover",backgroundPosition:"center"},_r.fadeIn500):void 0}}}),[o,null===(a=t.backgroundImage)||void 0===a?void 0:a.url]);return e.createElement(Gs,{styles:W},e.createElement(Gs,{styles:qI},e.createElement(LM,{showTroubleShootingErrorBar:!m||!f||N.length>0,permissionsState:O,onNetworkingTroubleShootingClick:u,onPermissionsTroubleshootingClick:d,errorBarProps:z,onDismissError:t.onDismissError})),v&&"unsupported"!==v&&y&&"unsupported"!==y&&e.createElement(QM,{modalLayerHostId:l,mobileView:o,environmentInfo:b,permissionsState:O,isPermissionsModalDismissed:L,setIsPermissionsModalDismissed:x,onPermissionsTroubleshootingClick:d}),v&&y&&("unsupported"===v||"unsupported"===y)&&e.createElement(ZM,{modalLayerHostId:l,mobileView:o,checkPermissionModalShowing:B,permissionsState:O,isPermissionsModalDismissed:L,environmentInfo:b,setIsPermissionsModalDismissed:x,onPermissionsTroubleshootingClick:d}),e.createElement(Gs,{verticalFill:!0,grow:!0,horizontal:!0,className:cM},e.createElement(Gs,{className:(q=D,K=!!t.logo,cn({width:"100%",position:"relative",height:`calc(100% - ${!q&&K?"3rem":"0rem"})`})),verticalAlign:"center",verticalFill:D,tokens:D?WP:zP},e.createElement(Gs.Item,{styles:XP},e.createElement(sk,{logo:t.logo}),M,k),e.createElement(Gs,{horizontal:!D,horizontalAlign:D?"stretch":"center",verticalFill:D,tokens:qP},nk(D,!("Consumer"!==w)),e.createElement(Gs,{styles:o?void 0:KP},!D&&e.createElement(Gs,{className:o?void 0:JP(h,ok(b))},e.createElement(mM,Object.assign({},p,g,{cameraPermissionGranted:rk(m,v),microphonePermissionGranted:ak(f,y),onClickEnableDevicePermission:()=>{x(!0)},onClickVideoEffects:V}))),e.createElement(Gs,{styles:D?rM:nM,horizontalAlign:D?"stretch":"end"},e.createElement(CM,{className:D?aM:sM,onClick:G,disabled:I,hideIcon:!0}))))),e.createElement(E_,{isOpen:$,hasCloseButton:!1,isBlocking:!1,isHiddenOnDismiss:!1,styles:dM,focusTrapZoneProps:uM,layerProps:j,type:e_.custom,customWidth:"17.5rem"},e.createElement(HR,{mobileView:t.mobileView,updateSidePaneRenderer:t.updateSidePaneRenderer,maxWidth:"17.5rem",minWidth:"17.5rem"}))));var q,K},nk=(t,i)=>{if(!i)return e.createElement(PM,{mobileView:t,showDevicesButton:t})},rk=(e,t)=>t&&"unsupported"!==t?"granted"===t:e,ak=(e,t)=>t&&"unsupported"!==t?"granted"===t:e,sk=t=>{return t.logo?e.createElement(Zo,{styles:(i=t.logo.shape,{root:{overflow:"initial",display:"flex",justifyContent:"center"},image:{height:"3rem",borderRadius:"circle"===i?"100%":void 0,aspectRatio:"circle"===i?"1 / 1":void 0,objectFit:"circle"===i?"cover":void 0}}),src:t.logo.url,alt:t.logo.alt}):e.createElement(e.Fragment,null);var i},ok=e=>e&&"safari"===(null==e?void 0:e.environment.browser.toLowerCase()),lk={maxWidth:"22.5rem",margin:"1rem"},ck={childrenGap:"0.5rem"},dk={root:{paddingTop:"1.125rem",borderRadius:"0.25rem"}},uk={fontSize:"1.25rem",fontWeight:600},hk={fontSize:"1rem"};function pk(t){const i=Xm(),n=fI(PI);return e.createElement(Gs,{className:cn(t.pageStyle),verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":t.dataUiId,"aria-atomic":!0},e.createElement(Gs,{className:cn(lk),tokens:ck},t.iconName&&e.createElement(Hm,{iconName:t.iconName}),e.createElement(Cf,{className:cn(uk),"aria-live":"assertive"},t.title),e.createElement(Cf,{className:cn(hk),"aria-live":"assertive"},t.moreDetails),!t.disableStartCallButton&&e.createElement(Gs,{styles:dk},e.createElement(CM,{onClick:()=>{n&&n.length>0?i.startCall(n):i.joinCall()},disabled:!1,rejoinCall:!0,autoFocus:!0}))))}const gk={margin:"1rem"},mk=(e,t)=>({fontSize:"1rem",color:t?"white":e.themePrimary,textAlign:"center"}),fk=(e,t)=>({fontSize:"0.75rem",color:t?"white":e.themePrimary,textAlign:"center"}),vk={root:{position:"absolute",top:"0rem",right:"0rem"}},Sk=t=>{var i;const n=t.localParticipantVideoStream,r=null!==(i=null==n?void 0:n.isAvailable)&&void 0!==i&&i,a=fI(aP),s=CE(),o=Qh().palette,l=CE();return e.createElement(SP,Object.assign({localParticipantVideoStream:t.localParticipantVideoStream,overlayContent:t.overlayProps?e.createElement(Gs,{verticalFill:!0,horizontalAlign:"center",verticalAlign:"center",className:cn(gk),"aria-atomic":!0},t.showLocalVideoCameraCycleButton&&r&&e.createElement(Gs.Item,{styles:vk},e.createElement(sy,Object.assign({},s,a,{size:"large"}))),e.createElement(Gs.Item,{className:cn(mk(o,r))},t.overlayProps.overlayIcon),e.createElement(Cf,{className:cn(mk(o,r)),"aria-live":"assertive","data-ui-id":"lobbyScreenTitle"},t.overlayProps.title),t.overlayProps.moreDetails&&e.createElement(Cf,{className:cn(fk(o,r)),"aria-live":"assertive"},t.overlayProps.moreDetails)):void 0},l))},yk=t=>{var i,n,r,a;const s=oI(Mh),o=fI(wP),l=ip().strings.call,c="InLobby"===fI(SI),d=null!==(i=fI(II))&&void 0!==i?i:{};let u=t.mobileView?zt(null===(n=t.options)||void 0===n?void 0:n.callControls):null===(r=t.options)||void 0===r?void 0:r.callControls;return u=Kt(u,["screenShareButton","participantsButton"]),e.createElement(iP,{complianceBannerProps:{strings:l},errorBarProps:!1!==(null===(a=t.options)||void 0===a?void 0:a.errorBar)&&s,callControlProps:{options:u,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(Sk,Object.assign({},o,{showLocalVideoCameraCycleButton:t.mobileView,overlayProps:Ck(l,c,Object.values(d))})),dataUiId:"lobby-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError})},Ck=(e,t,i)=>{const n=i[0]&&["Ringing","Connecting"].includes(i[0].state)&&1===i.length?i[0]:void 0;return t?Ek(e):n?Tk(e,n):_k(e)},_k=t=>({title:t.lobbyScreenConnectingToCallTitle,moreDetails:t.lobbyScreenConnectingToCallMoreDetails,overlayIcon:e.createElement(Hm,{iconName:"LobbyScreenConnectingToCall"})}),Ek=t=>({title:t.lobbyScreenWaitingToBeAdmittedTitle,moreDetails:t.lobbyScreenWaitingToBeAdmittedMoreDetails,overlayIcon:e.createElement(Hm,{iconName:"LobbyScreenWaitingToBeAdmitted"})}),Tk=(e,t)=>{var i;return m(t.identifier)?{title:t.identifier.phoneNumber,moreDetails:e.outboundCallingNoticeString}:{title:null!==(i=e.outboundCallingNoticeString)&&void 0!==i?i:""}},bk={width:"100%",height:"100%"},Ik={opacity:.4},wk={position:"absolute",top:"0",left:"0",width:"100%",height:"100%",minWidth:"100%",minHeight:"100%",objectPosition:"center",objectFit:"cover",zIndex:0},Rk={width:"100%",position:"absolute",top:"50%",transform:"translate(0, -50%)",display:"flex",justifyContent:"center"},Ak={root:{margin:"auto"}},Pk={textAlign:"center",fontSize:"1.5rem",fontWeight:400},Mk={circle:{borderWidth:"0.125rem"}},kk={textAlign:"center",fontSize:"1rem"},Dk=t=>{var i,n,r,a,s;const o=oI(Mh),l=ip().strings.call,c=fI(II),d=fI(_I),[u,h]=(0,e.useState)(void 0),p=t.mobileView?zt(null===(i=t.options)||void 0===i?void 0:i.callControls):null===(n=t.options)||void 0===n?void 0:n.callControls,g=(0,e.useMemo)((()=>{var e;return c?null===(e=Object.values(c))||void 0===e?void 0:e[0]:void 0}),[c]),m=(0,e.useMemo)((()=>{var e;return(null==d?void 0:d.remoteParticipants)?null===(e=Object.values(d.remoteParticipants))||void 0===e?void 0:e[0]:void 0}),[d]),f=(0,e.useMemo)((()=>d&&(null==m?void 0:m.displayName)?"transferTarget":"transferor"),[d,null==m?void 0:m.displayName]);(0,e.useEffect)((()=>{h(l.transferPageNoticeString)}),[l.transferPageNoticeString]);let v=g;"transferTarget"===f&&(v=m);let S=null!==(r=null==g?void 0:g.displayName)&&void 0!==r?r:l.transferPageUnknownTransferorDisplayName;return"transferTarget"===f&&(S=null!==(a=null==m?void 0:m.displayName)&&void 0!==a?a:l.transferPageUnknownTransferTargetDisplayName),e.createElement(Gs,{className:cn(bk)},e.createElement(zf,{announcementString:u,ariaLive:"polite"}),e.createElement(iP,{complianceBannerProps:{strings:l},errorBarProps:!1!==(null===(s=t.options)||void 0===s?void 0:s.errorBar)&&o,callControlProps:{options:p,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(Ok,{userId:v?_(null==v?void 0:v.identifier):void 0,displayName:S,initialsName:S,statusText:"transferTarget"===f?l.transferPageTransferTargetText:l.transferPageTransferorText,onFetchAvatarPersonaData:t.onFetchAvatarPersonaData}),dataUiId:"transfer-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError}))},Ok=t=>{const{displayName:i,initialsName:n,userId:r,onFetchAvatarPersonaData:a,statusText:s}=t,[o,l]=(0,e.useState)(),c=(0,e.useRef)(null),d=(0,e.useRef)(new ResizeObserver((e=>{const{width:t,height:i}=e[0].contentRect,n=Math.min(t,i)/2;l(Math.max(Math.min(n,150),32))})));(0,e.useLayoutEffect)((()=>{c.current&&d.current.observe(c.current);const e=d.current;return()=>e.disconnect()}),[d,c]);const u=(0,e.useMemo)((()=>({userId:r,text:null!=n?n:i,coinSize:o,styles:Ak,hidePersonaDetails:!0})),[r,n,i,o]),h=(0,e.useCallback)((()=>o?e.createElement(gT,Object.assign({},u,{dataProvider:a,className:cn(Ik)})):e.createElement(e.Fragment,null)),[u,a,o]),p=(0,e.useMemo)((()=>h()),[h]);return e.createElement("div",{ref:c,className:cn(wk),"data-is-focusable":!0},e.createElement(Gs,{className:cn(Rk),tokens:{childrenGap:"1rem"}},e.createElement(Gs,{horizontalAlign:"center",tokens:{childrenGap:"0.5rem"}},p,e.createElement(Cf,{className:cn(Pk)},i)),e.createElement(Gs,{horizontal:!0,horizontalAlign:"center",verticalAlign:"center",tokens:{childrenGap:"0.5rem"}},e.createElement(Fm,{size:km.large,className:cn(Mk)}),e.createElement(Cf,{className:cn(kk)},s))))},Nk={root:{borderRadius:bm(4),padding:`${bm(6)} ${bm(20)} `},label:{fontWeight:400,display:"flex",fontSize:bm(14)},labelDisabled:{fontWeight:400,display:"flex",fontSize:bm(14)}},Lk={root:{color:"inherit",fontWeight:600,fontHeight:bm(22),fontSize:bm(16),marginTop:"0.5rem",marginBottom:"1.5rem"}},xk={root:{color:"inherit",fontWeight:600,fontSize:bm(20),lineHeight:bm(28),margin:"auto"}},Fk={root:{width:"100%",height:"100%",background:"inherit"}},Uk={root:{display:"flex",margin:"auto",flexDirection:"column",justifyContent:"center",alignContent:"center",alignItems:"center"}};const Bk=()=>{const t=oI(ET),i=ip(),n=Gk(i),[r,a]=(0,e.useState)(0),s=$k(r),o=(0,e.useRef)(performance.now()),[l,c]=(0,e.useState)(!1);return e.useEffect((()=>{const e=setInterval((()=>{a(performance.now()-o.current)}),10);return()=>{clearInterval(e)}}),[o]),e.createElement(Gs,{styles:Fk},e.createElement(Gs,{horizontal:!0,styles:Uk},e.createElement(Cf,{styles:xk},s),e.createElement(Cf,{styles:Lk},n.holdScreenLabel),e.createElement(rE,{text:l?n.resumingCallButtonLabel:n.resumeCallButtonLabel,ariaLabel:l?n.resumingCallButtonAriaLabel:n.resumeCallButtonAriaLabel,styles:Nk,disabled:l,onClick:()=>{return e=void 0,i=void 0,r=function*(){c(!0);try{yield t.onToggleHold()}catch(e){throw c(!1),e}},new((n=void 0)||(n=Promise))((function(t,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var i;e.done?t(e.value):(i=e.value,i instanceof n?i:new n((function(e){e(i)}))).then(s,o)}l((r=r.apply(e,i||[])).next())}));var e,i,n,r},"data-ui-id":"hold-page-resume-call-button",autoFocus:!0})))},Vk=e=>Math.floor(Hk(e)/60),Hk=e=>Math.floor(e/1e3),$k=e=>{const t=(e=>Math.floor(Vk(e)/60))(e);return`${t>0?t+":":""}${("0"+Vk(e)%60).slice(-2)}:${("0"+Hk(e)%60).slice(-2)}`},Gk=e=>({holdScreenLabel:e.strings.call.holdScreenLabel,resumeCallButtonLabel:e.strings.call.resumeCallButtonLabel,resumeCallButtonAriaLabel:e.strings.call.resumeCallButtonAriaLabel,resumingCallButtonLabel:e.strings.call.resumingCallButtonLabel,resumingCallButtonAriaLabel:e.strings.call.resumingCallButtonAriaLabel}),jk=t=>{var i,n,r;const a=oI(Mh),s=ip().strings.call;let o=t.mobileView?zt(null===(i=t.options)||void 0===i?void 0:i.callControls):null===(n=t.options)||void 0===n?void 0:n.callControls;return o=Kt(o,["cameraButton","microphoneButton","devicesButton","screenShareButton","holdButton"]),e.createElement(iP,{complianceBannerProps:{strings:s},errorBarProps:!1!==(null===(r=t.options)||void 0===r?void 0:r.errorBar)&&a,callControlProps:{options:o,increaseFlyoutItemSize:t.mobileView},mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,onRenderGalleryContent:()=>e.createElement(Bk,null),dataUiId:"hold-page",updateSidePaneRenderer:t.updateSidePaneRenderer,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:t.latestErrors,onDismissError:t.onDismissError})},zk={root:{fontWeight:600,fontSize:bm(20),lineHeight:bm(28),margin:"auto",textAlign:"center",padding:"0.5rem"}},Wk={root:{margin:"auto",fontWeight:400,textAlign:"center"}},qk={root:{margin:"auto"}},Kk={root:{margin:"auto",fontWeight:600,textAlign:"center"}},Jk={root:{maxWidth:bm(375),padding:"2rem"}},Yk=e=>({root:{backgroundColor:"#C4314B",borderColor:e.palette.neutralLight,color:e.palette.white,padding:"1rem"}}),Qk=t=>{const{onTroubleshootingClick:i,strings:n,onContinueAnywayClick:r}=t,a=Qh();return e.createElement(Gs,{styles:Jk,tokens:{childrenGap:"2rem"}},e.createElement(al,{iconName:"UnsupportedEnvironmentWarning","data-ui-id":"unsupported-environment-icon"}),e.createElement(Gs,{styles:qk,tokens:{childrenGap:"0.25rem"}},e.createElement(Cf,{styles:zk},null==n?void 0:n.primaryText),e.createElement(Cf,{styles:Wk},null==n?void 0:n.secondaryText)),i&&e.createElement(pf,{styles:Kk,onClick:i,"data-ui-id":"unsupported-environment-link"},null==n?void 0:n.moreHelpLinkText),r&&e.createElement(yy,{"data-ui-id":"allowUnsupportedBrowserButton",styles:Yk(a),onClick:r},null==n?void 0:n.continueAnywayButtonText))},Zk=t=>e.createElement(Qk,Object.assign({},t)),Xk=t=>{const{onTroubleshootingClick:i,strings:n}=t,r=_h();return e.createElement(Zk,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},eD(r)),n)})},eD=e=>e.strings.UnsupportedOperatingSystem,tD=t=>{const{onTroubleshootingClick:i,strings:n}=t,r=_h();return e.createElement(Zk,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},iD(r)),n)})},iD=e=>e.strings.UnsupportedBrowser,nD=t=>{const{onTroubleshootingClick:i,strings:n,onContinueAnywayClick:r}=t,a=_h();return e.createElement(Zk,{onTroubleshootingClick:i,strings:Object.assign(Object.assign({},rD(a)),n),onContinueAnywayClick:r})},rD=e=>e.strings.UnsupportedBrowserVersion,aD=t=>{const{onTroubleshootingClick:i,environmentInfo:n}=t,r=Xm(),a=()=>{r.allowUnsupportedBrowserVersion()},s=ip(),o=s.component.strings.UnsupportedBrowser,l=s.component.strings.UnsupportedBrowserVersion,c=s.component.strings.UnsupportedOperatingSystem;let d=e.createElement(e.Fragment,null);if(null==n?void 0:n.isSupportedPlatform)if(null==n?void 0:n.isSupportedBrowser){if(null==n?void 0:n.isSupportedBrowserVersion)throw new Error("There was a problem with your environment info");d=e.createElement(nD,{onTroubleshootingClick:i,strings:l,onContinueAnywayClick:a})}else d=e.createElement(tD,{onTroubleshootingClick:i,strings:o});else d=e.createElement(Xk,{onTroubleshootingClick:i,strings:c});return e.createElement(Gs,{styles:sD},d)},sD={root:{margin:"auto",paddingTop:"3rem"}},oD=HE([e=>e.devices.cameras,e=>e.devices.microphones],((e,t)=>({camerasCount:e.length,microphonesCount:t.length}))),lD=HE([e=>{var t,i;return null===(i=null===(t=e.call)||void 0===t?void 0:t.capabilitiesFeature)||void 0===i?void 0:i.latestCapabilitiesChangeInfo},e=>{var t;return null===(t=e.call)||void 0===t?void 0:t.role}],((e,t)=>({capabilitiesChangeInfo:e,participantRole:t})));var cD={root:"ms-RatingStar-root",rootIsSmall:"ms-RatingStar-root--small",rootIsLarge:"ms-RatingStar-root--large",ratingStar:"ms-RatingStar-container",ratingStarBack:"ms-RatingStar-back",ratingStarFront:"ms-RatingStar-front",ratingButton:"ms-Rating-button",ratingStarIsSmall:"ms-Rating--small",ratingStartIsLarge:"ms-Rating--large",labelText:"ms-Rating-labelText",ratingFocusZone:"ms-Rating-focuszone"};function dD(e,t){var i;return{color:e,selectors:(i={},i[Nr]={color:t},i)}}var uD,hD=/[\{\}]/g,pD=/\{\d+\}/g;!function(e){e[e.Small=0]="Small",e[e.Large=1]="Large"}(uD||(uD={}));var gD=Ys(),mD=function(t){return e.createElement("div",{className:t.classNames.ratingStar},e.createElement(al,{className:t.classNames.ratingStarBack,iconName:0===t.fillPercentage||100===t.fillPercentage?t.icon:t.unselectedIcon}),!t.disabled&&e.createElement(al,{className:t.classNames.ratingStarFront,iconName:t.icon,style:{width:t.fillPercentage+"%"}}))},fD=function(e,t){return"".concat(e,"-star-").concat(t-1)},vD=e.forwardRef((function(t,i){var n=fu("Rating"),r=fu("RatingLabel"),a=t.ariaLabel,s=t.ariaLabelFormat,o=t.disabled,l=t.getAriaLabel,c=t.styles,d=t.min,u=void 0===d?t.allowZeroStars?0:1:d,h=t.max,p=void 0===h?5:h,g=t.readOnly,m=t.size,f=t.theme,v=t.icon,S=void 0===v?"FavoriteStarFill":v,y=t.unselectedIcon,C=void 0===y?"FavoriteStar":y,_=t.onRenderStar,E=Math.max(u,0),T=b_(t.rating,t.defaultRating,t.onChange),b=T[0],I=T[1],w=function(e,t,i){return Math.min(Math.max(null!=e?e:t,t),i)}(b,E,p);!function(t,i){e.useImperativeHandle(t,(function(){return{rating:i}}),[i])}(t.componentRef,w);var R=e.useRef(null),A=qo(R,i);Lo(R);for(var P=Ds(t,ks),M=gD(c,{disabled:o,readOnly:g,theme:f}),k=null==l?void 0:l(w,p),D=a||k,O=[],N=function(t){var i,a,l=function(e,t){var i=Math.ceil(t),n=100;return e===t?n=100:e===i?n=t%1*100:e>i&&(n=0),n}(t,w);O.push(e.createElement("button",Ii({className:Os(M.ratingButton,m===uD.Large?M.ratingStarIsLarge:M.ratingStarIsSmall),id:fD(n,t),key:t},t===Math.ceil(w)&&{"data-is-current":!0},{onKeyDown:function(e){var i=e.which,n=t;switch(i){case ao.right:case ao.down:n=Math.min(p,n+1);break;case ao.left:case ao.up:n=Math.max(1,n-1);break;case ao.home:case ao.pageUp:n=1;break;case ao.end:case ao.pageDown:n=p}n===t||void 0!==b&&Math.ceil(b)===n||I(n,e)},onClick:function(e){void 0!==b&&Math.ceil(b)===t||I(t,e)},disabled:!(!o&&!g),role:"radio","aria-hidden":g?"true":void 0,type:"button","aria-checked":t===Math.ceil(w)}),e.createElement("span",{id:"".concat(r,"-").concat(t),className:M.labelText},function(e){for(var t=[],i=1;i<arguments.length;i++)t[i-1]=arguments[i];var n=t;return e.replace(pD,(function(e){var t=n[e.replace(hD,"")];return null==t&&(t=""),t}))}(s||"",t,p)),(i={fillPercentage:l,disabled:o,classNames:M,icon:l>0?S:C,starNum:t,unselectedIcon:C},(a=_)?a(i):e.createElement(mD,Ii({},i)))))},L=1;L<=p;L++)N(L);var x=m===uD.Large?M.rootIsLarge:M.rootIsSmall;return e.createElement("div",Ii({ref:A,className:Os("ms-Rating-star",M.root,x),"aria-label":g?void 0:D,id:n,role:g?void 0:"radiogroup"},P),e.createElement(Yl,Ii({direction:dl.bidirectional,className:Os(M.ratingFocusZone,x),defaultActiveElement:"#"+fD(n,Math.ceil(w))},g&&{allowFocusRoot:!0,disabled:!0,role:"textbox","aria-label":k,"aria-readonly":!0,"data-is-focusable":!0,tabIndex:0}),O))}));vD.displayName="RatingBase";var SD=Ws(vD,(function(e){var t=e.disabled,i=e.readOnly,n=e.theme,r=n.semanticColors,a=n.palette,s=Kr(cD,n),o=a.neutralSecondary,l=a.themePrimary,c=a.themeDark,d=a.neutralPrimary,u=r.disabledBodySubtext;return{root:[s.root,n.fonts.medium,!t&&!i&&{selectors:{"&:hover":{selectors:{".ms-RatingStar-back":dD(d,"Highlight")}}}}],rootIsSmall:[s.rootIsSmall,{height:"32px"}],rootIsLarge:[s.rootIsLarge,{height:"36px"}],ratingStar:[s.ratingStar,{display:"inline-block",position:"relative",height:"inherit"}],ratingStarBack:[s.ratingStarBack,{color:o,width:"100%"},t&&dD(u,"GrayText")],ratingStarFront:[s.ratingStarFront,{position:"absolute",height:"100 %",left:"0",top:"0",textAlign:"center",verticalAlign:"middle",overflow:"hidden"},dD(d,"Highlight")],ratingButton:[jr(n),s.ratingButton,{backgroundColor:"transparent",padding:"".concat(8,"px ").concat(2,"px"),boxSizing:"content-box",margin:"0px",border:"none",cursor:"pointer",selectors:{"&:disabled":{cursor:"default"},"&[disabled]":{cursor:"default"}}},!t&&!i&&{selectors:{"&:hover ~ .ms-Rating-button":{selectors:{".ms-RatingStar-back":dD(o,"WindowText"),".ms-RatingStar-front":dD(o,"WindowText")}},"&:hover":{selectors:{".ms-RatingStar-back":{color:l},".ms-RatingStar-front":{color:c}}}}},t&&{cursor:"default"}],ratingStarIsSmall:[s.ratingStarIsSmall,{fontSize:"16px",lineHeight:"16px",height:"16px"}],ratingStarIsLarge:[s.ratingStartIsLarge,{fontSize:"20px",lineHeight:"20px",height:"20px"}],labelText:[s.labelText,Wr],ratingFocusZone:[jr(n),s.ratingFocusZone,{display:"inline-block"}]}}),void 0,{scope:"Rating"});const yD=e=>cn({fontWeight:600,fontSize:bm(16),lineHeight:bm(20),color:e.palette.neutralPrimary,paddingTop:bm(24)}),CD=e=>cn({fontWeight:400,fontSize:bm(12),lineHeight:bm(12),color:e.palette.themePrimary,marginBottom:bm(8),marginTop:bm(8),textAlign:"center"}),_D=e=>({root:{textAlign:"center",height:"auto",marginTop:bm(8)},ratingStarIsLarge:{height:"auto",padding:0},ratingStar:{transform:"scale(1.4)",margin:bm(6),height:"auto"},ratingStarFront:{color:e.palette.themePrimary}}),ED=cn({paddingBottom:bm(6)}),TD=t=>{const{onStarRatingSelected:i,selectedIcon:n,unselectedIcon:r,strings:a}=t,[s,o]=(0,e.useState)(0),[l,c]=(0,e.useState)(""),d=xh(),u=(0,e.useCallback)(((e,t)=>{if(t){switch(o(t),t){case 1:c(null==a?void 0:a.starSurveyOneStarText);break;case 2:c(null==a?void 0:a.starSurveyTwoStarText);break;case 3:c(null==a?void 0:a.starSurveyThreeStarText);break;case 4:c(null==a?void 0:a.starSurveyFourStarText);break;case 5:c(null==a?void 0:a.starSurveyFiveStarText)}null==i||i(t)}}),[null==a?void 0:a.starSurveyOneStarText,null==a?void 0:a.starSurveyTwoStarText,null==a?void 0:a.starSurveyThreeStarText,null==a?void 0:a.starSurveyFourStarText,null==a?void 0:a.starSurveyFiveStarText,i]);return e.createElement(Gs,{verticalAlign:"center"},e.createElement(Gs,{className:ED},e.createElement(Cf,{className:yD(d)},null==a?void 0:a.starSurveyHelperText)),e.createElement(SD,{max:5,size:uD.Large,defaultRating:0,allowZeroStars:!0,rating:s,onChange:u,styles:_D(d),icon:null!=n?n:"SurveyStarIconFilled",unselectedIcon:null!=r?r:"SurveyStarIcon",ariaLabelFormat:null==a?void 0:a.starRatingAriaLabel}),e.createElement(Cf,{className:CD(d)},l))},bD=t=>{const{onStarRatingSelected:i}=t,n=ip().strings.call,r={starSurveyHelperText:n.starSurveyHelperText,starSurveyOneStarText:n.starSurveyOneStarText,starSurveyTwoStarText:n.starSurveyTwoStarText,starSurveyThreeStarText:n.starSurveyThreeStarText,starSurveyFourStarText:n.starSurveyFourStarText,starSurveyFiveStarText:n.starSurveyFiveStarText,starRatingAriaLabel:n.starRatingAriaLabel};return e.createElement(TD,{strings:r,onStarRatingSelected:i})};function ID(t,i){void 0===i&&(i=null);var n,r=e.useRef({ref:(n=function(e){r.ref.current!==e&&(r.cleanup&&(r.cleanup(),r.cleanup=void 0),r.ref.current=e,null!==e&&(r.cleanup=r.callback(e)))},n.current=i,n),callback:t}).current;return r.callback=t,r.ref}var wD=function(t){function i(e){var i=t.call(this,e)||this;return lo(i),i}return bi(i,t),i.prototype.render=function(){return e.createElement("div",Ii({},Ds(this.props,ks)),this.props.children)},i}(e.Component),RD=Ys(),AD=function(t,i){var n={links:[],keyToIndexMapping:{},keyToTabIdMapping:{}};return e.Children.forEach(e.Children.toArray(t.children),(function(e,r){if(PD(e)){var a=e.props,s=a.linkText,o=wi(a,["linkText"]),l=e.props.itemKey||r.toString();n.links.push(Ii(Ii({headerText:s},o),{itemKey:l})),n.keyToIndexMapping[l]=r,n.keyToTabIdMapping[l]=function(e,t,i,n){return e.getTabId?e.getTabId(i,n):t+"-Tab".concat(n)}(t,i,l,r)}else e&&$a("The children of a Pivot component must be of type PivotItem to be rendered.")})),n},PD=function(t){var i;return e.isValidElement(t)&&(null===(i=t.type)||void 0===i?void 0:i.name)===wD.name},MD=e.forwardRef((function(t,i){var n,r=e.useRef(null),a=e.useRef(null),s=fu("Pivot"),o=b_(t.selectedKey,t.defaultSelectedKey),l=o[0],c=o[1],d=t.componentRef,u=t.theme,h=t.linkSize,p=t.linkFormat,g=t.overflowBehavior,m=t.overflowAriaLabel,f=t.focusZoneProps,v=t.overflowButtonAs,S={"aria-label":t["aria-label"],"aria-labelledby":t["aria-labelledby"]},y=Ds(t,ks,["aria-label","aria-labelledby"]),C=AD(t,s);e.useImperativeHandle(d,(function(){return{focus:function(){var e;null===(e=r.current)||void 0===e||e.focus()}}}));var _=function(t){if(!t)return null;var i=t.itemCount,r=t.itemIcon,a=t.headerText;return e.createElement("span",{className:n.linkContent},void 0!==r&&e.createElement("span",{className:n.icon},e.createElement(al,{iconName:r})),void 0!==a&&e.createElement("span",{className:n.text}," ",t.headerText),void 0!==i&&e.createElement("span",{className:n.count}," (",i,")"))},E=function(t,i,r,a){var s,o=i.itemKey,l=i.headerButtonProps,c=i.onRenderItemLink,d=t.keyToTabIdMapping[o],u=r===o;s=c?c(i,_):_(i);var h=i.headerText||"";h+=i.itemCount?" ("+i.itemCount+")":"",h+=i.itemIcon?" xx":"";var p=i.role&&"tab"!==i.role?{role:i.role}:{role:"tab","aria-selected":u};return e.createElement(XC,Ii({},l,p,{id:d,key:o,className:Os(a,u&&n.linkIsSelected),onClick:function(e){return T(o,e)},onKeyDown:function(e){return b(o,e)},"aria-label":i.ariaLabel,name:i.headerText,keytipProps:i.keytipProps,"data-content":h}),s)},T=function(e,t){t.preventDefault(),I(e,t)},b=function(e,t){t.which===ao.enter&&(t.preventDefault(),I(e))},I=function(i,n){var r;if(c(i),C=AD(t,s),t.onLinkClick&&C.keyToIndexMapping[i]>=0){var o=C.keyToIndexMapping[i],l=e.Children.toArray(t.children)[o];PD(l)&&t.onLinkClick(l,n)}null===(r=a.current)||void 0===r||r.dismissMenu()};n=RD(t.styles,{theme:u,linkSize:h,linkFormat:p});var w,R=null===(w=l)||void 0!==w&&void 0!==C.keyToIndexMapping[w]?l:C.links.length?C.links[0].itemKey:void 0,A=R?C.keyToIndexMapping[R]:0,P=C.links.map((function(e){return E(C,e,R,n.link)})),M=e.useMemo((function(){return{items:[],alignTargetEdge:!0,directionalHint:ll.bottomRightEdge}}),[]),k=function(t){var i=t.onOverflowItemsChanged,n=t.rtl,r=t.pinnedIndex,a=e.useRef(),s=e.useRef(),o=ID((function(e){var t=function(e,t){if("undefined"!=typeof ResizeObserver){var i=new ResizeObserver(t);return Array.isArray(e)?e.forEach((function(e){return i.observe(e)})):i.observe(e),function(){return i.disconnect()}}var n=function(){return t(void 0)},r=Tn(Array.isArray(e)?e[0]:e);if(!r)return function(){};var a=r.requestAnimationFrame(n);return r.addEventListener("resize",n,!1),function(){r.cancelAnimationFrame(a),r.removeEventListener("resize",n,!1)}}(e,(function(t){s.current=t?t[0].contentRect.width:e.clientWidth,a.current&&a.current()}));return function(){t(),s.current=void 0}})),l=ID((function(e){return o(e.parentElement),function(){return o(null)}}));return Wo((function(){var e=o.current,t=l.current;if(e&&t){for(var c=[],d=0;d<e.children.length;d++){var u=e.children[d];u instanceof HTMLElement&&u!==t&&c.push(u)}var h=[],p=0;a.current=function(){var e=s.current;if(void 0!==e){for(var i=c.length-1;i>=0;i--){if(void 0===h[i]){var a=n?e-c[i].offsetLeft:c[i].offsetLeft+c[i].offsetWidth;i+1<c.length&&i+1===r&&(p=h[i+1]-a),i===c.length-2&&(p+=t.offsetWidth),h[i]=a+p}if(e>h[i])return void m(i+1)}m(0)}};var g=c.length,m=function(e){g!==e&&(g=e,i(e,c.map((function(t,i){return{ele:t,isOverflowing:i>=e&&i!==r}}))))},f=void 0;if(void 0!==s.current){var v=Tn(e);if(v){var S=v.requestAnimationFrame(a.current);f=function(){return v.cancelAnimationFrame(S)}}}return function(){f&&f(),m(c.length),a.current=void 0}}})),{menuButtonRef:l}}({onOverflowItemsChanged:function(e,t){t.forEach((function(e){var t=e.ele,i=e.isOverflowing;return t.dataset.isOverflowing="".concat(i)})),M.items=C.links.slice(e).filter((function(e){return e.itemKey!==R})).map((function(t,i){return t.role="menuitem",{key:t.itemKey||"".concat(e+i),onRender:function(){return E(C,t,R,n.linkInMenu)}}}))},rtl:Rn(u),pinnedIndex:A}).menuButtonRef,D=v||XC;return e.createElement("div",Ii({ref:i},y),e.createElement(Yl,Ii({componentRef:r,role:"tablist"},S,{direction:dl.horizontal},f,{className:Os(n.root,null==f?void 0:f.className)}),P,"menu"===g&&e.createElement(D,{className:Os(n.link,n.overflowMenuButton),elementRef:k,componentRef:a,menuProps:M,menuIconProps:{iconName:"More",style:{color:"inherit"}},ariaLabel:m,role:"tab"})),R&&C.links.map((function(i){return(!0===i.alwaysRender||R===i.itemKey)&&function(i,r){if(t.headersOnly||!i)return null;var a=C.keyToIndexMapping[i],s=C.keyToTabIdMapping[i];return e.createElement("div",{role:"tabpanel",hidden:!r,key:i,"aria-hidden":!r,"aria-labelledby":s,className:n.itemContainer},e.Children.toArray(t.children)[a])}(i.itemKey,R===i.itemKey)})))}));MD.displayName="Pivot";var kD={count:"ms-Pivot-count",icon:"ms-Pivot-icon",linkIsSelected:"is-selected",link:"ms-Pivot-link",linkContent:"ms-Pivot-linkContent",root:"ms-Pivot",rootIsLarge:"ms-Pivot--large",rootIsTabs:"ms-Pivot--tabs",text:"ms-Pivot-text",linkInMenu:"ms-Pivot-linkInMenu",overflowMenuButton:"ms-Pivot-overflowMenuButton"},DD=function(e,t,i){var n,r,a;void 0===i&&(i=!1);var s=e.linkSize,o=e.linkFormat,l=e.theme,c=l.semanticColors,d=l.fonts,u="large"===s,h="tabs"===o;return[d.medium,{color:c.actionLink,padding:"0 8px",position:"relative",backgroundColor:"transparent",border:0,borderRadius:0,selectors:{":hover":{backgroundColor:c.buttonBackgroundHovered,color:c.buttonTextHovered,cursor:"pointer"},":active":{backgroundColor:c.buttonBackgroundPressed,color:c.buttonTextHovered},":focus":{outline:"none"}}},!i&&[{display:"inline-block",lineHeight:44,height:44,marginRight:8,textAlign:"center",selectors:(n={},n[".".concat(Vr," &:focus")]={outline:"1px solid ".concat(c.focusBorder)},n[".".concat(Vr," &:focus:after")]={content:"attr(data-content)",position:"relative",border:0},n[":before"]={backgroundColor:"transparent",bottom:0,content:'""',height:2,left:8,position:"absolute",right:8,transition:"left ".concat(yr," ").concat(Sr,",\n                        right ").concat(yr," ").concat(Sr)},n[":after"]={color:"transparent",content:"attr(data-content)",display:"block",fontWeight:Mr.bold,height:1,overflow:"hidden",visibility:"hidden"},n)},u&&{fontSize:d.large.fontSize},h&&[{marginRight:0,height:44,lineHeight:44,backgroundColor:c.buttonBackground,padding:"0 10px",verticalAlign:"top",selectors:(r={":focus":{outlineOffset:"-2px"}},r[".".concat(Vr," &:focus::before")]={height:"auto",background:"transparent",transition:"none"},r["&:hover, &:focus"]={color:c.buttonTextCheckedHovered},r["&:active, &:hover"]={color:c.primaryButtonText,backgroundColor:c.primaryButtonBackground},r["&.".concat(t.linkIsSelected)]={backgroundColor:c.primaryButtonBackground,color:c.primaryButtonText,fontWeight:Mr.regular,selectors:(a={":before":{backgroundColor:"transparent",transition:"none",position:"absolute",top:0,left:0,right:0,bottom:0,content:'""',height:0},":hover":{backgroundColor:c.primaryButtonBackgroundHovered,color:c.primaryButtonText},":active":{backgroundColor:c.primaryButtonBackgroundPressed,color:c.primaryButtonText}},a[Nr]=Ii({fontWeight:Mr.semibold,color:"HighlightText",background:"Highlight"},{forcedColorAdjust:"none",MsHighContrastAdjust:"none"}),a)},r[".".concat(Vr," &.").concat(t.linkIsSelected,":focus")]={outlineColor:c.primaryButtonText},r)}]]]},OD=Ws(MD,(function(e){var t,i,n,r,a=e.className,s=e.linkSize,o=e.linkFormat,l=e.theme,c=l.semanticColors,d=l.fonts,u=Kr(kD,l),h="large"===s,p="tabs"===o;return{root:[u.root,d.medium,Ba,{position:"relative",color:c.link,whiteSpace:"nowrap"},h&&u.rootIsLarge,p&&u.rootIsTabs,a],itemContainer:{selectors:{"&[hidden]":{display:"none"}}},link:Ai(Ai([u.link],DD(e,u),!0),[(t={},t["&[data-is-overflowing='true']"]={display:"none"},t)],!1),overflowMenuButton:[u.overflowMenuButton,(i={visibility:"hidden",position:"absolute",right:0},i[".".concat(u.link,"[data-is-overflowing='true'] ~ &")]={visibility:"visible",position:"relative"},i)],linkInMenu:Ai(Ai([u.linkInMenu],DD(e,u,!0),!0),[{textAlign:"left",width:"100%",height:36,lineHeight:36}],!1),linkIsSelected:[u.link,u.linkIsSelected,{fontWeight:Mr.semibold,selectors:(n={":before":{backgroundColor:c.inputBackgroundChecked,selectors:(r={},r[Nr]={backgroundColor:"Highlight"},r)},":hover::before":{left:0,right:0}},n[Nr]={color:"Highlight"},n)}],linkContent:[u.linkContent,{flex:"0 1 100%",selectors:{"& > * ":{marginLeft:4},"& > *:first-child":{marginLeft:0}}}],text:[u.text,{display:"inline-block",verticalAlign:"top"}],count:[u.count,{display:"inline-block",verticalAlign:"top"}],icon:u.icon}}),void 0,{scope:"Pivot"});const ND=e=>cn({fontWeight:600,fontSize:bm(16),lineHeight:bm(20),color:e.palette.neutralPrimary,marginTop:bm(8),marginBottom:bm(4)}),LD=e=>cn({fontWeight:400,fontSize:bm(12),lineHeight:bm(16),marginTop:bm(4),color:e.palette.neutralSecondary}),xD=cn({padding:bm(8),paddingLeft:0}),FD={root:{paddingBottom:bm(8),width:"100%"},label:{width:"100%"}},UD=cn({width:"100%",marginLeft:bm(4),input:{padding:0}}),BD=t=>{const{callIssuesToTag:i,categoryHeadings:n,onConfirm:r,strings:a,showFreeFormTextField:s}=t,[o,l]=(0,e.useState)({}),[c,d]=(0,e.useState)({}),[u,h]=(0,e.useState)({}),[p,g]=(0,e.useState)([]),m=(0,e.useMemo)((()=>{const e={overallRating:[],audioRating:[],videoRating:[],screenshareRating:[]};return rf(i).forEach((t=>{rf(i[t]).map((n=>{const r=(null==n?void 0:n.charAt(0).toUpperCase())+(null==n?void 0:n.slice(1)),a=i[t];e[t]?e[t].push({message:a[n],issue:r}):e[t]=[{message:a[n],issue:r}]}))})),e}),[i]),f=e.useCallback(((e,t,i)=>{t?i?l((t=>{var n;const r=null===(n=null==t?void 0:t[e])||void 0===n?void 0:n.issues;return r?t[e].issues=[...r,i]:t[e]={issues:[i]},t})):(g([...p,e]),h((t=>(t[e]=c[e],t)))):i?l((t=>{var n,r;const a=null===(r=null===(n=t[e])||void 0===n?void 0:n.issues)||void 0===r?void 0:r.filter((e=>e!==i));return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},t[e]||{}),{issues:a})})})):(g(p.filter((t=>t!==e))),h((t=>(delete t[e],t))))}),[c,p]),v=xh(),S=(0,e.useCallback)((t=>e.createElement(nb,{key:t,className:UD,underlined:!0,placeholder:null==a?void 0:a.tagsSurveyTextFieldDefaultText,onChange:(e,i)=>{i&&(g([...p,t]),d((e=>(e[t]=i,e))),h((e=>(e[t]=i,e))))}})),[null==a?void 0:a.tagsSurveyTextFieldDefaultText,p]);return(0,e.useEffect)((()=>{r&&r(o,u)}),[o,u,r]),e.createElement(e.Fragment,null,e.createElement(Gs,{verticalAlign:"center"},e.createElement(Cf,{className:ND(v)},null==a?void 0:a.tagsSurveyQuestion)),e.createElement(OD,null,rf(m).map(((t,i)=>e.createElement(wD,{key:`key-${i}`,headerText:n[t],headerButtonProps:{"data-order":i,"data-title":t},alwaysRender:!0},m[t].map(((i,n)=>e.createElement(k_,{className:xD,key:`checkBox_${n}`,label:i.message,onChange:(e,n)=>f(t,null!=n&&n,i.issue)}))),s&&e.createElement(k_,{checked:p.includes(t),styles:FD,onChange:(e,i)=>f(t,null!=i&&i),onRenderLabel:()=>S(t)}))))),e.createElement(Cf,{className:LD(v)},null==a?void 0:a.tagsSurveyHelperText))},VD=t=>{const i=ip().strings.call,n={tagsSurveyQuestion:i.tagsSurveyQuestion,tagsSurveyHelperText:i.tagsSurveyHelperText,tagsSurveyTextFieldDefaultText:i.tagsSurveyTextFieldDefaultText};return e.createElement(BD,{callIssuesToTag:i.surveyIssues,categoryHeadings:i.surveyIssuesHeadingStrings,onConfirm:t.onConfirm,strings:n,showFreeFormTextField:t.showFreeFormTextField})},HD=t=>{const[i,n]=(0,e.useState)(!1);return e.createElement(Gs,{"data-ui-id":"call-composite-survey"},e.createElement(bD,{onStarRatingSelected:e=>{e<5?(n(!0),t.setShowSubmitFeedbackButton(!0)):t.setShowSubmitFeedbackButton(!0),t.setRatings(e)}}),i&&e.createElement(VD,{onConfirm:(e,i)=>{t.setIssuesSelected(e),t.setShowSubmitFeedbackButton(!0),i&&t.setImprovementSuggestions&&t.setImprovementSuggestions(i)},showFreeFormTextField:!(void 0===t.setImprovementSuggestions)}))};function $D(t){const i=ip().strings.call;return e.createElement(Gs,{verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":"thank-you-page","aria-atomic":!0},e.createElement(Gs,{className:cn(lk),tokens:ck},t.iconName&&e.createElement(Hm,{iconName:t.iconName}),e.createElement(Cf,{className:cn(uk),"aria-live":"assertive"},i.endOfSurveyText)))}const GD=e=>cn({fontWeight:600,fontSize:bm(20),lineHeight:bm(20),color:e.palette.neutralPrimary}),jD=e=>cn(e?{width:"20rem",position:"absolute",top:"10%",left:"50%",transform:"translateX(-50%)"}:{width:"24rem",position:"absolute",top:"20%",left:"50%",transform:"translateX(-50%)"});const zD=t=>{const{onSubmitSurvey:i,onSurveySubmittedCustom:n,onSurveyClosed:r,iconName:a,title:s,moreDetails:o,disableStartCallButton:l,isMobile:c}=t,d=ip().strings.call,[u,h]=(0,e.useState)(0),[p,g]=(0,e.useState)(),[m,f]=(0,e.useState)(!1),[v,S]=(0,e.useState)({}),[y,C]=(0,e.useState)(!1),[_,E]=(0,e.useState)(!1),[T,b]=(0,e.useState)(!1),I=xh();return e.createElement(e.Fragment,null,y&&e.createElement($D,{iconName:a}),_&&e.createElement(pk,{iconName:a,title:s,moreDetails:o,dataUiId:"left-call-page",disableStartCallButton:l}),!y&&!_&&e.createElement(Gs,{verticalAlign:"center",className:jD(!!c)},e.createElement(Cf,{className:GD(I)},d.surveyTitle),e.createElement(HD,{setShowSubmitFeedbackButton:e=>{f(e)},setRatings:e=>{h(e)},setIssuesSelected:e=>{g(e)},setImprovementSuggestions:n?e=>{S(e)}:void 0}),e.createElement(Gs,{horizontal:!0,horizontalAlign:"end"},e.createElement(yy,{style:{marginTop:"1rem",marginRight:"0.5rem"},onClick:()=>{r?r("skipped"):E(!0)}},d.surveySkipButtonLabel),m&&e.createElement(rE,{disabled:T,style:{marginTop:"1rem",marginLeft:"0.5rem"},onClick:()=>{return e=void 0,t=void 0,s=function*(){const e={overallRating:{score:u}};(null==p?void 0:p.overallRating)&&(e.overallRating={score:u,issues:p.overallRating.issues}),(null==p?void 0:p.audioRating)&&(e.audioRating={score:u,issues:p.audioRating.issues}),(null==p?void 0:p.screenshareRating)&&(e.screenshareRating={score:u,issues:p.screenshareRating.issues}),(null==p?void 0:p.videoRating)&&(e.videoRating={score:u,issues:p.videoRating.issues}),i&&(b(!0),i(e).then((t=>{var i,a;n?n(null!==(i=null==t?void 0:t.callId)&&void 0!==i?i:"",null!==(a=null==t?void 0:t.id)&&void 0!==a?a:"",e,v).then((()=>b(!1))):b(!1),r?r("sent"):C(!0)})).catch((e=>{console.log("error when submitting survey: "+e),r&&r("error",e)})))},new((a=void 0)||(a=Promise))((function(i,n){function r(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(r,o)}l((s=s.apply(e,t||[])).next())}));var e,t,a,s}},d.surveyConfirmButtonLabel))))};function WD(t){var i,n;const r=CE();return e.createElement(Gs,{verticalFill:!0,verticalAlign:"center",horizontalAlign:"center","data-ui-id":t.dataUiId,"aria-atomic":!0},e.createElement(Gs,{className:cn(yP),tokens:ck},e.createElement(zD,Object.assign({},r,t,{onSurveySubmittedCustom:null===(i=t.surveyOptions)||void 0===i?void 0:i.onSurveySubmitted,onSurveyClosed:null===(n=t.surveyOptions)||void 0===n?void 0:n.onSurveyClosed,isMobile:t.mobileView}))))}const qD=e=>!!(null==e?void 0:e.isActive),KD=t=>{var i,n,r,a,s,o,l,c,d,u,h,p,g,m,f;const v=Xm(),{camerasCount:S,microphonesCount:y}=fI(oD),C=S>0,_=y>0;(0,e.useEffect)((()=>{var e,t,i,n;e=void 0,t=void 0,n=function*(){var e;const t=QD({role:null===(e=v.getState().call)||void 0===e?void 0:e.role});yield v.askDevicePermission(t),v.queryCameras(),v.queryMicrophones(),v.querySpeakers()},new((i=void 0)||(i=Promise))((function(r,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(s,o)}l((n=n.apply(e,t||[])).next())}))}),[v,C,_]);const{callInvitationUrl:E,onFetchAvatarPersonaData:T,onFetchParticipantMenuItems:b}=t,I=fI(CI),w=fI(vI),[R,A]=e.useState(),[P,M]=e.useState(),[k,D]=(0,e.useState)(null!==(r=null===(n=null===(i=t.options)||void 0===i?void 0:i.galleryOptions)||void 0===n?void 0:n.layout)&&void 0!==r?r:"floatingLocalVideo"),[O,N]=(0,e.useState)("Responsive"),L=(0,e.useRef)(t.overrideSidePane);(0,e.useEffect)((()=>{M(t.overrideSidePane),!qD(L.current)&&qD(t.overrideSidePane)&&A(void 0),L.current=t.overrideSidePane}),[t.overrideSidePane]);const x=t.onSidePaneIdChange;(0,e.useEffect)((()=>{null==x||x(null==R?void 0:R.id)}),[null==R?void 0:R.id,x]),(0,e.useEffect)((()=>{const e=()=>{A(void 0)};return v.on("callEnded",e),()=>{v.off("callEnded",e)}}),[v]);const F=Wm(),U=(t=>{const[i,n]=(0,e.useState)({}),r=(0,e.useRef)({shareScreen:{capabilityName:"shareScreen",isPresent:!0,changedReason:"RoleChanged"}});(0,e.useEffect)((()=>{r.current=((e,t)=>{var i,n;if(!e.capabilitiesChangeInfo)return t;for(const[r,a]of Object.entries(e.capabilitiesChangeInfo.newValue)){const s=r;if(t[s]&&a.isPresent===(null===(i=t[s])||void 0===i?void 0:i.isPresent)&&e.capabilitiesChangeInfo.reason===(null===(n=t[s])||void 0===n?void 0:n.changedReason))continue;const o={capabilityName:s,isPresent:a.isPresent,changedReason:e.capabilitiesChangeInfo.reason,role:e.participantRole,timestamp:new Date(Date.now())};t[s]=o}return t})(t,r.current),n((e=>((e,t)=>{var i,n;const r={};for(const a of t){const t=e[a.capabilityName];r[a.capabilityName]={mostRecentlyActive:null!==(n=null!==(i=a.timestamp)&&void 0!==i?i:null==t?void 0:t.mostRecentlyActive)&&void 0!==n?n:new Date(Date.now()),lastDismissedAt:null==t?void 0:t.lastDismissedAt}}return r})(e,Object.values(r.current))))}),[t]);const a=(0,e.useCallback)((e=>{n((t=>((e,t)=>{const i=new Date(Date.now()),n=t[e];return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},n||{}),{lastDismissedAt:i})})})(e.capabilityName,t)))}),[]);return{capabilitiesChangedNotifications:(0,e.useMemo)((()=>((e,t)=>e.filter((e=>{const i=t[e.capabilityName];return!i||!i.lastDismissedAt||i.lastDismissedAt<i.mostRecentlyActive})))(Object.values(r.current),i)),[i]),onDismissNotification:a}})(fI(lD)),B=oI(Mh).activeErrorMessages,[V,H]=(0,e.useState)({});(0,e.useEffect)((()=>{H((e=>((e,t)=>{var i,n;const r={};for(const a of t){const t=e[a.type];r[a.type]={mostRecentlyActive:null!==(n=null!==(i=a.timestamp)&&void 0!==i?i:null==t?void 0:t.mostRecentlyActive)&&void 0!==n?n:new Date(Date.now()),lastDismissedAt:null==t?void 0:t.lastDismissedAt}}return r})(e,B)))}),[B]);const $=(0,e.useCallback)((e=>{H((t=>((e,t)=>{const i=new Date(Date.now()),n=t[e];return Object.assign(Object.assign({},t),{[e]:Object.assign(Object.assign({},n||{}),{lastDismissedAt:i})})})(e.type,t)))}),[]),G=(0,e.useMemo)((()=>((e,t)=>e.filter((e=>{const i=t[e.type];return!i||!i.lastDismissedAt||i.lastDismissedAt<i.mostRecentlyActive})))(B,V)),[B,V]),j=fI(PI),z=ip(),W=Qh().palette,q=v.getState().alternateCallerId,K=(0,e.useMemo)((()=>(e=>({background:e.neutralLighterAlt}))(W)),[W]);let J;const[Y,Q]=(0,e.useState)([]);switch(I){case"configuration":J=e.createElement(ik,{mobileView:t.mobileView,startCallHandler:()=>{j?v.startCall(j,q?{alternateCallerId:{phoneNumber:q}}:{}):v.joinCall({microphoneOn:"keep",cameraOn:"keep"})},updateSidePaneRenderer:A,latestErrors:G,onDismissError:$,modalLayerHostId:t.modalLayerHostId,deviceChecks:null===(a=t.options)||void 0===a?void 0:a.deviceChecks,onPermissionsTroubleshootingClick:null===(s=t.options)||void 0===s?void 0:s.onPermissionsTroubleshootingClick,onNetworkingTroubleShootingClick:null===(o=t.options)||void 0===o?void 0:o.onNetworkingTroubleShootingClick,capabilitiesChangedNotificationBarProps:U,logo:null===(c=null===(l=t.options)||void 0===l?void 0:l.branding)||void 0===c?void 0:c.logo,backgroundImage:null===(u=null===(d=t.options)||void 0===d?void 0:d.branding)||void 0===u?void 0:u.backgroundImage});break;case"accessDeniedTeamsMeeting":J=e.createElement(pk,{iconName:"NoticePageAccessDeniedTeamsMeeting",title:z.strings.call.failedToJoinTeamsMeetingReasonAccessDeniedTitle,moreDetails:z.strings.call.failedToJoinTeamsMeetingReasonAccessDeniedMoreDetails,dataUiId:"access-denied-teams-meeting-page"});break;case"removedFromCall":J=e.createElement(pk,{iconName:"NoticePageRemovedFromCall",title:z.strings.call.removedFromCallTitle,moreDetails:z.strings.call.removedFromCallMoreDetails,dataUiId:"removed-from-call-page"});break;case"joinCallFailedDueToNoNetwork":J=e.createElement(pk,{iconName:"NoticePageJoinCallFailedDueToNoNetwork",title:z.strings.call.failedToJoinCallDueToNoNetworkTitle,moreDetails:z.strings.call.failedToJoinCallDueToNoNetworkMoreDetails,dataUiId:"join-call-failed-due-to-no-network-page"});break;case"leaving":J=e.createElement(pk,{title:null!==(h=z.strings.call.leavingCallTitle)&&void 0!==h?h:"Leaving...",dataUiId:"leaving-page",pageStyle:K,disableStartCallButton:!0});break;case"leftCall":{const{title:i,moreDetails:n,disableStartCallButton:r,iconName:a}=((e,t)=>{var i,n,r,a,s;let o=e.strings.call.leftCallTitle,l=e.strings.call.leftCallMoreDetails,c=!1,d="NoticePageLeftCall";switch(null===(i=null==t?void 0:t.callEndReason)||void 0===i?void 0:i.subCode){case 5732:e.strings.call.roomNotFoundTitle&&(o=e.strings.call.roomNotFoundTitle,l=e.strings.call.roomNotFoundDetails,c=!0,d="NoticePageRoomNotFound");break;case 5829:e.strings.call.roomNotValidTitle&&(o=e.strings.call.roomNotValidTitle,l=e.strings.call.roomNotValidDetails,c=!0,d="NoticePageRoomNotValid");break;case 5828:e.strings.call.notInvitedToRoomTitle&&(o=e.strings.call.notInvitedToRoomTitle,l=e.strings.call.notInvitedToRoomDetails,c=!0,d="NoticePageNotInvitedToRoom");break;case 5317:e.strings.call.inviteToRoomRemovedTitle&&(o=e.strings.call.inviteToRoomRemovedTitle,l=e.strings.call.inviteToRoomRemovedDetails,c=!0,d="NoticePageInviteToRoomRemoved");break;case 10004:487===(null===(n=null==t?void 0:t.callEndReason)||void 0===n?void 0:n.code)&&e.strings.call.callTimeoutTitle&&(o=e.strings.call.callTimeoutTitle,l=e.strings.call.callTimeoutDetails,c=!0,d="NoticePageCallTimeout");break;case 10321:486===(null===(r=null==t?void 0:t.callEndReason)||void 0===r?void 0:r.code)&&e.strings.call.callTimeoutBotTitle&&(o=e.strings.call.callTimeoutBotTitle,l=e.strings.call.callTimeoutBotDetails,c=!0,d="NoticePageCallTimeout")}switch(603===(null===(a=null==t?void 0:t.callEndReason)||void 0===a?void 0:a.code)&&e.strings.call.callRejectedTitle&&(o=e.strings.call.callRejectedTitle,l=e.strings.call.callRejectedMoreDetails,c=!0,d="NoticePageCallRejected"),null===(s=null==t?void 0:t.callEndReason)||void 0===s?void 0:s.subCode){case 10037:e.strings.call.participantCouldNotBeReachedTitle&&(o=e.strings.call.participantCouldNotBeReachedTitle,l=e.strings.call.participantCouldNotBeReachedMoreDetails,c=!0);break;case 10124:e.strings.call.permissionToReachTargetParticipantNotAllowedTitle&&(o=e.strings.call.permissionToReachTargetParticipantNotAllowedTitle,l=e.strings.call.permissionToReachTargetParticipantNotAllowedMoreDetails,c=!0);break;case 10119:e.strings.call.unableToResolveTenantTitle&&(o=e.strings.call.unableToResolveTenantTitle,l=e.strings.call.unableToResolveTenantMoreDetails,c=!0);break;case 10044:e.strings.call.participantIdIsMalformedTitle&&(o=e.strings.call.participantIdIsMalformedTitle,l=e.strings.call.participantIdIsMalformedMoreDetails,c=!0)}return{title:o,moreDetails:l,disableStartCallButton:c,iconName:d}})(z,w);if(!(null===(g=null===(p=t.options)||void 0===p?void 0:p.surveyOptions)||void 0===g?void 0:g.disableSurvey)){J=e.createElement(WD,{dataUiId:"left-call-page",surveyOptions:null===(m=t.options)||void 0===m?void 0:m.surveyOptions,iconName:a,title:i,moreDetails:n,disableStartCallButton:r,mobileView:t.mobileView});break}J=e.createElement(pk,{iconName:a,title:i,moreDetails:j?"":n,dataUiId:"left-call-page",disableStartCallButton:r});break}case"lobby":J=e.createElement(yk,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:A,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:G,onDismissError:$,capabilitiesChangedNotificationBarProps:U});break;case"transferring":J=e.createElement(Dk,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:A,mobileChatTabHeader:t.mobileChatTabHeader,onFetchAvatarPersonaData:T,latestErrors:G,onDismissError:$,capabilitiesChangedNotificationBarProps:U});break;case"call":J=e.createElement(NP,{callInvitationURL:E,onFetchAvatarPersonaData:T,onFetchParticipantMenuItems:b,mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:A,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:t.onCloseChatPane,latestErrors:G,onDismissError:$,galleryLayout:k,onUserSetGalleryLayoutChange:D,onSetUserSetOverflowGalleryPosition:N,userSetOverflowGalleryPosition:O,capabilitiesChangedNotificationBarProps:U,pinnedParticipants:Y,setPinnedParticipants:Q,compositeAudioContext:F});break;case"hold":J=e.createElement(e.Fragment,null,e.createElement(jk,{mobileView:t.mobileView,modalLayerHostId:t.modalLayerHostId,options:t.options,updateSidePaneRenderer:A,mobileChatTabHeader:t.mobileChatTabHeader,latestErrors:G,onDismissError:$,capabilitiesChangedNotificationBarProps:U}))}if((t=>{var i;(0,e.useEffect)((()=>{var e;switch(null===(e=null==t?void 0:t.callEndReason)||void 0===e?void 0:e.subCode){case 5732:console.error("Call ended because the room id provided through the adapter locator could not be found");break;case 5829:console.error("Call ended because this room is currently not valid.");break;case 5828:console.error("Call ended because you are not invited to this room.");break;case 5317:console.error("Call ended because your invite to this room has been removed.")}}),[null===(i=null==t?void 0:t.callEndReason)||void 0===i?void 0:i.subCode])})(w),"unsupportedEnvironment"===I&&(J=e.createElement(e.Fragment,null,e.createElement(aD,{onTroubleshootingClick:null===(f=t.options)||void 0===f?void 0:f.onEnvironmentInfoTroubleshootingClick,environmentInfo:v.getState().environmentInfo}))),!J)throw new Error("Invalid call composite page");return e.createElement(xR,{sidePaneRenderer:R,overrideSidePane:P},J)},JD=t=>e.createElement(YD,Object.assign({},t)),YD=t=>{const{adapter:i,callInvitationUrl:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:a,options:s,formFactor:o="desktop"}=t,l="mobile"===o,c=fu("modalLayerhost"),d=(0,e.useMemo)((()=>l?pR:hR),[l]);return e.createElement("div",{className:d},e.createElement(qm,Object.assign({},t),e.createElement(Zm,{adapter:i},e.createElement(KD,{callInvitationUrl:n,onFetchAvatarPersonaData:r,onFetchParticipantMenuItems:a,mobileView:l,modalLayerHostId:c,options:s,onSidePaneIdChange:t.onSidePaneIdChange,overrideSidePane:t.overrideSidePane,mobileChatTabHeader:t.mobileChatTabHeader,onCloseChatPane:t.onCloseChatPane}),e.createElement(Xh,{id:c,className:cn(Pw)}))))},QD=e=>"Consumer"===e.role?{video:!1,audio:!0}:{video:!0,audio:!0};function ZD(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons"',src:"url('".concat(e,"fabric-icons-a13498cf.woff') format('woff')")},icons:{GlobalNavButton:"",ChevronDown:"",ChevronUp:"",Edit:"",Add:"",Cancel:"",More:"",Settings:"",Mail:"",Filter:"",Search:"",Share:"",BlockedSite:"",FavoriteStar:"",FavoriteStarFill:"",CheckMark:"",Delete:"",ChevronLeft:"",ChevronRight:"",Calendar:"",Megaphone:"",Undo:"",Flag:"",Page:"",Pinned:"",View:"",Clear:"",Download:"",Upload:"",Folder:"",Sort:"",AlignRight:"",AlignLeft:"",Tag:"",AddFriend:"",Info:"",SortLines:"",List:"",CircleRing:"",Heart:"",HeartFill:"",Tiles:"",Embed:"",Glimmer:"",Ascending:"",Descending:"",SortUp:"",SortDown:"",SyncToPC:"",LargeGrid:"",SkypeCheck:"",SkypeClock:"",SkypeMinus:"",ClearFilter:"",Flow:"",StatusCircleCheckmark:"",MoreVertical:""}},t)}function XD(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-0"',src:"url('".concat(e,"fabric-icons-0-467ee27f.woff') format('woff')")},icons:{PageLink:"",CommentSolid:"",ChangeEntitlements:"",Installation:"",WebAppBuilderModule:"",WebAppBuilderFragment:"",WebAppBuilderSlot:"",BullseyeTargetEdit:"",WebAppBuilderFragmentCreate:"",PageData:"",PageHeaderEdit:"",ProductList:"",UnpublishContent:"",DependencyAdd:"",DependencyRemove:"",EntitlementPolicy:"",EntitlementRedemption:"",SchoolDataSyncLogo:"",PinSolid12:"",PinSolidOff12:"",AddLink:"",SharepointAppIcon16:"",DataflowsLink:"",TimePicker:"",UserWarning:"",ComplianceAudit:"",InternetSharing:"",Brightness:"",MapPin:"",Airplane:"",Tablet:"",QuickNote:"",Video:"",People:"",Phone:"",Pin:"",Shop:"",Stop:"",Link:"",AllApps:"",Zoom:"",ZoomOut:"",Microphone:"",Camera:"",Attach:"",Send:"",FavoriteList:"",PageSolid:"",Forward:"",Back:"",Refresh:"",Lock:"",ReportHacked:"",EMI:"",MiniLink:"",Blocked:"",ReadingMode:"",Favicon:"",Remove:"",Checkbox:"",CheckboxComposite:"",CheckboxFill:"",CheckboxIndeterminate:"",CheckboxCompositeReversed:"",BackToWindow:"",FullScreen:"",Print:"",Up:"",Down:"",OEM:"",Save:"",ReturnKey:"",Cloud:"",Flashlight:"",CommandPrompt:"",Sad:"",RealEstate:"",SIPMove:"",EraseTool:"",GripperTool:"",Dialpad:"",PageLeft:"",PageRight:"",MultiSelect:"",KeyboardClassic:"",Play:"",Pause:"",InkingTool:"",Emoji2:"",GripperBarHorizontal:"",System:"",Personalize:"",SearchAndApps:"",Globe:"",EaseOfAccess:"",ContactInfo:"",Unpin:"",Contact:"",Memo:"",IncomingCall:""}},t)}function eO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-1"',src:"url('".concat(e,"fabric-icons-1-4d521695.woff') format('woff')")},icons:{Paste:"",WindowsLogo:"",Error:"",GripperBarVertical:"",Unlock:"",Slideshow:"",Trim:"",AutoEnhanceOn:"",AutoEnhanceOff:"",Color:"",SaveAs:"",Light:"",Filters:"",AspectRatio:"",Contrast:"",Redo:"",Crop:"",PhotoCollection:"",Album:"",Rotate:"",PanoIndicator:"",Translate:"",RedEye:"",ViewOriginal:"",ThumbnailView:"",Package:"",Telemarketer:"",Warning:"",Financial:"",Education:"",ShoppingCart:"",Train:"",Move:"",TouchPointer:"",Merge:"",TurnRight:"",Ferry:"",Highlight:"",PowerButton:"",Tab:"",Admin:"",TVMonitor:"",Speakers:"",Game:"",HorizontalTabKey:"",UnstackSelected:"",StackIndicator:"",Nav2DMapView:"",StreetsideSplitMinimize:"",Car:"",Bus:"",EatDrink:"",SeeDo:"",LocationCircle:"",Home:"",SwitcherStartEnd:"",ParkingLocation:"",IncidentTriangle:"",Touch:"",MapDirections:"",CaretHollow:"",CaretSolid:"",History:"",Location:"",MapLayers:"",SearchNearby:"",Work:"",Recent:"",Hotel:"",Bank:"",LocationDot:"",Dictionary:"",ChromeBack:"",FolderOpen:"",PinnedFill:"",RevToggleKey:"",USB:"",Previous:"",Next:"",Sync:"",Help:"",Emoji:"",MailForward:"",ClosePane:"",OpenPane:"",PreviewLink:"",ZoomIn:"",Bookmarks:"",Document:"",ProtectedDocument:"",OpenInNewWindow:"",MailFill:"",ViewAll:"",Switch:"",Rename:"",Go:"",Remote:"",SelectAll:"",Orientation:"",Import:""}},t)}function tO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-2"',src:"url('".concat(e,"fabric-icons-2-63c99abf.woff') format('woff')")},icons:{Picture:"",ChromeClose:"",ShowResults:"",Message:"",CalendarDay:"",CalendarWeek:"",MailReplyAll:"",Read:"",Cut:"",PaymentCard:"",Copy:"",Important:"",MailReply:"",GotoToday:"",Font:"",FontColor:"",FolderFill:"",Permissions:"",DisableUpdates:"",Unfavorite:"",Italic:"",Underline:"",Bold:"",MoveToFolder:"",Dislike:"",Like:"",AlignCenter:"",OpenFile:"",ClearSelection:"",FontDecrease:"",FontIncrease:"",FontSize:"",CellPhone:"",RepeatOne:"",RepeatAll:"",Calculator:"",Library:"",PostUpdate:"",NewFolder:"",CalendarReply:"",UnsyncFolder:"",SyncFolder:"",BlockContact:"",Accept:"",BulletedList:"",Preview:"",News:"",Chat:"",Group:"",World:"",Comment:"",DockLeft:"",DockRight:"",Repair:"",Accounts:"",Street:"",RadioBullet:"",Stopwatch:"",Clock:"",WorldClock:"",AlarmClock:"",Photo:"",ActionCenter:"",Hospital:"",Timer:"",FullCircleMask:"",LocationFill:"",ChromeMinimize:"",ChromeRestore:"",Annotation:"",Fingerprint:"",Handwriting:"",ChromeFullScreen:"",Completed:"",Label:"",FlickDown:"",FlickUp:"",FlickLeft:"",FlickRight:"",MiniExpand:"",MiniContract:"",Streaming:"",MusicInCollection:"",OneDriveLogo:"",CompassNW:"",Code:"",LightningBolt:"",CalculatorMultiply:"",CalculatorAddition:"",CalculatorSubtract:"",CalculatorPercentage:"",CalculatorEqualTo:"",PrintfaxPrinterFile:"",StorageOptical:"",Communications:"",Headset:"",Health:"",Webcam2:"",FrontCamera:"",ChevronUpSmall:""}},t)}function iO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-3"',src:"url('".concat(e,"fabric-icons-3-089e217a.woff') format('woff')")},icons:{ChevronDownSmall:"",ChevronLeftSmall:"",ChevronRightSmall:"",ChevronUpMed:"",ChevronDownMed:"",ChevronLeftMed:"",ChevronRightMed:"",Devices2:"",PC1:"",PresenceChickletVideo:"",Reply:"",HalfAlpha:"",ConstructionCone:"",DoubleChevronLeftMed:"",Volume0:"",Volume1:"",Volume2:"",Volume3:"",Chart:"",Robot:"",Manufacturing:"",LockSolid:"",FitPage:"",FitWidth:"",BidiLtr:"",BidiRtl:"",RightDoubleQuote:"",Sunny:"",CloudWeather:"",Cloudy:"",PartlyCloudyDay:"",PartlyCloudyNight:"",ClearNight:"",RainShowersDay:"",Rain:"",Thunderstorms:"",RainSnow:"",Snow:"",BlowingSnow:"",Frigid:"",Fog:"",Squalls:"",Duststorm:"",Unknown:"",Precipitation:"",Ribbon:"",AreaChart:"",Assign:"",FlowChart:"",CheckList:"",Diagnostic:"",Generate:"",LineChart:"",Equalizer:"",BarChartHorizontal:"",BarChartVertical:"",Freezing:"",FunnelChart:"",Processing:"",Quantity:"",ReportDocument:"",StackColumnChart:"",SnowShowerDay:"",HailDay:"",WorkFlow:"",HourGlass:"",StoreLogoMed20:"",TimeSheet:"",TriangleSolid:"",UpgradeAnalysis:"",VideoSolid:"",RainShowersNight:"",SnowShowerNight:"",Teamwork:"",HailNight:"",PeopleAdd:"",Glasses:"",DateTime2:"",Shield:"",Header1:"",PageAdd:"",NumberedList:"",PowerBILogo:"",Info2:"",MusicInCollectionFill:"",Asterisk:"",ErrorBadge:"",CircleFill:"",Record2:"",AllAppsMirrored:"",BookmarksMirrored:"",BulletedListMirrored:"",CaretHollowMirrored:"",CaretSolidMirrored:"",ChromeBackMirrored:"",ClearSelectionMirrored:"",ClosePaneMirrored:"",DockLeftMirrored:"",DoubleChevronLeftMedMirrored:"",GoMirrored:""}},t)}function nO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-4"',src:"url('".concat(e,"fabric-icons-4-a656cc0a.woff') format('woff')")},icons:{HelpMirrored:"",ImportMirrored:"",ImportAllMirrored:"",ListMirrored:"",MailForwardMirrored:"",MailReplyMirrored:"",MailReplyAllMirrored:"",MiniContractMirrored:"",MiniExpandMirrored:"",OpenPaneMirrored:"",ParkingLocationMirrored:"",SendMirrored:"",ShowResultsMirrored:"",ThumbnailViewMirrored:"",Media:"",Devices3:"",Focus:"",VideoLightOff:"",Lightbulb:"",StatusTriangle:"",VolumeDisabled:"",Puzzle:"",EmojiNeutral:"",EmojiDisappointed:"",HomeSolid:"",Ringer:"",PDF:"",HeartBroken:"",StoreLogo16:"",MultiSelectMirrored:"",Broom:"",AddToShoppingList:"",Cocktails:"",Wines:"",Articles:"",Cycling:"",DietPlanNotebook:"",Pill:"",ExerciseTracker:"",HandsFree:"",Medical:"",Running:"",Weights:"",Trackers:"",AddNotes:"",AllCurrency:"",BarChart4:"",CirclePlus:"",Coffee:"",Cotton:"",Market:"",Money:"",PieDouble:"",PieSingle:"",RemoveFilter:"",Savings:"",Sell:"",StockDown:"",StockUp:"",Lamp:"",Source:"",MSNVideos:"",Cricket:"",Golf:"",Baseball:"",Soccer:"",MoreSports:"",AutoRacing:"",CollegeHoops:"",CollegeFootball:"",ProFootball:"",ProHockey:"",Rugby:"",SubstitutionsIn:"",Tennis:"",Arrivals:"",Design:"",Website:"",Drop:"",HistoricalWeather:"",SkiResorts:"",Snowflake:"",BusSolid:"",FerrySolid:"",AirplaneSolid:"",TrainSolid:"",Ticket:"",WifiWarning4:"",Devices4:"",AzureLogo:"",BingLogo:"",MSNLogo:"",OutlookLogoInverse:"",OfficeLogo:"",SkypeLogo:"",Door:"",EditMirrored:"",GiftCard:"",DoubleBookmark:"",StatusErrorFull:""}},t)}function rO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-5"',src:"url('".concat(e,"fabric-icons-5-f95ba260.woff') format('woff')")},icons:{Certificate:"",FastForward:"",Rewind:"",Photo2:"",OpenSource:"",Movers:"",CloudDownload:"",Family:"",WindDirection:"",Bug:"",SiteScan:"",BrowserScreenShot:"",F12DevTools:"",CSS:"",JS:"",DeliveryTruck:"",ReminderPerson:"",ReminderGroup:"",ReminderTime:"",TabletMode:"",Umbrella:"",NetworkTower:"",CityNext:"",CityNext2:"",Section:"",OneNoteLogoInverse:"",ToggleFilled:"",ToggleBorder:"",SliderThumb:"",ToggleThumb:"",Documentation:"",Badge:"",Giftbox:"",VisualStudioLogo:"",HomeGroup:"",ExcelLogoInverse:"",WordLogoInverse:"",PowerPointLogoInverse:"",Cafe:"",SpeedHigh:"",Commitments:"",ThisPC:"",MusicNote:"",MicOff:"",PlaybackRate1x:"",EdgeLogo:"",CompletedSolid:"",AlbumRemove:"",MessageFill:"",TabletSelected:"",MobileSelected:"",LaptopSelected:"",TVMonitorSelected:"",DeveloperTools:"",Shapes:"",InsertTextBox:"",LowerBrightness:"",WebComponents:"",OfflineStorage:"",DOM:"",CloudUpload:"",ScrollUpDown:"",DateTime:"",Event:"",Cake:"",Org:"",PartyLeader:"",DRM:"",CloudAdd:"",AppIconDefault:"",Photo2Add:"",Photo2Remove:"",Calories:"",POI:"",AddTo:"",RadioBtnOff:"",RadioBtnOn:"",ExploreContent:"",Product:"",ProgressLoopInner:"",ProgressLoopOuter:"",Blocked2:"",FangBody:"",Toolbox:"",PageHeader:"",ChatInviteFriend:"",Brush:"",Shirt:"",Crown:"",Diamond:"",ScaleUp:"",QRCode:"",Feedback:"",SharepointLogoInverse:"",YammerLogo:"",Hide:"",Uneditable:"",ReturnToSession:"",OpenFolderHorizontal:"",CalendarMirrored:""}},t)}function aO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-6"',src:"url('".concat(e,"fabric-icons-6-ef6fd590.woff') format('woff')")},icons:{SwayLogoInverse:"",OutOfOffice:"",Trophy:"",ReopenPages:"",EmojiTabSymbols:"",AADLogo:"",AccessLogo:"",AdminALogoInverse32:"",AdminCLogoInverse32:"",AdminDLogoInverse32:"",AdminELogoInverse32:"",AdminLLogoInverse32:"",AdminMLogoInverse32:"",AdminOLogoInverse32:"",AdminPLogoInverse32:"",AdminSLogoInverse32:"",AdminYLogoInverse32:"",DelveLogoInverse:"",ExchangeLogoInverse:"",LyncLogo:"",OfficeVideoLogoInverse:"",SocialListeningLogo:"",VisioLogoInverse:"",Balloons:"",Cat:"",MailAlert:"",MailCheck:"",MailLowImportance:"",MailPause:"",MailRepeat:"",SecurityGroup:"",Table:"",VoicemailForward:"",VoicemailReply:"",Waffle:"",RemoveEvent:"",EventInfo:"",ForwardEvent:"",WipePhone:"",AddOnlineMeeting:"",JoinOnlineMeeting:"",RemoveLink:"",PeopleBlock:"",PeopleRepeat:"",PeopleAlert:"",PeoplePause:"",TransferCall:"",AddPhone:"",UnknownCall:"",NoteReply:"",NoteForward:"",NotePinned:"",RemoveOccurrence:"",Timeline:"",EditNote:"",CircleHalfFull:"",Room:"",Unsubscribe:"",Subscribe:"",HardDrive:"",RecurringTask:"",TaskManager:"",TaskManagerMirrored:"",Combine:"",Split:"",DoubleChevronUp:"",DoubleChevronLeft:"",DoubleChevronRight:"",TextBox:"",TextField:"",NumberField:"",Dropdown:"",PenWorkspace:"",BookingsLogo:"",ClassNotebookLogoInverse:"",DelveAnalyticsLogo:"",DocsLogoInverse:"",Dynamics365Logo:"",DynamicSMBLogo:"",OfficeAssistantLogo:"",OfficeStoreLogo:"",OneNoteEduLogoInverse:"",PlannerLogo:"",PowerApps:"",Suitcase:"",ProjectLogoInverse:"",CaretLeft8:"",CaretRight8:"",CaretUp8:"",CaretDown8:"",CaretLeftSolid8:"",CaretRightSolid8:"",CaretUpSolid8:"",CaretDownSolid8:"",ClearFormatting:"",Superscript:"",Subscript:"",Strikethrough:"",Export:"",ExportMirrored:""}},t)}function sO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-7"',src:"url('".concat(e,"fabric-icons-7-2b97bb99.woff') format('woff')")},icons:{SingleBookmark:"",SingleBookmarkSolid:"",DoubleChevronDown:"",FollowUser:"",ReplyAll:"",WorkforceManagement:"",RecruitmentManagement:"",Questionnaire:"",ManagerSelfService:"",ProductionFloorManagement:"",ProductRelease:"",ProductVariant:"",ReplyMirrored:"",ReplyAllMirrored:"",Medal:"",AddGroup:"",QuestionnaireMirrored:"",CloudImportExport:"",TemporaryUser:"",CaretSolid16:"",GroupedDescending:"",GroupedAscending:"",AwayStatus:"",MyMoviesTV:"",GenericScan:"",AustralianRules:"",WifiEthernet:"",TrackersMirrored:"",DateTimeMirrored:"",StopSolid:"",DoubleChevronUp12:"",DoubleChevronDown12:"",DoubleChevronLeft12:"",DoubleChevronRight12:"",CalendarAgenda:"",ConnectVirtualMachine:"",AddEvent:"",AssetLibrary:"",DataConnectionLibrary:"",DocLibrary:"",FormLibrary:"",FormLibraryMirrored:"",ReportLibrary:"",ReportLibraryMirrored:"",ContactCard:"",CustomList:"",CustomListMirrored:"",IssueTracking:"",IssueTrackingMirrored:"",PictureLibrary:"",OfficeAddinsLogo:"",OfflineOneDriveParachute:"",OfflineOneDriveParachuteDisabled:"",TriangleSolidUp12:"",TriangleSolidDown12:"",TriangleSolidLeft12:"",TriangleSolidRight12:"",TriangleUp12:"",TriangleDown12:"",TriangleLeft12:"",TriangleRight12:"",ArrowUpRight8:"",ArrowDownRight8:"",DocumentSet:"",GoToDashboard:"",DelveAnalytics:"",ArrowUpRightMirrored8:"",ArrowDownRightMirrored8:"",CompanyDirectory:"",OpenEnrollment:"",CompanyDirectoryMirrored:"",OneDriveAdd:"",ProfileSearch:"",Header2:"",Header3:"",Header4:"",RingerSolid:"",Eyedropper:"",MarketDown:"",CalendarWorkWeek:"",SidePanel:"",GlobeFavorite:"",CaretTopLeftSolid8:"",CaretTopRightSolid8:"",ViewAll2:"",DocumentReply:"",PlayerSettings:"",ReceiptForward:"",ReceiptReply:"",ReceiptCheck:"",Fax:"",RecurringEvent:"",ReplyAlt:"",ReplyAllAlt:"",EditStyle:"",EditMail:"",Lifesaver:"",LifesaverLock:"",InboxCheck:"",FolderSearch:""}},t)}function oO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-8"',src:"url('".concat(e,"fabric-icons-8-6fdf1528.woff') format('woff')")},icons:{CollapseMenu:"",ExpandMenu:"",Boards:"",SunAdd:"",SunQuestionMark:"",LandscapeOrientation:"",DocumentSearch:"",PublicCalendar:"",PublicContactCard:"",PublicEmail:"",PublicFolder:"",WordDocument:"",PowerPointDocument:"",ExcelDocument:"",GroupedList:"",ClassroomLogo:"",Sections:"",EditPhoto:"",Starburst:"",ShareiOS:"",AirTickets:"",PencilReply:"",Tiles2:"",SkypeCircleCheck:"",SkypeCircleClock:"",SkypeCircleMinus:"",SkypeMessage:"",ClosedCaption:"",ATPLogo:"",OfficeFormsLogoInverse:"",RecycleBin:"",EmptyRecycleBin:"",Hide2:"",Breadcrumb:"",BirthdayCake:"",TimeEntry:"",CRMProcesses:"",PageEdit:"",PageArrowRight:"",PageRemove:"",Database:"",DataManagementSettings:"",CRMServices:"",EditContact:"",ConnectContacts:"",AppIconDefaultAdd:"",AppIconDefaultList:"",ActivateOrders:"",DeactivateOrders:"",ProductCatalog:"",ScatterChart:"",AccountActivity:"",DocumentManagement:"",CRMReport:"",KnowledgeArticle:"",Relationship:"",HomeVerify:"",ZipFolder:"",SurveyQuestions:"",TextDocument:"",TextDocumentShared:"",PageCheckedOut:"",PageShared:"",SaveAndClose:"",Script:"",Archive:"",ActivityFeed:"",Compare:"",EventDate:"",ArrowUpRight:"",CaretRight:"",SetAction:"",ChatBot:"",CaretSolidLeft:"",CaretSolidDown:"",CaretSolidRight:"",CaretSolidUp:"",PowerAppsLogo:"",PowerApps2Logo:"",SearchIssue:"",SearchIssueMirrored:"",FabricAssetLibrary:"",FabricDataConnectionLibrary:"",FabricDocLibrary:"",FabricFormLibrary:"",FabricFormLibraryMirrored:"",FabricReportLibrary:"",FabricReportLibraryMirrored:"",FabricPublicFolder:"",FabricFolderSearch:"",FabricMovetoFolder:"",FabricUnsyncFolder:"",FabricSyncFolder:"",FabricOpenFolderHorizontal:"",FabricFolder:"",FabricFolderFill:"",FabricNewFolder:"",FabricPictureLibrary:"",PhotoVideoMedia:"",AddFavorite:""}},t)}function lO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-9"',src:"url('".concat(e,"fabric-icons-9-c6162b42.woff') format('woff')")},icons:{AddFavoriteFill:"",BufferTimeBefore:"",BufferTimeAfter:"",BufferTimeBoth:"",PublishContent:"",ClipboardList:"",ClipboardListMirrored:"",CannedChat:"",SkypeForBusinessLogo:"",TabCenter:"",PageCheckedin:"",PageList:"",ReadOutLoud:"",CaretBottomLeftSolid8:"",CaretBottomRightSolid8:"",FolderHorizontal:"",MicrosoftStaffhubLogo:"",GiftboxOpen:"",StatusCircleOuter:"",StatusCircleInner:"",StatusCircleRing:"",StatusTriangleOuter:"",StatusTriangleInner:"",StatusTriangleExclamation:"",StatusCircleExclamation:"",StatusCircleErrorX:"",StatusCircleInfo:"",StatusCircleBlock:"",StatusCircleBlock2:"",StatusCircleQuestionMark:"",StatusCircleSync:"",Toll:"",ExploreContentSingle:"",CollapseContent:"",CollapseContentSingle:"",InfoSolid:"",GroupList:"",ProgressRingDots:"",CaloriesAdd:"",BranchFork:"",MuteChat:"",AddHome:"",AddWork:"",MobileReport:"",ScaleVolume:"",HardDriveGroup:"",FastMode:"",ToggleLeft:"",ToggleRight:"",TriangleShape:"",RectangleShape:"",CubeShape:"",Trophy2:"",BucketColor:"",BucketColorFill:"",Taskboard:"",SingleColumn:"",DoubleColumn:"",TripleColumn:"",ColumnLeftTwoThirds:"",ColumnRightTwoThirds:"",AccessLogoFill:"",AnalyticsLogo:"",AnalyticsQuery:"",NewAnalyticsQuery:"",AnalyticsReport:"",WordLogo:"",WordLogoFill:"",ExcelLogo:"",ExcelLogoFill:"",OneNoteLogo:"",OneNoteLogoFill:"",OutlookLogo:"",OutlookLogoFill:"",PowerPointLogo:"",PowerPointLogoFill:"",PublisherLogo:"",PublisherLogoFill:"",ScheduleEventAction:"",FlameSolid:"",ServerProcesses:"",Server:"",SaveAll:"",LinkedInLogo:"",Decimals:"",SidePanelMirrored:"",ProtectRestrict:"",Blog:"",UnknownMirrored:"",PublicContactCardMirrored:"",GridViewSmall:"",GridViewMedium:"",GridViewLarge:"",Step:"",StepInsert:"",StepShared:"",StepSharedAdd:"",StepSharedInsert:"",ViewDashboard:"",ViewList:""}},t)}function cO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-10"',src:"url('".concat(e,"fabric-icons-10-c4ded8e4.woff') format('woff')")},icons:{ViewListGroup:"",ViewListTree:"",TriggerAuto:"",TriggerUser:"",PivotChart:"",StackedBarChart:"",StackedLineChart:"",BuildQueue:"",BuildQueueNew:"",UserFollowed:"",ContactLink:"",Stack:"",Bullseye:"",VennDiagram:"",FiveTileGrid:"",FocalPoint:"",Insert:"",RingerRemove:"",TeamsLogoInverse:"",TeamsLogo:"",TeamsLogoFill:"",SkypeForBusinessLogoFill:"",SharepointLogo:"",SharepointLogoFill:"",DelveLogo:"",DelveLogoFill:"",OfficeVideoLogo:"",OfficeVideoLogoFill:"",ExchangeLogo:"",ExchangeLogoFill:"",Signin:"",DocumentApproval:"",CloneToDesktop:"",InstallToDrive:"",Blur:"",Build:"",ProcessMetaTask:"",BranchFork2:"",BranchLocked:"",BranchCommit:"",BranchCompare:"",BranchMerge:"",BranchPullRequest:"",BranchSearch:"",BranchShelveset:"",RawSource:"",MergeDuplicate:"",RowsGroup:"",RowsChild:"",Deploy:"",Redeploy:"",ServerEnviroment:"",VisioDiagram:"",HighlightMappedShapes:"",TextCallout:"",IconSetsFlag:"",VisioLogo:"",VisioLogoFill:"",VisioDocument:"",TimelineProgress:"",TimelineDelivery:"",Backlog:"",TeamFavorite:"",TaskGroup:"",TaskGroupMirrored:"",ScopeTemplate:"",AssessmentGroupTemplate:"",NewTeamProject:"",CommentAdd:"",CommentNext:"",CommentPrevious:"",ShopServer:"",LocaleLanguage:"",QueryList:"",UserSync:"",UserPause:"",StreamingOff:"",ArrowTallUpLeft:"",ArrowTallUpRight:"",ArrowTallDownLeft:"",ArrowTallDownRight:"",FieldEmpty:"",FieldFilled:"",FieldChanged:"",FieldNotChanged:"",RingerOff:"",PlayResume:"",BulletedList2:"",BulletedList2Mirrored:"",ImageCrosshair:"",GitGraph:"",Repo:"",RepoSolid:"",FolderQuery:"",FolderList:"",FolderListMirrored:"",LocationOutline:"",POISolid:"",CalculatorNotEqualTo:"",BoxSubtractSolid:""}},t)}function dO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-11"',src:"url('".concat(e,"fabric-icons-11-2a8393d6.woff') format('woff')")},icons:{BoxAdditionSolid:"",BoxMultiplySolid:"",BoxPlaySolid:"",BoxCheckmarkSolid:"",CirclePauseSolid:"",CirclePause:"",MSNVideosSolid:"",CircleStopSolid:"",CircleStop:"",NavigateBack:"",NavigateBackMirrored:"",NavigateForward:"",NavigateForwardMirrored:"",UnknownSolid:"",UnknownMirroredSolid:"",CircleAddition:"",CircleAdditionSolid:"",FilePDB:"",FileTemplate:"",FileSQL:"",FileJAVA:"",FileASPX:"",FileCSS:"",FileSass:"",FileLess:"",FileHTML:"",JavaScriptLanguage:"",CSharpLanguage:"",CSharp:"",VisualBasicLanguage:"",VB:"",CPlusPlusLanguage:"",CPlusPlus:"",FSharpLanguage:"",FSharp:"",TypeScriptLanguage:"",PythonLanguage:"",PY:"",CoffeeScript:"",MarkDownLanguage:"",FullWidth:"",FullWidthEdit:"",Plug:"",PlugSolid:"",PlugConnected:"",PlugDisconnected:"",UnlockSolid:"",Variable:"",Parameter:"",CommentUrgent:"",Storyboard:"",DiffInline:"",DiffSideBySide:"",ImageDiff:"",ImagePixel:"",FileBug:"",FileCode:"",FileComment:"",BusinessHoursSign:"",FileImage:"",FileSymlink:"",AutoFillTemplate:"",WorkItem:"",WorkItemBug:"",LogRemove:"",ColumnOptions:"",Packages:"",BuildIssue:"",AssessmentGroup:"",VariableGroup:"",FullHistory:"",Wheelchair:"",SingleColumnEdit:"",DoubleColumnEdit:"",TripleColumnEdit:"",ColumnLeftTwoThirdsEdit:"",ColumnRightTwoThirdsEdit:"",StreamLogo:"",PassiveAuthentication:"",AlertSolid:"",MegaphoneSolid:"",TaskSolid:"",ConfigurationSolid:"",BugSolid:"",CrownSolid:"",Trophy2Solid:"",QuickNoteSolid:"",ConstructionConeSolid:"",PageListSolid:"",PageListMirroredSolid:"",StarburstSolid:"",ReadingModeSolid:"",SadSolid:"",HealthSolid:"",ShieldSolid:"",GiftBoxSolid:"",ShoppingCartSolid:"",MailSolid:"",ChatSolid:"",RibbonSolid:""}},t)}function uO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-12"',src:"url('".concat(e,"fabric-icons-12-7e945a1e.woff') format('woff')")},icons:{FinancialSolid:"",FinancialMirroredSolid:"",HeadsetSolid:"",PermissionsSolid:"",ParkingSolid:"",ParkingMirroredSolid:"",DiamondSolid:"",AsteriskSolid:"",OfflineStorageSolid:"",BankSolid:"",DecisionSolid:"",Parachute:"",ParachuteSolid:"",FiltersSolid:"",ColorSolid:"",ReviewSolid:"",ReviewRequestSolid:"",ReviewRequestMirroredSolid:"",ReviewResponseSolid:"",FeedbackRequestSolid:"",FeedbackRequestMirroredSolid:"",FeedbackResponseSolid:"",WorkItemBar:"",WorkItemBarSolid:"",Separator:"",NavigateExternalInline:"",PlanView:"",TimelineMatrixView:"",EngineeringGroup:"",ProjectCollection:"",CaretBottomRightCenter8:"",CaretBottomLeftCenter8:"",CaretTopRightCenter8:"",CaretTopLeftCenter8:"",DonutChart:"",ChevronUnfold10:"",ChevronFold10:"",DoubleChevronDown8:"",DoubleChevronUp8:"",DoubleChevronLeft8:"",DoubleChevronRight8:"",ChevronDownEnd6:"",ChevronUpEnd6:"",ChevronLeftEnd6:"",ChevronRightEnd6:"",ContextMenu:"",AzureAPIManagement:"",AzureServiceEndpoint:"",VSTSLogo:"",VSTSAltLogo1:"",VSTSAltLogo2:"",FileTypeSolution:"",WordLogoInverse16:"",WordLogo16:"",WordLogoFill16:"",PowerPointLogoInverse16:"",PowerPointLogo16:"",PowerPointLogoFill16:"",ExcelLogoInverse16:"",ExcelLogo16:"",ExcelLogoFill16:"",OneNoteLogoInverse16:"",OneNoteLogo16:"",OneNoteLogoFill16:"",OutlookLogoInverse16:"",OutlookLogo16:"",OutlookLogoFill16:"",PublisherLogoInverse16:"",PublisherLogo16:"",PublisherLogoFill16:"",VisioLogoInverse16:"",VisioLogo16:"",VisioLogoFill16:"",TestBeaker:"",TestBeakerSolid:"",TestExploreSolid:"",TestAutoSolid:"",TestUserSolid:"",TestImpactSolid:"",TestPlan:"",TestStep:"",TestParameter:"",TestSuite:"",TestCase:"",Sprint:"",SignOut:"",TriggerApproval:"",Rocket:"",AzureKeyVault:"",Onboarding:"",Transition:"",LikeSolid:"",DislikeSolid:"",CRMCustomerInsightsApp:"",EditCreate:"",PlayReverseResume:"",PlayReverse:"",SearchData:"",UnSetColor:"",DeclineCall:""}},t)}function hO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-13"',src:"url('".concat(e,"fabric-icons-13-c3989a02.woff') format('woff')")},icons:{RectangularClipping:"",TeamsLogo16:"",TeamsLogoFill16:"",Spacer:"",SkypeLogo16:"",SkypeForBusinessLogo16:"",SkypeForBusinessLogoFill16:"",FilterSolid:"",MailUndelivered:"",MailTentative:"",MailTentativeMirrored:"",MailReminder:"",ReceiptUndelivered:"",ReceiptTentative:"",ReceiptTentativeMirrored:"",Inbox:"",IRMReply:"",IRMReplyMirrored:"",IRMForward:"",IRMForwardMirrored:"",VoicemailIRM:"",EventAccepted:"",EventTentative:"",EventTentativeMirrored:"",EventDeclined:"",IDBadge:"",BackgroundColor:"",OfficeFormsLogoInverse16:"",OfficeFormsLogo:"",OfficeFormsLogoFill:"",OfficeFormsLogo16:"",OfficeFormsLogoFill16:"",OfficeFormsLogoInverse24:"",OfficeFormsLogo24:"",OfficeFormsLogoFill24:"",PageLock:"",NotExecuted:"",NotImpactedSolid:"",FieldReadOnly:"",FieldRequired:"",BacklogBoard:"",ExternalBuild:"",ExternalTFVC:"",ExternalXAML:"",IssueSolid:"",DefectSolid:"",LadybugSolid:"",NugetLogo:"",TFVCLogo:"",ProjectLogo32:"",ProjectLogoFill32:"",ProjectLogo16:"",ProjectLogoFill16:"",SwayLogo32:"",SwayLogoFill32:"",SwayLogo16:"",SwayLogoFill16:"",ClassNotebookLogo32:"",ClassNotebookLogoFill32:"",ClassNotebookLogo16:"",ClassNotebookLogoFill16:"",ClassNotebookLogoInverse32:"",ClassNotebookLogoInverse16:"",StaffNotebookLogo32:"",StaffNotebookLogoFill32:"",StaffNotebookLogo16:"",StaffNotebookLogoFill16:"",StaffNotebookLogoInverted32:"",StaffNotebookLogoInverted16:"",KaizalaLogo:"",TaskLogo:"",ProtectionCenterLogo32:"",GallatinLogo:"",Globe2:"",Guitar:"",Breakfast:"",Brunch:"",BeerMug:"",Vacation:"",Teeth:"",Taxi:"",Chopsticks:"",SyncOccurence:"",UnsyncOccurence:"",GIF:"",PrimaryCalendar:"",SearchCalendar:"",VideoOff:"",MicrosoftFlowLogo:"",BusinessCenterLogo:"",ToDoLogoBottom:"",ToDoLogoTop:"",EditSolid12:"",EditSolidMirrored12:"",UneditableSolid12:"",UneditableSolidMirrored12:"",UneditableMirrored:"",AdminALogo32:"",AdminALogoFill32:"",ToDoLogoInverse:""}},t)}function pO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-14"',src:"url('".concat(e,"fabric-icons-14-5cf58db8.woff') format('woff')")},icons:{Snooze:"",WaffleOffice365:"",ImageSearch:"",NewsSearch:"",VideoSearch:"",R:"",FontColorA:"",FontColorSwatch:"",LightWeight:"",NormalWeight:"",SemiboldWeight:"",GroupObject:"",UngroupObject:"",AlignHorizontalLeft:"",AlignHorizontalCenter:"",AlignHorizontalRight:"",AlignVerticalTop:"",AlignVerticalCenter:"",AlignVerticalBottom:"",HorizontalDistributeCenter:"",VerticalDistributeCenter:"",Ellipse:"",Line:"",Octagon:"",Hexagon:"",Pentagon:"",RightTriangle:"",HalfCircle:"",QuarterCircle:"",ThreeQuarterCircle:"","6PointStar":"","12PointStar":"",ArrangeBringToFront:"",ArrangeSendToBack:"",ArrangeSendBackward:"",ArrangeBringForward:"",BorderDash:"",BorderDot:"",LineStyle:"",LineThickness:"",WindowEdit:"",HintText:"",MediaAdd:"",AnchorLock:"",AutoHeight:"",ChartSeries:"",ChartXAngle:"",ChartYAngle:"",Combobox:"",LineSpacing:"",Padding:"",PaddingTop:"",PaddingBottom:"",PaddingLeft:"",PaddingRight:"",NavigationFlipper:"",AlignJustify:"",TextOverflow:"",VisualsFolder:"",VisualsStore:"",PictureCenter:"",PictureFill:"",PicturePosition:"",PictureStretch:"",PictureTile:"",Slider:"",SliderHandleSize:"",DefaultRatio:"",NumberSequence:"",GUID:"",ReportAdd:"",DashboardAdd:"",MapPinSolid:"",WebPublish:"",PieSingleSolid:"",BlockedSolid:"",DrillDown:"",DrillDownSolid:"",DrillExpand:"",DrillShow:"",SpecialEvent:"",OneDriveFolder16:"",FunctionalManagerDashboard:"",BIDashboard:"",CodeEdit:"",RenewalCurrent:"",RenewalFuture:"",SplitObject:"",BulkUpload:"",DownloadDocument:"",GreetingCard:"",Flower:"",WaitlistConfirm:"",WaitlistConfirmMirrored:"",LaptopSecure:"",DragObject:"",EntryView:"",EntryDecline:"",ContactCardSettings:"",ContactCardSettingsMirrored:""}},t)}function gO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-15"',src:"url('".concat(e,"fabric-icons-15-3807251b.woff') format('woff')")},icons:{CalendarSettings:"",CalendarSettingsMirrored:"",HardDriveLock:"",HardDriveUnlock:"",AccountManagement:"",ReportWarning:"",TransitionPop:"",TransitionPush:"",TransitionEffect:"",LookupEntities:"",ExploreData:"",AddBookmark:"",SearchBookmark:"",DrillThrough:"",MasterDatabase:"",CertifiedDatabase:"",MaximumValue:"",MinimumValue:"",VisualStudioIDELogo32:"",PasteAsText:"",PasteAsCode:"",BrowserTab:"",BrowserTabScreenshot:"",DesktopScreenshot:"",FileYML:"",ClipboardSolid:"",FabricUserFolder:"",FabricNetworkFolder:"",BullseyeTarget:"",AnalyticsView:"",Video360Generic:"",Untag:"",Leave:"",Trending12:"",Blocked12:"",Warning12:"",CheckedOutByOther12:"",CheckedOutByYou12:"",CircleShapeSolid:"",SquareShapeSolid:"",TriangleShapeSolid:"",DropShapeSolid:"",RectangleShapeSolid:"",ZoomToFit:"",InsertColumnsLeft:"",InsertColumnsRight:"",InsertRowsAbove:"",InsertRowsBelow:"",DeleteColumns:"",DeleteRows:"",DeleteRowsMirrored:"",DeleteTable:"",AccountBrowser:"",VersionControlPush:"",StackedColumnChart2:"",TripleColumnWide:"",QuadColumn:"",WhiteBoardApp16:"",WhiteBoardApp32:"",PinnedSolid:"",InsertSignatureLine:"",ArrangeByFrom:"",Phishing:"",CreateMailRule:"",PublishCourse:"",DictionaryRemove:"",UserRemove:"",UserEvent:"",Encryption:"",PasswordField:"",OpenInNewTab:"",Hide3:"",VerifiedBrandSolid:"",MarkAsProtected:"",AuthenticatorApp:"",WebTemplate:"",DefenderTVM:"",MedalSolid:"",D365TalentLearn:"",D365TalentInsight:"",D365TalentHRCore:"",BacklogList:"",ButtonControl:"",TableGroup:"",MountainClimbing:"",TagUnknown:"",TagUnknownMirror:"",TagUnknown12:"",TagUnknown12Mirror:"",Link12:"",Presentation:"",Presentation12:"",Lock12:"",BuildDefinition:"",ReleaseDefinition:"",SaveTemplate:"",UserGauge:"",BlockedSiteSolid12:"",TagSolid:"",OfficeChat:""}},t)}function mO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-16"',src:"url('".concat(e,"fabric-icons-16-9cf93f3b.woff') format('woff')")},icons:{OfficeChatSolid:"",MailSchedule:"",WarningSolid:"",Blocked2Solid:"",SkypeCircleArrow:"",SkypeArrow:"",SyncStatus:"",SyncStatusSolid:"",ProjectDocument:"",ToDoLogoOutline:"",VisioOnlineLogoFill32:"",VisioOnlineLogo32:"",VisioOnlineLogoCloud32:"",VisioDiagramSync:"",Event12:"",EventDateMissed12:"",UserOptional:"",ResponsesMenu:"",DoubleDownArrow:"",DistributeDown:"",BookmarkReport:"",FilterSettings:"",GripperDotsVertical:"",MailAttached:"",AddIn:"",LinkedDatabase:"",TableLink:"",PromotedDatabase:"",BarChartVerticalFilter:"",BarChartVerticalFilterSolid:"",MicOff2:"",MicrosoftTranslatorLogo:"",ShowTimeAs:"",FileRequest:"",WorkItemAlert:"",PowerBILogo16:"",PowerBILogoBackplate16:"",BulletedListText:"",BulletedListBullet:"",BulletedListTextMirrored:"",BulletedListBulletMirrored:"",NumberedListText:"",NumberedListNumber:"",NumberedListTextMirrored:"",NumberedListNumberMirrored:"",RemoveLinkChain:"",RemoveLinkX:"",FabricTextHighlight:"",ClearFormattingA:"",ClearFormattingEraser:"",Photo2Fill:"",IncreaseIndentText:"",IncreaseIndentArrow:"",DecreaseIndentText:"",DecreaseIndentArrow:"",IncreaseIndentTextMirrored:"",IncreaseIndentArrowMirrored:"",DecreaseIndentTextMirrored:"",DecreaseIndentArrowMirrored:"",CheckListText:"",CheckListCheck:"",CheckListTextMirrored:"",CheckListCheckMirrored:"",NumberSymbol:"",Coupon:"",VerifiedBrand:"",ReleaseGate:"",ReleaseGateCheck:"",ReleaseGateError:"",M365InvoicingLogo:"",RemoveFromShoppingList:"",ShieldAlert:"",FabricTextHighlightComposite:"",Dataflows:"",GenericScanFilled:"",DiagnosticDataBarTooltip:"",SaveToMobile:"",Orientation2:"",ScreenCast:"",ShowGrid:"",SnapToGrid:"",ContactList:"",NewMail:"",EyeShadow:"",FabricFolderConfirm:"",InformationBarriers:"",CommentActive:"",ColumnVerticalSectionEdit:"",WavingHand:"",ShakeDevice:"",SmartGlassRemote:"",Rotate90Clockwise:"",Rotate90CounterClockwise:"",CampaignTemplate:"",ChartTemplate:"",PageListFilter:"",SecondaryNav:"",ColumnVerticalSection:"",SkypeCircleSlash:"",SkypeSlash:""}},t)}function fO(e,t){void 0===e&&(e=""),Wa({style:{MozOsxFontSmoothing:"grayscale",WebkitFontSmoothing:"antialiased",fontStyle:"normal",fontWeight:"normal",speak:"none"},fontFace:{fontFamily:'"FabricMDL2Icons-17"',src:"url('".concat(e,"fabric-icons-17-0c4ed701.woff') format('woff')")},icons:{CustomizeToolbar:"",DuplicateRow:"",RemoveFromTrash:"",MailOptions:"",Childof:"",Footer:"",Header:"",BarChartVerticalFill:"",StackedColumnChart2Fill:"",PlainText:"",AccessibiltyChecker:"",DatabaseSync:"",ReservationOrders:"",TabOneColumn:"",TabTwoColumn:"",TabThreeColumn:"",BulletedTreeList:"",MicrosoftTranslatorLogoGreen:"",MicrosoftTranslatorLogoBlue:"",InternalInvestigation:"",AddReaction:"",ContactHeart:"",VisuallyImpaired:"",EventToDoLogo:"",Variable2:"",ModelingView:"",DisconnectVirtualMachine:"",ReportLock:"",Uneditable2:"",Uneditable2Mirrored:"",BarChartVerticalEdit:"",GlobalNavButtonActive:"",PollResults:"",Rerun:"",QandA:"",QandAMirror:"",BookAnswers:"",AlertSettings:"",TrimStart:"",TrimEnd:"",TableComputed:"",DecreaseIndentLegacy:"",IncreaseIndentLegacy:"",SizeLegacy:""}},t)}ns("@fluentui/font-icons-mdl2","8.5.35");var vO="".concat("https://res.cdn.office.net/files/fabric-cdn-prod_20240129.001","/assets/icons/"),SO=Tn();!function(e,t){var i,n;void 0===e&&(e=(null===(i=null==SO?void 0:SO.FabricConfig)||void 0===i?void 0:i.iconBaseUrl)||(null===(n=null==SO?void 0:SO.FabricConfig)||void 0===n?void 0:n.fontBaseUrl)||vO),[ZD,XD,eO,tO,iO,nO,rO,aO,sO,oO,lO,cO,dO,uO,hO,pO,gO,mO,fO].forEach((function(t){return t(e,undefined)})),qa("trash","delete"),qa("onedrive","onedrivelogo"),qa("alertsolid12","eventdatemissed12"),qa("sixpointstar","6pointstar"),qa("twelvepointstar","12pointstar"),qa("toggleon","toggleleft"),qa("toggleoff","toggleright")}();const yO=async function(t,n,r){const{userId:a,token:s,displayName:o,targetCallees:l,options:c}=t,u=await function(e){return fi(this,void 0,void 0,(function*(){if(f(e.userId))throw new Error("Microsoft Teams user identifier is not supported by AzureCommunicationCallAdapter. Instead use TeamsCallAdapter.");return _i({userId:e.userId,displayName:e.displayName,credential:e.credential,locator:e.locator,targetCallees:e.targetCallees,alternateCallerId:e.alternateCallerId,options:e.options})}))}({userId:a,displayName:o??"anonymous",credential:new d(s),targetCallees:l||[l.foreach((e=>E(e)))],options:c});if(!n)throw new Error("Failed to find the root element");return(0,i.s)(n).render(e.createElement(JD,{...r,adapter:u},null)),u}})(),a})()));