@cloudflare/realtimekit 0.5.0-staging.49 → 0.5.0-staging.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.cjs.js CHANGED
@@ -1,45 +1,34 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var kt={exports:{}},fe={};/*
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var Dt={exports:{}},ye={};/*
2
2
  object-assign
3
3
  (c) Sindre Sorhus
4
4
  @license MIT
5
- */var Cu=Object.getOwnPropertySymbols,qv=Object.prototype.hasOwnProperty,Kv=Object.prototype.propertyIsEnumerable;function zv(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Yv(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}var Qv=Yv()?Object.assign:function(t,e){for(var r,n=zv(t),i,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var o in r)qv.call(r,o)&&(n[o]=r[o]);if(Cu){i=Cu(r);for(var a=0;a<i.length;a++)Kv.call(r,i[a])&&(n[i[a]]=r[i[a]])}}return n};/** @license React v17.0.2
5
+ */var ph=Object.getOwnPropertySymbols,Ny=Object.prototype.hasOwnProperty,Ly=Object.prototype.propertyIsEnumerable;function xy(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function Uy(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}var Fy=Uy()?Object.assign:function(t,e){for(var r,n=xy(t),i,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var o in r)Ny.call(r,o)&&(n[o]=r[o]);if(ph){i=ph(r);for(var a=0;a<i.length;a++)Ly.call(r,i[a])&&(n[i[a]]=r[i[a]])}}return n};/** @license React v17.0.2
6
6
  * react.production.min.js
7
7
  *
8
8
  * Copyright (c) Facebook, Inc. and its affiliates.
9
9
  *
10
10
  * This source code is licensed under the MIT license found in the
11
11
  * LICENSE file in the root directory of this source tree.
12
- */var Pl=Qv,os=60103,um=60106;fe.Fragment=60107;fe.StrictMode=60108;fe.Profiler=60114;var hm=60109,pm=60110,mm=60112;fe.Suspense=60113;var fm=60115,gm=60116;if(typeof Symbol=="function"&&Symbol.for){var qt=Symbol.for;os=qt("react.element"),um=qt("react.portal"),fe.Fragment=qt("react.fragment"),fe.StrictMode=qt("react.strict_mode"),fe.Profiler=qt("react.profiler"),hm=qt("react.provider"),pm=qt("react.context"),mm=qt("react.forward_ref"),fe.Suspense=qt("react.suspense"),fm=qt("react.memo"),gm=qt("react.lazy")}var Iu=typeof Symbol=="function"&&Symbol.iterator;function Xv(t){return t===null||typeof t!="object"?null:(t=Iu&&t[Iu]||t["@@iterator"],typeof t=="function"?t:null)}function uo(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r<arguments.length;r++)e+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var vm={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ym={};function as(t,e,r){this.props=t,this.context=e,this.refs=ym,this.updater=r||vm}as.prototype.isReactComponent={};as.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error(uo(85));this.updater.enqueueSetState(this,t,e,"setState")};as.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Em(){}Em.prototype=as.prototype;function Al(t,e,r){this.props=t,this.context=e,this.refs=ym,this.updater=r||vm}var Ml=Al.prototype=new Em;Ml.constructor=Al;Pl(Ml,as.prototype);Ml.isPureReactComponent=!0;var Dl={current:null},Sm=Object.prototype.hasOwnProperty,Tm={key:!0,ref:!0,__self:!0,__source:!0};function _m(t,e,r){var n,i={},s=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)Sm.call(e,n)&&!Tm.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1<a){for(var d=Array(a),h=0;h<a;h++)d[h]=arguments[h+2];i.children=d}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:os,type:t,key:s,ref:o,props:i,_owner:Dl.current}}function Zv(t,e){return{$$typeof:os,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function Ol(t){return typeof t=="object"&&t!==null&&t.$$typeof===os}function ey(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Ru=/\/+/g;function Kc(t,e){return typeof t=="object"&&t!==null&&t.key!=null?ey(""+t.key):e.toString(36)}function oa(t,e,r,n,i){var s=typeof t;(s==="undefined"||s==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(s){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case os:case um:o=!0}}if(o)return o=t,i=i(o),t=n===""?"."+Kc(o,0):n,Array.isArray(i)?(r="",t!=null&&(r=t.replace(Ru,"$&/")+"/"),oa(i,e,r,"",function(h){return h})):i!=null&&(Ol(i)&&(i=Zv(i,r+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(Ru,"$&/")+"/")+t)),e.push(i)),1;if(o=0,n=n===""?".":n+":",Array.isArray(t))for(var a=0;a<t.length;a++){s=t[a];var d=n+Kc(s,a);o+=oa(s,e,r,d,i)}else if(d=Xv(t),typeof d=="function")for(t=d.call(t),a=0;!(s=t.next()).done;)s=s.value,d=n+Kc(s,a++),o+=oa(s,e,r,d,i);else if(s==="object")throw e=""+t,Error(uo(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e));return o}function bo(t,e,r){if(t==null)return t;var n=[],i=0;return oa(t,n,"","",function(s){return e.call(r,s,i++)}),n}function ty(t){if(t._status===-1){var e=t._result;e=e(),t._status=0,t._result=e,e.then(function(r){t._status===0&&(r=r.default,t._status=1,t._result=r)},function(r){t._status===0&&(t._status=2,t._result=r)})}if(t._status===1)return t._result;throw t._result}var km={current:null};function Vr(){var t=km.current;if(t===null)throw Error(uo(321));return t}var ry={ReactCurrentDispatcher:km,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:Dl,IsSomeRendererActing:{current:!1},assign:Pl};fe.Children={map:bo,forEach:function(t,e,r){bo(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return bo(t,function(){e++}),e},toArray:function(t){return bo(t,function(e){return e})||[]},only:function(t){if(!Ol(t))throw Error(uo(143));return t}};fe.Component=as;fe.PureComponent=Al;fe.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ry;fe.cloneElement=function(t,e,r){if(t==null)throw Error(uo(267,t));var n=Pl({},t.props),i=t.key,s=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(s=e.ref,o=Dl.current),e.key!==void 0&&(i=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(d in e)Sm.call(e,d)&&!Tm.hasOwnProperty(d)&&(n[d]=e[d]===void 0&&a!==void 0?a[d]:e[d])}var d=arguments.length-2;if(d===1)n.children=r;else if(1<d){a=Array(d);for(var h=0;h<d;h++)a[h]=arguments[h+2];n.children=a}return{$$typeof:os,type:t.type,key:i,ref:s,props:n,_owner:o}};fe.createContext=function(t,e){return e===void 0&&(e=null),t={$$typeof:pm,_calculateChangedBits:e,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider={$$typeof:hm,_context:t},t.Consumer=t};fe.createElement=_m;fe.createFactory=function(t){var e=_m.bind(null,t);return e.type=t,e};fe.createRef=function(){return{current:null}};fe.forwardRef=function(t){return{$$typeof:mm,render:t}};fe.isValidElement=Ol;fe.lazy=function(t){return{$$typeof:gm,_payload:{_status:-1,_result:t},_init:ty}};fe.memo=function(t,e){return{$$typeof:fm,type:t,compare:e===void 0?null:e}};fe.useCallback=function(t,e){return Vr().useCallback(t,e)};fe.useContext=function(t,e){return Vr().useContext(t,e)};fe.useDebugValue=function(){};fe.useEffect=function(t,e){return Vr().useEffect(t,e)};fe.useImperativeHandle=function(t,e,r){return Vr().useImperativeHandle(t,e,r)};fe.useLayoutEffect=function(t,e){return Vr().useLayoutEffect(t,e)};fe.useMemo=function(t,e){return Vr().useMemo(t,e)};fe.useReducer=function(t,e,r){return Vr().useReducer(t,e,r)};fe.useRef=function(t){return Vr().useRef(t)};fe.useState=function(t){return Vr().useState(t)};fe.version="17.0.2";kt.exports=fe;var ny=kt.exports,wo,iy=new Uint8Array(16);function sy(){if(!wo&&(wo=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!wo))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return wo(iy)}var oy=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Nl(t){return typeof t=="string"&&oy.test(t)}var st=[];for(var zc=0;zc<256;++zc)st.push((zc+256).toString(16).substr(1));function ay(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(st[t[e+0]]+st[t[e+1]]+st[t[e+2]]+st[t[e+3]]+"-"+st[t[e+4]]+st[t[e+5]]+"-"+st[t[e+6]]+st[t[e+7]]+"-"+st[t[e+8]]+st[t[e+9]]+"-"+st[t[e+10]]+st[t[e+11]]+st[t[e+12]]+st[t[e+13]]+st[t[e+14]]+st[t[e+15]]).toLowerCase();if(!Nl(r))throw TypeError("Stringified UUID is invalid");return r}function di(t,e,r){t=t||{};var n=t.random||(t.rng||sy)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return ay(n)}const cy={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},bm={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Be={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},gt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Xr={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class N{static getFirstMatch(e,r){const n=r.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,r){const n=r.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,r,n){if(e.test(r))return n}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),r[0]===10)switch(r[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),!(r[0]===1&&r[1]<5)){if(r[0]===1&&r[1]<6)return"Cupcake";if(r[0]===1&&r[1]>=6)return"Donut";if(r[0]===2&&r[1]<2)return"Eclair";if(r[0]===2&&r[1]===2)return"Froyo";if(r[0]===2&&r[1]>2)return"Gingerbread";if(r[0]===3)return"Honeycomb";if(r[0]===4&&r[1]<1)return"Ice Cream Sandwich";if(r[0]===4&&r[1]<4)return"Jelly Bean";if(r[0]===4&&r[1]>=4)return"KitKat";if(r[0]===5)return"Lollipop";if(r[0]===6)return"Marshmallow";if(r[0]===7)return"Nougat";if(r[0]===8)return"Oreo";if(r[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,r,n=!1){const i=N.getVersionPrecision(e),s=N.getVersionPrecision(r);let o=Math.max(i,s),a=0;const d=N.map([e,r],h=>{const p=o-N.getVersionPrecision(h),f=h+new Array(p+1).join(".0");return N.map(f.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===a)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(e,r){const n=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,r);for(i=0;i<e.length;i+=1)n.push(r(e[i]));return n}static find(e,r){let n,i;if(Array.prototype.find)return Array.prototype.find.call(e,r);for(n=0,i=e.length;n<i;n+=1){const s=e[n];if(r(s,n))return s}}static assign(e,...r){const n=e;let i,s;if(Object.assign)return Object.assign(e,...r);for(i=0,s=r.length;i<s;i+=1){const o=r[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{n[d]=o[d]})}return e}static getBrowserAlias(e){return cy[e]}static getBrowserTypeByAlias(e){return bm[e]||""}}const _e=/version\/(\d+(\.?_?\d+)+)/i,dy=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=N.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=N.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=N.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=N.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=N.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=N.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=N.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=N.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=N.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=N.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=N.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=N.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=N.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=N.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=N.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=N.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=N.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=N.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=N.getFirstMatch(_e,t)||N.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=N.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=N.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=N.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=N.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=N.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=N.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=N.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=N.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=N.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=N.getFirstMatch(_e,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,r=/^(.*)\/(.*)[ \t]\((.*)/,i=t.search("\\(")!==-1?r:e;return{name:N.getFirstMatch(i,t),version:N.getSecondMatch(i,t)}}}];var ly=[{test:[/Roku\/DVP/],describe(t){const e=N.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:gt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=N.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:gt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=N.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=N.getWindowsVersionName(e);return{name:gt.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:gt.iOS},r=N.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=N.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=N.getMacOSVersionName(e),n={name:gt.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=N.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:gt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=N.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=N.getAndroidVersionName(e),n={name:gt.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=N.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:gt.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=N.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||N.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||N.getFirstMatch(/\bbb(\d+)/i,t);return{name:gt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=N.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:gt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=N.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:gt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:gt.Linux}}},{test:[/CrOS/],describe(){return{name:gt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=N.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:gt.PlayStation4,version:e}}}],uy=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=N.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:Be.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Be.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Be.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Be.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Be.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Be.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Be.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=N.getFirstMatch(/(ipod|iphone)/i,t);return{type:Be.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Be.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Be.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Be.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Be.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Be.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Be.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Be.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Be.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Be.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Be.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Be.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Be.tv}}}],hy=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Xr.Blink};const r=N.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Xr.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:Xr.Trident},r=N.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Xr.Presto},r=N.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:Xr.Gecko},r=N.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Xr.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Xr.WebKit},r=N.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class Pu{constructor(e,r=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},r!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=N.find(dy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=N.find(ly,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:r}=this.getOS();return e?String(r).toLowerCase()||"":r||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:r}=this.getPlatform();return e?String(r).toLowerCase()||"":r||""}parsePlatform(){this.parsedResult.platform={};const e=N.find(uy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=N.find(hy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return N.assign({},this.parsedResult)}satisfies(e){const r={};let n=0;const i={};let s=0;if(Object.keys(e).forEach(a=>{const d=e[a];typeof d=="string"?(i[a]=d,s+=1):typeof d=="object"&&(r[a]=d,n+=1)}),n>0){const a=Object.keys(r),d=N.find(a,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=N.find(a,p=>this.isPlatform(p));if(h){const p=this.satisfies(r[h]);if(p!==void 0)return p}}if(s>0){const a=Object.keys(i),d=N.find(a,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(e,r=!1){const n=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=N.getBrowserTypeByAlias(i);return r&&s&&(i=s.toLowerCase()),i===n}compareVersion(e){let r=[0],n=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(i=!0,n=e.substr(2)):r=[],e[0]===">"?r.push(1):r.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(i=!0,n=e.substr(1)),r.indexOf(N.compareVersions(s,n,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,r=!1){return this.isBrowser(e,r)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(r=>this.is(r))}}/*!
12
+ */var fu=Fy,vs=60103,Ym=60106;ye.Fragment=60107;ye.StrictMode=60108;ye.Profiler=60114;var Qm=60109,Xm=60110,Zm=60112;ye.Suspense=60113;var ef=60115,tf=60116;if(typeof Symbol=="function"&&Symbol.for){var ir=Symbol.for;vs=ir("react.element"),Ym=ir("react.portal"),ye.Fragment=ir("react.fragment"),ye.StrictMode=ir("react.strict_mode"),ye.Profiler=ir("react.profiler"),Qm=ir("react.provider"),Xm=ir("react.context"),Zm=ir("react.forward_ref"),ye.Suspense=ir("react.suspense"),ef=ir("react.memo"),tf=ir("react.lazy")}var mh=typeof Symbol=="function"&&Symbol.iterator;function Vy(t){return t===null||typeof t!="object"?null:(t=mh&&t[mh]||t["@@iterator"],typeof t=="function"?t:null)}function Ko(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,r=1;r<arguments.length;r++)e+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var rf={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},nf={};function ys(t,e,r){this.props=t,this.context=e,this.refs=nf,this.updater=r||rf}ys.prototype.isReactComponent={};ys.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error(Ko(85));this.updater.enqueueSetState(this,t,e,"setState")};ys.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function sf(){}sf.prototype=ys.prototype;function gu(t,e,r){this.props=t,this.context=e,this.refs=nf,this.updater=r||rf}var vu=gu.prototype=new sf;vu.constructor=gu;fu(vu,ys.prototype);vu.isPureReactComponent=!0;var yu={current:null},of=Object.prototype.hasOwnProperty,af={key:!0,ref:!0,__self:!0,__source:!0};function cf(t,e,r){var n,i={},s=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(s=""+e.key),e)of.call(e,n)&&!af.hasOwnProperty(n)&&(i[n]=e[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1<a){for(var d=Array(a),h=0;h<a;h++)d[h]=arguments[h+2];i.children=d}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return{$$typeof:vs,type:t,key:s,ref:o,props:i,_owner:yu.current}}function By(t,e){return{$$typeof:vs,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function Su(t){return typeof t=="object"&&t!==null&&t.$$typeof===vs}function jy(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var fh=/\/+/g;function Md(t,e){return typeof t=="object"&&t!==null&&t.key!=null?jy(""+t.key):e.toString(36)}function $a(t,e,r,n,i){var s=typeof t;(s==="undefined"||s==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(s){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case vs:case Ym:o=!0}}if(o)return o=t,i=i(o),t=n===""?"."+Md(o,0):n,Array.isArray(i)?(r="",t!=null&&(r=t.replace(fh,"$&/")+"/"),$a(i,e,r,"",function(h){return h})):i!=null&&(Su(i)&&(i=By(i,r+(!i.key||o&&o.key===i.key?"":(""+i.key).replace(fh,"$&/")+"/")+t)),e.push(i)),1;if(o=0,n=n===""?".":n+":",Array.isArray(t))for(var a=0;a<t.length;a++){s=t[a];var d=n+Md(s,a);o+=$a(s,e,r,d,i)}else if(d=Vy(t),typeof d=="function")for(t=d.call(t),a=0;!(s=t.next()).done;)s=s.value,d=n+Md(s,a++),o+=$a(s,e,r,d,i);else if(s==="object")throw e=""+t,Error(Ko(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e));return o}function ca(t,e,r){if(t==null)return t;var n=[],i=0;return $a(t,n,"","",function(s){return e.call(r,s,i++)}),n}function Hy(t){if(t._status===-1){var e=t._result;e=e(),t._status=0,t._result=e,e.then(function(r){t._status===0&&(r=r.default,t._status=1,t._result=r)},function(r){t._status===0&&(t._status=2,t._result=r)})}if(t._status===1)return t._result;throw t._result}var df={current:null};function rn(){var t=df.current;if(t===null)throw Error(Ko(321));return t}var Wy={ReactCurrentDispatcher:df,ReactCurrentBatchConfig:{transition:0},ReactCurrentOwner:yu,IsSomeRendererActing:{current:!1},assign:fu};ye.Children={map:ca,forEach:function(t,e,r){ca(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return ca(t,function(){e++}),e},toArray:function(t){return ca(t,function(e){return e})||[]},only:function(t){if(!Su(t))throw Error(Ko(143));return t}};ye.Component=ys;ye.PureComponent=gu;ye.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Wy;ye.cloneElement=function(t,e,r){if(t==null)throw Error(Ko(267,t));var n=fu({},t.props),i=t.key,s=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(s=e.ref,o=yu.current),e.key!==void 0&&(i=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(d in e)of.call(e,d)&&!af.hasOwnProperty(d)&&(n[d]=e[d]===void 0&&a!==void 0?a[d]:e[d])}var d=arguments.length-2;if(d===1)n.children=r;else if(1<d){a=Array(d);for(var h=0;h<d;h++)a[h]=arguments[h+2];n.children=a}return{$$typeof:vs,type:t.type,key:i,ref:s,props:n,_owner:o}};ye.createContext=function(t,e){return e===void 0&&(e=null),t={$$typeof:Xm,_calculateChangedBits:e,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider={$$typeof:Qm,_context:t},t.Consumer=t};ye.createElement=cf;ye.createFactory=function(t){var e=cf.bind(null,t);return e.type=t,e};ye.createRef=function(){return{current:null}};ye.forwardRef=function(t){return{$$typeof:Zm,render:t}};ye.isValidElement=Su;ye.lazy=function(t){return{$$typeof:tf,_payload:{_status:-1,_result:t},_init:Hy}};ye.memo=function(t,e){return{$$typeof:ef,type:t,compare:e===void 0?null:e}};ye.useCallback=function(t,e){return rn().useCallback(t,e)};ye.useContext=function(t,e){return rn().useContext(t,e)};ye.useDebugValue=function(){};ye.useEffect=function(t,e){return rn().useEffect(t,e)};ye.useImperativeHandle=function(t,e,r){return rn().useImperativeHandle(t,e,r)};ye.useLayoutEffect=function(t,e){return rn().useLayoutEffect(t,e)};ye.useMemo=function(t,e){return rn().useMemo(t,e)};ye.useReducer=function(t,e,r){return rn().useReducer(t,e,r)};ye.useRef=function(t){return rn().useRef(t)};ye.useState=function(t){return rn().useState(t)};ye.version="17.0.2";Dt.exports=ye;var $y=Dt.exports,da,Jy=new Uint8Array(16);function Gy(){if(!da&&(da=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!da))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return da(Jy)}var qy=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Eu(t){return typeof t=="string"&&qy.test(t)}var mt=[];for(var Dd=0;Dd<256;++Dd)mt.push((Dd+256).toString(16).substr(1));function zy(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(mt[t[e+0]]+mt[t[e+1]]+mt[t[e+2]]+mt[t[e+3]]+"-"+mt[t[e+4]]+mt[t[e+5]]+"-"+mt[t[e+6]]+mt[t[e+7]]+"-"+mt[t[e+8]]+mt[t[e+9]]+"-"+mt[t[e+10]]+mt[t[e+11]]+mt[t[e+12]]+mt[t[e+13]]+mt[t[e+14]]+mt[t[e+15]]).toLowerCase();if(!Eu(r))throw TypeError("Stringified UUID is invalid");return r}function bi(t,e,r){t=t||{};var n=t.random||(t.rng||Gy)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return zy(n)}const Ky={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},lf={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Je={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},wt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Sn={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class x{static getFirstMatch(e,r){const n=r.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,r){const n=r.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,r,n){if(e.test(r))return n}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),r[0]===10)switch(r[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),!(r[0]===1&&r[1]<5)){if(r[0]===1&&r[1]<6)return"Cupcake";if(r[0]===1&&r[1]>=6)return"Donut";if(r[0]===2&&r[1]<2)return"Eclair";if(r[0]===2&&r[1]===2)return"Froyo";if(r[0]===2&&r[1]>2)return"Gingerbread";if(r[0]===3)return"Honeycomb";if(r[0]===4&&r[1]<1)return"Ice Cream Sandwich";if(r[0]===4&&r[1]<4)return"Jelly Bean";if(r[0]===4&&r[1]>=4)return"KitKat";if(r[0]===5)return"Lollipop";if(r[0]===6)return"Marshmallow";if(r[0]===7)return"Nougat";if(r[0]===8)return"Oreo";if(r[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,r,n=!1){const i=x.getVersionPrecision(e),s=x.getVersionPrecision(r);let o=Math.max(i,s),a=0;const d=x.map([e,r],h=>{const p=o-x.getVersionPrecision(h),m=h+new Array(p+1).join(".0");return x.map(m.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===a)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(e,r){const n=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,r);for(i=0;i<e.length;i+=1)n.push(r(e[i]));return n}static find(e,r){let n,i;if(Array.prototype.find)return Array.prototype.find.call(e,r);for(n=0,i=e.length;n<i;n+=1){const s=e[n];if(r(s,n))return s}}static assign(e,...r){const n=e;let i,s;if(Object.assign)return Object.assign(e,...r);for(i=0,s=r.length;i<s;i+=1){const o=r[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{n[d]=o[d]})}return e}static getBrowserAlias(e){return Ky[e]}static getBrowserTypeByAlias(e){return lf[e]||""}}const we=/version\/(\d+(\.?_?\d+)+)/i,Yy=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=x.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=x.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=x.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=x.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=x.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=x.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=x.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=x.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=x.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=x.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=x.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=x.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=x.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=x.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=x.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=x.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=x.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=x.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=x.getFirstMatch(we,t)||x.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=x.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=x.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=x.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=x.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=x.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=x.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=x.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=x.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=x.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=x.getFirstMatch(we,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,r=/^(.*)\/(.*)[ \t]\((.*)/,i=t.search("\\(")!==-1?r:e;return{name:x.getFirstMatch(i,t),version:x.getSecondMatch(i,t)}}}];var Qy=[{test:[/Roku\/DVP/],describe(t){const e=x.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:wt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=x.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:wt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=x.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=x.getWindowsVersionName(e);return{name:wt.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:wt.iOS},r=x.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=x.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=x.getMacOSVersionName(e),n={name:wt.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=x.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:wt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=x.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=x.getAndroidVersionName(e),n={name:wt.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=x.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:wt.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=x.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||x.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||x.getFirstMatch(/\bbb(\d+)/i,t);return{name:wt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=x.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:wt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=x.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:wt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:wt.Linux}}},{test:[/CrOS/],describe(){return{name:wt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=x.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:wt.PlayStation4,version:e}}}],Xy=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=x.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:Je.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Je.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Je.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Je.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Je.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Je.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Je.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=x.getFirstMatch(/(ipod|iphone)/i,t);return{type:Je.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Je.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Je.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Je.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Je.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Je.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Je.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Je.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Je.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Je.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Je.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Je.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Je.tv}}}],Zy=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Sn.Blink};const r=x.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Sn.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:Sn.Trident},r=x.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Sn.Presto},r=x.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:Sn.Gecko},r=x.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Sn.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Sn.WebKit},r=x.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class gh{constructor(e,r=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},r!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=x.find(Yy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=x.find(Qy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:r}=this.getOS();return e?String(r).toLowerCase()||"":r||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:r}=this.getPlatform();return e?String(r).toLowerCase()||"":r||""}parsePlatform(){this.parsedResult.platform={};const e=x.find(Xy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=x.find(Zy,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return x.assign({},this.parsedResult)}satisfies(e){const r={};let n=0;const i={};let s=0;if(Object.keys(e).forEach(a=>{const d=e[a];typeof d=="string"?(i[a]=d,s+=1):typeof d=="object"&&(r[a]=d,n+=1)}),n>0){const a=Object.keys(r),d=x.find(a,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=x.find(a,p=>this.isPlatform(p));if(h){const p=this.satisfies(r[h]);if(p!==void 0)return p}}if(s>0){const a=Object.keys(i),d=x.find(a,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(e,r=!1){const n=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=x.getBrowserTypeByAlias(i);return r&&s&&(i=s.toLowerCase()),i===n}compareVersion(e){let r=[0],n=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(i=!0,n=e.substr(2)):r=[],e[0]===">"?r.push(1):r.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(i=!0,n=e.substr(1)),r.indexOf(x.compareVersions(s,n,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,r=!1){return this.isBrowser(e,r)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(r=>this.is(r))}}/*!
13
13
  * Bowser - a browser detector
14
14
  * https://github.com/lancedikson/bowser
15
15
  * MIT License | (c) Dustin Diaz 2012-2015
16
16
  * MIT License | (c) Denis Demchenko 2015-2019
17
- */class wm{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Pu(e,r)}static parse(e){return new Pu(e).getResult()}static get BROWSER_MAP(){return bm}static get ENGINE_MAP(){return Xr}static get OS_MAP(){return gt}static get PLATFORMS_MAP(){return Be}}function Ll(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function py(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let Mr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),vc=[];for(let t=0;t<Mr.length;t++)vc[Mr[t].charCodeAt(0)]=t;vc["-".charCodeAt(0)]=Mr.indexOf("+");vc["_".charCodeAt(0)]=Mr.indexOf("/");function my(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,o=0;for(let a=0;a<t.length;a++){if(s=vc[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":i=0;case`
18
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=s,i=1;break;case 1:r[n++]=o<<2|(s&48)>>4,o=s,i=2;break;case 2:r[n++]=(o&15)<<4|(s&60)>>2,o=s,i=3;break;case 3:r[n++]=(o&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function fy(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=Mr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=Mr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=Mr[i|n>>6],e+=Mr[n&63],r=0;break}return r&&(e+=Mr[i],e+="=",r==1&&(e+="=")),e}var Ua;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:o})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:o,data:a}of t.list(n))i.tag(s,o).raw(a)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];const e=r=>r&&Array.isArray(r[t.symbol])})(Ua||(Ua={}));var je;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(je||(je={}));function gy(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Yc(t,e,r){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(o>>>7==0&&e==0),d=(a?o|128:o)&255;if(r.push(d),!a)return}const n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){const o=e>>>s,a=o>>>7!=0,d=(a?o|128:o)&255;if(r.push(d),!a)return}r.push(e>>>31&1)}}const aa=(1<<16)*(1<<16);function Cm(t){let e=t[0]=="-";e&&(t=t.slice(1));const r=1e6;let n=0,i=0;function s(o,a){const d=Number(t.slice(o,a));i*=r,n=n*r+d,n>=aa&&(i=i+(n/aa|0),n=n%aa)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Hd(t,e){if(e>>>0<=2097151)return""+(aa*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,o=n+i*8147497,a=i*2,d=1e7;s>=d&&(o+=Math.floor(s/d),s%=d),o>=d&&(a+=Math.floor(o/d),o%=d);function h(p,f){let g=p?String(p):"";return f?"0000000".slice(g.length)+g:g}return h(a,0)+h(o,a)+h(s,1)}function Au(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function vy(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let ke;function yy(){const t=new DataView(new ArrayBuffer(8));ke=globalThis.BigInt!==void 0&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:t}:void 0}yy();function Im(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Rm=/^-?[0-9]+$/,Va=4294967296,Co=2147483648;class Pm{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Va+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class ut extends Pm{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.UMIN)throw new Error("signed value for ulong");if(e>ke.UMAX)throw new Error("ulong too large");return ke.V.setBigUint64(0,e,!0),new ut(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Rm.test(e))throw new Error("string is no integer");let[r,n,i]=Cm(e);if(r)throw new Error("signed value for ulong");return new ut(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new ut(e,e/Va)}throw new Error("unknown value "+typeof e)}toString(){return ke?this.toBigInt().toString():Hd(this.lo,this.hi)}toBigInt(){return Im(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigUint64(0,!0)}}ut.ZERO=new ut(0,0);class Ce extends Pm{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.MIN)throw new Error("signed long too small");if(e>ke.MAX)throw new Error("signed long too large");return ke.V.setBigInt64(0,e,!0),new Ce(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!Rm.test(e))throw new Error("string is no integer");let[r,n,i]=Cm(e);if(r){if(i>Co||i==Co&&n!=0)throw new Error("signed long too small")}else if(i>=Co)throw new Error("signed long too large");let s=new Ce(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new Ce(e,e/Va):new Ce(-e,-e/Va).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&Co)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new Ce(r,e)}toString(){if(ke)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Hd(e.lo,e.hi)}return Hd(this.lo,this.hi)}toBigInt(){return Im(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigInt64(0,!0)}}Ce.ZERO=new Ce(0,0);const Mu={readUnknownField:!0,readerFactory:t=>new Sy(t)};function Ey(t){return t?Object.assign(Object.assign({},Mu),t):Mu}class Sy{constructor(e,r){this.varint64=gy,this.uint32=vy,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r!=null?r:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case je.Varint:for(;this.buf[this.pos++]&128;);break;case je.Bit64:this.pos+=4;case je.Bit32:this.pos+=4;break;case je.LengthDelimited:let n=this.uint32();this.pos+=n;break;case je.StartGroup:let i;for(;(i=this.tag()[1])!==je.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new Ce(...this.varint64())}uint64(){return new ut(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new Ce(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ut(this.sfixed32(),this.sfixed32())}sfixed64(){return new Ce(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}}function ge(t,e){if(!t)throw new Error(e)}const Ty=34028234663852886e22,_y=-34028234663852886e22,ky=4294967295,by=2147483647,wy=-2147483648;function Xs(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>by||t<wy)throw new Error("invalid int 32: "+t)}function Ba(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>ky||t<0)throw new Error("invalid uint 32: "+t)}function xl(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>Ty||t<_y))throw new Error("invalid float 32: "+t)}const Du={writeUnknownFields:!0,writerFactory:()=>new Iy};function Cy(t){return t?Object.assign(Object.assign({},Du),t):Du}class Iy{constructor(e){this.stack=[],this.textEncoder=e!=null?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ba(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Xs(e),Au(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){xl(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){Ba(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){Xs(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return Xs(e),e=(e<<1^e>>31)>>>0,Au(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=Ce.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=ut.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=Ce.from(e);return Yc(r.lo,r.hi,this.buf),this}sint64(e){let r=Ce.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return Yc(i,s,this.buf),this}uint64(e){let r=ut.from(e);return Yc(r.lo,r.hi,this.buf),this}}const Ou={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Nu={ignoreUnknownFields:!1};function Ry(t){return t?Object.assign(Object.assign({},Nu),t):Nu}function Py(t){return t?Object.assign(Object.assign({},Ou),t):Ou}const Am=Symbol.for("protobuf-ts/message-type");function Lu(t){let e=!1;const r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var M;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(M||(M={}));var pr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(pr||(pr={}));var ja;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(ja||(ja={}));function Ay(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Lu(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:Lu(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:ja.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function My(t){if(typeof t!="object"||t===null||!t.hasOwnProperty("oneofKind"))return!1;switch(typeof t.oneofKind){case"string":return t[t.oneofKind]===void 0?!1:Object.keys(t).length==2;case"undefined":return Object.keys(t).length==1;default:return!1}}class Dy{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;const e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(o=>!i.includes(o))||!n&&i.some(o=>!s.known.includes(o)))return!1;if(r<1)return!0;for(const o of s.oneofs){const a=e[o];if(!My(a))return!1;if(a.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===a.oneofKind);if(!d||!this.field(a[a.oneofKind],d,n,r))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,M.INT32,i):this.scalar(e,M.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),M.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:switch(n){case pr.BIGINT:return i=="bigint";case pr.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case M.BOOL:return i=="boolean";case M.STRING:return i=="string";case M.BYTES:return e instanceof Uint8Array;case M.DOUBLE:case M.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case M.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,pr.STRING)}}}function tr(t,e){switch(e){case pr.BIGINT:return t.toBigInt();case pr.NUMBER:return t.toNumber();default:return t.toString()}}class Oy{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=Ll(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();const i=[];for(const[s,o]of Object.entries(e)){const a=this.fMap[s];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=a.localName;let h;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),h=r[a.oneof]={oneofKind:d}}else h=r;if(a.kind=="map"){if(o===null)continue;this.assert(py(o),a.name,o);const p=h[d];for(const[f,g]of Object.entries(o)){this.assert(g!==null,a.name+" map value",null);let E;switch(a.V.kind){case"message":E=a.V.T().internalJsonRead(g,n);break;case"enum":if(E=this.enum(a.V.T(),g,a.name,n.ignoreUnknownFields),E===!1)continue;break;case"scalar":E=this.scalar(g,a.V.T,a.V.L,a.name);break}this.assert(E!==void 0,a.name+" map value",g);let v=f;a.K==M.BOOL&&(v=v=="true"?!0:v=="false"?!1:v),v=this.scalar(v,a.K,pr.STRING,a.name).toString(),p[v]=E}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);const p=h[d];for(const f of o){this.assert(f!==null,a.name,null);let g;switch(a.kind){case"message":g=a.T().internalJsonRead(f,n);break;case"enum":if(g=this.enum(a.T(),f,a.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(f,a.T,a.L,a.name);break}this.assert(g!==void 0,a.name,o),p.push(g)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}h[d]=a.T().internalJsonRead(o,n,h[d]);break;case"enum":let p=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(p===!1)continue;h[d]=p;break;case"scalar":h[d]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&ge(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return ge(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let o=e[1][s];return typeof o=="undefined"&&i?!1:(ge(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),o)}ge(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case M.DOUBLE:case M.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){s="not a number";break}if(!Number.isFinite(o)){s="too large or small";break}return r==M.FLOAT&&xl(o),o;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":a=Number(e)),a===void 0)break;return r==M.UINT32?Ba(a):Xs(a),a;case M.INT64:case M.SFIXED64:case M.SINT64:if(e===null)return tr(Ce.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return tr(Ce.from(e),n);case M.FIXED64:case M.UINT64:if(e===null)return tr(ut.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return tr(ut.from(e),n);case M.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case M.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case M.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return my(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}}class Ny{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){const n={},i=e;for(const s of this.fields){if(!s.oneof){let h=this.field(s,i[s.localName],r);h!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=h);continue}const o=i[s.oneof];if(o.oneofKind!==s.localName)continue;const a=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r;let d=this.field(s,o[s.localName],a);ge(d!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,r,n){let i;if(e.kind=="map"){ge(typeof r=="object"&&r!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(r)){const p=this.scalar(e.V.T,h,e.name,!1,!0);ge(p!==void 0),s[d.toString()]=p}break;case"message":const o=e.V.T();for(const[d,h]of Object.entries(r)){const p=this.message(o,h,e.name,n);ge(p!==void 0),s[d.toString()]=p}break;case"enum":const a=e.V.T();for(const[d,h]of Object.entries(r)){ge(h===void 0||typeof h=="number");const p=this.enum(a,h,e.name,!1,!0,n.enumAsInteger);ge(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){ge(Array.isArray(r));const s=[];switch(e.kind){case"scalar":for(let d=0;d<r.length;d++){const h=this.scalar(e.T,r[d],e.name,e.opt,!0);ge(h!==void 0),s.push(h)}break;case"enum":const o=e.T();for(let d=0;d<r.length;d++){ge(r[d]===void 0||typeof r[d]=="number");const h=this.enum(o,r[d],e.name,e.opt,!0,n.enumAsInteger);ge(h!==void 0),s.push(h)}break;case"message":const a=e.T();for(let d=0;d<r.length;d++){const h=this.message(a,r[d],e.name,n);ge(h!==void 0),s.push(h)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){ge(i);return}if(!(r===0&&!s&&!i))return ge(typeof r=="number"),ge(Number.isInteger(r)),o||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){ge(i);return}const o=s||i;switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:return r===0?o?0:void 0:(Xs(r),r);case M.FIXED32:case M.UINT32:return r===0?o?0:void 0:(Ba(r),r);case M.FLOAT:xl(r);case M.DOUBLE:return r===0?o?0:void 0:(ge(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case M.STRING:return r===""?o?"":void 0:(ge(typeof r=="string"),r);case M.BOOL:return r===!1?o?!1:void 0:(ge(typeof r=="boolean"),r);case M.UINT64:case M.FIXED64:ge(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let a=ut.from(r);return a.isZero()&&!o?void 0:a.toString();case M.INT64:case M.SFIXED64:case M.SINT64:ge(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let d=Ce.from(r);return d.isZero()&&!o?void 0:d.toString();case M.BYTES:return ge(r instanceof Uint8Array),r.byteLength?fy(r):o?"":void 0}}}function Wd(t,e=pr.STRING){switch(t){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:return tr(ut.ZERO,e);case M.INT64:case M.SFIXED64:case M.SINT64:return tr(Ce.ZERO,e);case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}class Ly{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[o,a]=e.tag(),d=this.fieldNoToField.get(o);if(!d){let g=n.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let E=e.skip(a);g!==!1&&(g===!0?Ua.onRead:g)(this.info.typeName,r,o,a,E);continue}let h=r,p=d.repeat,f=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==f&&(h=r[d.oneof]={oneofKind:f})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?M.INT32:d.T,E=d.kind=="scalar"?d.L:void 0;if(p){let A=h[f];if(a==je.LengthDelimited&&g!=M.STRING&&g!=M.BYTES){let D=e.uint32()+e.pos;for(;e.pos<D;)A.push(this.scalar(e,g,E))}else A.push(this.scalar(e,g,E))}else h[f]=this.scalar(e,g,E);break;case"message":if(p){let A=h[f],D=d.T().internalBinaryRead(e,e.uint32(),n);A.push(D)}else h[f]=d.T().internalBinaryRead(e,e.uint32(),n,h[f]);break;case"map":let[v,I]=this.mapEntry(d,e,n);h[f][v]=I;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,o,a;for(;r.pos<s;){let[d,h]=r.tag();switch(d){case 1:e.K==M.BOOL?o=r.bool().toString():o=this.scalar(r,e.K,pr.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(r,e.V.T,e.V.L);break;case"enum":a=r.int32();break;case"message":a=e.V.T().internalBinaryRead(r,r.uint32(),n);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let d=Wd(e.K);o=e.K==M.BOOL?d.toString():d}if(a===void 0)switch(e.V.kind){case"scalar":a=Wd(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,r,n){switch(r){case M.INT32:return e.int32();case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT64:return tr(e.int64(),n);case M.UINT64:return tr(e.uint64(),n);case M.FIXED64:return tr(e.fixed64(),n);case M.FIXED32:return e.fixed32();case M.BYTES:return e.bytes();case M.UINT32:return e.uint32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return tr(e.sfixed64(),n);case M.SINT32:return e.sint32();case M.SINT64:return tr(e.sint64(),n)}}}class xy{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(const s of this.fields){let o,a,d=s.repeat,h=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==h)continue;o=p[h],a=!0}else o=e[h],a=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?M.INT32:s.T;if(d)if(ge(Array.isArray(o)),d==ja.PACKED)this.packed(r,p,s.no,o);else for(const f of o)this.scalar(r,p,s.no,f,!0);else o===void 0?ge(s.opt):this.scalar(r,p,s.no,o,a||s.opt);break;case"message":if(d){ge(Array.isArray(o));for(const f of o)this.message(r,n,s.T(),s.no,f)}else this.message(r,n,s.T(),s.no,o);break;case"map":ge(typeof o=="object"&&o!==null);for(const[f,g]of Object.entries(o))this.mapEntry(r,n,s,f,g);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?Ua.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,je.LengthDelimited),e.fork();let o=i;switch(n.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:o=Number.parseInt(i);break;case M.BOOL:ge(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,M.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,je.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[o,a,d]=this.scalarInfo(r,i);(!d||s)&&(e.tag(n,o),e[a](i))}packed(e,r,n,i){if(!i.length)return;ge(r!==M.BYTES&&r!==M.STRING),e.tag(n,je.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let o=0;o<i.length;o++)e[s](i[o]);e.join()}scalarInfo(e,r){let n=je.Varint,i,s=r===void 0,o=r===0;switch(e){case M.INT32:i="int32";break;case M.STRING:o=s||!r.length,n=je.LengthDelimited,i="string";break;case M.BOOL:o=r===!1,i="bool";break;case M.UINT32:i="uint32";break;case M.DOUBLE:n=je.Bit64,i="double";break;case M.FLOAT:n=je.Bit32,i="float";break;case M.INT64:o=s||Ce.from(r).isZero(),i="int64";break;case M.UINT64:o=s||ut.from(r).isZero(),i="uint64";break;case M.FIXED64:o=s||ut.from(r).isZero(),n=je.Bit64,i="fixed64";break;case M.BYTES:o=s||!r.byteLength,n=je.LengthDelimited,i="bytes";break;case M.FIXED32:n=je.Bit32,i="fixed32";break;case M.SFIXED32:n=je.Bit32,i="sfixed32";break;case M.SFIXED64:o=s||Ce.from(r).isZero(),n=je.Bit64,i="sfixed64";break;case M.SINT32:i="sint32";break;case M.SINT64:o=s||Ce.from(r).isZero(),i="sint64";break}return[n,i,s||o]}}function Fy(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},Am,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=Wd(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Qc(t,e,r){let n,i=r,s;for(let o of t.fields){let a=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[a],s=e[o.oneof],s.oneofKind=d.oneofKind,n==null){delete s[a];continue}}else if(n=i[a],s=e,n==null)continue;switch(o.repeat&&(s[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=n[h];else s[a]=n;break;case"message":let d=o.T();if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=d.create(n[h]);else s[a]===void 0?s[a]=d.create(n):d.mergePartial(s[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[a],n);break;case"message":let h=o.V.T();for(let p of Object.keys(n))s[a][p]=h.create(n[p]);break}break}}}function Uy(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?M.INT32:n.T;if(!(n.repeat?xu(a,s,o):Mm(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?Fu(n.V.T(),Io(s),Io(o)):xu(n.V.kind=="enum"?M.INT32:n.V.T,Io(s),Io(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?Fu(d,s,o):d.equals(s,o)))return!1;break}}return!0}const Io=Object.values;function Mm(t,e,r){if(e===r)return!0;if(t!==M.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function xu(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!Mm(t,e[n],r[n]))return!1;return!0}function Fu(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}const Vy=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class _{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Ay),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Vy),{[Am]:{value:this}})),this.refTypeCheck=new Dy(this),this.refJsonReader=new Oy(this),this.refJsonWriter=new Ny(this),this.refBinReader=new Ly(this),this.refBinWriter=new xy(this)}create(e){let r=Fy(this);return e!==void 0&&Qc(this,r,e),r}clone(e){let r=this.create();return Qc(this,r,e),r}equals(e,r){return Uy(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Qc(this,e,r)}fromBinary(e,r){let n=Ey(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Ry(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Py(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r==null?void 0:r.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=Cy(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n!=null?n:this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Ll(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i!=null?i:this.create();return this.refBinReader.read(e,s,n,r),s}}const By=t=>(e,r)=>(t.set(e,r),r),Uu=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Dm=536870912,Vu=Dm*2,jy=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<Vu?n+1:0;if(!r.has(i))return t(r,i);if(r.size<Dm){for(;r.has(i);)i=Math.floor(Math.random()*Vu);return t(r,i)}if(r.size>Uu)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*Uu);return t(r,i)},Om=new WeakMap,Hy=By(Om),Ro=jy(Hy,Om),Wy=t=>t.method!==void 0&&t.method==="call",$y=t=>t.error===null&&typeof t.id=="number",Gy=t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(Wy(h)){const{params:{timerId:p,timerType:f}}=h;if(f==="interval"){const g=e.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(f==="timeout"){const g=r.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),r.delete(p);else throw new Error("The timer is in an undefined state.")}}else if($y(h)){const{id:p}=h,f=n.get(p);if(f===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:E}=f;n.delete(p),E==="interval"?e.delete(g):r.delete(g)}else{const{error:{message:p}}=h;throw new Error(p)}}),{clearInterval:h=>{const p=Ro(n);n.set(p,{timerId:h,timerType:"interval"}),e.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const p=Ro(n);n.set(p,{timerId:h,timerType:"timeout"}),r.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,p=0)=>{const f=Ro(e);return e.set(f,()=>{h(),typeof e.get(f)=="function"&&i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}}),f},setTimeout:(h,p=0)=>{const f=Ro(r);return r.set(f,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"timeout"}}),f}}},Jy=(t,e)=>{let r=null;return()=>{if(r!==null)return r;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=t(i),setTimeout(()=>URL.revokeObjectURL(i)),r}},qy=`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`,yc=Jy(Gy,qy),Nm=t=>yc().clearInterval(t),Ky=t=>yc().clearTimeout(t),Lm=(t,e)=>yc().setInterval(t,e),zy=(t,e)=>yc().setTimeout(t,e);var Yy=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Nm,clearTimeout:Ky,setInterval:Lm,setTimeout:zy},Symbol.toStringTag,{value:"Module"})),xm={},Fl={exports:{}},Bu=Fl.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return t.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{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(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=t.raddr!=null?" raddr %s rport %d":"%v%v",e+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(e+=" generation %d"),e+=t["network-id"]!=null?" network-id %d":"%v",e+=t["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(t){var e="ssrc:%d";return t.attribute!=null&&(e+=" %s",t.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(t){return t.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=t.id!=null?"id=%s %s":"%v%s",e+=t.mediaClockValue!=null?"=%s":"",e+=t.rateNumerator!=null?" rate=%s":"",e+=t.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Bu).forEach(function(t){var e=Bu[t];e.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});(function(t){var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,d,h,p){if(p&&!h)d[p]=e(a[1]);else for(var f=0;f<h.length;f+=1)a[f+1]!=null&&(d[h[f]]=e(a[f+1]))},n=function(a,d,h){var p=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:p&&!d[a.name]&&(d[a.name]={});var f=a.push?{}:p?d[a.name]:d;r(h.match(a.reg),f,a.names,a.name),a.push&&d[a.push].push(f)},i=Fl.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var d={},h=[],p=d;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(f){var g=f[0],E=f.slice(2);g==="m"&&(h.push({rtp:[],fmtp:[]}),p=h[h.length-1]);for(var v=0;v<(i[g]||[]).length;v+=1){var I=i[g][v];if(I.reg.test(E))return n(I,p,E)}}),d.media=h,d};var o=function(a,d){var h=d.split(/=(.+)/,2);return h.length===2?a[h[0]]=e(h[1]):h.length===1&&d.length>1&&(a[h[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var d=[],h=a.split(" ").map(e),p=0;p<h.length;p+=3)d.push({component:h[p],ip:h[p+1],port:h[p+2]});return d},t.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(h){var p,f=!1;return h[0]!=="~"?p=e(h):(p=e(h.substring(1,h.length)),f=!0),{scid:p,paused:f}})})}})(xm);var Xc=Fl.exports,Qy=/%[sdv%]/g,Xy=function(t){var e=1,r=arguments,n=r.length;return t.replace(Qy,function(i){if(e>=n)return i;var s=r[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},fs=function(t,e,r){var n=e.format instanceof Function?e.format(e.push?r:r[e.name]):e.format,i=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?i.push(r[e.name][o]):i.push(r[e.names[s]])}else i.push(r[e.name]);return Xy.apply(null,i)},Zy=["v","o","s","i","u","e","p","c","b","t","r","z","a"],eE=["i","c","b","a"],tE=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=e.outerOrder||Zy,n=e.innerOrder||eE,i=[];return r.forEach(function(s){Xc[s].forEach(function(o){o.name in t&&t[o.name]!=null?i.push(fs(s,o,t)):o.push in t&&t[o.push]!=null&&t[o.push].forEach(function(a){i.push(fs(s,o,a))})})}),t.media.forEach(function(s){i.push(fs("m",Xc.m[0],s)),n.forEach(function(o){Xc[o].forEach(function(a){a.name in s&&s[a.name]!=null?i.push(fs(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){i.push(fs(o,a,d))})})})}),i.join(`\r
17
+ */class uf{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new gh(e,r)}static parse(e){return new gh(e).getResult()}static get BROWSER_MAP(){return lf}static get ENGINE_MAP(){return Sn}static get OS_MAP(){return wt}static get PLATFORMS_MAP(){return Je}}function Tu(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function eS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let qr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),td=[];for(let t=0;t<qr.length;t++)td[qr[t].charCodeAt(0)]=t;td["-".charCodeAt(0)]=qr.indexOf("+");td["_".charCodeAt(0)]=qr.indexOf("/");function tS(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,o=0;for(let a=0;a<t.length;a++){if(s=td[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":i=0;case`
18
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=s,i=1;break;case 1:r[n++]=o<<2|(s&48)>>4,o=s,i=2;break;case 2:r[n++]=(o&15)<<4|(s&60)>>2,o=s,i=3;break;case 3:r[n++]=(o&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function rS(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=qr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=qr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=qr[i|n>>6],e+=qr[n&63],r=0;break}return r&&(e+=qr[i],e+="=",r==1&&(e+="=")),e}var kc;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:o})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:o,data:a}of t.list(n))i.tag(s,o).raw(a)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];const e=r=>r&&Array.isArray(r[t.symbol])})(kc||(kc={}));var qe;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(qe||(qe={}));function nS(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Od(t,e,r){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(o>>>7==0&&e==0),d=(a?o|128:o)&255;if(r.push(d),!a)return}const n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){const o=e>>>s,a=o>>>7!=0,d=(a?o|128:o)&255;if(r.push(d),!a)return}r.push(e>>>31&1)}}const Ja=(1<<16)*(1<<16);function hf(t){let e=t[0]=="-";e&&(t=t.slice(1));const r=1e6;let n=0,i=0;function s(o,a){const d=Number(t.slice(o,a));i*=r,n=n*r+d,n>=Ja&&(i=i+(n/Ja|0),n=n%Ja)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Rl(t,e){if(e>>>0<=2097151)return""+(Ja*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,o=n+i*8147497,a=i*2,d=1e7;s>=d&&(o+=Math.floor(s/d),s%=d),o>=d&&(a+=Math.floor(o/d),o%=d);function h(p,m){let g=p?String(p):"";return m?"0000000".slice(g.length)+g:g}return h(a,0)+h(o,a)+h(s,1)}function vh(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function iS(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let Ie;function sS(){const t=new DataView(new ArrayBuffer(8));Ie=globalThis.BigInt!==void 0&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:t}:void 0}sS();function pf(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const mf=/^-?[0-9]+$/,_c=4294967296,la=2147483648;class ff{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*_c+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class yt extends ff{static from(e){if(Ie)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Ie.C(e);case"number":if(e===0)return this.ZERO;e=Ie.C(e);case"bigint":if(!e)return this.ZERO;if(e<Ie.UMIN)throw new Error("signed value for ulong");if(e>Ie.UMAX)throw new Error("ulong too large");return Ie.V.setBigUint64(0,e,!0),new yt(Ie.V.getInt32(0,!0),Ie.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mf.test(e))throw new Error("string is no integer");let[r,n,i]=hf(e);if(r)throw new Error("signed value for ulong");return new yt(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new yt(e,e/_c)}throw new Error("unknown value "+typeof e)}toString(){return Ie?this.toBigInt().toString():Rl(this.lo,this.hi)}toBigInt(){return pf(Ie),Ie.V.setInt32(0,this.lo,!0),Ie.V.setInt32(4,this.hi,!0),Ie.V.getBigUint64(0,!0)}}yt.ZERO=new yt(0,0);class Re extends ff{static from(e){if(Ie)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Ie.C(e);case"number":if(e===0)return this.ZERO;e=Ie.C(e);case"bigint":if(!e)return this.ZERO;if(e<Ie.MIN)throw new Error("signed long too small");if(e>Ie.MAX)throw new Error("signed long too large");return Ie.V.setBigInt64(0,e,!0),new Re(Ie.V.getInt32(0,!0),Ie.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mf.test(e))throw new Error("string is no integer");let[r,n,i]=hf(e);if(r){if(i>la||i==la&&n!=0)throw new Error("signed long too small")}else if(i>=la)throw new Error("signed long too large");let s=new Re(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new Re(e,e/_c):new Re(-e,-e/_c).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&la)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new Re(r,e)}toString(){if(Ie)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Rl(e.lo,e.hi)}return Rl(this.lo,this.hi)}toBigInt(){return pf(Ie),Ie.V.setInt32(0,this.lo,!0),Ie.V.setInt32(4,this.hi,!0),Ie.V.getBigInt64(0,!0)}}Re.ZERO=new Re(0,0);const yh={readUnknownField:!0,readerFactory:t=>new aS(t)};function oS(t){return t?Object.assign(Object.assign({},yh),t):yh}class aS{constructor(e,r){this.varint64=nS,this.uint32=iS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r!=null?r:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case qe.Varint:for(;this.buf[this.pos++]&128;);break;case qe.Bit64:this.pos+=4;case qe.Bit32:this.pos+=4;break;case qe.LengthDelimited:let n=this.uint32();this.pos+=n;break;case qe.StartGroup:let i;for(;(i=this.tag()[1])!==qe.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new Re(...this.varint64())}uint64(){return new yt(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new Re(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new yt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Re(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}}function Se(t,e){if(!t)throw new Error(e)}const cS=34028234663852886e22,dS=-34028234663852886e22,lS=4294967295,uS=2147483647,hS=-2147483648;function Fo(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>uS||t<hS)throw new Error("invalid int 32: "+t)}function bc(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>lS||t<0)throw new Error("invalid uint 32: "+t)}function ku(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>cS||t<dS))throw new Error("invalid float 32: "+t)}const Sh={writeUnknownFields:!0,writerFactory:()=>new mS};function pS(t){return t?Object.assign(Object.assign({},Sh),t):Sh}class mS{constructor(e){this.stack=[],this.textEncoder=e!=null?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(bc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Fo(e),vh(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){ku(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){bc(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){Fo(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return Fo(e),e=(e<<1^e>>31)>>>0,vh(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=Re.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=yt.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=Re.from(e);return Od(r.lo,r.hi,this.buf),this}sint64(e){let r=Re.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return Od(i,s,this.buf),this}uint64(e){let r=yt.from(e);return Od(r.lo,r.hi,this.buf),this}}const Eh={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Th={ignoreUnknownFields:!1};function fS(t){return t?Object.assign(Object.assign({},Th),t):Th}function gS(t){return t?Object.assign(Object.assign({},Eh),t):Eh}const gf=Symbol.for("protobuf-ts/message-type");function kh(t){let e=!1;const r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var L;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(L||(L={}));var br;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(br||(br={}));var wc;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(wc||(wc={}));function vS(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:kh(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:kh(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:wc.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function yS(t){if(typeof t!="object"||t===null||!t.hasOwnProperty("oneofKind"))return!1;switch(typeof t.oneofKind){case"string":return t[t.oneofKind]===void 0?!1:Object.keys(t).length==2;case"undefined":return Object.keys(t).length==1;default:return!1}}class SS{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;const e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(o=>!i.includes(o))||!n&&i.some(o=>!s.known.includes(o)))return!1;if(r<1)return!0;for(const o of s.oneofs){const a=e[o];if(!yS(a))return!1;if(a.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===a.oneofKind);if(!d||!this.field(a[a.oneofKind],d,n,r))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,L.INT32,i):this.scalar(e,L.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),L.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case L.UINT64:case L.FIXED64:case L.INT64:case L.SFIXED64:case L.SINT64:switch(n){case br.BIGINT:return i=="bigint";case br.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case L.BOOL:return i=="boolean";case L.STRING:return i=="string";case L.BYTES:return e instanceof Uint8Array;case L.DOUBLE:case L.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case L.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,br.STRING)}}}function pr(t,e){switch(e){case br.BIGINT:return t.toBigInt();case br.NUMBER:return t.toNumber();default:return t.toString()}}class ES{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=Tu(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();const i=[];for(const[s,o]of Object.entries(e)){const a=this.fMap[s];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=a.localName;let h;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),h=r[a.oneof]={oneofKind:d}}else h=r;if(a.kind=="map"){if(o===null)continue;this.assert(eS(o),a.name,o);const p=h[d];for(const[m,g]of Object.entries(o)){this.assert(g!==null,a.name+" map value",null);let v;switch(a.V.kind){case"message":v=a.V.T().internalJsonRead(g,n);break;case"enum":if(v=this.enum(a.V.T(),g,a.name,n.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(g,a.V.T,a.V.L,a.name);break}this.assert(v!==void 0,a.name+" map value",g);let _=m;a.K==L.BOOL&&(_=_=="true"?!0:_=="false"?!1:_),_=this.scalar(_,a.K,br.STRING,a.name).toString(),p[_]=v}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);const p=h[d];for(const m of o){this.assert(m!==null,a.name,null);let g;switch(a.kind){case"message":g=a.T().internalJsonRead(m,n);break;case"enum":if(g=this.enum(a.T(),m,a.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(m,a.T,a.L,a.name);break}this.assert(g!==void 0,a.name,o),p.push(g)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}h[d]=a.T().internalJsonRead(o,n,h[d]);break;case"enum":let p=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(p===!1)continue;h[d]=p;break;case"scalar":h[d]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&Se(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return Se(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let o=e[1][s];return typeof o=="undefined"&&i?!1:(Se(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),o)}Se(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case L.DOUBLE:case L.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){s="not a number";break}if(!Number.isFinite(o)){s="too large or small";break}return r==L.FLOAT&&ku(o),o;case L.INT32:case L.FIXED32:case L.SFIXED32:case L.SINT32:case L.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":a=Number(e)),a===void 0)break;return r==L.UINT32?bc(a):Fo(a),a;case L.INT64:case L.SFIXED64:case L.SINT64:if(e===null)return pr(Re.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return pr(Re.from(e),n);case L.FIXED64:case L.UINT64:if(e===null)return pr(yt.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return pr(yt.from(e),n);case L.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case L.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case L.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return tS(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}}class TS{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){const n={},i=e;for(const s of this.fields){if(!s.oneof){let h=this.field(s,i[s.localName],r);h!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=h);continue}const o=i[s.oneof];if(o.oneofKind!==s.localName)continue;const a=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r;let d=this.field(s,o[s.localName],a);Se(d!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,r,n){let i;if(e.kind=="map"){Se(typeof r=="object"&&r!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(r)){const p=this.scalar(e.V.T,h,e.name,!1,!0);Se(p!==void 0),s[d.toString()]=p}break;case"message":const o=e.V.T();for(const[d,h]of Object.entries(r)){const p=this.message(o,h,e.name,n);Se(p!==void 0),s[d.toString()]=p}break;case"enum":const a=e.V.T();for(const[d,h]of Object.entries(r)){Se(h===void 0||typeof h=="number");const p=this.enum(a,h,e.name,!1,!0,n.enumAsInteger);Se(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){Se(Array.isArray(r));const s=[];switch(e.kind){case"scalar":for(let d=0;d<r.length;d++){const h=this.scalar(e.T,r[d],e.name,e.opt,!0);Se(h!==void 0),s.push(h)}break;case"enum":const o=e.T();for(let d=0;d<r.length;d++){Se(r[d]===void 0||typeof r[d]=="number");const h=this.enum(o,r[d],e.name,e.opt,!0,n.enumAsInteger);Se(h!==void 0),s.push(h)}break;case"message":const a=e.T();for(let d=0;d<r.length;d++){const h=this.message(a,r[d],e.name,n);Se(h!==void 0),s.push(h)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){Se(i);return}if(!(r===0&&!s&&!i))return Se(typeof r=="number"),Se(Number.isInteger(r)),o||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){Se(i);return}const o=s||i;switch(e){case L.INT32:case L.SFIXED32:case L.SINT32:return r===0?o?0:void 0:(Fo(r),r);case L.FIXED32:case L.UINT32:return r===0?o?0:void 0:(bc(r),r);case L.FLOAT:ku(r);case L.DOUBLE:return r===0?o?0:void 0:(Se(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case L.STRING:return r===""?o?"":void 0:(Se(typeof r=="string"),r);case L.BOOL:return r===!1?o?!1:void 0:(Se(typeof r=="boolean"),r);case L.UINT64:case L.FIXED64:Se(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let a=yt.from(r);return a.isZero()&&!o?void 0:a.toString();case L.INT64:case L.SFIXED64:case L.SINT64:Se(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let d=Re.from(r);return d.isZero()&&!o?void 0:d.toString();case L.BYTES:return Se(r instanceof Uint8Array),r.byteLength?rS(r):o?"":void 0}}}function Al(t,e=br.STRING){switch(t){case L.BOOL:return!1;case L.UINT64:case L.FIXED64:return pr(yt.ZERO,e);case L.INT64:case L.SFIXED64:case L.SINT64:return pr(Re.ZERO,e);case L.DOUBLE:case L.FLOAT:return 0;case L.BYTES:return new Uint8Array(0);case L.STRING:return"";default:return 0}}class kS{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[o,a]=e.tag(),d=this.fieldNoToField.get(o);if(!d){let g=n.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let v=e.skip(a);g!==!1&&(g===!0?kc.onRead:g)(this.info.typeName,r,o,a,v);continue}let h=r,p=d.repeat,m=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==m&&(h=r[d.oneof]={oneofKind:m})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?L.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(p){let C=h[m];if(a==qe.LengthDelimited&&g!=L.STRING&&g!=L.BYTES){let M=e.uint32()+e.pos;for(;e.pos<M;)C.push(this.scalar(e,g,v))}else C.push(this.scalar(e,g,v))}else h[m]=this.scalar(e,g,v);break;case"message":if(p){let C=h[m],M=d.T().internalBinaryRead(e,e.uint32(),n);C.push(M)}else h[m]=d.T().internalBinaryRead(e,e.uint32(),n,h[m]);break;case"map":let[_,A]=this.mapEntry(d,e,n);h[m][_]=A;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,o,a;for(;r.pos<s;){let[d,h]=r.tag();switch(d){case 1:e.K==L.BOOL?o=r.bool().toString():o=this.scalar(r,e.K,br.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(r,e.V.T,e.V.L);break;case"enum":a=r.int32();break;case"message":a=e.V.T().internalBinaryRead(r,r.uint32(),n);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let d=Al(e.K);o=e.K==L.BOOL?d.toString():d}if(a===void 0)switch(e.V.kind){case"scalar":a=Al(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,r,n){switch(r){case L.INT32:return e.int32();case L.STRING:return e.string();case L.BOOL:return e.bool();case L.DOUBLE:return e.double();case L.FLOAT:return e.float();case L.INT64:return pr(e.int64(),n);case L.UINT64:return pr(e.uint64(),n);case L.FIXED64:return pr(e.fixed64(),n);case L.FIXED32:return e.fixed32();case L.BYTES:return e.bytes();case L.UINT32:return e.uint32();case L.SFIXED32:return e.sfixed32();case L.SFIXED64:return pr(e.sfixed64(),n);case L.SINT32:return e.sint32();case L.SINT64:return pr(e.sint64(),n)}}}class _S{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(const s of this.fields){let o,a,d=s.repeat,h=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==h)continue;o=p[h],a=!0}else o=e[h],a=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?L.INT32:s.T;if(d)if(Se(Array.isArray(o)),d==wc.PACKED)this.packed(r,p,s.no,o);else for(const m of o)this.scalar(r,p,s.no,m,!0);else o===void 0?Se(s.opt):this.scalar(r,p,s.no,o,a||s.opt);break;case"message":if(d){Se(Array.isArray(o));for(const m of o)this.message(r,n,s.T(),s.no,m)}else this.message(r,n,s.T(),s.no,o);break;case"map":Se(typeof o=="object"&&o!==null);for(const[m,g]of Object.entries(o))this.mapEntry(r,n,s,m,g);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?kc.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,qe.LengthDelimited),e.fork();let o=i;switch(n.K){case L.INT32:case L.FIXED32:case L.UINT32:case L.SFIXED32:case L.SINT32:o=Number.parseInt(i);break;case L.BOOL:Se(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,L.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,qe.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[o,a,d]=this.scalarInfo(r,i);(!d||s)&&(e.tag(n,o),e[a](i))}packed(e,r,n,i){if(!i.length)return;Se(r!==L.BYTES&&r!==L.STRING),e.tag(n,qe.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let o=0;o<i.length;o++)e[s](i[o]);e.join()}scalarInfo(e,r){let n=qe.Varint,i,s=r===void 0,o=r===0;switch(e){case L.INT32:i="int32";break;case L.STRING:o=s||!r.length,n=qe.LengthDelimited,i="string";break;case L.BOOL:o=r===!1,i="bool";break;case L.UINT32:i="uint32";break;case L.DOUBLE:n=qe.Bit64,i="double";break;case L.FLOAT:n=qe.Bit32,i="float";break;case L.INT64:o=s||Re.from(r).isZero(),i="int64";break;case L.UINT64:o=s||yt.from(r).isZero(),i="uint64";break;case L.FIXED64:o=s||yt.from(r).isZero(),n=qe.Bit64,i="fixed64";break;case L.BYTES:o=s||!r.byteLength,n=qe.LengthDelimited,i="bytes";break;case L.FIXED32:n=qe.Bit32,i="fixed32";break;case L.SFIXED32:n=qe.Bit32,i="sfixed32";break;case L.SFIXED64:o=s||Re.from(r).isZero(),n=qe.Bit64,i="sfixed64";break;case L.SINT32:i="sint32";break;case L.SINT64:o=s||Re.from(r).isZero(),i="sint64";break}return[n,i,s||o]}}function bS(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},gf,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=Al(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Nd(t,e,r){let n,i=r,s;for(let o of t.fields){let a=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[a],s=e[o.oneof],s.oneofKind=d.oneofKind,n==null){delete s[a];continue}}else if(n=i[a],s=e,n==null)continue;switch(o.repeat&&(s[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=n[h];else s[a]=n;break;case"message":let d=o.T();if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=d.create(n[h]);else s[a]===void 0?s[a]=d.create(n):d.mergePartial(s[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[a],n);break;case"message":let h=o.V.T();for(let p of Object.keys(n))s[a][p]=h.create(n[p]);break}break}}}function wS(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?L.INT32:n.T;if(!(n.repeat?_h(a,s,o):vf(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?bh(n.V.T(),ua(s),ua(o)):_h(n.V.kind=="enum"?L.INT32:n.V.T,ua(s),ua(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?bh(d,s,o):d.equals(s,o)))return!1;break}}return!0}const ua=Object.values;function vf(t,e,r){if(e===r)return!0;if(t!==L.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function _h(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!vf(t,e[n],r[n]))return!1;return!0}function bh(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}const IS=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class E{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(vS),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},IS),{[gf]:{value:this}})),this.refTypeCheck=new SS(this),this.refJsonReader=new ES(this),this.refJsonWriter=new TS(this),this.refBinReader=new kS(this),this.refBinWriter=new _S(this)}create(e){let r=bS(this);return e!==void 0&&Nd(this,r,e),r}clone(e){let r=this.create();return Nd(this,r,e),r}equals(e,r){return wS(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Nd(this,e,r)}fromBinary(e,r){let n=oS(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,fS(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,gS(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r==null?void 0:r.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=pS(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n!=null?n:this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Tu(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i!=null?i:this.create();return this.refBinReader.read(e,s,n,r),s}}const CS=t=>(e,r)=>(t.set(e,r),r),wh=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,yf=536870912,Ih=yf*2,PS=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<Ih?n+1:0;if(!r.has(i))return t(r,i);if(r.size<yf){for(;r.has(i);)i=Math.floor(Math.random()*Ih);return t(r,i)}if(r.size>wh)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*wh);return t(r,i)},Sf=new WeakMap,RS=CS(Sf),ha=PS(RS,Sf),AS=t=>t.method!==void 0&&t.method==="call",MS=t=>t.error===null&&typeof t.id=="number",DS=t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(AS(h)){const{params:{timerId:p,timerType:m}}=h;if(m==="interval"){const g=e.get(p);if(typeof g=="number"){const v=n.get(g);if(v===void 0||v.timerId!==p||v.timerType!==m)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(m==="timeout"){const g=r.get(p);if(typeof g=="number"){const v=n.get(g);if(v===void 0||v.timerId!==p||v.timerType!==m)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),r.delete(p);else throw new Error("The timer is in an undefined state.")}}else if(MS(h)){const{id:p}=h,m=n.get(p);if(m===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:v}=m;n.delete(p),v==="interval"?e.delete(g):r.delete(g)}else{const{error:{message:p}}=h;throw new Error(p)}}),{clearInterval:h=>{const p=ha(n);n.set(p,{timerId:h,timerType:"interval"}),e.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const p=ha(n);n.set(p,{timerId:h,timerType:"timeout"}),r.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,p=0)=>{const m=ha(e);return e.set(m,()=>{h(),typeof e.get(m)=="function"&&i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"interval"}}),m},setTimeout:(h,p=0)=>{const m=ha(r);return r.set(m,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:m,timerType:"timeout"}}),m}}},OS=(t,e)=>{let r=null;return()=>{if(r!==null)return r;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=t(i),setTimeout(()=>URL.revokeObjectURL(i)),r}},NS=`(()=>{"use strict";const e=new Map,t=new Map,r=(e,t)=>{let r,o;const i=performance.now();r=i,o=e-Math.max(0,i-t);return{expected:r+o,remainingDelay:o}},o=(e,t,r,i)=>{const s=performance.now();s>r?postMessage({id:null,method:"call",params:{timerId:t,timerType:i}}):e.set(t,setTimeout(o,r-s,e,t,r,i))};addEventListener("message",(i=>{let{data:s}=i;try{if("clear"===s.method){const{id:r,params:{timerId:o,timerType:i}}=s;if("interval"===i)(t=>{const r=e.get(t);if(void 0===r)throw new Error('There is no interval scheduled with the given id "'.concat(t,'".'));clearTimeout(r),e.delete(t)})(o),postMessage({error:null,id:r});else{if("timeout"!==i)throw new Error('The given type "'.concat(i,'" is not supported'));(e=>{const r=t.get(e);if(void 0===r)throw new Error('There is no timeout scheduled with the given id "'.concat(e,'".'));clearTimeout(r),t.delete(e)})(o),postMessage({error:null,id:r})}}else{if("set"!==s.method)throw new Error('The given method "'.concat(s.method,'" is not supported'));{const{params:{delay:i,now:n,timerId:a,timerType:d}}=s;if("interval"===d)((t,i,s)=>{const{expected:n,remainingDelay:a}=r(t,s);e.set(i,setTimeout(o,a,e,i,n,"interval"))})(i,a,n);else{if("timeout"!==d)throw new Error('The given type "'.concat(d,'" is not supported'));((e,i,s)=>{const{expected:n,remainingDelay:a}=r(e,s);t.set(i,setTimeout(o,a,t,i,n,"timeout"))})(i,a,n)}}}}catch(e){postMessage({error:{message:e.message},id:s.id,result:null})}}))})();`,rd=OS(DS,NS),Ef=t=>rd().clearInterval(t),LS=t=>rd().clearTimeout(t),Tf=(t,e)=>rd().setInterval(t,e),xS=(t,e)=>rd().setTimeout(t,e);var US=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Ef,clearTimeout:LS,setInterval:Tf,setTimeout:xS},Symbol.toStringTag,{value:"Module"})),kf={},_u={exports:{}},Ch=_u.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(t){return t.encoding?"rtpmap:%d %s/%s/%s":t.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(t){return t.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(t){return t.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(t){return"extmap:%d"+(t.direction?"/%s":"%v")+(t["encrypt-uri"]?" %s":"%v")+" %s"+(t.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(t){return t.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{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(t){var e="candidate:%s %d %s %d %s %d typ %s";return e+=t.raddr!=null?" raddr %s rport %d":"%v%v",e+=t.tcptype!=null?" tcptype %s":"%v",t.generation!=null&&(e+=" generation %d"),e+=t["network-id"]!=null?" network-id %d":"%v",e+=t["network-cost"]!=null?" network-cost %d":"%v",e}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(t){var e="ssrc:%d";return t.attribute!=null&&(e+=" %s",t.value!=null&&(e+=":%s")),e}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(t){return t.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(t){return t.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(t){return"imageattr:%s %s %s"+(t.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(t){return"simulcast:%s %s"+(t.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(t){return"ts-refclk:%s"+(t.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(t){var e="mediaclk:";return e+=t.id!=null?"id=%s %s":"%v%s",e+=t.mediaClockValue!=null?"=%s":"",e+=t.rateNumerator!=null?" rate=%s":"",e+=t.rateDenominator!=null?"/%s":"",e}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(Ch).forEach(function(t){var e=Ch[t];e.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});(function(t){var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,d,h,p){if(p&&!h)d[p]=e(a[1]);else for(var m=0;m<h.length;m+=1)a[m+1]!=null&&(d[h[m]]=e(a[m+1]))},n=function(a,d,h){var p=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:p&&!d[a.name]&&(d[a.name]={});var m=a.push?{}:p?d[a.name]:d;r(h.match(a.reg),m,a.names,a.name),a.push&&d[a.push].push(m)},i=_u.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var d={},h=[],p=d;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(m){var g=m[0],v=m.slice(2);g==="m"&&(h.push({rtp:[],fmtp:[]}),p=h[h.length-1]);for(var _=0;_<(i[g]||[]).length;_+=1){var A=i[g][_];if(A.reg.test(v))return n(A,p,v)}}),d.media=h,d};var o=function(a,d){var h=d.split(/=(.+)/,2);return h.length===2?a[h[0]]=e(h[1]):h.length===1&&d.length>1&&(a[h[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var d=[],h=a.split(" ").map(e),p=0;p<h.length;p+=3)d.push({component:h[p],ip:h[p+1],port:h[p+2]});return d},t.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(h){var p,m=!1;return h[0]!=="~"?p=e(h):(p=e(h.substring(1,h.length)),m=!0),{scid:p,paused:m}})})}})(kf);var Ld=_u.exports,FS=/%[sdv%]/g,VS=function(t){var e=1,r=arguments,n=r.length;return t.replace(FS,function(i){if(e>=n)return i;var s=r[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Bs=function(t,e,r){var n=e.format instanceof Function?e.format(e.push?r:r[e.name]):e.format,i=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?i.push(r[e.name][o]):i.push(r[e.names[s]])}else i.push(r[e.name]);return VS.apply(null,i)},BS=["v","o","s","i","u","e","p","c","b","t","r","z","a"],jS=["i","c","b","a"],HS=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=e.outerOrder||BS,n=e.innerOrder||jS,i=[];return r.forEach(function(s){Ld[s].forEach(function(o){o.name in t&&t[o.name]!=null?i.push(Bs(s,o,t)):o.push in t&&t[o.push]!=null&&t[o.push].forEach(function(a){i.push(Bs(s,o,a))})})}),t.media.forEach(function(s){i.push(Bs("m",Ld.m[0],s)),n.forEach(function(o){Ld[o].forEach(function(a){a.name in s&&s[a.name]!=null?i.push(Bs(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){i.push(Bs(o,a,d))})})})}),i.join(`\r
19
19
  `)+`\r
20
- `},li=xm,rE=tE,nE=rE,Ul=li.parse;li.parseParams;li.parseFmtpConfig;li.parsePayloads;li.parseRemoteCandidates;li.parseImageAttributes;li.parseSimulcastStreamList;var iE=Object.defineProperty,sE=Object.defineProperties,oE=Object.getOwnPropertyDescriptors,Ha=Object.getOwnPropertySymbols,aE=Object.getPrototypeOf,Fm=Object.prototype.hasOwnProperty,Um=Object.prototype.propertyIsEnumerable,cE=Reflect.get,dE=Math.pow,$d=(t,e,r)=>e in t?iE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V=(t,e)=>{for(var r in e||(e={}))Fm.call(e,r)&&$d(t,r,e[r]);if(Ha)for(var r of Ha(e))Um.call(e,r)&&$d(t,r,e[r]);return t},ne=(t,e)=>sE(t,oE(e)),Ec=(t,e)=>{var r={};for(var n in t)Fm.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&Ha)for(var n of Ha(t))e.indexOf(n)<0&&Um.call(t,n)&&(r[n]=t[n]);return r},m=(t,e,r)=>($d(t,typeof e!="symbol"?e+"":e,r),r),Vl=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(Vl(t,e,"read from private field"),r?r.call(t):e.get(t)),k=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},T=(t,e,r,n)=>(Vl(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(Vl(t,e,"access private method"),r),lE=(t,e,r)=>cE(aE(t),r,e),u=(t,e,r)=>new Promise((n,i)=>{var s=d=>{try{a(r.next(d))}catch(h){i(h)}},o=d=>{try{a(r.throw(d))}catch(h){i(h)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,o);a((r=r.apply(t,e)).next())}),ju=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function uE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var It={},hE={get exports(){return It},set exports(t){It=t}},qi=typeof Reflect=="object"?Reflect:null,Hu=qi&&typeof qi.apply=="function"?qi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},ca;qi&&typeof qi.ownKeys=="function"?ca=qi.ownKeys:Object.getOwnPropertySymbols?ca=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ca=function(t){return Object.getOwnPropertyNames(t)};function pE(t){console&&console.warn&&console.warn(t)}var Vm=Number.isNaN||function(t){return t!==t};function Se(){Se.init.call(this)}hE.exports=Se;It.once=vE;Se.EventEmitter=Se;Se.prototype._events=void 0;Se.prototype._eventsCount=0;Se.prototype._maxListeners=void 0;var Wu=10;function Sc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Se,"defaultMaxListeners",{enumerable:!0,get:function(){return Wu},set:function(t){if(typeof t!="number"||t<0||Vm(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wu=t}});Se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Se.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Vm(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Bm(t){return t._maxListeners===void 0?Se.defaultMaxListeners:t._maxListeners}Se.prototype.getMaxListeners=function(){return Bm(this)};Se.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")Hu(a,this,e);else for(var d=a.length,h=Gm(a,d),r=0;r<d;++r)Hu(h[r],this,e);return!0};function jm(t,e,r,n){var i,s,o;if(Sc(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Bm(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,pE(a)}return t}Se.prototype.addListener=function(t,e){return jm(this,t,e,!1)};Se.prototype.on=Se.prototype.addListener;Se.prototype.prependListener=function(t,e){return jm(this,t,e,!0)};function mE(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Hm(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=mE.bind(n);return i.listener=r,n.wrapFn=i,i}Se.prototype.once=function(t,e){return Sc(e),this.on(t,Hm(this,t,e)),this};Se.prototype.prependOnceListener=function(t,e){return Sc(e),this.prependListener(t,Hm(this,t,e)),this};Se.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Sc(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():fE(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};Se.prototype.off=Se.prototype.removeListener;Se.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Wm(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?gE(i):Gm(i,i.length)}Se.prototype.listeners=function(t){return Wm(this,t,!0)};Se.prototype.rawListeners=function(t){return Wm(this,t,!1)};Se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):$m.call(t,e)};Se.prototype.listenerCount=$m;function $m(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Se.prototype.eventNames=function(){return this._eventsCount>0?ca(this._events):[]};function Gm(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function fE(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gE(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function vE(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Jm(t,e,s,{once:!0}),e!=="error"&&yE(t,i,{once:!0})})}function yE(t,e,r){typeof t.on=="function"&&Jm(t,"error",e,r)}function Jm(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var ur={},EE={get exports(){return ur},set exports(t){ur=t}},Zc,$u;function SE(){if($u)return Zc;$u=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Zc=function(p,f){f=f||{};var g=typeof p;if(g==="string"&&p.length>0)return o(p);if(g==="number"&&isFinite(p))return f.long?d(p):a(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(f){var g=parseFloat(f[1]),E=(f[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*n;case"hours":case"hour":case"hrs":case"hr":case"h":return g*r;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function a(p){var f=Math.abs(p);return f>=n?Math.round(p/n)+"d":f>=r?Math.round(p/r)+"h":f>=e?Math.round(p/e)+"m":f>=t?Math.round(p/t)+"s":p+"ms"}function d(p){var f=Math.abs(p);return f>=n?h(p,f,n,"day"):f>=r?h(p,f,r,"hour"):f>=e?h(p,f,e,"minute"):f>=t?h(p,f,t,"second"):p+" ms"}function h(p,f,g,E){var v=f>=g*1.5;return Math.round(p/g)+" "+E+(v?"s":"")}return Zc}function TE(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=o,r.humanize=SE(),r.destroy=h,Object.keys(t).forEach(p=>{r[p]=t[p]}),r.names=[],r.skips=[],r.formatters={};function e(p){let f=0;for(let g=0;g<p.length;g++)f=(f<<5)-f+p.charCodeAt(g),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(p){let f,g=null,E,v;function I(...A){if(!I.enabled)return;const D=I,x=Number(new Date),W=x-(f||x);D.diff=W,D.prev=f,D.curr=x,f=x,A[0]=r.coerce(A[0]),typeof A[0]!="string"&&A.unshift("%O");let H=0;A[0]=A[0].replace(/%([a-zA-Z%])/g,(R,S)=>{if(R==="%%")return"%";H++;const P=r.formatters[S];if(typeof P=="function"){const O=A[H];R=P.call(D,O),A.splice(H,1),H--}return R}),r.formatArgs.call(D,A),(D.log||r.log).apply(D,A)}return I.namespace=p,I.useColors=r.useColors(),I.color=r.selectColor(p),I.extend=n,I.destroy=r.destroy,Object.defineProperty(I,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(E!==r.namespaces&&(E=r.namespaces,v=r.enabled(p)),v),set:A=>{g=A}}),typeof r.init=="function"&&r.init(I),I}function n(p,f){const g=r(this.namespace+(typeof f=="undefined"?":":f)+p);return g.log=this.log,g}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let f;const g=(typeof p=="string"?p:"").split(/[\s,]+/),E=g.length;for(f=0;f<E;f++)g[f]&&(p=g[f].replace(/\*/g,".*?"),p[0]==="-"?r.skips.push(new RegExp("^"+p.slice(1)+"$")):r.names.push(new RegExp("^"+p+"$")))}function s(){const p=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),p}function o(p){if(p[p.length-1]==="*")return!0;let f,g;for(f=0,g=r.skips.length;f<g;f++)if(r.skips[f].test(p))return!1;for(f=0,g=r.names.length;f<g;f++)if(r.names[f].test(p))return!0;return!1}function a(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function d(p){return p instanceof Error?p.stack||p.message:p}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var _E=TE;(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let d;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(d=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(d[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;d.splice(1,0,h,"color: inherit");let p=0,f=0;d[0].replace(/%[a-zA-Z%]/g,g=>{g!=="%%"&&(p++,g==="%c"&&(f=p))}),d.splice(f,0,h)}e.log=console.debug||console.log||(()=>{});function i(d){try{d?e.storage.setItem("debug",d):e.storage.removeItem("debug")}catch{}}function s(){let d;try{d=e.storage.getItem("debug")}catch{}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function o(){try{return localStorage}catch{}}t.exports=_E(e);const{formatters:a}=t.exports;a.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(EE,ur);const Ei="mediasoup-client";let kE=class{constructor(t){t?(this._debug=ur(`${Ei}:${t}`),this._warn=ur(`${Ei}:WARN:${t}`),this._error=ur(`${Ei}:ERROR:${t}`)):(this._debug=ur(Ei),this._warn=ur(`${Ei}:WARN`),this._error=ur(`${Ei}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const bE=new kE("EnhancedEventEmitter");let Wa=class extends It.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(t,...e){return super.emit(t,...e)}safeEmit(t,...e){const r=super.listenerCount(t);try{return super.emit(t,...e)}catch(n){return bE.error("safeEmit() | event listener threw an error [eventName:%s]:%o",t,n),Boolean(r)}}on(t,e){return super.on(t,e),this}off(t,e){return super.off(t,e),this}addListener(t,e){return super.on(t,e),this}prependListener(t,e){return super.prependListener(t,e),this}once(t,e){return super.once(t,e),this}prependOnceListener(t,e){return super.prependOnceListener(t,e),this}removeListener(t,e){return super.off(t,e),this}removeAllListeners(t){return super.removeAllListeners(t),this}listenerCount(t){return super.listenerCount(t)}listeners(t){return super.listeners(t)}rawListeners(t){return super.rawListeners(t)}};var z;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(z||(z={}));var U;(function(t){t.PRECALL_TEST_BEGIN="precall_begin",t.PRECALL_TEST_COMPLETE="precall_end",t.CALL_JOIN_BEGIN="call_join",t.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",t.NET_QUALITY_TEST_END="net_quality_test_end",t.WEBSOCKET_CONNECTED="websocket_connected",t.TRANSPORT_CONNECTED="transport_connected",t.AUDIO_ON="audio_on",t.AUDIO_OFF="audio_off",t.VIDEO_ON="video_on",t.VIDEO_OFF="video_off",t.PARTICIPANT_ROLE="participant_role",t.PING_STAT="ping_stat",t.DISCONNECT="disconnect",t.RECONNECT_ATTEMPT="reconnect_attempt",t.SCREENSHARE_START_REQUESTED="screenshare_start_requested",t.SCREENSHARE_STARTED="screenshare_started",t.SCREENSHARE_STOPPED="screenshare_stopped",t.TAB_CHANGE="tab_change",t.BROWSER_BACKGROUNDED="browser_backgrounded",t.BROWSER_FOREGROUNDED="browser_foregrounded",t.DOMINANT_SPEAKER="dominant_speaker",t.AUDIO_DEVICES_UPDATES="audio_devices_updates",t.VIDEO_DEVICES_UPDATES="video_devices_updates",t.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",t.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",t.SELECTED_CAMERA_UPDATE="selected_camera_update",t.SELECTED_SPEAKER_UPDATE="selected_speaker_update",t.MEDIA_PERMISSION="media_permission",t.LEGACY_SWITCH="legacy_switch",t.AUDIO_PLAY_FAILED="audio_play_failed",t.VIDEO_PLAY_FAILED="video_play_failed",t.AUDIO_TRACK_MUTED="audio_track_muted",t.VIDEO_TRACK_MUTED="video_track_muted",t.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",t.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",t.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",t.IVS_PLAYER_ERROR="ivs_player_error",t.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",t.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",t.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",t.LIVESTREAM_LATENCY="livestream_latency",t.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",t.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",t.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",t.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(U||(U={}));const wE=new Map([[U.PRECALL_TEST_BEGIN,z.MINOR_EVENT],[U.PRECALL_TEST_COMPLETE,z.MINOR_EVENT],[U.CALL_JOIN_BEGIN,z.MAJOR_EVENT],[U.NET_QUALITY_TEST_BEGIN,z.MINOR_EVENT],[U.NET_QUALITY_TEST_END,z.MINOR_EVENT],[U.WEBSOCKET_CONNECTED,z.MINOR_EVENT],[U.TRANSPORT_CONNECTED,z.MAJOR_EVENT],[U.AUDIO_ON,z.MINOR_EVENT],[U.AUDIO_OFF,z.MINOR_EVENT],[U.VIDEO_ON,z.MINOR_EVENT],[U.VIDEO_OFF,z.MINOR_EVENT],[U.PARTICIPANT_ROLE,z.MINOR_EVENT],[U.PING_STAT,z.MAJOR_EVENT],[U.DISCONNECT,z.MAJOR_EVENT],[U.RECONNECT_ATTEMPT,z.MAJOR_EVENT],[U.SCREENSHARE_START_REQUESTED,z.MINOR_EVENT],[U.SCREENSHARE_STARTED,z.MINOR_EVENT],[U.SCREENSHARE_STOPPED,z.MINOR_EVENT],[U.TAB_CHANGE,z.MINOR_EVENT],[U.BROWSER_BACKGROUNDED,z.MINOR_EVENT],[U.BROWSER_FOREGROUNDED,z.MINOR_EVENT],[U.DOMINANT_SPEAKER,z.MINOR_EVENT],[U.AUDIO_DEVICES_UPDATES,z.MINOR_EVENT],[U.VIDEO_DEVICES_UPDATES,z.MINOR_EVENT],[U.SPEAKER_DEVICES_UPDATES,z.MINOR_EVENT],[U.SELECTED_MICROHPONE_UPDATE,z.MINOR_EVENT],[U.SELECTED_CAMERA_UPDATE,z.MINOR_EVENT],[U.SELECTED_SPEAKER_UPDATE,z.MINOR_EVENT],[U.MEDIA_PERMISSION,z.MINOR_EVENT],[U.LEGACY_SWITCH,z.MINOR_EVENT],[U.AUDIO_PLAY_FAILED,z.MINOR_EVENT],[U.VIDEO_PLAY_FAILED,z.MINOR_EVENT],[U.AUDIO_TRACK_MUTED,z.MINOR_EVENT],[U.VIDEO_TRACK_MUTED,z.MINOR_EVENT],[U.IVS_PLAYER_REBUFFERING,z.MAJOR_EVENT],[U.IVS_PLAYER_AUDIO_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_PLAYBACK_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_RECOVERABLE_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_WORKER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_NETWORK_UNAVAILABLE,z.MAJOR_EVENT],[U.LIVESTREAM_LATENCY,z.MAJOR_EVENT],[U.IVS_PLAYER_ANALYTICS_EVENT,z.MINOR_EVENT],[U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_QUALITY_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_INITIALIZED,z.MINOR_EVENT]]);class CE{constructor(){m(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class IE extends It{constructor({logger:e,peerId:r,apiHostnames:n}){super(),m(this,"logger"),m(this,"peerId"),m(this,"eventStore"),m(this,"apiEndpoint"),this.logger=e,this.peerId=r,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new CE}sendEventsChunkToServer(e){return u(this,null,function*(){var r;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(i){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:i}),(r=e.entries)==null||r.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),wE.get(e.event)===z.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const r=this.eventStore.flush();return(e=r==null?void 0:r.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(r),!0):!1})}}var Gu;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(Gu||(Gu={}));const Zs={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Gt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Gt||(Gt={}));var Ju;(function(t){t[t.INIT=0]="INIT",t[t.ACCEPTED=1]="ACCEPTED",t[t.DENIED=2]="DENIED",t[t.SYS_DENIED=3]="SYS_DENIED",t[t.FAILED=4]="FAILED",t[t.NOTFOUND=5]="NOTFOUND",t[t.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Ju||(Ju={}));const qm=240,Km=720,zm=8,Ym=3,Tc=10,_c=.02,kc=.03;function xr({stat:t,weight:e,rangeMin:r,rangeMax:n,rangeRankingDirection:i}){return t==null?e:r===n?i==="UP"?t<=r?e:0:t>=n?e:0:i==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r))*e:i==="DOWN"?Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r)*e:e}function Qm({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:r,jitterQuality:n,packetsLostQuality:i}){const s=.8*((t?.85:1)*(r?.7:1)*(e?.5:1))+.2*(n*i);return Math.round((s+Number.EPSILON)*100)/100}function Xm({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Zm({packetsLost:t,packetsSent:e,jitter:r}){const n=xr({stat:Xm({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Tc,rangeRankingDirection:"UP"}),i=xr({stat:r,weight:.3,rangeMin:_c,rangeMax:kc,rangeRankingDirection:"UP"});return n+i}function RE({frameWidth:t,isScreenShare:e}){return t<(e?Km:qm)}function PE({framesPerSecond:t,isScreenShare:e}){return t<(e?Ym:zm)}function AE({framesEncoded:t}){return t===0}function ef({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:o}){const a=xr({stat:Xm({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:Tc,rangeRankingDirection:"UP"}),d=xr({stat:i,weight:1,rangeMin:_c,rangeMax:kc,rangeRankingDirection:"UP"}),h=RE({frameWidth:t,isScreenShare:s}),p=PE({framesPerSecond:e,isScreenShare:s}),f=AE({framesEncoded:o,isScreenShare:s});return Qm({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}function tf({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function rf({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=xr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=xr({stat:tf({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:Tc,rangeRankingDirection:"UP"}),a=xr({stat:n,weight:.3,rangeMin:_c,rangeMax:kc,rangeRankingDirection:"UP"});return i+o+a}function ME({framesDecoded:t}){return t===0}function DE({framesPerSecond:t,isScreenShare:e}){return t<(e?Ym:zm)}function OE({frameWidth:t,isScreenShare:e}){return t<(e?Km:qm)}function nf({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:o}){const a=xr({stat:tf({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:Tc,rangeRankingDirection:"UP"}),d=xr({stat:i,weight:1,rangeMin:_c,rangeMax:kc,rangeRankingDirection:"UP"}),h=OE({frameWidth:t,isScreenShare:s}),p=DE({framesPerSecond:e,isScreenShare:s}),f=ME({framesDecoded:o,isScreenShare:s});return Qm({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}class Fr{constructor(e){m(this,"pc1"),m(this,"pc2"),m(this,"constrainVideoBitrateKbps"),m(this,"constrainOfferToRemoveVideoFec",!1),m(this,"iceCandidateFilter");const r=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=r,this.pc2=n,this.iceCandidateFilter=Fr.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(e){const r="candidate:",n=e.indexOf(r)+r.length,i=e.substr(n).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(e){return e.type!=="host"}static isHost(e){return e.type==="host"}static isRelay(e){return e.type==="relay"}static isReflexive(e){return e.type==="srflx"}static noFilter(e){return!0}onIceCandidate(e,r){if(r.candidate){const n=Fr.parseCandidate(r.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(r.candidate)}}setIceCandidateFilter(e){this.iceCandidateFilter=e}constrainVideoBitrate(e){this.constrainVideoBitrateKbps=e}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(e){this.constrainOfferToRemoveVideoFec&&(e.sdp=e.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
20
+ `},wi=kf,WS=HS,$S=WS,bu=wi.parse;wi.parseParams;wi.parseFmtpConfig;wi.parsePayloads;wi.parseRemoteCandidates;wi.parseImageAttributes;wi.parseSimulcastStreamList;var JS=Object.defineProperty,GS=Object.defineProperties,qS=Object.getOwnPropertyDescriptors,Ic=Object.getOwnPropertySymbols,zS=Object.getPrototypeOf,_f=Object.prototype.hasOwnProperty,bf=Object.prototype.propertyIsEnumerable,KS=Reflect.get,YS=Math.pow,Ml=(t,e,r)=>e in t?JS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,B=(t,e)=>{for(var r in e||(e={}))_f.call(e,r)&&Ml(t,r,e[r]);if(Ic)for(var r of Ic(e))bf.call(e,r)&&Ml(t,r,e[r]);return t},Z=(t,e)=>GS(t,qS(e)),nd=(t,e)=>{var r={};for(var n in t)_f.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&Ic)for(var n of Ic(t))e.indexOf(n)<0&&bf.call(t,n)&&(r[n]=t[n]);return r},f=(t,e,r)=>(Ml(t,typeof e!="symbol"?e+"":e,r),r),wu=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(wu(t,e,"read from private field"),r?r.call(t):e.get(t)),T=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},S=(t,e,r,n)=>(wu(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ye=(t,e,r)=>(wu(t,e,"access private method"),r),QS=(t,e,r)=>KS(zS(t),r,e),u=(t,e,r)=>new Promise((n,i)=>{var s=d=>{try{a(r.next(d))}catch(h){i(h)}},o=d=>{try{a(r.throw(d))}catch(h){i(h)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,o);a((r=r.apply(t,e)).next())}),Ph=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function XS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ft={},ZS={get exports(){return ft},set exports(t){ft=t}},os=typeof Reflect=="object"?Reflect:null,Rh=os&&typeof os.apply=="function"?os.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ga;os&&typeof os.ownKeys=="function"?Ga=os.ownKeys:Object.getOwnPropertySymbols?Ga=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ga=function(t){return Object.getOwnPropertyNames(t)};function eE(t){console&&console.warn&&console.warn(t)}var wf=Number.isNaN||function(t){return t!==t};function ke(){ke.init.call(this)}ZS.exports=ke;ft.once=iE;ke.EventEmitter=ke;ke.prototype._events=void 0;ke.prototype._eventsCount=0;ke.prototype._maxListeners=void 0;var Ah=10;function id(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ke,"defaultMaxListeners",{enumerable:!0,get:function(){return Ah},set:function(t){if(typeof t!="number"||t<0||wf(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Ah=t}});ke.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};ke.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||wf(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function If(t){return t._maxListeners===void 0?ke.defaultMaxListeners:t._maxListeners}ke.prototype.getMaxListeners=function(){return If(this)};ke.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")Rh(a,this,e);else for(var d=a.length,h=Mf(a,d),r=0;r<d;++r)Rh(h[r],this,e);return!0};function Cf(t,e,r,n){var i,s,o;if(id(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=If(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,eE(a)}return t}ke.prototype.addListener=function(t,e){return Cf(this,t,e,!1)};ke.prototype.on=ke.prototype.addListener;ke.prototype.prependListener=function(t,e){return Cf(this,t,e,!0)};function tE(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Pf(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=tE.bind(n);return i.listener=r,n.wrapFn=i,i}ke.prototype.once=function(t,e){return id(e),this.on(t,Pf(this,t,e)),this};ke.prototype.prependOnceListener=function(t,e){return id(e),this.prependListener(t,Pf(this,t,e)),this};ke.prototype.removeListener=function(t,e){var r,n,i,s,o;if(id(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():rE(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};ke.prototype.off=ke.prototype.removeListener;ke.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Rf(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?nE(i):Mf(i,i.length)}ke.prototype.listeners=function(t){return Rf(this,t,!0)};ke.prototype.rawListeners=function(t){return Rf(this,t,!1)};ke.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Af.call(t,e)};ke.prototype.listenerCount=Af;function Af(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ke.prototype.eventNames=function(){return this._eventsCount>0?Ga(this._events):[]};function Mf(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function rE(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function nE(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function iE(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Df(t,e,s,{once:!0}),e!=="error"&&sE(t,i,{once:!0})})}function sE(t,e,r){typeof t.on=="function"&&Df(t,"error",e,r)}function Df(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var X;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(X||(X={}));var F;(function(t){t.PRECALL_TEST_BEGIN="precall_begin",t.PRECALL_TEST_COMPLETE="precall_end",t.CALL_JOIN_BEGIN="call_join",t.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",t.NET_QUALITY_TEST_END="net_quality_test_end",t.WEBSOCKET_CONNECTED="websocket_connected",t.TRANSPORT_CONNECTED="transport_connected",t.AUDIO_ON="audio_on",t.AUDIO_OFF="audio_off",t.VIDEO_ON="video_on",t.VIDEO_OFF="video_off",t.PARTICIPANT_ROLE="participant_role",t.PING_STAT="ping_stat",t.DISCONNECT="disconnect",t.RECONNECT_ATTEMPT="reconnect_attempt",t.SCREENSHARE_START_REQUESTED="screenshare_start_requested",t.SCREENSHARE_STARTED="screenshare_started",t.SCREENSHARE_STOPPED="screenshare_stopped",t.TAB_CHANGE="tab_change",t.BROWSER_BACKGROUNDED="browser_backgrounded",t.BROWSER_FOREGROUNDED="browser_foregrounded",t.DOMINANT_SPEAKER="dominant_speaker",t.AUDIO_DEVICES_UPDATES="audio_devices_updates",t.VIDEO_DEVICES_UPDATES="video_devices_updates",t.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",t.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",t.SELECTED_CAMERA_UPDATE="selected_camera_update",t.SELECTED_SPEAKER_UPDATE="selected_speaker_update",t.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",t.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",t.MEDIA_PERMISSION="media_permission",t.LEGACY_SWITCH="legacy_switch",t.AUDIO_PLAY_FAILED="audio_play_failed",t.VIDEO_PLAY_FAILED="video_play_failed",t.AUDIO_TRACK_MUTED="audio_track_muted",t.VIDEO_TRACK_MUTED="video_track_muted",t.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",t.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",t.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",t.IVS_PLAYER_ERROR="ivs_player_error",t.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",t.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",t.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",t.LIVESTREAM_LATENCY="livestream_latency",t.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",t.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",t.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",t.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(F||(F={}));const oE=new Map([[F.PRECALL_TEST_BEGIN,X.MINOR_EVENT],[F.PRECALL_TEST_COMPLETE,X.MINOR_EVENT],[F.CALL_JOIN_BEGIN,X.MAJOR_EVENT],[F.NET_QUALITY_TEST_BEGIN,X.MINOR_EVENT],[F.NET_QUALITY_TEST_END,X.MINOR_EVENT],[F.WEBSOCKET_CONNECTED,X.MINOR_EVENT],[F.TRANSPORT_CONNECTED,X.MAJOR_EVENT],[F.AUDIO_ON,X.MINOR_EVENT],[F.AUDIO_OFF,X.MINOR_EVENT],[F.VIDEO_ON,X.MINOR_EVENT],[F.VIDEO_OFF,X.MINOR_EVENT],[F.PARTICIPANT_ROLE,X.MINOR_EVENT],[F.PING_STAT,X.MAJOR_EVENT],[F.DISCONNECT,X.MAJOR_EVENT],[F.RECONNECT_ATTEMPT,X.MAJOR_EVENT],[F.SCREENSHARE_START_REQUESTED,X.MINOR_EVENT],[F.SCREENSHARE_STARTED,X.MINOR_EVENT],[F.SCREENSHARE_STOPPED,X.MINOR_EVENT],[F.TAB_CHANGE,X.MINOR_EVENT],[F.BROWSER_BACKGROUNDED,X.MINOR_EVENT],[F.BROWSER_FOREGROUNDED,X.MINOR_EVENT],[F.DOMINANT_SPEAKER,X.MINOR_EVENT],[F.AUDIO_DEVICES_UPDATES,X.MINOR_EVENT],[F.VIDEO_DEVICES_UPDATES,X.MINOR_EVENT],[F.SPEAKER_DEVICES_UPDATES,X.MINOR_EVENT],[F.SELECTED_MICROHPONE_UPDATE,X.MINOR_EVENT],[F.SELECTED_CAMERA_UPDATE,X.MINOR_EVENT],[F.SELECTED_SPEAKER_UPDATE,X.MINOR_EVENT],[F.MEDIA_PERMISSION,X.MINOR_EVENT],[F.LEGACY_SWITCH,X.MINOR_EVENT],[F.AUDIO_PLAY_FAILED,X.MINOR_EVENT],[F.VIDEO_PLAY_FAILED,X.MINOR_EVENT],[F.AUDIO_TRACK_MUTED,X.MINOR_EVENT],[F.VIDEO_TRACK_MUTED,X.MINOR_EVENT],[F.IVS_PLAYER_REBUFFERING,X.MAJOR_EVENT],[F.IVS_PLAYER_AUDIO_BLOCKED,X.MAJOR_EVENT],[F.IVS_PLAYER_PLAYBACK_BLOCKED,X.MAJOR_EVENT],[F.IVS_PLAYER_ERROR,X.MAJOR_EVENT],[F.IVS_PLAYER_RECOVERABLE_ERROR,X.MAJOR_EVENT],[F.IVS_PLAYER_WORKER_ERROR,X.MAJOR_EVENT],[F.IVS_PLAYER_NETWORK_UNAVAILABLE,X.MAJOR_EVENT],[F.LIVESTREAM_LATENCY,X.MAJOR_EVENT],[F.IVS_PLAYER_ANALYTICS_EVENT,X.MINOR_EVENT],[F.IVS_PLAYER_PLAYBACK_RATE_CHANGED,X.MINOR_EVENT],[F.IVS_PLAYER_QUALITY_CHANGED,X.MINOR_EVENT],[F.IVS_PLAYER_INITIALIZED,X.MINOR_EVENT],[F.EXPECTED_VIDEO_RESOLUTION,X.MINOR_EVENT],[F.EXPECTED_SCREENSHARE_RESOLUTION,X.MINOR_EVENT]]);class aE{constructor(){f(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class cE extends ft{constructor({logger:e,peerId:r,apiHostnames:n}){super(),f(this,"logger"),f(this,"peerId"),f(this,"eventStore"),f(this,"apiEndpoint"),this.logger=e,this.peerId=r,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new aE}sendEventsChunkToServer(e){return u(this,null,function*(){var r;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(i){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:i}),(r=e.entries)==null||r.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),oE.get(e.event)===X.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const r=this.eventStore.flush();return(e=r==null?void 0:r.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(r),!0):!1})}}var Mh;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(Mh||(Mh={}));const Vo={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var tr;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(tr||(tr={}));var Dh;(function(t){t[t.INIT=0]="INIT",t[t.ACCEPTED=1]="ACCEPTED",t[t.DENIED=2]="DENIED",t[t.SYS_DENIED=3]="SYS_DENIED",t[t.FAILED=4]="FAILED",t[t.NOTFOUND=5]="NOTFOUND",t[t.NOT_APPLICABLE=6]="NOT_APPLICABLE"})(Dh||(Dh={}));function Nn(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Cc({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Pc({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const Of=240,Nf=720,Lf=8,xf=3,sd=10,od=.02,ad=.03;function Xr({stat:t,weight:e,rangeMin:r,rangeMax:n,rangeRankingDirection:i}){return t==null?e:r===n?i==="UP"?t<=r?e:0:t>=n?e:0:i==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r))*e:i==="DOWN"?Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r)*e:e}function Uf({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:r,jitterQuality:n,packetsLostQuality:i}){const s=.8*((t?.85:1)*(r?.7:1)*(e?.5:1))+.2*(n*i);return Math.round((s+Number.EPSILON)*100)/100}function Ff({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function Vf({packetsLost:t,packetsSent:e,jitter:r}){const n=Xr({stat:Ff({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:sd,rangeRankingDirection:"UP"}),i=Xr({stat:r,weight:.3,rangeMin:od,rangeMax:ad,rangeRankingDirection:"UP"});return n+i}function dE({frameWidth:t,isScreenShare:e}){return t<(e?Nf:Of)}function lE({framesPerSecond:t,isScreenShare:e}){return t<(e?xf:Lf)}function uE({framesEncoded:t}){return t===0}function Bf({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:o}){const a=Xr({stat:Ff({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:sd,rangeRankingDirection:"UP"}),d=Xr({stat:i,weight:1,rangeMin:od,rangeMax:ad,rangeRankingDirection:"UP"}),h=dE({frameWidth:t,isScreenShare:s}),p=lE({framesPerSecond:e,isScreenShare:s}),m=uE({framesEncoded:o,isScreenShare:s});return Uf({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:a})}function jf({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function Hf({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=Xr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=Xr({stat:jf({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:sd,rangeRankingDirection:"UP"}),a=Xr({stat:n,weight:.3,rangeMin:od,rangeMax:ad,rangeRankingDirection:"UP"});return i+o+a}function hE({framesDecoded:t}){return t===0}function pE({framesPerSecond:t,isScreenShare:e}){return t<(e?xf:Lf)}function mE({frameWidth:t,isScreenShare:e}){return t<(e?Nf:Of)}function Wf({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:o}){const a=Xr({stat:jf({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:sd,rangeRankingDirection:"UP"}),d=Xr({stat:i,weight:1,rangeMin:od,rangeMax:ad,rangeRankingDirection:"UP"}),h=mE({frameWidth:t,isScreenShare:s}),p=pE({framesPerSecond:e,isScreenShare:s}),m=hE({framesDecoded:o,isScreenShare:s});return Uf({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:m,jitterQuality:d,packetsLostQuality:a})}class en{constructor(e){f(this,"pc1"),f(this,"pc2"),f(this,"constrainVideoBitrateKbps"),f(this,"constrainOfferToRemoveVideoFec",!1),f(this,"iceCandidateFilter");const r=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=r,this.pc2=n,this.iceCandidateFilter=en.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(e){const r="candidate:",n=e.indexOf(r)+r.length,i=e.substr(n).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(e){return e.type!=="host"}static isHost(e){return e.type==="host"}static isRelay(e){return e.type==="relay"}static isReflexive(e){return e.type==="srflx"}static noFilter(e){return!0}onIceCandidate(e,r){if(r.candidate){const n=en.parseCandidate(r.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(r.candidate)}}setIceCandidateFilter(e){this.iceCandidateFilter=e}constrainVideoBitrate(e){this.constrainVideoBitrateKbps=e}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(e){this.constrainOfferToRemoveVideoFec&&(e.sdp=e.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
21
21
  `),e.sdp=e.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),e.sdp=e.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(e),this.pc2.setRemoteDescription(e),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(e){this.constrainVideoBitrateKbps&&(e.sdp=e.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
22
22
  b=AS:${this.constrainVideoBitrateKbps}\r
23
- `)),this.pc2.setLocalDescription(e),this.pc1.setRemoteDescription(e)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(e){console.error("Error:",e)}getRoundTripTime(){return u(this,null,function*(){const[e,r]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,i;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),r.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(i=s)}),n&&i)try{if(n.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const s=(i.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch{return}})}close(){this.pc1.close(),this.pc2.close()}}class sf extends It{constructor(e){super(),m(this,"call"),m(this,"timeOut"),this.call=new Fr(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const NE=8,LE=1/1e3;class xE extends sf{constructor(e){super(e),m(this,"senderChannel"),m(this,"recieveChannel"),m(this,"startTime"),m(this,"lastBitrateMeasureTime"),m(this,"sentPayloadBytes",0),m(this,"recievedPayloadBytes",0),m(this,"lastReceivedPayloadBytes",0),m(this,"stopSending",!1),m(this,"testProgress",0),m(this,"samplePacket",""),m(this,"finalBitrateSum",0),m(this,"bitRateSampels",0),m(this,"maxNumberOfPacketsToSend",0),m(this,"bytesToKeepBuffered",0),m(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(Fr.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch{}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const i=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*NE/(n/1e3);this.finalBitrateSum+=i,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*LE)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Bl extends sf{constructor(e,r=Fr.noFilter){super(e),m(this,"ch1"),m(this,"ch2"),this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch{}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class FE extends Bl{constructor(e){super(e,Fr.isHost)}}class UE extends Bl{constructor(e){super(e,Fr.isRelay)}}class VE extends Bl{constructor(e){super(e,Fr.isReflexive)}}class BE{constructor(){m(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:r,apiHostnames:n}){var i;if(!this.ipInformation){try{const o=`https://${n.location}`,a=yield(yield fetch(o)).json();if(((i=a.loc)==null?void 0:i.length)>5)return this.ipInformation=a,a;throw Error("Insufficient data")}catch{}const s=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${r}`,{method:"POST"});this.ipInformation=yield s.json()}return this.ipInformation})}resetCache(){this.ipInformation=null}}const jl=new BE,qu=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Ku(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class of{constructor(){m(this,"transport"),m(this,"candidatePair"),m(this,"outboundVideoRtp",new Map),m(this,"inboundVideoRtp",new Map),m(this,"outboundAudioRtp",new Map),m(this,"inboundAudioRtp",new Map),m(this,"remoteInboundRtp",new Map),m(this,"producerStreamMap",new Map),m(this,"consumerStreamMap",new Map),m(this,"staleProducerStreamMap",!1),m(this,"staleConsumerStreamMap",!1)}}class af extends Wa{constructor(){super(),m(this,"observer"),m(this,"outboundProducerMap",new Map),m(this,"inboundConsumerMap",new Map),m(this,"consumerPeerIdMap",new Map),m(this,"pausedConsumerMap",new Map),m(this,"pausedProducerMap",new Map),m(this,"overallProducingTransportsStatsMap",{}),m(this,"overallConsumingTransportsStatsMap",{}),m(this,"overallConsumersStatsMap",{}),m(this,"overallProducersStatsMap",{}),m(this,"videoProducerToStatsMap",new Map),m(this,"audioProducerToStatsMap",new Map),m(this,"videoConsumerToStatsMap",new Map),m(this,"audioConsumerToStatsMap",new Map),m(this,"consumerIdsWithFreezedVideo",new Set),m(this,"consumerIdsWithFreezedAudio",new Set),m(this,"producerIdsWithFreezedVideo",new Set),m(this,"producerIdsWithFreezedAudio",new Set),m(this,"freezedProducingTransportIds",new Set),m(this,"freezedConsumingTransportIds",new Set),m(this,"screenShareProducers",new Set),m(this,"screenShareConsumers",new Set),m(this,"ipDetails"),m(this,"callStatsInstance"),this.observer=new Wa}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{},{audio:o,video:a,screen:d}=s,h=o||a||d;r.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,n){var i,s;const o=!!Array.from(((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((a,d)=>a||d.audio||d.video||d.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return u(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}generateProducerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"outbound-rtp":{this.outboundProducerMap.set(s.id,e.id);break}}return i})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"inbound-rtp":{this.inboundConsumerMap.set(s.id,e.id);break}}return i})}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(r=>{const n=r.framesEncoded>0,i=r.packetsSent>0,s=r.frameWidth&&r.frameHeight;return n&&i&&!!s})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new of,I=r.length?new Set(r):void 0,A=[],D=[],x=[],W=new Map,H=new Map;for(const R of E.values()){if(I){if(I.size===0)break;if(I.has(R.type))n&&I.delete(R.type);else continue}switch(R.type){case"local-candidate":{A.push(this.getIceCandidateStats(R));break}case"remote-candidate":{D.push(this.getIceCandidateStats(R));break}case"candidate-pair":{const{nominated:S}=R,{selected:P}=R,O=R,ae={nominated:S!=null?S:P,currentRoundTripTime:O.currentRoundTripTime,totalRoundTripTime:O.totalRoundTripTime,bytesReceived:O.bytesReceived,bytesSent:O.bytesSent,availableOutgoingBitrate:O.availableOutgoingBitrate,lastPacketReceivedTimestamp:O.lastPacketReceivedTimestamp,lastPacketSentTimestamp:O.lastPacketSentTimestamp,localCandidateId:O.localCandidateId,remoteCandidateId:O.remoteCandidateId,bytesDiscardedOnSend:O.bytesDiscardedOnSend,packetsSent:O.packetsSent,packetsReceived:O.packetsReceived,packetsDiscardedOnSend:O.packetsDiscardedOnSend};x.push(ae),(R.nominated===!0||R.selected===!0)&&(v.candidatePair=ae);break}case"transport":{const S=R;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const O=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,O,P)}if(s.consuming){const O=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,O,P)}}break}case"remote-inbound-rtp":{const S=R,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=R,P=i||this.outboundProducerMap.get(R.id),O=this.pausedProducerMap.get(P);if(O){if(O.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ae=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(R.id)){v.staleProducerStreamMap=!0;break}const Oe=this.callStatsInstance.producers.get(P);if(((o=Oe==null?void 0:Oe.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const F=S,ye=V({frameHeight:F.frameHeight,frameWidth:F.frameWidth,framesEncoded:F.framesEncoded,framesDropped:F.framesDropped,framesPerSecond:F.framesPerSecond,framesSent:F.framesSent,keyFramesEncoded:F.keyFramesEncoded,firCount:F.firCount,encoderImplementation:F.encoderImplementation,hugeFramesSent:F.hugeFramesSent,pliCount:F.pliCount,qpSum:F.qpSum,qualityLimitationDurations:F.qualityLimitationDurations,qualityLimitationReason:F.qualityLimitationReason,qualityLimitationResolutionChanges:F.qualityLimitationResolutionChanges,totalEncodeTime:F.targetBitrate,totalPacketSendDelay:F.totalPacketSendDelay,retransmittedBytesSent:F.retransmittedBytesSent,retransmittedPacketsSent:F.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(P,ye),v.outboundVideoRtp.set(R.id,ye),v.producerStreamMap.get(P).outboundVideoRtpId.push(R.id),this.processOutboundProducerVideoStats(P,ae,ye)}else if(S.mediaType==="audio"||S.kind==="audio"){const F=S,ye=V({retransmittedBytesSent:F.retransmittedBytesSent,retransmittedPacketsSent:F.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(P,ye),v.outboundAudioRtp.set(R.id,ye),v.producerStreamMap.get(P).outboundAudioRtpId.push(R.id),this.processOutboundProducerAudioStats(P,ae,ye)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=R,P=i||this.inboundConsumerMap.get(R.id),O=this.pausedConsumerMap.get(P);if(O){if(O.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ae=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(R.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Oe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,F=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped,framesPerSecond:$.framesPerSecond,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Oe);F.score=nf({frameWidth:F.frameWidth||0,framesDecoded:(F.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:F.framesPerSecond||0,packetsLost:(F.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(F.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:F.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,F.score),this.videoConsumerToStatsMap.set(P,F),v.inboundVideoRtp.set(R.id,F),v.consumerStreamMap.get(P).inboundVideoRtpId.push(R.id),this.processInboundConsumerVideoStats(P,ae,F)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,F=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Oe);F.score=rf({concealmentEvents:(F.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(F.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(F.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:F.jitter||0}),H.set(P,F.score),this.audioConsumerToStatsMap.set(P,F),v.inboundAudioRtp.set(R.id,F),v.consumerStreamMap.get(P).inboundAudioRtpId.push(R.id),this.processInboundConsumerAudioStats(P,ae,F)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((R,S)=>{var P,O,ae,Oe,$,F,ye,Hr,Sn,Tn,dt;if(R.outboundVideoRtpId.length>0){const Ke=[];R.outboundVideoRtpId.forEach(ms=>{Ke.push(v.outboundVideoRtp.get(ms))});const ze=this.getWorkingSimulcastVideoStats(Ke);ze.score=ef({frameWidth:ze.frameWidth||0,framesPerSecond:ze.framesPerSecond||0,jitter:((P=ze.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(ze.packetsSent||0)-(((O=this.videoProducerToStatsMap.get(S))==null?void 0:O.packetsSent)||0),packetsLost:(((ae=ze.remoteData)==null?void 0:ae.packetsLost)||0)-((($=(Oe=this.videoProducerToStatsMap.get(S))==null?void 0:Oe.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(ze.framesEncoded||0)-(((F=this.videoProducerToStatsMap.get(S))==null?void 0:F.framesEncoded)||0)}),W.set(S,ze.score)}else if(R.outboundAudioRtpId.length>0){const Ke=v.outboundAudioRtp.get(R.outboundAudioRtpId[0]);Ke.score=Zm({packetsSent:(Ke.packetsSent||0)-(((ye=this.audioProducerToStatsMap.get(S))==null?void 0:ye.packetsSent)||0),packetsLost:(((Hr=Ke.remoteData)==null?void 0:Hr.packetsLost)||0)-(((Tn=(Sn=this.audioProducerToStatsMap.get(S))==null?void 0:Sn.remoteData)==null?void 0:Tn.packetsLost)||0),jitter:((dt=Ke.remoteData)==null?void 0:dt.jitter)||0}),W.set(S,Ke.score)}}),x.forEach(R=>{const S=A.find(O=>O.id===R.localCandidateId?(R.localCandidateId=O.id,O):null),P=D.find(O=>O.id===R.remoteCandidateId?(R.remoteCandidateId=O.id,O):null);S&&(R.localCandidateType=S.type,R.localCandidateAddress=S.address,R.localCandidatePort=S.port,R.localCandidateProtocol=S.protocol,R.localCandidateUrl=S.url,R.localCandidateNetworkType=S.networkType,R.localCandidateRelatedAddress=S.relatedAddress,R.localCandidateRelatedPort=S.relatedPort),P&&(R.remoteCandidateType=P.type,R.remoteCandidateAddress=P.address,R.remoteCandidatePort=P.port,R.remoteCandidateProtocol=P.protocol,R.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=x),v.transport&&!v.transport.roundTripTime){let R=0,S=0;v.remoteInboundRtp.forEach((P,O)=>{P.roundTripTime&&P.roundTripTime>R&&(R=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=R,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getConsumersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,r,n){return u(this,null,function*(){const i=yield this.getTransportReport(e),s={producing:n,consuming:r,id:e.id},o=i,a=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!a)return;const d={stats:a.transport,transportId:e.id,consuming:r,producing:n},h=a.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(a),p=a.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(a);return{transportReport:d,producerReport:h,consumerReport:p}})}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var s,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(a=>e.outboundVideoRtp.get(a)),audioStats:n.outboundAudioRtpId.map(a=>e.outboundAudioRtp.get(a)),appData:((o=(s=this.callStatsInstance.producers)==null?void 0:s.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:s,producerId:o,appData:a,videoStats:n.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:n.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}getUserLocation(){return u(this,null,function*(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const r={iceServers:e||qu},n=new Promise((h,p)=>{try{const f=new FE(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),i=new Promise((h,p)=>{try{const f=new UE(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),s=new Promise((h,p)=>{try{const f=new VE(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[o,a,d]=yield Promise.all([n,i,s]);return{host:o==null?void 0:o.connectivity,relay:a==null?void 0:a.connectivity,reflexive:d==null?void 0:d.connectivity}}catch{return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const r=yield new Promise((n,i)=>{try{const s={iceServers:e||qu},o=new xE(s);o.addListener("done",n),o.addListener("failed",i),o.start(1e4)}catch(s){i(s)}});return{throughput:r.throughput,fractionalLoss:0,RTT:r.RTT,jitter:0,backendRTT:r.backendRTT}}catch{return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield jl.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch{return}})}getNetworkQuality(e){return u(this,null,function*(){const[r,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}})}getNetworkInfo(e,r=!1){return u(this,null,function*(){var n,i;if(r){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d.loc?Ku(d.loc):void 0}}const[s,o,a]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:a.loc?Ku(a.loc):void 0,turnConnectivity:s?s.host||s.relay||s.reflexive:!1,connectivity:s,throughput:o==null?void 0:o.throughput,fractionalLoss:o==null?void 0:o.fractionalLoss,RTT:o==null?void 0:o.RTT,jitter:o==null?void 0:o.jitter,backendRTT:o==null?void 0:o.backendRTT}})}}class jE extends af{}class cf extends af{constructor(){super(...arguments),m(this,"producerMap",new Map),m(this,"consumerMap",new Map)}registerProducer(e){return u(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return u(this,null,function*(){this.consumerMap.set(e.id,e),yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,s,e.id):void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return o})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new of,I=r.length?new Set(r):void 0,A=[],D=[],x=[],W=new Map,H=new Map;for(const R of E.values()){if(I){if(I.size===0)break;if(I.has(R.type))n&&I.delete(R.type);else continue}switch(R.type){case"local-candidate":{A.push(this.getIceCandidateStats(R));break}case"remote-candidate":{D.push(this.getIceCandidateStats(R));break}case"candidate-pair":{const{nominated:S}=R,{selected:P}=R,O=R,ae={nominated:S!=null?S:P,currentRoundTripTime:O.currentRoundTripTime,totalRoundTripTime:O.totalRoundTripTime,bytesReceived:O.bytesReceived,bytesSent:O.bytesSent,availableOutgoingBitrate:O.availableOutgoingBitrate,lastPacketReceivedTimestamp:O.lastPacketReceivedTimestamp,lastPacketSentTimestamp:O.lastPacketSentTimestamp,localCandidateId:O.localCandidateId,remoteCandidateId:O.remoteCandidateId,bytesDiscardedOnSend:O.bytesDiscardedOnSend,packetsSent:O.packetsSent,packetsReceived:O.packetsReceived,packetsDiscardedOnSend:O.packetsDiscardedOnSend};x.push(ae),(R.nominated===!0||R.selected===!0)&&(v.candidatePair=ae);break}case"transport":{const S=R;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const O=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,O,P)}if(s.consuming){const O=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,O,P)}}break}case"remote-inbound-rtp":{const S=R,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=R,P=i||this.outboundProducerMap.get(R.id),O=this.pausedProducerMap.get(P);if(O){if(O.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ae=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(R.id)){v.staleProducerStreamMap=!0;break}const Oe=this.callStatsInstance.producers.get(P);if(((o=Oe==null?void 0:Oe.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const F=S,ye=V({frameHeight:F.frameHeight,frameWidth:F.frameWidth,framesEncoded:F.framesEncoded,framesDropped:F.framesDropped?F.framesDropped:F.droppedFrames,framesPerSecond:F.framesPerSecond?F.framesPerSecond:F.framerateMean,framesSent:F.framesSent,keyFramesEncoded:F.keyFramesEncoded,firCount:F.firCount,encoderImplementation:F.encoderImplementation,hugeFramesSent:F.hugeFramesSent,pliCount:F.pliCount,qpSum:F.qpSum,qualityLimitationReason:F.qualityLimitationReason,qualityLimitationDurations:F.qualityLimitationDurations,qualityLimitationResolutionChanges:F.qualityLimitationResolutionChanges,totalEncodeTime:F.totalEncodeTime,totalPacketSendDelay:F.totalEncodeTime,retransmittedBytesSent:F.retransmittedBytesSent,retransmittedPacketsSent:F.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(R.id,ye),v.outboundVideoRtp.set(R.id,ye),v.producerStreamMap.get(P).outboundVideoRtpId.push(R.id),this.processOutboundProducerVideoStats(P,ae,ye)}else if(S.mediaType==="audio"||S.kind==="audio"){const F=S,ye=V({retransmittedBytesSent:F.retransmittedBytesSent,retransmittedPacketsSent:F.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(R.id,ye),v.outboundAudioRtp.set(R.id,ye),v.producerStreamMap.get(P).outboundAudioRtpId.push(R.id),this.processOutboundProducerAudioStats(P,ae,ye)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=R,P=i||this.inboundConsumerMap.get(R.id),O=this.pausedConsumerMap.get(P);if(O){if(O.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ae=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(R.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Oe={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,F=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped?$.framesDropped:$.droppedFrames,framesPerSecond:$.framesPerSecond?$.framesPerSecond:$.framerateMean,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Oe);F.score=nf({frameWidth:F.frameWidth||0,framesDecoded:(F.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:F.framesPerSecond||0,packetsLost:(F.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(F.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:F.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,F.score),this.videoConsumerToStatsMap.set(P,F),v.inboundVideoRtp.set(R.id,F),v.consumerStreamMap.get(P).inboundVideoRtpId.push(R.id),this.processInboundConsumerVideoStats(P,ae,F)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,F=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Oe);F.score=rf({concealmentEvents:(F.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(F.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(F.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:F.jitter||0}),H.set(P,F.score),this.audioConsumerToStatsMap.set(P,F),v.inboundAudioRtp.set(R.id,F),v.consumerStreamMap.get(P).inboundAudioRtpId.push(R.id),this.processInboundConsumerAudioStats(P,ae,F)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((R,S)=>{var P,O,ae,Oe,$,F,ye,Hr,Sn,Tn,dt;if(R.outboundVideoRtpId.length>0){const Ke=[];R.outboundVideoRtpId.forEach(ms=>{Ke.push(v.outboundVideoRtp.get(ms))});const ze=this.getWorkingSimulcastVideoStats(Ke);ze.score=ef({frameWidth:ze.frameWidth||0,framesPerSecond:ze.framesPerSecond||0,jitter:((P=ze.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(ze.packetsSent||0)-(((O=this.videoProducerToStatsMap.get(S))==null?void 0:O.packetsSent)||0),packetsLost:(((ae=ze.remoteData)==null?void 0:ae.packetsLost)||0)-((($=(Oe=this.videoProducerToStatsMap.get(S))==null?void 0:Oe.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(ze.framesEncoded||0)-(((F=this.videoProducerToStatsMap.get(S))==null?void 0:F.framesEncoded)||0)}),W.set(S,ze.score)}else if(R.outboundAudioRtpId.length>0){const Ke=v.outboundAudioRtp.get(R.outboundAudioRtpId[0]);Ke.score=Zm({packetsSent:(Ke.packetsSent||0)-(((ye=this.audioProducerToStatsMap.get(S))==null?void 0:ye.packetsSent)||0),packetsLost:(((Hr=Ke.remoteData)==null?void 0:Hr.packetsLost)||0)-(((Tn=(Sn=this.audioProducerToStatsMap.get(S))==null?void 0:Sn.remoteData)==null?void 0:Tn.packetsLost)||0),jitter:((dt=Ke.remoteData)==null?void 0:dt.jitter)||0}),W.set(S,Ke.score)}}),x.forEach(R=>{const S=A.find(O=>O.id===R.localCandidateId?(R.localCandidateId=O.id,O):null),P=D.find(O=>O.id===R.remoteCandidateId?(R.remoteCandidateId=O.id,O):null);S&&(R.localCandidateType=S.type,R.localCandidateAddress=S.address,R.localCandidatePort=S.port,R.localCandidateProtocol=S.protocol,R.localCandidateUrl=S.url,R.localCandidateNetworkType=S.networkType,R.localCandidateRelatedAddress=S.relatedAddress,R.localCandidateRelatedPort=S.relatedPort),P&&(R.remoteCandidateType=P.type,R.remoteCandidateAddress=P.address,R.remoteCandidatePort=P.port,R.remoteCandidateProtocol=P.protocol,R.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.bytesReceived=v.candidatePair.bytesReceived,v.transport.bytesSent=v.candidatePair.bytesSent,v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=x),v.transport&&!v.transport.roundTripTime){let R=0,S=0;v.remoteInboundRtp.forEach((P,O)=>{P.roundTripTime&&P.roundTripTime>R&&(R=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=R,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const s=this.producerMap.get(i),o=s.track.getSettings(),a=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),d={producerId:i,appData:s.appData,videoStats:a,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(n),d=r==null?void 0:r.inboundVideoRtpId.map(h=>{const p=this.consumerMap.get(n).track.getSettings(),f=e.inboundVideoRtp.get(h);return f.frameHeight||(f.frameHeight=p.height,f.frameWidth=p.width,f.framesPerSecond=p.frameRate),f});i={consumerId:n,peerId:s,producerId:o,appData:a,videoStats:d,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class HE extends cf{}function $a(t,e,r,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof r=="function"&&n instanceof e)r.call(null,n,t);else throw n}function zu(t,e,r){const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{$a(this,e,r,o)}):s}catch(s){$a(this,e,r,s)}return null},t}const te=(t,e)=>(r,n,i)=>{const s=i.value;return i.value=function(...o){try{const a=s.apply(this,o);return a&&a instanceof Promise?a.catch(d=>{$a(this,t,e,d)}):a}catch(a){$a(this,t,e,a)}return null},i},WE=(t,e)=>(r,n,i)=>{if(i)return zu(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);o.value instanceof Function&&Object.defineProperty(r.prototype,s,zu(o,t,e))}};var Z=globalThis&&globalThis.__decorate||function(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};const ee=console;let Q=class extends Wa{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=Zs.PROD,n,i,s,o){switch(super(),m(this,"observer"),m(this,"eventHandler"),m(this,"measurements"),m(this,"producingTransport"),m(this,"consumingTransport"),m(this,"producers",new Map),m(this,"consumers",new Map),m(this,"iceServers"),m(this,"connectionInfoPromise"),m(this,"pingStatsTimeout"),m(this,"logger"),m(this,"env"),m(this,"apiHostnames"),m(this,"peerId"),m(this,"consumerSharedMediaStatesMap",new Map),m(this,"currentUserMediaStates",{}),this.env=r,this.apiHostnames=o,this.logger=i,this.peerId=s,this.eventHandler=new IE({logger:i,peerId:s,apiHostnames:o}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new jE;break;case"Gecko":this.measurements=new cf;break;case"WebKit":this.measurements=new HE;break;default:throw Error(`Unknown engineName! ${e}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new Wa,this.measurements.observer.on("consumer_score",a=>{i.debug(`callStats::consumer_score ${[...a.entries()]}`),this.eventHandler.emit("consumer_score",a)}),this.measurements.observer.on("producer_score",a=>{i.debug(`callStats::producer_score ${[...a.entries()]}`),this.eventHandler.emit("producer_score",a)})}registerIceServers(t){this.iceServers=t}registerConsumer(t){var e;this.consumerSharedMediaStatesMap.has(t.id)||this.consumerSharedMediaStatesMap.set(t.id,{}),this.consumers.set(t.id,t),this.measurements.registerConsumer(t),this.logger.debug("callStats::registerConsumer",{consumerId:t.id,consumerkind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterConsumer.bind(this,t))}registerProducer(t){var e;this.producers.set(t.id,t),this.measurements.registerProducer(t),this.logger.debug("callStats::registerProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const r=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(r,e))}registerProducingTransport(t){var e;this.producingTransport=t,t.observer.on("close",this.disconnectProducingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectProducingTransport.bind(this,t)),Array.from(((e=t._producers)==null?void 0:e.values())||[]).forEach(r=>{this.registerProducer(r)}),t.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(t){var e;this.consumingTransport=t,t.observer.on("close",this.disconnectConsumingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,t)),Array.from(((e=t._consumers)==null?void 0:e.values())||[]).forEach(r=>{this.registerConsumer(r)}),t.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(t){this.consumers.delete(t.id)}deRegisterProducer(t){var e;this.producers.delete(t.id),this.logger.debug("callStats::deRegisterProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(t){this.eventHandler.callEvent(t)}sendPreCallTestBeginEvent(t=!1){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,t),this.eventHandler.callEvent({event:U.PRECALL_TEST_BEGIN,timestamp:new Date}),this.connectionInfoPromise&&this.connectionInfoPromise.then(e=>{this.eventHandler.callEvent({event:U.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:e},timestamp:new Date})})}sendScreenShareToggleEvent(t,e){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?U.SCREENSHARE_STARTED:U.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:new Date})}sendScreenShareRequestedEvent(){this.eventHandler.callEvent({event:U.SCREENSHARE_START_REQUESTED,timestamp:new Date})}sendActiveSpeakerEvent(t){this.eventHandler.callEvent({event:U.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:new Date})}devices(t,e){this.eventHandler.callEvent({event:t===Gt.AUDIO&&U.AUDIO_DEVICES_UPDATES||t===Gt.VIDEO&&U.VIDEO_DEVICES_UPDATES||t===Gt.SPEAKER&&U.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:new Date})}selectedDevice(t,e){this.eventHandler.callEvent({event:t===Gt.AUDIO&&U.SELECTED_MICROHPONE_UPDATE||t===Gt.VIDEO&&U.SELECTED_CAMERA_UPDATE||t===Gt.SPEAKER&&U.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:new Date})}mediaPermission(t,e){this.eventHandler.callEvent({event:U.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:new Date})}mediaPlaybackFailed(t){this.eventHandler.callEvent({event:t===Gt.AUDIO&&U.AUDIO_PLAY_FAILED||t===Gt.VIDEO&&U.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:new Date})}mediaTrackMuted(t){this.eventHandler.callEvent({event:t===Gt.AUDIO&&U.AUDIO_TRACK_MUTED||t===Gt.VIDEO&&U.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:new Date})}tabChanged(t){this.eventHandler.callEvent({event:U.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:new Date})}browserBackgrounded(){this.eventHandler.callEvent({event:U.BROWSER_BACKGROUNDED,timestamp:new Date})}browserForegrounded(){this.eventHandler.callEvent({event:U.BROWSER_FOREGROUNDED,timestamp:new Date})}legacySwitch(t){this.eventHandler.callEvent({event:U.LEGACY_SWITCH,metadata:{on:t},timestamp:new Date})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t){t=ne(V({},t),{meetingEnv:this.env}),t.deviceInfo=ne(V({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:U.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:new Date})}sendNetworkQualityTestBeginEvent(t){this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_BEGIN,timestamp:new Date}),new Promise((e,r)=>u(this,null,function*(){const n=[];try{for(const i of t)try{if(i.iceServers&&i.iceServers.length>0){const s=yield this.measurements.getNetworkQuality(i.iceServers);n.push(ne(V({},i),{networkResults:s}))}}catch(s){console.warn("Error handling ",s)}e({regionData:n})}catch(i){console.warn("Error in callstats, ",i),r(i)}})).then(e=>{this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_END,timestamp:new Date,metaData:e})})}sendWebSocketConnectedEvent(){this.eventHandler.callEvent({event:U.WEBSOCKET_CONNECTED,timestamp:new Date})}sendTransportConnectedEvent(){this.eventHandler.callEvent({event:U.TRANSPORT_CONNECTED,timestamp:new Date})}sendAudioToggleEvent(t){this.currentUserMediaStates.audio=t;let e;t?e=U.AUDIO_ON:e=U.AUDIO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendVideoToggleEvent(t){this.currentUserMediaStates.video=t;let e;t?e=U.VIDEO_ON:e=U.VIDEO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendParticipantRoleToggleEvent(t){this.eventHandler.callEvent({event:U.PARTICIPANT_ROLE,timestamp:new Date,metaData:t})}startPingStats(t=7e3){this.sendPingStatsEvent(!1),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),t)}stopPingStats(){clearInterval(this.pingStatsTimeout)}sendPingStatsEvent(t=!0){return u(this,null,function*(){let e,r;if(this.producingTransport&&(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!e||!(e!=null&&e.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const i=yield this.measurements.getProducersReport([...this.producers.values()]);e&&i?e.producerReport=i:(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!e||!(e!=null&&e.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!r||!r.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const i=yield this.measurements.getConsumersReport([...this.consumers.values()]);r&&i?r.consumerReport=i:(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!r||!r.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const n={producingTransportStats:e?e==null?void 0:e.transportReport:void 0,consumingTransportStats:r?r==null?void 0:r.transportReport:void 0,producerStats:[].concat((e==null?void 0:e.producerReport)||[]).concat((r==null?void 0:r.producerReport)||[]),consumerStats:[].concat((r==null?void 0:r.consumerReport)||[]).concat((e==null?void 0:e.consumerReport)||[])};if(t&&n.producerStats.length===0&&n.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:U.PING_STAT,metaData:n,timestamp:new Date})})}sendIVSPlayerRebufferEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_REBUFFERING,timestamp:new Date})}sendIVSPlayerAudioBlockEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_AUDIO_BLOCKED,timestamp:new Date})}sendIVSPlayerPlaybackBlockedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:new Date})}sendIVSPlayerNetworkUnavailableEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:new Date})}sendIVSPlayerInitializedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_INITIALIZED,timestamp:new Date})}sendIVSPlayerWorkerErrorEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_WORKER_ERROR,timestamp:new Date})}sendIVSPlayerErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerAnalyticsEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ANALYTICS_EVENT,timestamp:new Date,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:new Date,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_QUALITY_CHANGED,timestamp:new Date,metaData:t})}sendPlayerLiveLatency(t){this.eventHandler.callEvent({event:U.LIVESTREAM_LATENCY,timestamp:new Date,metaData:{latency:t}})}sendDisconnectEvent(){this.eventHandler.callEvent({event:U.DISCONNECT,timestamp:new Date})}sendReconnectEvent(){this.eventHandler.callEvent({event:U.RECONNECT_ATTEMPT,timestamp:new Date})}};Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerIceServers",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerConsumer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerProducer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendConsumerSharedMediaStateEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerProducingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"registerConsumingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"deRegisterConsumer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"deRegisterProducer",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"disconnectConsumingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"disconnectProducingTransport",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPreCallTestBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendScreenShareToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendScreenShareRequestedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendActiveSpeakerEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"devices",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"selectedDevice",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaPermission",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaPlaybackFailed",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"mediaTrackMuted",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"tabChanged",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"browserBackgrounded",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"browserForegrounded",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"legacySwitch",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"getPreCallTestResults",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendCallJoinBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendNetworkQualityTestBeginEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendWebSocketConnectedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendTransportConnectedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendAudioToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendVideoToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendParticipantRoleToggleEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"startPingStats",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"stopPingStats",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPingStatsEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerRebufferEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerAudioBlockEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerInitializedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerWorkerErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerRecoverableErrorEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerAnalyticsEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendIVSPlayerQualityChanged",null);Z([te(TypeError,(t,e)=>ee.error(e,t))],Q.prototype,"sendPlayerLiveLatency",null);Q=Z([WE(TypeError,(t,e)=>ee.error(e,t))],Q);const $E=Q;class GE extends It{constructor(){super(...arguments),m(this,"stats"),m(this,"roomURL"),m(this,"peerId"),m(this,"backend"),m(this,"iceServers"),m(this,"initialized",!1),m(this,"stalled",!1),m(this,"ipInformation"),m(this,"logger")}initialize(e){return u(this,arguments,function*({peerId:r,engineName:n,env:i=Zs.PROD,iceServers:s,apiBase:o="https://api.cluster.dyte.in",flags:a,logger:d=console,apiHostnames:h,skipConnectivityChecks:p=!1}){var f,g,E;try{this.peerId=r,this.logger=d,this.ipInformation=yield jl.getIPDetails({peerId:r,apiHostnames:h}),this.backend=new $E(o,n,i,a,d,r,h),this.iceServers=s,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(g=this.backend)==null?void 0:g.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(v){this.logger.error("callStats::CallStatsIntegration: ",{error:v}),this.stallCallStats()}})}setRoomName(e){this.roomURL=e}configureSendTransport(e){var r;(r=this.backend)==null||r.registerProducingTransport(e)}configureRecvTransport(e){var r;(r=this.backend)==null||r.registerConsumingTransport(e)}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){var r;try{(r=this.backend)==null||r.sendNetworkQualityTestBeginEvent(e)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}roomJoined(e){return u(this,null,function*(){var r,n;(r=this.backend)==null||r.sendCallJoinBeginEvent(e),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!1)}audioOn(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!0)}videoOff(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!1)}videoOn(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!0)}callEnded(){var e,r;(e=this.backend)==null||e.stopPingStats(),(r=this.backend)==null||r.sendDisconnectEvent()}screenShareStart(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!0,e)}consumerSharedMediaState(e,r){var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)}screenShareStop(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!1,e)}screenShareRequested(){var e;(e=this.backend)==null||e.sendScreenShareRequestedEvent()}activeSpeaker(e){var r;e===this.peerId&&((r=this.backend)==null||r.sendActiveSpeakerEvent(e))}devices(e,r){var n;(n=this.backend)==null||n.devices(e,r)}selectedDevice(e,r){var n;(n=this.backend)==null||n.selectedDevice(e,r)}mediaPermission(e,r){var n;(n=this.backend)==null||n.mediaPermission(e,r)}mediaPlaybackFailed(e){var r;(r=this.backend)==null||r.mediaPlaybackFailed(e)}mediaTrackMuted(e){var r;(r=this.backend)==null||r.mediaTrackMuted(e)}tabChanged(e=!1){var r;(r=this.backend)==null||r.tabChanged(e)}browserBackgrounded(){var e;(e=this.backend)==null||e.browserBackgrounded()}browserForegrounded(){var e;(e=this.backend)==null||e.browserForegrounded()}legacySwitch(e){var r;(r=this.backend)==null||r.legacySwitch(e)}startPreCallTest(e=!1){return u(this,null,function*(){var r;(r=this.backend)==null||r.sendPreCallTestBeginEvent(e)})}onPreCallTestResults(e){var r;return(r=this.backend)==null||r.eventHandler.once("precall_end",e),e}onReceivingConsumerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)}onReceivingConsumerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)}onReceivingProducerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)}onReceivingProducerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)}onReceivingProducingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)}onReceivingConsumingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)}onProducerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)}onConsumerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){var n,i,s,o,a,d,h,p,f,g,E;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent();break;case"PlayerAudioBlocked":(i=this.backend)==null||i.sendIVSPlayerAudioBlockEvent();break;case"PlayerPlaybackBlocked":(s=this.backend)==null||s.sendIVSPlayerPlaybackBlockedEvent();break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent();break;case"PlayerInitialized":(a=this.backend)==null||a.sendIVSPlayerInitializedEvent();break;case"PlayerWorkerError":(d=this.backend)==null||d.sendIVSPlayerWorkerErrorEvent();break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r);break;case"PlayerRecoverableError":(p=this.backend)==null||p.sendIVSPlayerRecoverableErrorEvent(r);break;case"PlayerAnalyticsEvent":(f=this.backend)==null||f.sendIVSPlayerAnalyticsEvent(r);break;case"PlayerPlaybackRateChanged":(g=this.backend)==null||g.sendIVSPlayerPlaybackRateChangedEvent(r);break;case"PlayerQualityChanged":(E=this.backend)==null||E.sendIVSPlayerQualityChanged(r);break}}livestreamLatency(e){var r;(r=this.backend)==null||r.sendPlayerLiveLatency(e)}}const B=new GE;B.setMaxListeners(30);function JE(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}Array.prototype.at||Object.assign(Array.prototype,{at:JE});function qE(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}String.prototype.at||Object.assign(String.prototype,{at:qE});var qe;(function(t){t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT"})(qe||(qe={}));var Ga;(function(t){t.Skip="SKIP",t.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",t.SkipOnAccept="SKIP_ON_ACCEPT"})(Ga||(Ga={}));var q;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST"})(q||(q={}));var Ja;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED"})(Ja||(Ja={}));var Yu;(function(t){t.FULL_ACCESS="FULL_ACCESS",t.VIEW_ONLY="VIEW_ONLY"})(Yu||(Yu={}));var qa;(function(t){t.skip="SKIP",t.onAccept="ON_ACCEPT",t.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",t.skipOnAccept="SKIP_ON_ACCEPT"})(qa||(qa={}));var Zi;(function(t){t.none="NONE",t.recorder="RECORDER",t.livestreamer="LIVESTREAMER"})(Zi||(Zi={}));var Gd;(function(t){t.groupCall="GROUP_CALL",t.webinar="WEBINAR",t.audioRoom="AUDIO_ROOM",t.livestream="LIVESTREAM",t.chat="CHAT"})(Gd||(Gd={}));var Qu;(function(t){t.SKIP="skip",t.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",t.ON_ACCEPT="skipOnAccept",t.SKIP_ON_ACCEPT="skipOnAccept"})(Qu||(Qu={}));Gd.groupCall,qa.skipOnAccept,Zi.none;var Jd={},KE={get exports(){return Jd},set exports(t){Jd=t}},Ka={},zE={get exports(){return Ka},set exports(t){Ka=t}},df=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},YE=df,gn=Object.prototype.toString;function Hl(t){return Array.isArray(t)}function qd(t){return typeof t=="undefined"}function QE(t){return t!==null&&!qd(t)&&t.constructor!==null&&!qd(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function lf(t){return gn.call(t)==="[object ArrayBuffer]"}function XE(t){return gn.call(t)==="[object FormData]"}function ZE(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&lf(t.buffer),e}function eS(t){return typeof t=="string"}function tS(t){return typeof t=="number"}function uf(t){return t!==null&&typeof t=="object"}function da(t){if(gn.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function rS(t){return gn.call(t)==="[object Date]"}function nS(t){return gn.call(t)==="[object File]"}function iS(t){return gn.call(t)==="[object Blob]"}function hf(t){return gn.call(t)==="[object Function]"}function sS(t){return uf(t)&&hf(t.pipe)}function oS(t){return gn.call(t)==="[object URLSearchParams]"}function aS(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function cS(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Wl(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Hl(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function Kd(){var t={};function e(i,s){da(t[s])&&da(i)?t[s]=Kd(t[s],i):da(i)?t[s]=Kd({},i):Hl(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)Wl(arguments[r],e);return t}function dS(t,e,r){return Wl(e,function(n,i){r&&typeof n=="function"?t[i]=YE(n,r):t[i]=n}),t}function lS(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var Rt={isArray:Hl,isArrayBuffer:lf,isBuffer:QE,isFormData:XE,isArrayBufferView:ZE,isString:eS,isNumber:tS,isObject:uf,isPlainObject:da,isUndefined:qd,isDate:rS,isFile:nS,isBlob:iS,isFunction:hf,isStream:sS,isURLSearchParams:oS,isStandardBrowserEnv:cS,forEach:Wl,merge:Kd,extend:dS,trim:aS,stripBOM:lS},Si=Rt;function Xu(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var pf=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(Si.isURLSearchParams(e))n=e.toString();else{var i=[];Si.forEach(e,function(o,a){o===null||typeof o=="undefined"||(Si.isArray(o)?a=a+"[]":o=[o],Si.forEach(o,function(d){Si.isDate(d)?d=d.toISOString():Si.isObject(d)&&(d=JSON.stringify(d)),i.push(Xu(a)+"="+Xu(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},uS=Rt;function bc(){this.handlers=[]}bc.prototype.use=function(t,e,r){return this.handlers.push({fulfilled:t,rejected:e,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1};bc.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)};bc.prototype.forEach=function(t){uS.forEach(this.handlers,function(e){e!==null&&t(e)})};var hS=bc,pS=Rt,mS=function(t,e){pS.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},mf=function(t,e,r,n,i){return t.config=e,r&&(t.code=r),t.request=n,t.response=i,t.isAxiosError=!0,t.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}},t},ed,Zu;function ff(){if(Zu)return ed;Zu=1;var t=mf;return ed=function(e,r,n,i,s){var o=new Error(e);return t(o,r,n,i,s)},ed}var td,eh;function fS(){if(eh)return td;eh=1;var t=ff();return td=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(t("Request failed with status code "+n.status,n.config,null,n.request,n))},td}var rd,th;function gS(){if(th)return rd;th=1;var t=Rt;return rd=t.isStandardBrowserEnv()?function(){return{write:function(e,r,n,i,s,o){var a=[];a.push(e+"="+encodeURIComponent(r)),t.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),t.isString(i)&&a.push("path="+i),t.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var r=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),rd}var rh,nh;function vS(){return nh||(nh=1,rh=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),rh}var ih,sh;function yS(){return sh||(sh=1,ih=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),ih}var nd,oh;function ES(){if(oh)return nd;oh=1;var t=vS(),e=yS();return nd=function(r,n){return r&&!t(n)?e(r,n):n},nd}var id,ah;function SS(){if(ah)return id;ah=1;var t=Rt,e=["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"];return id=function(r){var n={},i,s,o;return r&&t.forEach(r.split(`
24
- `),function(a){if(o=a.indexOf(":"),i=t.trim(a.substr(0,o)).toLowerCase(),s=t.trim(a.substr(o+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([s]):n[i]=n[i]?n[i]+", "+s:s}}),n},id}var sd,ch;function TS(){if(ch)return sd;ch=1;var t=Rt;return sd=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{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 n=i(window.location.href),function(s){var o=t.isString(s)?i(s):s;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),sd}var od,dh;function wc(){if(dh)return od;dh=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,od=t,od}var ad,lh;function _S(){if(lh)return ad;lh=1;var t=Rt,e=fS(),r=gS(),n=pf,i=ES(),s=SS(),o=TS(),a=ff(),d=Cc(),h=wc();return ad=function(p){return new Promise(function(f,g){var E=p.data,v=p.headers,I=p.responseType,A;function D(){p.cancelToken&&p.cancelToken.unsubscribe(A),p.signal&&p.signal.removeEventListener("abort",A)}t.isFormData(E)&&delete v["Content-Type"];var x=new XMLHttpRequest;if(p.auth){var W=p.auth.username||"",H=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";v.Authorization="Basic "+btoa(W+":"+H)}var R=i(p.baseURL,p.url);x.open(p.method.toUpperCase(),n(R,p.params,p.paramsSerializer),!0),x.timeout=p.timeout;function S(){if(x){var O="getAllResponseHeaders"in x?s(x.getAllResponseHeaders()):null,ae=!I||I==="text"||I==="json"?x.responseText:x.response,Oe={data:ae,status:x.status,statusText:x.statusText,headers:O,config:p,request:x};e(function($){f($),D()},function($){g($),D()},Oe),x=null}}if("onloadend"in x?x.onloadend=S:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(S)},x.onabort=function(){x&&(g(a("Request aborted",p,"ECONNABORTED",x)),x=null)},x.onerror=function(){g(a("Network Error",p,null,x)),x=null},x.ontimeout=function(){var O=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",ae=p.transitional||d.transitional;p.timeoutErrorMessage&&(O=p.timeoutErrorMessage),g(a(O,p,ae.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",x)),x=null},t.isStandardBrowserEnv()){var P=(p.withCredentials||o(R))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;P&&(v[p.xsrfHeaderName]=P)}"setRequestHeader"in x&&t.forEach(v,function(O,ae){typeof E=="undefined"&&ae.toLowerCase()==="content-type"?delete v[ae]:x.setRequestHeader(ae,O)}),t.isUndefined(p.withCredentials)||(x.withCredentials=!!p.withCredentials),I&&I!=="json"&&(x.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&x.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&x.upload&&x.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(A=function(O){x&&(g(!O||O&&O.type?new h("canceled"):O),x.abort(),x=null)},p.cancelToken&&p.cancelToken.subscribe(A),p.signal&&(p.signal.aborted?A():p.signal.addEventListener("abort",A))),E||(E=null),x.send(E)})},ad}var cd,uh;function Cc(){if(uh)return cd;uh=1;var t=Rt,e=mS,r=mf,n={"Content-Type":"application/x-www-form-urlencoded"};function i(d,h){!t.isUndefined(d)&&t.isUndefined(d["Content-Type"])&&(d["Content-Type"]=h)}function s(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=_S()),d}function o(d,h,p){if(t.isString(d))try{return(h||JSON.parse)(d),t.trim(d)}catch(f){if(f.name!=="SyntaxError")throw f}return(p||JSON.stringify)(d)}var a={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:s(),transformRequest:[function(d,h){return e(h,"Accept"),e(h,"Content-Type"),t.isFormData(d)||t.isArrayBuffer(d)||t.isBuffer(d)||t.isStream(d)||t.isFile(d)||t.isBlob(d)?d:t.isArrayBufferView(d)?d.buffer:t.isURLSearchParams(d)?(i(h,"application/x-www-form-urlencoded;charset=utf-8"),d.toString()):t.isObject(d)||h&&h["Content-Type"]==="application/json"?(i(h,"application/json"),o(d)):d}],transformResponse:[function(d){var h=this.transitional||a.transitional,p=h&&h.silentJSONParsing,f=h&&h.forcedJSONParsing,g=!p&&this.responseType==="json";if(g||f&&t.isString(d)&&d.length)try{return JSON.parse(d)}catch(E){if(g)throw E.name==="SyntaxError"?r(E,this,"E_JSON_PARSE"):E}return d}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(d){return d>=200&&d<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return t.forEach(["delete","get","head"],function(d){a.headers[d]={}}),t.forEach(["post","put","patch"],function(d){a.headers[d]=t.merge(n)}),cd=a,cd}var kS=Rt,bS=Cc(),wS=function(t,e,r){var n=this||bS;return kS.forEach(r,function(i){t=i.call(n,t,e)}),t},hh,ph;function gf(){return ph||(ph=1,hh=function(t){return!!(t&&t.__CANCEL__)}),hh}var mh=Rt,dd=wS,CS=gf(),IS=Cc(),RS=wc();function ld(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new RS("canceled")}var PS=function(t){ld(t),t.headers=t.headers||{},t.data=dd.call(t,t.data,t.headers,t.transformRequest),t.headers=mh.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),mh.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||IS.adapter;return e(t).then(function(r){return ld(t),r.data=dd.call(t,r.data,r.headers,t.transformResponse),r},function(r){return CS(r)||(ld(t),r&&r.response&&(r.response.data=dd.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},Dt=Rt,vf=function(t,e){e=e||{};var r={};function n(h,p){return Dt.isPlainObject(h)&&Dt.isPlainObject(p)?Dt.merge(h,p):Dt.isPlainObject(p)?Dt.merge({},p):Dt.isArray(p)?p.slice():p}function i(h){if(Dt.isUndefined(e[h])){if(!Dt.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function s(h){if(!Dt.isUndefined(e[h]))return n(void 0,e[h])}function o(h){if(Dt.isUndefined(e[h])){if(!Dt.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function a(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var d={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return Dt.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var p=d[h]||i,f=p(h);Dt.isUndefined(f)&&p!==a||(r[h]=f)}),r},fh,gh;function yf(){return gh||(gh=1,fh={version:"0.25.0"}),fh}var AS=yf().version,$l={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){$l[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var vh={};$l.transitional=function(t,e,r){function n(i,s){return"[Axios v"+AS+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return function(i,s,o){if(t===!1)throw new Error(n(s," has been removed"+(e?" in "+e:"")));return e&&!vh[s]&&(vh[s]=!0,console.warn(n(s," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,s,o):!0}};function MS(t,e,r){if(typeof t!="object")throw new TypeError("options must be an object");for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],o=e[s];if(o){var a=t[s],d=a===void 0||o(a,s,t);if(d!==!0)throw new TypeError("option "+s+" must be "+d);continue}if(r!==!0)throw Error("Unknown option "+s)}}var DS={assertOptions:MS,validators:$l},Ef=Rt,OS=pf,yh=hS,Eh=PS,Ic=vf,Sf=DS,Ti=Sf.validators;function ho(t){this.defaults=t,this.interceptors={request:new yh,response:new yh}}ho.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=Ic(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&Sf.assertOptions(r,{silentJSONParsing:Ti.transitional(Ti.boolean),forcedJSONParsing:Ti.transitional(Ti.boolean),clarifyTimeoutError:Ti.transitional(Ti.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(e)===!1||(i=i&&f.synchronous,n.unshift(f.fulfilled,f.rejected))});var s=[];this.interceptors.response.forEach(function(f){s.push(f.fulfilled,f.rejected)});var o;if(!i){var a=[Eh,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(s),o=Promise.resolve(e);a.length;)o=o.then(a.shift(),a.shift());return o}for(var d=e;n.length;){var h=n.shift(),p=n.shift();try{d=h(d)}catch(f){p(f);break}}try{o=Eh(d)}catch(f){return Promise.reject(f)}for(;s.length;)o=o.then(s.shift(),s.shift());return o};ho.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=Ic(this.defaults,t),OS(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")};Ef.forEach(["delete","get","head","options"],function(t){ho.prototype[t]=function(e,r){return this.request(Ic(r||{},{method:t,url:e,data:(r||{}).data}))}});Ef.forEach(["post","put","patch"],function(t){ho.prototype[t]=function(e,r,n){return this.request(Ic(n||{},{method:t,url:e,data:r}))}});var NS=ho,ud,Sh;function LS(){if(Sh)return ud;Sh=1;var t=wc();function e(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(s){n=s});var i=this;this.promise.then(function(s){if(i._listeners){var o,a=i._listeners.length;for(o=0;o<a;o++)i._listeners[o](s);i._listeners=null}}),this.promise.then=function(s){var o,a=new Promise(function(d){i.subscribe(d),o=d}).then(s);return a.cancel=function(){i.unsubscribe(o)},a},r(function(s){i.reason||(i.reason=new t(s),n(i.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(r){if(this.reason){r(this.reason);return}this._listeners?this._listeners.push(r):this._listeners=[r]},e.prototype.unsubscribe=function(r){if(this._listeners){var n=this._listeners.indexOf(r);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var r,n=new e(function(i){r=i});return{token:n,cancel:r}},ud=e,ud}var Th,_h;function xS(){return _h||(_h=1,Th=function(t){return function(e){return t.apply(null,e)}}),Th}var hd,kh;function FS(){if(kh)return hd;kh=1;var t=Rt;return hd=function(e){return t.isObject(e)&&e.isAxiosError===!0},hd}var bh=Rt,US=df,la=NS,VS=vf,BS=Cc();function Tf(t){var e=new la(t),r=US(la.prototype.request,e);return bh.extend(r,la.prototype,e),bh.extend(r,e),r.create=function(n){return Tf(VS(t,n))},r}var vr=Tf(BS);vr.Axios=la;vr.Cancel=wc();vr.CancelToken=LS();vr.isCancel=gf();vr.VERSION=yf().version;vr.all=function(t){return Promise.all(t)};vr.spread=xS();vr.isAxiosError=FS();zE.exports=vr;Ka.default=vr;(function(t){t.exports=Ka})(KE);const za=uE(Jd);let _f="hXgU8Wc8pwuGNq9ms5q9Hh";var wh;typeof process!="undefined"&&(wh=process==null?void 0:process.env)!=null&&wh.FLAGSMITH_ENVIRONMENT_KEY&&(_f={}.FLAGSMITH_ENVIRONMENT_KEY);function jS(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}class HS{constructor(e=_f){m(this,"flags",{}),m(this,"environmentKey",null),this.environmentKey=e,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}identify(e){return u(this,arguments,function*(r,n={},i=!1,s=5e3,o="edge.api.flagsmith.com"){const a=JSON.parse(JSON.stringify(n)),d=Object.entries(a).map(h=>({trait_key:h[0],trait_value:h[1]}));try{const h="_"+(Math.random()+1).toString(36).substring(2),p=yield za.post(`https://${o}/api/v1/identities/`,{identifier:r+(i?h:""),traits:d},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:s});this.flags=jS(p.data.flags||[])}catch{}return this.flags})}getValue(e){return this.flags&&this.flags[e]&&this.flags[e].value}hasFeature(e){return this.flags&&this.flags[e]&&this.flags[e].enabled}getAllFlags(){return this.flags}}const K=new HS,kf=[-2,-1,0,1,2],WS=[0,1,2,3,4];function $S(t){t=t.trim();let e="0",r="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],r="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],r="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+r,+n]}const GS=(t,e,r)=>{let n,i,s;if(e==0)n=i=s=r;else{const o=(h,p,f)=>(f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?h+(p-h)*6*f:f<.5?p:f<.6666666666666666?h+(p-h)*(.6666666666666666-f)*6:h),a=r<.5?r*(1+e):r+e-r*e,d=2*r-a;n=o(d,a,t+1/3),i=o(d,a,t),s=o(d,a,t-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(s*255)]},JS=(t,e,r)=>{t/=255,e/=255,r/=255;const n=Math.max(t,e,r),i=Math.min(t,e,r);let s,o;const a=(n+i)/2;if(n==i)s=o=0;else{const d=n-i;switch(o=a>.5?d/(2-n-i):d/(n+i),n){case t:s=(e-r)/d+(e<r?6:0);break;case e:s=(r-t)/d+2;break;case r:s=(t-e)/d+4;break}s/=6}return[s,o,a]},qS=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},bf=(t,e=kf,r=.4)=>{const n=[],[i,s,o]=$S(t),[a,d,h]=JS(i,s,o),p=Math.round(h*100);p>70?r=.8:p>60?r=.9:p<10?r=.075:p<42&&(r=.3);const f=e.findIndex(A=>A===0);if(f===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-f,E=f+1,v=(100-p)/g,I=p/E;for(const A of e){let D;A<0?D=p+A*I*r:A>0?D=p+A*v*r:D=p;const[x,W,H]=GS(a,d,D/100);n.push(qS(x,W,H))}return n},Ch={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},KS=t=>{const[e,r,n,i,s]=bf(t,kf);return{300:e,400:r,500:n,600:i,700:s}},zS=t=>{if(t==="#FFFFFF")return Ch.light.background;if(t==="#000000")return Ch.dark.background;const[e,r,n,i,s]=bf(t,WS);return{1e3:e,900:r,800:n,700:i,600:s}};function YS(){this.__data__=[],this.size=0}function Rc(t,e){return t===e||t!==t&&e!==e}function Pc(t,e){for(var r=t.length;r--;)if(Rc(t[r][0],e))return r;return-1}var QS=Array.prototype,XS=QS.splice;function ZS(t){var e=this.__data__,r=Pc(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():XS.call(e,r,1),--this.size,!0}function eT(t){var e=this.__data__,r=Pc(e,t);return r<0?void 0:e[r][1]}function tT(t){return Pc(this.__data__,t)>-1}function rT(t,e){var r=this.__data__,n=Pc(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function Br(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Br.prototype.clear=YS;Br.prototype.delete=ZS;Br.prototype.get=eT;Br.prototype.has=tT;Br.prototype.set=rT;function nT(){this.__data__=new Br,this.size=0}function iT(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function sT(t){return this.__data__.get(t)}function oT(t){return this.__data__.has(t)}var aT=typeof global=="object"&&global&&global.Object===Object&&global;const wf=aT;var cT=typeof self=="object"&&self&&self.Object===Object&&self,dT=wf||cT||Function("return this")();const ir=dT;var lT=ir.Symbol;const es=lT;var Cf=Object.prototype,uT=Cf.hasOwnProperty,hT=Cf.toString,gs=es?es.toStringTag:void 0;function pT(t){var e=uT.call(t,gs),r=t[gs];try{t[gs]=void 0;var n=!0}catch{}var i=hT.call(t);return n&&(e?t[gs]=r:delete t[gs]),i}var mT=Object.prototype,fT=mT.toString;function gT(t){return fT.call(t)}var vT="[object Null]",yT="[object Undefined]",Ih=es?es.toStringTag:void 0;function ui(t){return t==null?t===void 0?yT:vT:Ih&&Ih in Object(t)?pT(t):gT(t)}function nr(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ET="[object AsyncFunction]",ST="[object Function]",TT="[object GeneratorFunction]",_T="[object Proxy]";function Gl(t){if(!nr(t))return!1;var e=ui(t);return e==ST||e==TT||e==ET||e==_T}var kT=ir["__core-js_shared__"];const pd=kT;var Rh=function(){var t=/[^.]+$/.exec(pd&&pd.keys&&pd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function bT(t){return!!Rh&&Rh in t}var wT=Function.prototype,CT=wT.toString;function hi(t){if(t!=null){try{return CT.call(t)}catch{}try{return t+""}catch{}}return""}var IT=/[\\^$.*+?()[\]{}|]/g,RT=/^\[object .+?Constructor\]$/,PT=Function.prototype,AT=Object.prototype,MT=PT.toString,DT=AT.hasOwnProperty,OT=RegExp("^"+MT.call(DT).replace(IT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function NT(t){if(!nr(t)||bT(t))return!1;var e=Gl(t)?OT:RT;return e.test(hi(t))}function LT(t,e){return t==null?void 0:t[e]}function pi(t,e){var r=LT(t,e);return NT(r)?r:void 0}var xT=pi(ir,"Map");const so=xT;var FT=pi(Object,"create");const oo=FT;function UT(){this.__data__=oo?oo(null):{},this.size=0}function VT(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var BT="__lodash_hash_undefined__",jT=Object.prototype,HT=jT.hasOwnProperty;function WT(t){var e=this.__data__;if(oo){var r=e[t];return r===BT?void 0:r}return HT.call(e,t)?e[t]:void 0}var $T=Object.prototype,GT=$T.hasOwnProperty;function JT(t){var e=this.__data__;return oo?e[t]!==void 0:GT.call(e,t)}var qT="__lodash_hash_undefined__";function KT(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=oo&&e===void 0?qT:e,this}function ii(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}ii.prototype.clear=UT;ii.prototype.delete=VT;ii.prototype.get=WT;ii.prototype.has=JT;ii.prototype.set=KT;function zT(){this.size=0,this.__data__={hash:new ii,map:new(so||Br),string:new ii}}function YT(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function Ac(t,e){var r=t.__data__;return YT(e)?r[typeof e=="string"?"string":"hash"]:r.map}function QT(t){var e=Ac(this,t).delete(t);return this.size-=e?1:0,e}function XT(t){return Ac(this,t).get(t)}function ZT(t){return Ac(this,t).has(t)}function e_(t,e){var r=Ac(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function cs(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}cs.prototype.clear=zT;cs.prototype.delete=QT;cs.prototype.get=XT;cs.prototype.has=ZT;cs.prototype.set=e_;var t_=200;function r_(t,e){var r=this.__data__;if(r instanceof Br){var n=r.__data__;if(!so||n.length<t_-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new cs(n)}return r.set(t,e),this.size=r.size,this}function mi(t){var e=this.__data__=new Br(t);this.size=e.size}mi.prototype.clear=nT;mi.prototype.delete=iT;mi.prototype.get=sT;mi.prototype.has=oT;mi.prototype.set=r_;function n_(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var i_=function(){try{var t=pi(Object,"defineProperty");return t({},"",{}),t}catch{}}();const Ya=i_;function Jl(t,e,r){e=="__proto__"&&Ya?Ya(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var s_=Object.prototype,o_=s_.hasOwnProperty;function If(t,e,r){var n=t[e];(!(o_.call(t,e)&&Rc(n,r))||r===void 0&&!(e in t))&&Jl(t,e,r)}function po(t,e,r,n){var i=!r;r||(r={});for(var s=-1,o=e.length;++s<o;){var a=e[s],d=n?n(r[a],t[a],a,r,t):void 0;d===void 0&&(d=t[a]),i?Jl(r,a,d):If(r,a,d)}return r}function a_(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function vn(t){return t!=null&&typeof t=="object"}var c_="[object Arguments]";function Ph(t){return vn(t)&&ui(t)==c_}var Rf=Object.prototype,d_=Rf.hasOwnProperty,l_=Rf.propertyIsEnumerable,u_=Ph(function(){return arguments}())?Ph:function(t){return vn(t)&&d_.call(t,"callee")&&!l_.call(t,"callee")};const Qa=u_;var h_=Array.isArray;const ts=h_;function p_(){return!1}var Pf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ah=Pf&&typeof module=="object"&&module&&!module.nodeType&&module,m_=Ah&&Ah.exports===Pf,Mh=m_?ir.Buffer:void 0,f_=Mh?Mh.isBuffer:void 0,g_=f_||p_;const Mc=g_;var v_=9007199254740991,y_=/^(?:0|[1-9]\d*)$/;function Af(t,e){var r=typeof t;return e=e==null?v_:e,!!e&&(r=="number"||r!="symbol"&&y_.test(t))&&t>-1&&t%1==0&&t<e}var E_=9007199254740991;function Mf(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=E_}var S_="[object Arguments]",T_="[object Array]",__="[object Boolean]",k_="[object Date]",b_="[object Error]",w_="[object Function]",C_="[object Map]",I_="[object Number]",R_="[object Object]",P_="[object RegExp]",A_="[object Set]",M_="[object String]",D_="[object WeakMap]",O_="[object ArrayBuffer]",N_="[object DataView]",L_="[object Float32Array]",x_="[object Float64Array]",F_="[object Int8Array]",U_="[object Int16Array]",V_="[object Int32Array]",B_="[object Uint8Array]",j_="[object Uint8ClampedArray]",H_="[object Uint16Array]",W_="[object Uint32Array]",Ae={};Ae[L_]=Ae[x_]=Ae[F_]=Ae[U_]=Ae[V_]=Ae[B_]=Ae[j_]=Ae[H_]=Ae[W_]=!0;Ae[S_]=Ae[T_]=Ae[O_]=Ae[__]=Ae[N_]=Ae[k_]=Ae[b_]=Ae[w_]=Ae[C_]=Ae[I_]=Ae[R_]=Ae[P_]=Ae[A_]=Ae[M_]=Ae[D_]=!1;function $_(t){return vn(t)&&Mf(t.length)&&!!Ae[ui(t)]}function ql(t){return function(e){return t(e)}}var Df=typeof exports=="object"&&exports&&!exports.nodeType&&exports,eo=Df&&typeof module=="object"&&module&&!module.nodeType&&module,G_=eo&&eo.exports===Df,md=G_&&wf.process,J_=function(){try{var t=eo&&eo.require&&eo.require("util").types;return t||md&&md.binding&&md.binding("util")}catch{}}();const rs=J_;var Dh=rs&&rs.isTypedArray,q_=Dh?ql(Dh):$_;const Kl=q_;var K_=Object.prototype,z_=K_.hasOwnProperty;function Of(t,e){var r=ts(t),n=!r&&Qa(t),i=!r&&!n&&Mc(t),s=!r&&!n&&!i&&Kl(t),o=r||n||i||s,a=o?a_(t.length,String):[],d=a.length;for(var h in t)(e||z_.call(t,h))&&!(o&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Af(h,d)))&&a.push(h);return a}var Y_=Object.prototype;function Dc(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||Y_;return t===r}function Nf(t,e){return function(r){return t(e(r))}}var Q_=Nf(Object.keys,Object);const X_=Q_;var Z_=Object.prototype,ek=Z_.hasOwnProperty;function Lf(t){if(!Dc(t))return X_(t);var e=[];for(var r in Object(t))ek.call(t,r)&&r!="constructor"&&e.push(r);return e}function mo(t){return t!=null&&Mf(t.length)&&!Gl(t)}function zl(t){return mo(t)?Of(t):Lf(t)}function tk(t,e){return t&&po(e,zl(e),t)}function rk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var nk=Object.prototype,ik=nk.hasOwnProperty;function sk(t){if(!nr(t))return rk(t);var e=Dc(t),r=[];for(var n in t)n=="constructor"&&(e||!ik.call(t,n))||r.push(n);return r}function fo(t){return mo(t)?Of(t,!0):sk(t)}function ok(t,e){return t&&po(e,fo(e),t)}var xf=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Oh=xf&&typeof module=="object"&&module&&!module.nodeType&&module,ak=Oh&&Oh.exports===xf,Nh=ak?ir.Buffer:void 0,Lh=Nh?Nh.allocUnsafe:void 0;function Ff(t,e){if(e)return t.slice();var r=t.length,n=Lh?Lh(r):new t.constructor(r);return t.copy(n),n}function Uf(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function ck(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r<n;){var o=t[r];e(o,r,t)&&(s[i++]=o)}return s}function Vf(){return[]}var dk=Object.prototype,lk=dk.propertyIsEnumerable,xh=Object.getOwnPropertySymbols,uk=xh?function(t){return t==null?[]:(t=Object(t),ck(xh(t),function(e){return lk.call(t,e)}))}:Vf;const Yl=uk;function hk(t,e){return po(t,Yl(t),e)}function Bf(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var pk=Nf(Object.getPrototypeOf,Object);const Ql=pk;var mk=Object.getOwnPropertySymbols,fk=mk?function(t){for(var e=[];t;)Bf(e,Yl(t)),t=Ql(t);return e}:Vf;const jf=fk;function gk(t,e){return po(t,jf(t),e)}function Hf(t,e,r){var n=e(t);return ts(t)?n:Bf(n,r(t))}function vk(t){return Hf(t,zl,Yl)}function yk(t){return Hf(t,fo,jf)}var Ek=pi(ir,"DataView");const zd=Ek;var Sk=pi(ir,"Promise");const Yd=Sk;var Tk=pi(ir,"Set");const Qd=Tk;var _k=pi(ir,"WeakMap");const Xd=_k;var Fh="[object Map]",kk="[object Object]",Uh="[object Promise]",Vh="[object Set]",Bh="[object WeakMap]",jh="[object DataView]",bk=hi(zd),wk=hi(so),Ck=hi(Yd),Ik=hi(Qd),Rk=hi(Xd),Un=ui;(zd&&Un(new zd(new ArrayBuffer(1)))!=jh||so&&Un(new so)!=Fh||Yd&&Un(Yd.resolve())!=Uh||Qd&&Un(new Qd)!=Vh||Xd&&Un(new Xd)!=Bh)&&(Un=function(t){var e=ui(t),r=e==kk?t.constructor:void 0,n=r?hi(r):"";if(n)switch(n){case bk:return jh;case wk:return Fh;case Ck:return Uh;case Ik:return Vh;case Rk:return Bh}return e});const Oc=Un;var Pk=Object.prototype,Ak=Pk.hasOwnProperty;function Mk(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&Ak.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var Dk=ir.Uint8Array;const Hh=Dk;function Xl(t){var e=new t.constructor(t.byteLength);return new Hh(e).set(new Hh(t)),e}function Ok(t,e){var r=e?Xl(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var Nk=/\w*$/;function Lk(t){var e=new t.constructor(t.source,Nk.exec(t));return e.lastIndex=t.lastIndex,e}var Wh=es?es.prototype:void 0,$h=Wh?Wh.valueOf:void 0;function xk(t){return $h?Object($h.call(t)):{}}function Wf(t,e){var r=e?Xl(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var Fk="[object Boolean]",Uk="[object Date]",Vk="[object Map]",Bk="[object Number]",jk="[object RegExp]",Hk="[object Set]",Wk="[object String]",$k="[object Symbol]",Gk="[object ArrayBuffer]",Jk="[object DataView]",qk="[object Float32Array]",Kk="[object Float64Array]",zk="[object Int8Array]",Yk="[object Int16Array]",Qk="[object Int32Array]",Xk="[object Uint8Array]",Zk="[object Uint8ClampedArray]",eb="[object Uint16Array]",tb="[object Uint32Array]";function rb(t,e,r){var n=t.constructor;switch(e){case Gk:return Xl(t);case Fk:case Uk:return new n(+t);case Jk:return Ok(t,r);case qk:case Kk:case zk:case Yk:case Qk:case Xk:case Zk:case eb:case tb:return Wf(t,r);case Vk:return new n;case Bk:case Wk:return new n(t);case jk:return Lk(t);case Hk:return new n;case $k:return xk(t)}}var Gh=Object.create,nb=function(){function t(){}return function(e){if(!nr(e))return{};if(Gh)return Gh(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const ib=nb;function $f(t){return typeof t.constructor=="function"&&!Dc(t)?ib(Ql(t)):{}}var sb="[object Map]";function ob(t){return vn(t)&&Oc(t)==sb}var Jh=rs&&rs.isMap,ab=Jh?ql(Jh):ob;const cb=ab;var db="[object Set]";function lb(t){return vn(t)&&Oc(t)==db}var qh=rs&&rs.isSet,ub=qh?ql(qh):lb;const hb=ub;var pb=1,mb=2,fb=4,Gf="[object Arguments]",gb="[object Array]",vb="[object Boolean]",yb="[object Date]",Eb="[object Error]",Jf="[object Function]",Sb="[object GeneratorFunction]",Tb="[object Map]",_b="[object Number]",qf="[object Object]",kb="[object RegExp]",bb="[object Set]",wb="[object String]",Cb="[object Symbol]",Ib="[object WeakMap]",Rb="[object ArrayBuffer]",Pb="[object DataView]",Ab="[object Float32Array]",Mb="[object Float64Array]",Db="[object Int8Array]",Ob="[object Int16Array]",Nb="[object Int32Array]",Lb="[object Uint8Array]",xb="[object Uint8ClampedArray]",Fb="[object Uint16Array]",Ub="[object Uint32Array]",we={};we[Gf]=we[gb]=we[Rb]=we[Pb]=we[vb]=we[yb]=we[Ab]=we[Mb]=we[Db]=we[Ob]=we[Nb]=we[Tb]=we[_b]=we[qf]=we[kb]=we[bb]=we[wb]=we[Cb]=we[Lb]=we[xb]=we[Fb]=we[Ub]=!0;we[Eb]=we[Jf]=we[Ib]=!1;function ua(t,e,r,n,i,s){var o,a=e&pb,d=e&mb,h=e&fb;if(r&&(o=i?r(t,n,i,s):r(t)),o!==void 0)return o;if(!nr(t))return t;var p=ts(t);if(p){if(o=Mk(t),!a)return Uf(t,o)}else{var f=Oc(t),g=f==Jf||f==Sb;if(Mc(t))return Ff(t,a);if(f==qf||f==Gf||g&&!i){if(o=d||g?{}:$f(t),!a)return d?gk(t,ok(o,t)):hk(t,tk(o,t))}else{if(!we[f])return i?t:{};o=rb(t,f,a)}}s||(s=new mi);var E=s.get(t);if(E)return E;s.set(t,o),hb(t)?t.forEach(function(A){o.add(ua(A,e,r,A,t,s))}):cb(t)&&t.forEach(function(A,D){o.set(D,ua(A,e,r,D,t,s))});var v=h?d?yk:vk:d?fo:zl,I=p?void 0:v(t);return n_(I||t,function(A,D){I&&(D=A,A=t[D]),If(o,D,ua(A,e,r,D,t,s))}),o}var Vb=1,Bb=4;function Zl(t){return ua(t,Vb|Bb)}var jb="[object Symbol]";function Hb(t){return typeof t=="symbol"||vn(t)&&ui(t)==jb}const Wb={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:KS("#2160FD"),background:zS("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Kf(){return Zl(Wb)}const $b={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:Ga.Skip,plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:q.Allowed,can_consume:Ja.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed,can_consume:Ja.Allowed}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:Zi.none,show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Kf(),config_diff:{}},config:{view_type:qe.GroupCall,media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"hybrid"};function Gb(){return Zl($b)}Zi.none,qa.skip;const Jb={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:Ga.Skip,plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:q.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:Zi.none,show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Kf(),config_diff:{}},config:{view_type:qe.GroupCall,media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"2.0.0"};function eu(){return Zl(Jb)}var qb=/\s/;function Kb(t){for(var e=t.length;e--&&qb.test(t.charAt(e)););return e}var zb=/^\s+/;function Yb(t){return t&&t.slice(0,Kb(t)+1).replace(zb,"")}var Kh=0/0,Qb=/^[-+]0x[0-9a-f]+$/i,Xb=/^0b[01]+$/i,Zb=/^0o[0-7]+$/i,e0=parseInt;function zh(t){if(typeof t=="number")return t;if(Hb(t))return Kh;if(nr(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=nr(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Yb(t);var r=Xb.test(t);return r||Zb.test(t)?e0(t.slice(2),r?2:8):Qb.test(t)?Kh:+t}function zf(t){return t}function t0(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var r0=800,n0=16,i0=Date.now;function s0(t){var e=0,r=0;return function(){var n=i0(),i=n0-(n-r);if(r=n,i>0){if(++e>=r0)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function o0(t){return function(){return t}}var a0=Ya?function(t,e){return Ya(t,"toString",{configurable:!0,enumerable:!1,value:o0(e),writable:!0})}:zf;const c0=a0;var d0=s0(c0);const l0=d0;var Yh=Math.max;function u0(t,e,r){return e=Yh(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=Yh(n.length-e,0),o=Array(s);++i<s;)o[i]=n[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=n[i];return a[e]=r(o),t0(t,this,a)}}function h0(t,e){return l0(u0(t,e,zf),t+"")}function p0(t,e,r){if(!nr(r))return!1;var n=typeof e;return(n=="number"?mo(r)&&Af(e,r.length):n=="string"&&e in r)?Rc(r[e],t):!1}function m0(t){return h0(function(e,r){var n=-1,i=r.length,s=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&p0(r[0],r[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++n<i;){var a=r[n];a&&t(e,a,n,s)}return e})}var f0="[object Object]",g0=Function.prototype,v0=Object.prototype,Yf=g0.toString,y0=v0.hasOwnProperty,E0=Yf.call(Object);function S0(t){if(!vn(t)||ui(t)!=f0)return!1;var e=Ql(t);if(e===null)return!0;var r=y0.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&Yf.call(r)==E0}function T0(t){return function(e,r,n){for(var i=-1,s=Object(e),o=n(e),a=o.length;a--;){var d=o[t?a:++i];if(r(s[d],d,s)===!1)break}return e}}var _0=T0();const k0=_0;var b0=function(){return ir.Date.now()};const fd=b0;var w0="Expected a function",C0=Math.max,I0=Math.min;function mr(t,e,r){var n,i,s,o,a,d,h=0,p=!1,f=!1,g=!0;if(typeof t!="function")throw new TypeError(w0);e=zh(e)||0,nr(r)&&(p=!!r.leading,f="maxWait"in r,s=f?C0(zh(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function E(S){var P=n,O=i;return n=i=void 0,h=S,o=t.apply(O,P),o}function v(S){return h=S,a=setTimeout(D,e),p?E(S):o}function I(S){var P=S-d,O=S-h,ae=e-P;return f?I0(ae,s-O):ae}function A(S){var P=S-d,O=S-h;return d===void 0||P>=e||P<0||f&&O>=s}function D(){var S=fd();if(A(S))return x(S);a=setTimeout(D,I(S))}function x(S){return a=void 0,g&&n?E(S):(n=i=void 0,o)}function W(){a!==void 0&&clearTimeout(a),h=0,n=d=i=a=void 0}function H(){return a===void 0?o:x(fd())}function R(){var S=fd(),P=A(S);if(n=arguments,i=this,d=S,P){if(a===void 0)return v(d);if(f)return clearTimeout(a),a=setTimeout(D,e),E(d)}return a===void 0&&(a=setTimeout(D,e)),o}return R.cancel=W,R.flush=H,R}function Zd(t,e,r){(r!==void 0&&!Rc(t[e],r)||r===void 0&&!(e in t))&&Jl(t,e,r)}function R0(t){return vn(t)&&mo(t)}function el(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function P0(t){return po(t,fo(t))}function A0(t,e,r,n,i,s,o){var a=el(t,r),d=el(e,r),h=o.get(d);if(h){Zd(t,r,h);return}var p=s?s(a,d,r+"",t,e,o):void 0,f=p===void 0;if(f){var g=ts(d),E=!g&&Mc(d),v=!g&&!E&&Kl(d);p=d,g||E||v?ts(a)?p=a:R0(a)?p=Uf(a):E?(f=!1,p=Ff(d,!0)):v?(f=!1,p=Wf(d,!0)):p=[]:S0(d)||Qa(d)?(p=a,Qa(a)?p=P0(a):(!nr(a)||Gl(a))&&(p=$f(d))):f=!1}f&&(o.set(d,p),i(p,d,n,s,o),o.delete(d)),Zd(t,r,p)}function Qf(t,e,r,n,i){t!==e&&k0(e,function(s,o){if(i||(i=new mi),nr(s))A0(t,e,o,r,Qf,n,i);else{var a=n?n(el(t,o),s,o+"",t,e,i):void 0;a===void 0&&(a=s),Zd(t,o,a)}},fo)}var M0="[object Map]",D0="[object Set]",O0=Object.prototype,N0=O0.hasOwnProperty;function L0(t){if(t==null)return!0;if(mo(t)&&(ts(t)||typeof t=="string"||typeof t.splice=="function"||Mc(t)||Kl(t)||Qa(t)))return!t.length;var e=Oc(t);if(e==M0||e==D0)return!t.size;if(Dc(t))return!Lf(t).length;for(var r in t)if(N0.call(t,r))return!1;return!0}var x0=m0(function(t,e,r){Qf(t,e,r)});const Zr=x0;var tl=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(tl||{});const X={REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",INTERNAL_CALL_STATS:"internal_call_stats",SIMULCAST:"simulcast",CHAT_SOCKET_SERVER:"chat_socket_server",POLL_SOCKET_SERVER:"poll_socket_server",PLUGIN_SOCKET_SERVER:"plugin_socket_server",NR_OTEL_WEB:"nr_otel_web",CONNECTED_MEETINGS:"connected_meetings",ICE_RESTART_ON_FAILED_STATE:"ice_restart_on_failed_state",ICE_RESTART_ON_DISCONNECTED_STATE:"ice_restart_on_disconnected_state",ENABLE_ICE_STATE_LOGGING:"enable_ice_state_logging",SUPPRESS_PEER_MUTE_UNMUTE_EMITS:"web_core_suppress_peer_mute_unmute_emits",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",CUSTOM_PING_PONG:"custom_ping_pong",ENABLE_HIVE_SIMULCAST:"enable_hive_simulcast",ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_hive_transport_reconnection_on_ice_failed",ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY:"enable_hive_fail_recovery",ENABLE_HIVE_INFINITE_RETRIES:"enable_hive_infinite_retries",HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"hive_transport_force_relay_on_ice_failed",ENABLE_HIVE_CONSUME_OVER_DC:"enable_hive_consume_over_dc",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_cf_transport_reconnection_on_ice_failed",ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY:"enable_cf_fail_recovery",ENABLE_CF_INFINITE_RETRIES:"enable_cf_infinite_retries",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",BYPASS_LOG_EXCLUSION_LIST:"bypass_log_exclusion_list",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",SCREENSHARE_DTX:"screenshare_dtx",SCREENSHARE_PRIORITY:"screenshare_priority",SCREENSHARE_MIN_BITRATE:"screenshare_minbitrate",SCREENSHARE_SIMULCAST:"screenshare_simulcast",DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE:"disable_webcam_layers_on_screenshare",SCREENSHARE_FORCE_GOOG_CONFERENCE:"screenshare_force_goog_conference",LIVESTREAM:"feat_livestream",FETCH_RETRY:"fetch_retry",DISABLE_WEBCAM_SIMULCAST:"webcore_disable_webcam_simulcast",OVERRIDE_WEBCAM_SIMULCAST:"override_webcam_simulcast",SOCKET_POLLING:"socket_polling",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",TROUBLESHOOTING:"feat_troubleshooting",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",DYNAMIC_VIDEO_QUALITY:"dynamic_video_quality",EXP_RESHARE:"exp_reshare",LEAVE_STAGE_ON_END:"leave_stage_on_end",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test"};function ha(t){const e={};return typeof(t==null?void 0:t.code)=="number"&&(e.code=t.code),typeof(t==null?void 0:t.code)=="string"&&(e.code=t.code.substring(0,100)),typeof(t==null?void 0:t.name)=="string"&&(e.name=t.name.substring(0,500)),typeof(t==null?void 0:t.message)=="string"&&(e.message=t.message.substring(0,500)),typeof(t==null?void 0:t.reason)=="string"&&(e.reason=t.reason.substring(0,500)),typeof(t==null?void 0:t.stack)=="string"&&(e.stack=t.stack.substring(0,500)),e}function Xf(t){var e,r,n,i;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((r=window.location.host)==null?void 0:r.includes("dyte.io")),o=!!((i=(n=t.getValue("modules"))==null?void 0:n.devTools)!=null&&i.logs);return s||o}function F0(t){if(K.hasFeature(X.LOG_LEVEL)){let e=K.getValue(X.LOG_LEVEL)||"all";if(e=e.toLowerCase().trim(),e==="off")return!1;if(e!=="all"){const r=["debug","log","info","warn","error"],n=r.indexOf(t),i=r.indexOf(e);if(n<i)return!1}}return!0}function Zf(t,e,r={}){return Object.getOwnPropertyNames(t).forEach(n=>{var i;if([null,void 0,NaN].includes(t[n])||e&&(((i=e.match(/\./g))==null?void 0:i.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?Zf(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function Qh(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),o=JSON.parse(s),a=Zf(o,n),d=JSON.stringify(a);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
25
- ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw Xf(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const o=ha(s);i[`${n}.error.message`]=o.message||"",i[`${n}.error.stack`]=o.stack||"",i[`${n}.error.reason`]=o.reason||"",i[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const ao="chrome",eg="opera",tg="firefox",rg="iexplorer",ng="safari",ig="nwjs",sg="electron",og="react-native",tu="unknown",Xa={Chrome:ao,Chromium:ao,Opera:eg,Firefox:tg,"Internet Explorer":rg,Safari:ng};function U0(){const{userAgent:t}=navigator,e={name:tu,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const r=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(e.name=ao,e.version=r)}else e.name=ao,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function V0(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:sg,version:e}}return null}function B0(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:ig,version:e}}}function j0(){const t=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let e;if(t||navigator.product==="ReactNative")return t&&t.length>2&&(t[1],e=t[2]),e||(e="unknown"),{name:og,version:e}}function H0(t){let e;const r=[j0,V0,B0];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in Xa?{name:Xa[n],version:t.getBrowserVersion()}:(e=U0(),e||{name:tu,version:void 0})}class W0{constructor(){m(this,"_bowser"),m(this,"_name"),m(this,"_version"),m(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(e){let r,n;if(this._bowser=wm.getParser(navigator.userAgent),typeof e=="undefined"){const i=H0(this._bowser);r=i.name,n=i.version}else e.name in Xa?(r=Xa[e.name],n=e.version):(r=tu,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===ao}isOpera(){return this._name===eg}isFirefox(){return this._name===tg}isIExplorer(){return this._name===rg}isSafari(){return this._name===ng}isNWJS(){return this._name===ig}isElectron(){return this._name===sg}isReactNative(){return this._name===og||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}}class $0 extends W0{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const e=new ReadableStream;try{return window.postMessage(e,"*",[e]),!0}catch{return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const e=navigator.userAgent;if(e.match(/Chrome/))return Number.parseInt(e.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Ee=new $0,rl={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},vs={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},G0={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,devTools:{logs:!1}};function Xh(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function J0({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?Zs.PREPROD:t!=null&&t.includes("devel.dyte")?Zs.DEVEL:Zs.PROD}function Ki({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function ag(t){const e=t.getValue("baseURI");return{location:Ki({servicePrefix:"location",baseURI:e}),locationLegacy:Ki({servicePrefix:"location-legacy",baseURI:e}),daCollector:Ki({servicePrefix:"da-collector",baseURI:e})}}function q0(t){const e=V({},t),r=new Map,n=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>{var d;return(d=r.get(o))==null?void 0:d.delete(a)}),i=(o,a)=>{var d;(d=r.get(o))==null||d.delete(a)},s=o=>{var a;(a=r.get(o))==null||a.forEach(d=>{try{d(e[o])}catch(h){l.error(`Error in notifying for "${o.toString()}"`,h)}})};return{subscribe:n,unsubscribe:i,notify:s,setValue:(o,a,d=!0)=>{e[o]=a,d&&s(o)},getValue:o=>e[o],getAllValues:()=>e}}class K0{constructor(){m(this,"contexts",new Map)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,q0(r)),this.contexts.get(e))}remapContext(e,r){const n=r.getValue("peerId");n!==e&&(r.setValue("peerId",e),this.contexts.set(e,r),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}}const to=new K0,me=class{static get logsEndpoint(){const t=to.getContext(me.meetingMetadata.peerId);return`https://${Ki({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){me.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");me.tracingEnabled=e,me.meetingMetadata.peerId=r,me.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),me.meetingMetadata.deviceInfo=Ee.getDeviceInfo(),me.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",me.processCachedLogs),me.logsProcessorTimer=setInterval(me.processCachedLogs,me.logsProcessingInterval),e&&(me.initialized=!0)}static trace(t){return(e,r,n)=>{const i=n.value;return n.value=function(...s){if(!me.initialized||navigator.isReactNative||!me.tracingEnabled||K.hasFeature(X.SKIP_OTEL_TRACES))return i.apply(this,s);me.addLogInCurrentSpan("info",t);const o=performance.now(),a=i.apply(this,s);return Promise.resolve(a).then(()=>{const d=performance.now();d-o>10&&me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}).catch(()=>{const d=performance.now();me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}),a},n}}static injectContext(t){var e;const r=di().replace(/-/g,"").substring(0,16),n=(e=me.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${r}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:ha(r.error)});const i=to.getContext(me.meetingMetadata.peerId);if(Xf(i)&&(L0(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!F0(t))try{const s=Qh(i,e,r,"metadata"),o=new Date,a=ne(V({message:e,level:t},s),{loggedAt:o.toISOString(),loggedAtTzOffset:o.getTimezoneOffset()});n?me.sendOtelLogsToNewRelic([a]):me.logsCache.push(a)}catch(s){me.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:ha(s)})}}static sendOtelLogsToNewRelic(t){const e=to.getContext(me.meetingMetadata.peerId);za.post(me.logsEndpoint,{meetingMetadata:Qh(e,"sendOtelLogsToNewRelic",me.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{me.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:ha(r)}),me.logsCache.push(...t)})}static processCachedLogs(){const t=me.logsCache.splice(0,25);t!=null&&t.length&&me.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(me.logsProcessorTimer),me.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",me.processCachedLogs)}};let y=me;m(y,"logsCache",[]),m(y,"logsProcessorTimer"),m(y,"tracingEnabled",!0),m(y,"initialized",!1),m(y,"logsProcessingInterval",7e3),m(y,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]),m(y,"meetingMetadata",{});class l{static info(e,r,n){y.addLogInCurrentSpan("info",e,r,n)}static error(e,r,n){y.addLogInCurrentSpan("error",e,r,n)}static debug(e,r,n){y.addLogInCurrentSpan("debug",e,r,n)}static log(e,r,n){y.addLogInCurrentSpan("log",e,r,n)}static warn(e,r,n){y.addLogInCurrentSpan("warn",e,r,n)}}const z0=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&l.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,n,i,s,o,a,d;l.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(i=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:i.baseURL,method:(o=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:o.method,status:(a=t==null?void 0:t.reason)==null?void 0:a.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},Y0={"00":"DyteClient","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption"},pa={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0100":"Internal exception","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0510":"Invalid channel name.","0600":"Internal exception","0700":"Internal exception","0800":"Internal exception","0900":"Internal exception",1e3:"Internal exception",1100:"Internal exception",1200:"Internal exception",1300:"Internal exception",1400:"Internal exception",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1701:"Crypto error",9900:"Internal exception"};Object.keys(pa).forEach(t=>{pa[t]=`{${Y0[t.slice(0,2)]}} ${pa[t]}`});class C extends Error{constructor(e,r,n=!1){super(e),m(this,"code"),this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${pa[this.code]}
26
- ${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}})}catch{}}}function Po(t,e,r,n){if(n instanceof C){if(navigator.isReactNative||typeof reportError!="function")throw n;reportError(n)}else if(n instanceof e){const i=new C(n.message,r);throw i.stack=n.stack,i}else throw n}function Zh(t,e,r){if(!t.value){const i=t.get,s=t.set;return i&&(t.get=function(){try{return i.apply(this)}catch(o){Po(this,e,r,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(a){Po(this,e,r,a)}}),t}const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{Po(this,e,r,o)}):s}catch(s){Po(this,e,r,s)}},t}function Q0(t,e){return(r,n,i)=>{if(i)return Zh(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(r.prototype,s,Zh(o,t,e))}}}const ht=t=>Q0(Error,t);function X0(t){let e=0,r,n;if(!t)return e;for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var en,tn;const cg=class extends It.EventEmitter{constructor(){super(),k(this,en,void 0),k(this,tn,void 0),m(this,"asyncPromiseTimeout"),T(this,en,new Map),T(this,tn,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,en).set(t,[]);const r=c(this,tn).get(t).map(()=>new Promise(n=>{c(this,en).get(t).push(n)}));lE(cg.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(r),new Promise((n,i)=>setTimeout(()=>i(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),c(this,en).delete(t)})}onAsync(t,e){const r=c(this,en),n=(...i)=>u(this,null,function*(){var s;try{yield e(...i)}catch(a){l.error("[onAsync]",{error:a})}const o=(s=r.get(t))==null?void 0:s.shift();o==null||o()});return c(this,tn).get(t)||c(this,tn).set(t,[]),c(this,tn).get(t).push(n),super.on(t,n)}reset(){T(this,en,new Map),T(this,tn,new Map),super.removeAllListeners()}};let Z0=cg;en=new WeakMap,tn=new WeakMap;const w=new Z0;function ew(){Ee.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>u(this,null,function*(){const t=yield window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let e=[];if(t&&(Array.isArray(t)?e=t:e=[t]),!(e!=null&&e.length))throw new Error("Couldn't find any media source for screen share.");let r=e.find(i=>{var s;return(s=i.id)==null?void 0:s.includes("screen")});r=r!=null?r:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var xt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(xt||(xt={}));var Ct;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(Ct||(Ct={}));class tw extends _{constructor(){super("media.Codec",[])}}new tw;class rw extends _{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new rw;class nw extends _{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",xt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const sr=new nw;class iw extends _{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>sr}])}}const dg=new iw;class sw extends _{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>sr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const ru=new sw;class ow extends _{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>sr}])}}const lg=new ow;class aw extends _{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>sr}])}}new aw;class cw extends _{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const dw=new cw;class lw extends _{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const uw=new lw;class hw extends _{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new hw;class pw extends _{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new pw;class mw extends _{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ct]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const go=new mw;class fw extends _{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go},{no:3,name:"producer_track",kind:"message",T:()=>uw}])}}const gw=new fw;class vw extends _{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>gw}}])}}const ug=new vw;class yw extends _{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const Ew=new yw;class Sw extends _{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>Ew}])}}const hg=new Sw;class Tw extends _{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const pg=new Tw;class _w extends _{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const mg=new _w;class kw extends _{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new kw;class bw extends _{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9}])}}const fg=new bw;class ww extends _{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>sr},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9}])}}const gg=new ww;class Cw extends _{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Cw;class Iw extends _{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const vg=new Iw;class Rw extends _{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const hn=new Rw;class Pw extends _{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Za=new Pw;class Aw extends _{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>sr}])}}const yg=new Aw;class Mw extends _{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>sr}])}}const Eg=new Mw;class Dw extends _{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Sg=new Dw;class Ow extends _{constructor(){super("media.edge.KickAllPeersRequest",[])}}const Tg=new Ow;class Nw extends _{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const _g=new Nw;class Lw extends _{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const kg=new Lw;class xw extends _{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const bg=new xw;class Fw extends _{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const Uw=new Fw;class Vw extends _{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const Bw=new Vw;class jw extends _{constructor(){super("media.edge.EmptyResponse",[])}}new jw;class Hw extends _{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>go},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9}])}}const wg=new Hw;class Ww extends _{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const nl=new Ww;class $w extends _{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const Gw=new $w;class Jw extends _{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>Gw}])}}const ep=new Jw;class qw extends _{constructor(){super("media.edge.PeerJoinResponse",[])}}new qw;class Kw extends _{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Uw},{no:2,name:"participants",kind:"message",repeat:1,T:()=>wg},{no:3,name:"selected_peers",kind:"message",T:()=>nl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const ec=new Kw;class zw extends _{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Cg=new zw;class Yw extends _{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>ug}])}}new Yw;class Qw extends _{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>ug},{no:3,name:"description",kind:"message",T:()=>sr}])}}const Ig=new Qw;class Xw extends _{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>sr}])}}const Rg=new Xw;class Zw extends _{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>dw}])}}new Zw;class eC extends _{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new eC;class tC extends _{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new tC;class rC extends _{constructor(){super("media.edge.ProducerToggleResponse",[])}}new rC;class nC extends _{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new nC;class iC extends _{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>sr}])}}const Pg=new iC;class sC extends _{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>sr}])}}new sC;class oC extends _{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new oC;class aC extends _{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ag=new aC;class cC extends _{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Mg=new cC;class dC extends _{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Dg=new dC;class lC extends _{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Og=new lC;class uC extends _{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ng=new uC;class hC extends _{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>wg}])}}const tp=new hC;class pC extends _{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>ru}])}}new pC;class mC extends _{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Lg=new mC;class fC extends _{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const xg=new fC;class gC extends _{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>go}])}}const Fg=new gC;class vC extends _{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const tc=new vC;class yC extends _{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const rp=new yC;class EC extends _{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new EC;class SC extends _{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new SC;class TC extends _{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new TC;class _C extends _{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new _C;class kC extends _{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new kC;class bC extends _{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new bC;class wC extends _{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const gd=new wC;class CC extends _{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new CC;class IC extends _{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const RC=new IC;var rc;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(rc||(rc={}));var Dr;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ON_STAGE=1]="ON_STAGE",t[t.APPROVED_STAGE=2]="APPROVED_STAGE",t[t.REQUESTED_STAGE=3]="REQUESTED_STAGE",t[t.OFF_STAGE=4]="OFF_STAGE"})(Dr||(Dr={}));var il;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(il||(il={}));var nc;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(nc||(nc={}));class PC extends _{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const AC=new PC;class MC extends _{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Dr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>AC}])}}const Nc=new MC;class DC extends _{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Nc}])}}const Fi=new DC;class OC extends _{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",Dr,"STAGE_TYPE_"]}])}}const np=new OC;class NC extends _{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const LC=new NC;class xC extends _{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Nc}])}}const vd=new xC;class FC extends _{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const ip=new FC;class UC extends _{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>BC},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Ug=new UC;class VC extends _{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",rc]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const BC=new VC;class jC extends _{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Ug}])}}const sp=new jC;class HC extends _{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Vg=new HC;class WC extends _{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new WC;class $C extends _{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Nc},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",nc,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const GC=new $C;class JC extends _{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Nc},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const qC=new JC;class KC extends _{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Ug}])}}new KC;class zC extends _{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new zC;class YC extends _{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const nu=new YC;class QC extends _{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const XC=new QC;class ZC extends _{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>XC}])}}const op=new ZC;class eI extends _{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>op},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>op}])}}const tI=new eI;class rI extends _{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const nI=new rI;class iI extends _{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>nI}])}}const sI=new iI;class oI extends _{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>nu}])}}const aI=new oI;class cI extends _{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>aI}])}}const ap=new cI;class dI extends _{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const lI=new dI;class uI extends _{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>lI}])}}new uI;class hI extends _{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const pI=new hI;class mI extends _{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>pI}])}}const fI=new mI;class gI extends _{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>EI}])}}const vI=new gI;class yI extends _{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>nu}])}}const EI=new yI;class SI extends _{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const TI=new SI;class _I extends _{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>TI}])}}const kI=new _I;class bI extends _{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>nu}])}}const Bg=new bI;class wI extends _{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Bg}])}}new wI;class CI extends _{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const II=new CI;class RI extends _{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>MI}])}}const PI=new RI;class AI extends _{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const MI=new AI;class DI extends _{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const OI=new DI;class NI extends _{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Ao=new NI;class LI extends _{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const xI=new LI;class FI extends _{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const UI=new FI;class VI extends _{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9}])}}const BI=new VI;class jI extends _{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>BI}])}}const cp=new jI;class HI extends _{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const dp=new HI;var sl;(function(t){t[t.NONE=0]="NONE",t[t.SKIP=1]="SKIP",t[t.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",t[t.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(sl||(sl={}));var ic;(function(t){t[t.NONE=0]="NONE",t[t.ALLOWED=1]="ALLOWED",t[t.NOT_ALLOWED=2]="NOT_ALLOWED",t[t.CAN_REQUEST=3]="CAN_REQUEST"})(ic||(ic={}));class WI extends _{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const $I=new WI;class GI extends _{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const JI=new GI;class qI extends _{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const KI=new qI;class zI extends _{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const YI=new zI;class QI extends _{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>KI},{no:2,name:"private",kind:"message",T:()=>YI}])}}const XI=new QI;class ZI extends _{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const eR=new ZI;class tR extends _{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",ic,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",ic,"STREAM_PERMISSION_TYPE_"]}])}}const yd=new tR;class rR extends _{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>yd},{no:2,name:"audio",kind:"message",T:()=>yd},{no:3,name:"screenshare",kind:"message",T:()=>yd}])}}const nR=new rR;class iR extends _{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>$I},{no:2,name:"plugins",kind:"message",T:()=>JI},{no:3,name:"chat",kind:"message",T:()=>XI},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",sl,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",il,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>eR},{no:23,name:"media",kind:"message",T:()=>nR}])}}const iu=new iR;class sR extends _{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const oR=new sR;class aR extends _{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const cR=new aR;class dR extends _{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>cR}])}}const lR=new dR;class uR extends _{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>iu}])}}const jg=new uR;class hR extends _{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>jg}])}}const pR=new hR;class mR extends _{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>jg}])}}const lp=new mR;class fR extends _{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const gR=new fR;class vR extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>gR},{no:2,name:"patch",kind:"message",T:()=>iu}])}}new vR;class yR extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>iu}])}}new yR;class ER extends _{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const fi=new ER;class SR extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const TR=new SR;class _R extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>fi},{no:2,name:"next",kind:"scalar",T:8}])}}const kR=new _R;class bR extends _{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>fi}])}}const Hg=new bR;class wR extends _{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const CR=new wR;class IR extends _{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>fi}])}}const Ed=new IR;class RR extends _{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const PR=new RR;class AR extends _{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>fi}])}}const Sd=new AR;class MR extends _{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const DR=new MR;class OR extends _{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>fi}])}}new OR;class NR extends _{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const LR=new NR;class xR extends _{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const FR=new xR;class UR extends _{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Mo=new UR;class VR extends _{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>fi}])}}const Do=new VR;class BR extends _{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const jR=new BR;class HR extends _{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const Oo=new HR;class WR extends _{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const $R=new WR;class GR extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const JR=new GR;class qR extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const KR=new qR;class zR extends _{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const YR=new zR;class QR extends _{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const XR=new QR;class ZR extends _{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new ZR;class eP extends _{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const tP=new eP;class rP extends _{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>fi},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const nP=new rP;class iP extends _{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>nP},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const sP=new iP;class oP extends _{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>sP}])}}const Cr=new oP;class aP extends _{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const cP=new aP;class dP extends _{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>cP}])}}const lP=new dP;class uP extends _{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const hP=new uP;class pP extends _{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const mP=new pP;class fP extends _{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const gP=new fP;class vP extends _{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const yP=new vP;class EP extends _{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const SP=new EP;class TP extends _{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const _P=new TP;class kP extends _{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const bP=new kP;class wP extends _{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const CP=new wP;class IP extends _{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const su=new IP;class RP extends _{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>su}])}}const up=new RP;class PP extends _{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>su}])}}const AP=new PP;class MP extends _{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>su}])}}const DP=new MP;class OP extends _{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const NP=new OP;class LP extends _{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const ol=new LP;class xP extends _{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>ol}])}}const FP=new xP;class UP extends _{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const hp=new UP;class VP extends _{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const BP=new VP;class jP extends _{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>BP}])}}const pp=new jP;class HP extends _{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const mp=new HP;class WP extends _{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9}])}}const fp=new WP;class $P extends _{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const gp=new $P;class GP extends _{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const JP=new GP;class qP extends _{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>JP}])}}const Td=new qP;class KP extends _{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const zP=new KP;class YP extends _{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QP=new YP;class XP extends _{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const vp=new XP;class ZP extends _{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>tA},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Wg=new ZP;class eA extends _{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>nA}])}}const tA=new eA;class rA extends _{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const nA=new rA;class iA extends _{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const sA=new iA;class oA extends _{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const aA=new oA;class cA extends _{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Wg}])}}const _d=new cA;class dA extends _{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Wg}])}}const lA=new dA;class uA extends _{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",rc]}])}}const yp=new uA;class hA extends _{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),r=Date.now();return e.seconds=Ce.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(Ce.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=Ce.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=Ce.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",i)}internalJsonRead(e,r,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+Ll(e)+".");let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return n||(n=this.create()),n.seconds=Ce.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new hA;class ds extends It.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Ut extends It.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}const pA=0,mA=1,fA=2,gA=3,vA=4,yA=5,EA={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToPeers:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43},SA={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},TA={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},_A={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},$g={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94},kA={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},bA={getUserPresets:0,updateUserPreset:1};function ls(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function Gg(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=ls(pA,EA),Le=ls(mA,SA),J=ls(fA,TA),Pr=ls(gA,_A),ei=ls(vA,kA),ie=Gg($g,16777216),se=Gg($g,50331648),ma=ls(yA,bA);var wA=Object.defineProperty,CA=Object.getOwnPropertyDescriptor,ou=(t,e,r,n)=>{for(var i=n>1?void 0:n?CA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&wA(e,r,i),i},_n,Ep;const al=(Ep=class{constructor(t){k(this,_n,void 0),T(this,_n,t)}createChannel(t,e,r,n="public",i=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:r,visibility:n,isDirectMessage:i};i&&(s.visibility="private");const o=yield c(this,_n).sendMessagePromise(ei.createChatChannel,YR.toBinary(s)),a=Cr.fromBinary(o.payload).chatChannels;return al.formatChannel(a[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,_n).sendMessagePromise(ei.updateChatChannel,XR.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=Cr.fromBinary(r.payload).chatChannels;return al.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=ne(V({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=r==null?void 0:r.unreadCount)!=null?e:0});return r!=null&&r.message&&(n.latestMessage=Nr.formatSocketServiceMessage(r.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield c(this,_n).sendMessagePromise(ei.getChannelMembers,tP.toBinary({chatChannelId:t}));return lP.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=Ec(n,["id"]);return ne(V({},s),{userId:i})})}catch{return[]}})}on(t,e){let r,n;switch(t){case ei.createChatChannel:{r=Cr.fromBinary.bind(Cr),n=Cr.create();break}case ei.updateChatChannel:{r=Cr.fromBinary.bind(Cr),n=Cr.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,_n).on(t,({payload:i})=>{let s=n;try{s=r(i)}catch(o){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}},_n=new WeakMap,Ep);let si=al;ou([y.trace("ChatChannelHandler.createChannel")],si.prototype,"createChannel",1);ou([y.trace("ChatChannelHandler.updateChannel")],si.prototype,"updateChannel",1);ou([y.trace("ChatChannelHandler.getChannelMembers")],si.prototype,"getChannelMembers",1);var IA=Object.defineProperty,RA=Object.getOwnPropertyDescriptor,or=(t,e,r,n)=>{for(var i=n>1?void 0:n?RA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&IA(e,r,i),i},_t=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(_t||{}),vt;class Jt{constructor(e){k(this,vt,void 0),T(this,vt,e)}getChatMessages(){return c(this,vt).sendMessagePromise(Le.getMessages)}getChatMessagesPaginated(e,r,n,i=0,s=""){return u(this,null,function*(){const o={timeStamp:e,size:r,from:i,reversed:n,channelId:s},a=yield c(this,vt).sendMessagePromise(Le.getPaginatedMessages,TR.toBinary(o));return a.payload?kR.fromBinary(a.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,vt).sendMessage(Le.sendMessageToRoom,CR.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,vt).sendMessage(Le.sendMessageToPeers,PR.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,vt).sendMessage(Le.sendMessageToChannel,DR.toBinary(i))}sendMessage(e,r,n,i){if(i&&this.sendMessageToChannel(e,r,i),n&&n.length>0){this.sendMessageToPeers(e,r,n);return}this.sendMessageToRoom(e,r)}editMessage(e,r,n,i,s){return u(this,null,function*(){const o={chatId:e,payloadType:n,payload:r};i&&(o.channelId=i),s!==void 0&&(o.pinned=s);const a=yield c(this,vt).sendMessagePromise(Le.editMessage,LR.toBinary(o));return Do.fromBinary(a.payload).message})}deleteMessage(e,r){return u(this,null,function*(){const n={chatId:e};r&&(n.channelId=r);const i=yield c(this,vt).sendMessagePromise(Le.deleteMessage,jR.toBinary(n)),s=Oo.fromBinary(i.payload);return V({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,r){return u(this,null,function*(){var n,i,s;const o={searchTerm:e,timeStamp:(n=r.timestamp)!=null?n:Date.now(),size:(i=r.size)!=null?i:75,from:0,reversed:(s=r.reversed)!=null?s:!0};r.channelId&&(o.channelId=r.channelId);try{const a=yield c(this,vt).sendMessagePromise(Le.searchChannelMessages,$R.toBinary(o));return Hg.fromBinary(a.payload).messages}catch{return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,vt).sendMessagePromise(Le.getAllChatChannels);return Cr.fromBinary(e.payload).chatChannels.map(si.formatChannel)}catch{return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,vt).sendMessagePromise(Le.markChannelIndexAsRead,JR.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return KR.fromBinary(n.payload).channelIndex})}setPinState(e,r){return u(this,null,function*(){const n={chatId:e.id,pinned:r,channelId:e.channelId},i=yield c(this,vt).sendMessagePromise(Le.pinMessage,FR.toBinary(n));return Mo.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case Le.sendMessageToRoom:{n=Ed.fromBinary.bind(Ed),i=Ed.create();break}case Le.sendMessageToPeers:{n=Sd.fromBinary.bind(Sd),i=Sd.create();break}case Le.editMessage:{n=Do.fromBinary.bind(Do),i=Do.create();break}case Le.pinMessage:{n=Mo.fromBinary.bind(Mo),i=Mo.create();break}case Le.deleteMessage:{n=Oo.fromBinary.bind(Oo),i=Oo.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,vt).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}vt=new WeakMap;or([y.trace("SocketService.getChatMessages")],Jt.prototype,"getChatMessages",1);or([y.trace("SocketService.getChatMessagesPaginated")],Jt.prototype,"getChatMessagesPaginated",1);or([y.trace("SocketService.sendMessageToRoom")],Jt.prototype,"sendMessageToRoom",1);or([y.trace("SocketService.sendMessageToPeers")],Jt.prototype,"sendMessageToPeers",1);or([y.trace("SocketService.sendMessageToChannel")],Jt.prototype,"sendMessageToChannel",1);or([y.trace("SocketService.sendMessage")],Jt.prototype,"sendMessage",1);or([y.trace("SocketService.editMessage")],Jt.prototype,"editMessage",1);or([y.trace("SocketService.deleteMessage")],Jt.prototype,"deleteMessage",1);or([y.trace("SocketService.searchMessages")],Jt.prototype,"searchMessages",1);or([y.trace("SocketService.getAllChannels")],Jt.prototype,"getAllChannels",1);or([y.trace("SocketService.markLastReadMessage")],Jt.prototype,"markLastReadMessage",1);function PA(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function fr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>fr(r));const e={};return Object.keys(t).forEach(r=>{const n=Nl(r)?r:PA(r);e[n]=fr(t[r])}),e}function AA(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Jg(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Jg(r));const e={};return Object.keys(t).forEach(r=>{const n=Nl(r)?r:AA(r);e[n]=t[r]}),e}function sc(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){sc(t[r],e[r]={});return}e[r]=t[r]}}),e)}const MA=3,DA=30,OA=8e3;class NA{constructor(e,r){m(this,"ipInfo"),m(this,"axios"),m(this,"requests"),m(this,"roomName"),m(this,"roomUUID"),m(this,"authToken"),m(this,"organizationId"),m(this,"iceServers"),m(this,"pluginInformation"),m(this,"userDetails"),m(this,"roomDetails"),m(this,"context"),this.context=e;const{timeout:n=OA,retry:i=MA,retryDelay:s=DA,baseURL:o="https://api.cluster.dyte.in",authToken:a,cachedUserDetails:d}=r||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=za.create({baseURL:o,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=za,this.setAuthToken(a,{bearer:!0}),this.requests.interceptors.request.use(h=>(y.injectContext(this.requests.defaults.headers.common),h),h=>u(this,null,function*(){l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:h})})),this.requests.interceptors.response.use(h=>{try{h.config.url!==y.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,method:h.config.method}})}catch(p){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,response:h})}return h},h=>u(this,null,function*(){var p;try{if(!h)return Promise.reject(new C("Unknown network error occurred","0011"));h&&h.config&&((p=h.config)==null?void 0:p.url)!==y.logsEndpoint&&l.error("xhr::axios",{error:h,networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,retries:h.config.retry,method:h.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:f,message:g}=h;return f&&g&&f.retry!==void 0&&f.retry>0&&(g.includes("timeout")||g.includes("Network Error"))?(f.retry-=1,this.requests(f)):Promise.reject(new C(g,"0011"))}catch(f){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:f,responseError:h}),Promise.reject(new C(f.message,"0011"))}}))}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,r){const{bearer:n}=r||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,r){this.requests.defaults.headers.common[e]=r}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var LA=Object.defineProperty,xA=Object.getOwnPropertyDescriptor,au=(t,e,r,n)=>{for(var i=n>1?void 0:n?xA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&LA(e,r,i),i};class Lc extends NA{constructor(e,r){super(e,r),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:r}=this;try{const n=yield jl.getIPDetails({peerId:r,apiHostnames:ag(this.context)});if(l.log("ipInfo",{ipInfo:n}),((e=n.loc)==null?void 0:e.length)>5)return n;throw Error("Insufficient data")}catch(n){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:n.name,message:n.message}});return}})}getICEServers(){return u(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(yield this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r})}getPlugins(){return u(this,null,function*(){var e,r,n,i,s,o,a;if(this.pluginInformation)return this.pluginInformation;let{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data;const h=((r=(e=K.getValue(X.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:r.split(","))||[];return d=d.reduce((p,f)=>(p[h.includes(f.id)?"v1":"v2"].push(f),p),{v1:[],v2:[]}).v2,(s=(i=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:i.plugins)!=null&&s.length&&((a=(o=this.context.getValue("modules"))==null?void 0:o.devTools)==null||a.plugins.forEach(p=>{var f,g,E;const v=ne(V({},vs),{tags:[...vs.tags]});v.baseURL=`http://localhost:${p.port}`,v.name=p.name,v.picture=(f=p.picture)!=null?f:vs.picture,v.description=(g=p.description)!=null?g:vs.description,v.staggered=(E=p.staggered)!=null?E:vs.staggered,v.createdAt=new Date().toISOString(),v.updatedAt=new Date().toISOString(),v.id=p.id,v.organizationId=this.organizationId,d.push(v)})),d})}getPluginDetails(e){return u(this,null,function*(){const{plugin:r}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r})}getPluginConfig(e){return u(this,null,function*(){return(yield this.axios.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const r={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return n})}getPresignedUrls(e,r){return u(this,null,function*(){const n={roomUUID:this.roomUUID,filename:e};K.hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=r);const{getLocation:i,putLocation:s}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:i,putLocation:s}})}uploadFile(e,r){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){l.error(`sendFileMessage::${n}`)}else yield this.axios.put(r,e,{headers:{"Content-Type":e.type}})})}}au([y.trace("APIClient.getIPDetails")],Lc.prototype,"getIPDetails",1);au([y.trace("APIClient.getICEServers")],Lc.prototype,"getICEServers",1);au([y.trace("APIClient.getPlugins")],Lc.prototype,"getPlugins",1);var FA=Object.defineProperty,UA=Object.getOwnPropertyDescriptor,jr=(t,e,r,n)=>{for(var i=n>1?void 0:n?UA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&FA(e,r,i),i};class yr extends Lc{startLivestreaming(){return u(this,null,function*(){var e,r;return(r=(e=(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`)).data)==null?void 0:e.data)==null?void 0:r.playback_url})}stopLivestreaming(){return u(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return u(this,null,function*(){const{playbackUrl:e,status:r}=fr((yield this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{status:r,playbackUrl:e}})}getUserDetails(){return u(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return fr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",ne(V({},Jg(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r}))).data.data.id})}updateRecording(e,r){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:r})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:r}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}})}getActiveTranscript(){return u(this,null,function*(){const{transcript_download_url:e}=(yield this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(yield this.axios.get(e)).data}}catch{throw new C("Cant fetch transcript s3 url")}})}getRoomNodeData(){return u(this,null,function*(){if(this.roomDetails)return this.roomDetails;const e=yield this.getIPDetails();this.ipInfo=e;const{roomNodeLink:r,title:n,useHiveMedia:i,sfu:s}=fr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}jr([y.trace("APIClient.startLivestreaming")],yr.prototype,"startLivestreaming",1);jr([y.trace("APIClient.stopLivestreaming")],yr.prototype,"stopLivestreaming",1);jr([y.trace("APIClient.getActiveLivestream")],yr.prototype,"getActiveLivestream",1);jr([y.trace("APIClient.getUserDetails")],yr.prototype,"getUserDetails",1);jr([y.trace("APIClient.startRecording")],yr.prototype,"startRecording",1);jr([y.trace("APIClient.stopRecording")],yr.prototype,"updateRecording",1);jr([y.trace("APIClient.getActiveRecording")],yr.prototype,"getActiveRecording",1);jr([y.trace("APIClient.getActiveTranscript")],yr.prototype,"getActiveTranscript",1);jr([y.trace("APIClient.getRoomNodeData")],yr.prototype,"getRoomNodeData",1);let cl;function VA(t,e){return cl=new yr(t,e),cl}function We(){return cl}function BA(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
23
+ `)),this.pc2.setLocalDescription(e),this.pc1.setRemoteDescription(e)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(e){console.error("Error:",e)}getRoundTripTime(){return u(this,null,function*(){const[e,r]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,i;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),r.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(i=s)}),n&&i)try{if(n.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const s=(i.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch{return}})}close(){this.pc1.close(),this.pc2.close()}}class $f extends ft{constructor(e){super(),f(this,"call"),f(this,"timeOut"),this.call=new en(e)}start(e=1e4){this.call.establishConnection(),this.timeOut=setTimeout(this.testFailed.bind(this),e)}testComplete(e){clearTimeout(this.timeOut),this.call.close(),this.emit("done",e)}testFailed(e){this.call.close(),this.emit("failed",e)}}const fE=8,gE=1/1e3;class vE extends $f{constructor(e){super(e),f(this,"senderChannel"),f(this,"recieveChannel"),f(this,"startTime"),f(this,"lastBitrateMeasureTime"),f(this,"sentPayloadBytes",0),f(this,"recievedPayloadBytes",0),f(this,"lastReceivedPayloadBytes",0),f(this,"stopSending",!1),f(this,"testProgress",0),f(this,"samplePacket",""),f(this,"finalBitrateSum",0),f(this,"bitRateSampels",0),f(this,"maxNumberOfPacketsToSend",0),f(this,"bytesToKeepBuffered",0),f(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(en.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<1024*256;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch{}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const i=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*fE/(n/1e3);this.finalBitrateSum+=i,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*gE)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Iu extends $f{constructor(e,r=en.noFilter){super(e),f(this,"ch1"),f(this,"ch2"),this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch{}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class yE extends Iu{constructor(e){super(e,en.isHost)}}class SE extends Iu{constructor(e){super(e,en.isRelay)}}class EE extends Iu{constructor(e){super(e,en.isReflexive)}}class TE{constructor(){f(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:r,apiHostnames:n,logger:i}){var s,o,a;if(!this.ipInformation){try{const d=`https://${n.location}`,h=yield(yield fetch(d)).json();if(((s=h.loc)==null?void 0:s.length)>5)return this.ipInformation=h,(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=Nn(this.ipInformation.ip)),h;throw Error("Insufficient data")}catch(d){i.error("callstats::ipDetails:: failed to fetch ip using location service",{error:d})}try{const d=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${r}`,{method:"POST"});this.ipInformation=yield d.json(),(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Nn(this.ipInformation.ip))}catch(d){i.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:d})}}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Cu=new TE,Oh=[{urls:"turn:turn.dyte.in:443?transport=tcp",username:"dyte",credential:"dytein",credentialType:"password"},{urls:"turn:turn.dyte.in:3478?transport=udp",username:"dyte",credential:"dytein",credentialType:"password"}];function Nh(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class Jf{constructor(){f(this,"transport"),f(this,"candidatePair"),f(this,"outboundVideoRtp",new Map),f(this,"inboundVideoRtp",new Map),f(this,"outboundAudioRtp",new Map),f(this,"inboundAudioRtp",new Map),f(this,"remoteInboundRtp",new Map),f(this,"producerStreamMap",new Map),f(this,"consumerStreamMap",new Map),f(this,"staleProducerStreamMap",!1),f(this,"staleConsumerStreamMap",!1)}}class Gf extends ft{constructor(){super(),f(this,"observer"),f(this,"outboundProducerMap",new Map),f(this,"inboundConsumerMap",new Map),f(this,"consumerPeerIdMap",new Map),f(this,"pausedConsumerMap",new Map),f(this,"pausedProducerMap",new Map),f(this,"overallProducingTransportsStatsMap",{}),f(this,"overallConsumingTransportsStatsMap",{}),f(this,"overallConsumersStatsMap",{}),f(this,"overallProducersStatsMap",{}),f(this,"videoProducerToStatsMap",new Map),f(this,"audioProducerToStatsMap",new Map),f(this,"videoConsumerToStatsMap",new Map),f(this,"audioConsumerToStatsMap",new Map),f(this,"consumerIdsWithFreezedVideo",new Set),f(this,"consumerIdsWithFreezedAudio",new Set),f(this,"producerIdsWithFreezedVideo",new Set),f(this,"producerIdsWithFreezedAudio",new Set),f(this,"freezedProducingTransportIds",new Set),f(this,"freezedConsumingTransportIds",new Set),f(this,"screenShareProducers",new Set),f(this,"screenShareConsumers",new Set),f(this,"ipDetails"),f(this,"callStatsInstance"),this.observer=new ft}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{},{audio:o,video:a,screen:d}=s,h=o||a||d;r.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,n){var i,s;const o=!!Array.from(((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((a,d)=>a||d.audio||d.video||d.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return u(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}generateProducerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"outbound-rtp":{this.outboundProducerMap.set(s.id,e.id);break}}return i})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"inbound-rtp":{this.inboundConsumerMap.set(s.id,e.id);break}}return i})}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(r=>{const n=r.framesEncoded>0,i=r.packetsSent>0,s=r.frameWidth&&r.frameHeight;return n&&i&&!!s})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,m,g,v,_,A,C,M,N;const J=e,P=new Jf,G=r.length?new Set(r):void 0,W=[],ae=[],se=[],Ne=new Map,Tt=new Map;for(const O of J.values()){if(G){if(G.size===0)break;if(G.has(O.type))n&&G.delete(O.type);else continue}switch(O.type){case"local-candidate":{W.push(this.getIceCandidateStats(O));break}case"remote-candidate":{ae.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,Ae={nominated:k!=null?k:R,currentRoundTripTime:H.currentRoundTripTime,totalRoundTripTime:H.totalRoundTripTime,bytesReceived:H.bytesReceived,bytesSent:H.bytesSent,availableOutgoingBitrate:H.availableOutgoingBitrate,availableIncomingBitrate:H.availableIncomingBitrate,lastPacketReceivedTimestamp:H.lastPacketReceivedTimestamp,lastPacketSentTimestamp:H.lastPacketSentTimestamp,localCandidateId:H.localCandidateId,remoteCandidateId:H.remoteCandidateId,bytesDiscardedOnSend:H.bytesDiscardedOnSend,packetsSent:H.packetsSent,packetsReceived:H.packetsReceived,packetsDiscardedOnSend:H.packetsDiscardedOnSend};se.push(Ae),(O.nominated===!0||O.selected===!0)&&(P.candidatePair=Ae);break}case"transport":{const k=O;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const R={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(P.transport=R,s){if(s.producing){const H=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,H,R)}if(s.consuming){const H=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,H,R)}}break}case"remote-inbound-rtp":{const k=O,R={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};P.remoteInboundRtp.set(k.localId,R);break}case"outbound-rtp":{const k=O,R=i||this.outboundProducerMap.get(O.id),H=this.pausedProducerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ae=this.overallProducersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(O.id)){P.staleProducerStreamMap=!0;break}const Ze=this.callStatsInstance.producers.get(R);if(((o=Ze==null?void 0:Ze.track)==null?void 0:o.readyState)==="ended")break;P.producerStreamMap.has(R)||P.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:k.bytesSent,packetsSent:k.packetsSent,nackCount:k.nackCount,ssrc:k.ssrc,mid:k.mid,active:k.active,codecId:k.codecId,headerBytesSent:k.headerBytesSent||0,totalPacketSendDelay:k.totalPacketSendDelay||0};if(k.mediaType==="video"||k.kind==="video"){const D=k,et=B({frameHeight:D.frameHeight,frameWidth:D.frameWidth,framesEncoded:D.framesEncoded,framesDropped:D.framesDropped,framesPerSecond:D.framesPerSecond,framesSent:D.framesSent,keyFramesEncoded:D.keyFramesEncoded,firCount:D.firCount,encoderImplementation:D.encoderImplementation,hugeFramesSent:D.hugeFramesSent,pliCount:D.pliCount,qpSum:D.qpSum,qualityLimitationDurations:D.qualityLimitationDurations,qualityLimitationReason:D.qualityLimitationReason,qualityLimitationResolutionChanges:D.qualityLimitationResolutionChanges,totalEncodeTime:D.targetBitrate,totalPacketSendDelay:D.totalPacketSendDelay,retransmittedBytesSent:D.retransmittedBytesSent,retransmittedPacketsSent:D.retransmittedPacketsSent,scalabilityMode:D.scalabilityMode,powerEfficientEncoder:D.powerEfficientEncoder},V);P.outboundVideoRtp.set(O.id,et),P.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,Ae,et)}else if(k.mediaType==="audio"||k.kind==="audio"){const D=k,et=B({retransmittedBytesSent:D.retransmittedBytesSent,retransmittedPacketsSent:D.retransmittedPacketsSent},V);P.outboundAudioRtp.set(O.id,et),P.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,Ae,et)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=O,R=i||this.inboundConsumerMap.get(O.id),H=this.pausedConsumerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ae=this.overallConsumersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(O.id)){P.staleConsumerStreamMap=!0;break}P.consumerStreamMap.has(R)||P.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ze={bytesReceived:k.bytesReceived,packetsReceived:k.packetsReceived,packetsLost:k.packetsLost>=0?k.packetsLost:0,jitter:k.jitter,nackCount:k.nackCount,jitterBufferDelay:k.jitterBufferDelay,jitterBufferEmittedCount:k.jitterBufferEmittedCount,lastPacketReceivedTimestamp:k.lastPacketReceivedTimestamp,ssrc:k.ssrc,mid:k.mid,codecId:k.codecId,headerBytesReceived:k.headerBytesReceived||0,packetsDiscarded:k.packetsDiscarded||0,jitterBufferMinimumDelay:k.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:k.jitterBufferTargetDelay||0};if(k.mediaType==="video"||k.kind==="video"){const V=k,D=B({frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder},Ze);D.score=Wf({frameWidth:D.frameWidth||0,framesDecoded:(D.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(R))==null?void 0:a.framesDecoded)||0),framesPerSecond:D.framesPerSecond||0,packetsLost:(D.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(R))==null?void 0:d.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(R))==null?void 0:h.packetsReceived)||0),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),Tt.set(R,{score:+(D.score*10).toFixed(),frameWidth:D.frameWidth||0,frameHeight:D.frameHeight||0,framesPerSecond:D.framesPerSecond||0,packetsLostPercentage:Pc({packetsLost:(D.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(R))==null?void 0:p.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((m=this.videoConsumerToStatsMap.get(R))==null?void 0:m.packetsReceived)||0)}),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((D.bytesReceived||0)-(((g=this.videoConsumerToStatsMap.get(R))==null?void 0:g.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,D),P.inboundVideoRtp.set(O.id,D),P.consumerStreamMap.get(R).inboundVideoRtpId.push(O.id),this.processInboundConsumerVideoStats(R,Ae,D)}else if(k.mediaType==="audio"||k.kind==="audio"){const V=k,D=B({audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId},Ze);D.score=Hf({concealmentEvents:(D.concealmentEvents||0)-(((v=this.audioConsumerToStatsMap.get(R))==null?void 0:v.concealmentEvents)||0),packetsLost:(D.packetsLost||0)-(((_=this.audioConsumerToStatsMap.get(R))==null?void 0:_.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((A=this.audioConsumerToStatsMap.get(R))==null?void 0:A.packetsReceived)||0),jitter:D.jitter||0}),Tt.set(R,{score:+(D.score*10).toFixed(),packetsLostPercentage:Pc({packetsLost:(D.packetsLost||0)-(((C=this.audioConsumerToStatsMap.get(R))==null?void 0:C.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(R))==null?void 0:M.packetsReceived)||0)}),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((D.bytesReceived||0)-(((N=this.audioConsumerToStatsMap.get(R))==null?void 0:N.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,D),P.inboundAudioRtp.set(O.id,D),P.consumerStreamMap.get(R).inboundAudioRtpId.push(O.id),this.processInboundConsumerAudioStats(R,Ae,D)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(P.producerStreamMap.forEach((O,k)=>{var R,H,Ae,Ze,V,D,et,Ar,ws,Is,Cs,Ps,Rs,As,Ms,Ds,Os,Ns,Ls,xs,Us,Fs,Vs;if(O.outboundVideoRtpId.length>0){const be=[];O.outboundVideoRtpId.forEach(Ad=>{be.push(P.outboundVideoRtp.get(Ad))});const he=this.getWorkingSimulcastVideoStats(be);he.score=Bf({frameWidth:he.frameWidth||0,framesPerSecond:he.framesPerSecond||0,jitter:((R=he.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(he.packetsSent||0)-(((H=this.videoProducerToStatsMap.get(k))==null?void 0:H.packetsSent)||0),packetsLost:(((Ae=he.remoteData)==null?void 0:Ae.packetsLost)||0)-(((V=(Ze=this.videoProducerToStatsMap.get(k))==null?void 0:Ze.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((D=this.videoProducerToStatsMap.get(k))==null?void 0:D.framesEncoded)||0)}),Ne.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((et=he.remoteData)==null?void 0:et.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:Cc({packetsSent:(he.packetsSent||0)-(((Ar=this.videoProducerToStatsMap.get(k))==null?void 0:Ar.packetsSent)||0),packetsLost:(((ws=he.remoteData)==null?void 0:ws.packetsLost)||0)-(((Cs=(Is=this.videoProducerToStatsMap.get(k))==null?void 0:Is.remoteData)==null?void 0:Cs.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((Ps=this.videoProducerToStatsMap.get(k))==null?void 0:Ps.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const be=P.outboundAudioRtp.get(O.outboundAudioRtpId[0]);be.score=Vf({packetsSent:(be.packetsSent||0)-(((Rs=this.audioProducerToStatsMap.get(k))==null?void 0:Rs.packetsSent)||0),packetsLost:(((As=be.remoteData)==null?void 0:As.packetsLost)||0)-(((Ds=(Ms=this.audioProducerToStatsMap.get(k))==null?void 0:Ms.remoteData)==null?void 0:Ds.packetsLost)||0),jitter:((Os=be.remoteData)==null?void 0:Os.jitter)||0}),Ne.set(k,{score:+(be.score*10).toFixed(),bitrate:((be.bytesSent||0)-(((Ns=this.audioProducerToStatsMap.get(k))==null?void 0:Ns.bytesSent)||0))*8/7,packetsLostPercentage:Cc({packetsSent:(be.packetsSent||0)-(((Ls=this.audioProducerToStatsMap.get(k))==null?void 0:Ls.packetsSent)||0),packetsLost:(((xs=be.remoteData)==null?void 0:xs.packetsLost)||0)-(((Fs=(Us=this.audioProducerToStatsMap.get(k))==null?void 0:Us.remoteData)==null?void 0:Fs.packetsLost)||0)}),jitter:((Vs=be.remoteData)==null?void 0:Vs.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,be)}}),se.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=ae.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=Nn(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=Nn(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=Nn(R.address),O.remoteCandidatePort=R.port,O.remoteCandidateProtocol=R.protocol,O.remoteCandidateUrl=R.url)}),P.candidatePair&&(P.transport?(P.transport.totalRoundTripTime=P.candidatePair.totalRoundTripTime,P.transport.availableOutgoingBitrate=P.candidatePair.availableOutgoingBitrate,P.transport.availableIncomingBitrate=P.candidatePair.availableIncomingBitrate,P.transport.roundTripTime=P.candidatePair.currentRoundTripTime):P.transport={bytesReceived:P.candidatePair.bytesReceived,bytesSent:P.candidatePair.bytesSent,totalRoundTripTime:P.candidatePair.totalRoundTripTime,availableOutgoingBitrate:P.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:P.candidatePair.availableIncomingBitrate,roundTripTime:P.candidatePair.currentRoundTripTime}),P.transport&&(P.transport.candidatePairs=se),P.transport&&!P.transport.roundTripTime){let O=0,k=0;P.remoteInboundRtp.forEach((R,H)=>{R.roundTripTime&&R.roundTripTime>O&&(O=R.roundTripTime,k=R.totalRoundTripTime)}),P.transport.roundTripTime=O,P.transport.totalRoundTripTime=k}if(Tt.size>0)try{this.observer.emit("consumer_score",Tt)}catch{}if(Ne.size>0)try{this.observer.emit("producer_score",Ne)}catch{}return P}getProducersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getConsumersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,r,n){return u(this,null,function*(){const i=yield this.getTransportReport(e),s={producing:n,consuming:r,id:e.id},o=i,a=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!a)return;const d={stats:a.transport,transportId:e.id,consuming:r,producing:n},h=a.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(a),p=a.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(a);return{transportReport:d,producerReport:h,consumerReport:p}})}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var s,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(a=>e.outboundVideoRtp.get(a)),audioStats:n.outboundAudioRtpId.map(a=>e.outboundAudioRtp.get(a)),appData:((o=(s=this.callStatsInstance.producers)==null?void 0:s.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:s,producerId:o,appData:a,videoStats:n.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:n.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}getUserLocation(){return u(this,null,function*(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const r={iceServers:e||Oh},n=new Promise((h,p)=>{try{const m=new yE(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),i=new Promise((h,p)=>{try{const m=new SE(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),s=new Promise((h,p)=>{try{const m=new EE(r);m.addListener("done",h),m.addListener("failed",()=>{h({connectivity:!1})}),m.start(2e3)}catch(m){p(m)}}),[o,a,d]=yield Promise.all([n,i,s]);return{host:o==null?void 0:o.connectivity,relay:a==null?void 0:a.connectivity,reflexive:d==null?void 0:d.connectivity}}catch{return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const r=yield new Promise((n,i)=>{try{const s={iceServers:e||Oh},o=new vE(s);o.addListener("done",n),o.addListener("failed",i),o.start(1e4)}catch(s){i(s)}});return{throughput:r.throughput,fractionalLoss:0,RTT:r.RTT,jitter:0,backendRTT:r.backendRTT}}catch{return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield Cu.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch{return}})}getNetworkQuality(e){return u(this,null,function*(){const[r,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}})}getNetworkInfo(e,r=!1){return u(this,null,function*(){var n,i;if(r){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d!=null&&d.loc?Nh(d==null?void 0:d.loc):void 0}}const[s,o,a]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:a!=null&&a.loc?Nh(a==null?void 0:a.loc):void 0,turnConnectivity:s?s.host||s.relay||s.reflexive:!1,connectivity:s,throughput:o==null?void 0:o.throughput,fractionalLoss:o==null?void 0:o.fractionalLoss,RTT:o==null?void 0:o.RTT,jitter:o==null?void 0:o.jitter,backendRTT:o==null?void 0:o.backendRTT}})}}class kE extends Gf{}class qf extends Gf{constructor(){super(...arguments),f(this,"producerMap",new Map),f(this,"consumerMap",new Map)}registerProducer(e){return u(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return u(this,null,function*(){this.consumerMap.set(e.id,e),yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,s,e.id):void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return o})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,m,g,v,_,A,C,M,N;const J=e,P=new Jf,G=r.length?new Set(r):void 0,W=[],ae=[],se=[],Ne=new Map,Tt=new Map;for(const O of J.values()){if(G){if(G.size===0)break;if(G.has(O.type))n&&G.delete(O.type);else continue}switch(O.type){case"local-candidate":{W.push(this.getIceCandidateStats(O));break}case"remote-candidate":{ae.push(this.getIceCandidateStats(O));break}case"candidate-pair":{const{nominated:k}=O,{selected:R}=O,H=O,Ae={nominated:k!=null?k:R,currentRoundTripTime:H.currentRoundTripTime,totalRoundTripTime:H.totalRoundTripTime,bytesReceived:H.bytesReceived,bytesSent:H.bytesSent,availableOutgoingBitrate:H.availableOutgoingBitrate,availableIncomingBitrate:H.availableIncomingBitrate,lastPacketReceivedTimestamp:H.lastPacketReceivedTimestamp,lastPacketSentTimestamp:H.lastPacketSentTimestamp,localCandidateId:H.localCandidateId,remoteCandidateId:H.remoteCandidateId,bytesDiscardedOnSend:H.bytesDiscardedOnSend,packetsSent:H.packetsSent,packetsReceived:H.packetsReceived,packetsDiscardedOnSend:H.packetsDiscardedOnSend};se.push(Ae),(O.nominated===!0||O.selected===!0)&&(P.candidatePair=Ae);break}case"transport":{const k=O;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const R={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(P.transport=R,s){if(s.producing){const H=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,H,R)}if(s.consuming){const H=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,H,R)}}break}case"remote-inbound-rtp":{const k=O,R={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};P.remoteInboundRtp.set(k.localId,R);break}case"outbound-rtp":{const k=O,R=i||this.outboundProducerMap.get(O.id),H=this.pausedProducerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedProducerMap.set(R,{lastReportCalculated:!0})}this.overallProducersStatsMap[R]||(this.overallProducersStatsMap[R]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ae=this.overallProducersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(O.id)){P.staleProducerStreamMap=!0;break}const Ze=this.callStatsInstance.producers.get(R);if(((o=Ze==null?void 0:Ze.track)==null?void 0:o.readyState)==="ended")break;P.producerStreamMap.has(R)||P.producerStreamMap.set(R,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={bytesSent:k.bytesSent,packetsSent:k.packetsSent,nackCount:k.nackCount,ssrc:k.ssrc,mid:k.mid,active:k.active,codecId:k.codecId,headerBytesSent:k.headerBytesSent||0,totalPacketSendDelay:k.totalPacketSendDelay||0};if(k.mediaType==="video"||k.kind==="video"){const D=k,et=B({frameHeight:D.frameHeight,frameWidth:D.frameWidth,framesEncoded:D.framesEncoded,framesDropped:D.framesDropped?D.framesDropped:D.droppedFrames,framesPerSecond:D.framesPerSecond?D.framesPerSecond:D.framerateMean,framesSent:D.framesSent,keyFramesEncoded:D.keyFramesEncoded,firCount:D.firCount,encoderImplementation:D.encoderImplementation,hugeFramesSent:D.hugeFramesSent,pliCount:D.pliCount,qpSum:D.qpSum,qualityLimitationReason:D.qualityLimitationReason,qualityLimitationDurations:D.qualityLimitationDurations,qualityLimitationResolutionChanges:D.qualityLimitationResolutionChanges,totalEncodeTime:D.totalEncodeTime,totalPacketSendDelay:D.totalEncodeTime,retransmittedBytesSent:D.retransmittedBytesSent,retransmittedPacketsSent:D.retransmittedPacketsSent,scalabilityMode:D.scalabilityMode,powerEfficientEncoder:D.powerEfficientEncoder},V);P.outboundVideoRtp.set(O.id,et),P.producerStreamMap.get(R).outboundVideoRtpId.push(O.id),this.processOutboundProducerVideoStats(R,Ae,et)}else if(k.mediaType==="audio"||k.kind==="audio"){const D=k,et=B({retransmittedBytesSent:D.retransmittedBytesSent,retransmittedPacketsSent:D.retransmittedPacketsSent},V);P.outboundAudioRtp.set(O.id,et),P.producerStreamMap.get(R).outboundAudioRtpId.push(O.id),this.processOutboundProducerAudioStats(R,Ae,et)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=O,R=i||this.inboundConsumerMap.get(O.id),H=this.pausedConsumerMap.get(R);if(H){if(H.lastReportCalculated===!0)break;this.pausedConsumerMap.set(R,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[R]||(this.overallConsumersStatsMap[R]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ae=this.overallConsumersStatsMap[R];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(O.id)){P.staleConsumerStreamMap=!0;break}P.consumerStreamMap.has(R)||P.consumerStreamMap.set(R,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ze={bytesReceived:k.bytesReceived,packetsReceived:k.packetsReceived,packetsLost:k.packetsLost>=0?k.packetsLost:0,jitter:k.jitter,nackCount:k.nackCount,jitterBufferDelay:k.jitterBufferDelay,jitterBufferEmittedCount:k.jitterBufferEmittedCount,lastPacketReceivedTimestamp:k.lastPacketReceivedTimestamp,ssrc:k.ssrc,mid:k.mid,codecId:k.codecId,headerBytesReceived:k.headerBytesReceived||0,packetsDiscarded:k.packetsDiscarded||0,jitterBufferMinimumDelay:k.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:k.jitterBufferTargetDelay||0};if(k.mediaType==="video"||k.kind==="video"){const V=k,D=B({frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder},Ze);D.score=Wf({frameWidth:D.frameWidth||0,framesDecoded:(D.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(R))==null?void 0:a.framesDecoded)||0),framesPerSecond:D.framesPerSecond||0,packetsLost:(D.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(R))==null?void 0:d.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(R))==null?void 0:h.packetsReceived)||0),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R)}),Tt.set(R,{score:+(D.score*10).toFixed(),frameWidth:D.frameWidth||0,frameHeight:D.frameHeight||0,framesPerSecond:D.framesPerSecond||0,packetsLostPercentage:Pc({packetsLost:(D.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(R))==null?void 0:p.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((m=this.videoConsumerToStatsMap.get(R))==null?void 0:m.packetsReceived)||0)}),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((D.bytesReceived||0)-(((g=this.videoConsumerToStatsMap.get(R))==null?void 0:g.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(R,D),P.inboundVideoRtp.set(O.id,D),P.consumerStreamMap.get(R).inboundVideoRtpId.push(O.id),this.processInboundConsumerVideoStats(R,Ae,D)}else if(k.mediaType==="audio"||k.kind==="audio"){const V=k,D=B({audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId},Ze);D.score=Hf({concealmentEvents:(D.concealmentEvents||0)-(((v=this.audioConsumerToStatsMap.get(R))==null?void 0:v.concealmentEvents)||0),packetsLost:(D.packetsLost||0)-(((_=this.audioConsumerToStatsMap.get(R))==null?void 0:_.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((A=this.audioConsumerToStatsMap.get(R))==null?void 0:A.packetsReceived)||0),jitter:D.jitter||0}),Tt.set(R,{score:+(D.score*10).toFixed(),packetsLostPercentage:Pc({packetsLost:(D.packetsLost||0)-(((C=this.audioConsumerToStatsMap.get(R))==null?void 0:C.packetsLost)||0),packetsReceived:(D.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(R))==null?void 0:M.packetsReceived)||0)}),jitter:D.jitter||0,isScreenShare:this.screenShareConsumers.has(R),bitrate:((D.bytesReceived||0)-(((N=this.audioConsumerToStatsMap.get(R))==null?void 0:N.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(R,D),P.inboundAudioRtp.set(O.id,D),P.consumerStreamMap.get(R).inboundAudioRtpId.push(O.id),this.processInboundConsumerAudioStats(R,Ae,D)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(P.producerStreamMap.forEach((O,k)=>{var R,H,Ae,Ze,V,D,et,Ar,ws,Is,Cs,Ps,Rs,As,Ms,Ds,Os,Ns,Ls,xs,Us,Fs,Vs;if(O.outboundVideoRtpId.length>0){const be=[];O.outboundVideoRtpId.forEach(Ad=>{be.push(P.outboundVideoRtp.get(Ad))});const he=this.getWorkingSimulcastVideoStats(be);he.score=Bf({frameWidth:he.frameWidth||0,framesPerSecond:he.framesPerSecond||0,jitter:((R=he.remoteData)==null?void 0:R.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(he.packetsSent||0)-(((H=this.videoProducerToStatsMap.get(k))==null?void 0:H.packetsSent)||0),packetsLost:(((Ae=he.remoteData)==null?void 0:Ae.packetsLost)||0)-(((V=(Ze=this.videoProducerToStatsMap.get(k))==null?void 0:Ze.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(he.framesEncoded||0)-(((D=this.videoProducerToStatsMap.get(k))==null?void 0:D.framesEncoded)||0)}),Ne.set(k,{score:+(he.score*10).toFixed(),frameWidth:he.frameWidth||0,frameHeight:he.frameHeight||0,framesPerSecond:he.framesPerSecond||0,jitter:((et=he.remoteData)==null?void 0:et.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:Cc({packetsSent:(he.packetsSent||0)-(((Ar=this.videoProducerToStatsMap.get(k))==null?void 0:Ar.packetsSent)||0),packetsLost:(((ws=he.remoteData)==null?void 0:ws.packetsLost)||0)-(((Cs=(Is=this.videoProducerToStatsMap.get(k))==null?void 0:Is.remoteData)==null?void 0:Cs.packetsLost)||0)}),bitrate:((he.bytesSent||0)-(((Ps=this.videoProducerToStatsMap.get(k))==null?void 0:Ps.bytesSent)||0))*8/7,cpuLimitations:he.qualityLimitationReason==="cpu",bandwidthLimitations:he.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,he)}else if(O.outboundAudioRtpId.length>0){const be=P.outboundAudioRtp.get(O.outboundAudioRtpId[0]);be.score=Vf({packetsSent:(be.packetsSent||0)-(((Rs=this.audioProducerToStatsMap.get(k))==null?void 0:Rs.packetsSent)||0),packetsLost:(((As=be.remoteData)==null?void 0:As.packetsLost)||0)-(((Ds=(Ms=this.audioProducerToStatsMap.get(k))==null?void 0:Ms.remoteData)==null?void 0:Ds.packetsLost)||0),jitter:((Os=be.remoteData)==null?void 0:Os.jitter)||0}),Ne.set(k,{score:+(be.score*10).toFixed(),bitrate:((be.bytesSent||0)-(((Ns=this.audioProducerToStatsMap.get(k))==null?void 0:Ns.bytesSent)||0))*8/7,packetsLostPercentage:Cc({packetsSent:(be.packetsSent||0)-(((Ls=this.audioProducerToStatsMap.get(k))==null?void 0:Ls.packetsSent)||0),packetsLost:(((xs=be.remoteData)==null?void 0:xs.packetsLost)||0)-(((Fs=(Us=this.audioProducerToStatsMap.get(k))==null?void 0:Us.remoteData)==null?void 0:Fs.packetsLost)||0)}),jitter:((Vs=be.remoteData)==null?void 0:Vs.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,be)}}),se.forEach(O=>{const k=W.find(H=>H.id===O.localCandidateId?(O.localCandidateId=H.id,H):null),R=ae.find(H=>H.id===O.remoteCandidateId?(O.remoteCandidateId=H.id,H):null);k&&(O.localCandidateType=k.type,O.localCandidateAddress=Nn(k.address),O.localCandidatePort=k.port,O.localCandidateProtocol=k.protocol,O.localCandidateUrl=k.url,O.localCandidateNetworkType=k.networkType,O.localCandidateRelatedAddress=Nn(k.relatedAddress),O.localCandidateRelatedPort=k.relatedPort),R&&(O.remoteCandidateType=R.type,O.remoteCandidateAddress=Nn(R.address),O.remoteCandidatePort=R.port,O.remoteCandidateProtocol=R.protocol,O.remoteCandidateUrl=R.url)}),P.candidatePair&&(P.transport?(P.transport.bytesReceived=P.candidatePair.bytesReceived,P.transport.bytesSent=P.candidatePair.bytesSent,P.transport.totalRoundTripTime=P.candidatePair.totalRoundTripTime,P.transport.availableOutgoingBitrate=P.candidatePair.availableOutgoingBitrate,P.transport.availableIncomingBitrate=P.candidatePair.availableIncomingBitrate,P.transport.roundTripTime=P.candidatePair.currentRoundTripTime):P.transport={bytesReceived:P.candidatePair.bytesReceived,bytesSent:P.candidatePair.bytesSent,totalRoundTripTime:P.candidatePair.totalRoundTripTime,availableOutgoingBitrate:P.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:P.candidatePair.availableIncomingBitrate,roundTripTime:P.candidatePair.currentRoundTripTime}),P.transport&&(P.transport.candidatePairs=se),P.transport&&!P.transport.roundTripTime){let O=0,k=0;P.remoteInboundRtp.forEach((R,H)=>{R.roundTripTime&&R.roundTripTime>O&&(O=R.roundTripTime,k=R.totalRoundTripTime)}),P.transport.roundTripTime=O,P.transport.totalRoundTripTime=k}if(Tt.size>0)try{this.observer.emit("consumer_score",Tt)}catch{}if(Ne.size>0)try{this.observer.emit("producer_score",Ne)}catch{}return P}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const s=this.producerMap.get(i),o=s.track.getSettings(),a=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),d={producerId:i,appData:s.appData,videoStats:a,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(n),d=r==null?void 0:r.inboundVideoRtpId.map(h=>{const p=this.consumerMap.get(n).track.getSettings(),m=e.inboundVideoRtp.get(h);return m.frameHeight||(m.frameHeight=p.height,m.frameWidth=p.width,m.framesPerSecond=p.frameRate),m});i={consumerId:n,peerId:s,producerId:o,appData:a,videoStats:d,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class _E extends qf{}function Rc(t,e,r,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof r=="function"&&n instanceof e)r.call(null,n,t);else throw n}function Lh(t,e,r){const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{Rc(this,e,r,o)}):s}catch(s){Rc(this,e,r,s)}return null},t}const re=(t,e)=>(r,n,i)=>{const s=i.value;return i.value=function(...o){try{const a=s.apply(this,o);return a&&a instanceof Promise?a.catch(d=>{Rc(this,t,e,d)}):a}catch(a){Rc(this,t,e,a)}return null},i},bE=(t,e)=>(r,n,i)=>{if(i)return Lh(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);o.value instanceof Function&&Object.defineProperty(r.prototype,s,Lh(o,t,e))}};var ee=globalThis&&globalThis.__decorate||function(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};const te=console;let Y=class extends ft{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=Vo.PROD,n,i,s,o){switch(super(),f(this,"observer"),f(this,"eventHandler"),f(this,"measurements"),f(this,"producingTransport"),f(this,"consumingTransport"),f(this,"producers",new Map),f(this,"consumers",new Map),f(this,"iceServers"),f(this,"connectionInfoPromise"),f(this,"pingStatsTimeout"),f(this,"logger"),f(this,"env"),f(this,"apiHostnames"),f(this,"peerId"),f(this,"consumerSharedMediaStatesMap",new Map),f(this,"currentUserMediaStates",{}),this.env=r,this.apiHostnames=o,this.logger=i,this.peerId=s,this.eventHandler=new cE({logger:i,peerId:s,apiHostnames:o}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new kE;break;case"Gecko":this.measurements=new qf;break;case"WebKit":this.measurements=new _E;break;default:throw Error(`Unknown engineName! ${e}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new ft,this.measurements.observer.on("consumer_score",a=>{i.debug(`callStats::consumer_score ${[...a.entries()]}`),this.eventHandler.emit("consumer_score",a)}),this.measurements.observer.on("producer_score",a=>{i.debug(`callStats::producer_score ${[...a.entries()]}`),this.eventHandler.emit("producer_score",a)})}registerIceServers(t){this.iceServers=t}registerConsumer(t){var e;this.consumerSharedMediaStatesMap.has(t.id)||this.consumerSharedMediaStatesMap.set(t.id,{}),this.consumers.set(t.id,t),this.measurements.registerConsumer(t),this.logger.debug("callStats::registerConsumer",{consumerId:t.id,consumerkind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterConsumer.bind(this,t))}registerProducer(t){var e;this.producers.set(t.id,t),this.measurements.registerProducer(t),this.logger.debug("callStats::registerProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const r=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(r,e))}registerProducingTransport(t){var e;this.producingTransport=t,t.observer.on("close",this.disconnectProducingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectProducingTransport.bind(this,t)),Array.from(((e=t._producers)==null?void 0:e.values())||[]).forEach(r=>{this.registerProducer(r)}),t.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(t){var e;this.consumingTransport=t,t.observer.on("close",this.disconnectConsumingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,t)),Array.from(((e=t._consumers)==null?void 0:e.values())||[]).forEach(r=>{this.registerConsumer(r)}),t.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(t){this.consumers.delete(t.id)}deRegisterProducer(t){var e;this.producers.delete(t.id),this.logger.debug("callStats::deRegisterProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(t){this.eventHandler.callEvent(t)}sendPreCallTestBeginEvent(t=!1,e){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,t),this.eventHandler.callEvent({event:F.PRECALL_TEST_BEGIN,timestamp:e}),this.connectionInfoPromise&&this.connectionInfoPromise.then(r=>{this.eventHandler.callEvent({event:F.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:r},timestamp:e})})}sendScreenShareToggleEvent(t,e=null,r){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?F.SCREENSHARE_STARTED:F.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:r})}sendScreenShareRequestedEvent(t){this.eventHandler.callEvent({event:F.SCREENSHARE_START_REQUESTED,timestamp:t})}sendActiveSpeakerEvent(t,e){this.eventHandler.callEvent({event:F.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:e})}devices(t,e,r){this.eventHandler.callEvent({event:t===tr.AUDIO&&F.AUDIO_DEVICES_UPDATES||t===tr.VIDEO&&F.VIDEO_DEVICES_UPDATES||t===tr.SPEAKER&&F.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:r})}selectedDevice(t,e,r){this.eventHandler.callEvent({event:t===tr.AUDIO&&F.SELECTED_MICROHPONE_UPDATE||t===tr.VIDEO&&F.SELECTED_CAMERA_UPDATE||t===tr.SPEAKER&&F.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:r})}mediaPermission(t,e,r){this.eventHandler.callEvent({event:F.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:r})}mediaPlaybackFailed(t,e){this.eventHandler.callEvent({event:t===tr.AUDIO&&F.AUDIO_PLAY_FAILED||t===tr.VIDEO&&F.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===tr.AUDIO&&F.AUDIO_TRACK_MUTED||t===tr.VIDEO&&F.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:e})}tabChanged(t,e){this.eventHandler.callEvent({event:F.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:e})}browserBackgrounded(t){this.eventHandler.callEvent({event:F.BROWSER_BACKGROUNDED,timestamp:t})}browserForegrounded(t){this.eventHandler.callEvent({event:F.BROWSER_FOREGROUNDED,timestamp:t})}legacySwitch(t,e){this.eventHandler.callEvent({event:F.LEGACY_SWITCH,metadata:{on:t},timestamp:e})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t,e){t=Z(B({},t),{meetingEnv:this.env}),t.deviceInfo=Z(B({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:F.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:e})}sendNetworkQualityTestBeginEvent(t,e){this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_BEGIN,timestamp:e}),new Promise((r,n)=>u(this,null,function*(){const i=[];try{for(const s of t)try{if(s.iceServers&&s.iceServers.length>0){const o=yield this.measurements.getNetworkQuality(s.iceServers);i.push(Z(B({},s),{networkResults:o}))}}catch(o){console.warn("Error handling ",o)}r({regionData:i})}catch(s){console.warn("Error in callstats, ",s),n(s)}})).then(r=>{this.eventHandler.callEvent({event:F.NET_QUALITY_TEST_END,timestamp:e,metaData:r})})}sendWebSocketConnectedEvent(t){this.eventHandler.callEvent({event:F.WEBSOCKET_CONNECTED,timestamp:t})}sendTransportConnectedEvent(t){this.eventHandler.callEvent({event:F.TRANSPORT_CONNECTED,timestamp:t})}sendAudioToggleEvent(t,e){this.currentUserMediaStates.audio=t;let r;t?r=F.AUDIO_ON:r=F.AUDIO_OFF,this.eventHandler.callEvent({event:r,timestamp:e})}sendVideoToggleEvent(t,e){this.currentUserMediaStates.video=t;let r;t?r=F.VIDEO_ON:r=F.VIDEO_OFF,this.eventHandler.callEvent({event:r,timestamp:e})}sendParticipantRoleToggleEvent(t,e){this.eventHandler.callEvent({event:F.PARTICIPANT_ROLE,timestamp:e,metaData:t})}startPingStats(t=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),t)}stopPingStats(){clearInterval(this.pingStatsTimeout)}sendPingStatsEvent(t=!0,e){return u(this,null,function*(){let r,n;if(this.producingTransport&&(r=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!r||!(r!=null&&r.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const s=yield this.measurements.getProducersReport([...this.producers.values()]);r&&s?r.producerReport=s:(r=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!r||!(r!=null&&r.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!n.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const s=yield this.measurements.getConsumersReport([...this.consumers.values()]);n&&s?n.consumerReport=s:(n=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const i={producingTransportStats:r?r==null?void 0:r.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((r==null?void 0:r.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((r==null?void 0:r.consumerReport)||[])};if(t&&i.producerStats.length===0&&i.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:F.PING_STAT,metaData:i,timestamp:e})})}sendIVSPlayerRebufferEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_REBUFFERING,timestamp:t})}sendIVSPlayerAudioBlockEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_AUDIO_BLOCKED,timestamp:t})}sendIVSPlayerPlaybackBlockedEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:t})}sendIVSPlayerNetworkUnavailableEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:t})}sendIVSPlayerInitializedEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_INITIALIZED,timestamp:t})}sendIVSPlayerWorkerErrorEvent(t){this.eventHandler.callEvent({event:F.IVS_PLAYER_WORKER_ERROR,timestamp:t})}sendIVSPlayerErrorEvent(t,e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ERROR,timestamp:e,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t,e){this.eventHandler.callEvent({event:F.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:e,metaData:t})}sendIVSPlayerAnalyticsEvent(t,e){this.eventHandler.callEvent({event:F.IVS_PLAYER_ANALYTICS_EVENT,timestamp:e,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t,e){this.eventHandler.callEvent({event:F.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:e,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t,e){this.eventHandler.callEvent({event:F.IVS_PLAYER_QUALITY_CHANGED,timestamp:e,metaData:t})}sendPlayerLiveLatency(t,e){this.eventHandler.callEvent({event:F.LIVESTREAM_LATENCY,timestamp:e,metaData:{latency:t}})}sendDisconnectEvent(t){this.eventHandler.callEvent({event:F.DISCONNECT,timestamp:t})}sendReconnectEvent(t){this.eventHandler.callEvent({event:F.RECONNECT_ATTEMPT,timestamp:t})}expectedVideoResolution(t,e,r){this.eventHandler.callEvent({event:F.EXPECTED_VIDEO_RESOLUTION,timestamp:r,metaData:{frameWidth:t,frameHeight:e}})}expectedScreenshareResolution(t,e,r){this.eventHandler.callEvent({event:F.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:r,metaData:{frameWidth:t,frameHeight:e}})}};ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerIceServers",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerConsumer",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerProducer",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendConsumerSharedMediaStateEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerProducingTransport",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"registerConsumingTransport",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"deRegisterConsumer",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"deRegisterProducer",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"disconnectConsumingTransport",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"disconnectProducingTransport",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPreCallTestBeginEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendScreenShareToggleEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendScreenShareRequestedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendActiveSpeakerEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"devices",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"selectedDevice",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaPermission",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaPlaybackFailed",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"mediaTrackMuted",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"tabChanged",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"browserBackgrounded",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"browserForegrounded",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"legacySwitch",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"getPreCallTestResults",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendCallJoinBeginEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendNetworkQualityTestBeginEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendWebSocketConnectedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendTransportConnectedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendAudioToggleEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendVideoToggleEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendParticipantRoleToggleEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"startPingStats",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"stopPingStats",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPingStatsEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerRebufferEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerAudioBlockEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackBlockedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerNetworkUnavailableEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerInitializedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerWorkerErrorEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerErrorEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerRecoverableErrorEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerAnalyticsEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendIVSPlayerQualityChanged",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendPlayerLiveLatency",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendDisconnectEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"sendReconnectEvent",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"expectedVideoResolution",null);ee([re(TypeError,(t,e)=>te.error(e,t))],Y.prototype,"expectedScreenshareResolution",null);Y=ee([bE(TypeError,(t,e)=>te.error(e,t))],Y);const wE=Y;class IE extends ft{constructor(){super(...arguments),f(this,"stats"),f(this,"peerId"),f(this,"backend"),f(this,"iceServers"),f(this,"initialized",!1),f(this,"stalled",!1),f(this,"ipInformation"),f(this,"logger")}initialize(e){return u(this,arguments,function*({peerId:r,engineName:n,env:i=Vo.PROD,iceServers:s,apiBase:o="https://api.cluster.dyte.in",flags:a,logger:d=console,apiHostnames:h,skipConnectivityChecks:p=!1}){var m,g,v;try{this.peerId=r,this.logger=d,this.ipInformation=yield Cu.getIPDetails({peerId:r,apiHostnames:h,logger:d}),this.backend=new wE(o,n,i,a,d,r,h),this.iceServers=s,(m=this.backend)==null||m.registerIceServers(this.iceServers),this.initialized=!0,(v=(g=this.backend)==null?void 0:g.eventHandler)==null||v.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(_){this.logger.error("callStats::CallStatsIntegration: ",{error:_}),this.stallCallStats()}})}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n;try{(n=this.backend)==null||n.sendNetworkQualityTestBeginEvent(e,r)}catch(i){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:i.reason}})}})})}roomJoined(e){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n,i;(n=this.backend)==null||n.sendCallJoinBeginEvent(e,r),this.backend,(i=this.backend)==null||i.startPingStats()})})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,n;(r=this.backend)==null||r.stopPingStats(),(n=this.backend)==null||n.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendActiveSpeakerEvent(e,r)})}devices(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.devices(e,r,n)})}selectedDevice(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.selectedDevice(e,r,n)})}mediaPermission(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPermission(e,r,n)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.legacySwitch(e,r)})}startPreCallTest(e=!1){return u(this,null,function*(){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPreCallTestBeginEvent(e,r)})})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const n=new Date;this.onSafeInitialization(()=>{var i,s,o,a,d,h,p,m,g,v,_;switch(e){case"PlayerRebuffering":(i=this.backend)==null||i.sendIVSPlayerRebufferEvent(n);break;case"PlayerAudioBlocked":(s=this.backend)==null||s.sendIVSPlayerAudioBlockEvent(n);break;case"PlayerPlaybackBlocked":(o=this.backend)==null||o.sendIVSPlayerPlaybackBlockedEvent(n);break;case"PlayerNetworkUnavailable":(a=this.backend)==null||a.sendIVSPlayerNetworkUnavailableEvent(n);break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent(n);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(n);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(r,n);break;case"PlayerRecoverableError":(m=this.backend)==null||m.sendIVSPlayerRecoverableErrorEvent(r,n);break;case"PlayerAnalyticsEvent":(g=this.backend)==null||g.sendIVSPlayerAnalyticsEvent(r,n);break;case"PlayerPlaybackRateChanged":(v=this.backend)==null||v.sendIVSPlayerPlaybackRateChangedEvent(r,n);break;case"PlayerQualityChanged":(_=this.backend)==null||_.sendIVSPlayerQualityChanged(r,n);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.expectedVideoResolution(e,r,n)})}expectedScreenshareResolution(e,r){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.expectedScreenshareResolution(e,r,n)})}}const $=new IE;$.setMaxListeners(30);function CE(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}Array.prototype.at||Object.assign(Array.prototype,{at:CE});function PE(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}String.prototype.at||Object.assign(String.prototype,{at:PE});var Dl={},RE={get exports(){return Dl},set exports(t){Dl=t}},Ac={},AE={get exports(){return Ac},set exports(t){Ac=t}},zf=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},ME=zf,Vn=Object.prototype.toString;function Pu(t){return Array.isArray(t)}function Ol(t){return typeof t=="undefined"}function DE(t){return t!==null&&!Ol(t)&&t.constructor!==null&&!Ol(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function Kf(t){return Vn.call(t)==="[object ArrayBuffer]"}function OE(t){return Vn.call(t)==="[object FormData]"}function NE(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Kf(t.buffer),e}function LE(t){return typeof t=="string"}function xE(t){return typeof t=="number"}function Yf(t){return t!==null&&typeof t=="object"}function qa(t){if(Vn.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function UE(t){return Vn.call(t)==="[object Date]"}function FE(t){return Vn.call(t)==="[object File]"}function VE(t){return Vn.call(t)==="[object Blob]"}function Qf(t){return Vn.call(t)==="[object Function]"}function BE(t){return Yf(t)&&Qf(t.pipe)}function jE(t){return Vn.call(t)==="[object URLSearchParams]"}function HE(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function WE(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function Ru(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Pu(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function Nl(){var t={};function e(i,s){qa(t[s])&&qa(i)?t[s]=Nl(t[s],i):qa(i)?t[s]=Nl({},i):Pu(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)Ru(arguments[r],e);return t}function $E(t,e,r){return Ru(e,function(n,i){r&&typeof n=="function"?t[i]=ME(n,r):t[i]=n}),t}function JE(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var Vt={isArray:Pu,isArrayBuffer:Kf,isBuffer:DE,isFormData:OE,isArrayBufferView:NE,isString:LE,isNumber:xE,isObject:Yf,isPlainObject:qa,isUndefined:Ol,isDate:UE,isFile:FE,isBlob:VE,isFunction:Qf,isStream:BE,isURLSearchParams:jE,isStandardBrowserEnv:WE,forEach:Ru,merge:Nl,extend:$E,trim:HE,stripBOM:JE},Oi=Vt;function xh(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Xf=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(Oi.isURLSearchParams(e))n=e.toString();else{var i=[];Oi.forEach(e,function(o,a){o===null||typeof o=="undefined"||(Oi.isArray(o)?a=a+"[]":o=[o],Oi.forEach(o,function(d){Oi.isDate(d)?d=d.toISOString():Oi.isObject(d)&&(d=JSON.stringify(d)),i.push(xh(a)+"="+xh(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},GE=Vt;function cd(){this.handlers=[]}cd.prototype.use=function(t,e,r){return this.handlers.push({fulfilled:t,rejected:e,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1};cd.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)};cd.prototype.forEach=function(t){GE.forEach(this.handlers,function(e){e!==null&&t(e)})};var qE=cd,zE=Vt,KE=function(t,e){zE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},Zf=function(t,e,r,n,i){return t.config=e,r&&(t.code=r),t.request=n,t.response=i,t.isAxiosError=!0,t.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}},t},xd,Uh;function eg(){if(Uh)return xd;Uh=1;var t=Zf;return xd=function(e,r,n,i,s){var o=new Error(e);return t(o,r,n,i,s)},xd}var Ud,Fh;function YE(){if(Fh)return Ud;Fh=1;var t=eg();return Ud=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(t("Request failed with status code "+n.status,n.config,null,n.request,n))},Ud}var Fd,Vh;function QE(){if(Vh)return Fd;Vh=1;var t=Vt;return Fd=t.isStandardBrowserEnv()?function(){return{write:function(e,r,n,i,s,o){var a=[];a.push(e+"="+encodeURIComponent(r)),t.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),t.isString(i)&&a.push("path="+i),t.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var r=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Fd}var Bh,jh;function XE(){return jh||(jh=1,Bh=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),Bh}var Hh,Wh;function ZE(){return Wh||(Wh=1,Hh=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),Hh}var Vd,$h;function eT(){if($h)return Vd;$h=1;var t=XE(),e=ZE();return Vd=function(r,n){return r&&!t(n)?e(r,n):n},Vd}var Bd,Jh;function tT(){if(Jh)return Bd;Jh=1;var t=Vt,e=["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"];return Bd=function(r){var n={},i,s,o;return r&&t.forEach(r.split(`
24
+ `),function(a){if(o=a.indexOf(":"),i=t.trim(a.substr(0,o)).toLowerCase(),s=t.trim(a.substr(o+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([s]):n[i]=n[i]?n[i]+", "+s:s}}),n},Bd}var jd,Gh;function rT(){if(Gh)return jd;Gh=1;var t=Vt;return jd=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{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 n=i(window.location.href),function(s){var o=t.isString(s)?i(s):s;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),jd}var Hd,qh;function dd(){if(qh)return Hd;qh=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,Hd=t,Hd}var Wd,zh;function nT(){if(zh)return Wd;zh=1;var t=Vt,e=YE(),r=QE(),n=Xf,i=eT(),s=tT(),o=rT(),a=eg(),d=ld(),h=dd();return Wd=function(p){return new Promise(function(m,g){var v=p.data,_=p.headers,A=p.responseType,C;function M(){p.cancelToken&&p.cancelToken.unsubscribe(C),p.signal&&p.signal.removeEventListener("abort",C)}t.isFormData(v)&&delete _["Content-Type"];var N=new XMLHttpRequest;if(p.auth){var J=p.auth.username||"",P=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";_.Authorization="Basic "+btoa(J+":"+P)}var G=i(p.baseURL,p.url);N.open(p.method.toUpperCase(),n(G,p.params,p.paramsSerializer),!0),N.timeout=p.timeout;function W(){if(N){var se="getAllResponseHeaders"in N?s(N.getAllResponseHeaders()):null,Ne=!A||A==="text"||A==="json"?N.responseText:N.response,Tt={data:Ne,status:N.status,statusText:N.statusText,headers:se,config:p,request:N};e(function(O){m(O),M()},function(O){g(O),M()},Tt),N=null}}if("onloadend"in N?N.onloadend=W:N.onreadystatechange=function(){!N||N.readyState!==4||N.status===0&&!(N.responseURL&&N.responseURL.indexOf("file:")===0)||setTimeout(W)},N.onabort=function(){N&&(g(a("Request aborted",p,"ECONNABORTED",N)),N=null)},N.onerror=function(){g(a("Network Error",p,null,N)),N=null},N.ontimeout=function(){var se=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",Ne=p.transitional||d.transitional;p.timeoutErrorMessage&&(se=p.timeoutErrorMessage),g(a(se,p,Ne.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",N)),N=null},t.isStandardBrowserEnv()){var ae=(p.withCredentials||o(G))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;ae&&(_[p.xsrfHeaderName]=ae)}"setRequestHeader"in N&&t.forEach(_,function(se,Ne){typeof v=="undefined"&&Ne.toLowerCase()==="content-type"?delete _[Ne]:N.setRequestHeader(Ne,se)}),t.isUndefined(p.withCredentials)||(N.withCredentials=!!p.withCredentials),A&&A!=="json"&&(N.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&N.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&N.upload&&N.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(C=function(se){N&&(g(!se||se&&se.type?new h("canceled"):se),N.abort(),N=null)},p.cancelToken&&p.cancelToken.subscribe(C),p.signal&&(p.signal.aborted?C():p.signal.addEventListener("abort",C))),v||(v=null),N.send(v)})},Wd}var $d,Kh;function ld(){if(Kh)return $d;Kh=1;var t=Vt,e=KE,r=Zf,n={"Content-Type":"application/x-www-form-urlencoded"};function i(d,h){!t.isUndefined(d)&&t.isUndefined(d["Content-Type"])&&(d["Content-Type"]=h)}function s(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=nT()),d}function o(d,h,p){if(t.isString(d))try{return(h||JSON.parse)(d),t.trim(d)}catch(m){if(m.name!=="SyntaxError")throw m}return(p||JSON.stringify)(d)}var a={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:s(),transformRequest:[function(d,h){return e(h,"Accept"),e(h,"Content-Type"),t.isFormData(d)||t.isArrayBuffer(d)||t.isBuffer(d)||t.isStream(d)||t.isFile(d)||t.isBlob(d)?d:t.isArrayBufferView(d)?d.buffer:t.isURLSearchParams(d)?(i(h,"application/x-www-form-urlencoded;charset=utf-8"),d.toString()):t.isObject(d)||h&&h["Content-Type"]==="application/json"?(i(h,"application/json"),o(d)):d}],transformResponse:[function(d){var h=this.transitional||a.transitional,p=h&&h.silentJSONParsing,m=h&&h.forcedJSONParsing,g=!p&&this.responseType==="json";if(g||m&&t.isString(d)&&d.length)try{return JSON.parse(d)}catch(v){if(g)throw v.name==="SyntaxError"?r(v,this,"E_JSON_PARSE"):v}return d}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(d){return d>=200&&d<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return t.forEach(["delete","get","head"],function(d){a.headers[d]={}}),t.forEach(["post","put","patch"],function(d){a.headers[d]=t.merge(n)}),$d=a,$d}var iT=Vt,sT=ld(),oT=function(t,e,r){var n=this||sT;return iT.forEach(r,function(i){t=i.call(n,t,e)}),t},Yh,Qh;function tg(){return Qh||(Qh=1,Yh=function(t){return!!(t&&t.__CANCEL__)}),Yh}var Xh=Vt,Jd=oT,aT=tg(),cT=ld(),dT=dd();function Gd(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new dT("canceled")}var lT=function(t){Gd(t),t.headers=t.headers||{},t.data=Jd.call(t,t.data,t.headers,t.transformRequest),t.headers=Xh.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Xh.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||cT.adapter;return e(t).then(function(r){return Gd(t),r.data=Jd.call(t,r.data,r.headers,t.transformResponse),r},function(r){return aT(r)||(Gd(t),r&&r.response&&(r.response.data=Jd.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},Ht=Vt,rg=function(t,e){e=e||{};var r={};function n(h,p){return Ht.isPlainObject(h)&&Ht.isPlainObject(p)?Ht.merge(h,p):Ht.isPlainObject(p)?Ht.merge({},p):Ht.isArray(p)?p.slice():p}function i(h){if(Ht.isUndefined(e[h])){if(!Ht.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function s(h){if(!Ht.isUndefined(e[h]))return n(void 0,e[h])}function o(h){if(Ht.isUndefined(e[h])){if(!Ht.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function a(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var d={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return Ht.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var p=d[h]||i,m=p(h);Ht.isUndefined(m)&&p!==a||(r[h]=m)}),r},Zh,ep;function ng(){return ep||(ep=1,Zh={version:"0.25.0"}),Zh}var uT=ng().version,Au={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){Au[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var tp={};Au.transitional=function(t,e,r){function n(i,s){return"[Axios v"+uT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return function(i,s,o){if(t===!1)throw new Error(n(s," has been removed"+(e?" in "+e:"")));return e&&!tp[s]&&(tp[s]=!0,console.warn(n(s," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,s,o):!0}};function hT(t,e,r){if(typeof t!="object")throw new TypeError("options must be an object");for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],o=e[s];if(o){var a=t[s],d=a===void 0||o(a,s,t);if(d!==!0)throw new TypeError("option "+s+" must be "+d);continue}if(r!==!0)throw Error("Unknown option "+s)}}var pT={assertOptions:hT,validators:Au},ig=Vt,mT=Xf,rp=qE,np=lT,ud=rg,sg=pT,Ni=sg.validators;function Yo(t){this.defaults=t,this.interceptors={request:new rp,response:new rp}}Yo.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=ud(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&sg.assertOptions(r,{silentJSONParsing:Ni.transitional(Ni.boolean),forcedJSONParsing:Ni.transitional(Ni.boolean),clarifyTimeoutError:Ni.transitional(Ni.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(e)===!1||(i=i&&m.synchronous,n.unshift(m.fulfilled,m.rejected))});var s=[];this.interceptors.response.forEach(function(m){s.push(m.fulfilled,m.rejected)});var o;if(!i){var a=[np,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(s),o=Promise.resolve(e);a.length;)o=o.then(a.shift(),a.shift());return o}for(var d=e;n.length;){var h=n.shift(),p=n.shift();try{d=h(d)}catch(m){p(m);break}}try{o=np(d)}catch(m){return Promise.reject(m)}for(;s.length;)o=o.then(s.shift(),s.shift());return o};Yo.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=ud(this.defaults,t),mT(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")};ig.forEach(["delete","get","head","options"],function(t){Yo.prototype[t]=function(e,r){return this.request(ud(r||{},{method:t,url:e,data:(r||{}).data}))}});ig.forEach(["post","put","patch"],function(t){Yo.prototype[t]=function(e,r,n){return this.request(ud(n||{},{method:t,url:e,data:r}))}});var fT=Yo,qd,ip;function gT(){if(ip)return qd;ip=1;var t=dd();function e(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(s){n=s});var i=this;this.promise.then(function(s){if(i._listeners){var o,a=i._listeners.length;for(o=0;o<a;o++)i._listeners[o](s);i._listeners=null}}),this.promise.then=function(s){var o,a=new Promise(function(d){i.subscribe(d),o=d}).then(s);return a.cancel=function(){i.unsubscribe(o)},a},r(function(s){i.reason||(i.reason=new t(s),n(i.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(r){if(this.reason){r(this.reason);return}this._listeners?this._listeners.push(r):this._listeners=[r]},e.prototype.unsubscribe=function(r){if(this._listeners){var n=this._listeners.indexOf(r);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var r,n=new e(function(i){r=i});return{token:n,cancel:r}},qd=e,qd}var sp,op;function vT(){return op||(op=1,sp=function(t){return function(e){return t.apply(null,e)}}),sp}var zd,ap;function yT(){if(ap)return zd;ap=1;var t=Vt;return zd=function(e){return t.isObject(e)&&e.isAxiosError===!0},zd}var cp=Vt,ST=zf,za=fT,ET=rg,TT=ld();function og(t){var e=new za(t),r=ST(za.prototype.request,e);return cp.extend(r,za.prototype,e),cp.extend(r,e),r.create=function(n){return og(ET(t,n))},r}var Pr=og(TT);Pr.Axios=za;Pr.Cancel=dd();Pr.CancelToken=gT();Pr.isCancel=tg();Pr.VERSION=ng().version;Pr.all=function(t){return Promise.all(t)};Pr.spread=vT();Pr.isAxiosError=yT();AE.exports=Pr;Ac.default=Pr;(function(t){t.exports=Ac})(RE);const Mc=XS(Dl);function kT(){this.__data__=[],this.size=0}function Qo(t,e){return t===e||t!==t&&e!==e}function hd(t,e){for(var r=t.length;r--;)if(Qo(t[r][0],e))return r;return-1}var _T=Array.prototype,bT=_T.splice;function wT(t){var e=this.__data__,r=hd(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():bT.call(e,r,1),--this.size,!0}function IT(t){var e=this.__data__,r=hd(e,t);return r<0?void 0:e[r][1]}function CT(t){return hd(this.__data__,t)>-1}function PT(t,e){var r=this.__data__,n=hd(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function nn(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}nn.prototype.clear=kT;nn.prototype.delete=wT;nn.prototype.get=IT;nn.prototype.has=CT;nn.prototype.set=PT;function RT(){this.__data__=new nn,this.size=0}function AT(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function MT(t){return this.__data__.get(t)}function DT(t){return this.__data__.has(t)}var OT=typeof global=="object"&&global&&global.Object===Object&&global;const ag=OT;var NT=typeof self=="object"&&self&&self.Object===Object&&self,LT=ag||NT||Function("return this")();const vr=LT;var xT=vr.Symbol;const xn=xT;var cg=Object.prototype,UT=cg.hasOwnProperty,FT=cg.toString,js=xn?xn.toStringTag:void 0;function VT(t){var e=UT.call(t,js),r=t[js];try{t[js]=void 0;var n=!0}catch{}var i=FT.call(t);return n&&(e?t[js]=r:delete t[js]),i}var BT=Object.prototype,jT=BT.toString;function HT(t){return jT.call(t)}var WT="[object Null]",$T="[object Undefined]",dp=xn?xn.toStringTag:void 0;function Ii(t){return t==null?t===void 0?$T:WT:dp&&dp in Object(t)?VT(t):HT(t)}function gr(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var JT="[object AsyncFunction]",GT="[object Function]",qT="[object GeneratorFunction]",zT="[object Proxy]";function Mu(t){if(!gr(t))return!1;var e=Ii(t);return e==GT||e==qT||e==JT||e==zT}var KT=vr["__core-js_shared__"];const Kd=KT;var lp=function(){var t=/[^.]+$/.exec(Kd&&Kd.keys&&Kd.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function YT(t){return!!lp&&lp in t}var QT=Function.prototype,XT=QT.toString;function Ci(t){if(t!=null){try{return XT.call(t)}catch{}try{return t+""}catch{}}return""}var ZT=/[\\^$.*+?()[\]{}|]/g,e0=/^\[object .+?Constructor\]$/,t0=Function.prototype,r0=Object.prototype,n0=t0.toString,i0=r0.hasOwnProperty,s0=RegExp("^"+n0.call(i0).replace(ZT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function o0(t){if(!gr(t)||YT(t))return!1;var e=Mu(t)?s0:e0;return e.test(Ci(t))}function a0(t,e){return t==null?void 0:t[e]}function Pi(t,e){var r=a0(t,e);return o0(r)?r:void 0}var c0=Pi(vr,"Map");const $o=c0;var d0=Pi(Object,"create");const Jo=d0;function l0(){this.__data__=Jo?Jo(null):{},this.size=0}function u0(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var h0="__lodash_hash_undefined__",p0=Object.prototype,m0=p0.hasOwnProperty;function f0(t){var e=this.__data__;if(Jo){var r=e[t];return r===h0?void 0:r}return m0.call(e,t)?e[t]:void 0}var g0=Object.prototype,v0=g0.hasOwnProperty;function y0(t){var e=this.__data__;return Jo?e[t]!==void 0:v0.call(e,t)}var S0="__lodash_hash_undefined__";function E0(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Jo&&e===void 0?S0:e,this}function Si(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Si.prototype.clear=l0;Si.prototype.delete=u0;Si.prototype.get=f0;Si.prototype.has=y0;Si.prototype.set=E0;function T0(){this.size=0,this.__data__={hash:new Si,map:new($o||nn),string:new Si}}function k0(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function pd(t,e){var r=t.__data__;return k0(e)?r[typeof e=="string"?"string":"hash"]:r.map}function _0(t){var e=pd(this,t).delete(t);return this.size-=e?1:0,e}function b0(t){return pd(this,t).get(t)}function w0(t){return pd(this,t).has(t)}function I0(t,e){var r=pd(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function Ri(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Ri.prototype.clear=T0;Ri.prototype.delete=_0;Ri.prototype.get=b0;Ri.prototype.has=w0;Ri.prototype.set=I0;var C0=200;function P0(t,e){var r=this.__data__;if(r instanceof nn){var n=r.__data__;if(!$o||n.length<C0-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Ri(n)}return r.set(t,e),this.size=r.size,this}function wr(t){var e=this.__data__=new nn(t);this.size=e.size}wr.prototype.clear=RT;wr.prototype.delete=AT;wr.prototype.get=MT;wr.prototype.has=DT;wr.prototype.set=P0;function R0(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var A0=function(){try{var t=Pi(Object,"defineProperty");return t({},"",{}),t}catch{}}();const Dc=A0;function Du(t,e,r){e=="__proto__"&&Dc?Dc(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var M0=Object.prototype,D0=M0.hasOwnProperty;function dg(t,e,r){var n=t[e];(!(D0.call(t,e)&&Qo(n,r))||r===void 0&&!(e in t))&&Du(t,e,r)}function Xo(t,e,r,n){var i=!r;r||(r={});for(var s=-1,o=e.length;++s<o;){var a=e[s],d=n?n(r[a],t[a],a,r,t):void 0;d===void 0&&(d=t[a]),i?Du(r,a,d):dg(r,a,d)}return r}function O0(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function Cr(t){return t!=null&&typeof t=="object"}var N0="[object Arguments]";function up(t){return Cr(t)&&Ii(t)==N0}var lg=Object.prototype,L0=lg.hasOwnProperty,x0=lg.propertyIsEnumerable,U0=up(function(){return arguments}())?up:function(t){return Cr(t)&&L0.call(t,"callee")&&!x0.call(t,"callee")};const Oc=U0;var F0=Array.isArray;const Un=F0;function V0(){return!1}var ug=typeof exports=="object"&&exports&&!exports.nodeType&&exports,hp=ug&&typeof module=="object"&&module&&!module.nodeType&&module,B0=hp&&hp.exports===ug,pp=B0?vr.Buffer:void 0,j0=pp?pp.isBuffer:void 0,H0=j0||V0;const us=H0;var W0=9007199254740991,$0=/^(?:0|[1-9]\d*)$/;function hg(t,e){var r=typeof t;return e=e==null?W0:e,!!e&&(r=="number"||r!="symbol"&&$0.test(t))&&t>-1&&t%1==0&&t<e}var J0=9007199254740991;function pg(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=J0}var G0="[object Arguments]",q0="[object Array]",z0="[object Boolean]",K0="[object Date]",Y0="[object Error]",Q0="[object Function]",X0="[object Map]",Z0="[object Number]",ek="[object Object]",tk="[object RegExp]",rk="[object Set]",nk="[object String]",ik="[object WeakMap]",sk="[object ArrayBuffer]",ok="[object DataView]",ak="[object Float32Array]",ck="[object Float64Array]",dk="[object Int8Array]",lk="[object Int16Array]",uk="[object Int32Array]",hk="[object Uint8Array]",pk="[object Uint8ClampedArray]",mk="[object Uint16Array]",fk="[object Uint32Array]",Oe={};Oe[ak]=Oe[ck]=Oe[dk]=Oe[lk]=Oe[uk]=Oe[hk]=Oe[pk]=Oe[mk]=Oe[fk]=!0;Oe[G0]=Oe[q0]=Oe[sk]=Oe[z0]=Oe[ok]=Oe[K0]=Oe[Y0]=Oe[Q0]=Oe[X0]=Oe[Z0]=Oe[ek]=Oe[tk]=Oe[rk]=Oe[nk]=Oe[ik]=!1;function gk(t){return Cr(t)&&pg(t.length)&&!!Oe[Ii(t)]}function Ou(t){return function(e){return t(e)}}var mg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Bo=mg&&typeof module=="object"&&module&&!module.nodeType&&module,vk=Bo&&Bo.exports===mg,Yd=vk&&ag.process,yk=function(){try{var t=Bo&&Bo.require&&Bo.require("util").types;return t||Yd&&Yd.binding&&Yd.binding("util")}catch{}}();const hs=yk;var mp=hs&&hs.isTypedArray,Sk=mp?Ou(mp):gk;const md=Sk;var Ek=Object.prototype,Tk=Ek.hasOwnProperty;function fg(t,e){var r=Un(t),n=!r&&Oc(t),i=!r&&!n&&us(t),s=!r&&!n&&!i&&md(t),o=r||n||i||s,a=o?O0(t.length,String):[],d=a.length;for(var h in t)(e||Tk.call(t,h))&&!(o&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||hg(h,d)))&&a.push(h);return a}var kk=Object.prototype;function fd(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||kk;return t===r}function gg(t,e){return function(r){return t(e(r))}}var _k=gg(Object.keys,Object);const bk=_k;var wk=Object.prototype,Ik=wk.hasOwnProperty;function vg(t){if(!fd(t))return bk(t);var e=[];for(var r in Object(t))Ik.call(t,r)&&r!="constructor"&&e.push(r);return e}function Zo(t){return t!=null&&pg(t.length)&&!Mu(t)}function Nu(t){return Zo(t)?fg(t):vg(t)}function Ck(t,e){return t&&Xo(e,Nu(e),t)}function Pk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var Rk=Object.prototype,Ak=Rk.hasOwnProperty;function Mk(t){if(!gr(t))return Pk(t);var e=fd(t),r=[];for(var n in t)n=="constructor"&&(e||!Ak.call(t,n))||r.push(n);return r}function ea(t){return Zo(t)?fg(t,!0):Mk(t)}function Dk(t,e){return t&&Xo(e,ea(e),t)}var yg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,fp=yg&&typeof module=="object"&&module&&!module.nodeType&&module,Ok=fp&&fp.exports===yg,gp=Ok?vr.Buffer:void 0,vp=gp?gp.allocUnsafe:void 0;function Sg(t,e){if(e)return t.slice();var r=t.length,n=vp?vp(r):new t.constructor(r);return t.copy(n),n}function Eg(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function Nk(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r<n;){var o=t[r];e(o,r,t)&&(s[i++]=o)}return s}function Tg(){return[]}var Lk=Object.prototype,xk=Lk.propertyIsEnumerable,yp=Object.getOwnPropertySymbols,Uk=yp?function(t){return t==null?[]:(t=Object(t),Nk(yp(t),function(e){return xk.call(t,e)}))}:Tg;const Lu=Uk;function Fk(t,e){return Xo(t,Lu(t),e)}function kg(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var Vk=gg(Object.getPrototypeOf,Object);const xu=Vk;var Bk=Object.getOwnPropertySymbols,jk=Bk?function(t){for(var e=[];t;)kg(e,Lu(t)),t=xu(t);return e}:Tg;const _g=jk;function Hk(t,e){return Xo(t,_g(t),e)}function bg(t,e,r){var n=e(t);return Un(t)?n:kg(n,r(t))}function Ll(t){return bg(t,Nu,Lu)}function Wk(t){return bg(t,ea,_g)}var $k=Pi(vr,"DataView");const xl=$k;var Jk=Pi(vr,"Promise");const Ul=Jk;var Gk=Pi(vr,"Set");const Fl=Gk;var qk=Pi(vr,"WeakMap");const Vl=qk;var Sp="[object Map]",zk="[object Object]",Ep="[object Promise]",Tp="[object Set]",kp="[object WeakMap]",_p="[object DataView]",Kk=Ci(xl),Yk=Ci($o),Qk=Ci(Ul),Xk=Ci(Fl),Zk=Ci(Vl),ei=Ii;(xl&&ei(new xl(new ArrayBuffer(1)))!=_p||$o&&ei(new $o)!=Sp||Ul&&ei(Ul.resolve())!=Ep||Fl&&ei(new Fl)!=Tp||Vl&&ei(new Vl)!=kp)&&(ei=function(t){var e=Ii(t),r=e==zk?t.constructor:void 0,n=r?Ci(r):"";if(n)switch(n){case Kk:return _p;case Yk:return Sp;case Qk:return Ep;case Xk:return Tp;case Zk:return kp}return e});const ps=ei;var e_=Object.prototype,t_=e_.hasOwnProperty;function r_(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&t_.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var n_=vr.Uint8Array;const Nc=n_;function Uu(t){var e=new t.constructor(t.byteLength);return new Nc(e).set(new Nc(t)),e}function i_(t,e){var r=e?Uu(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var s_=/\w*$/;function o_(t){var e=new t.constructor(t.source,s_.exec(t));return e.lastIndex=t.lastIndex,e}var bp=xn?xn.prototype:void 0,wp=bp?bp.valueOf:void 0;function a_(t){return wp?Object(wp.call(t)):{}}function wg(t,e){var r=e?Uu(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var c_="[object Boolean]",d_="[object Date]",l_="[object Map]",u_="[object Number]",h_="[object RegExp]",p_="[object Set]",m_="[object String]",f_="[object Symbol]",g_="[object ArrayBuffer]",v_="[object DataView]",y_="[object Float32Array]",S_="[object Float64Array]",E_="[object Int8Array]",T_="[object Int16Array]",k_="[object Int32Array]",__="[object Uint8Array]",b_="[object Uint8ClampedArray]",w_="[object Uint16Array]",I_="[object Uint32Array]";function C_(t,e,r){var n=t.constructor;switch(e){case g_:return Uu(t);case c_:case d_:return new n(+t);case v_:return i_(t,r);case y_:case S_:case E_:case T_:case k_:case __:case b_:case w_:case I_:return wg(t,r);case l_:return new n;case u_:case m_:return new n(t);case h_:return o_(t);case p_:return new n;case f_:return a_(t)}}var Ip=Object.create,P_=function(){function t(){}return function(e){if(!gr(e))return{};if(Ip)return Ip(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const R_=P_;function Ig(t){return typeof t.constructor=="function"&&!fd(t)?R_(xu(t)):{}}var A_="[object Map]";function M_(t){return Cr(t)&&ps(t)==A_}var Cp=hs&&hs.isMap,D_=Cp?Ou(Cp):M_;const O_=D_;var N_="[object Set]";function L_(t){return Cr(t)&&ps(t)==N_}var Pp=hs&&hs.isSet,x_=Pp?Ou(Pp):L_;const U_=x_;var F_=1,V_=2,B_=4,Cg="[object Arguments]",j_="[object Array]",H_="[object Boolean]",W_="[object Date]",$_="[object Error]",Pg="[object Function]",J_="[object GeneratorFunction]",G_="[object Map]",q_="[object Number]",Rg="[object Object]",z_="[object RegExp]",K_="[object Set]",Y_="[object String]",Q_="[object Symbol]",X_="[object WeakMap]",Z_="[object ArrayBuffer]",eb="[object DataView]",tb="[object Float32Array]",rb="[object Float64Array]",nb="[object Int8Array]",ib="[object Int16Array]",sb="[object Int32Array]",ob="[object Uint8Array]",ab="[object Uint8ClampedArray]",cb="[object Uint16Array]",db="[object Uint32Array]",Pe={};Pe[Cg]=Pe[j_]=Pe[Z_]=Pe[eb]=Pe[H_]=Pe[W_]=Pe[tb]=Pe[rb]=Pe[nb]=Pe[ib]=Pe[sb]=Pe[G_]=Pe[q_]=Pe[Rg]=Pe[z_]=Pe[K_]=Pe[Y_]=Pe[Q_]=Pe[ob]=Pe[ab]=Pe[cb]=Pe[db]=!0;Pe[$_]=Pe[Pg]=Pe[X_]=!1;function Ka(t,e,r,n,i,s){var o,a=e&F_,d=e&V_,h=e&B_;if(r&&(o=i?r(t,n,i,s):r(t)),o!==void 0)return o;if(!gr(t))return t;var p=Un(t);if(p){if(o=r_(t),!a)return Eg(t,o)}else{var m=ps(t),g=m==Pg||m==J_;if(us(t))return Sg(t,a);if(m==Rg||m==Cg||g&&!i){if(o=d||g?{}:Ig(t),!a)return d?Hk(t,Dk(o,t)):Fk(t,Ck(o,t))}else{if(!Pe[m])return i?t:{};o=C_(t,m,a)}}s||(s=new wr);var v=s.get(t);if(v)return v;s.set(t,o),U_(t)?t.forEach(function(C){o.add(Ka(C,e,r,C,t,s))}):O_(t)&&t.forEach(function(C,M){o.set(M,Ka(C,e,r,M,t,s))});var _=h?d?Wk:Ll:d?ea:Nu,A=p?void 0:_(t);return R0(A||t,function(C,M){A&&(M=C,C=t[M]),dg(o,M,Ka(C,e,r,M,t,s))}),o}var lb=1,ub=4;function Fu(t){return Ka(t,lb|ub)}var hb="[object Symbol]";function pb(t){return typeof t=="symbol"||Cr(t)&&Ii(t)==hb}var mb=Object.defineProperty,fb=(t,e)=>{for(var r in e)mb(t,r,{get:e[r],enumerable:!0})},gb={};fb(gb,{permissions:()=>vb,theme:()=>yb});var vt=(t=>(t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT",t))(vt||{}),K=(t=>(t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST",t))(K||{}),vb={view_type:"GROUP_CALL",accept_waiting_requests:!1,accept_present_requests:!1,request_produce:!1,can_allow_participant_audio:!1,can_allow_participant_screensharing:!1,can_allow_participant_video:!1,can_spotlight:!1,request_kick_participant:!1,kick_participant:!1,pin_participant:!1,can_edit_display_name:!1,can_record:!1,can_livestream:!1,can_present:!0,waiting_room_type:"SKIP_ON_ACCEPT",recorder_type:"NONE",plugins:{can_close:!0,can_start:!0},polls:{can_create:!0,can_vote:!0,can_view:!0},produce:{video:{allow:!0,quality:"vga",frame_rate:24},audio:!0,screenshare:{allow:!0,quality:"hd",frame_rate:5}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},reactions:!1,hidden_participant:!1,is_recorder:!1,show_participant_list:!0,can_change_participant_role:!1,can_change_theme:!1,max_screenshare_count:1},yb={setup_screen:{is_enabled:!0},alone_here:{is_enabled:!0},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!0,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"multi"},controls:{pip_toggle:!1}},Ag="hXgU8Wc8pwuGNq9ms5q9Hh",Rp;typeof process!="undefined"&&(Rp=process==null?void 0:process.env)!=null&&Rp.FLAGSMITH_ENVIRONMENT_KEY&&(Ag={}.FLAGSMITH_ENVIRONMENT_KEY);function Sb(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}var Eb=class{constructor(t=Ag){f(this,"flags",{}),f(this,"environmentKey",null),this.environmentKey=t,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}identify(t){return u(this,arguments,function*(e,r={},n=!1,i=5e3,s="edge.api.flagsmith.com"){const o=JSON.parse(JSON.stringify(r)),a=Object.entries(o).map(d=>({trait_key:d[0],trait_value:d[1]}));try{const d="_"+(Math.random()+1).toString(36).substring(2),h=yield Mc.post(`https://${s}/api/v1/identities/`,{identifier:e+(n?d:""),traits:a},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:i});this.flags=Sb(h.data.flags||[])}catch{}return this.flags})}getValue(t){return this.flags&&this.flags[t]&&this.flags[t].value}hasFeature(t){return this.flags&&this.flags[t]&&this.flags[t].enabled}getAllFlags(){return this.flags}},Q=new Eb,Mg=[-2,-1,0,1,2],Tb=[0,1,2,3,4];function kb(t){t=t.trim();let e="0",r="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],r="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],r="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+r,+n]}var _b=(t,e,r)=>{let n,i,s;if(e==0)n=i=s=r;else{const o=(h,p,m)=>(m<0&&(m+=1),m>1&&(m-=1),m<.16666666666666666?h+(p-h)*6*m:m<.5?p:m<.6666666666666666?h+(p-h)*(.6666666666666666-m)*6:h),a=r<.5?r*(1+e):r+e-r*e,d=2*r-a;n=o(d,a,t+1/3),i=o(d,a,t),s=o(d,a,t-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(s*255)]},bb=(t,e,r)=>{t/=255,e/=255,r/=255;const n=Math.max(t,e,r),i=Math.min(t,e,r);let s,o;const a=(n+i)/2;if(n==i)s=o=0;else{const d=n-i;switch(o=a>.5?d/(2-n-i):d/(n+i),n){case t:s=(e-r)/d+(e<r?6:0);break;case e:s=(r-t)/d+2;break;case r:s=(t-e)/d+4;break}s/=6}return[s,o,a]},wb=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},Dg=(t,e=Mg,r=.4)=>{const n=[],[i,s,o]=kb(t),[a,d,h]=bb(i,s,o),p=Math.round(h*100);p>70?r=.8:p>60?r=.9:p<10?r=.075:p<42&&(r=.3);const m=e.findIndex(C=>C===0);if(m===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-m,v=m+1,_=(100-p)/g,A=p/v;for(const C of e){let M;C<0?M=p+C*A*r:C>0?M=p+C*_*r:M=p;const[N,J,P]=_b(a,d,M/100);n.push(wb(N,J,P))}return n},Ap={dark:{background:{1e3:"#252525",900:"#2F2F2F",800:"#323232",700:"#3E3E3E",600:"#4A4A4A"},text:"#F5F5F5","video-bg":"#1C1C1C"},light:{background:{1e3:"#FFFFFF",900:"#F5F5F5",800:"#EBEBEB",700:"#E0E0E0",600:"#D6D6D6"},text:"#111111","text-on-brand":"#ffffff","video-bg":"#DADADA"}},Ib=t=>{const[e,r,n,i,s]=Dg(t,Mg);return{300:e,400:r,500:n,600:i,700:s}},Cb=t=>{if(t==="#FFFFFF")return Ap.light.background;if(t==="#000000")return Ap.dark.background;const[e,r,n,i,s]=Dg(t,Tb);return{1e3:e,900:r,800:n,700:i,600:s}},Pb={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:Ib("#2160FD"),background:Cb("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Og(){return Fu(Pb)}var Rb={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:Og(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"hybrid"};function Ab(){return Fu(Rb)}var Mb={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:Og(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"2.0.0"};function Vu(){return Fu(Mb)}var Db=/\s/;function Ob(t){for(var e=t.length;e--&&Db.test(t.charAt(e)););return e}var Nb=/^\s+/;function Lb(t){return t&&t.slice(0,Ob(t)+1).replace(Nb,"")}var Mp=0/0,xb=/^[-+]0x[0-9a-f]+$/i,Ub=/^0b[01]+$/i,Fb=/^0o[0-7]+$/i,Vb=parseInt;function Dp(t){if(typeof t=="number")return t;if(pb(t))return Mp;if(gr(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=gr(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Lb(t);var r=Ub.test(t);return r||Fb.test(t)?Vb(t.slice(2),r?2:8):xb.test(t)?Mp:+t}function Ng(t){return t}function Bb(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var jb=800,Hb=16,Wb=Date.now;function $b(t){var e=0,r=0;return function(){var n=Wb(),i=Hb-(n-r);if(r=n,i>0){if(++e>=jb)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function Jb(t){return function(){return t}}var Gb=Dc?function(t,e){return Dc(t,"toString",{configurable:!0,enumerable:!1,value:Jb(e),writable:!0})}:Ng;const qb=Gb;var zb=$b(qb);const Kb=zb;var Op=Math.max;function Yb(t,e,r){return e=Op(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=Op(n.length-e,0),o=Array(s);++i<s;)o[i]=n[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=n[i];return a[e]=r(o),Bb(t,this,a)}}function Qb(t,e){return Kb(Yb(t,e,Ng),t+"")}function Xb(t,e,r){if(!gr(r))return!1;var n=typeof e;return(n=="number"?Zo(r)&&hg(e,r.length):n=="string"&&e in r)?Qo(r[e],t):!1}function Zb(t){return Qb(function(e,r){var n=-1,i=r.length,s=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&Xb(r[0],r[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++n<i;){var a=r[n];a&&t(e,a,n,s)}return e})}var ew="[object Object]",tw=Function.prototype,rw=Object.prototype,Lg=tw.toString,nw=rw.hasOwnProperty,iw=Lg.call(Object);function sw(t){if(!Cr(t)||Ii(t)!=ew)return!1;var e=xu(t);if(e===null)return!0;var r=nw.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&Lg.call(r)==iw}var ow="__lodash_hash_undefined__";function aw(t){return this.__data__.set(t,ow),this}function cw(t){return this.__data__.has(t)}function Lc(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new Ri;++e<r;)this.add(t[e])}Lc.prototype.add=Lc.prototype.push=aw;Lc.prototype.has=cw;function dw(t,e){for(var r=-1,n=t==null?0:t.length;++r<n;)if(e(t[r],r,t))return!0;return!1}function lw(t,e){return t.has(e)}var uw=1,hw=2;function xg(t,e,r,n,i,s){var o=r&uw,a=t.length,d=e.length;if(a!=d&&!(o&&d>a))return!1;var h=s.get(t),p=s.get(e);if(h&&p)return h==e&&p==t;var m=-1,g=!0,v=r&hw?new Lc:void 0;for(s.set(t,e),s.set(e,t);++m<a;){var _=t[m],A=e[m];if(n)var C=o?n(A,_,m,e,t,s):n(_,A,m,t,e,s);if(C!==void 0){if(C)continue;g=!1;break}if(v){if(!dw(e,function(M,N){if(!lw(v,N)&&(_===M||i(_,M,r,n,s)))return v.push(N)})){g=!1;break}}else if(!(_===A||i(_,A,r,n,s))){g=!1;break}}return s.delete(t),s.delete(e),g}function pw(t){var e=-1,r=Array(t.size);return t.forEach(function(n,i){r[++e]=[i,n]}),r}function mw(t){var e=-1,r=Array(t.size);return t.forEach(function(n){r[++e]=n}),r}var fw=1,gw=2,vw="[object Boolean]",yw="[object Date]",Sw="[object Error]",Ew="[object Map]",Tw="[object Number]",kw="[object RegExp]",_w="[object Set]",bw="[object String]",ww="[object Symbol]",Iw="[object ArrayBuffer]",Cw="[object DataView]",Np=xn?xn.prototype:void 0,Qd=Np?Np.valueOf:void 0;function Pw(t,e,r,n,i,s,o){switch(r){case Cw:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case Iw:return!(t.byteLength!=e.byteLength||!s(new Nc(t),new Nc(e)));case vw:case yw:case Tw:return Qo(+t,+e);case Sw:return t.name==e.name&&t.message==e.message;case kw:case bw:return t==e+"";case Ew:var a=pw;case _w:var d=n&fw;if(a||(a=mw),t.size!=e.size&&!d)return!1;var h=o.get(t);if(h)return h==e;n|=gw,o.set(t,e);var p=xg(a(t),a(e),n,i,s,o);return o.delete(t),p;case ww:if(Qd)return Qd.call(t)==Qd.call(e)}return!1}var Rw=1,Aw=Object.prototype,Mw=Aw.hasOwnProperty;function Dw(t,e,r,n,i,s){var o=r&Rw,a=Ll(t),d=a.length,h=Ll(e),p=h.length;if(d!=p&&!o)return!1;for(var m=d;m--;){var g=a[m];if(!(o?g in e:Mw.call(e,g)))return!1}var v=s.get(t),_=s.get(e);if(v&&_)return v==e&&_==t;var A=!0;s.set(t,e),s.set(e,t);for(var C=o;++m<d;){g=a[m];var M=t[g],N=e[g];if(n)var J=o?n(N,M,g,e,t,s):n(M,N,g,t,e,s);if(!(J===void 0?M===N||i(M,N,r,n,s):J)){A=!1;break}C||(C=g=="constructor")}if(A&&!C){var P=t.constructor,G=e.constructor;P!=G&&"constructor"in t&&"constructor"in e&&!(typeof P=="function"&&P instanceof P&&typeof G=="function"&&G instanceof G)&&(A=!1)}return s.delete(t),s.delete(e),A}var Ow=1,Lp="[object Arguments]",xp="[object Array]",pa="[object Object]",Nw=Object.prototype,Up=Nw.hasOwnProperty;function Lw(t,e,r,n,i,s){var o=Un(t),a=Un(e),d=o?xp:ps(t),h=a?xp:ps(e);d=d==Lp?pa:d,h=h==Lp?pa:h;var p=d==pa,m=h==pa,g=d==h;if(g&&us(t)){if(!us(e))return!1;o=!0,p=!1}if(g&&!p)return s||(s=new wr),o||md(t)?xg(t,e,r,n,i,s):Pw(t,e,d,r,n,i,s);if(!(r&Ow)){var v=p&&Up.call(t,"__wrapped__"),_=m&&Up.call(e,"__wrapped__");if(v||_){var A=v?t.value():t,C=_?e.value():e;return s||(s=new wr),i(A,C,r,n,s)}}return g?(s||(s=new wr),Dw(t,e,r,n,i,s)):!1}function Ug(t,e,r,n,i){return t===e?!0:t==null||e==null||!Cr(t)&&!Cr(e)?t!==t&&e!==e:Lw(t,e,r,n,Ug,i)}function xw(t){return function(e,r,n){for(var i=-1,s=Object(e),o=n(e),a=o.length;a--;){var d=o[t?a:++i];if(r(s[d],d,s)===!1)break}return e}}var Uw=xw();const Fw=Uw;var Vw=function(){return vr.Date.now()};const Xd=Vw;var Bw="Expected a function",jw=Math.max,Hw=Math.min;function Zr(t,e,r){var n,i,s,o,a,d,h=0,p=!1,m=!1,g=!0;if(typeof t!="function")throw new TypeError(Bw);e=Dp(e)||0,gr(r)&&(p=!!r.leading,m="maxWait"in r,s=m?jw(Dp(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function v(W){var ae=n,se=i;return n=i=void 0,h=W,o=t.apply(se,ae),o}function _(W){return h=W,a=setTimeout(M,e),p?v(W):o}function A(W){var ae=W-d,se=W-h,Ne=e-ae;return m?Hw(Ne,s-se):Ne}function C(W){var ae=W-d,se=W-h;return d===void 0||ae>=e||ae<0||m&&se>=s}function M(){var W=Xd();if(C(W))return N(W);a=setTimeout(M,A(W))}function N(W){return a=void 0,g&&n?v(W):(n=i=void 0,o)}function J(){a!==void 0&&clearTimeout(a),h=0,n=d=i=a=void 0}function P(){return a===void 0?o:N(Xd())}function G(){var W=Xd(),ae=C(W);if(n=arguments,i=this,d=W,ae){if(a===void 0)return _(d);if(m)return clearTimeout(a),a=setTimeout(M,e),v(d)}return a===void 0&&(a=setTimeout(M,e)),o}return G.cancel=J,G.flush=P,G}function Bl(t,e,r){(r!==void 0&&!Qo(t[e],r)||r===void 0&&!(e in t))&&Du(t,e,r)}function Ww(t){return Cr(t)&&Zo(t)}function jl(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function $w(t){return Xo(t,ea(t))}function Jw(t,e,r,n,i,s,o){var a=jl(t,r),d=jl(e,r),h=o.get(d);if(h){Bl(t,r,h);return}var p=s?s(a,d,r+"",t,e,o):void 0,m=p===void 0;if(m){var g=Un(d),v=!g&&us(d),_=!g&&!v&&md(d);p=d,g||v||_?Un(a)?p=a:Ww(a)?p=Eg(a):v?(m=!1,p=Sg(d,!0)):_?(m=!1,p=wg(d,!0)):p=[]:sw(d)||Oc(d)?(p=a,Oc(a)?p=$w(a):(!gr(a)||Mu(a))&&(p=Ig(d))):m=!1}m&&(o.set(d,p),i(p,d,n,s,o),o.delete(d)),Bl(t,r,p)}function Fg(t,e,r,n,i){t!==e&&Fw(e,function(s,o){if(i||(i=new wr),gr(s))Jw(t,e,o,r,Fg,n,i);else{var a=n?n(jl(t,o),s,o+"",t,e,i):void 0;a===void 0&&(a=s),Bl(t,o,a)}},ea)}var Gw="[object Map]",qw="[object Set]",zw=Object.prototype,Kw=zw.hasOwnProperty;function Yw(t){if(t==null)return!0;if(Zo(t)&&(Un(t)||typeof t=="string"||typeof t.splice=="function"||us(t)||md(t)||Oc(t)))return!t.length;var e=ps(t);if(e==Gw||e==qw)return!t.size;if(fd(t))return!vg(t).length;for(var r in t)if(Kw.call(t,r))return!1;return!0}function Qw(t,e){return Ug(t,e)}var Xw=Zb(function(t,e,r){Fg(t,e,r)});const En=Xw;var Hl=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Hl||{});const ie={PROPAGATE_KICK_ALL:"propagate_kick_across_rooms",REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",SIMULCAST:"simulcast",CHAT_SOCKET_SERVER:"chat_socket_server",POLL_SOCKET_SERVER:"poll_socket_server",PLUGIN_SOCKET_SERVER:"plugin_socket_server",NR_OTEL_WEB:"nr_otel_web",ICE_RESTART_ON_FAILED_STATE:"ice_restart_on_failed_state",ICE_RESTART_ON_DISCONNECTED_STATE:"ice_restart_on_disconnected_state",ENABLE_ICE_STATE_LOGGING:"enable_ice_state_logging",SUPPRESS_PEER_MUTE_UNMUTE_EMITS:"web_core_suppress_peer_mute_unmute_emits",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",CUSTOM_PING_PONG:"custom_ping_pong",ENABLE_HIVE_SIMULCAST:"enable_hive_simulcast",ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_hive_transport_reconnection_on_ice_failed",ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY:"enable_hive_fail_recovery",ENABLE_HIVE_INFINITE_RETRIES:"enable_hive_infinite_retries",HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"hive_transport_force_relay_on_ice_failed",ENABLE_HIVE_CONSUME_OVER_DC:"enable_hive_consume_over_dc",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_cf_transport_reconnection_on_ice_failed",ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY:"enable_cf_fail_recovery",ENABLE_CF_INFINITE_RETRIES:"enable_cf_infinite_retries",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",BYPASS_LOG_EXCLUSION_LIST:"bypass_log_exclusion_list",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",SCREENSHARE_DTX:"screenshare_dtx",SCREENSHARE_PRIORITY:"screenshare_priority",SCREENSHARE_MIN_BITRATE:"screenshare_minbitrate",SCREENSHARE_SIMULCAST:"screenshare_simulcast",DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE:"disable_webcam_layers_on_screenshare",SCREENSHARE_FORCE_GOOG_CONFERENCE:"screenshare_force_goog_conference",LIVESTREAM:"feat_livestream",FETCH_RETRY:"fetch_retry",DISABLE_WEBCAM_SIMULCAST:"webcore_disable_webcam_simulcast",OVERRIDE_WEBCAM_SIMULCAST:"override_webcam_simulcast",SOCKET_POLLING:"socket_polling",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",TROUBLESHOOTING:"feat_troubleshooting",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",DYNAMIC_VIDEO_QUALITY:"dynamic_video_quality",EXP_RESHARE:"exp_reshare",LEAVE_STAGE_ON_END:"leave_stage_on_end",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test",CONSUMER_BIND_NO_RETRY:"consumer_bind_no_retry",DEBUG_SOCKET_JOIN:"debug_socket_join",FORCE_RELAY:"force_relay",FORCE_VIDEO_CODEC:"force_video_codec"};function Ya(t){const e={};return typeof(t==null?void 0:t.code)=="number"&&(e.code=t.code),typeof(t==null?void 0:t.code)=="string"&&(e.code=t.code.substring(0,100)),typeof(t==null?void 0:t.name)=="string"&&(e.name=t.name.substring(0,500)),typeof(t==null?void 0:t.message)=="string"&&(e.message=t.message.substring(0,500)),typeof(t==null?void 0:t.reason)=="string"&&(e.reason=t.reason.substring(0,500)),typeof(t==null?void 0:t.stack)=="string"&&(e.stack=t.stack.substring(0,500)),e}function Vg(t){var e,r,n,i;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((r=window.location.host)==null?void 0:r.includes("dyte.io")),o=!!((i=(n=t==null?void 0:t.getValue("modules"))==null?void 0:n.devTools)!=null&&i.logs);return s||o}function Zw(t){if(Q.hasFeature(ie.LOG_LEVEL)){let e=Q.getValue(ie.LOG_LEVEL)||"all";if(e=e.toLowerCase().trim(),e==="off")return!1;if(e!=="all"){const r=["debug","log","info","warn","error"],n=r.indexOf(t),i=r.indexOf(e);if(n<i)return!1}}return!0}function Bg(t,e,r={}){return Object.getOwnPropertyNames(t).forEach(n=>{var i;if([null,void 0,NaN].includes(t[n])||e&&(((i=e.match(/\./g))==null?void 0:i.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?Bg(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function Fp(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),o=JSON.parse(s),a=Bg(o,n),d=JSON.stringify(a);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
25
+ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw Vg(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const o=Ya(s);i[`${n}.error.message`]=o.message||"",i[`${n}.error.stack`]=o.stack||"",i[`${n}.error.reason`]=o.reason||"",i[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Go="chrome",jg="opera",Hg="firefox",Wg="iexplorer",$g="safari",Jg="nwjs",Gg="electron",qg="react-native",Bu="unknown",xc={Chrome:Go,Chromium:Go,Opera:jg,Firefox:Hg,"Internet Explorer":Wg,Safari:$g};function eI(){const{userAgent:t}=navigator,e={name:Bu,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const r=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(e.name=Go,e.version=r)}else e.name=Go,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function tI(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:Gg,version:e}}return null}function rI(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Jg,version:e}}}function nI(){const t=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let e;if(t||navigator.product==="ReactNative")return t&&t.length>2&&(t[1],e=t[2]),e||(e="unknown"),{name:qg,version:e}}function iI(t){let e;const r=[nI,tI,rI];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in xc?{name:xc[n],version:t.getBrowserVersion()}:(e=eI(),e||{name:Bu,version:void 0})}class sI{constructor(){f(this,"_bowser"),f(this,"_name"),f(this,"_version"),f(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(e){let r,n;if(this._bowser=uf.getParser(navigator.userAgent),typeof e=="undefined"){const i=iI(this._bowser);r=i.name,n=i.version}else e.name in xc?(r=xc[e.name],n=e.version):(r=Bu,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===Go}isOpera(){return this._name===jg}isFirefox(){return this._name===Hg}isIExplorer(){return this._name===Wg}isSafari(){return this._name===$g}isNWJS(){return this._name===Jg}isElectron(){return this._name===Gg}isReactNative(){return this._name===qg||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(e){if(this._version)return this._bowser.satisfies(e)}isVersionGreaterThan(e){return this._checkCondition({[this._name]:`>${e}`})}isVersionLessThan(e){return this._checkCondition({[this._name]:`<${e}`})}isVersionEqualTo(e){return this._checkCondition({[this._name]:`~${e}`})}}class oI extends sI{doesVideoMuteByStreamRemove(){return this.isChromiumBased()||this.isWebKitBased()}supportsP2P(){return!this.usesUnifiedPlan()}isChromiumBased(){return this.isChrome()||this.isElectron()||this.isNWJS()||this.isOpera()}isWebKitBased(){return this._bowser.isEngine("webkit")&&typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getUserMedia!="undefined"&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(RTCRtpTransceiver.prototype).indexOf("currentDirection")>-1}isSupported(){return typeof RTCPeerConnection!="undefined"}isUserInteractionRequiredForUnmute(){return this.isFirefox()&&this.isVersionLessThan("68")}supportsVideoMuteOnConnInterrupted(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsBandwidthStatistics(){return!this.isFirefox()&&!this.isWebKitBased()}supportsCodecPreferences(){return this.usesUnifiedPlan()&&typeof window.RTCRtpTransceiver!="undefined"&&Object.keys(window.RTCRtpTransceiver.prototype).indexOf("setCodecPreferences")>-1&&Object.keys(RTCRtpSender.prototype).indexOf("getCapabilities")>-1&&!this.isWebKitBased()}supportsDeviceChangeEvent(){return navigator.mediaDevices&&typeof navigator.mediaDevices.ondevicechange!="undefined"&&typeof navigator.mediaDevices.addEventListener!="undefined"}supportsLocalCandidateRttStatistics(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}supportsPerformanceObserver(){return typeof window.PerformanceObserver!="undefined"&&PerformanceObserver.supportedEntryTypes.indexOf("longtask")>-1}supportsReceiverStats(){return typeof window.RTCRtpReceiver!="undefined"&&Object.keys(RTCRtpReceiver.prototype).indexOf("getSynchronizationSources")>-1}supportsRTTStatistics(){return!this.isFirefox()}usesPlanB(){return!this.usesUnifiedPlan()}usesSdpMungingForSimulcast(){return this.isChromiumBased()||this.isReactNative()||this.isWebKitBased()}usesUnifiedPlan(){return!!(this.isFirefox()||this.isWebKitBased())}usesNewGumFlow(){return!!(this.isChromiumBased()||this.isFirefox()||this.isWebKitBased())}usesAdapter(){return this.usesNewGumFlow()}usesRidsForSimulcast(){return!1}supportsGetDisplayMedia(){return typeof navigator.getDisplayMedia!="undefined"||typeof navigator.mediaDevices!="undefined"&&typeof navigator.mediaDevices.getDisplayMedia!="undefined"}supportsInsertableStreams(){if(!(typeof window.RTCRtpSender!="undefined"&&(window.RTCRtpSender.prototype.createEncodedStreams||window.RTCRtpSender.prototype.createEncodedVideoStreams)))return!1;const e=new ReadableStream;try{return window.postMessage(e,"*",[e]),!0}catch{return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const e=navigator.userAgent;if(e.match(/Chrome/))return Number.parseInt(e.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Te=new oI,aI={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Hs={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},cI={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,devTools:{logs:!1}};function Uc(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function dI({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?Vo.PREPROD:t!=null&&t.includes("devel.dyte")?Vo.DEVEL:Vo.PROD}function as({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function zg(t){const e=t.getValue("baseURI");return{location:as({servicePrefix:"location",baseURI:e}),locationLegacy:as({servicePrefix:"location-legacy",baseURI:e}),daCollector:as({servicePrefix:"da-collector",baseURI:e})}}const lI='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',uI='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="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" fill="currentColor"></path></svg>',ma=t=>{if(!t)return;if(!t.startsWith("<svg"))return new Promise(i=>{i(t)});const e=new Blob([t],{type:"image/svg+xml"}),r=new Image,n=window.URL.createObjectURL(e);return new Promise((i,s)=>{r.onload=()=>{i(r),window.URL.revokeObjectURL(n)},r.onerror=()=>{s(),window.URL.revokeObjectURL(n)},r.src=n})};function hI(t){const e=B({},t),r=new Map,n=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>{var d;return(d=r.get(o))==null?void 0:d.delete(a)}),i=(o,a)=>{var d;(d=r.get(o))==null||d.delete(a)},s=o=>{var a;(a=r.get(o))==null||a.forEach(d=>{try{d(e[o])}catch(h){l.error(`Error in notifying for "${o.toString()}"`,h)}})};return{subscribe:n,unsubscribe:i,notify:s,setValue:(o,a,d=!0)=>{e[o]=a,d&&s(o)},getValue:o=>e[o],getAllValues:()=>e}}class pI{constructor(){f(this,"contexts",new Map),f(this,"mostRecentPeerId",null)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,hI(r)),this.mostRecentPeerId=e,this.contexts.get(e))}remapContext(e,r){const n=r.getValue("peerId");n!==e&&(r.setValue("peerId",e),this.mostRecentPeerId=e,this.contexts.set(e,r),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}getMostRecentPeerId(){return this.mostRecentPeerId}}const gi=new pI,ge=class{static get logsEndpoint(){const t=gi.getContext(ge.meetingMetadata.peerId);return`https://${as({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){ge.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");ge.tracingEnabled=e,ge.meetingMetadata.peerId=r,ge.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),ge.meetingMetadata.deviceInfo=Te.getDeviceInfo(),ge.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",ge.processCachedLogs),ge.logsProcessorTimer=setInterval(ge.processCachedLogs,ge.logsProcessingInterval),e&&(ge.initialized=!0)}static trace(t,e=void 0){return(r,n,i)=>{const s=i.value;return i.value=function(...o){if(!ge.initialized||navigator.isReactNative||!ge.tracingEnabled||Q.hasFeature(ie.SKIP_OTEL_TRACES))return s.apply(this,o);ge.addLogInCurrentSpan("info",t,e);const a=performance.now(),d=s.apply(this,o);return Promise.resolve(d).then(()=>{const h=performance.now();h-a>10&&ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-a,country:ge.location.country})}).catch(()=>{const h=performance.now();ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-a})}),d},i}}static injectContext(t){var e;const r=bi().replace(/-/g,"").substring(0,16),n=(e=ge.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${r}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:Ya(r.error)});const i=gi.getContext(ge.meetingMetadata.peerId);if(Vg(i)&&(Yw(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!Zw(t))try{const s=Fp(i,e,r,"metadata"),o=new Date,a=Z(B({message:e,level:t},s),{loggedAt:o.toISOString(),loggedAtTzOffset:o.getTimezoneOffset()});n?ge.sendOtelLogsToNewRelic([a]):ge.logsCache.push(a)}catch(s){ge.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Ya(s)})}}static sendOtelLogsToNewRelic(t){const e=gi.getContext(ge.meetingMetadata.peerId);Mc.post(ge.logsEndpoint,{meetingMetadata:Fp(e,"sendOtelLogsToNewRelic",ge.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{ge.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Ya(r)}),ge.logsCache.push(...t)})}static processCachedLogs(){const t=ge.logsCache.splice(0,25);t!=null&&t.length&&ge.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(ge.logsProcessorTimer),ge.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",ge.processCachedLogs)}};let y=ge;f(y,"logsCache",[]),f(y,"logsProcessorTimer"),f(y,"location",{country:void 0}),f(y,"tracingEnabled",!0),f(y,"initialized",!1),f(y,"logsProcessingInterval",7e3),f(y,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]),f(y,"meetingMetadata",{});class l{static info(e,r,n){y.addLogInCurrentSpan("info",e,r,n)}static error(e,r,n){y.addLogInCurrentSpan("error",e,r,n)}static debug(e,r,n){y.addLogInCurrentSpan("debug",e,r,n)}static log(e,r,n){y.addLogInCurrentSpan("log",e,r,n)}static warn(e,r,n){y.addLogInCurrentSpan("warn",e,r,n)}}const mI=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&l.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,n,i,s,o,a,d;l.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(i=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:i.baseURL,method:(o=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:o.method,status:(a=t==null?void 0:t.reason)==null?void 0:a.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},fI={"00":"DyteClient","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},Qa={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0510":"Invalid channel name.","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(Qa).forEach(t=>{Qa[t]=`{${fI[t.slice(0,2)]}} ${Qa[t]}`});class b extends Error{constructor(e,r,n=!1){super(e),f(this,"code"),this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${Qa[this.code]}
26
+ ${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}});const s=gi.getContext(gi.getMostRecentPeerId());if(s){const o=s.getValue("onError");try{o(this)}catch{}}}catch{}}}function fa(t,e,r,n){if(n instanceof b)throw n;if(n instanceof e){const i=new b(n.message,r);throw i.stack=n.stack,i}else throw n}function Vp(t,e,r){if(!t.value){const i=t.get,s=t.set;return i&&(t.get=function(){try{return i.apply(this)}catch(o){fa(this,e,r,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(a){fa(this,e,r,a)}}),t}const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{fa(this,e,r,o)}):s}catch(s){fa(this,e,r,s)}},t}function gI(t,e){return(r,n,i)=>{if(i)return Vp(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(r.prototype,s,Vp(o,t,e))}}}const St=t=>gI(Error,t);function vI(t){let e=0,r,n;if(!t)return e;for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var Tn,kn;const Kg=class extends ft.EventEmitter{constructor(){super(),T(this,Tn,void 0),T(this,kn,void 0),f(this,"asyncPromiseTimeout"),S(this,Tn,new Map),S(this,kn,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,Tn).set(t,[]);const r=c(this,kn).get(t).map(()=>new Promise(n=>{c(this,Tn).get(t).push(n)}));QS(Kg.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(r),new Promise((n,i)=>setTimeout(()=>i(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),c(this,Tn).delete(t)})}onAsync(t,e){const r=c(this,Tn),n=(...i)=>u(this,null,function*(){var s;try{yield e(...i)}catch(a){l.error("[onAsync]",{error:a})}const o=(s=r.get(t))==null?void 0:s.shift();o==null||o()});return c(this,kn).get(t)||c(this,kn).set(t,[]),c(this,kn).get(t).push(n),super.on(t,n)}reset(){S(this,Tn,new Map),S(this,kn,new Map),super.removeAllListeners()}};let yI=Kg;Tn=new WeakMap,kn=new WeakMap;const I=new yI;function SI(){Te.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>u(this,null,function*(){const t=yield window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let e=[];if(t&&(Array.isArray(t)?e=t:e=[t]),!(e!=null&&e.length))throw new Error("Couldn't find any media source for screen share.");let r=e.find(i=>{var s;return(s=i.id)==null?void 0:s.includes("screen")});r=r!=null?r:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var w=(t=>(t.NEW_PRODUCER="NEW_PRODUCER",t.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",t.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",t.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",t.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",t.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",t.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",t.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",t.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",t.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",t.ROOM_NODE_FAILED="ROOM_NODE_FAILED",t.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",t.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",t.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",t.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",t.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",t.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",t.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",t.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",t.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",t.WAITLISTED="WAIT_LISTED",t.MESSAGE="websocket/message",t.ROOM_MESSAGE="websocket/room-message",t.PEER_JOINED_INTERNAL="peer/joined-internal",t.PEER_CLOSED="websocket/peer-closed",t.CONSUMER_CLOSED="websocket/consumer-closed",t.CONSUMER_PAUSED="websocket/consumer-paused",t.CONSUMER_RESUMED="websocket/consumer-resumed",t.PRODUCER_CLOSED="websocket/producer-closed",t.NEW_CONSUMER="websocket/new-consumer",t.PRODUCER_SCORE="websocket/producer-score",t.CONSUMER_SCORE="websocket/consumer-score",t.PRODUCER_TOGGLE="hive/producer-toggle",t.CONSUMER_TOGGLE="hive/consumer-toggle",t.SELECTED_PEERS_DIFF="hive/selected-peers-diff",t.UPDATE_ACTIVE="media/update-active",t.RESET_PRODUCER_STATE="hive/reset-producer-state",t.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",t.CF_ROOM_REJOINING="cf/room-rejoining",t.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",t.CF_ROOM_REJOINED="cf/room-rejoined",t.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",t.ROOM_STATE="sockethub/room-state",t.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",t.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",t.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",t.KICK_PEER="KICK_PEER",t.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",t.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",t.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",t.PIP_HANGUP="PIP_HANGUP",t.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",t.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",t.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",t.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",t.SOCKET_PEERS="SOCKET_PEERS",t.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",t.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",t.MUTE_SELF="MUTE_SELF",t.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",t))(w||{});class Ss extends ft.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Yt extends ft.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch{}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function EI(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(r=>r.charAt(0)).join("").toUpperCase()}const Bp=1080,jp=1920,TI=(t,e,r,n,i,s)=>{let o=.5,a=.5;const d=i,h=s,p=Math.min(r/d,n/h);let m=d*p,g=h*p,v,_,A,C,M=1;return m<r&&(M=r/m),Math.abs(M-1)<1e-14&&g<n&&(M=n/g),m*=M,g*=M,A=d/(m/r),C=h/(g/n),v=(d-A)*o,_=(h-C)*a,v<0&&(v=0),_<0&&(_=0),A>d&&(A=d),C>h&&(C=h),[v,_,A,C,t,e,r,n]};var dr,yo,It,lr,Ge,kr,_n,xt,nt,So,Eo,bn,To;const Yg=class extends Yt{constructor(t,e,r,n){super(),T(this,dr,void 0),T(this,yo,void 0),T(this,It,void 0),T(this,lr,void 0),T(this,Ge,{height:Bp,width:jp}),T(this,kr,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),T(this,_n,void 0),T(this,xt,{}),T(this,nt,void 0),T(this,So,void 0),T(this,Eo,void 0),T(this,bn,void 0),T(this,To,!1),f(this,"cleanupEventListeners",()=>{c(this,yo).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,nt).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,nt).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,nt).removeListener("roomLeft",()=>this.disable())}),f(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),f(this,"onSelfVideoUpdateListener",({videoEnabled:i})=>{this.updateMediaSession("CAMERA",i)}),f(this,"onSelfAudioUpdateListener",({audioEnabled:i})=>{this.updateMediaSession("MIC",i)}),f(this,"handlePipMediaControls",i=>{i==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),f(this,"eventCallback",i=>{i==="CAMERA"&&(c(this,nt).videoEnabled?c(this,nt).disableVideo():c(this,nt).enableVideo(),this.emit("cameraToggled")),i==="MIC"&&(c(this,nt).audioEnabled?c(this,nt).disableAudio():c(this,nt).enableAudio(),this.emit("micToggled")),i==="END"&&(I.emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),f(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),f(this,"animate",()=>{if(!this.isActive&&c(this,bn)==="active"){this.disable(!0);return}c(this,xt)!==void 0&&this.paintCanvas(),c(this,_n)!==void 0&&S(this,_n,requestAnimationFrame(()=>this.animate()))}),f(this,"disable",(i=!1)=>{S(this,bn,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(c(this,_n)),i!==!0&&document.body.removeChild(c(this,It)),S(this,_n,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),S(this,yo,t),S(this,bn,"idle"),S(this,nt,e),S(this,kr,{brand:e.config.designTokens.colors.brand[500],background:e.config.designTokens.colors.background[1e3],text:e.config.designTokens.colors.text,videoBackground:e.config.designTokens.colors.videoBg,textOnBrand:e.config.designTokens.colors.textOnBrand}),r&&this.setupIcon("pin",r),n&&this.setupIcon("handRaise",n)}static _init(t,e){return u(this,null,function*(){let r,n;try{r=yield ma(lI),n=yield ma(uI)}catch{}return new Yg(t,e,r,n)})}setupIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,Eo,e);break;case"pin":S(this,So,e);break}})}overrideIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":S(this,Eo,yield ma(e));break;case"pin":S(this,So,yield ma(e));break}})}constructImage(t){const e=new Image,r=new Blob([t],{type:"image/svg+xml"}),n=window.URL.createObjectURL(r);return new Promise(i=>{e.onload=()=>{i(e),window.URL.revokeObjectURL(n)},e.src=n})}createVideoContainer(){S(this,It,document.createElement("div")),c(this,It).style.width="0.1px",c(this,It).style.height="0.1px",c(this,It).style.overflow="hidden",c(this,It).style.position="absolute",c(this,It).style.bottom="0",c(this,It).style.right="0",c(this,It).style.opacity="0",c(this,It).appendChild(c(this,lr))}setupEventListeners(){c(this,yo).subscribe("stageStatus",this.handlePipMediaControls),c(this,nt).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,nt).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,nt).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=c(this,Ge).height,t.width=c(this,Ge).width,S(this,dr,t)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||c(this,nt).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,nt).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const t=Object.values(c(this,xt)).reduce((e,r)=>(e[r.pinned?"pinned":"regular"].push(r),e),{pinned:[],regular:[]});return[...t.pinned,...t.regular]}drawEmptyTile(t,e,r,n){if(c(this,dr)===void 0)return;const i=c(this,dr).getContext("2d"),s=c(this,dr).width,o=0,a=0,d=e-o*2,h=r-o*2,p=Math.floor(s/d),m=Math.floor(t/p),g=t%p*(d+o)+o,v=m*(h+o)+o,{displayText:_,image:A}=n!=null?n:{};i.fillStyle=_||A?c(this,kr).videoBackground:c(this,kr).background,i.strokeStyle=c(this,kr).brand,i.beginPath(),i.moveTo(g+a,v),i.arcTo(g+d,v,g+d,v+a,a),i.arcTo(g+d,v+h,g+d-a,v+h,a),i.arcTo(g,v+h,g,v+h-a,a),i.arcTo(g,v,g+a,v,a),i.closePath(),i.fill(),i.stroke();const C=d/6,M=d/2+g,N=h/2+v;i.save(),(_||A)&&(i.beginPath(),i.arc(M,N,C,0,Math.PI*2),i.fillStyle=c(this,kr).brand,i.fill(),A?(i.clip(),i.drawImage(A,M-C,N-C,C*2,C*2),i.restore()):_&&(i.fillStyle=c(this,kr).textOnBrand,i.font=`${C/2}px sans-serif`,i.textAlign="center",i.textBaseline="middle",i.fillText(_,M,N)),this.drawIcons(n,g,v,Math.max(d,h)))}drawIcons(t,e,r,n){const i=Math.min(Math.max(n*.15,100),200),s=i*.2,o=i*.2;let a=e+s;const d=r+s,h=p=>{const m=c(this,dr).getContext("2d");m.save(),m.fillStyle=c(this,kr).background,m.beginPath(),m.moveTo(a+o,d),m.arcTo(a+i,d,a+i,d+o,o),m.arcTo(a+i,d+i,a+i-o,d+i,o),m.arcTo(a,d+i,a,d+i-o,o),m.arcTo(a,d,a+o,d,o),m.closePath(),m.fill(),typeof p=="string"?(m.font=`${i/1.5}px sans-serif`,m.fillStyle=c(this,kr).text,m.textAlign="center",m.textBaseline="top",m.fillText(p,i/2+a,d+s)):m.drawImage(p,a+s,d+s,i-s*2,i-s*2),a+=i+s,m.restore()};t.pinned&&h(c(this,So)),t.handRaised&&h(c(this,Eo))}drawTile(t,e,r){var n,i;if(c(this,dr)===void 0)return;const s=c(this,dr).getContext("2d"),o=this.getSources();let a=0,d=0;for(;a<c(this,Ge).height-5;){let h=0;for(;h<c(this,Ge).width-5&&d<r;){if((n=o[d])!=null&&n.enabled){const p=o[d].element,[m,g,v,_,A,C,M,N]=TI(h,a,t,e,p.videoWidth,p.videoHeight);(i=p==null?void 0:p.classList)!=null&&i.contains("mirror")?(s.save(),s.scale(-1,1),s.drawImage(p,m,g,v,_,-1*A,C,-1*M,N),s.restore()):s.drawImage(p,m,g,v,_,A,C,M,N),this.drawIcons(o[d],A,C,Math.max(M,N))}else this.drawEmptyTile(d,t,e,o[d]);d+=1,h+=t}a+=e}}calcGridElemSize(t){switch(t){case 0:case 1:return[c(this,Ge).width,c(this,Ge).height];case 2:return[Math.floor(c(this,Ge).width/2),c(this,Ge).height];case 3:case 4:return[Math.floor(c(this,Ge).width/2),Math.floor(c(this,Ge).height/2)];case 5:case 6:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/3)];default:return[Math.floor(c(this,Ge).width/3),Math.floor(c(this,Ge).height/2)]}}paintCanvas(){let t=this.getSources().length;t!==1&&(t=t%2>0?t+1:t);const[e,r]=this.calcGridElemSize(t);this.drawTile(e,r,t)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(S(this,To,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,It))try{document.body.removeChild(c(this,It))}catch{}this.removeAllSources(),S(this,dr,void 0),S(this,lr,void 0),S(this,_n,void 0)}init({height:t,width:e}={}){if(c(this,To))return;S(this,To,!0),this.createCanvas(),this.setupMediaSessionEvents();const r=document.createElement("video");S(this,Ge,{height:t!=null?t:Bp,width:e!=null?e:jp}),r.height=c(this,Ge).height,r.width=c(this,Ge).width,r.autoplay=!0,r.muted=!0,r.srcObject=c(this,dr).captureStream(24),S(this,lr,r),c(this,lr).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,lr).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch{this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(t,e){navigator.mediaSession!==void 0&&(t==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(e),t==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(e))}enableSource(t){c(this,xt)[t]!==void 0&&(c(this,xt)[t].enabled=!0)}disableSource(t){c(this,xt)[t]!==void 0&&(c(this,xt)[t].enabled=!1)}generateAvatar(t,e){return u(this,null,function*(){if(!e)return;const r=new Image;try{const n=yield fetch(e).then(s=>s.blob()),i=window.URL.createObjectURL(n);r.onload=()=>{this.updateSource(t,{image:r}),window.URL.revokeObjectURL(i)},r.src=i}catch(n){l.error("DytePip::GenerateAvatar",{error:n})}})}addSource(t,e,r,n=!1,i=void 0,s=void 0,o=!1){l.debug("DytePIP::AddSource",{pip:{id:t,handRaised:o}}),c(this,xt)[t]={id:t,element:e,enabled:r,pinned:n,displayText:i?EI(i):void 0,imageUrl:s,handRaised:o},s&&this.generateAvatar(t,s)}updateSource(t,e){l.info("DytePIP::UpdateSource",{pip:{id:t,handRaised:e.handRaised}});const r=c(this,xt)[t];r&&(c(this,xt)[t]=B(B({},r),e))}removeSource(t){delete c(this,xt)[t]}removePinnedSource(){Object.values(c(this,xt)).forEach(t=>{t.pinned&&this.removeSource(t.id)})}removeAllSources(){S(this,xt,{})}enable(){S(this,bn,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,nt).videoEnabled),this.updateMediaSession("MIC",c(this,nt).audioEnabled),document.body.appendChild(c(this,It)),S(this,_n,requestAnimationFrame(()=>this.animate())),c(this,lr).onloadedmetadata=()=>{c(this,lr).requestPictureInPicture().then(()=>{S(this,bn,"active")})},c(this,lr).readyState===4&&c(this,lr).requestPictureInPicture().then(()=>{S(this,bn,"active")})}};let kI=Yg;dr=new WeakMap,yo=new WeakMap,It=new WeakMap,lr=new WeakMap,Ge=new WeakMap,kr=new WeakMap,_n=new WeakMap,xt=new WeakMap,nt=new WeakMap,So=new WeakMap,Eo=new WeakMap,bn=new WeakMap,To=new WeakMap;var zt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(zt||(zt={}));var Ft;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(Ft||(Ft={}));class _I extends E{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9}])}}const bI=new _I;class wI extends E{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const II=new wI;class CI extends E{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new CI;class PI extends E{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",zt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const yr=new PI;class RI extends E{constructor(){super("media.CreateTransportRequest",[{no:1,name:"consuming",kind:"scalar",T:8},{no:2,name:"force_tcp",kind:"scalar",opt:!0,T:8},{no:3,name:"description",kind:"message",T:()=>yr},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8}])}}const Qg=new RI;class AI extends E{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>yr},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const ju=new AI;class MI extends E{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>yr}])}}const Xg=new MI;class DI extends E{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>yr}])}}new DI;class OI extends E{constructor(){super("media.NestedScore",[{no:1,name:"encoding_idx",kind:"scalar",T:5},{no:2,name:"rid",kind:"scalar",T:9},{no:3,name:"score",kind:"scalar",T:5},{no:4,name:"ssrc",kind:"scalar",T:3,L:0}])}}const NI=new OI;class LI extends E{constructor(){super("media.ProducerTrack",[{no:1,name:"track_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9},{no:3,name:"stream_id",kind:"scalar",T:9}])}}const xI=new LI;class UI extends E{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new UI;class FI extends E{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new FI;class VI extends E{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ft]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const ta=new VI;class BI extends E{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ta},{no:3,name:"producer_track",kind:"message",T:()=>xI}])}}const jI=new BI;class HI extends E{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>jI}}])}}const Zg=new HI;class WI extends E{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Wp},{no:2,name:"receiver",kind:"message",T:()=>Wp}])}}const ev=new WI;class $I extends E{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>bI},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>II}])}}const Hp=new $I;class JI extends E{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Hp},{no:2,name:"video",kind:"message",T:()=>Hp}])}}const Wp=new JI;class GI extends E{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const qI=new GI;class zI extends E{constructor(){super("media.edge.GeoLocation",[{no:1,name:"latitude",kind:"scalar",T:2},{no:2,name:"longitude",kind:"scalar",T:2},{no:3,name:"region",kind:"scalar",opt:!0,T:9}])}}const KI=new zI;class YI extends E{constructor(){super("media.edge.PeerJoinRequest",[{no:1,name:"display_name",kind:"scalar",opt:!0,T:9},{no:2,name:"prejoined",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:5,name:"preset",kind:"scalar",opt:!0,T:12},{no:6,name:"user_id",kind:"scalar",opt:!0,T:9},{no:7,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:8,name:"location",kind:"message",T:()=>KI},{no:9,name:"capabilities",kind:"message",T:()=>ev}])}}const tv=new YI;class QI extends E{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const rv=new QI;class XI extends E{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const nv=new XI;class ZI extends E{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new ZI;class eC extends E{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>qI}])}}const Hu=new eC;class tC extends E{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Hu}])}}new tC;class rC extends E{constructor(){super("media.edge.ProducerCreateRequest",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"description",kind:"message",T:()=>yr},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const iv=new rC;class nC extends E{constructor(){super("media.edge.SelectedPeersRequest",[])}}new nC;class iC extends E{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const sv=new iC;class sC extends E{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Mn=new sC;class oC extends E{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Fc=new oC;class aC extends E{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>yr}])}}const ov=new aC;class cC extends E{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>yr}])}}const av=new cC;class dC extends E{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const cv=new dC;class lC extends E{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Wu=new lC;class uC extends E{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const dv=new uC;class hC extends E{constructor(){super("media.edge.HostMediaControlForPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"audio",kind:"scalar",T:8},{no:3,name:"video",kind:"scalar",T:8},{no:4,name:"scree_share",kind:"scalar",T:8}])}}const lv=new hC;class pC extends E{constructor(){super("media.edge.HostMediaControlForAllPeerRequest",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8}])}}const uv=new pC;class mC extends E{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const fC=new mC;class gC extends E{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const vC=new gC;class yC extends E{constructor(){super("media.edge.EmptyResponse",[])}}new yC;class SC extends E{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>ta},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>ev}])}}const hv=new SC;class EC extends E{constructor(){super("media.edge.SelectedPeersResponse",[{no:1,name:"audio_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"compulsory_peers",kind:"scalar",repeat:2,T:9}])}}const Wl=new EC;class TC extends E{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const kC=new TC;class _C extends E{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>kC}])}}const $p=new _C;class bC extends E{constructor(){super("media.edge.PeerJoinResponse",[])}}new bC;class wC extends E{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>fC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>hv},{no:3,name:"selected_peers",kind:"message",T:()=>Wl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Vc=new wC;class IC extends E{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const pv=new IC;class CC extends E{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zg}])}}new CC;class PC extends E{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Zg},{no:3,name:"description",kind:"message",T:()=>yr}])}}const mv=new PC;class RC extends E{constructor(){super("media.edge.ProducerCreateResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"producer_id",kind:"scalar",T:9},{no:4,name:"description",kind:"message",T:()=>yr}])}}const fv=new RC;class AC extends E{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>NI}])}}new AC;class MC extends E{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new MC;class DC extends E{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new DC;class OC extends E{constructor(){super("media.edge.ProducerToggleResponse",[])}}new OC;class NC extends E{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new NC;class LC extends E{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>yr}])}}const gv=new LC;class xC extends E{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>yr}])}}new xC;class UC extends E{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new UC;class FC extends E{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const vv=new FC;class VC extends E{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const yv=new VC;class BC extends E{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Sv=new BC;class jC extends E{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Ev=new jC;class HC extends E{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Tv=new HC;class WC extends E{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>hv}])}}const Jp=new WC;class $C extends E{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Gp=new $C;class JC extends E{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Gp},{no:3,name:"screenshare",kind:"message",T:()=>Gp}])}}const GC=new JC;class qC extends E{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>ju},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>GC}])}}new qC;class zC extends E{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ta}])}}const kv=new zC;class KC extends E{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ta},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const $l=new KC;class YC extends E{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ta}])}}const _v=new YC;class QC extends E{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Bc=new QC;class XC extends E{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const qp=new XC;class ZC extends E{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new ZC;class eP extends E{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new eP;class tP extends E{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new tP;class rP extends E{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new rP;class nP extends E{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new nP;class iP extends E{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new iP;class sP extends E{constructor(){super("socket.ai.MeetingTranscript",[{no:1,name:"meeting_id",kind:"scalar",T:9},{no:2,name:"transcript",kind:"scalar",T:9},{no:3,name:"is_partial",kind:"scalar",T:8}])}}const Zd=new sP;class oP extends E{constructor(){super("socket.api.BaseSocketHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9}])}}new oP;class aP extends E{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const cP=new aP;var vi;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(vi||(vi={}));var zr;(function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ON_STAGE=1]="ON_STAGE",t[t.APPROVED_STAGE=2]="APPROVED_STAGE",t[t.REQUESTED_STAGE=3]="REQUESTED_STAGE",t[t.OFF_STAGE=4]="OFF_STAGE"})(zr||(zr={}));var Jl;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Jl||(Jl={}));var Gl;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(Gl||(Gl={}));var jc;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(jc||(jc={}));class dP extends E{constructor(){super("socket.room.PeerFlags",[{no:1,name:"preset_name",kind:"scalar",T:9},{no:2,name:"recorder_type",kind:"scalar",T:9},{no:3,name:"hidden_participant",kind:"scalar",T:8}])}}const lP=new dP;class uP extends E{constructor(){super("socket.room.Peer",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",zr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>lP}])}}const gd=new uP;class hP extends E{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>gd}])}}const zi=new hP;class pP extends E{constructor(){super("socket.room.PeerStatusUpdate",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"stage_type",kind:"enum",opt:!0,T:()=>["socket.room.StageType",zr,"STAGE_TYPE_"]}])}}const zp=new pP;class mP extends E{constructor(){super("socket.room.RoomPeersInfoRequest",[{no:1,name:"seach_query",kind:"scalar",T:9},{no:2,name:"limit",kind:"scalar",T:5},{no:3,name:"offset",kind:"scalar",T:5}])}}const fP=new mP;class gP extends E{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>gd}])}}const el=new gP;class vP extends E{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Kp=new vP;class yP extends E{constructor(){super("socket.room.Room",[{no:1,name:"room_id",kind:"scalar",T:9},{no:2,name:"title",kind:"scalar",T:9},{no:4,name:"created_at",kind:"scalar",T:4,L:2},{no:5,name:"active_recordings",kind:"message",repeat:1,T:()=>EP},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const bv=new yP;class SP extends E{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",vi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const EP=new SP;class TP extends E{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>bv}])}}const Yp=new TP;class kP extends E{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const wv=new kP;class _P extends E{constructor(){super("socket.room.UpdatePeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9}])}}new _P;class bP extends E{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>gd},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"organization_id",kind:"scalar",opt:!0,T:9},{no:5,name:"use_hive",kind:"scalar",opt:!0,T:8},{no:6,name:"preset",kind:"scalar",opt:!0,T:12},{no:7,name:"capabilities",kind:"enum",repeat:1,T:()=>["socket.room.Capabilities",jc,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const wP=new bP;class IP extends E{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>gd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const CP=new IP;class PP extends E{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>bv}])}}new PP;class RP extends E{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new RP;class AP extends E{constructor(){super("socket.room.ServiceError",[{no:1,name:"message",kind:"scalar",opt:!0,T:9},{no:2,name:"code",kind:"scalar",opt:!0,T:9}])}}const $u=new AP;class MP extends E{constructor(){super("socket.room.ConnectedMeetingPeer",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:5,name:"display_picture_url",kind:"scalar",opt:!0,T:9}])}}const DP=new MP;class OP extends E{constructor(){super("socket.room.ConnectedMeetingDump",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>DP}])}}const Qp=new OP;class NP extends E{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Qp},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Qp}])}}const LP=new NP;class xP extends E{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const UP=new xP;class FP extends E{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>UP}])}}const VP=new FP;class BP extends E{constructor(){super("socket.room.CreateRoomResponsePayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>$u}])}}const jP=new BP;class HP extends E{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>jP}])}}const Xp=new HP;class WP extends E{constructor(){super("socket.room.UpdateRoomRequestPayload",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"title",kind:"scalar",opt:!0,T:9}])}}const $P=new WP;class JP extends E{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>$P}])}}new JP;class GP extends E{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const qP=new GP;class zP extends E{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>qP}])}}const KP=new zP;class YP extends E{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>ZP}])}}const QP=new YP;class XP extends E{constructor(){super("socket.room.DisableConnectedRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"status",kind:"scalar",opt:!0,T:9},{no:3,name:"title",kind:"scalar",opt:!0,T:9},{no:4,name:"error",kind:"message",T:()=>$u}])}}const ZP=new XP;class eR extends E{constructor(){super("socket.room.MovePeerPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9},{no:2,name:"preset_id",kind:"scalar",opt:!0,T:9}])}}const tR=new eR;class rR extends E{constructor(){super("socket.room.MovePeersBetweenRoomsRequest",[{no:1,name:"source_meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"destination_meeting_id",kind:"scalar",opt:!0,T:9},{no:3,name:"participants",kind:"message",repeat:1,T:()=>tR}])}}const nR=new rR;class iR extends E{constructor(){super("socket.room.MovedPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:3,name:"error",kind:"message",T:()=>$u}])}}const Iv=new iR;class sR extends E{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Iv}])}}new sR;class oR extends E{constructor(){super("socket.room.TransferPeer",[{no:1,name:"meeting_id",kind:"scalar",opt:!0,T:9},{no:2,name:"auth_token",kind:"scalar",opt:!0,T:9}])}}const aR=new oR;class cR extends E{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>uR}])}}const dR=new cR;class lR extends E{constructor(){super("socket.room.AddedParticipant",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const uR=new lR;class hR extends E{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const pR=new hR;class mR extends E{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",Gl,"BROADCAST_TYPE_"]}])}}const Ws=new mR;class fR extends E{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const gR=new fR;class vR extends E{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const yR=new vR;class SR extends E{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const ER=new SR;class TR extends E{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>ER}])}}const Zp=new TR;class kR extends E{constructor(){super("socket.room.GetRoomStageStateResponse",[{no:1,name:"on_stage_peers",kind:"scalar",repeat:2,T:9},{no:2,name:"approved_stage_peers",kind:"scalar",repeat:2,T:9},{no:3,name:"requested_stage_peers",kind:"scalar",repeat:2,T:9}])}}const em=new kR;var ql;(function(t){t[t.NONE=0]="NONE",t[t.SKIP=1]="SKIP",t[t.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",t[t.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(ql||(ql={}));var Dn;(function(t){t[t.NONE=0]="NONE",t[t.ALLOWED=1]="ALLOWED",t[t.NOT_ALLOWED=2]="NOT_ALLOWED",t[t.CAN_REQUEST=3]="CAN_REQUEST"})(Dn||(Dn={}));class _R extends E{constructor(){super("socket.preset.PollsPermissionUpdate",[{no:1,name:"can_create",kind:"scalar",opt:!0,T:8},{no:2,name:"can_vote",kind:"scalar",opt:!0,T:8},{no:3,name:"can_view",kind:"scalar",opt:!0,T:8}])}}const bR=new _R;class wR extends E{constructor(){super("socket.preset.PluginsPermissionsUpdate",[{no:1,name:"can_close",kind:"scalar",opt:!0,T:8},{no:2,name:"can_start",kind:"scalar",opt:!0,T:8}])}}const IR=new wR;class CR extends E{constructor(){super("socket.preset.PublicChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"text",kind:"scalar",opt:!0,T:8},{no:3,name:"files",kind:"scalar",opt:!0,T:8}])}}const PR=new CR;class RR extends E{constructor(){super("socket.preset.PrivateChatPermission",[{no:1,name:"can_send",kind:"scalar",opt:!0,T:8},{no:2,name:"can_receive",kind:"scalar",opt:!0,T:8},{no:3,name:"text",kind:"scalar",opt:!0,T:8},{no:4,name:"files",kind:"scalar",opt:!0,T:8}])}}const AR=new RR;class MR extends E{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>PR},{no:2,name:"private",kind:"message",T:()=>AR}])}}const DR=new MR;class OR extends E{constructor(){super("socket.preset.ConnectedMeetingPermissionUpdate",[{no:1,name:"can_alter_connected_meetings",kind:"scalar",opt:!0,T:8},{no:2,name:"can_switch_to_parent_meeting",kind:"scalar",opt:!0,T:8},{no:3,name:"can_switch_connected_meetings",kind:"scalar",opt:!0,T:8}])}}const NR=new OR;class LR extends E{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Dn,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Dn,"STREAM_PERMISSION_TYPE_"]}])}}const tl=new LR;class xR extends E{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>tl},{no:2,name:"audio",kind:"message",T:()=>tl},{no:3,name:"screenshare",kind:"message",T:()=>tl}])}}const UR=new xR;class FR extends E{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>bR},{no:2,name:"plugins",kind:"message",T:()=>IR},{no:3,name:"chat",kind:"message",T:()=>DR},{no:4,name:"accept_waiting_requests",kind:"scalar",opt:!0,T:8},{no:5,name:"can_accept_production_requests",kind:"scalar",opt:!0,T:8},{no:6,name:"can_edit_display_name",kind:"scalar",opt:!0,T:8},{no:7,name:"can_record",kind:"scalar",opt:!0,T:8},{no:8,name:"can_livestream",kind:"scalar",opt:!0,T:8},{no:9,name:"can_spotlight",kind:"scalar",opt:!0,T:8},{no:10,name:"disable_participant_audio",kind:"scalar",opt:!0,T:8},{no:11,name:"disable_participant_screensharing",kind:"scalar",opt:!0,T:8},{no:12,name:"disable_participant_video",kind:"scalar",opt:!0,T:8},{no:13,name:"kick_participant",kind:"scalar",opt:!0,T:8},{no:14,name:"pin_participant",kind:"scalar",opt:!0,T:8},{no:15,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:16,name:"waiting_room_type",kind:"enum",opt:!0,T:()=>["socket.preset.WaitingRoomType",ql,"WAITING_ROOM_TYPE_"]},{no:17,name:"is_recorder",kind:"scalar",opt:!0,T:8},{no:18,name:"recorder_type",kind:"enum",opt:!0,T:()=>["socket.room.RecorderType",Jl,"RECORDER_TYPE_"]},{no:19,name:"hidden_participant",kind:"scalar",opt:!0,T:8},{no:20,name:"show_participant_list",kind:"scalar",opt:!0,T:8},{no:21,name:"can_change_participant_permissions",kind:"scalar",opt:!0,T:8},{no:22,name:"connected_meetings",kind:"message",T:()=>NR},{no:23,name:"media",kind:"message",T:()=>UR}])}}const Ju=new FR;class VR extends E{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const BR=new VR;class jR extends E{constructor(){super("socket.preset.PeerPreset",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"preset",kind:"scalar",T:12}])}}const HR=new jR;class WR extends E{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>HR}])}}const $R=new WR;class JR extends E{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ju}])}}const Cv=new JR;class GR extends E{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Cv}])}}const qR=new GR;class zR extends E{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Cv}])}}const tm=new zR;class KR extends E{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const YR=new KR;class QR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>YR},{no:2,name:"patch",kind:"message",T:()=>Ju}])}}new QR;class XR extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ju}])}}new XR;class ZR extends E{constructor(){super("socket.chat.ChatMessage",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"user_id",kind:"scalar",T:9},{no:4,name:"display_name",kind:"scalar",T:9},{no:5,name:"pinned",kind:"scalar",T:8},{no:6,name:"is_edited",kind:"scalar",T:8},{no:7,name:"payload_type",kind:"scalar",T:5},{no:8,name:"payload",kind:"scalar",T:9},{no:10,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:11,name:"created_at",kind:"scalar",T:4,L:2},{no:12,name:"created_at_ms",kind:"scalar",opt:!0,T:4,L:2},{no:13,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:14,name:"channel_index",kind:"scalar",opt:!0,T:9}])}}const Ai=new ZR;class eA extends E{constructor(){super("socket.chat.GetPaginatedChatMessageRoomRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const tA=new eA;class rA extends E{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ai},{no:2,name:"next",kind:"scalar",T:8}])}}const nA=new rA;class iA extends E{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ai}])}}const Pv=new iA;class sA extends E{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const oA=new sA;class aA extends E{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ai}])}}const rl=new aA;class cA extends E{constructor(){super("socket.chat.SendChatMessageToPeersRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const dA=new cA;class lA extends E{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ai}])}}const nl=new lA;class uA extends E{constructor(){super("socket.chat.SendChatMessageToChannelRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",T:5},{no:3,name:"payload",kind:"scalar",T:9}])}}const hA=new uA;class pA extends E{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ai}])}}new pA;class mA extends E{constructor(){super("socket.chat.EditChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"payload_type",kind:"scalar",opt:!0,T:5},{no:3,name:"payload",kind:"scalar",opt:!0,T:9},{no:4,name:"pinned",kind:"scalar",opt:!0,T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const fA=new mA;class gA extends E{constructor(){super("socket.chat.PinChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const vA=new gA;class yA extends E{constructor(){super("socket.chat.PinChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"pinned",kind:"scalar",T:8},{no:3,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const ga=new yA;class SA extends E{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ai}])}}const va=new SA;class EA extends E{constructor(){super("socket.chat.DeleteChatMessageRequest",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const TA=new EA;class kA extends E{constructor(){super("socket.chat.DeleteChatMessageResponse",[{no:1,name:"chat_id",kind:"scalar",T:9},{no:2,name:"channel_id",kind:"scalar",opt:!0,T:9}])}}const ya=new kA;class _A extends E{constructor(){super("socket.chat.SearchChatMessagesRequest",[{no:1,name:"time_stamp",kind:"scalar",T:4,L:2},{no:2,name:"size",kind:"scalar",T:5},{no:3,name:"from",kind:"scalar",T:5},{no:4,name:"reversed",kind:"scalar",T:8},{no:5,name:"channel_id",kind:"scalar",opt:!0,T:9},{no:6,name:"search_term",kind:"scalar",T:9}])}}const bA=new _A;class wA extends E{constructor(){super("socket.chat.MarkChannelIndexAsReadRequest",[{no:1,name:"channel_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"channel_index",kind:"scalar",T:9}])}}const IA=new wA;class CA extends E{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const PA=new CA;class RA extends E{constructor(){super("socket.chat.CreateChatChannelRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8}])}}const AA=new RA;class MA extends E{constructor(){super("socket.chat.UpdateChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",opt:!0,T:9},{no:3,name:"target_user_ids",kind:"scalar",repeat:2,T:9},{no:4,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:5,name:"visibility",kind:"scalar",opt:!0,T:9},{no:6,name:"is_direct_message",kind:"scalar",opt:!0,T:8}])}}const DA=new MA;class OA extends E{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new OA;class NA extends E{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const LA=new NA;class xA extends E{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ai},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const UA=new xA;class FA extends E{constructor(){super("socket.chat.ChatChannel",[{no:1,name:"chat_channel_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9},{no:3,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:4,name:"visibility",kind:"scalar",T:9},{no:5,name:"is_direct_message",kind:"scalar",T:8},{no:6,name:"latest_message_and_unread_count",kind:"message",T:()=>UA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const VA=new FA;class BA extends E{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>VA}])}}const Fr=new BA;class jA extends E{constructor(){super("socket.chat.ChannelMember",[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",opt:!0,T:9},{no:3,name:"picture",kind:"scalar",opt:!0,T:9},{no:4,name:"custom_participant_id",kind:"scalar",T:9}])}}const HA=new jA;class WA extends E{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>HA}])}}const $A=new WA;class JA extends E{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const GA=new JA;class qA extends E{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const zA=new qA;class KA extends E{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const YA=new KA;class QA extends E{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const XA=new QA;class ZA extends E{constructor(){super("socket.plugin.EnablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const eM=new ZA;class tM extends E{constructor(){super("socket.plugin.DisablePluginForPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const rM=new tM;class nM extends E{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const iM=new nM;class sM extends E{constructor(){super("socket.plugin.PluginEventToPeersRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"peer_ids",kind:"scalar",repeat:2,T:9},{no:3,name:"plugin_data",kind:"scalar",T:12}])}}const oM=new sM;class aM extends E{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const Gu=new aM;class cM extends E{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>Gu}])}}const rm=new cM;class dM extends E{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>Gu}])}}const lM=new dM;class uM extends E{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>Gu}])}}const hM=new uM;class pM extends E{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const mM=new pM;class fM extends E{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const zl=new fM;class gM extends E{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>zl}])}}const vM=new gM;class yM extends E{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const nm=new yM;class SM extends E{constructor(){super("socket.plugin.PluginStoreItem",[{no:1,name:"timestamp",kind:"scalar",T:9},{no:2,name:"peer_id",kind:"scalar",T:9},{no:3,name:"store_key",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}])}}const EM=new SM;class TM extends E{constructor(){super("socket.plugin.PluginStoreResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"store_items",kind:"message",repeat:1,T:()=>EM}])}}const im=new TM;class kM extends E{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const sm=new kM;class _M extends E{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const om=new _M;class bM extends E{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const am=new bM;class wM extends E{constructor(){super("socket.livestreaming.StageRequest",[{no:1,name:"display_name",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9}])}}const IM=new wM;class CM extends E{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>IM}])}}const il=new CM;class PM extends E{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const RM=new PM;class AM extends E{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const MM=new AM;class DM extends E{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const cm=new DM;class OM extends E{constructor(){super("socket.polls.Poll",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"created_by",kind:"scalar",T:9},{no:3,name:"created_by_user_id",kind:"scalar",T:9},{no:4,name:"question",kind:"scalar",T:9},{no:5,name:"options",kind:"message",repeat:1,T:()=>LM},{no:6,name:"hide_votes",kind:"scalar",T:8},{no:7,name:"anonymous",kind:"scalar",T:8},{no:8,name:"votes",kind:"scalar",repeat:2,T:9}])}}const Rv=new OM;class NM extends E{constructor(){super("socket.polls.PollOption",[{no:1,name:"text",kind:"scalar",T:9},{no:2,name:"count",kind:"scalar",opt:!0,T:4,L:2},{no:3,name:"votes",kind:"message",repeat:1,T:()=>UM}])}}const LM=new NM;class xM extends E{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const UM=new xM;class FM extends E{constructor(){super("socket.polls.NewPollRequest",[{no:1,name:"question",kind:"scalar",T:9},{no:2,name:"options",kind:"scalar",repeat:2,T:9},{no:3,name:"anonymous",kind:"scalar",T:8},{no:4,name:"hide_votes",kind:"scalar",T:8},{no:5,name:"created_by",kind:"scalar",opt:!0,T:9},{no:6,name:"created_by_user_id",kind:"scalar",opt:!0,T:9}])}}const VM=new FM;class BM extends E{constructor(){super("socket.polls.VotePollRequest",[{no:1,name:"poll_id",kind:"scalar",T:9},{no:2,name:"index",kind:"scalar",T:4,L:2}])}}const jM=new BM;class HM extends E{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Rv}])}}const sl=new HM;class WM extends E{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Rv}])}}const $M=new WM;class JM extends E{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",vi]}])}}const dm=new JM;class GM extends E{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),r=Date.now();return e.seconds=Re.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(Re.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=Re.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=Re.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",i)}internalJsonRead(e,r,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+Tu(e)+".");let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return n||(n=this.create()),n.seconds=Re.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new GM;const qM=0,zM=1,KM=2,YM=3,QM=4,XM=5,ZM={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},eD={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},tD={getPlugins:0,addPlugin:1,enablePluginForRoom:2,disablePluginForPeers:3,enablePluginForPeers:4,disablePluginForRoom:5,removePlugin:6,customPluginEventToRoom:7,customPluginEventToPeers:8,storeInsertKeys:9,storeGetKeys:10,storeDeleteKeys:11,storeDelete:12},rD={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Av={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94},nD={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},iD={getUserPresets:0,updateUserPreset:1};function Es(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function Mv(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=Es(qM,ZM),Ue=Es(zM,eD),z=Es(KM,tD),Jr=Es(YM,rD),pi=Es(QM,nD),ce=Mv(Av,16777216),de=Mv(Av,50331648),Xa=Es(XM,iD);var sD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,qu=(t,e,r,n)=>{for(var i=n>1?void 0:n?oD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&sD(e,r,i),i},Wn,lm;const Kl=(lm=class{constructor(t){T(this,Wn,void 0),S(this,Wn,t)}createChannel(t,e,r,n="public",i=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:r,visibility:n,isDirectMessage:i};i&&(s.visibility="private");const o=yield c(this,Wn).sendMessagePromise(pi.createChatChannel,AA.toBinary(s)),a=Fr.fromBinary(o.payload).chatChannels;return Kl.formatChannel(a[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,Wn).sendMessagePromise(pi.updateChatChannel,DA.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=Fr.fromBinary(r.payload).chatChannels;return Kl.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=Z(B({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=r==null?void 0:r.unreadCount)!=null?e:0});return r!=null&&r.message&&(n.latestMessage=Yr.formatSocketServiceMessage(r.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield c(this,Wn).sendMessagePromise(pi.getChannelMembers,LA.toBinary({chatChannelId:t}));return $A.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=nd(n,["id"]);return Z(B({},s),{userId:i})})}catch{return[]}})}on(t,e){let r,n;switch(t){case pi.createChatChannel:{r=Fr.fromBinary.bind(Fr),n=Fr.create();break}case pi.updateChatChannel:{r=Fr.fromBinary.bind(Fr),n=Fr.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,Wn).on(t,({payload:i})=>{let s=n;try{s=r(i)}catch(o){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}},Wn=new WeakMap,lm);let Ei=Kl;qu([y.trace("ChatChannelHandler.createChannel")],Ei.prototype,"createChannel",1);qu([y.trace("ChatChannelHandler.updateChannel")],Ei.prototype,"updateChannel",1);qu([y.trace("ChatChannelHandler.getChannelMembers")],Ei.prototype,"getChannelMembers",1);var aD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,Sr=(t,e,r,n)=>{for(var i=n>1?void 0:n?cD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&aD(e,r,i),i},Mt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(Mt||{}),Ct;class nr{constructor(e){T(this,Ct,void 0),S(this,Ct,e)}getChatMessages(){return c(this,Ct).sendMessagePromise(Ue.getMessages)}getChatMessagesPaginated(e,r,n,i=0,s=""){return u(this,null,function*(){const o={timeStamp:e,size:r,from:i,reversed:n,channelId:s},a=yield c(this,Ct).sendMessagePromise(Ue.getPaginatedMessages,tA.toBinary(o));return a.payload?nA.fromBinary(a.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,Ct).sendMessage(Ue.sendMessageToRoom,oA.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,Ct).sendMessage(Ue.sendMessageToPeers,dA.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,Ct).sendMessage(Ue.sendMessageToChannel,hA.toBinary(i))}sendMessage(e,r,n,i){if(i&&this.sendMessageToChannel(e,r,i),n&&n.length>0){this.sendMessageToPeers(e,r,n);return}this.sendMessageToRoom(e,r)}editMessage(e,r,n,i,s){return u(this,null,function*(){const o={chatId:e,payloadType:n,payload:r};i&&(o.channelId=i),s!==void 0&&(o.pinned=s);const a=yield c(this,Ct).sendMessagePromise(Ue.editMessage,fA.toBinary(o));return va.fromBinary(a.payload).message})}deleteMessage(e,r){return u(this,null,function*(){const n={chatId:e};r&&(n.channelId=r);const i=yield c(this,Ct).sendMessagePromise(Ue.deleteMessage,TA.toBinary(n)),s=ya.fromBinary(i.payload);return B({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,r){return u(this,null,function*(){var n,i,s;const o={searchTerm:e,timeStamp:(n=r.timestamp)!=null?n:Date.now(),size:(i=r.size)!=null?i:75,from:0,reversed:(s=r.reversed)!=null?s:!0};r.channelId&&(o.channelId=r.channelId);try{const a=yield c(this,Ct).sendMessagePromise(Ue.searchChannelMessages,bA.toBinary(o));return Pv.fromBinary(a.payload).messages}catch{return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,Ct).sendMessagePromise(Ue.getAllChatChannels);return Fr.fromBinary(e.payload).chatChannels.map(Ei.formatChannel)}catch{return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,Ct).sendMessagePromise(Ue.markChannelIndexAsRead,IA.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return PA.fromBinary(n.payload).channelIndex})}setPinState(e,r){return u(this,null,function*(){const n={chatId:e.id,pinned:r,channelId:e.channelId},i=yield c(this,Ct).sendMessagePromise(Ue.pinMessage,vA.toBinary(n));return ga.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case Ue.sendMessageToRoom:{n=rl.fromBinary.bind(rl),i=rl.create();break}case Ue.sendMessageToPeers:{n=nl.fromBinary.bind(nl),i=nl.create();break}case Ue.editMessage:{n=va.fromBinary.bind(va),i=va.create();break}case Ue.pinMessage:{n=ga.fromBinary.bind(ga),i=ga.create();break}case Ue.deleteMessage:{n=ya.fromBinary.bind(ya),i=ya.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,Ct).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}Ct=new WeakMap;Sr([y.trace("SocketService.getChatMessages")],nr.prototype,"getChatMessages",1);Sr([y.trace("SocketService.getChatMessagesPaginated")],nr.prototype,"getChatMessagesPaginated",1);Sr([y.trace("SocketService.sendMessageToRoom")],nr.prototype,"sendMessageToRoom",1);Sr([y.trace("SocketService.sendMessageToPeers")],nr.prototype,"sendMessageToPeers",1);Sr([y.trace("SocketService.sendMessageToChannel")],nr.prototype,"sendMessageToChannel",1);Sr([y.trace("SocketService.sendMessage")],nr.prototype,"sendMessage",1);Sr([y.trace("SocketService.editMessage")],nr.prototype,"editMessage",1);Sr([y.trace("SocketService.deleteMessage")],nr.prototype,"deleteMessage",1);Sr([y.trace("SocketService.searchMessages")],nr.prototype,"searchMessages",1);Sr([y.trace("SocketService.getAllChannels")],nr.prototype,"getAllChannels",1);Sr([y.trace("SocketService.markLastReadMessage")],nr.prototype,"markLastReadMessage",1);function dD(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function fr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>fr(r));const e={};return Object.keys(t).forEach(r=>{const n=Eu(r)?r:dD(r);e[n]=fr(t[r])}),e}function lD(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Dv(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Dv(r));const e={};return Object.keys(t).forEach(r=>{const n=Eu(r)?r:lD(r);e[n]=t[r]}),e}function Hc(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){Hc(t[r],e[r]={});return}e[r]=t[r]}}),e)}const uD=3,hD=30,pD=8e3;class mD{constructor(e,r){f(this,"ipInfo"),f(this,"axios"),f(this,"requests"),f(this,"roomName"),f(this,"roomUUID"),f(this,"authToken"),f(this,"organizationId"),f(this,"iceServers"),f(this,"pluginInformation"),f(this,"userDetails"),f(this,"roomDetails"),f(this,"context"),this.context=e;const{timeout:n=pD,retry:i=uD,retryDelay:s=hD,baseURL:o="https://api.cluster.dyte.in",authToken:a,cachedUserDetails:d}=r||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=Mc.create({baseURL:o,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=Mc,this.setAuthToken(a,{bearer:!0}),this.requests.interceptors.request.use(h=>(y.injectContext(this.requests.defaults.headers.common),h),h=>u(this,null,function*(){l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:h})})),this.requests.interceptors.response.use(h=>{try{h.config.url!==y.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,method:h.config.method}})}catch(p){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,response:h})}return h},h=>u(this,null,function*(){var p;try{if(!h)return Promise.reject(new b("Unknown network error occurred","0011"));h&&h.config&&((p=h.config)==null?void 0:p.url)!==y.logsEndpoint&&l.error("xhr::axios",{error:h,networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,retries:h.config.retry,method:h.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:m,message:g}=h;return m&&g&&m.retry!==void 0&&m.retry>0&&(g.includes("timeout")||g.includes("Network Error"))?(m.retry-=1,this.requests(m)):Promise.reject(new b(g,"0011"))}catch(m){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:m,responseError:h}),Promise.reject(new b(m.message,"0011"))}}))}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,r){const{bearer:n}=r||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,r){this.requests.defaults.headers.common[e]=r}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var fD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,zu=(t,e,r,n)=>{for(var i=n>1?void 0:n?gD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&fD(e,r,i),i};class vd extends mD{constructor(e,r){super(e,r),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:r}=this;try{const n=yield Cu.getIPDetails({peerId:r,apiHostnames:zg(this.context),logger:l});if(l.log("ipInfo",{ipInfo:n}),((e=n==null?void 0:n.loc)==null?void 0:e.length)>5)return n;throw Error("Insufficient data")}catch(n){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:n.name,message:n.message}});return}})}getICEServers(){return u(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(yield this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r})}getPlugins(){return u(this,null,function*(){var e,r,n,i,s,o,a;if(this.pluginInformation)return this.pluginInformation;const{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data,h=((r=(e=Q.getValue(ie.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:r.split(","))||[],p=d.reduce((m,g)=>(m[h.includes(g.id)?"v1":"v2"].push(Z(B({},g),{name:g.name.replace("v2","")})),m),{v1:[],v2:[]});return(s=(i=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:i.plugins)!=null&&s.length&&((a=(o=this.context.getValue("modules"))==null?void 0:o.devTools)==null||a.plugins.forEach(m=>{var g,v,_;const A=Z(B({},Hs),{tags:[...Hs.tags],baseUrl:`http://localhost:${m.port}`,name:m.name,picture:(g=m.picture)!=null?g:Hs.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:m.id,organizationId:this.organizationId,description:(v=m.description)!=null?v:Hs.description,staggered:(_=m.staggered)!=null?_:Hs.staggered});p.v2.push(A)})),p.v2})}getPluginDetails(e){return u(this,null,function*(){const{plugin:r}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r})}getPluginConfig(e){return u(this,null,function*(){return(yield this.axios.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const r={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return n})}getPresignedUrls(e,r){return u(this,null,function*(){const n=Uc(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof n=="number"?n:void 0};Q.hasFeature(ie.FEAT_CHAT_SDK)&&(i.viewType=r);const{getLocation:s,putLocation:o}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",i)).data.data;return{getLocation:s,putLocation:o}})}uploadFile(e,r){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){l.error(`sendFileMessage::${n}`)}else yield this.axios.put(r,e,{headers:{"Content-Type":e.type}})})}}zu([y.trace("APIClient.getIPDetails")],vd.prototype,"getIPDetails",1);zu([y.trace("APIClient.getICEServers")],vd.prototype,"getICEServers",1);zu([y.trace("APIClient.getPlugins")],vd.prototype,"getPlugins",1);var vD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,sn=(t,e,r,n)=>{for(var i=n>1?void 0:n?yD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&vD(e,r,i),i};class Rr extends vd{startLivestreaming(e){return u(this,arguments,function*({manualIngestion:r}){const n=fr(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!r})).data.data;return{playbackUrl:n.playbackUrl,status:n.status,manualIngest:n.manualIngest,ingestionCredentials:n.streamKey?{ingestionServer:n.ingestServer,streamKey:n.streamKey}:null}})}stopLivestreaming(){return u(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return u(this,null,function*(){const e=fr((yield this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}})}getUserDetails(){return u(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return fr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",Z(B({},Dv(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r}))).data.data.id})}updateRecording(e,r){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:r})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:r}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}})}getActiveTranscript(){return u(this,null,function*(){const{transcript_download_url:e}=(yield this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(yield this.axios.get(e)).data}}catch{throw new b("Cant fetch transcript s3 url","1801")}})}getRoomNodeData(){return u(this,null,function*(){const e=yield this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{roomNodeLink:r,title:n,useHiveMedia:i,sfu:s}=fr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}sn([y.trace("APIClient.startLivestreaming")],Rr.prototype,"startLivestreaming",1);sn([y.trace("APIClient.stopLivestreaming")],Rr.prototype,"stopLivestreaming",1);sn([y.trace("APIClient.getActiveLivestream")],Rr.prototype,"getActiveLivestream",1);sn([y.trace("APIClient.getUserDetails")],Rr.prototype,"getUserDetails",1);sn([y.trace("APIClient.startRecording")],Rr.prototype,"startRecording",1);sn([y.trace("APIClient.stopRecording")],Rr.prototype,"updateRecording",1);sn([y.trace("APIClient.getActiveRecording")],Rr.prototype,"getActiveRecording",1);sn([y.trace("APIClient.getActiveTranscript")],Rr.prototype,"getActiveTranscript",1);sn([y.trace("APIClient.getRoomNodeData")],Rr.prototype,"getRoomNodeData",1);let Yl;function SD(t,e){return Yl=new Rr(t,e),Yl}function Ke(){return Yl}function ED(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
27
27
 
28
- ${t}`}function Pt(t){return function(e,r,n){const i=n.value;let s=0,o=Date.now();return n.value=function(...a){const d=Date.now();if(d-o>t.period*1e3&&(o=d,s=0),s>=t.maxInvocations)throw new C(`Method rate limit ${t.maxInvocations} invocations/${t.period}sec exceeded`);return s+=1,i.apply(this,a)},n}}var jA=Object.defineProperty,HA=Object.getOwnPropertyDescriptor,pt=(t,e,r,n)=>{for(var i=n>1?void 0:n?HA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&jA(e,r,i),i};const WA=["text","image","file","custom","poll"],fa={maxInvocations:180,period:60};var re,_i,Ye,ki,No,kd,Sp,Tp;let nt=(Tp=class extends Ut{constructor(t,e,r,n,i){super(),k(this,kd),m(this,"messages"),m(this,"channels",[]),k(this,re,void 0),k(this,_i,void 0),k(this,Ye,void 0),k(this,ki,void 0),k(this,No,void 0),m(this,"maxTextLimit",2e3),T(this,No,t),T(this,Ye,e),T(this,ki,r),T(this,re,n),T(this,_i,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get roomJoined(){var t;return((t=c(this,kd,Sp))==null?void 0:t.roomJoined)===!0}sendMessageInternal(t,e,r){return u(this,arguments,function*(n,i,s,o={}){switch(n.type){case"text":{const a=o.replyTo&&o.replyTo.type==="text"?BA(n.message,o.replyTo.message):n.message;yield this.sendTextMessageInternal(a,i,s);break}case"image":yield this.sendImageMessageInternal(n.image,i,s);break;case"file":yield this.sendFileMessageInternal(n.file,i,s);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(t.length>this.maxTextLimit)throw new C("Max character limit breached");if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");if(r){c(this,Ye).sendMessageToChannel(t,_t.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,re).id),h=c(this,_i).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,re).userId)),c(this,Ye).sendMessage(t,_t.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=We(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,Ye).sendMessageToChannel(p,_t.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,_i).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),g.push(c(this,re).userId)),c(this,Ye).sendMessage(p,_t.IMAGE,e)}catch{throw new C("Error sending image message.")}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=We(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,Ye).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),_t.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,_i).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,re).userId));const E=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,Ye).sendMessage(E,_t.FILE,e)}catch{throw new C("Error sending file message.")}})}get rateLimits(){return fa}updateRateLimits(t,e){fa.maxInvocations=t,fa.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,n,i,s,o,a,d,h,p,f,g,E,v,I,A;if(e&&e.length>0){if(!((r=c(this,re).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,re).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)||!((p=(h=c(this,re).permissions)==null?void 0:h.chatPublic)!=null&&p.text)){l.error("sendCustomMessage::permission_denied");return}const D=W=>u(this,null,function*(){try{if(typeof W=="string")return{link:W};const H=We(),{getLocation:R,putLocation:S}=yield H.getPresignedUrls(W.name,c(this,re).config.viewType);return yield H.uploadFile(W,S),{link:R,type:W.type,name:W.name,size:W.size}}catch{throw new C("Error sending image message.")}}),x=ne(V({},t),{files:yield Promise.all((g=(f=t.files)!=null?f:[])==null?void 0:g.map(W=>u(this,null,function*(){return D(W)}))),images:yield Promise.all((v=(E=t.images)!=null?E:[])==null?void 0:v.map(W=>u(this,null,function*(){return D(W)}))),videos:yield Promise.all((A=(I=t.videos)!=null?I:[])==null?void 0:A.map(W=>u(this,null,function*(){return D(W)})))});c(this,Ye).sendMessage(JSON.stringify(x),_t.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(((i=(n=c(this,re).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,Ye).editMessage(t,e,_t.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const a=We(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,Ye).editMessage(t,d,_t.IMAGE,r)}catch{throw new C("Error editing image message.")}})}editFileMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const a=We(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,Ye).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),_t.FILE,r)}catch{throw new C("Error editing file message.")}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,n;if(((n=(r=c(this,re).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");c(this,Ye).deleteMessage(t,e)})}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}pin(t){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to pin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,Ye).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`)})}unpin(t){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,Ye).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`)})}getMessages(t,e,r,n=0,i=void 0){return u(this,null,function*(){const s=yield c(this,Ye).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(o=>Nr.formatSocketServiceMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const o=(s=c(this,re).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(i.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new C("channel name cannot be empty.","0510");const a=[...new Set([...n,c(this,re).userId])];return yield c(this,ki).createChannel(r.trim(),a,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var r,n,i,s,o;const a=this.channels.find(p=>p.id===t),d=(r=c(this,re).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(a.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(a.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const h={memberIds:(n=e.memberIds)!=null?n:a.memberIds,displayName:(i=e.displayName)!=null?i:a.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:a.displayPictureUrl,visibility:(o=e.visibility)!=null?o:a.visibility};return c(this,ki).updateChannel(t,h)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,n,i={}){return this.sendMessageInternal(r,null,n,i)})}getChannelMembers(t){return u(this,null,function*(){return c(this,ki).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!K.hasFeature(X.FEAT_CHAT_SDK_SEARCH))throw new C("searchMessages is temporarily disabled!");return(yield c(this,Ye).searchMessages(e,r)).map(Nr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,Ye).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=ne(V({},r),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},re=new WeakMap,_i=new WeakMap,Ye=new WeakMap,ki=new WeakMap,No=new WeakMap,kd=new WeakSet,Sp=function(){return c(this,No).getValue("roomNodeClient")},Tp);pt([y.trace("DyteChat.sendTextMessage"),Pt(fa)],nt.prototype,"sendTextMessage",1);pt([y.trace("DyteChat.sendImageMessage"),Pt({maxInvocations:20,period:60})],nt.prototype,"sendImageMessage",1);pt([y.trace("DyteChat.sendFileMessage"),Pt({maxInvocations:20,period:60})],nt.prototype,"sendFileMessage",1);pt([y.trace("DyteChat.sendMessage"),Pt({maxInvocations:180,period:60})],nt.prototype,"sendMessage",1);pt([y.trace("DyteChat.editTextMessage")],nt.prototype,"editTextMessage",1);pt([y.trace("DyteChat.editImageMessage")],nt.prototype,"editImageMessage",1);pt([y.trace("DyteChat.editFileMessage")],nt.prototype,"editFileMessage",1);pt([y.trace("DyteChat.editMessage")],nt.prototype,"editMessage",1);pt([y.trace("DyteChat.deleteMessage")],nt.prototype,"deleteMessage",1);pt([y.trace("DyteChat.createChannel")],nt.prototype,"createChannel",1);pt([y.trace("DyteChat.updateChannel")],nt.prototype,"updateChannel",1);pt([y.trace("DyteChat.sendMessageToChannel")],nt.prototype,"sendMessageToChannel",1);pt([y.trace("DyteChat.getChannelMembers")],nt.prototype,"getChannelMembers",1);pt([y.trace("DyteChat.searchMessages")],nt.prototype,"searchMessages",1);pt([y.trace("DyteChat.markLastReadMessage")],nt.prototype,"markLastReadMessage",1);nt=pt([ht("0500")],nt);var b=(t=>(t.NEW_PRODUCER="NEW_PRODUCER",t.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",t.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",t.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",t.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",t.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",t.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",t.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",t.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",t.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",t.ROOM_NODE_FAILED="ROOM_NODE_FAILED",t.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",t.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",t.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",t.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",t.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",t.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",t.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",t.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",t.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",t.WAITLISTED="WAIT_LISTED",t.MESSAGE="websocket/message",t.ROOM_MESSAGE="websocket/room-message",t.PEER_JOINED_INTERNAL="peer/joined-internal",t.PEER_CLOSED="websocket/peer-closed",t.CONSUMER_CLOSED="websocket/consumer-closed",t.CONSUMER_PAUSED="websocket/consumer-paused",t.CONSUMER_RESUMED="websocket/consumer-resumed",t.PRODUCER_CLOSED="websocket/producer-closed",t.NEW_CONSUMER="websocket/new-consumer",t.PRODUCER_SCORE="websocket/producer-score",t.CONSUMER_SCORE="websocket/consumer-score",t.PRODUCER_TOGGLE="hive/producer-toggle",t.CONSUMER_TOGGLE="hive/consumer-toggle",t.SELECTED_PEERS_DIFF="hive/selected-peers-diff",t.REFRESH_GRID="hive/refresh-grid",t.UPDATE_ACTIVE="media/update-active",t.RESET_PRODUCER_STATE="hive/reset-producer-state",t.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",t.CF_ROOM_REJOINING="cf/room-rejoining",t.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",t.CF_ROOM_REJOINED="cf/room-rejoined",t.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",t.ROOM_STATE="sockethub/room-state",t.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",t.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",t.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",t.KICK_PEER="KICK_PEER",t.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",t.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",t.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",t.PIP_HANGUP="PIP_HANGUP",t.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",t.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",t.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",t.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",t.SOCKET_PEERS="SOCKET_PEERS",t.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",t.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",t.MUTE_ALL="MUTE_ALL",t.MUTE_ALL_VIDEO="MUTE_ALL_VIDEO",t))(b||{}),$A=Object.defineProperty,GA=Object.getOwnPropertyDescriptor,JA=(t,e,r,n)=>{for(var i=n>1?void 0:n?GA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$A(e,r,i),i},bd,_p;const Vn=(_p=class{constructor(t,e,r,n,i){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),k(this,bd,void 0),T(this,bd,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new nt(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Vn(t,e,r,n,i)})}static formatMessage(t){return ne(V({},t),{time:new Date(t.time),type:WA[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,r={displayName:t.displayName,id:t.chatId,time:e,timeMs:t.createdAtMs,type:t.payloadType,isEdited:t.isEdited,userId:t.userId,targetUserIds:t.targetUserIds,channelId:t.channelId,channelIndex:t.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:t.pinned};switch(r.type){case _t.TEXT:{r.message=t.payload;break}case _t.IMAGE:{r.link=t.payload;break}case _t.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case _t.CUSTOM:{const{html:n,images:i,message:s,videos:o,files:a}=JSON.parse(t.payload);r.message=s,r.html=n,r.images=i,r.videos=o,r.files=a;break}}return Vn.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||K.hasFeature(X.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=Hg.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Vn.formatSocketServiceMessage(r))})}setupEvents(){w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Le.sendMessageToRoom,t=>{const e=Vn.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(n=>n.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Le.sendMessageToPeers,t=>{const e=Vn.formatSocketServiceMessage(t.message);this.chat.messages=[...this.chat.messages,e],this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Le.editMessage,t=>{const e=Vn.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(n=>n.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Le.deleteMessage,t=>{if(t.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:t.chatId,channelId:t.channelId},messages:this.chat.messages});return}const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ei.createChatChannel,t=>{const[e]=t.chatChannels,r=si.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(Le.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ei.updateChatChannel,t=>{const[e]=t.chatChannels,r=si.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},bd=new WeakMap,_p);let Nr=Vn;JA([y.trace("ChatController.setupEvents")],Nr.prototype,"setupEvents",1);var qA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,zA=(t,e,r,n)=>{for(var i=n>1?void 0:n?KA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&qA(e,r,i),i},wd,kp,bi,ys,Lo,bp;let dl=(bp=class extends Ut{constructor(t,e,r){super(),k(this,wd),m(this,"items"),k(this,bi,void 0),k(this,ys,void 0),k(this,Lo,void 0),T(this,Lo,t),T(this,bi,e),T(this,ys,r),this.items=[]}get roomJoined(){var t;return((t=c(this,wd,kp))==null?void 0:t.roomJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(c(this,bi).config.viewType!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can't create polls without joining room");if(!c(this,bi).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield c(this,ys).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,bi).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,ys).votePoll(t,e)})}},wd=new WeakSet,kp=function(){return c(this,Lo).getValue("roomNodeClient")},bi=new WeakMap,ys=new WeakMap,Lo=new WeakMap,bp);dl=zA([ht("0700")],dl);var YA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,XA=(t,e,r,n)=>{for(var i=n>1?void 0:n?QA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&YA(e,r,i),i},xo,kn,wp;const Ui=(wp=class{constructor(t,e,r){m(this,"polls"),k(this,xo,void 0),k(this,kn,void 0),this.polls=new dl(t,e,r),T(this,xo,e),T(this,kn,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Ui(t,e,r)})}canViewPolls(){return c(this,xo).permissions.polls.canView}setupEvents(){w.on(b.UPDATE_PERMISSIONS,t=>{t.polls&&(t.polls.canView?this.getPolls():this.polls.items=[])}),this.canViewPolls()&&(w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),c(this,kn).on(Pr.createPoll,t=>{t.poll&&this.updatePoll(Ui.formatSocketServicePoll(t.poll))}),c(this,kn).on(Pr.updatePoll,t=>{t.poll&&this.updatePoll(Ui.formatSocketServicePoll(t.poll))}),c(this,kn).on(Pr.votePoll,t=>{t.poll&&this.updatePoll(Ui.formatSocketServicePoll(t.poll))}))}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==JSON.stringify(t)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,t],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}getPolls(){return u(this,null,function*(){const t=yield c(this,kn).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=lA.fromBinary(t.payload);this.polls.items=e.map(r=>Ui.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(n=>({id:n.userId,name:n.name}))}));return{anonymous:t.anonymous,createdBy:t.createdBy,createdByUserId:t.createdByUserId,hideVotes:t.hideVotes,id:t.pollId,options:e,question:t.question,voted:t.votes}}},xo=new WeakMap,kn=new WeakMap,wp);let qg=Ui;XA([y.trace("PollController.setupEvents")],qg.prototype,"setupEvents",1);var ZA=Object.defineProperty,eM=Object.getOwnPropertyDescriptor,tM=(t,e,r,n)=>{for(var i=n>1?void 0:n?eM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&ZA(e,r,i),i},Kg=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Kg||{}),Fo,Es,Uo,wi,Vo,Cp;let ll=(Cp=class extends Ut{constructor(t,e,r,n,i){super(),k(this,Es),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),k(this,Fo,void 0),k(this,wi,void 0),k(this,Vo,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),T(this,Fo,t),T(this,wi,e),this.viewType=r,T(this,Vo,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){var t;return(t=c(this,Es,Uo))==null?void 0:t.socketState}get mediaState(){var t;return(t=c(this,Es,Uo))==null?void 0:t.mediaState}get meetingId(){var t;return(t=c(this,Es,Uo))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,wi).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,wi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,Vo).broadcastMessage("spotlight",{userId:c(this,wi).userId,currentTab:this.selfActiveTab})}},Fo=new WeakMap,Es=new WeakSet,Uo=function(){return c(this,Fo).getValue("roomNodeClient")},wi=new WeakMap,Vo=new WeakMap,Cp);ll=tM([ht("0800")],ll);function rM(t){let e="",r=[""];const n=[r];let i=0,s=0,o=!0,a;for(a of t)a==='"'?(o&&a===e&&(r[i]+=a),o=!o):a===","&&o?a=r[++i]="":a===`
29
- `&&o?(e==="\r"&&(r[i]=r[i].slice(0,-1)),r=n[++s]=[a=""],i=0):r[i]+=a,e=a;return n}var nM=Object.defineProperty,iM=Object.getOwnPropertyDescriptor,zg=(t,e,r,n)=>{for(var i=n>1?void 0:n?iM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&nM(e,r,i),i};let mn=class extends Ut{constructor(){super(),m(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new mn;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,s,o,a]]=rM(t);return{id:di(),name:o,peerId:n,userId:i,customParticipantId:s,transcript:a,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(`
30
- `).map(e=>mn.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=We(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=mn.parseTranscripts(e)}catch{}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const n=r.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts.push(t),this.emit("transcript",t)})}};zg([y.trace("DyteAi.getActiveTranscript")],mn.prototype,"getActiveTranscript",1);mn=zg([ht("0000")],mn);var sM=Object.defineProperty,oM=Object.getOwnPropertyDescriptor,aM=(t,e,r,n)=>{for(var i=n>1?void 0:n?oM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&sM(e,r,i),i},bn,Ss,Cd,Ip;const Yg=(Ip=class{constructor(t,e,r,n,i,s){m(this,"meta"),m(this,"ai"),k(this,bn,void 0),k(this,Ss,void 0),m(this,"aiSocketHandler"),k(this,Cd,void 0),T(this,Cd,t),this.meta=new ll(t,e,e.config.viewType,r,s),this.ai=n,T(this,bn,e),T(this,Ss,r),this.aiSocketHandler=i,e.config.viewType!==qe.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield mn.init(e.permissions.transcriptionEnabled);return new Yg(t,e,r,s,n,i)})}conditionallySetActiveTab(t){var e;t!=null&&t.currentTab&&((e=this.meta.selfActiveTab)==null?void 0:e.id)!==t.currentTab.id&&(this.meta.setSelfActiveTab(t.currentTab,Kg.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){w.on(b.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),w.on(b.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),w.on(b.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),w.on(b.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,bn).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,Ss).broadcastMessage("spotlight",{userId:c(this,bn).userId,currentTab:this.meta.selfActiveTab})),w.on(b.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,bn).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,Ss).broadcastToPeers("spotlight",[t.id],{userId:c(this,bn).userId,currentTab:this.meta.selfActiveTab})})),w.on(b.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),w.on(b.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:r,isPartial:n}=t,i=mn.parseTranscript(r,n);if(!i){l.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:o,transcript:a}=i;l.debug(`${e} Received transcript for peer ${s} - ${o}: ${a}`)})}},bn=new WeakMap,Ss=new WeakMap,Cd=new WeakMap,Ip);let Qg=Yg;aM([y.trace("MetaController.setupEvents")],Qg.prototype,"setupEvents",1);var cM=Object.defineProperty,dM=Object.getOwnPropertyDescriptor,gi=(t,e,r,n)=>{for(var i=n>1?void 0:n?dM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&cM(e,r,i),i},cr,Us,Fe,ga,Bn,lr,Vs,va;class yn extends Ut{constructor(e,r,n,i,s){super(),k(this,Vs),k(this,cr,void 0),k(this,Us,void 0),k(this,Fe,void 0),k(this,ga,void 0),k(this,Bn,void 0),k(this,lr,void 0),T(this,lr,e),T(this,cr,i),T(this,Us,s),T(this,Fe,r),T(this,ga,n),T(this,Bn,[]),this.setupEvents()}get status(){return c(this,lr).getValue("stageStatus")}setupEvents(){w.onAsync(b.GET_STAGE_REQUESTS,e=>u(this,null,function*(){T(this,Bn,e)})),w.onAsync(b.UPDATE_STAGE_REQUESTS,e=>u(this,[e],function*({add:r}){const n=c(this,ga).joined.toArray().filter(i=>i.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(i=>({displayName:i.name,userId:i.userId,peerId:i.id}));(r||n.length>c(this,Bn).length)&&this.emit("newStageRequest",{count:n.length}),T(this,Bn,n),this.emit("stageAccessRequestUpdate",n)}))}getAccessRequests(){if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,Fe).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new C("You do not have permission to perform this action/");return{stageRequests:c(this,Bn)}}requestAccess(){return u(this,null,function*(){if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`);if(c(this,Fe).permissions.stageAccess===q.Allowed){ue(this,Vs,va).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,cr).requestAccess(),ue(this,Vs,va).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");c(this,cr).cancelRequestAccess(),ue(this,Vs,va).call(this,"OFF_STAGE")})}grantAccess(e){if(!c(this,Fe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,Fe).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,cr).grantAccess(e)}denyAccess(e){if(!c(this,Fe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,Fe).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,cr).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,lr).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,Fe).permissions.stageAccess===q.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`);if(yield c(this,cr).joinStage(),e===qe.Livestream){const{name:r,id:n,userId:i}=c(this,Fe);yield c(this,Us).joinRoom(r,n,i,e)}if(c(this,lr).setValue("stageStatus","ON_STAGE",!1),yield w.emitAsync(b.JOIN_MEDIA_ROOM),c(this,lr).notify("stageStatus"),e===qe.Livestream){const{peers:r}=yield c(this,Us).getStagePeers();w.emit(b.SOCKET_PEERS,r)}})}leave(){return u(this,null,function*(){if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`);c(this,Fe).setIsPinned(!1),yield c(this,cr).leaveStage(c(this,Fe).userId),c(this,lr).setValue("stageStatus","OFF_STAGE",!1),yield w.emitAsync(b.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,lr).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!c(this,Fe).roomJoined)throw new C("Can`t kick participant without joining room");if(!c(this,Fe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,Fe).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new C("You do not have permissions for kick");return c(this,cr).kick(e)})}}cr=new WeakMap,Us=new WeakMap,Fe=new WeakMap,ga=new WeakMap,Bn=new WeakMap,lr=new WeakMap,Vs=new WeakSet,va=function(t){return u(this,null,function*(){this.status!==t&&c(this,lr).setValue("stageStatus",t)})};gi([y.trace("DyteStage.getStageRequests")],yn.prototype,"getAccessRequests",1);gi([y.trace("DyteStage.requestAccess")],yn.prototype,"requestAccess",1);gi([y.trace("DyteStage.cancelRequestAccess")],yn.prototype,"cancelRequestAccess",1);gi([y.trace("DyteStage.grantAccess")],yn.prototype,"grantAccess",1);gi([y.trace("DyteStage.denyAccess")],yn.prototype,"denyAccess",1);gi([y.trace("DyteStage.joinStage")],yn.prototype,"join",1);gi([y.trace("DyteStage.leaveStage")],yn.prototype,"leave",1);function lM(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function oc(t){switch(t){case Dr.UNSPECIFIED:return"OFF_STAGE";case Dr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Dr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Dr.OFF_STAGE:return"OFF_STAGE";case Dr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var uM=Object.defineProperty,hM=Object.getOwnPropertyDescriptor,pM=(t,e,r,n)=>{for(var i=n>1?void 0:n?hM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&uM(e,r,i),i},jn,Vi,Hn,ya,rn;class Xg{constructor(e,r,n,i,s){m(this,"stage"),k(this,jn,void 0),k(this,Vi,void 0),k(this,Hn,void 0),k(this,ya,0),k(this,rn,void 0),T(this,rn,e),this.stage=new yn(e,i,s,r,n),T(this,Hn,r),T(this,jn,i),T(this,Vi,s),this.setupEvents()}setupEvents(){c(this,rn).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,Hn).on(j.grantStageAccess,()=>{c(this,jn).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Hn).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,jn).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,Hn).on(j.denyStageAccess,()=>{c(this,jn).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Hn).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,jn).permissions.stageAccess!==q.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield w.emitAsync(b.GET_STAGE_REQUESTS,n),c(this,ya)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),T(this,ya,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Vi).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&c(this,rn).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=oc(e.stageType),n=c(this,rn).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,rn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:c(this,rn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Vi).joined.get(e.peerId),n=c(this,Vi).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&w.emit(b.REFRESH_GRID);break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),n&&w.emit(b.REFRESH_GRID);break}w.emit(b.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}jn=new WeakMap,Vi=new WeakMap,Hn=new WeakMap,ya=new WeakMap,rn=new WeakMap;pM([y.trace("DyteStage.setupEvents")],Xg.prototype,"setupEvents",1);var mM=Object.defineProperty,fM=Object.getOwnPropertyDescriptor,xc=(t,e,r,n)=>{for(var i=n>1?void 0:n?fM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&mM(e,r,i),i};const Ue={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var mt,Kt,Ts,_s,Wr,ks,bs,Ci,ws,Rp;let ns=(Rp=class extends ds{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:s,organizationId:o,picture:a,private:d,published:h,staggered:p,tags:f,type:g,updatedAt:E},v,I,A,D){super(),k(this,Ci),k(this,mt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),k(this,Kt,void 0),k(this,Ts,void 0),k(this,_s,void 0),m(this,"organizationId"),m(this,"picture"),m(this,"private"),m(this,"published"),m(this,"staggered"),m(this,"tags"),m(this,"type"),m(this,"updatedAt"),k(this,Wr,void 0),m(this,"config"),k(this,ks,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),k(this,bs,void 0),T(this,bs,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,T(this,Kt,I),this.organizationId=o,this.picture=a,this.private=d,this.published=h,this.staggered=p,this.tags=f,this.type=g,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,T(this,mt,v),T(this,Ts,A),T(this,_s,D),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:n,uuid:i,type:s}=r;switch(s){case J.customPluginEventToRoom:{c(this,mt).customPluginEventToRoom(this.id,n,i);break}case J.customPluginEventToPeers:{c(this,mt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case J.enablePluginForRoom:{c(this,mt).enablePluginForRoom(this.id,i);break}case J.enablePluginForPeers:{c(this,mt).enablePluginForPeers(this.id,n.peerIds,i);break}case J.disablePluginForRoom:{c(this,mt).disablePluginForRoom(this.id,i);break}case J.disablePluginForPeers:{c(this,mt).disablePluginForPeers(this.id,n.peerIds,i);break}case J.storeInsertKeys:{c(this,mt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case J.storeGetKeys:{c(this,mt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case J.storeDeleteKeys:{c(this,mt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case J.storeDelete:{c(this,mt).storeDelete(this.id,n.store,i);break}case Ue.chatMessage:{const{messagePayload:o,peerIds:a}=n;if(!c(this,_s)){this.sendIframeEvent({type:Ue.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,_s).sendMessage(o,a),this.sendIframeEvent({type:Ue.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ue.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Ue.getPeer:{let o;const{peerId:a}=n,d=ne(V({},c(this,Kt)),{isRecorder:(e=c(this,Kt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Kt).permissions.hiddenParticipant,stageStatus:c(this,Kt).stageStatus});a?(o=c(this,Ts).joined.get(n.peerId),c(this,Kt).id===a&&(o=d)):o=d,this.sendIframeEvent({type:Ue.getPeer,payload:{peer:o&&sc(o)},uuid:r.uuid});break}case Ue.getPeers:{const o=c(this,Ts).joined.toArray().map(a=>sc(a));this.sendIframeEvent({type:Ue.getPeers,payload:{peers:o},uuid:r.uuid});break}case Ue.getPluginInitiator:{this.sendIframeEvent({type:Ue.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Ue.getDisplayTitle:{this.sendIframeEvent({type:Ue.getDisplayTitle,payload:{displayTitle:c(this,Ci,ws).meetingTitle},uuid:r.uuid});break}case Ue.getRoomName:{this.sendIframeEvent({type:Ue.getRoomName,payload:{roomName:c(this,Ci,ws).roomName},uuid:r.uuid});break}case Ue.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ue.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:n}=(e=this.iframes.get(t))!=null?e:{};(r||n)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!c(this,ks))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new C("No auth token set for plugin.");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new C("Iframe was not provided.");this.removePluginView(e);const n=t,i=new URL(this.baseURL),s={auth:c(this,ks),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,bs).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Ci,ws).roomName)!=null?r:"",displayTitle:c(this,Ci,ws).meetingTitle};if(Object.keys(s).forEach(o=>{i.searchParams.set(o,s[o])}),n.src=i.href,n.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",n.title=e,navigator.isReactNative)n.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:n});else{const o=a=>u(this,null,function*(){a.source===t.contentWindow&&(yield this.handleIframeMessage(a.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:n,listener:o})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=We(),e=yield t.authorizePlugin(this.id);T(this,ks,e),T(this,Wr,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),T(this,Wr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=c(this,Kt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,mt).addPlugin(this.id,this.staggered),T(this,Wr,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=c(this,Kt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Kt).id||(c(this,mt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,Wr)?new Date().getTime()-c(this,Wr).getTime():0}}),T(this,Wr,void 0)))})}},mt=new WeakMap,Kt=new WeakMap,Ts=new WeakMap,_s=new WeakMap,Wr=new WeakMap,ks=new WeakMap,bs=new WeakMap,Ci=new WeakSet,ws=function(){return c(this,bs).getValue("roomNodeClient")},Rp);xc([Pt({maxInvocations:5,period:1})],ns.prototype,"sendData",1);xc([y.trace("DytePlugin.activatePlugin")],ns.prototype,"activate",1);xc([y.trace("DytePlugin.deactivatePlugin")],ns.prototype,"deactivate",1);ns=xc([ht("0600")],ns);var Je,Bi;class Zg extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),k(this,Je,void 0),k(this,Bi,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),T(this,Je,new ds),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,T(this,Bi,new Map)}emit(e,...r){return c(this,Je).emit(e,...r)}on(e,r){return c(this,Je).on(e,r)}addListener(e,r){return c(this,Je).addListener(e,r)}off(e,r){return c(this,Je).off(e,r)}once(e,r){return c(this,Je).once(e,r)}prependListener(e,r){return c(this,Je).prependListener(e,r)}prependOnceListener(e,r){return c(this,Je).prependOnceListener(e,r)}removeListener(e,r){return c(this,Je).removeListener(e,r)}removeAllListeners(e){return c(this,Je).removeAllListeners(e)}listeners(e){return c(this,Je).listeners(e)}listenerCount(e){return c(this,Je).listenerCount(e)}getMaxListeners(){return c(this,Je).getMaxListeners()}setMaxListeners(e){return c(this,Je).setMaxListeners(e)}eventNames(){return c(this,Je).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),s=(o,...a)=>{this.emit(o,r,...a)};return c(this,Bi).set(e,s),r.on("*",s),n&&c(this,Je).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,Bi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,Je).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,Bi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,Je).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}Je=new WeakMap,Bi=new WeakMap;class Pp extends Zg{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var gM=Object.defineProperty,vM=Object.getOwnPropertyDescriptor,yM=(t,e,r,n)=>{for(var i=n>1?void 0:n?vM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&gM(e,r,i),i};let ul=class{constructor(){m(this,"all"),m(this,"active"),this.all=new Pp,this.active=new Pp}};ul=yM([ht("0600")],ul);var EM=Object.defineProperty,SM=Object.getOwnPropertyDescriptor,Fc=(t,e,r,n)=>{for(var i=n>1?void 0:n?SM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&EM(e,r,i),i},zt,Cs,Bo,Ap;const ev=(Ap=class{constructor(t,e,r,n){m(this,"plugins"),k(this,zt,void 0),k(this,Cs,void 0),k(this,Bo,void 0),T(this,zt,e),T(this,Cs,r),T(this,Bo,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,o){return u(this,null,function*(){const a=new ul;return e.forEach(d=>{const h=new ns(t,d,r,s,o,i);a.all.add(h)}),new ev(t,r,n,a)})}getRoomPlugins(){return u(this,null,function*(){const{plugins:t}=yield c(this,zt).getActivePlugins();yield Promise.all(t.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,n){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:r,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),w.onAsync(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,zt).on(J.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),c(this,zt).on(J.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[J.enablePluginForPeers,J.enablePluginForRoom].forEach(t=>{c(this,zt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[J.disablePluginForPeers,J.disablePluginForRoom].forEach(t=>{c(this,zt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[J.customPluginEventToPeers,J.customPluginEventToRoom].forEach(t=>{c(this,zt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,zt).on(t,(e,r)=>u(this,null,function*(){var n;const i=(n=e.storeItems)==null?void 0:n.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:i})}))}),c(this,zt).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,Cs).on(Le.sendMessageToPeers,t=>{const e=Nr==null?void 0:Nr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ue.chatMessage,{message:e})}),c(this,Cs).on(Le.sendMessageToRoom,t=>{const e=Nr==null?void 0:Nr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ue.chatMessage,{message:e})}),w.on(b.PEER_JOINED_INTERNAL,t=>{const e=sc(t);this.broadcastIframeEvent(Ue.peerJoined,e)}),w.on(b.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ue.peerLeft,t)}),w.on(b.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ue.peerStageStatusUpdate,t)}),c(this,Bo).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ue.stageStatusUpdate,t)})}},zt=new WeakMap,Cs=new WeakMap,Bo=new WeakMap,Ap);let vo=ev;Fc([y.trace("PluginController.getRoomPlugins")],vo.prototype,"getRoomPlugins",1);Fc([y.trace("PluginController.enableForSelf")],vo.prototype,"enablePlugin",1);Fc([y.trace("PluginController.disableForSelf")],vo.prototype,"disablePlugin",1);Fc([y.trace("PluginController.setupEvents")],vo.prototype,"setupEvents",1);var TM=Object.defineProperty,_M=Object.getOwnPropertyDescriptor,yo=(t,e,r,n)=>{for(var i=n>1?void 0:n?_M(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&TM(e,r,i),i},Is,jo,Rs,Ho,Mp;let oi=(Mp=class extends Ut{constructor(t,e){super(),k(this,Rs),k(this,Is,void 0),k(this,jo,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),T(this,jo,t),T(this,Is,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!c(this,Is).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new C("User does not have permission to start recording");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(`Cant start recording, recordingState irregular: ${this.recordingState}`);try{const e=We(),{recording:r={}}=c(this,jo).getValue("defaults"),n=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording")}})}stop(t){return u(this,null,function*(){yield ue(this,Rs,Ho).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield ue(this,Rs,Ho).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield ue(this,Rs,Ho).call(this,"resume",["PAUSED"],t)})}},Is=new WeakMap,jo=new WeakMap,Rs=new WeakSet,Ho=function(t,e,r){return u(this,null,function*(){if(!c(this,Is).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new C("User does not have permission to stop recording");let n=[];if(r!==void 0){const i=this.recordings.find(s=>s.id===r);if(i===void 0)throw new C("Could not find the specified recording");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield We().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new C("Error while stopping recording")}}))})},Mp);yo([y.trace("DyteRecording.start")],oi.prototype,"start",1);yo([y.trace("DyteRecording.stop")],oi.prototype,"stop",1);yo([y.trace("DyteRecording.stop")],oi.prototype,"pause",1);yo([y.trace("DyteRecording.stop")],oi.prototype,"resume",1);oi=yo([ht("1000")],oi);var kM=Object.defineProperty,bM=Object.getOwnPropertyDescriptor,wM=(t,e,r,n)=>{for(var i=n>1?void 0:n?bM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&kM(e,r,i),i},hl;class tv{constructor(e,r,n){m(this,"recording"),m(this,"room"),k(this,hl,void 0),T(this,hl,e),this.recording=new oi(e,r),this.room=n,this.setupEvents()}setupEvents(){w.on(b.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>({id:r.recordingId,state:r.recordingStatus}))):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let r=!1;const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(r=!0,i.state="RECORDING")}),r===!1&&n.push({id:e.recordingId,state:"RECORDING"}),this.recording.updateRecordings(n)}),this.room.on(j.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(j.recordingStopped,e=>{const r=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(r)})}}hl=new WeakMap;wM([y.trace("RecordingController.setupEvents")],tv.prototype,"setupEvents",1);class CM{static hasFeature(e){var r;return(r=K.hasFeature(e))!=null?r:!1}static getFeatureValue(e){return K.getValue(e)}static getAllFeatures(){return K.getAllFlags()}}class cu{constructor(e,r,n){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Ee,this.callStats=n}static init(e){return new cu(l,CM,e)}}class du{constructor(e){m(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=cu.init(B);return new du(e)})}}var IM=Object.defineProperty,RM=Object.getOwnPropertyDescriptor,Vt=(t,e,r,n)=>{for(var i=n>1?void 0:n?RM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&IM(e,r,i),i},et,lt,Xe,Ir,Zt,Ea,pl;class At extends ds{constructor(e,r,n=Op,i=!0){super(),k(this,et,void 0),k(this,lt,void 0),k(this,Xe,void 0),k(this,Ir,void 0),k(this,Zt,void 0),k(this,Ea,void 0),k(this,pl,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),T(this,pl,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,et,new rv(e,r)),T(this,lt,new YM(c(this,et),void 0,n)),T(this,Xe,new nD(c(this,et),void 0,n)),T(this,Zt,new eD(c(this,et))),T(this,Ir,new XM(c(this,et))),T(this,Ea,i),c(this,lt).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,lt).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Xe).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Xe).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,Zt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){B.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?B.browserBackgrounded():B.browserForegrounded()}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:n}){var i;let s,o;if(r&&n)try{const a=yield c(this,et).getAudioAndVideoTrack();s=a.audioTrack,o=a.videoTrack}catch(a){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:a})}if(!s&&r)try{s=yield c(this,et).getAudioTrack(!1)}catch(a){l.error("LocalMediaHandler::init::Failed to get audio track",{error:a})}if(!o&&n)try{o=yield c(this,et).getVideoTrack()}catch(a){l.error("LocalMediaHandler::init::Failed to get video track",{error:a})}yield c(this,lt).setMediaTrack(s),yield c(this,Xe).setMediaTrack(o);try{yield c(this,Ir).setupSpeaker()}catch{}if(o){const a=yield this.getDeviceById(o.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",a)})}if(s){const a=yield this.getDeviceById(s.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",a)})}(i=c(this,Ir).currentDevice)!=null&&i.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",c(this,Ir).currentDevice)}),c(this,et).onDeviceChange((a,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,lt).currentDevice,video:c(this,Xe).currentDevice,speaker:c(this,Ir).currentDevice}}get permissions(){return c(this,et).permissions}getAllDevices(){return c(this,et).getAvailableDevices()}getDeviceById(e,r){return c(this,et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,lt).mediaTrack}get audioTrack(){return c(this,lt).transformedMediaTrack}get audioEnabled(){return c(this,lt).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,lt).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,lt).muteTrack()}getAudioDevices(e){return c(this,et).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,lt).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",e)}),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return c(this,Ir).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Ir).setupSpeaker(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",e)}),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,Xe).mediaTrack}get videoTrack(){return c(this,Xe).transformedMediaTrack}get videoEnabled(){return c(this,Xe).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Xe).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Xe).disableTrack()}getVideoDevices(e){return c(this,et).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Xe).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",e)}),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield c(this,Xe).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,Zt).audioMediaTrack,video:c(this,Zt).videoMediaTrack}}get screenShareEnabled(){return c(this,Zt).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,Zt).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,Zt).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,Zt).updateConstraints(e)})}getSpeakerDevices(e){return c(this,et).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,lt).addMiddleware(e)}removeAudioMiddleware(e){return c(this,lt).removeMiddleware(e)}addVideoMiddleware(e){return c(this,Xe).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Xe).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,Xe).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,lt).disableTrack(),c(this,Xe).disableTrack(),c(this,Xe).terminateMiddlewareWebWorker(),c(this,Zt).disableScreenShare(),c(this,et).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,Ea))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!Op(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const a=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);a&&(yield this.setSpeakerDevice(a))}})))})}removeAllTracks(){this.destruct()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}et=new WeakMap,lt=new WeakMap,Xe=new WeakMap,Ir=new WeakMap,Zt=new WeakMap,Ea=new WeakMap,pl=new WeakMap;Vt([y.trace("MediaHandler.setupStreams")],At.prototype,"setupStreams",1);Vt([y.trace("MediaHandler.enableAudio")],At.prototype,"enableAudio",1);Vt([y.trace("MediaHandler.disableAudio")],At.prototype,"disableAudio",1);Vt([y.trace("MediaHandler.setAudioDevice")],At.prototype,"setAudioDevice",1);Vt([y.trace("MediaHandler.enableVideo")],At.prototype,"enableVideo",1);Vt([y.trace("MediaHandler.disableVideo")],At.prototype,"disableVideo",1);Vt([y.trace("MediaHandler.setVideoDevice")],At.prototype,"setVideoDevice",1);Vt([y.trace("MediaHandler.updateVideoConstraints")],At.prototype,"updateVideoConstraints",1);Vt([y.trace("MediaHandler.enableScreenShare")],At.prototype,"enableScreenShare",1);Vt([y.trace("MediaHandler.disableScreenShare")],At.prototype,"disableScreenShare",1);Vt([y.trace("MediaHandler.updateScreenshareConstraints")],At.prototype,"updateScreenshareConstraints",1);Vt([y.trace("MediaHandler.destruct")],At.prototype,"destruct",1);Vt([y.trace("MediaHandler.onDeviceChange")],At.prototype,"onDeviceChange",1);var ml=(t=>(t.NotAllowedError="NotAllowedError",t.NotReadableError="NotReadableError",t.NO_DEVICES_AVAILABLEError="NO_DEVICES_AVAILABLEError",t.AbortError="AbortError",t))(ml||{});function Dp(t,e,r){switch(!0){case Ee.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ee.isSafari():switch(e){case"NotReadableError":return"DENIED";default:return"COULD_NOT_START"}case Ee.isFirefox():switch(e){case"NO_DEVICES_AVAILABLEError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const PM=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function Op(t){const e=t.label.toLowerCase();return Ee._bowser.getOSName()==="macOS"&&e.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):PM.some(r=>e.includes(r))}function AM(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const r=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(o=>o(r))),i=r.createMediaStreamSource(new MediaStream([e])),s=r.createMediaStreamDestination();try{let o=i;for(let a=0;a<n.length;a+=1)o.connect(n[a]),o=n[a];o.connect(s)}catch(o){return l.error("getTransformedAudioTrack::middleware_execution_failed",{error:o}),e}return s.stream.getAudioTracks()[0]})}var ji;class MM{constructor(){k(this,ji,void 0)}terminateMiddlewareWebWorker(){if(c(this,ji))try{Nm(c(this,ji)),T(this,ji,void 0)}catch{l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,n){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:i,WorkerTimers:Yy})));if(n.disablePerFrameCanvasRendering)return i.captureStream().getVideoTracks()[0];const o=document.createElement("video"),a=new MediaStream;a.addTrack(r);const d=i.getContext("2d");o.srcObject=a,o.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](i,d))}catch(p){l.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch{}return o.addEventListener("play",()=>{i.width=o.width||r.getSettings().width,i.height=o.width||r.getSettings().height,T(this,ji,Lm(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}ji=new WeakMap;const Np={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},Lp={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]},DM={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},xp={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]};var Y=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Y||{});const OM=Gb(),Ii=fr(OM.config.media);function NM(t){var e,r;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),n.video=t.video.quality,n}var Hi,fl;class LM{constructor(e,r){k(this,Hi,void 0),k(this,fl,void 0),m(this,"getScreenShareConstraints",()=>{var n,i,s,o,a,d,h,p,f;const g=(n=c(this,Hi))==null?void 0:n.screenshare,E=(s=(i=g==null?void 0:g.width)==null?void 0:i.max)!=null?s:1920,v=(a=(o=g==null?void 0:g.height)==null?void 0:o.max)!=null?a:1080,I=(h=(d=g==null?void 0:g.frameRate)==null?void 0:d.max)!=null?h:5;let A=(f=(p=g==null?void 0:g.frameRate)==null?void 0:p.ideal)!=null?f:5;const D=g==null?void 0:g.displaySurface,x=g==null?void 0:g.selfBrowserSurface;K.getValue(X.VAL_MIN_FRAMERATE)&&(A=parseInt(K.getValue(X.VAL_MIN_FRAMERATE),10));let W={width:{max:E},height:{max:v},frameRate:{ideal:A,max:I}};if(K.hasFeature(X.SCREENSHARE_CONSTRAINTS)){const H=K.getValue(X.SCREENSHARE_CONSTRAINTS);W=JSON.parse(H)}return D!==void 0&&["monitor","browser","window"].includes(D)&&(W=ne(V({},W),{displaySurface:D})),x!==void 0&&(W=ne(V({},W),{selfBrowserSurface:x})),{audio:!0,video:W}}),m(this,"getAudioConstraints",n=>{var i,s,o,a,d,h,p,f;const g={},E=(i=c(this,Hi))==null?void 0:i.audio,v=E!=null&&E.enableStereo?2:1;return Ee.isFirefox()||Ee.isWebKitBased()?(g.audio={deviceId:n,autoGainControl:(s=E==null?void 0:E.autoGainControl)!=null?s:!0,echoCancellation:(o=E==null?void 0:E.echoCancellation)!=null?o:!0,noiseSuppression:(a=E==null?void 0:E.noiseSupression)!=null?a:!0,channelCount:v},g):(g.audio={},g.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:v},{echoCancellation:(d=E==null?void 0:E.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=E==null?void 0:E.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=E==null?void 0:E.autoGainControl)!=null?p:!0},{googNoiseSuppression:(f=E==null?void 0:E.noiseSupression)!=null?f:!0},{googHighpassFilter:!0}],g)}),m(this,"getVideoConstraints",n=>{var i,s,o;const a={},d=(i=c(this,Hi))==null?void 0:i.video;let h=Np.vga;if(typeof d=="string"?h=Np[d]:d!==void 0&&(h.height.ideal=d.height.ideal,h.width.ideal=d.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},Ee.isChromiumBased()&&(h.frameRate.max=30),K.hasFeature(X.VIDEO_CONSTRAINTS)){const p=K.getValue(X.VIDEO_CONSTRAINTS);h=JSON.parse(p)}return a.video=h,typeof a.video=="boolean"||(n?a.video.deviceId={exact:n}:a.video.facingMode="user"),a}),T(this,fl,e),T(this,Hi,r)}getUpdatedVideoConstraints(e){return e}}Hi=new WeakMap,fl=new WeakMap;class Fp extends Error{constructor(e,r,n){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=n}}class xM{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audiooutput")})}}var FM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,ar=(t,e,r,n)=>{for(var i=n>1?void 0:n?UM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&FM(e,r,i),i},Ps,Sr,Id,Up;let Ft=(Up=class extends xM{constructor(t,e){super(),m(this,"availableDevices"),k(this,Ps,void 0),k(this,Sr,void 0),k(this,Id,void 0),T(this,Id,t),T(this,Sr,new LM(t,e)),T(this,Ps,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,Sr)}destruct(){return u(this,null,function*(){var t;(t=c(this,Ps))==null||t.abort()})}handlePermissionErrors(t,e){const r=Dp(t,e.name,e.message);return this.permissions[t]=r,w.emit(b.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,Sr).getAudioConstraints().audio,video:c(this,Sr).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=yield navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",K.hasFeature(X.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const i=(yield this.getVideoInputDevices()).find(s=>s.label.includes("OBS Virtual"));n=yield this.getVideoTrack(i.deviceId)}return w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new C("Couldnt fetch audio and video track")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available");const n=i=>u(this,null,function*(){let s;try{r=r.filter(a=>a.deviceId!==i),s=c(this,Sr).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const o=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks()[0];return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const a=Dp("audio",o.name,o.message),d=new Fp(o.name,o.message,s);if(a==="COULD_NOT_START"){const h=r.shift();if(!h)throw d;return n(h.deviceId)}throw d}});try{const i=yield n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new C(i.message,"1601")}})}handleGUMError(t,e,r){return u(this,null,function*(){throw this.handlePermissionErrors(t,new Fp(e.name,e.message,r)),l.error(`WebMediaInterface.get${t}Tracks Error while fetching ${t} tracks`,{error:e}),new C(`Couldnt fetch ${t} tracks`)})}getScreenShareTracks(){return u(this,null,function*(){let t=c(this,Sr).getScreenShareConstraints(),e;try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(t)}),B.screenShareRequested(),e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(t)})}catch(r){if(r.name===ml.NotReadableError&&Ee.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{t={video:!0},e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media_retry",{constraints:JSON.stringify(t)})}catch{yield this.handleGUMError("screenshare",r,t)}else yield this.handleGUMError("screenshare",r,t)}return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:e.getAudioTracks()[0],videoTrack:e.getVideoTracks()[0]}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getVideoTrack(t){return u(this,null,function*(){const e=K.hasFeature(X.OBS_QUALITY),r=yield this.getCurrentDeviceLabel(t),n=r&&r.includes("OBS Virtual"),{video:i}=c(this,Sr).getVideoConstraints(t);let s={},o;e&&n&&typeof i!="boolean"?s={deviceId:i.deviceId}:s=i;try{if((yield this.getVideoInputDevices()).length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available");[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)})}catch(a){if(a.name===ml.NotReadableError&&Ee.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{s=!0,[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media_retry",{constraints:JSON.stringify(s)})}catch(d){yield this.handleGUMError("video",d,s)}else yield this.handleGUMError("video",a,s)}if(e&&n&&typeof i!="boolean"&&typeof i.width=="object"){const{width:a,height:d}=o.getSettings(),{ideal:h}=i.width;o.applyConstraints({width:{ideal:h},height:{ideal:Math.floor(d*h/a)},frameRate:i.frameRate})}return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),o})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new C("Failed to get available devices")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get device")}})}onDeviceChange(t){return u(this,null,function*(){Ee.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,n;const i=p=>`${p.kind}-${p.deviceId}`,s=this.availableDevices,o=new Set(s.map(p=>i(p))),a=yield this.getAvailableDevices(),d=new Set(a.map(p=>i(p))),h={added:a.filter(p=>!o.has(i(p))),removed:s.filter(p=>!d.has(i(p))),devices:a};if((r=h.added)!=null&&r.length||(n=h.removed)!=null&&n.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...h.added,...h.removed];B.onSafeInitialization(()=>u(this,null,function*(){p.some(f=>f.kind==="audioinput")&&B.devices("AUDIO",a==null?void 0:a.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&B.devices("VIDEO",a==null?void 0:a.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&B.devices("SPEAKER",a==null?void 0:a.filter(f=>f.kind==="audiooutput"))})),t(e,h,!1)}}),{signal:c(this,Ps).signal})})}},Ps=new WeakMap,Sr=new WeakMap,Id=new WeakMap,Up);ar([y.trace("WebMediaInterface.destruct")],Ft.prototype,"destruct",1);ar([y.trace("WebMediaInterface.handlePermissionErrors")],Ft.prototype,"handlePermissionErrors",1);ar([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Ft.prototype,"getAudioAndVideoTrack",1);ar([y.trace("WebMediaInterface.getAudioTrack")],Ft.prototype,"getAudioTrack",1);ar([y.trace("WebMediaInterface.getScreenShareTracks")],Ft.prototype,"getScreenShareTracks",1);ar([y.trace("WebMediaInterface.getVideoTrack")],Ft.prototype,"getVideoTrack",1);ar([y.trace("WebMediaInterface.getAvailableDevices")],Ft.prototype,"getAvailableDevices",1);ar([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Ft.prototype,"getAvailableDevicesByKind",1);ar([y.trace("WebMediaInterface.getDevice")],Ft.prototype,"getDevice",1);ar([y.trace("WebMediaInterface.onDeviceChange")],Ft.prototype,"onDeviceChange",1);Ft=ar([ht("1600")],Ft);const rv=Ft,Rd={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(r){l.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){l.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},VM=(t=0)=>new Promise(e=>setTimeout(e,t)),BM=(t,e,r)=>{const n=typeof r=="number"?r:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const o=new Uint8Array(s.fftSize);let a=!1;setTimeout(()=>{a=!0},n);function d(){return a?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(h=>h!==128&&h!==0)?Promise.resolve(!1):VM().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},jM=typeof AudioContext!="undefined"?AudioContext:null;class lu{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:jM},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:lu}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch{}return this.audioContext}release(e){this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.delete(e),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Vp=new lu,HM=3,WM=250;function $M(t){const e={},r=Vp.getOrCreate(e);let n=HM;function i(){return n-=1,BM(r,t.srcObject,WM).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Vp.release(e)})}function Bp(t){return u(this,null,function*(){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let n=!1;try{const i=e.play();i&&(yield i),n=yield $M(e),n&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return n})}var GM=Object.defineProperty,JM=Object.getOwnPropertyDescriptor,qM=(t,e,r,n)=>{for(var i=n>1?void 0:n?JM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&GM(e,r,i),i};let gl=class extends ds{constructor(t,e,r){super(),m(this,"constructorName",this.constructor.name),m(this,"userSelectedDevice"),m(this,"mediaInterface"),m(this,"isNonPreferredDevice"),m(this,"_mediaTrack"),m(this,"transformedMediaTrack"),m(this,"middlewares",[]),m(this,"currentDevice"),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return u(this,null,function*(){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track")}})}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}((t=this.currentDevice)==null?void 0:t.deviceId)!==this.mediaTrack.getSettings().deviceId&&(this.currentDevice=yield this.mediaInterface.getDevice(this.mediaTrack.getSettings().deviceId))})}addMiddleware(t){return u(this,null,function*(){if(Ee.isWebKitBased()&&!K.hasFeature(X.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};gl=qM([ht("1600")],gl);const nv=gl;var KM=Object.defineProperty,zM=Object.getOwnPropertyDescriptor,uu=(t,e,r,n)=>{for(var i=n>1?void 0:n?zM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&KM(e,r,i),i};const Pd="[Dyte]nonSilentDeviceLabels";class Uc extends nv{setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;this.userSelectedDevice=e.deviceId,yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,e.deviceId))}catch(r){throw l.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C(r.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const r=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(r)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield AM(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){l.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const o=JSON.parse(Rd.getItem(Pd));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Bp(n))){const d=(r=o==null?void 0:o.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return Rd.setItem(Pd,JSON.stringify({devices:d})),n}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==a).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Bp(n))){const h=o.devices.concat({label:n.label});return Rd.setItem(Pd,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}uu([y.trace("AudioMediaHandler.setTransformedTrack")],Uc.prototype,"setTransformedTrack",1);uu([y.trace("AudioMediaHandler.onTrackEnded")],Uc.prototype,"onTrackEnded",1);uu([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Uc.prototype,"conditionallyChangeTrack",1);const YM=Uc;var Bs;class QM{constructor(e){k(this,Bs,void 0),m(this,"currentDevice"),T(this,Bs,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,Bs)instanceof rv))return;let n=e;if(e||([n]=yield c(this,Bs).getAvailableDevicesByKind("audiooutput")),!n)throw new C("No speaker found");((r=this.currentDevice)==null?void 0:r.deviceId)!==n.deviceId&&(this.currentDevice=n,document.querySelectorAll("audio").forEach(i=>u(this,null,function*(){if(typeof i.sinkId!="undefined"&&this.currentDevice.deviceId&&i.sinkId!==this.currentDevice.deviceId)try{yield i.setSinkId(this.currentDevice.deviceId)}catch{}})))})}}Bs=new WeakMap;const XM=QM;class ZM extends ds{constructor(e){super(),m(this,"mediaInterface"),m(this,"audioMediaTrack"),m(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:n,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",w.emit(b.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this))}removeMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const eD=ZM;var tD=Object.defineProperty,rD=Object.getOwnPropertyDescriptor,Vc=(t,e,r,n)=>{for(var i=n>1?void 0:n?rD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&tD(e,r,i),i},js,Sa;class Eo extends nv{constructor(e,r,n){super(e,r,n),k(this,js,void 0),k(this,Sa,{disablePerFrameCanvasRendering:!1}),T(this,js,new MM)}setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c(this,js).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,Sa)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){T(this,Sa,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){c(this,js).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const n=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),r})}}js=new WeakMap,Sa=new WeakMap;Vc([y.trace("VideoMediaHandler.setTransformedTrack")],Eo.prototype,"setTransformedTrack",1);Vc([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Eo.prototype,"setVideoMiddlewareGlobalConfig",1);Vc([y.trace("VideoMediaHandler.onTrackEnded")],Eo.prototype,"onTrackEnded",1);Vc([y.trace("VideoMediaHandler.conditionallyChangeTrack")],Eo.prototype,"conditionallyChangeTrack",1);const nD=Eo,jp=fr(eu());var $t,Wi,Ta,Hs;const Ws=class{constructor(t){if(k(this,$t,void 0),k(this,Wi,void 0),k(this,Ta,void 0),k(this,Hs,void 0),!t)throw new C("Could not load preset.");T(this,$t,t.config),T(this,Ta,t.name),T(this,Wi,t.ui||fr(eu().ui)),T(this,Hs,t.permissions.plugins.config)}static fromResponse(t){return new Ws(t)}static default(){return new Ws(jp)}static init(t,e=!0){return!t||e?new Ws(jp):new Ws(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:c(this,Wi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,$t).viewType}get maxVideoStreams(){return c(this,$t).maxVideoStreams}get maxScreenShareCount(){return c(this,$t).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Hs)).filter(t=>c(this,Hs)[t].disabled)}get designTokens(){return c(this,Wi).designTokens}get configDiff(){return c(this,Wi).configDiff}get mediaConstraints(){var t,e,r,n,i,s,o,a,d,h,p,f,g,E,v,I,A,D,x,W,H,R,S,P;return{audio:{enableStereo:(n=(r=(e=(t=c(this,$t))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:Ii.audio.enableStereo,enableHighBitrate:(a=(o=(s=(i=c(this,$t))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?a:Ii.audio.enableHighBitrate},video:{quality:(f=(p=(h=(d=c(this,$t))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:Ii.video.quality,frameRate:(I=(v=(E=(g=c(this,$t))==null?void 0:g.media)==null?void 0:E.video)==null?void 0:v.frameRate)!=null?I:Ii.video.frameRate},screenshare:{quality:(W=(x=(D=(A=c(this,$t))==null?void 0:A.media)==null?void 0:D.screenshare)==null?void 0:x.quality)!=null?W:Ii.screenshare.quality,frameRate:(P=(S=(R=(H=c(this,$t))==null?void 0:H.media)==null?void 0:R.screenshare)==null?void 0:S.frameRate)!=null?P:Ii.screenshare.frameRate}}}get name(){return c(this,Ta)}};let iD=Ws;$t=new WeakMap,Wi=new WeakMap,Ta=new WeakMap,Hs=new WeakMap;var sD=Object.defineProperty,oD=Object.getOwnPropertyDescriptor,iv=(t,e,r,n)=>{for(var i=n>1?void 0:n?oD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&sD(e,r,i),i},$s;class hu extends Ut{constructor(e){super(),k(this,$s,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"viewerCount"),T(this,$s,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new C("User does not have permission to start livestreaming");this.setLivestreamState("STARTING");try{const e=yield We().startLivestreaming();this.playbackUrl=e}catch(e){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:e}),this.setLivestreamState("IDLE"),new C("Error while starting livestream")}})}stop(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming");if(this.state!=="LIVESTREAMING")throw l.error("DyteLivestream::stop::inconsistent_state"),new C("Livestream not started yet");try{this.setLivestreamState("STOPPING"),yield We().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream")}})}}$s=new WeakMap;iv([y.trace("livestream.start")],hu.prototype,"start",1);iv([y.trace("livestream.stop")],hu.prototype,"stop",1);var aD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,dD=(t,e,r,n)=>{for(var i=n>1?void 0:n?cD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&aD(e,r,i),i},Gs,Wn;class sv{constructor(e,r){m(this,"livestream"),k(this,Gs,void 0),k(this,Wn,void 0),this.livestream=new hu(e),T(this,Wn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=We(),{status:r,playbackUrl:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")})}setupEvents(){c(this,Wn).on(j.startedLivestream,e=>{this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,Wn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Wn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,Wn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),w.on(b.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,Gs,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),w.on(b.PEER_CLOSED,e=>{e.id===c(this,Gs)&&(T(this,Gs,void 0),this.livestream.setLivestreamState("IDLE"))}),w.onAsync(b.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{l.error("Error: LivestreamController.fetchLivestream")}}))}}Gs=new WeakMap,Wn=new WeakMap;dD([y.trace("LivestreamController.setupEvents")],sv.prototype,"setupEvents",1);var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,So=(t,e,r,n)=>{for(var i=n>1?void 0:n?uD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&lD(e,r,i),i};const ov={maxInvocations:1,period:200},pu={maxInvocations:5,period:1e3};var Tt,$n,Gn,vl,av;class us{constructor({name:e,socketHandler:r,meetingId:n}){k(this,vl),m(this,"name",""),k(this,Tt,{}),k(this,$n,""),k(this,Gn,void 0),m(this,"volatile"),m(this,"listeners",{}),this.name=e,T(this,Gn,r),T(this,$n,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,Tt)[e]=r,n&&c(this,Gn).storeInsertKeys(c(this,$n),this.name,[{key:e,payload:r}]),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,Tt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,Tt)[e]})))})}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,Tt)[r]=n}),c(this,Gn).storeInsertKeys(c(this,$n),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){ue(this,vl,av).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,Tt)[e]&&delete c(this,Tt)[e],r)return c(this,Gn).storeDeleteKeys(c(this,$n),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{c(this,Tt)[r]&&delete c(this,Tt)[r]}),c(this,Gn).storeDeleteKeys(c(this,$n),this.name,e)})}get(e){if(c(this,Tt)[e])return c(this,Tt)[e]}getAll(){return c(this,Tt)}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e){this.listeners[e]&&delete this.listeners[e]}populate(e){T(this,Tt,e)}}Tt=new WeakMap,$n=new WeakMap,Gn=new WeakMap,vl=new WeakSet,av=function(t,e,r=!0){let n;const i=c(this,Tt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n=V(V({},i),e);break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)};So([Pt(pu)],us.prototype,"set",1);So([Pt(ov)],us.prototype,"bulkSet",1);So([Pt(pu)],us.prototype,"update",1);So([Pt(pu)],us.prototype,"delete",1);So([Pt(ov)],us.prototype,"bulkDelete",1);var Gi,Ji,_a,Ad,ac,ti,yl,cv;class hD{constructor(e,r){k(this,_a),k(this,yl),m(this,"stores",new Map),k(this,Gi,void 0),k(this,Ji,""),k(this,ac,void 0),k(this,ti,new Map),T(this,Gi,r),T(this,Ji,e.getValue("meetingId")),T(this,ac,e),ue(this,yl,cv).call(this)}create(e){const r=new us({name:e,socketHandler:c(this,Gi),meetingId:c(this,Ji)});return c(this,Gi).storeGetKeys(c(this,Ji),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,ti).set(e,{rejectTimeout:s,resolve:n,store:r})})}}Gi=new WeakMap,Ji=new WeakMap,_a=new WeakSet,Ad=function(){return c(this,ac).getValue("peerId")},ac=new WeakMap,ti=new WeakMap,yl=new WeakSet,cv=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,Gi).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,Ji))return;const i=(r=e.storeItems)==null?void 0:r.map(o=>{var a;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((a=o.payload)!=null&&a.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===J.storeGetKeys){const o=c(this,ti).get(e.storeName),a=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,ti).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(a),clearTimeout(o.rejectTimeout),c(this,ti).delete(e.storeName)),i.forEach(d=>{a.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=c(this,ti).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===J.storeInsertKeys&&i.forEach(({key:o,peerId:a,payload:d})=>{a===c(this,_a,Ad)&&t!==J.storeGetKeys||s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&i.forEach(({key:o,peerId:a})=>{a!==c(this,_a,Ad)&&s.delete(o,!1,!0)}))}))})};function ri(t){var e,r,n,i,s,o,a,d,h,p,f,g,E;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(a=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:a.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(f=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:f.enabled,trackId:(E=(g=t.screenShareTracks)==null?void 0:g.video)==null?void 0:E.id}}}}:{}}var pD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,hs=(t,e,r,n)=>{for(var i=n>1?void 0:n?mD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&pD(e,r,i),i};const fD=.8,gD=1.2;var As,Ms,Wo,wn,Ri,$r,$o,Cn,Gr,Md,Go,Dd,Od,Hp,Wp;let Ur=(Wp=class extends Ut{constructor(t,e,r,n){super(),k(this,wn),k(this,Go),k(this,Od),m(this,"id"),m(this,"userId"),m(this,"name"),m(this,"picture"),m(this,"isHost"),m(this,"customParticipantId"),m(this,"flags"),m(this,"device"),m(this,"videoTrack"),m(this,"audioTrack"),m(this,"screenShareTracks"),m(this,"videoEnabled"),m(this,"audioEnabled"),m(this,"screenShareEnabled"),m(this,"producers"),m(this,"manualProducerConfig"),k(this,As,void 0),m(this,"supportsRemoteControl",!1),k(this,Ms,void 0),m(this,"presetName"),k(this,Wo,void 0),k(this,$r,void 0),k(this,$o,void 0),k(this,Cn,new Map),k(this,Gr,1),k(this,Md,mr(H=>{if(!this.videoTrack)return;const{clientWidth:R,clientHeight:S}=H,{width:P,height:O}=this.videoTrack.getSettings();if(!P||!O)return;const ae=O/S,Oe=P/R,$=Math.max(ae,Oe);$>gD&&c(this,Gr)===1?(T(this,Gr,0),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Gr)})):$<fD&&c(this,Gr)===0&&(T(this,Gr,1),w.emit(b.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Gr)}))},2e3)),T(this,Wo,t);const{id:i,userId:s,displayName:o,device:a,picture:d,isHost:h,flags:p,clientSpecificId:f,stageStatus:g,customParticipantId:E,audioMuted:v,audioTrack:I,videoEnabled:A=!1,videoTrack:D,producers:x,metadata:W}=e;this.id=i,this.userId=s,this.name=o,this.device=a,this.picture=d,this.isHost=h,this.flags=p,this.manualProducerConfig=rl,T(this,Ms,g!=null?g:"ON_STAGE"),this.customParticipantId=E!=null?E:f,this.audioEnabled=!v,this.audioTrack=I,this.videoEnabled=A,this.videoTrack=D,this.screenShareTracks={audio:void 0,video:void 0},this.producers=x!=null?x:[],this.presetName=W==null?void 0:W.preset_name,T(this,As,!1),T(this,$r,r),T(this,$o,n),this.setupEvents()}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,Ms)}get roomJoined(){var t;return((t=c(this,wn,Ri))==null?void 0:t.roomJoined)===!0}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},ri(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},ri(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",ue(this,Od,Hp))}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participant without joining room");if(!c(this,$r).permissions.pinParticipant)throw new C("You do not have permission to pin participants.");return c(this,wn,Ri).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participant without joining room");if(!c(this,$r).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.");return c(this,wn,Ri).pinPeer(null)})}setIsPinned(t,e=!0){T(this,As,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant audio without joining room");if(c(this,$r).permissions.canDisableParticipantAudio)return c(this,wn,Ri).disableAudio(t);throw l.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.")})}kick(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t kick participant without joining room");if(c(this,$r).permissions.kickParticipant){yield w.emitAsync(b.KICK_PEER,{peerId:t});return}throw l.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant video without joining room");if(c(this,$r).permissions.canDisableParticipantVideo)return c(this,wn,Ri).disableVideo(t);throw l.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.")})}getPermissions(){return u(this,null,function*(){return c(this,$o).getUserPermissions(this.userId)})}setStageStatus(t){T(this,Ms,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,As)}registerVideoElement(t){var e,r;let n;(r=(e=c(this,Cn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>c(this,Md).call(this,t)),n.observe(t)),c(this,Cn).set(t,{observer:n}),ue(this,Go,Dd).call(this,t)}deregisterVideoElement(t){var e,r;t.srcObject=void 0,(r=(e=c(this,Cn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,Cn).delete(t)}},As=new WeakMap,Ms=new WeakMap,Wo=new WeakMap,wn=new WeakSet,Ri=function(){return c(this,Wo).getValue("roomNodeClient")},$r=new WeakMap,$o=new WeakMap,Cn=new WeakMap,Gr=new WeakMap,Md=new WeakMap,Go=new WeakSet,Dd=function(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0},Od=new WeakSet,Hp=function(){Array.from(c(this,Cn).keys()).forEach(ue(this,Go,Dd))},Wp);hs([y.trace("DyteParticipant.disableAudio")],Ur.prototype,"disableAudio",1);hs([y.trace("DyteParticipant.kick")],Ur.prototype,"kick",1);hs([y.trace("DyteParticipant.disableVideo")],Ur.prototype,"disableVideo",1);hs([y.trace("DyteParticipant.getPermissions")],Ur.prototype,"getPermissions",1);hs([y.trace("DyteParticipant.setStageStatus")],Ur.prototype,"setStageStatus",1);Ur=hs([ht("1200")],Ur);class Jo extends Zg{constructor(e){const{onAddEvent:r="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:n,onClearEvent:i})}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var Jn;class vD extends ds{constructor(){super(),k(this,Jn,void 0),T(this,Jn,new Map)}__set(e,r){return c(this,Jn).set(e,r)}__clear(){return c(this,Jn).clear()}get(e){return c(this,Jn).get(e)}toArray(){return Array.from(c(this,Jn).values())}}Jn=new WeakMap;function yD(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(r=>r.charAt(0)).join("").toUpperCase()}const $p=1080,Gp=1920,ED=(t,e,r,n,i,s)=>{let o=.5,a=.5;const d=i,h=s,p=Math.min(r/d,n/h);let f=d*p,g=h*p,E,v,I,A,D=1;return f<r&&(D=r/f),Math.abs(D-1)<1e-14&&g<n&&(D=n/g),f*=D,g*=D,I=d/(f/r),A=h/(g/n),E=(d-I)*o,v=(h-A)*a,E<0&&(E=0),v<0&&(v=0),I>d&&(I=d),A>h&&(A=h),[E,v,I,A,t,e,r,n]};var dr,Js,yt,nn,Ne,sn,on,er,Ze;class SD extends Ut{constructor(e,r){super(),k(this,dr,void 0),k(this,Js,void 0),k(this,yt,void 0),k(this,nn,void 0),k(this,Ne,{height:$p,width:Gp}),k(this,sn,{brand:"#2160FD",background:"#141414",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),k(this,on,void 0),k(this,er,{}),k(this,Ze,void 0),m(this,"cleanupEventListeners",()=>{c(this,Js).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).removeListener("roomLeft",this.disable)}),m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),m(this,"onSelfVideoUpdateListener",({videoEnabled:n})=>{this.updateMediaSession("CAMERA",n)}),m(this,"onSelfAudioUpdateListener",({audioEnabled:n})=>{this.updateMediaSession("MIC",n)}),m(this,"handlePipMediaControls",n=>{n==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),m(this,"eventCallback",n=>{n==="CAMERA"&&(c(this,Ze).videoEnabled?c(this,Ze).disableVideo():c(this,Ze).enableVideo(),this.emit("cameraToggled")),n==="MIC"&&(c(this,Ze).audioEnabled?c(this,Ze).disableAudio():c(this,Ze).enableAudio(),this.emit("micToggled")),n==="END"&&(w.emit(b.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),m(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),m(this,"animate",()=>{c(this,er)!==void 0&&this.paintCanvas(),c(this,on)!==void 0&&T(this,on,requestAnimationFrame(()=>this.animate()))}),m(this,"disable",()=>{this.cleanupEventListeners(),cancelAnimationFrame(c(this,on)),document.body.removeChild(c(this,yt)),T(this,on,void 0),document.exitPictureInPicture()}),T(this,Js,e),T(this,Ze,r),T(this,sn,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand})}createVideoContainer(){T(this,yt,document.createElement("div")),c(this,yt).style.width="0.1px",c(this,yt).style.height="0.1px",c(this,yt).style.overflow="hidden",c(this,yt).style.position="absolute",c(this,yt).style.bottom="0",c(this,yt).style.right="0",c(this,yt).style.opacity="0",c(this,yt).appendChild(c(this,nn))}setupEventListeners(){c(this,Js).subscribe("stageStatus",this.handlePipMediaControls),c(this,Ze).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,Ze).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,Ze).addListener("roomLeft",this.disable)}createCanvas(){const e=document.createElement("canvas");e.height=c(this,Ne).height,e.width=c(this,Ne).width,T(this,dr,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||c(this,Ze).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,Ze).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const e=Object.values(c(this,er)),r=e.filter(n=>n.pinned);return r.length===1?r:e}drawEmptyTile(e,r,n,i,s){if(c(this,dr)===void 0)return;const o=c(this,dr).getContext("2d"),a=c(this,dr).width,d=4,h=4,p=r-d*2,f=n-d*2,g=Math.floor(a/p),E=Math.floor(e/g),v=e%g*(p+d)+d,I=E*(f+d)+d;o.fillStyle=c(this,sn).videoBackground,o.strokeStyle=c(this,sn).brand,o.beginPath(),o.moveTo(v+h,I),o.arcTo(v+p,I,v+p,I+h,h),o.arcTo(v+p,I+f,v+p-h,I+f,h),o.arcTo(v,I+f,v,I+f-h,h),o.arcTo(v,I,v+h,I,h),o.closePath(),o.fill(),o.stroke();const A=p/6,D=p/2+v,x=f/2+I;if(o.save(),(i||s)&&(o.beginPath(),o.arc(D,x,A,0,Math.PI*2),o.fillStyle=c(this,sn).brand,o.fill()),i&&(o.fillStyle=c(this,sn).textOnBrand,o.font=`${A/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(i,D,x)),s){const W=new Image;W.src=s,W.onload=()=>{o.drawImage(W,D-A,x-A,A*2,A*2),o.restore()}}}drawGrid(e,r,n){if(c(this,dr)===void 0)return;const i=c(this,dr).getContext("2d");i.fillStyle=c(this,sn).background,i.fillRect(0,0,c(this,Ne).width,c(this,Ne).height);const s=this.getSources();let o=0,a=0;for(;o<c(this,Ne).height-5;){let d=0;for(;d<c(this,Ne).width-5&&a<n;){const h=s[a].element;if(s[a].enabled){const[p,f,g,E,v,I,A,D]=ED(d,o,e,r,h.videoWidth,h.videoHeight);i.drawImage(h,p,f,g,E,v,I,A,D)}else this.drawEmptyTile(a,e,r,s[a].displayText);a+=1,d+=e}o+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[c(this,Ne).width,c(this,Ne).height];case 2:return[Math.floor(c(this,Ne).width/2),c(this,Ne).height];case 3:case 4:return[Math.floor(c(this,Ne).width/2),Math.floor(c(this,Ne).height/2)];case 5:case 6:return[Math.floor(c(this,Ne).width/3),Math.floor(c(this,Ne).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Ne).width/3),Math.floor(c(this,Ne).height/3)];default:return[Math.floor(c(this,Ne).width/3),Math.floor(c(this,Ne).height/2)]}}paintCanvas(){const e=this.getSources().length,[r,n]=this.calcGridElemSize(e);this.drawGrid(r,n,e)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,yt))try{document.body.removeChild(c(this,yt))}catch{}this.removeAllSources(),T(this,dr,void 0),T(this,nn,void 0),T(this,on,void 0)}init({height:e,width:r}={}){this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,Ne,{height:e!=null?e:$p,width:r!=null?r:Gp}),n.height=c(this,Ne).height,n.width=c(this,Ne).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,dr).captureStream(24),T(this,nn,n),c(this,nn).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,nn).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch{this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!0)}disableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!1)}addSource(e,r,n,i=!1,s=void 0){i&&this.removePinnedSource(),c(this,er)[e]={id:e,element:r,enabled:n,pinned:i,displayText:s?yD(s):void 0}}removeSource(e){delete c(this,er)[e]}removePinnedSource(){const[e]=this.getSources();e&&this.removeSource(e.id)}removeAllSources(){T(this,er,{})}enable(){this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,Ze).videoEnabled),this.updateMediaSession("MIC",c(this,Ze).audioEnabled),document.body.appendChild(c(this,yt)),T(this,on,requestAnimationFrame(()=>this.animate())),c(this,nn).requestPictureInPicture()}}dr=new WeakMap,Js=new WeakMap,yt=new WeakMap,nn=new WeakMap,Ne=new WeakMap,sn=new WeakMap,on=new WeakMap,er=new WeakMap,Ze=new WeakMap;var ni={},Bc={},TD=ju&&ju.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Bc,"__esModule",{value:!0});Bc.Logger=void 0;const Pi=TD(ur),Ai="awaitqueue";class _D{constructor(e){e?(this._debug=(0,Pi.default)(`${Ai}:${e}`),this._warn=(0,Pi.default)(`${Ai}:WARN:${e}`),this._error=(0,Pi.default)(`${Ai}:ERROR:${e}`)):(this._debug=(0,Pi.default)(Ai),this._warn=(0,Pi.default)(`${Ai}:WARN`),this._error=(0,Pi.default)(`${Ai}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}Bc.Logger=_D;Object.defineProperty(ni,"__esModule",{value:!0});var is=ni.AwaitQueue=ni.AwaitQueueRemovedTaskError=ni.AwaitQueueStoppedError=void 0;const kD=Bc,Jr=new kD.Logger;class mu extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,mu)}}ni.AwaitQueueStoppedError=mu;class jc extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,jc)}}ni.AwaitQueueRemovedTaskError=jc;class bD{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,r){return u(this,null,function*(){if(r=r!=null?r:e.name,Jr.debug(`push() [name:${r}]`),typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch{}return new Promise((n,i)=>{const s={id:this.nextTaskId++,task:e,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:o=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),Jr.debug(`resolving task [name:${s.name}]`),n(o);const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)},reject:o=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),Jr.debug(`rejecting task [name:${s.name}]: %s`,String(o)),i(o),!this.stopping)){const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){Jr.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Jr.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){Jr.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){Jr.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new jc)}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:r++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}execute(e){return u(this,null,function*(){if(Jr.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=yield e.task();e.resolve(r)}catch(r){e.reject(r)}})}}is=ni.AwaitQueue=bD;var ka;class dv{constructor(){m(this,"meetingTitle"),m(this,"roomName"),m(this,"roomUUID"),k(this,ka,void 0),m(this,"context"),m(this,"authToken"),m(this,"maxPreferredStreams"),m(this,"roomJoined")}get peerId(){return this.context.getValue("peerId")}get sfuHandler(){return c(this,ka)}get socketState(){return{state:void 0,reconnected:!1,reconnectionAttempt:void 0}}get mediaState(){return c(this,ka).transportState}reconnect(){throw new C("Method not implemented.")}partialJoinRoom(e,r,n=!1,i=void 0){return u(this,null,function*(){throw new C("Method not implemented.")})}joinRoom(e,r){return u(this,arguments,function*(n,i,s={},o=!1,a=!1){throw new C("Method not implemented.")})}leaveRoom(){return u(this,null,function*(){throw new C("Method not implemented.")})}reset(e=!0){throw new C("Method not implemented")}handleSocketCallbacks(e){return u(this,null,function*(){throw new C("Method not implemented.")})}handleSockets(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}shareMic(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareWebcam(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareScreen(e){return u(this,null,function*(){throw new C("Method not implemented.")})}unmuteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}muteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}pauseWebcam(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableScreenShare(){return u(this,null,function*(){throw new C("Method not implemented.")})}acceptWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}rejectWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAll(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAllVideo(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableAudio(e){return u(this,null,function*(){throw new C("Method not implemented.")})}disableVideo(e){return u(this,null,function*(){throw new C("Method not implemented.")})}kickAll(){return u(this,null,function*(){throw new C("Method not implemented.")})}kick(e){return u(this,null,function*(){throw new C("Method not implemented.")})}pinPeer(e){return u(this,null,function*(){throw new C("Method not implemented.")})}getConsumers(){throw new C("Method not implemented.")}stopAllProducers(){throw new C("Method not implemented.")}activatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}deactivatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}switchConsumersToLayer(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}}ka=new WeakMap;var Lr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(Lr||{});class lv extends It.EventEmitter{}class ai extends It.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...r){const n=this.listenerCount(e);try{return this.emit(e,...r)}catch(i){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(n)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...r)})}safeEmitAsPromiseWithTimeout(e,r,...n){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...n,i,s)}catch(o){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}function wD(t,e){const r=new Error(e);return r.name=t,r}class ci extends C{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ci):this.stack=new Error(e).stack}}class at extends C{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,at):this.stack=new Error(e).stack}}var ba,wa,Ca,Ia,Rr,Ra,Pa,hr,$i,Aa,Ma,Da,Nd,El,uv,Sl,hv;class pv extends ai{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:s,handler:o,track:a,appData:d,paused:h,reuseTrack:p,rtpReceiver:f}){super(),k(this,Da),k(this,El),k(this,Sl),m(this,"rtpReceiver"),m(this,"observer"),k(this,ba,void 0),k(this,wa,void 0),k(this,Ca,void 0),k(this,Ia,void 0),k(this,Rr,void 0),k(this,Ra,void 0),k(this,Pa,void 0),k(this,hr,void 0),k(this,$i,void 0),k(this,Aa,void 0),k(this,Ma,void 0),T(this,ba,e),T(this,wa,r),T(this,Pa,o),T(this,Ma,d),T(this,Aa,i),T(this,Ia,s),T(this,Rr,!1),T(this,Ca,n),T(this,hr,a),T(this,$i,h!=null?h:!1),T(this,Ra,p),this.observer=new ai,this.rtpReceiver=f,ue(this,El,uv).call(this)}get id(){return c(this,ba)}get peerId(){return c(this,Aa)}get localId(){return c(this,wa)}get producerId(){return c(this,Ca)}get producingTransportId(){return c(this,Ia)}get closed(){return c(this,Rr)}get kind(){return c(this,hr).kind}get track(){return c(this,hr)}get paused(){return c(this,$i)}get remotelyPaused(){return this.paused}get appData(){return c(this,Ma)}close(e){c(this,Rr)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),T(this,Rr,!0),c(this,Ra)||ue(this,Sl,hv).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,Rr))throw new at("closed");return c(this,Pa).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Rr)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,$i,!0),c(this,hr).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Rr)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,$i,!1),c(this,hr).enabled=!0,this.observer.safeEmit("resume")}}ba=new WeakMap,wa=new WeakMap,Ca=new WeakMap,Ia=new WeakMap,Rr=new WeakMap,Ra=new WeakMap,Pa=new WeakMap,hr=new WeakMap,$i=new WeakMap,Aa=new WeakMap,Ma=new WeakMap,Da=new WeakSet,Nd=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},El=new WeakSet,uv=function(){c(this,hr).addEventListener("ended",ue(this,Da,Nd).bind(this))},Sl=new WeakSet,hv=function(){try{c(this,hr).removeEventListener("ended",ue(this,Da,Nd)),c(this,hr).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let CD=class extends pv{};const Jp=t=>new Promise(e=>setTimeout(e,t));function gr(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let a=0,d,h=!1;const p=f=>{h=!0,n(f)};for(;a<s;){try{const f=yield t(a,p);return r(f)}catch(f){if(d=f,h)break;if(a<s)i==="linear"?yield Jp(o*(a+1)):i==="exponential"&&(yield Jp(o*(a+Math.max(0,a-1))));else break}a+=1}return n(d)}))})}function cc(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(r=>r.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}function ID(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function mv(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Tl(t){return Math.random().toString(36).substring(2,2+t)}const qo=1;function qp(t){const e=t;return delete e.payload._bolt,e}function RD(t){return t.payload&&mv(t.payload)}function dc(t){var e,r;return RD(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var qn;const qs=class extends It.EventEmitter{constructor(t,e,r){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),k(this,qn,new Map),m(this,"respond",(n,i,s=!1)=>{let o;s?o=qs.createErrorResponse(n,i):o=qs.createResponse(n,i),this.channel.send(JSON.stringify(o))}),m(this,"notify",n=>{const i=qs.createNotification(n);this.channel.send(JSON.stringify(i))}),m(this,"request",n=>u(this,null,function*(){const i=qs.createRequest(n),s=new Promise((o,a)=>{const d=1e3*(5+.1*this.queue.size),{id:h}=i.payload._bolt,p={id:h,method:i.type,resolve:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),o(f))},timer:setTimeout(()=>{this.queue.delete(h)&&a(new Error(`request timeout for message id: ${h}`))},d),cancel:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),a(f))}};this.queue.set(h,p)});return this.channel.send(JSON.stringify(i)),s})),m(this,"send",n=>{const i=JSON.stringify(n),s=16384;if(i.length>s){const o=s-200,a=Math.ceil(i.length/o),d=[];for(let p=0;p<a;p+=1){const f=p*o,g=(p+1)*o;d.push(i.slice(f,g))}const h=di();for(let p=0;p<a;p+=1){const f=d[p],g=JSON.stringify({id:h,count:a,chunkIndex:p,chunk:f});l.debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else l.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),m(this,"processMessage",n=>{var i;c(this,qn).has(n.id)||c(this,qn).set(n.id,[]);const s=c(this,qn).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(o=>o===void 0)){const o=c(this,qn).get(n.id),a=o==null?void 0:o.reduce((h,p)=>h+p.chunk,"");c(this,qn).delete(n.id);const d=JSON.parse(a);if(!d.payload||!mv(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),m(this,"processResponseMsg",n=>{const{id:i}=n.payload._bolt,s=this.queue.get(i);return s?(l.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(qp(n)):s.resolve(qp(n)),!0):!1}),m(this,"processBoltHandshake",n=>{var i,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(i=n.payload._bolt)==null?void 0:i.id)!=null?s:Tl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let Ks=qs;qn=new WeakMap,m(Ks,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{_bolt:{id:Tl(8),type:"REQUEST",version:qo}})}}),m(Ks,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:ne(V({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:qo}})}}),m(Ks,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{bolt:{id:Tl(8),type:"NOTIFY",version:qo}})}}),m(Ks,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:qo}}}));const _l="transport closed";class fv extends ai{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:o,additionalSettings:a,appData:d,config:h}){var p,f;super(),m(this,"awaitQueue"),m(this,"observer"),m(this,"id"),m(this,"serverId"),m(this,"closed",!1),m(this,"direction"),m(this,"maxSctpMessageSize"),m(this,"handler"),m(this,"connectionState","new"),m(this,"producers"),m(this,"consumers"),m(this,"datachannels"),m(this,"connected",!1),m(this,"eventsDCReadyPromise"),m(this,"eventsDCReadyPromiseResolver"),m(this,"eventsDCFailureTimer"),m(this,"transportConnectionPromise"),m(this,"consumerTrackEvents"),m(this,"unknownTracksMap"),m(this,"consumerTrackPool"),m(this,"appData"),l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const g=ID(a,{});delete g.iceServers,delete g.iceTransportPolicy,delete g.bundlePolicy,delete g.rtcpMuxPolicy,delete g.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new is,this.observer=new ai,this.handler=n(),this.handler._enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler._enableStereo=(f=h==null?void 0:h.enableStereo)!=null?f:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:s,additionalSettings:a,proprietaryConstraints:o}),this.appData=d||{},this.transportConnectionPromise=new Promise(E=>{this.observer.once("connected",()=>{E(!0)}),this.observer.once("disconnect",()=>{E(!1)}),this.observer.once("close",()=>{E(!1)})}),this.eventsDCReadyPromise=new Promise(E=>{this.eventsDCReadyPromiseResolver=E}),this.handler.on("@connectionstatechange",E=>{E!==this.connectionState&&(l.debug(`connection state changed to ${E}`),this.connectionState=E,E==="connected"&&(this.connected=!0,this.observer.emit("connected")),E==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(E==="failed"||E==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",E))}),this.handler.on("@icecandidate",({candidate:E})=>{this.closed||this.safeEmit("icecandidate",E)}),this.handler.on("dc_open",E=>{let v=this.datachannels.get(E.label);v||(v||(v=new Ks(E,E.label,this.serverId),this.datachannels.set(E.label,v)),this.eventsDCFailureTimer=setTimeout(()=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",E.label))},5e3))}),this.handler.on("datachannel",(E,v)=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const I=this.datachannels.get(E.label);if(!I){l.error("unregistered datachannel for message",{rtcChannel:{label:E.label,message:v}});return}try{const A=JSON.parse(v);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:A.id,count:A.count,chunkIndex:A.chunkIndex,chunk:A.chunk,transprtId:this.serverId}});const D=I.processMessage(A);if(!D)return;l.debug(`datachannel message with id:${A.id} on transport:${this.serverId}complete - ${JSON.stringify(D)}`),this.emit(`datachannel:${E.label}`,I.label,D)}catch(A){l.error("error parsing message",{error:A})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("close()"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(_l).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(_l)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new at("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new at("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new at("closed");return this.handler.updateIceServers(e)})}setRemoteOffer(e){return u(this,null,function*(){yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer(),n=Ul(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=V({},i),o=s.fmtp.find(a=>a.payload===111);return o&&(o.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(a=>a.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),r.sdp=nE(n),yield this.setLocalDescription(r),r})}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}createConsumerOverDC(e){return u(this,null,function*(){const r=this.getDatachannel("events");if(!r)throw wD("DC_NOT_READY","events datachannel not ready");if(e.length===0)throw new Error("one of producer id or publisher id is required");const n={type:"create_consumer",payload:{}};e.length===1?n.payload={producerId:e[0].producerId,publisherId:e[0].producingTransportId}:n.payload={publisherId:e[0].producingTransportId};const i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=(yield r.request(n)).payload,o=new Map;return Object.entries(s).forEach(([a,d])=>{const h=i.get(d.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${d.producerId}`,{consumerState:d});return}o.set(d.producerId,{consumerId:a,producingTransportId:h.producingTransportId,kind:h.kind,paused:h.pause,streamId:d.streamId,trackId:d.trackId,screenShare:h.screenShare,appData:{}})}),l.info(`createConsumerOverDC::response ${JSON.stringify(s)}`),o})}}class gv extends ai{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,handler:a,appData:d,rtpSender:h}){super(),m(this,"_id"),m(this,"_localId"),m(this,"_closed",!1),m(this,"_handler"),m(this,"_track"),m(this,"_kind"),m(this,"_paused"),m(this,"_maxSpatialLayer"),m(this,"_stopTracks"),m(this,"_disableTrackOnPause"),m(this,"_zeroRtpOnPause"),m(this,"_appData"),m(this,"observer"),m(this,"rtpSender"),this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=s?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=s,this._zeroRtpOnPause=o,this._appData=d||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=a,this.rtpSender=h,this.observer=new ai,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}close(e){return u(this,null,function*(){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===_l){this.observer.emit("close");return}const{offerSdp:r,callback:n}=yield this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)})}getStats(){return u(this,null,function*(){if(this._closed)throw new at("closed");return this._handler.getSenderStats(this.localId)})}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}}),this._closed){if(r&&this._stopTracks)try{r.stop()}catch(n){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id},error:n})}throw new at("closed")}else if(r&&r.readyState==="ended")throw new at("track ended");if(r===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}});return}(!this._zeroRtpOnPause||!this._paused)&&(yield this._handler.replaceTrack(this.localId,r)),this._destroyTrack(),this._track=r,this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(this._closed)throw new at("closed");if(this._kind!=="video")throw new ci("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e})}setRtpEncodingParameters(e){return u(this,null,function*(){if(this._closed)throw new at("closed");if(typeof e!="object")throw new TypeError("invalid params");yield this._handler.setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let PD=class extends gv{},AD=class extends fv{consume(t){return u(this,null,function*(){const{producers:e,producingPeerId:r,consumeOverDC:n}=t;if(l.debug(`consume() peerId: ${r}, producers: ${JSON.stringify(e)}`),this.closed)throw new at("closed");if(this.direction!=="recv")throw new ci("not a receiving Transport");if(typeof t.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[];let s;if(n)s=yield this.createConsumerOverDC(e);else{const o={producingPeerId:r};e.length===1&&(o.producerId=e[0].producerId);const{consumersMap:a}=yield this.safeEmitAsPromise("consume_peer",V({},o));s=a}return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:I}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:r,producingTransportId:I,paused:f,screenShare:p,appData:v}))}),cc(i)})}connect(){return u(this,null,function*(){try{const{offerSdp:t,callback:e}=yield this.handler.connect(),{answer:r}=yield this.safeEmitAsPromise("connect",{offer:t});if(yield e(r),!(yield this.isConnected))throw new Error("ice connection failed");if(!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}})}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const s=this.consumerTrackEvents.get(i);s?(s(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}consumerCreationTask(t){return u(this,arguments,function*({consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,paused:a,screenShare:d,appData:h,kind:p}){const f=`${s}:${p}`,g={consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,appData:h,kind:p,paused:a,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((E,v)=>{const I=setTimeout(()=>{this.consumerTrackEvents.delete(f),g.isTimedout=!0,v(g)},5e3),A=(W,H)=>{try{if(W.readyState==="ended")clearTimeout(I),v(g);else{const R=W;R.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const S=new CD({id:e,localId:H.mid,track:R,paused:a,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:ne(V({},h),{screenShare:d,peerId:n}),reuseTrack:!0,rtpReceiver:H.receiver});this.consumers.set(e,S),S.once("close",()=>{this.consumers.delete(S.id),this.handler.midTransceiverMap.delete(H.mid)}),l.info("consumer created for ",{consumer:{id:e,kind:p,appData:{screenShare:d},peerId:n,producerId:r}}),this.observer.emit("newconsumer",S),clearTimeout(I),E(S)}}catch(R){l.warn("error while creating consumer:",R),clearTimeout(I),v(g)}},D=this.consumerTrackPool.get(e);if((D==null?void 0:D.length)===2){A(D[0],D[1]);return}const x=this.unknownTracksMap.get(f);x?(this.unknownTracksMap.delete(f),A(x.track,x.transceiver)):this.consumerTrackEvents.set(f,A)})})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return cc(t.map(e=>u(this,null,function*(){return gr(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(V({},e))}))})))})}produce(){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:s=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new ci("not a sending Transport");if(t.readyState==="ended")throw new at("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:a,localId:d,rtpSender:h}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:f,callback:g,sender:E,mid:v}=yield this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:I,producerId:A}=yield this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:ne(V({},o||{}),{mid:v})}),D=yield g(I);return{producerId:A,localId:D,rtpSender:E}}),"producer"),p=new PD({id:a,localId:d,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:s,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(a,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p})}};class fu extends ai{constructor(){super(),m(this,"_mapMidTransceiver",new Map),m(this,"_enableHighBitrate",!1),m(this,"_enableStereo",!1),this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class gu extends fu{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new gu}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`send() [kind:${r.kind}, track.id:${r.id}]`);const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(r.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(i){const f=h.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`codecOption.parameters:${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=Array.from(new Set(g).values());f.sdpFmtpLine=E.join(";")}p.push(f)}l.info(`selected codecs: ${JSON.stringify(p)}`),a.setCodecPreferences(p)}const d=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(d),i&&i.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),d.sdp+=`a=rtcp-fb:111 nack\r
31
- `}return{offerSdp:d,callback:h=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")})}pauseReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")})}resumeReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class lc extends fu{constructor(e){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1),m(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new lc(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")})}restartIce(){return u(this,null,function*(){l.debug("Firefox60::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,screenShare:i}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${r.kind}, track.id:${r.id}]`),l.debug("Firefox60::creating new transceiver");const s=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},o=this._pc.addTransceiver(r,V({direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream]},s));if(!this.supportsSendEncodings&&n){n.reverse();const d=o.sender.getParameters();d.encodings=n,yield o.sender.setParameters(d)}const a=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(a),r.kind==="audio"){const d=this._enableStereo,h=this._enableHighBitrate?d?128e3:64e3:d?64e3:32e3;a.sdp=a.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${d?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:a,callback:d=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),yield this._pc.setRemoteDescription(d),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),s=i.encodings.length-1-r;i.encodings.forEach((o,a)=>{a>=s?o.active=!0:o.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})}),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class vu extends fu{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new vu}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("Safari12::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${r.kind}, track.id: ${r.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),d=RTCRtpSender.getCapabilities(r.kind);l.info(`Safari12::senders available params: ${JSON.stringify(d)}`);const h=[];if(i){const f=d.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=[...new Set(g).values()];f.sdpFmtpLine=E.join(";")}h.push(f)}l.info(`Safari12::selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h);const p=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(p),r.kind==="audio"){const f=this._enableStereo,g=this._enableHighBitrate?f?128e3:64e3:f?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${f?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${g}`)}return{offerSdp:p,callback:f=>u(this,null,function*(){return l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(f)}]`),yield this._pc.setRemoteDescription(f),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}receive(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}})}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)})}}}function MD(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=wm.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(e.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(e.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"}))return"Safari11";if(e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(r.name&&r.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(n){const i=Number(n[1]);return i>=74?"Chrome74":i>=70?"Chrome70":i>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class vv{constructor({handlerName:e,handlerFactory:r}={}){if(m(this,"handlerFactory"),m(this,"_handlerName"),m(this,"_observer"),l.debug("constructor()"),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)l.debug(`Device::constructor() | handler given: ${e}`);else if(e=MD(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=gu.createFactory();break;case"Safari12":this.handlerFactory=vu.createFactory();break;case"Firefox60":this.handlerFactory=lc.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=lc.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new It}get handlerName(){return this._handlerName}createSendTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o})}createRecvTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s})}}let DD=class extends vv{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){const a=di(),d=new AD({id:a,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",d),d}};var Et;class OD{constructor(e){k(this,Et,void 0),T(this,Et,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Et).sendMessagePromiseWithTimeout({event:ie.joinRoom,protobuf:hg.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.createWebRTCTransport,dg.toBinary(e))).payload,{transportId:n,description:i}=ru.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Et).sendMessagePromise(ie.produce,gg.toBinary(e))).payload,s=Rg.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.consume,fg.toBinary(e))).payload,{consumerIdsMap:{map:n}}=Ig.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.closeProducer,yg.toBinary(e))).payload,{description:n}=Pg.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Et).sendMessagePromise(ie.closeConsumer,Eg.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Et).sendMessagePromise(ie.hostControlPeer,kg.toBinary(n))).payload;if(!i)return!1;const{status:s}=Dg.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Et).sendMessagePromise(ie.hostControlAllPeers,bg.toBinary(r))).payload;if(!n)return!1;const{status:i}=Og.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.kickAll,Tg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Mg.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.kickPeer,Sg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ag.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.changeDisplayName,_g.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ng.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.selfJoinComplete,pg.toBinary(e))).payload;return ec.fromBinary(r)})}}Et=new WeakMap;const ND=Error("task execution aborted");class LD{constructor(e,r){m(this,"id"),m(this,"executor"),m(this,"cancel"),this.id=e,this.executor=r}execute(){return u(this,null,function*(){return new Promise((e,r)=>{this.cancel=()=>r(ND),this.executor.then(n=>e(n))})})}}let Kp=0;const Ko=new Map;class zi{static execute(e){const r=Kp;Kp+=1;const n=new LD(r,e);return Ko.set(r,n),{id:r,value:n.execute().finally(()=>Ko.delete(r))}}static stop(e){const r=Ko.get(e);r&&(r.cancel(),Ko.delete(e))}}var ot=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t))(ot||{}),ss=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(ss||{});const xD=2e3;var an;class FD extends lv{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),k(this,an,void 0),T(this,an,e),this._device=new DD({}),this._socket=r,this.transportState={consuming:{state:ot.NEW,reconnected:!1},producing:{state:ot.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new OD(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield We().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&zi.stop(v.id),s){case"send":{const I=zi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,an).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,an).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,an).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,I),I.value}case"recv":{const I=zi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,an).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,I),I.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield gr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield gr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?xt.SUBSCRIBER:xt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},xD);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,dc(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,dc(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${i.type}`);break}}catch{l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Ul(o.sdp).media.filter(I=>a==="video"?I.type==="video":I.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:xt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:I,producerId:A}=yield this._socketHandler.produce(v);p({answer:I,producerId:A})}catch(I){l.error("create producer error:",I),f(I)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o,producerId:a},d,h){l.info("consumePeer:",o);const p={producingPeerId:o,producerId:a};try{const f=yield this._socketHandler.consume(p);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:f});const g=new Map;Object.entries(f).forEach(([E,v])=>{var I,A,D;let x={};try{x=JSON.parse(v.producerState.appData)}catch{}g.set(E,{consumerId:v.consumerId,trackId:(I=v.producerTrack)==null?void 0:I.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===Ct.VIDEO?"video":"audio",appData:x,screenShare:(A=v.producerState)==null?void 0:A.screenShare,paused:(D=v.producerState)==null?void 0:D.pause})}),d({consumersMap:g})}catch(f){l.error("consumePeer error:",{error:f}),h(f)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,I,A,D,x;const W={producingPeerId:a,producerId:o};try{const H=(yield this._socketHandler.consume(W))[o];let R={};try{R=JSON.parse((p=H.producerState)==null?void 0:p.appData)}catch{}l.info("consumer create response:",{consumer:{remotelyPaused:(f=H.producerState)==null?void 0:f.pause,producerId:(g=H.producerState)==null?void 0:g.producerId,kind:(v=(E=H.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},R),{screenShare:(I=H.producerState)==null?void 0:I.screenShare}),id:H.consumerId},consumerState:H}),d({consumerId:H.consumerId,screenShare:(A=H.producerState)==null?void 0:A.screenShare,trackId:(D=H.producerTrack)==null?void 0:D.trackId,streamId:H.producerTrack.streamId,kind:H.producerState.kind===Ct.VIDEO?"video":"audio",paused:(x=H.producerState)==null?void 0:x.pause,appData:R})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Lr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Lr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:xt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Lr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Lr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(s=>this.getProducer(s.producerId))){l.warn("why are you creating a consumer for local producer?");return}const i=K.hasFeature(X.ENABLE_HIVE_CONSUME_OVER_DC);yield gr(s=>u(this,null,function*(){s>0&&l.debug(`retrying consume call, retryCount: ${s}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r,consumeOverDC:i}).catch(o=>{throw l.error("failed to consume:",{error:o}),o})).forEach(o=>{o.status==="rejected"?(l.error("consumer creation task is failing",o.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(o.value)})})).catch(s=>{l.error("create consumer failed after retries",{error:s}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(b.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,an).getValue("modules").e2ee.enabled&&w.emit(b.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(ie.toggleConsumer,Za.toBinary(r)),e.pause(),w.emit(b.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(ie.toggleConsumer,Za.toBinary(n)),r.resume(),w.emit(b.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:xt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(ie.renegotiateSessionDescription,lg.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch{l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:ot.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:ot.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:ot.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>20*1e3&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:ot.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(b.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}an=new WeakMap;var UD=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,de=(t,e,r,n)=>{for(var i=n>1?void 0:n?VD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&UD(e,r,i),i};const In={joinAttempted:!1},BD=3e3;var Ie,he,Tr,Mi,Rn,Pn,zo,Yo,Qo,qr,Ds,Yt,_r,Kr,zp;const yv=(zp=class extends dv{constructor(t,e){var r,n;super(),k(this,_r),k(this,Ie,void 0),k(this,he,void 0),k(this,Tr,void 0),k(this,Mi,void 0),k(this,Rn,void 0),k(this,Pn,void 0),k(this,zo,void 0),k(this,Yo,void 0),k(this,Qo,void 0),k(this,qr,void 0),k(this,Ds,void 0),k(this,Yt,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Ie,a),T(this,Tr,!1),T(this,Yt,void 0),T(this,he,new FD(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,qr,new Set),T(this,Mi,!1),T(this,Rn,0),T(this,Pn,new is),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSocketConnectionEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),T(this,zo,mr(()=>u(this,null,function*(){if(!In.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,Yo,mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),T(this,Qo,mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(b.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Ie).connectionState}get mediaState(){return c(this,he).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new yv(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,he)}get rejoinRoom(){return c(this,zo)}reset(t=!0){var e,r,n,i;(r=(e=c(this,he))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,he))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,qr).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Pn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,Pn,new is))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,Tr)}`),!(!t||c(this,Tr))&&(t.direction==="send"?yield c(this,Yo).call(this,t):yield c(this,Qo).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,he).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,he).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){In.joinAttempted=!0,T(this,Tr,!0),this.reset(s);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,Ds)){const h=a.loc.split(",");T(this,Ds,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Pn).push(()=>this._joinRoom(r,n,i,o,c(this,Ds)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=We().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield gr((o,a)=>(c(this,Ie).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Pn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},Ee.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{this.roomJoined=!0;const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,T(this,Mi,!0),T(this,Tr,!1),this.maxPreferredStreams=t!=null?t:6,w.emit(b.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),this.roomJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){c(this,he).stopAllTransports(),T(this,Mi,!1),In.joinAttempted=!1;const t={closeRoom:!1};c(this,Ie).sendMessagePromise(ie.leaveRoom,mg.toBinary(t)).then(e=>{var r;(r=Cg.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,he).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t,e="default"){return u(this,null,function*(){if(l.info("deactivating producers",{producerInfo:{peerId:t.peerId,producers:t.producers}}),t.producers.some(r=>r.screenShare&&r.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:r,kind:n})=>{if(n==="audio"&&e!=="default"){l.debug("we don't want to deactive audio consumers");return}const i=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!i){l.warn(`consumer not found in deactivate producers: ${r}`);return}this.sfuHandler.closeConsumer(i)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){return t.forEach(e=>{this.activatedProducingPeerIds.delete(e)}),this.sfuHandler.closeConsumers(t)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,he).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in HiveNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,he).producers.has(Y.WEBCAM)){const n=c(this,he).producers.get(Y.WEBCAM);if(!n.closed&&!navigator.isReactNative)return yield n.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,he).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(K.hasFeature(X.ENABLE_HIVE_SIMULCAST)){let n=t.getConstraints().width;n in Lp||(n=320),e.encodings=Lp[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,he).createProducer(Y.WEBCAM,e,r)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,he).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,he).createProducer(Y.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new at("track undefined");if(c(this,he).producers.has(Y.MIC)){const n=c(this,he).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,he).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,he).createProducer(Y.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,he).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,hn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,hn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,hn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,hn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,he).removeProducer(Y.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,he).removeProducer(Y.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,he).removeProducer(Y.SCREENSHARE_VIDEO),yield c(this,he).removeProducer(Y.SCREENSHARE_AUDIO),c(this,qr).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,he).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,he).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.hiveSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.hiveSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Ie).sendMessagePromise(ie.globalPinPeer,vg.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,qr).add(t.consumerPeerId),c(this,qr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ie).on(ie.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Lg.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===Ct.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=xg.fromBinary(t),s=r===Ct.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),e===this.peerId&&n){w.emit(s==="audio"?b.MUTE_ALL:b.MUTE_ALL_VIDEO);return}w.emit(b.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),w.emit(b.CONSUMER_PAUSED,{id:o.id})):(o.resume(),w.emit(b.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ie).on(ie.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=tc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,qr).delete(e),this.sfuHandler.cleanupConsumers(e),w.emit(b.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Fg.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(b.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Ie).on(ie.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Tr)&&!c(this,Mi)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Ie).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,Yt)&&(clearTimeout(c(this,Yt)),T(this,Yt,void 0)),ue(this,_r,Kr).call(this,"connected")})),c(this,Ie).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==ot.CONNECTED||n.state!==ot.CONNECTED?w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:In.joinAttempted}):T(this,Yt,setTimeout(()=>{w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:In.joinAttempted}),T(this,Yt,void 0)},BD)),ue(this,_r,Kr).call(this,"disconnected"),this.roomJoined=!1}),c(this,Ie).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,_r,Kr).call(this,"reconnecting")})),c(this,Ie).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,_r,Kr).call(this,"reconnectAttempt",e)})),c(this,Ie).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,_r,Kr).call(this,"reconnectFailure",t)}),c(this,Ie).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:In}),c(this,Yt)&&(clearTimeout(c(this,Yt)),T(this,Yt,void 0)),w.emit(b.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:In.joinAttempted}),ue(this,_r,Kr).call(this,"reconnected")})),c(this,Ie).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),w.emit(b.SOCKET_SERVICE_FAILED),ue(this,_r,Kr).call(this,"failed"),this.roomJoined=!1}))}handleSFUEvents(){c(this,he).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,he).on("rejoin",t=>{if(c(this,Rn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Tr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,Rn,c(this,Rn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Rn)}]`),this.roomJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Ie=new WeakMap,he=new WeakMap,Tr=new WeakMap,Mi=new WeakMap,Rn=new WeakMap,Pn=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Qo=new WeakMap,qr=new WeakMap,Ds=new WeakMap,Yt=new WeakMap,_r=new WeakSet,Kr=function(t,e){let r;const{reconnected:n}=c(this,Ie).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(w.emit(b.SOCKET_STATE_UPDATE,r),c(this,Ie).connectionState=r)},zp);let oe=yv;de([y.trace("HiveNodeClient.reset")],oe.prototype,"reset",1);de([y.trace("HiveNodeClient.reconnect")],oe.prototype,"reconnectTransport",1);de([y.trace("HiveNodeClient.setupTransport")],oe.prototype,"setupTransports",1);de([y.trace("HiveNodeClient.stopAllProducers")],oe.prototype,"stopAllProducers",1);de([y.trace("HiveNodeClient.joinRoom")],oe.prototype,"joinRoom",1);de([y.trace("HiveNodeClient.completeJoinRoom")],oe.prototype,"completeJoinRoom",1);de([y.trace("HiveNodeClient.leaveRoom")],oe.prototype,"leaveRoom",1);de([y.trace("HiveNodeClient.activatePeers")],oe.prototype,"activatePeers",1);de([y.trace("HiveNodeClient.deactivatePeers")],oe.prototype,"deactivatePeers",1);de([y.trace("HiveNodeClient.createConsumer")],oe.prototype,"createConsumer",1);de([y.trace("HiveNodeClient.pauseConsumers")],oe.prototype,"pauseConsumers",1);de([y.trace("HiveNodeClient.resumeConsumers")],oe.prototype,"resumeConsumers",1);de([y.trace("HiveNodeClient.closeConsumers")],oe.prototype,"closeConsumers",1);de([y.trace("HiveNodeClient.consumePeer")],oe.prototype,"consumePeer",1);de([y.trace("HiveNodeClient.shareWebcam")],oe.prototype,"shareWebcam",1);de([y.trace("HiveNodeClient.shareScreen")],oe.prototype,"shareScreen",1);de([y.trace("HiveNodeClient.shareMic")],oe.prototype,"shareMic",1);de([y.trace("HiveNodeClient.pauseMic")],oe.prototype,"pauseMic",1);de([y.trace("HiveNodeClient.pauseWebcam")],oe.prototype,"pauseWebcam",1);de([y.trace("HiveNodeClient.resumeMic")],oe.prototype,"resumeMic",1);de([y.trace("HiveNodeClient.resumeWebcam")],oe.prototype,"resumeWebcam",1);de([y.trace("HiveNodeClient.disableWebcam")],oe.prototype,"disableWebcam",1);de([y.trace("HiveClient.disableMic")],oe.prototype,"disableMic",1);de([y.trace("HiveClient.disableScreenShare")],oe.prototype,"disableScreenShare",1);de([y.trace("HiveNodeClient.muteSelf")],oe.prototype,"muteSelf",1);de([y.trace("HiveNodeClient.resetVideoProducers")],oe.prototype,"resetVideoProducers",1);de([y.trace("HiveNodeClient.changeDisplayName")],oe.prototype,"changeDisplayName",1);de([y.trace("HiveNodeClient.kickPeer")],oe.prototype,"kick",1);de([y.trace("HiveNodeClient.kickAllPeers")],oe.prototype,"kickAll",1);de([y.trace("HiveNodeClient.muteAll")],oe.prototype,"muteAll",1);de([y.trace("HiveNodeClient.muteAllVideo")],oe.prototype,"muteAllVideo",1);de([y.trace("HiveNodeClient.disableAudio")],oe.prototype,"disableAudio",1);de([y.trace("HiveNodeClient.disableVideo")],oe.prototype,"disableVideo",1);de([y.trace("HiveNodeClient.pinPeer")],oe.prototype,"pinPeer",1);de([y.trace("HiveNodeClient.validateScreenShare")],oe.prototype,"validateScreenShare",1);de([y.trace("HiveNodeClient.init")],oe,"init",1);class jD{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const i=this.add(e,r);return n!==i?i:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class kl{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new jD,this._compulsoryPeers=new Set}add(e,r){if(r<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,r)}delete(e){l.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get peerPriorities(){return Array.from(this._activeSpeakerPeers).map((e,r)=>r)}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}var HD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Bt=(t,e,r,n)=>{for(var i=n>1?void 0:n?WD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&HD(e,r,i),i};const $D=["ACTIVE_GRID","PAGINATED","MANUAL"];var Di,jt,Qt,An,Ht,Yp;let bt=(Yp=class extends Ut{constructor(t,e,r,n){var i;super(),k(this,jt),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"pinned"),m(this,"all"),m(this,"pip"),k(this,Di,void 0),k(this,An,void 0),k(this,Ht,void 0),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",new kl),T(this,Di,t),T(this,An,e),T(this,Ht,r),this.waitlisted=new Jo,this.joined=new Jo,this.active=new Jo,this.pinned=new Jo,this.selectedPeers=new kl,this.all=new vD,this.viewMode="ACTIVE_GRID",this.currentPage=0,((i=n==null?void 0:n.pip)==null||i)&&(this.pip=new SD(t,e)),this.setupEvents()}get roomJoined(){var t;return((t=c(this,jt,Qt))==null?void 0:t.roomJoined)===!0}setupEvents(){w.on(b.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Di).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){return c(this,jt,Qt).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24");c(this,jt,Qt).maxPreferredStreams=t,c(this,An).roomJoined&&w.emit(b.REFRESH_GRID)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.joined.toArray().filter(e=>e.stageStatus==="ON_STAGE");return Math.ceil(t.length/this.maxActiveParticipantsCount)}return 0}acceptWaitingRoomRequest(t){var e,r;if(!this.roomJoined)throw new C("Can`t accept waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return c(this,Ht).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,Ht).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!this.roomJoined)throw new C("Can`t reject waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;c(this,Ht).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>$D.includes(e))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`);if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,jt,Qt)instanceof oe))throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,w.emit(b.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,w.emit(b.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Please activate MANUAL subscription mode first.");const e={},r=[],n=[];t.forEach(a=>{e[a.id]=!0;const d=this.active.get(a.id);if(!d)r.push(a);else{d.manualProducerConfig=a.producers;const h=p=>u(this,[p],function*({producers:f,config:g}){const E=[];f.forEach(v=>{const I=v.kind==="audio",A=v.kind==="video";(I&&(g.audio&&!v.screenShare||g.screenshareAudio&&v.screenShare)||A&&(g.video&&!v.screenShare||g.screenshareVideo&&v.screenShare))&&E.push(v.producerId),c(this,jt,Qt).closeConsumers(E)})});n.push(h({peerId:a.id,config:a.producers,producers:d.producers}))}});const i=[];this.active.forEach(a=>{if(e[a.id])return;const d=h=>u(this,null,function*(){const p={peerId:h.id,producers:h.producers};yield c(this,jt,Qt).deactivatePeers(p,"manual"),this.active.delete(h.id);const f=this.joined.get(h.id);f.manualProducerConfig=rl});i.push(d(a))}),yield Promise.all([...i,...n]);const s=(a,d)=>a.reduce((h,p)=>(!p.screenShare&&d[p.kind]&&h.push(p),p.screenShare&&(p.kind==="audio"&&d.screenshareAudio||p.kind==="video"&&d.screenshareVideo)&&h.push(p),h),[]),o=r.map(a=>{const d=this.joined.get(a.id);return this.active.add(d),d.manualProducerConfig=a.producers,{peerId:d.id,producers:s(d.producers,a.producers)}});yield c(this,jt,Qt).activatePeers(o),this.active.emit("participantsUpdate")})}unsubscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");t.forEach(e=>u(this,null,function*(){const r=this.joined.get(e);if(!r)return;const n={peerId:r.id,producers:r.producers};r.manualProducerConfig=rl,yield c(this,jt,Qt).deactivatePeers(n,"manual"),this.active.delete(r.id)}))})}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,s))}setPage(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw l.error("DyteParticipants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`);this.currentPage=t,w.emit(b.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.roomJoined)throw new C("Can`t disable all audio without joining room");if(c(this,An).permissions.canAllowParticipantAudio)return c(this,jt,Qt).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.")})}disableAllVideo(){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_video"),!this.roomJoined)throw new C("Can`t disable all video without joining room");if(c(this,An).permissions.canAllowParticipantVideo)return c(this,jt,Qt).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield w.emitAsync(b.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Di).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can`t kick all without joining room");if(!c(this,An).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.");c(this,Ht).kickAll()})}broadcastMessage(t,e,r){return u(this,null,function*(){if(l.info("DyteParticipants::broadcastMessage"),!this.roomJoined)throw new C("Can`t broadcast message without joining room");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.");if(r){let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var s;return(s=r.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),c(this,Ht).broadcastToPeers(t,n,e)}else c(this,Ht).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,Ht).getRoomPeers(t,e,r)).peers.map(Er.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];c(this,Ht).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,Ht).getRoomPeersNonPaginated()})}},Di=new WeakMap,jt=new WeakSet,Qt=function(){return c(this,Di).getValue("roomNodeClient")},An=new WeakMap,Ht=new WeakMap,Yp);Bt([y.trace("DyteParticipants.setViewMode")],bt.prototype,"setViewMode",1);Bt([y.trace("DyteParticipants.setPage")],bt.prototype,"setPage",1);Bt([y.trace("DyteParticipants.disableAllAudio")],bt.prototype,"disableAllAudio",1);Bt([y.trace("DyteParticipants.disableAllVideo")],bt.prototype,"disableAllVideo",1);Bt([y.trace("DyteParticipants.disablePeerAudio")],bt.prototype,"disableAudio",1);Bt([y.trace("DyteParticipants.disablePeerVideo")],bt.prototype,"disableVideo",1);Bt([y.trace("DyteParticipants.kickPeer")],bt.prototype,"kick",1);Bt([y.trace("DyteParticipants.kickAll")],bt.prototype,"kickAll",1);Bt([y.trace("DyteParticipants.broadcastMessage"),Pt({maxInvocations:500,period:60})],bt.prototype,"broadcastMessage",1);Bt([y.trace("DyteParticipants.getAllJoinedPeers"),Pt({maxInvocations:10,period:60})],bt.prototype,"getAllJoinedPeers",1);Bt([y.trace("DyteParticipant.updatePermissions"),Pt({maxInvocations:1e3,period:60})],bt.prototype,"updatePermissions",1);Bt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],bt.prototype,"getParticipantsInMeetingPreJoin",1);bt=Bt([ht("1200")],bt);var GD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,vi=(t,e,r,n)=>{for(var i=n>1?void 0:n?JD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&GD(e,r,i),i};class Er{constructor(e,r,n,i){m(this,"participants"),m(this,"self"),m(this,"selectedPeers",new kl),m(this,"currentActiveGridParticipants",new Set),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),m(this,"updateConsumerSpatialLayers",mr(()=>{const s={},o=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(o.entries()).forEach(([a,d])=>{s[d]===void 0&&(s[d]={layer:d,consumerIds:[]}),s[d].consumerIds.push(a)}),Object.keys(s).forEach(a=>{const d=s[a];l.log(`Switching max spatial layer to ${d.layer}`,{consumerIds:d.consumerIds}),this.roomNodeClient.switchConsumersToLayer(d.consumerIds,d.layer)})},2e3)),m(this,"refreshGridParticipants",mr((s=!1)=>{const o=new Map,a=Array.from(this.participants.joined.toArray().filter(I=>I.stageStatus==="ON_STAGE").map(I=>(o.set(I.id,!0),I.id))),d=this.selectedPeers.peers,h=this.participants.pinned.toArray().reduce((I,A)=>(A.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(A.id):I.push(A.id),I),[]);if(this.participants.viewMode!=="ACTIVE_GRID"){l.warn("ParticipantController::refreshGridParticipants::not_refreshing_grid_in_not_active_grid_mode");return}const p=this.self.stageStatus==="ON_STAGE"?1:0,f=this.participants.maxActiveParticipantsCount-p,g=new Set(d.concat(h).filter(I=>I!==this.self.id&&o.has(I)));let E=Array.from(g);const v=f-g.size;if(v>=0){const I=a.filter(A=>!g.has(A)&&A!==this.self.id).slice(0,v);E=Array.from(g).concat(I)}else E=E.slice(0,f);this.updateActiveParticipants(E,s)},500,{trailing:!0,leading:!0})),this.context=e,this.roomSocketHandler=n,this.participants=new bt(e,r,this.roomSocketHandler,i),this.self=r,this.consumerPeerMap=new Map,r.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get roomJoined(){var e;return((e=this.roomNodeClient)==null?void 0:e.roomJoined)===!0}waitingRoomRequestHandler(e){const r=e.requests.filter(i=>!this.participants.waitlisted.toArray().find(s=>s.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!e.requests.find(s=>s.userId===i.userId));r.forEach(i=>this.participants.waitlisted.add(new Ur(this.context,{id:i.peerId,displayName:i.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:i.userId,flags:{},isHost:!1},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}updateActive(e){return u(this,arguments,function*({page:r}){if(r&&r!==0){const{compulsoryPeers:n}=this.selectedPeers,i=n.filter(p=>this.participants.joined.has(p)),s=Array.from(this.participants.pinned.keys()).filter(p=>!i.includes(p)),o=Array.from(this.participants.joined.toArray().filter(p=>p.stageStatus==="ON_STAGE").map(p=>p.id)),a=Math.max((r-1)*(this.roomNodeClient.maxPreferredStreams-i.length-s.length)),d=r*(this.roomNodeClient.maxPreferredStreams-i.length-s.length),h=i.concat(s,o.slice(a,d));this.updatePageParticipants(h)}else w.emit(b.REFRESH_GRID)})}updatePageParticipants(e){const r=new Set(e),n=new Map(this.participants.active);this.participants.active.forEach((s,o)=>{this.participants.active.delete(o,!r.has(o))}),r.forEach(s=>{if(!this.participants.joined.get(s)){l.warn("updatePageParticipants::participant_not_in_joined_list",{dyteParticipant:{id:s}});return}this.participants.active.add(this.participants.joined.get(s),!n.get(s))}),this.currentActiveGridParticipants=new Set(this.participants.active.keys()),Array.from(n.keys()).forEach(s=>{if(r.has(s))return;const o=this.participants.joined.get(s);if(!o)return;const a={producers:o.producers,peerId:o.id};this.roomNodeClient.deactivatePeers(a)});const i=[];return this.participants.active.forEach(s=>{const o={peerId:s.id,producers:s.producers};i.push(o)}),this.roomNodeClient.activatePeers(i),{activePeers:n,peerIdsSet:r}}computeActivateParticipants(e,r){const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(e){var r,n,i,s;const o={};return(r=e.flags)!=null&&r.hiddenParticipant&&(o.hidden_participant=(n=e.flags)==null?void 0:n.hiddenParticipant),((i=e.flags)==null?void 0:i.recorderType)!==void 0&&((s=e.flags)==null?void 0:s.recorderType)!=="NONE"&&(o.recorder=!0),new Ur(this.context,ne(V({},e),{flags:o,id:e.peerId,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0,picture:e.displayPictureUrl,stageStatus:oc(e.stageType)}),this.self,this.roomSocketHandler)}onMediaJoined(e,r){return u(this,null,function*(){if(!this.roomJoined||e===this.self.id)return;const n=this.participants.joined.get(e);if(!n){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${e}`);return}r.forEach(i=>{i.kind===Ct.AUDIO&&!i.screenShare?n.setAudioEnabled(!i.pause):i.kind===Ct.VIDEO&&!i.screenShare&&n.setVideoEnabled(!i.pause),n.producers.push(ne(V({},i),{producingTransportId:i.producingTransportId,kind:i.kind===Ct.AUDIO?"audio":"video"}))})})}updateActiveParticipantsMapMinReplacement(e){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipants",{roomJoined:this.roomJoined});return}const r=Array.from(this.participants.active.keys()),n=new Map(this.participants.active),i={};e.forEach(o=>{i[o]=!0});const s=[];r.forEach((o,a)=>{(!i[o]||!this.participants.joined.get(o))&&s.push(a)}),e.forEach(o=>{n.get(o)||(r.length<e.length?r.push(o):r[s.shift()]=o)}),r.forEach((o,a)=>{i[o]||r.splice(a,1)}),Array.from(this.participants.active.keys()).forEach(o=>{this.participants.active.delete(o,!i[o])}),r.forEach(o=>{if(!this.participants.joined.get(o)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:o}});return}this.participants.active.add(this.participants.joined.get(o),!n.get(o))}),this.participants.active.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(e=>{e.setIsPinned(!1),this.participants.pinned.delete(e.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:e})=>{if(!e.waitlisted){if(this.context.getValue("viewType")==="LIVESTREAM"&&e.stageType!==1)return;this.onParticipantJoined(this.fromSocketService(e))}}),this.roomSocketHandler.on(j.leaveRoom,e=>{this.selectedPeers.delete(e.peer.peerId),this.onParticipantLeave(e.peer.peerId)}),w.on(b.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),w.on(b.SOCKET_SERVICE_DISCONNECTED,()=>{Array.from(this.participants.joined.keys()).forEach(e=>{this.participants.joined.delete(e)}),Array.from(this.participants.active.keys()).forEach(e=>{this.participants.active.delete(e)}),Array.from(this.participants.pinned.keys()).forEach(e=>{this.participants.pinned.delete(e)}),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),this.currentActiveGridParticipants=new Set}),w.on(b.CONSUMER_PAUSED,({id:e})=>{this.processConsumerPaused(e)}),w.on(b.CONSUMER_RESUMED,({id:e})=>{this.processConsumerResumed(e)}),w.on(b.NEW_CONSUMER,({id:e})=>{this.processNewConsumer(e)}),w.on(b.CONSUMER_CLOSED,({id:e})=>{this.processConsumerClosed(e)}),w.on(b.ROOM_MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),w.on(b.MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),w.on(b.LOW_CONSUMER_SCORE,({peerId:e,score:r,kind:n})=>{const i=this.participants.joined.get(e);i&&(i.emit("poorConnection",{score:r,kind:n}),this.participants.emit("poorConnection",{participantId:e,score:r,kind:n}))}),w.on(b.CONSUMER_SCORE_UPDATE,({score:e,kind:r,appData:n,peerId:i})=>{var s;const o=r==="video"&&((s=n==null?void 0:n.screenShare)!=null?s:!1),a=this.participants.joined.get(i);a&&(a.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}),this.participants.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}))}),w.onAsync(b.KICK_PEER,e=>u(this,[e],function*({peerId:r}){const n=this.participants.joined.get(r);yield this.roomNodeClient.kick(r),yield this.roomSocketHandler.kick(r),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:r})})),w.on(b.UPDATE_ACTIVE,(...e)=>u(this,[...e],function*({page:r}={}){yield this.updateActive({page:r})}))}onParticipantPinned(e){return u(this,null,function*(){if(!e){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(e===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const r=this.participants.joined.get(e);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),r.setIsPinned(!0),this.participants.pinned.add(r)})}onParticipantJoined(e){return u(this,null,function*(){var r,n,i;this.self.id!==e.id&&!((r=e.flags)!=null&&r.recorder)&&!((n=e.flags)!=null&&n.hidden_participant)&&!((i=e.flags)!=null&&i.hiddenParticipant)&&(this.participants.active.delete(e.id),this.participants.joined.add(e),this.participants.waitlisted.delete(e.id),e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(b.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!0})),w.emit(b.PEER_JOINED_INTERNAL,e),!(this.self.config.viewType===qe.Webinar&&e.stageStatus!=="ON_STAGE")&&(this.roomNodeClient===void 0||this.participants.active.size>=this.roomNodeClient.maxPreferredStreams||this.updateActive({page:this.participants.currentPage}))})}onParticipantLeave(e){return u(this,null,function*(){const r=this.participants.joined.get(e);this.participants.joined.delete(e,!0,!0),this.participants.pinned.delete(e,!0,!0),this.participants.waitlisted.delete(e,!0,!0),r&&r.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&w.emit(b.UPDATE_STAGE_REQUESTS,{request:{displayName:r.name,userId:r.userId,peerId:r.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),s=this.participants.active.get(e);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?n===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(n-1):s&&this.updateActive({page:n})})}processMedia(e){var r;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:o,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}=(r=n.get(e))!=null?r:{};if(!i)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:e,kind:s,peerId:i,appData:{supportsRemoteControl:o==null?void 0:o.supportsRemoteControl,screenShare:o==null?void 0:o.screenShare},remotelyPaused:a,producerId:h}}),{};const f=o;return s==="video"&&f.screenShare!==!0&&this.videoPeerConsumerMap.set(i,e),l.info("ParticipantController::processMedia",{consumer:{id:e,peerId:i,kind:s,appData:f,remotelyPaused:a,producerId:h}}),this.consumerPeerMap.set(e,{type:s,peerId:i,appData:f,remotelyPaused:a,producerId:h}),{peerId:i,kind:s,appData:f,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}}processConsumerClosed(e){const{peerId:r,type:n,appData:i,remotelyPaused:s,producerId:o}=this.consumerPeerMap.get(e)||{},a=this.participants.joined.get(r);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:e,peerId:r,appData:i,kind:n,remotelyPaused:s,producerId:o}}),this.consumerPeerMap.delete(e),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(r),!a)return;const d=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),B.consumerSharedMediaState(e,{screen:!1}),a.screenShareTracks.video&&d.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&d.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&d.push(a.audioTrack.id),B.consumerSharedMediaState(e,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),a.videoTrack&&d.push(a.videoTrack.id),B.consumerSharedMediaState(e,{video:!1}),a.videoTrack=void 0),i.e2ee&&d.forEach(h=>{w.emit(b.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:h})})}processConsumerResumed(e){const{peerId:r,kind:n,appData:i,track:s,remotelyPaused:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:e,peerId:r,kind:n,appData:i,remotelyPaused:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(i.e2ee&&w.emit(b.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s}),i.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),h.setScreenShareEnabled(!0),B.consumerSharedMediaState(e,{screen:!0});return}n==="video"?(h.videoTrack=s,h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!0})):n==="audio"&&(h.audioTrack=s,h.setAudioEnabled(h.audioEnabled),B.consumerSharedMediaState(e,{audio:h.audioEnabled}))}}processConsumerPaused(e){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${e}`);const{peerId:r,kind:n,track:i,appData:s,remotelyPaused:o,producerId:a}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:e,peerId:r,kind:n,appData:s,remotelyPaused:o,producerId:a}});const d=this.participants.joined.get(r);d&&(i&&s.e2ee&&w.emit(b.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:i.id}),n==="video"?(d.videoTrack=i,d.setVideoEnabled(!1),B.consumerSharedMediaState(e,{video:!1})):n==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),B.consumerSharedMediaState(e,{audio:d.audioEnabled})))}processNewConsumer(e){const{peerId:r,kind:n,remotelyPaused:i,track:s,appData:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(o.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||K.hasFeature(X.SCREEENSHARE_ERR_HACK))&&h.setScreenShareEnabled(!0),o.supportsRemoteControl&&(h.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:r,screenShare:!0,consumerId:e,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});return}n==="video"?(h.videoTrack=s,i||h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!i})):n==="audio"&&(h.audioTrack=s,i||h.setAudioEnabled(!0),B.consumerSharedMediaState(e,{audio:!i})),!i&&o.e2ee&&w.emit(b.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s})}}static formatSocketServiceMessage(e){var r,n,i,s;if(!e)return;const o=oc(e.stageType);return{id:e.peerId,userId:e.userId,name:e.displayName,displayName:e.displayName,stageType:o,customParticipantId:e.customParticipantId,presetId:e.presetId,picture:e.displayPictureUrl,waitlisted:e.waitlisted,stageStatus:o,metadata:{preset_name:(r=e.flags)==null?void 0:r.presetName},recorderType:(n=e.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=e.flags)==null?void 0:i.hiddenParticipant,recorder:!!((s=e.flags)!=null&&s.recorderType)}}}updateActiveParticipants(e,r=!1){if(this.updateActiveParticipantsMapMinReplacement(e),!this.roomJoined)return;l.info("ParticipantController::updateActiveParticipants::updating_current_selected_peers",{debuggingHint:r?"Forcefully updating currentActiveGridParticipants set":null}),r&&(this.currentActiveGridParticipants=new Set);const n=new Set(e),i=[],s=[];if(this.currentActiveGridParticipants.forEach(a=>{n.has(a)||i.push(a)}),n.forEach(a=>{this.currentActiveGridParticipants.has(a)||s.push(a)}),this.currentActiveGridParticipants=n,s.length===0&&i.length===0)return;const o=[];i.forEach(a=>{const d=this.participants.joined.get(a);if(!d)return;const h={producers:d.producers,peerId:d.id};o.push(this.roomNodeClient.deactivatePeers(h))}),Promise.all(o).then(()=>{const a=[];s.forEach(d=>{const h=this.participants.active.get(d);if(!h){l.warn("peer is not in active map which is going to activate, should not happen",{dyteParticipant:{id:d}});return}const p={peerId:h.id,producers:h.producers,force:r};a.push(p)}),this.roomNodeClient.activatePeers(a)}).catch(a=>{l.info("Error on deactivating peers",a)})}onSelectedPeers(e,r){return u(this,null,function*(){if(this.participants.viewMode!=="ACTIVE_GRID")return;const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)})}updateActiveParticipantsWithPriorities(e,r=!1){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.roomJoined});return}let n=null;e.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority),(n===null||i.priority<n.priority)&&(n=i)}),n&&n.peerId!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n.peerId,this.participants.emit("activeSpeaker",{peerId:n.peerId,volume:n.priority})),r&&this.refreshGridParticipants()}}vi([y.trace("updateActiveParticipantsMapMinReplacement")],Er.prototype,"updateActiveParticipantsMapMinReplacement",1);vi([y.trace("ParticipantController.setupEvents")],Er.prototype,"setupEventsGlobal",1);vi([y.trace("ParticipantController.processMedia")],Er.prototype,"processMedia",1);vi([y.trace("ParticipantController.processConsumerClosed")],Er.prototype,"processConsumerClosed",1);vi([y.trace("ParticipantController.processConsumerResumed")],Er.prototype,"processConsumerResumed",1);vi([y.trace("ParticipantController.processConsumerPaused")],Er.prototype,"processConsumerPaused",1);vi([y.trace("ParticipantController.processNewConsumer")],Er.prototype,"processNewConsumer",1);var qD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,zD=(t,e,r,n)=>{for(var i=n>1?void 0:n?KD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&qD(e,r,i),i};class Ev extends Er{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(b.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(se.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(se.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),w.emit(b.REFRESH_GRID,!0)}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&mr(()=>{this.refreshGridParticipants(e)},500,{maxWait:1e3,leading:!0})()}),w.on(b.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),w.on(b.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),w.on(b.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(se.globalPeerPinBroadcast,({participantId:e})=>{if(!this.roomJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);this.roomNodeClient.activatePeers([{peerId:n.id,producers:n.producers}]).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(se.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(se.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}zD([y.trace("ParticipantController.setupEvents")],Ev.prototype,"setupEvents",1);var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,XD=(t,e,r,n)=>{for(var i=n>1?void 0:n?QD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&YD(e,r,i),i};class Sv extends Er{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),w.on(b.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>{r.waitlisted||this.onParticipantJoined(this.fromSocketService(r))})})),this.roomSocketHandler.on(ie.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(ie.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),w.emit(b.REFRESH_GRID,!0)}),w.on(b.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),w.on(b.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&this.refreshGridParticipants(e)}),w.on(b.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}if(n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=r.kind==="audio",o=r.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!r.screenShare||a.screenshareAudio&&r.screenShare)||o&&(a.video&&!r.screenShare||a.screenshareVideo&&r.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumer(e,r):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}});return}(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),w.on(b.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),w.on(b.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(ie.globalPeerPinBroadcast,e=>{let r;if(e&&(r=e.participantId),!this.roomJoined)return;const n=r;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers([{peerId:i.id,producers:i.producers}]).catch(s=>{l.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(ie.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ie.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}XD([y.trace("ParticipantController.setupEvents")],Sv.prototype,"setupEvents",1);const be=fr(eu().permissions);var G,zs,ro,bl,wt,Nt;const Ys=class extends Ut{constructor(t,e,r,n=!1){if(super(),k(this,wt),k(this,G,void 0),k(this,zs,void 0),k(this,ro,void 0),k(this,bl,i=>{const s=i,{chat:o,connectedMeetings:a,plugins:d,polls:h,media:p}=s,f=Ec(s,["chat","connectedMeetings","plugins","polls","media"]);let g=!1;o&&(i.chat.private&&Zr(c(this,G).chat.private,i.chat.private),i.chat.public&&Zr(c(this,G).chat.public,i.chat.public),g=!0,this.emit("chatUpdate")),a&&(g=!0,Zr(c(this,G).connectedMeetings,i.connectedMeetings)),p&&(g=!0,Zr(c(this,G).media,i.media)),d&&(Zr(c(this,G).plugins,i.plugins),g=!0,this.emit("pluginsUpdate")),h&&(Zr(c(this,G).polls,i.polls),g=!0,this.emit("pollsUpdate")),Object.keys(f).length!==0&&(Zr(c(this,G),f),g=!0),g&&this.emit("permissionsUpdate")}),!e)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.");T(this,ro,t),T(this,zs,r),T(this,G,e),n&&this.setupEvents()}setupEvents(){w.on(b.UPDATE_PERMISSIONS,c(this,bl))}static fromResponse(t,e,r){return new Ys(r,t,e,!0)}static default(t,e){return new Ys(t,be,e)}static init(t,e,r){let n;return r?n=new Ys(t,r,e,!0):n=new Ys(t,be,e),n}get mediaRoomType(){const{sfu:t}=c(this,ro).getValue("roomNodeOptions");return t===ss.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,G))==null?void 0:t.stageEnabled)||c(this,zs)===qe.Webinar||c(this,zs)===qe.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=c(this,G))==null?void 0:t.acceptStageRequests)||((e=c(this,G))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=c(this,G))==null?void 0:t.stageAccess)===q.NotAllowed?q.NotAllowed:((e=c(this,G))==null?void 0:e.stageAccess)===q.CanRequest?q.CanRequest:((r=c(this,G))==null?void 0:r.stageAccess)===q.Allowed||c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed?q.Allowed:c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=c(this,G))==null?void 0:t.acceptWaitingRequests)!=null?e:be.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantAudio)!=null?e:be.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:be.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:be.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.kickParticipant)!=null?e:be.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.pinParticipant)!=null?e:be.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canRecord)!=null?e:be.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:be.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:be.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,G))==null?void 0:t.plugins)!=null?e:be.plugins}get polls(){var t,e;return(e=(t=c(this,G))==null?void 0:t.polls)!=null?e:be.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest}get canProduceVideo(){var t;const e=(t=c(this,G).media.video.canProduce)!=null?t:be.media.video.canProduce;return this.stageEnabled&&(c(this,wt,Nt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,wt,Nt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,wt,Nt)==="OFF_STAGE"||c(this,wt,Nt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=c(this,G).media.screenshare.canProduce)!=null?t:be.media.screenshare.canProduce;return this.stageEnabled&&(c(this,wt,Nt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,wt,Nt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,wt,Nt)==="OFF_STAGE"||c(this,wt,Nt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=c(this,G).media.audio.canProduce)!=null?t:be.media.audio.canProduce;return this.stageEnabled&&(c(this,wt,Nt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,wt,Nt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,wt,Nt)==="OFF_STAGE"||c(this,wt,Nt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:be.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:be.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:be.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:be.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,G))==null?void 0:t.connectedMeetings)!=null?e:be==null?void 0:be.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.hiddenParticipant)!=null?e:be.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,G).showParticipantList)!=null?t:be.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:be.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:be.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=c(this,G).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,G).isRecorder}get canSpotlight(){return c(this,G).canSpotlight}get canLivestream(){return c(this,G).canLivestream}get transcriptionEnabled(){return c(this,G).transcriptionEnabled}};let ZD=Ys;G=new WeakMap,zs=new WeakMap,ro=new WeakMap,bl=new WeakMap,wt=new WeakSet,Nt=function(){return c(this,ro).getValue("stageStatus")};var Tv;class eO extends Ut{constructor(){super(...arguments),m(this,"localMediaHandler"),k(this,Tv,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const n=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?w.emit(b.MEDIA_PERMISSION_ERROR,f):w.emit(b.MEDIA_PERMISSION_UPDATE,f)};if(Ee.getName()==="firefox")return;const i="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),a=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:s}),d=(h,p)=>{switch(p){case"granted":n(h,"ACCEPTED");break;case"denied":n(h,"DENIED");break;case"prompt":n(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};o&&(o.onchange=()=>d("audio",o.state)),a&&(a.onchange=()=>d("video",a.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:n}){B.onSafeInitialization(()=>{switch(n){case"audio":{B.mediaPermission("AUDIO",r),B.mediaPermission("SPEAKER",r);break}case"video":{B.mediaPermission("VIDEO",r);break}case"screenshare":{B.mediaPermission("SCREENSHARE",r);break}}})})}init(){return u(this,arguments,function*(e={},r=!1,n=null){var i,s,o,a,d;if(Ee.init(),!this.localMediaHandler)try{let h=!0;if(n!=null&&n.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:p}=navigator;this.localMediaHandler=yield p.init()}else this.localMediaHandler=new At(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(w.on(b.MEDIA_PERMISSION_UPDATE,p=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:p.message,kind:p.kind}),p.message==="NOT_REQUESTED")switch(p==null?void 0:p.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",p)})),w.on(b.MEDIA_PERMISSION_ERROR,p=>u(this,null,function*(){const{kind:f,message:g,constraints:E}=p;this.populateMediaPermissionsInCallstats({message:g,kind:f}),f==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):f==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:g},constraints:E,mediaPermissionsErrors:{kind:f,message:g}}),this.emit("mediaPermissionError",p),this.emit("mediaPermissionUpdate",{message:g,kind:f})})),h){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${!!(e!=null&&e.audio)} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const p=this.localMediaHandler.setupStreams({video:(a=e==null?void 0:e.video)!=null?a:!0,audio:(d=e==null?void 0:e.audio)!=null?d:!0});r||(yield p)}}catch(h){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch{}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(e)}catch{}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Tv=new WeakMap;const Os={},En={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const o=s.value;return s.value=function(...a){if(Os[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}Os[e]=!0;const d=setTimeout(()=>delete Os[e],r),h=o.apply(this,a);return Promise.resolve(h).then(()=>{delete Os[e],clearTimeout(d)}).catch(()=>{delete Os[e],clearTimeout(d)}),h},s}}};var tO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,Mt=(t,e,r,n)=>{for(var i=n>1?void 0:n?rO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&tO(e,r,i),i},Xo,kr,Ns,Oi,$e,Qe,Ls,Ld,Qp,Xp;let ct=(Xp=class extends eO{constructor(t,e,r,n,i){var s;super(),k(this,$e),k(this,Ld),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),k(this,Xo,void 0),k(this,kr,void 0),k(this,Ns,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),k(this,Oi,void 0),m(this,"presetName"),m(this,"roomState","init"),k(this,Ls,new Set),T(this,Oi,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",T(this,kr,r),T(this,Xo,n),T(this,Ns,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ee.isElectron(),this.device=Ee.getDeviceInfo(),this.presetName=i,n.viewType!==qe.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this)}get stageStatus(){return c(this,Oi).getValue("stageStatus")}get id(){return c(this,Oi).getValue("peerId")}static __init__(t,e,r,n,i,s=!1){return u(this,null,function*(){var o,a,d,h,p;let f=(a=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?a:!0,g=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;r.canProduceAudio!=="ALLOWED"&&(f=!1),r.canProduceVideo!=="ALLOWED"&&(g=!1);const E=new ct(t,e,r,n,i);if(n.viewType===qe.Chat)return E;const v=NM(n.mediaConstraints);return Zr(v,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield E.init({audio:f,video:g,constraints:v},s,t),E.setupEvents(),E})}setupEvents(){this.on("videoUpdate",ue(this,Ld,Qp)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},ri(this))),this.roomJoined&&this.audioEnabled)try{yield c(this,$e,Qe).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",V({},ri(this))),this.roomJoined&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&this.roomJoined)try{const t=yield c(this,$e,Qe).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,$e,Qe).shareWebcam(this.videoTrack))}catch(t){l.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>u(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!this.roomJoined){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,$e,Qe).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",V({},ri(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){l.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",V({},ri(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{B.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){this.roomJoined&&(yield c(this,$e,Qe).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff()}))}get permissions(){return c(this,kr)}get config(){return c(this,Xo)}get roomJoined(){var t;return((t=c(this,$e,Qe))==null?void 0:t.roomJoined)===!0}setName(t){if(!t)throw new C("Name cannot be empty.");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){var e,r;return t.forceReset&&(c(this,$e,Qe).stopAllProducers(),this.localMediaHandler.removeAllTracks()),this.localMediaHandler.setupStreams({video:(e=t.video)!=null?e:!0,audio:(r=t.audio)!=null?r:!0})})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==q.NotAllowed&&!(c(this,kr).canProduceAudio===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(yield this.localMediaHandler.enableAudio(),this.roomJoined&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,$e,Qe).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,$e,Qe).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOn()}})}enableVideo(){return u(this,null,function*(){if(c(this,kr).canProduceVideo!==q.NotAllowed&&!(c(this,kr).canProduceVideo===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(yield this.localMediaHandler.enableVideo(),this.roomJoined&&this.stageStatus==="ON_STAGE")try{yield c(this,$e,Qe).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",V({},ri(this))),B.videoOn()}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t enable screenshare without joining room");if(c(this,kr).canProduceScreenshare!==q.NotAllowed&&!(c(this,kr).canProduceScreenshare===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield c(this,$e,Qe).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),this.roomJoined&&c(this,$e,Qe).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),this.roomJoined&&(yield c(this,$e,Qe).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),this.roomJoined&&(yield c(this,$e,Qe).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){T(this,Ns,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}get isPinned(){return c(this,Ns)}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participants without joining room");return c(this,$e,Qe).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participants without joining room");return c(this,$e,Qe).pinPeer(null)})}setDevice(t){return u(this,null,function*(){var e,r,n;if(!t)throw new C("No device selected");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((r=i==null?void 0:i.video)==null?void 0:r.deviceId)===t.deviceId||((n=i==null?void 0:i.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),K.hasFeature(X.SKIP_SETTING_IN_USE_DEVICE)))throw new C("Cannot set device currently in use");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch{this.roomJoined&&(yield c(this,$e,Qe).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch{this.roomJoined&&(yield c(this,$e,Qe).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t){c(this,Ls).add(t),this.updateVideo(t)}deregisterVideoElement(t){t.srcObject=void 0,c(this,Ls).delete(t)}updateVideo(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0}},Xo=new WeakMap,kr=new WeakMap,Ns=new WeakMap,Oi=new WeakMap,$e=new WeakSet,Qe=function(){return c(this,Oi).getValue("roomNodeClient")},Ls=new WeakMap,Ld=new WeakSet,Qp=function(){Array.from(c(this,Ls)).forEach(this.updateVideo)},Xp);Mt([y.trace("DyteSelf.setupEvents")],ct.prototype,"setupEvents",1);Mt([y.trace("DyteSelf.setupTracks")],ct.prototype,"setupTracks",1);Mt([y.trace("DyteSelf.destructMediaHandler")],ct.prototype,"destructMediaHandler",1);Mt([y.trace("DyteSelf.removeDocumentEventListeners")],ct.prototype,"removeDocumentEventListeners",1);Mt([En.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],ct.prototype,"enableAudio",1);Mt([En.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],ct.prototype,"enableVideo",1);Mt([y.trace("DyteSelf.updateVideoConstraints")],ct.prototype,"updateVideoConstraints",1);Mt([y.trace("DyteSelf.enableScreenShare"),En.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ct.prototype,"enableScreenShare",1);Mt([y.trace("DyteSelf.updateScreenshareConstraints")],ct.prototype,"updateScreenshareConstraints",1);Mt([En.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],ct.prototype,"disableAudio",1);Mt([En.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],ct.prototype,"disableVideo",1);Mt([En.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],ct.prototype,"disableScreenShare",1);Mt([y.trace("DyteSelf.setDevice")],ct.prototype,"setDevice",1);ct=Mt([ht("1100")],ct);class nO extends pv{constructor(e){super(e),m(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class iO extends gv{}class sO extends fv{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return cc(e.map(r=>u(this,null,function*(){return gr(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(V({},r))}))})))})}consumerCreationTask(e){return u(this,arguments,function*({consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,paused:d,screenShare:h,appData:p,kind:f,sessionDescription:g}){const E=`${o}:${f}`,v={consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,sessionDescription:g,appData:p,kind:f,paused:d,screenShare:h,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((I,A)=>u(this,null,function*(){const D=setTimeout(()=>{this.consumerTrackEvents.delete(E),v.isTimedout=!0,A(v)},5e3),x=(R,S)=>{try{if(R.readyState==="ended")clearTimeout(D),A(v);else{const P=R;P.enabled=!0,this.handler.midTransceiverMap.set(S.mid,S);const O=new nO({id:r,localId:S.mid,track:P,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:ne(V({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:S.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,O),O.once("close",()=>{this.consumers.delete(O.id),this.handler.midTransceiverMap.delete(S.mid)}),l.info("consumer created for ",{consumer:{id:r,kind:f,appData:{screenShare:h},peerId:i,producerId:n}}),this.observer.emit("newconsumer",O),clearTimeout(D),I(O)}}catch(P){l.warn("error while creating consumer:",P),clearTimeout(D),A(v)}},W=this.consumerTrackPool.get(r);if((W==null?void 0:W.length)===2){x(W[0],W[1]);return}const H=this.unknownTracksMap.get(E);H?(this.unknownTracksMap.delete(E),x(H.track,H.transceiver)):this.consumerTrackEvents.set(E,x),g&&(yield this.safeEmitAsPromise("negotiate",{description:g}))}))})}connect(){return u(this,null,function*(){try{const{offerSdp:e,callback:r}=yield this.handler.connect(),{answer:n}=yield this.safeEmitAsPromise("connect",{offer:e});if(yield r(n),!(yield this.isConnected))throw new Error("ice connection failed")}catch(e){throw l.error("transport failed to connect:",e),e}})}_ontrack(e){const{track:r,transceiver:n}=e;l.info(`track event received [trackId: ${r.id}]`);const i=`${n.mid}:${r.kind}`;r.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${r.id}]`),this.consumerTrackPool.delete(r.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(r.id,[r,n]);const s=this.consumerTrackEvents.get(i);s?(s(r,n),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,e))}consume(e){return u(this,null,function*(){const{producers:r,producingPeerId:n}=e;if(l.debug(`consume() peerId: ${n}, producers: ${JSON.stringify(r)}`),this.closed)throw new at("closed");if(this.direction!=="recv")throw new ci("not a receiving Transport");if(typeof e.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[],{consumersMap:s}=yield this.safeEmitAsPromise("consume_peer",{producingPeerId:n});return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:I,sessionDescription:A}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:n,producingTransportId:I,paused:f,screenShare:p,appData:v,sessionDescription:A}))}),cc(i)})}produce(){return u(this,arguments,function*({track:e,encodings:r,codecOptions:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,appData:a={}}={}){if(l.debug(`produce() [track:${e.id}]`),e){if(this.direction!=="send")throw new ci("not a sending Transport");if(e.readyState==="ended")throw new at("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:g,callback:E,sender:v,mid:I}=yield this.handler.send({track:e,encodings:r,codecOption:n,screenShare:a==null?void 0:a.screenShare}),{answer:A,producerId:D}=yield this.safeEmitAsPromise("produce",{offer:g,kind:e.kind,paused:s?!e.enabled:!1,appData:ne(V({},a||{}),{mid:I})}),x=yield E(A);return{producerId:D,localId:x,rtpSender:v}}),"producer"),f=new iO({id:d,localId:h,track:e,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:a,handler:this.handler,rtpSender:p});return this.producers.set(d,f),f.observer.on("close",()=>{this.producers.delete(f.id)}),this.emit("newproducer",f),this.observer.emit("newproducer",f),f})}}class oO extends vv{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,config:a}){const d=di(),h=new sO({id:d,direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,handlerFactory:this.handlerFactory,config:a});return this._observer.emit("newtransport",h),h}}var St;class aO{constructor(e){k(this,St,void 0),T(this,St,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,St).sendMessagePromiseWithTimeout({event:se.joinRoom,protobuf:hg.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,St).sendMessagePromise(se.createWebRTCTransport,dg.toBinary(e))).payload,{transportId:n,description:i}=ru.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,St).sendMessagePromise(se.produce,gg.toBinary(e))).payload,s=Rg.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,St).sendMessagePromise(se.consume,fg.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=Ig.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,St).sendMessagePromise(se.closeProducer,yg.toBinary(e))).payload,{description:n}=Pg.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,St).sendMessagePromise(se.closeConsumer,Eg.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,St).sendMessagePromise(se.hostControlPeer,kg.toBinary(n))).payload;if(!i)return!1;const{status:s}=Dg.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,St).sendMessagePromise(se.hostControlAllPeers,bg.toBinary(r))).payload;if(!n)return!1;const{status:i}=Og.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,St).sendMessagePromise(se.kickAll,Tg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Mg.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,St).sendMessagePromise(se.kickPeer,Sg.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ag.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,St).sendMessagePromise(se.changeDisplayName,_g.toBinary(e))).payload;if(!r)return!1;const{status:n}=Ng.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,St).sendMessagePromise(se.selfJoinComplete,pg.toBinary(e))).payload;return ec.fromBinary(r)})}}St=new WeakMap;const cO=2e3;var cn;class dO extends lv{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),k(this,cn,void 0),T(this,cn,e),this._device=new oO({}),this._socket=r,this.transportState={consuming:{state:ot.NEW,reconnected:!1},producing:{state:ot.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new aO(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield We().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&zi.stop(v.id),s){case"send":{const I=zi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,cn).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,cn).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,cn).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,I),I.value}case"recv":{const I=zi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,cn).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,I),I.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield gr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield gr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?xt.SUBSCRIBER:xt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},cO);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,dc(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,dc(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch{l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Ul(o.sdp).media.filter(I=>a==="video"?I.type==="video":I.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:xt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:I,producerId:A}=yield this._socketHandler.produce(v);p({answer:I,producerId:A})}catch(I){l.error("create producer error:",{error:I}),f(I)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o},a,d){l.info("consumePeer:",o);const h={producingPeerId:o};try{const p=yield this._socketHandler.consume(h);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:p.consumerStateMap});const f=new Map;Object.entries(p.consumerStateMap).forEach(([g,E])=>{var v,I,A;let D={};try{D=JSON.parse(E.producerState.appData)}catch{}f.set(g,{consumerId:E.consumerId,trackId:(v=E.producerTrack)==null?void 0:v.trackId,streamId:E.producerTrack.streamId,kind:E.producerState.kind===Ct.VIDEO?"video":"audio",appData:D,screenShare:(I=E.producerState)==null?void 0:I.screenShare,paused:(A=E.producerState)==null?void 0:A.pause,sessionDescription:p.sessionDescription})}),a({consumersMap:f})}catch(p){l.error("consumePeer error:",{error:p}),d(p)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,I,A,D,x;const W={producingPeerId:a,producerId:o};try{const H=yield this._socketHandler.consume(W),R=H.consumerStateMap[o];let S={};try{S=JSON.parse((p=R.producerState)==null?void 0:p.appData)}catch{}l.info("consumer create response:",{consumer:{remotelyPaused:(f=R.producerState)==null?void 0:f.pause,producerId:(g=R.producerState)==null?void 0:g.producerId,kind:(v=(E=R.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},S),{screenShare:(I=R.producerState)==null?void 0:I.screenShare}),id:R.consumerId,sessionDescription:H.sessionDescription},consumerState:R}),d({consumerId:R.consumerId,screenShare:(A=R.producerState)==null?void 0:A.screenShare,trackId:(D=R.producerTrack)==null?void 0:D.trackId,streamId:R.producerTrack.streamId,kind:R.producerState.kind===Ct.VIDEO?"video":"audio",paused:(x=R.producerState)==null?void 0:x.pause,appData:S,sessionDescription:H.sessionDescription})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Lr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Lr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:xt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Y.MIC,Y.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Lr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Lr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Y.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Y.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),w.emit(b.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),w.emit(b.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(i=>this.getProducer(i.producerId))){l.warn("why are you creating a consumer for local producer?");return}yield gr(i=>u(this,null,function*(){i>0&&l.debug(`retrying consume call, retryCount: ${i}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r}).catch(s=>{throw l.error("failed to consume:",{error:s}),s})).forEach(s=>{s.status==="rejected"?(l.error("consumer creation task is failing",s.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(s.value)})})).catch(i=>{l.error("create consumer failed after retries",{error:i}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&w.emit(b.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,cn).getValue("modules").e2ee.enabled&&w.emit(b.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(se.toggleConsumer,Za.toBinary(r)),e.pause(),w.emit(b.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(se.toggleConsumer,Za.toBinary(n)),r.resume(),w.emit(b.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:xt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(se.renegotiateSessionDescription,lg.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),w.emit(b.CONSUMER_PAUSED,{id:i.id})):(i.resume(),w.emit(b.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch{l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:ot.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:ot.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:ot.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>20*1e3&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:ot.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),w.emit(b.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}cn=new WeakMap;var lO=Object.defineProperty,uO=Object.getOwnPropertyDescriptor,le=(t,e,r,n)=>{for(var i=n>1?void 0:n?uO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&lO(e,r,i),i};const Ni={joinAttempted:!1},hO=5e3;var Re,pe,br,Li,Mn,Dn,Zo,ea,ta,zr,xs,On,wr,Yr,Zp;const _v=(Zp=class extends dv{constructor(t,e){var r,n;super(),k(this,wr),k(this,Re,void 0),k(this,pe,void 0),k(this,br,void 0),k(this,Li,void 0),k(this,Mn,void 0),k(this,Dn,void 0),k(this,Zo,void 0),k(this,ea,void 0),k(this,ta,void 0),k(this,zr,void 0),k(this,xs,void 0),k(this,On,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Re,a),T(this,br,!1),T(this,On,void 0),T(this,pe,new dO(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,zr,new Set),T(this,Li,!1),T(this,Mn,0),T(this,Dn,new is),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSFUEvents(),this.handleSocketConnectionEvents(),this.handleCallstatsEvents(),T(this,Zo,mr(()=>u(this,null,function*(){if(!Ni.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(w.emit(b.RESET_PRODUCER_STATE),w.emit(b.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,ea,mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),w.emit(b.RESET_PRODUCER_STATE)}),1e3)),T(this,ta,mr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,w.emit(b.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Re).connectionState}get mediaState(){return c(this,pe).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new _v(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,Zo)}reset(t=!0){var e,r,n,i;(r=(e=c(this,pe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,pe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,zr).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Dn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,Dn,new is))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,br)}`),!(!t||c(this,br))&&(t.direction==="send"?yield c(this,ea).call(this,t):yield c(this,ta).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,pe).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,pe).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){Ni.joinAttempted=!0,T(this,br,!0),this.reset(s);const a=We().ipInfo;if(a!=null&&a.loc&&!c(this,xs)){const h=a.loc.split(",");T(this,xs,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Dn).push(()=>this._joinRoom(r,n,i,o,c(this,xs)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||w.emit(b.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=We().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield gr((o,a)=>(c(this,Re).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Dn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},Ee.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,T(this,br,!1),T(this,Li,!0),this.roomJoined=!0,w.emit(b.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}})}leaveRoom(){return u(this,null,function*(){c(this,pe).stopAllTransports(),T(this,Li,!1),Ni.joinAttempted=!1;const t={closeRoom:!1};c(this,Re).sendMessagePromise(se.leaveRoom,mg.toBinary(t)).then(e=>{var r;(r=Cg.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,pe).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t){return u(this,null,function*(){if(l.info("deactivating producers"),t.producers.some(e=>e.screenShare&&e.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:e,kind:r})=>{if(r==="audio"){l.debug("we don't want to deactive audio consumers");return}const n=this.sfuHandler.producerIdToConsumerIdMap.get(e);if(!n){l.warn(`consumer not found in deactivate producers: ${e}`);return}this.sfuHandler.closeConsumer(n)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){const e=Array.from(this.getConsumers().values()).filter(r=>t.includes(r.peerId)).map(r=>r.id);return t.forEach(r=>{this.activatedProducingPeerIds.delete(r)}),this.sfuHandler.closeConsumers(e)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,pe).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,pe).producers.has(Y.WEBCAM)){const i=c(this,pe).producers.get(Y.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,pe).removeProducer(Y.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in xp||(r=640),e.encodings=DM[r],K.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=xp[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Y.WEBCAM,e,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,pe).createProducer(Y.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ee.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,pe).createProducer(Y.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new at("track undefined");if(c(this,pe).producers.has(Y.MIC)){const n=c(this,pe).producers.get(Y.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,pe).removeProducer(Y.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,pe).createProducer(Y.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,hn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,hn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,hn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Y.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&w.emit(b.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,hn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,pe).removeProducer(Y.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,pe).removeProducer(Y.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO),yield c(this,pe).removeProducer(Y.SCREENSHARE_AUDIO),c(this,zr).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,pe).removeProducer(Y.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,pe).removeProducer(Y.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.cfSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.cfSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Re).sendMessagePromise(se.globalPinPeer,vg.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,zr).add(t.consumerPeerId),c(this,zr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Re).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Lg.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),w.emit(b.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===Ct.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Re).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=xg.fromBinary(t),s=r===Ct.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),w.emit(b.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),w.emit(b.CONSUMER_PAUSED,{id:o.id})):(o.resume(),w.emit(b.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Re).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=tc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,zr).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Re).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=Fg.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),w.emit(b.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),w.emit(b.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Re).on(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,br)&&!c(this,Li)||(l.warn("media hub termination broadcast received, rejoining room"),w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Re).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),clearTimeout(c(this,On)),T(this,On,void 0),ue(this,wr,Yr).call(this,"connected")})),c(this,Re).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==ot.CONNECTED||n.state!==ot.CONNECTED?w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Ni.joinAttempted}):T(this,On,setTimeout(()=>{w.emit(b.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Ni.joinAttempted}),T(this,On,void 0)},hO)),ue(this,wr,Yr).call(this,"disconnected"),this.roomJoined=!1}),c(this,Re).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,wr,Yr).call(this,"reconnecting")})),c(this,Re).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,wr,Yr).call(this,"reconnectAttempt",e)})),c(this,Re).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,wr,Yr).call(this,"reconnectFailure",t)}),c(this,Re).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:Ni}),w.emit(b.SOCKET_SERVICE_RECONNECTED),ue(this,wr,Yr).call(this,"reconnected")})),c(this,Re).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),ue(this,wr,Yr).call(this,"failed")}))}handleSFUEvents(){c(this,pe).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,pe).on("rejoin",t=>{if(c(this,Mn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,br)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,Mn,c(this,Mn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Mn)}]`),this.roomJoined=!1,w.emit(b.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&w.emit(b.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&w.emit(b.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Re=new WeakMap,pe=new WeakMap,br=new WeakMap,Li=new WeakMap,Mn=new WeakMap,Dn=new WeakMap,Zo=new WeakMap,ea=new WeakMap,ta=new WeakMap,zr=new WeakMap,xs=new WeakMap,On=new WeakMap,wr=new WeakSet,Yr=function(t,e){let r;const{reconnected:n}=c(this,Re).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(c(this,Re).connectionState=r,w.emit(b.SOCKET_STATE_UPDATE,r))},Zp);let ce=_v;le([y.trace("CFNodeClient.reset")],ce.prototype,"reset",1);le([y.trace("CFNodeClient.reconnect")],ce.prototype,"reconnectTransport",1);le([y.trace("CFNodeClient.setupTransport")],ce.prototype,"setupTransports",1);le([y.trace("CFNodeClient.stopAllProducers")],ce.prototype,"stopAllProducers",1);le([y.trace("CFNodeClient.joinRoom")],ce.prototype,"joinRoom",1);le([y.trace("CFNodeClient.completeJoinRoom")],ce.prototype,"completeJoinRoom",1);le([y.trace("CFNodeClient.leaveRoom")],ce.prototype,"leaveRoom",1);le([y.trace("CFNodeClient.activatePeers")],ce.prototype,"activatePeers",1);le([y.trace("CFNodeClient.deactivatePeers")],ce.prototype,"deactivatePeers",1);le([y.trace("CFNodeClient.createConsumer")],ce.prototype,"createConsumer",1);le([y.trace("CFNodeClient.pauseConsumers")],ce.prototype,"pauseConsumers",1);le([y.trace("CFNodeClient.resumeConsumers")],ce.prototype,"resumeConsumers",1);le([y.trace("CFNodeClient.closeConsumers")],ce.prototype,"closeConsumers",1);le([y.trace("CFNodeClient.consumePeer")],ce.prototype,"consumePeer",1);le([y.trace("CFNodeClient.shareWebcam")],ce.prototype,"shareWebcam",1);le([y.trace("CFNodeClient.shareScreen")],ce.prototype,"shareScreen",1);le([y.trace("CFNodeClient.shareMic")],ce.prototype,"shareMic",1);le([y.trace("CFNodeClient.pauseMic")],ce.prototype,"pauseMic",1);le([y.trace("CFNodeClient.pauseWebcam")],ce.prototype,"pauseWebcam",1);le([y.trace("CFNodeClient.resumeMic")],ce.prototype,"resumeMic",1);le([y.trace("CFNodeClient.resumeWebcam")],ce.prototype,"resumeWebcam",1);le([y.trace("CFNodeClient.disableWebcam")],ce.prototype,"disableWebcam",1);le([y.trace("CFClient.disableMic")],ce.prototype,"disableMic",1);le([y.trace("CFClient.disableScreenShare")],ce.prototype,"disableScreenShare",1);le([y.trace("CFNodeClient.muteSelf")],ce.prototype,"muteSelf",1);le([y.trace("CFNodeClient.resetVideoProducers")],ce.prototype,"resetVideoProducers",1);le([y.trace("CFNodeClient.changeDisplayName")],ce.prototype,"changeDisplayName",1);le([y.trace("CFNodeClient.kickPeer")],ce.prototype,"kick",1);le([y.trace("CFNodeClient.kickAllPeers")],ce.prototype,"kickAll",1);le([y.trace("CFNodeClient.muteAll")],ce.prototype,"muteAll",1);le([y.trace("CFNodeClient.muteAllVideo")],ce.prototype,"muteAllVideo",1);le([y.trace("CFNodeClient.disableAudio")],ce.prototype,"disableAudio",1);le([y.trace("CFNodeClient.disableVideo")],ce.prototype,"disableVideo",1);le([y.trace("CFNodeClient.pinPeer")],ce.prototype,"pinPeer",1);le([y.trace("CFNodeClient.validateScreenShare")],ce.prototype,"validateScreenShare",1);le([y.trace("CFNodeClient.init")],ce,"init",1);function pO(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof oe)return r;throw new Error("Room Node Client already setup")}const n=yield oe.init(t,e);return t.setValue("roomNodeClient",n),n})}function mO(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ce)return r;throw new Error("Room Node Client already setup")}const n=yield ce.init(t,e);return t.setValue("roomNodeClient",n),n})}function kv(t,e){return u(this,arguments,function*(r,n,i=ss.HIVE){return i===ss.CF?mO(r,n):pO(r,n)})}function bv(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var fO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,vO=(t,e,r,n)=>{for(var i=n>1?void 0:n?gO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&fO(e,r,i),i};let xi;const wv=class{constructor(t){m(this,"socket"),this.socket=t,this.handleSocketEvents()}static create(t){return xi||(xi=new wv(t)),xi}static cleanup(){var t;try{(t=xi==null?void 0:xi.socket)==null||t.disconnect()}catch{l.error("roomSocketHandler::cleanup")}xi=void 0}joinRoom(t,e,r,n){return u(this,null,function*(){const i={capabilities:[],peer:{displayName:t!=null?t:"Participant",peerId:e,userId:r,waitlisted:!1},roomUuid:""},s=this.socket.sendMessagePromise(j.joinRoom,GC.toBinary(i));try{const{peer:o}=Fi.fromBinary((yield s).payload);w.emit(b.SOCKET_SERVICE_ROOM_JOINED,{peer:o});const a=this.getRoomState();let d=()=>new Promise(f=>{f({peers:[]})});n!==qe.Livestream&&(d=this.getRoomPeersNonPaginated()),n===qe.Livestream&&o.stageType===1&&(d=this.getStagePeers());const[{room:h},{peers:p}]=yield Promise.all([a,d]);return w.emit(b.ROOM_STATE,h),w.emit(b.SOCKET_PEERS,p),{peer:o}}catch(o){throw l.error("RoomSocketHandler.joinRoom.failed",{error:o}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",o)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return PI.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=Ec(e,["id"]);return ne(V({},n),{userId:r})})}catch{return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let n;try{const i={seachQuery:t,limit:e,offset:r},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,LC.toBinary(i));n=vd.fromBinary(s.payload)}catch(i){l.error("getRoomPeers::binary_decode_error",{error:i})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=vd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=vd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(j.getPeerInfo,Vg.toBinary({peerId:t}));e=Fi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=sp.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=sp.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=dp.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=dp.fromBinary(e.payload)}catch(e){l.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),peerIds:[]};return this.socket.sendMessagePromise(j.broadcastMessage,Ao.toBinary(r))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),peerIds:e};return this.socket.sendMessage(j.broadcastToPeers,Ao.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.sendMessagePromise(j.leaveRoom,qC.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,OI.toBinary(e))})}kickAll(){return u(this,null,function*(){this.socket.sendMessage(j.kickAll)})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,xI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,UI.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(ma.updateUserPreset,pR.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=Ao.fromBinary(t);w.emit(b.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToPeers,({payload:t})=>{try{const e=Ao.fromBinary(t);w.emit(b.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,n;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{r=Fi.fromBinary.bind(Fi),n=Fi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?cp.fromBinary(i,s):{requests:[]},n=cp.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=yp.fromBinary.bind(yp);break}case ma.updateUserPreset:{r=lp.fromBinary.bind(lp);break}case se.peerJoinedBroadcast:case ie.peerJoinedBroadcast:{r=tp.fromBinary.bind(tp);break}case se.selfJoinComplete:case ie.selfJoinComplete:{r=ec.fromBinary.bind(ec);break}case se.globalPeerPinBroadcast:case ie.globalPeerPinBroadcast:{r=rp.fromBinary.bind(rp);break}case se.selectedPeer:case ie.selectedPeer:{r=nl.fromBinary.bind(nl);break}case se.selectedPeerDiff:case ie.selectedPeerDiff:{r=ep.fromBinary.bind(ep);break}case se.leaveRoom:case ie.leaveRoom:{r=tc.fromBinary.bind(tc);break}}this.socket.on(t,({payload:i})=>{let s=n;if(!r)return e(void 0);try{s=r(i)}catch(o){l.error("roomSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(ma.getUserPresets,oR.toBinary(e)),n=lR.fromBinary(r.payload).peerPresets[0],i=new TextDecoder().decode(n.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(r){throw l.error("Error in getting user preset",{error:r}),r}})}};let uc=wv;vO([y.trace("RoomSocketHandler.joinRoom")],uc.prototype,"joinRoom",1);var yO=Object.defineProperty,EO=Object.getOwnPropertyDescriptor,ps=(t,e,r,n)=>{for(var i=n>1?void 0:n?EO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&yO(e,r,i),i},Nn,Xt,ft,Ot,Wt,em;const Cv=(em=class{constructor(t,e,r,n){k(this,Ot),m(this,"self"),m(this,"authToken"),k(this,Nn,void 0),m(this,"viewType"),k(this,Xt,void 0),k(this,ft,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,T(this,ft,t),this.viewType=n,this.authToken=s,T(this,Nn,i),T(this,Xt,r),e.config.viewType!==qe.Chat&&this.setupEvents()}get peerId(){return c(this,ft).getValue("peerId")}static init(t,e,r,n,i){return u(this,null,function*(){const s=We(),o=t.getValue("peerId"),a=!!t.getValue("cachedUserDetails"),d=yield ct.__init__(t,r,n,i,i.name,a);if(K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"){const h=!K.hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),B.onSafeInitialization(()=>u(this,null,function*(){B.devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),B.devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),B.devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput"))})),B.initialize({peerId:o,engineName:Ee.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:K.getAllFlags(),logger:l,apiHostnames:ag(t),skipConnectivityChecks:h})}))}return new Cv(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:n,audioEnabled:i,videoEnabled:s,screenShareEnabled:o,screenShareTracks:a}=this.self;if(n.canProduceAudio&&i)try{yield c(this,Ot,Wt).shareMic(e)}catch{this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Ot,Wt).shareWebcam(r);d&&d.id!==r.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Ot,Wt).shareWebcam(d))}catch{this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=c(this,Ot,Wt))==null?void 0:t.shareScreen({video:a.video,audio:a.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){if(B.callEnded(),!t){c(this,Ot,Wt).reset();return}yield this.joinRoom(t)})}setupEvents(){w.on(b.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.self.roomJoined&&this.shareMediaTracks()})),w.on(b.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),w.on(b.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),w.on(b.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),w.on(b.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{this.self.roomState="init",this.resetSelf(t)}),w.on(b.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;(t||this.self.waitlistStatus==="waiting")&&K.hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(e=di()),c(this,Nn).updateURL(e),y.resetPeerId(e),We().setHeader("dyte-tracing-id",e),to.remapContext(e,c(this,ft)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),w.on(b.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,Xt).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,Xt).on(ma.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&w.emit(b.UPDATE_PERMISSIONS,e.patch)})}),c(this,Xt).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,Xt).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,Xt).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),w.onAsync(b.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),w.on(b.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r})=>{var n;const i=e==="video"&&((n=r==null?void 0:r.screenShare)!=null?n:!1);this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:i,score:t,participantId:this.self.id})}),w.on(b.MUTE_ALL,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),B.audioOff())})),w.on(b.MUTE_ALL_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),B.videoOff())})),w.onAsync(b.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),w.on(b.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,Xt).joinRoom(this.self.name,this.self.id,this.self.userId,this.self.config.viewType);c(this,Xt).socket.flush();const r=oc(e.stageType);if(c(this,ft).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,ft).notify("stageStatus")}catch(e){throw l.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(t==="rejected"){try{(e=c(this,Nn))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),yield c(this,Xt).leaveRoom(),c(this,ft).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,ft).notify("stageStatus");try{(r=c(this,Nn))==null||r.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}bv(c(this,ft)),uc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Ot,Wt))==null||t.partialJoinRoom(this.self.name,c(this,ft).getValue("meetingId"),void 0)}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:n,viewType:i,meetingId:s,authToken:o,stageStatus:a,roomNodeOptions:d}=c(this,ft).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:f}=d;try{if(i===qe.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield kv(c(this,ft),{socket:c(this,Nn),peerId:n,meetingId:s,authToken:o,roomNodeUrl:p,meetingTitle:f},h)}const{roomJoined:g}=(r=yield(e=c(this,Ot,Wt))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?r:{};if(!g)return;a==="ON_STAGE"&&this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(g){throw l.error("Error:SelfController.mediaRoomJoin",g),new C("Error: could not join media room",g)}})}leaveMediaRoom(t){return u(this,null,function*(){const e=c(this,ft).getValue("viewType");yield this.cleanupSelf(),!(t==="stageLeft"&&e===qe.Webinar)&&c(this,Ot,Wt)&&(c(this,Ot,Wt).roomJoined&&t!=="disconnected"&&(yield c(this,Ot,Wt).leaveRoom()),!(t==="stageLeft"&&e===qe.Livestream)&&(this.self.roomState="init",c(this,Ot,Wt).roomJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Nn=new WeakMap,Xt=new WeakMap,ft=new WeakMap,Ot=new WeakSet,Wt=function(){return c(this,ft).getValue("roomNodeClient")},em);let yi=Cv;ps([y.trace("SelfController.resetSelf")],yi.prototype,"resetSelf",1);ps([y.trace("SelfController.setupEvents")],yi.prototype,"setupEvents",1);ps([y.trace("SelfController.joinRoom")],yi.prototype,"joinRoom",1);ps([y.trace("SelfController.leaveRoom")],yi.prototype,"leaveRoom",1);ps([y.trace("SelfController.joinMediaRoom")],yi.prototype,"joinMediaRoom",1);ps([y.trace("SelfController.leaveMediaRoom")],yi.prototype,"leaveMediaRoom",1);var Oa;class SO{constructor(e){k(this,Oa,void 0),T(this,Oa,e)}on(e,r){let n;e===j.roomPeerCount?n=ip.fromBinary.bind(ip):n=fp.fromBinary.bind(fp),c(this,Oa).on(e,({payload:i})=>{const s=n(i);return r(s)})}}Oa=new WeakMap;var Na;class TO{constructor(e){k(this,Na,void 0),T(this,Na,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=gd.fromBinary.bind(gd),i=gd.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,Na).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}Na=new WeakMap;var _O=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,yu=(t,e,r,n)=>{for(var i=n>1?void 0:n?kO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&_O(e,r,i),i},Kn;class Hc{constructor(e){k(this,Kn,void 0),T(this,Kn,e)}getPolls(){return c(this,Kn).sendMessagePromise(Pr.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,Kn).sendMessage(Pr.createPoll,sA.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,Kn).sendMessage(Pr.votePoll,aA.toBinary(n))}on(e,r){let n,i;switch(e){case Pr.updatePoll:case Pr.createPoll:case Pr.votePoll:{n=_d.fromBinary.bind(_d),i=_d.create();break}}c(this,Kn).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("pollSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}Kn=new WeakMap;yu([y.trace("PollSocketHandler.getPolls")],Hc.prototype,"getPolls",1);yu([y.trace("PollSocketHandler.createPoll")],Hc.prototype,"createPoll",1);yu([y.trace("PollSocketHandler.votePoll")],Hc.prototype,"votePoll",1);var Lt;class bO{constructor(e){k(this,Lt,void 0),T(this,Lt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Lt).sendMessagePromise(j.getStageRequests);return e?Td.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Lt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Lt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Lt).sendMessage(j.grantStageAccess,zP.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Lt).sendMessage(j.denyStageAccess,QP.toBinary(r))})}joinStage(){return c(this,Lt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Lt).sendMessagePromise(j.leaveStage,vp.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Lt).sendMessagePromise(j.leaveStage,vp.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=gp.fromBinary.bind(gp);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=Td.fromBinary.bind(Td);break}case j.peerStageStatusUpdate:{n=np.fromBinary.bind(np);break}}c(this,Lt).on(e,({payload:i,id:s})=>{if(!i||!n)return r(void 0,s);const o=n(i);return r(o,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield c(this,Lt).sendMessagePromise(j.getPeerInfo,Vg.toBinary({peerId:e}));return Fi.fromBinary(r.payload)})}}Lt=new WeakMap;var tt;class wO{constructor(e){k(this,tt,void 0),T(this,tt,e)}addPlugin(e,r){c(this,tt).sendMessage(J.addPlugin,hP.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,tt).sendMessage(J.removePlugin,mP.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,tt).sendMessagePromise(J.getPlugins);return e?FP.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,tt).sendMessage(J.customPluginEventToRoom,bP.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,tt).sendMessage(J.customPluginEventToPeers,CP.toBinary(s),i)}enablePluginForRoom(e,r){c(this,tt).sendMessage(J.enablePluginForRoom,gP.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.enablePluginForPeers,SP.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,tt).sendMessage(J.disablePluginForRoom,yP.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.disablePluginForPeers,_P.toBinary({pluginId:e,peerIds:r}),n)}storeInsertKeys(e,r,n,i){const s={pluginId:e,storeName:r,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};c(this,tt).sendMessage(J.storeInsertKeys,up.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeGetKeys,AP.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeDeleteKeys,DP.toBinary(s),i)}storeDelete(e,r,n){c(this,tt).sendMessage(J.storeDelete,NP.toBinary({pluginId:e,storeName:r}),n)}getPluginDataOld(e,r){l.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,n){const i={pluginId:e,storeName:r,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};c(this,tt).sendMessage(J.storeInsertKeys,up.toBinary(i))}on(e,r){let n;switch(e){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{n=ol.fromBinary.bind(ol);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{n=hp.fromBinary.bind(hp);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{n=mp.fromBinary.bind(mp);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{n=pp.fromBinary.bind(pp);break}}c(this,tt).on(e,({payload:i,id:s})=>{const o=n(i);return r(o,s)})}}tt=new WeakMap;var CO=Object.defineProperty,IO=(t,e,r)=>e in t?CO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,RO=(t,e,r)=>(IO(t,typeof e!="symbol"?e+"":e,r),r),Eu=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},L=(t,e,r)=>(Eu(t,e,"read from private field"),r?r.call(t):e.get(t)),Pe=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},ve=(t,e,r,n)=>(Eu(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),De=(t,e,r)=>(Eu(t,e,"access private method"),r),dn,zn,Yn,Ve,Qn,Me,He,ln,rt,Or,pn,rr,Yi,Ar,wl,Iv,Qs,La,Cl,Rv,Su,Pv,hc,Tu,Il,Av,co,pc,no,mc,fc,_u,Qi,lo,io,gc,ku={exports:{}},Xi=typeof Reflect=="object"?Reflect:null,tm=Xi&&typeof Xi.apply=="function"?Xi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},xa;Xi&&typeof Xi.ownKeys=="function"?xa=Xi.ownKeys:Object.getOwnPropertySymbols?xa=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:xa=function(t){return Object.getOwnPropertyNames(t)};function PO(t){console&&console.warn&&console.warn(t)}var Mv=Number.isNaN||function(t){return t!==t};function Te(){Te.init.call(this)}ku.exports=Te;ku.exports.once=OO;Te.EventEmitter=Te;Te.prototype._events=void 0;Te.prototype._eventsCount=0;Te.prototype._maxListeners=void 0;var rm=10;function Wc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Te,"defaultMaxListeners",{enumerable:!0,get:function(){return rm},set:function(t){if(typeof t!="number"||t<0||Mv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");rm=t}});Te.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Te.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Mv(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Dv(t){return t._maxListeners===void 0?Te.defaultMaxListeners:t._maxListeners}Te.prototype.getMaxListeners=function(){return Dv(this)};Te.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")tm(a,this,e);else for(var d=a.length,h=Fv(a,d),r=0;r<d;++r)tm(h[r],this,e);return!0};function Ov(t,e,r,n){var i,s,o;if(Wc(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Dv(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,PO(a)}return t}Te.prototype.addListener=function(t,e){return Ov(this,t,e,!1)};Te.prototype.on=Te.prototype.addListener;Te.prototype.prependListener=function(t,e){return Ov(this,t,e,!0)};function AO(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Nv(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=AO.bind(n);return i.listener=r,n.wrapFn=i,i}Te.prototype.once=function(t,e){return Wc(e),this.on(t,Nv(this,t,e)),this};Te.prototype.prependOnceListener=function(t,e){return Wc(e),this.prependListener(t,Nv(this,t,e)),this};Te.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Wc(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():MO(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};Te.prototype.off=Te.prototype.removeListener;Te.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Lv(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?DO(i):Fv(i,i.length)}Te.prototype.listeners=function(t){return Lv(this,t,!0)};Te.prototype.rawListeners=function(t){return Lv(this,t,!1)};Te.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):xv.call(t,e)};Te.prototype.listenerCount=xv;function xv(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Te.prototype.eventNames=function(){return this._eventsCount>0?xa(this._events):[]};function Fv(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function MO(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function DO(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function OO(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Uv(t,e,s,{once:!0}),e!=="error"&&NO(t,i,{once:!0})})}function NO(t,e,r){typeof t.on=="function"&&Uv(t,"error",e,r)}function Uv(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var LO=ku.exports;class xO extends _{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const nm=new xO;class Vv{static encode(e){return nm.toBinary(e)}static decode(e){return nm.fromBinary(new Uint8Array(e))}}function FO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class UO{constructor(e={}){RO(this,"opts"),Pe(this,dn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ve(this,dn,0)}wait(){return u(this,null,function*(){ve(this,dn,L(this,dn)+1);const e=FO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*dE(2,L(this,dn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return L(this,dn)}reset(){ve(this,dn,0)}}dn=new WeakMap;const Qr={debug:0,info:1,warn:2,error:3};class VO{constructor(e){Pe(this,zn,void 0),Pe(this,Yn,void 0),ve(this,zn,console),ve(this,Yn,e)}debug(...e){Qr[L(this,Yn)]>Qr.debug||L(this,zn).debug("[Sockrates]:",...e)}info(...e){Qr[L(this,Yn)]>Qr.info||L(this,zn).info("[Sockrates]:",...e)}warn(...e){Qr[L(this,Yn)]>Qr.warn||L(this,zn).warn("[Sockrates]:",...e)}error(...e){Qr[L(this,Yn)]>Qr.error||L(this,zn).error("[Sockrates]:",...e)}}zn=new WeakMap;Yn=new WeakMap;var Bv=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Bv||{});const BO="2",jO="3";class HO{constructor(e,r){Pe(this,wl),Pe(this,Qs),Pe(this,Cl),Pe(this,Su),Pe(this,hc),Pe(this,Il),Pe(this,co),Pe(this,no),Pe(this,fc),Pe(this,Qi),Pe(this,io),Pe(this,Ve,void 0),Pe(this,Qn,void 0),Pe(this,Me,void 0),Pe(this,He,void 0),Pe(this,ln,void 0),Pe(this,rt,void 0),Pe(this,Or,void 0),Pe(this,pn,void 0),Pe(this,rr,void 0),Pe(this,Yi,void 0),Pe(this,Ar,void 0);var n,i,s,o,a,d,h,p,f,g;ve(this,Qn,e),ve(this,ln,[]),ve(this,rt,new LO),ve(this,Or,!0),ve(this,rr,!1),ve(this,Me,r!=null?r:{}),(n=L(this,Me)).autoReconnect!=null||(n.autoReconnect=!0),(i=L(this,Me)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=L(this,Me)).pingTimeout!=null||(s.pingTimeout=3e4),(o=L(this,Me)).connectionTimeout!=null||(o.connectionTimeout=5e3),(a=L(this,Me)).debug!=null||(a.debug=!0),(d=L(this,Me)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=L(this,Me)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=L(this,Me)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(f=L(this,Me)).flushOnReconnect!=null||(f.flushOnReconnect=!1),ve(this,pn,{code:void 0,reason:void 0}),ve(this,He,(g=L(this,Me).logger)!=null?g:new VO(L(this,Me).debug?"debug":"info")),ve(this,Ar,new UO)}get readyState(){var e;return(e=L(this,Ve))==null?void 0:e.readyState}get url(){return L(this,Qn)}updateURL(e){ve(this,Qn,e),De(this,Il,Av).call(this)}get config(){return L(this,Me)}get sendQueue(){return L(this,ln)}flush(){if(!L(this,Me).queueOnDisconnect)return!1;const e=[];return L(this,ln).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),ve(this,ln,e),L(this,ln)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,Or)!==!1)return new Promise((r,n)=>{De(this,Qi,lo).call(this),De(this,io,gc).call(this);try{ve(this,Ve,new WebSocket(De(this,wl,Iv).call(this,L(this,Qn)))),L(this,Ve).binaryType="arraybuffer",L(this,He).debug("Connecting to",L(this,Qn));const i=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),ve(this,Or,!0),De(this,io,gc).call(this),L(this,Ve).close(3001,"Connection Timeout"),L(this,Me).autoReconnect&&!L(this,rr)&&(L(this,rt).emit("reconnecting"),De(this,co,pc).call(this)),n(new Error("Connection timed out!"))},L(this,Me).connectionTimeout);L(this,Ve).onopen=()=>{L(this,He).debug(`Ready State: ${Bv[L(this,Ve).readyState]}`),i&&clearTimeout(i),De(this,fc,_u).call(this),ve(this,pn,{code:void 0,reason:void 0}),L(this,rt).emit("connected"),L(this,Me).flushOnReconnect&&this.flush(),r()},L(this,Ve).onclose=s=>{try{i&&clearTimeout(i);const{code:o,reason:a}=s;n(a),L(this,He).debug("Socket closed. Close event:",s),L(this,He).debug("Connection closed code:",o),L(this,He).debug("Connection closed reason:",a),L(this,rr)||De(this,hc,Tu).call(this,o,a)}catch(o){De(this,Qs,La).call(this,o)}},L(this,Ve).onerror=s=>{De(this,Qs,La).call(this,s)},L(this,Ve).onmessage=s=>De(this,Cl,Rv).call(this,s)}catch(i){De(this,Qs,La).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(L(this,Me).queueOnDisconnect&&(!L(this,Ve)||L(this,Ve).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,ln).push(s),!1;const o=Vv.encode(s);return De(this,no,mc).call(this,o)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return De(this,no,mc).call(this,e)}receive(e,r){return L(this,rt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){L(this,rt).on(e,r);return}this.receive(e,r)}removeAllListeners(){L(this,rt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){L(this,rt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,rt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){ve(this,Or,!1),De(this,Qi,lo).call(this),this.removeAllListeners(),ve(this,pn,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,Ve).close(1e3,"Sockrates disconnect method called.")}}Ve=new WeakMap;Qn=new WeakMap;Me=new WeakMap;He=new WeakMap;ln=new WeakMap;rt=new WeakMap;Or=new WeakMap;pn=new WeakMap;rr=new WeakMap;Yi=new WeakMap;Ar=new WeakMap;wl=new WeakSet;Iv=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")};Qs=new WeakSet;La=function(t,e){L(this,He).error("Error:",{error:t}),L(this,rt).emit("errored",{error:t}),e==null||e(t)};Cl=new WeakSet;Rv=function(t){if(De(this,fc,_u).call(this),t.data===BO){L(this,He).debug("Received ping from server"),De(this,no,mc).call(this,jO);return}L(this,He).debug("Received data:",t.data);const e=Vv.decode(t.data),{id:r,payload:n}=e;L(this,rt).emit(e.event.toString(),{id:r,payload:n})};Su=new WeakSet;Pv=function(){return L(this,Ve).readyState===1};hc=new WeakSet;Tu=function(t,e){ve(this,pn,{reason:e,code:t}),L(this,rt).emit("disconnected",{code:t,reason:e})};Il=new WeakSet;Av=function(){const{reason:t,code:e}=L(this,pn);e&&e!==1e3&&L(this,Or)&&L(this,Me).autoReconnect&&!L(this,rr)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,rt).emit("reconnecting"),De(this,co,pc).call(this))};co=new WeakSet;pc=function(t=!0){return u(this,null,function*(){if(t&&L(this,rr)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,rr)||L(this,Ar).reset(),L(this,Me).maxReconnectionAttempts!==null&&L(this,Ar).getAttempts()>=L(this,Me).maxReconnectionAttempts){L(this,rt).emit("failed"),ve(this,rr,!1);return}ve(this,rr,!0),De(this,io,gc).call(this),De(this,Qi,lo).call(this);try{if(yield L(this,Ar).wait(),L(this,Or)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,Ar).getAttempts()}`),L(this,rt).emit("reconnectAttempt",{attempt:L(this,Ar).getAttempts()}),yield this.connect(),!De(this,Su,Pv).call(this))throw Error("Reconnect Failed");ve(this,rr,!1),ve(this,pn,{code:void 0,reason:void 0}),L(this,rt).emit("reconnected")}catch{L(this,He).debug("Failed to reconnect."),L(this,rt).emit("reconnectFailure",{attempt:L(this,Ar).getAttempts()}),De(this,co,pc).call(this,!1)}})};no=new WeakSet;mc=function(t){try{return L(this,Ve).send(t),!0}catch(e){return L(this,He).error(e.message),!1}};fc=new WeakSet;_u=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),De(this,Qi,lo).call(this),ve(this,Yi,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),ve(this,Or,!0);const e=3002,r="Ping timeout";(t=L(this,Ve))==null||t.close(e,r),De(this,hc,Tu).call(this,e,r)},L(this,Me).pingTimeout)))};Qi=new WeakSet;lo=function(){L(this,Yi)&&(clearTimeout(L(this,Yi)),ve(this,Yi,void 0))};io=new WeakSet;gc=function(){L(this,Ve)&&(L(this,Ve).onopen=void 0,L(this,Ve).onerror=void 0,L(this,Ve).onmessage=void 0,L(this,Ve).onclose=void 0)};var WO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,$c=(t,e,r,n)=>{for(var i=n>1?void 0:n?$O(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&WO(e,r,i),i};const im=65535;var Ln,Ge,xn,ra,xd,na,Fd,sm;const jv=(sm=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){k(this,ra),k(this,na),k(this,Ln,void 0),k(this,Ge,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),m(this,"connectionState"),k(this,xn,void 0);var s;if(!e||!r||!n)throw new C("peerId, roomName, or authToken can not be empty");T(this,xn,t),this.capabilities=i,this.roomName=r,this.authToken=n,this.connectionState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},T(this,Ln,ue(this,ra,xd).call(this,e)),T(this,Ge,new HO(c(this,Ln),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l}))}get peerId(){return c(this,xn).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,Ln,ue(this,ra,xd).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,Ge).updateURL(c(this,Ln))}static getSocketEdgeDomain(t){return Ki({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,Ln)}connect(){return u(this,null,function*(){yield c(this,Ge).connect()})}disconnect(){return c(this,Ge).disconnect()}get isConnected(){try{return c(this,Ge).readyState===1}catch{return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,Ge).send(t,r!=null?r:ue(this,na,Fd).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,r,n){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:r,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:n,resp:i}){const s=i!=null?i:t;return new Promise((o,a)=>{const d=(E,v)=>{c(this,Ge).removeListener(s,E),c(this,Ge).removeListener(im,v),c(this,Ge).removeListener(ie.errorResponse,v),c(this,Ge).removeListener(se.errorResponse,v)},h=n!=null?n:ue(this,na,Fd).call(this),p={};y.injectContext(p);const f=({id:E,payload:v})=>{if(h===E){let I;try{const A=Bw.fromBinary(v);I=new Error(A.errorMessage)}catch(A){I=new Error("failed to parse error message",{cause:A});try{const D=RC.fromBinary(v);I=new Error(D.message)}catch(D){I=new Error("failed to parse error message",{cause:D})}}a(I),d(g,f)}},g=({id:E,payload:v})=>{h===E&&(o({id:E,payload:v}),d(g,f))};c(this,Ge).on(s,g),c(this,Ge).on(im,f),c(this,Ge).on(ie.errorResponse,f),c(this,Ge).on(se.errorResponse,f),setTimeout(()=>{d(g,f),a(new Error(`request timeout for callback eventId:${t}`))},e),c(this,Ge).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,Ge).on(t,e)}onStateEvent(t,e){c(this,Ge).on(t,e)}flush(){return c(this,Ge).flush()}},Ln=new WeakMap,Ge=new WeakMap,xn=new WeakMap,ra=new WeakSet,xd=function(t){let e=jv.getSocketEdgeDomain(c(this,xn).getValue("baseURI"));typeof Xh(c(this,xn),"socket_server_base")=="string"&&(e=Xh(c(this,xn),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=ne(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>nc[o]).join(" ")});return Object.entries(s).forEach(([o,a])=>{n.searchParams.append(o,a.toString())}),n.href},na=new WeakSet,Fd=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},sm);let To=jv;$c([y.trace("SocketService.connect")],To.prototype,"connect",1);$c([y.trace("SocketService.disconnect")],To.prototype,"disconnect",1);$c([y.trace("SocketService.sendMessagePromise")],To.prototype,"sendMessagePromise",1);$c([y.trace("SocketService.sendMessagePromiseWithTimeout")],To.prototype,"sendMessagePromiseWithTimeout",1);const Xn=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=tI.fromBinary(t),n=r.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(e=r.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=II.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Bg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return ap.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return vI.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Xn.socketService.sendMessagePromise(j.getConnectedRoomsDump);return Xn.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Xn.socketService.sendMessagePromise(j.createConnectedRooms,sI.toBinary({payloads:t}));return ap.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),r=yield Xn.socketService.sendMessagePromise(j.deleteConnectedRooms,fI.toBinary({payloads:e}));return Xn.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Xn.socketService.sendMessagePromise(j.movePeers,kI.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let xe=Xn;m(xe,"socketService"),m(xe,"currentMeetingId");var GO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,Gc=(t,e,r,n)=>{for(var i=n>1?void 0:n?JO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&GO(e,r,i),i};const Zn=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){const{peerId:e,apiBase:r,authToken:n,meetingId:i,organizationId:s,cachedUserDetails:o}=t.getAllValues();if(w.reset(),uc.cleanup(),bv(t),Ee.isSupported()===!1)throw new C("Browser not supported","0010",!0);const a=VA(t,{authToken:n,baseURL:r,cachedUserDetails:o});a.setRoomName(i),a.setRoomUUID(i),a.setOrganizationId(s),a.setHeader("dyte-tracing-id",e),t.setValue("apiClient",a);const d=Zn.createSocketService(t),h=d.connect(),p=a.getPlugins(),[{sfu:f,userResponse:g,meetingTitle:E,roomNodeUrl:v}]=yield Promise.all([Zn.getRoomMetadata(),Zn.setupFlagsmith(t)]);t.setValue("roomNodeOptions",{sfu:f,meetingTitle:E,roomNodeUrl:v});const{theme:I,controllers:A}=yield Zn.setupControllers(d,t,g,p);lM(I)&&Zn.createRoomNodeClient(t,d),ew();try{yield h,A.selfController.partialMediaRoom()}catch(D){throw l.error("[Socket Service] Failed to connect to socket server:",{error:D}),new C("Failed to connect to websocket","0012")}return new Zn(r,A)})}static getRoomMetadata(){return u(this,null,function*(){const t=We(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=ss.HIVE},i]=yield Promise.all([t.getRoomNodeData(),t.getUserDetails()]);return{sfu:n,roomNodeUrl:e,meetingTitle:r,userResponse:i}})}static setupFlagsmith(t){return u(this,null,function*(){const{peerId:e,baseURI:r,overrides:n,meetingId:i,organizationId:s}=t.getAllValues(),o=X0(i),a=ne(V({entity:tl.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:o,roomName:i},Ee.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?Ki({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield K.identify(`${tl.PEER}_${e}`,JSON.parse(JSON.stringify(a)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(K.getAllFlags())},!0)}catch{l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,n){return u(this,null,function*(){var i,s,o;const a=e.getValue("modules"),{preset:d,participant:h}=r,p=e.getValue("defaults"),{sfu:f,meetingTitle:g}=e.getValue("roomNodeOptions"),E=iD.init(d,!a.theme),{viewType:v,mediaConstraints:{audio:I}}=E;e.setValue("viewType",v),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(i=I.enableHighBitrate)!=null?i:!1,enableStereo:(s=I.enableStereo)!=null?s:!1}}},p));const A=ZD.init(e,v,d.permissions);let D,x,W,H,R,S,P,O;const ae=new TO(t);xe.socketService=t;const Oe=new Hc(t),$=new Jt(t),F=new bO(t),ye=uc.create(t),Hr=new wO(t),Sn=new SO(t),Tn=new si(t),dt=yield yi.init(e,ye,h,A,E),Ke=yield Qg.init(e,dt.self,ye,ae,g);if(a.participant&&(f===ss.CF&&(O=new Ev(e,dt.self,ye,a)),O=new Sv(e,dt.self,ye,a)),(o=a.e2ee)!=null&&o.enabled&&a.e2ee.manager.init(l,w),a.chat&&(x=yield Nr.init(e,$,Tn,dt.self,O.participants)),a.internals&&(R=yield du.init()),a.livestream&&E.viewType===qe.Livestream&&K.hasFeature(X.LIVESTREAM)&&(P=new sv(dt.self,Sn)),E.viewType!==qe.Chat&&(a.poll&&(D=yield qg.init(e,dt.self,Oe)),a.recording&&(S=new tv(e,dt.self,ye)),a.stage&&(W=new Xg(e,F,ye,dt.self,O.participants)),a.plugin)){if(!O)throw new C("The plugin module cannot be initialized without the `participant` module");const ms=yield n;H=yield vo.init(e,ms,Hr,$,x==null?void 0:x.chat,dt.self,O.participants)}const ze={storesManager:new hD(e,Hr),pollController:D,selfController:dt,metaController:Ke,chatController:x,stageController:W,pluginController:H,recordingController:S,internalsController:R,livestreamController:P,participantController:O};return{theme:E,permissions:A,controllers:ze}})}static createRoomNodeClient(t,e){return u(this,null,function*(){const{peerId:r,meetingId:n,authToken:i,roomNodeOptions:s}=t.getAllValues(),{sfu:o,roomNodeUrl:a,meetingTitle:d}=s;return kv(t,{socket:e,peerId:r,meetingId:n,authToken:i,roomNodeUrl:a,meetingTitle:d},o)})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:n}=t.getAllValues(),i=["PING"];return new To(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let _o=Zn;Gc([y.trace("Controller.init")],_o,"init",1);Gc([y.trace("setupFlagsmith")],_o,"setupFlagsmith",1);Gc([y.trace("Controller.createSocketServiceAndRoomNodeClient")],_o,"createRoomNodeClient",1);Gc([y.trace("Controller.createSocketService")],_o,"createSocketService",1);var qO=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,zO=(t,e,r,n)=>{for(var i=n>1?void 0:n?KO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&qO(e,r,i),i},Fa,Rl;class Hv extends Ut{constructor(e,r){super(),k(this,Fa,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),k(this,Rl,void 0),T(this,Rl,e),T(this,Fa,r.self)}get supportsConnectedMeetings(){return c(this,Fa).id!==""&&K.hasFeature(X.CONNECTED_MEETINGS)}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return xe.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
32
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield xe.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield xe.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield xe.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(r),yield xe.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield xe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,r,n),i})}moveParticipantsWithCustomPreset(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield xe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(s=>s.id)),i})}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(r===s.id){const o=s.participants.concat(n.map(a=>i.get(a)));return ne(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(a=>!n.includes(a.id));return ne(V({},s),{participants:o})}return s})}}Fa=new WeakMap,Rl=new WeakMap;zO([Pt({maxInvocations:60,period:60})],Hv.prototype,"getConnectedMeetings",1);var YO=Object.defineProperty,QO=Object.getOwnPropertyDescriptor,bu=(t,e,r,n)=>{for(var i=n>1?void 0:n?QO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&YO(e,r,i),i},Fs,Fn,Ud,Vd;const un=(Ud=class{constructor(t,e,r){m(this,"connectedMeetings"),k(this,Fs,void 0),k(this,Fn,void 0),k(this,Vd,void 0),T(this,Vd,t),T(this,Fs,r),this.connectedMeetings=new Hv(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return un.instance||(un.instance=new un(t,e,r)),un.instance.connectedMeetings.supportsConnectedMeetings&&(un.instance.setupEvents(),e.self.once("roomJoined",()=>un.instance.getConnectedMeetings())),un.instance}setCurrentMeeting(t){T(this,Fn,t),xe.currentMeetingId=t.meta.roomName}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){xe.socketService&&(xe.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),xe.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),xe.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),xe.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),xe.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=xe.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
33
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.connectedMeetings.emit("changingMeeting",r),yield c(this,Fn).leave("connected-meeting"),xe.socketService=void 0;const n=yield Wv.init(ne(V({},c(this,Fs)),{cachedUserDetails:null,defaults:ne(V({},c(this,Fs).defaults),{video:c(this,Fn).self.videoEnabled,audio:c(this,Fn).self.audioEnabled}),authToken:e}));n.self.setName(c(this,Fn).self.name);try{yield n.join()}catch(i){y.addLogInCurrentSpan("error","ConnectedMeetingsController.joinRoom",{error:i})}return this.connectedMeetings.emit("meetingChanged",n),this.setCurrentMeeting(n),n})}handleConnectedRoomsDump(t){const e=xe.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return xe.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=xe.handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(n=>{r.set(n.id,n)}),e.forEach(n=>{r.has(n.id)?r.get(n.id).title=n.title:r.set(n.id,ne(V({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=xe.handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id))}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Fs=new WeakMap,Fn=new WeakMap,Vd=new WeakMap,m(Ud,"instance"),Ud);let Jc=un;bu([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Jc.prototype,"getConnectedMeetings",1);bu([y.trace("ConnectedMeetingsController.setupEvents")],Jc.prototype,"setupEvents",1);bu([y.trace("ConnectedMeetingsController.switchMeeting")],Jc.prototype,"switchMeeting",1);class XO{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const om=new XO;function ZO(t,e){try{const{meetingId:r,orgId:n,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://api.${s}`;return{meetingId:r,orgId:n,participantId:i,baseURI:s,apiBase:o}}catch(r){throw l.error("constants::decodeAuthToken",{error:r,debuggingHint:`Unable to decode auth token: ${t}`},!0),new C("Invalid auth token")}}var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,qc=(t,e,r,n)=>{for(var i=n>1?void 0:n?tN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&eN(e,r,i),i},it,ia,sa,Bd,am,cm;let fn=(cm=class{constructor(t,e){k(this,Bd),k(this,it,void 0),k(this,ia,void 0),k(this,sa,void 0),T(this,sa,t),T(this,it,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;z0(),Ee.init();const o=di();om.init();const{authToken:a,baseURI:d}=t,h=ZO(a,d),{meetingId:p}=h,f=Ec(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=fn.setupContext(o,t,p,f);y.meetingMetadata.roomName=p,y.meetingMetadata.userId=f.participantId,y.meetingMetadata.organizationId=f.orgId,y.init(g,(r=(e=t.modules)==null?void 0:e.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:ne(V({},t),{authToken:`${(n=t.authToken)==null?void 0:n.slice(0,10)}...
34
- ${(i=t.authToken)==null?void 0:i.slice(-10)}`})});const E=yield _o.init(g),v=new fn(g,E);return ue(s=v,Bd,am).call(s,t),v})}static setupContext(t,e,r,n){var i;const s=to.createContext(t,e),o=V(V({},G0),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",r),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",J0({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("cachedUserDetails",fr(e.cachedUserDetails)),s.setValue("sdkVersion","2.0.0-staging.50"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,it);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){om.cleanup();const{selfController:e}=c(this,it);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,it).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,it).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,it).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,it).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,it).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,it).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,it).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,ia))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,it).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,it).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,it).stageController)==null?void 0:t.stage}get stores(){return c(this,it).storesManager}get __internals__(){var t;return(t=c(this,it).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},it=new WeakMap,ia=new WeakMap,sa=new WeakMap,Bd=new WeakSet,am=function(t){T(this,ia,Jc.init(c(this,sa),this,t))},cm);qc([ht("0002"),En.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],fn.prototype,"join",1);qc([ht("0003")],fn.prototype,"leave",1);qc([ht("0001"),En.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],fn,"init",1);fn=qc([ht("0000")],fn);const Wv=fn;var rN=Object.defineProperty,nN=(t,e,r)=>e in t?rN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jd=(t,e,r)=>(nN(t,typeof e!="symbol"?e+"":e,r),r),$v={exports:{}},ko={};/*
35
- object-assign
36
- (c) Sindre Sorhus
37
- @license MIT
38
- */var dm=Object.getOwnPropertySymbols,iN=Object.prototype.hasOwnProperty,sN=Object.prototype.propertyIsEnumerable;function oN(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function aN(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}aN();/** @license React v17.0.2
39
- * react-jsx-runtime.production.min.js
40
- *
41
- * Copyright (c) Facebook, Inc. and its affiliates.
42
- *
43
- * This source code is licensed under the MIT license found in the
44
- * LICENSE file in the root directory of this source tree.
45
- */var cN=ny,Gv=60103;ko.Fragment=60107;if(typeof Symbol=="function"&&Symbol.for){var lm=Symbol.for;Gv=lm("react.element"),ko.Fragment=lm("react.fragment")}var dN=cN.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,lN=Object.prototype.hasOwnProperty,uN={key:!0,ref:!0,__self:!0,__source:!0};function Jv(t,e,r){var n,i={},s=null,o=null;r!==void 0&&(s=""+r),e.key!==void 0&&(s=""+e.key),e.ref!==void 0&&(o=e.ref);for(n in e)lN.call(e,n)&&!uN.hasOwnProperty(n)&&(i[n]=e[n]);if(t&&t.defaultProps)for(n in e=t.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$$typeof:Gv,type:t,key:s,ref:o,props:i,_owner:dN.current}}ko.jsx=Jv;ko.jsxs=Jv;$v.exports=ko;const hN=$v.exports.jsx;class pN{constructor(e){jd(this,"meeting"),jd(this,"l"),jd(this,"onUpdate",()=>{this.l.forEach(H=>{H()})});var r,n,i,s,o,a,d,h,p,f,g,E,v,I,A,D,x,W;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(n=this.meeting.meta)==null||n.addListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.addListener("*",this.onUpdate),(o=(s=this.meeting.participants)==null?void 0:s.joined)==null||o.addListener("*",this.onUpdate),(d=(a=this.meeting.participants)==null?void 0:a.active)==null||d.addListener("*",this.onUpdate),(p=(h=this.meeting.participants)==null?void 0:h.waitlisted)==null||p.addListener("*",this.onUpdate),(f=this.meeting.stage)==null||f.addListener("*",this.onUpdate),(g=this.meeting.livestream)==null||g.addListener("*",this.onUpdate),(E=this.meeting.chat)==null||E.addListener("*",this.onUpdate),(v=this.meeting.plugins)==null||v.all.addListener("*",this.onUpdate),(I=this.meeting.recording)==null||I.addListener("*",this.onUpdate),(A=this.meeting.connectedMeetings)==null||A.addListener("*",this.onUpdate),(D=this.meeting.spotlight)==null||D.addListener("*",this.onUpdate),(x=this.meeting.remote)==null||x.addListener("*",this.onUpdate),(W=this.meeting.polls)==null||W.addListener("*",this.onUpdate)}clean(){var e,r,n,i,s,o,a,d,h,p,f,g,E,v,I,A,D,x;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(n=this.meeting.participants)==null||n.removeListener("*",this.onUpdate),(s=(i=this.meeting.participants)==null?void 0:i.joined)==null||s.removeListener("*",this.onUpdate),(a=(o=this.meeting.participants)==null?void 0:o.active)==null||a.removeListener("*",this.onUpdate),(h=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||h.removeListener("*",this.onUpdate),(p=this.meeting.stage)==null||p.removeListener("*",this.onUpdate),(f=this.meeting.livestream)==null||f.removeListener("*",this.onUpdate),(g=this.meeting.chat)==null||g.removeListener("*",this.onUpdate),(E=this.meeting.plugins)==null||E.all.removeListener("*",this.onUpdate),(v=this.meeting.recording)==null||v.removeListener("*",this.onUpdate),(I=this.meeting.connectedMeetings)==null||I.removeListener("*",this.onUpdate),(A=this.meeting.spotlight)==null||A.removeListener("*",this.onUpdate),(D=this.meeting.remote)==null||D.removeListener("*",this.onUpdate),(x=this.meeting.polls)==null||x.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const wu=kt.exports.createContext({meeting:void 0,updates:void 0});function mN({value:t,children:e,fallback:r}){const[n,i]=kt.exports.useState(),s=kt.exports.useRef();return kt.exports.useEffect(()=>(t&&i(new pN(t)),()=>{var o;(o=s.current)==null||o.clean()}),[t]),hN(wu.Provider,{value:{meeting:t,updates:n},children:t?e:r})}const fN=()=>{const{meeting:t}=kt.exports.useContext(wu);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},gN=t=>{const e=kt.exports.useRef(!1),[r,n]=kt.exports.useState(),i=t==null?void 0:t.resetOnLeave,s=async o=>{if(!e.current)return e.current=!0,Wv.init(o).then(a=>(n(a),a)).finally(()=>{e.current=!1})};return kt.exports.useEffect(()=>{if(!r||!i)return()=>{};const o=({state:a})=>{a!=="connected-meeting"&&a!=="disconnected"&&n(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),kt.exports.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=a=>{n(void 0),setTimeout(()=>{n(a)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,s]},vN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),yN=t=>{const{meeting:e,updates:r}=kt.exports.useContext(wu);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const n=kt.exports.useRef(t(e)),[,i]=kt.exports.useReducer(s=>s+1,0);return kt.exports.useEffect(()=>{const s=e&&t(e),o=()=>{const a=e&&t(e);vN(n.current,a)&&(n.current=a,i())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",i),()=>{s.removeListener("*",i)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),n.current},EN=t=>gN(t),SN=mN,TN=fN,_N=yN,kN=()=>TN,bN=t=>_N(t);exports.RealtimeKitProvider=SN;exports.useRTKSelector=bN;exports.useRealtimeKitClient=EN;exports.useRealtimeKitMeeting=kN;
28
+ ${t}`}const Ts={maxInvocations:5,period:1};function Bt(t,e){return function(r,n,i){const s=i.value;let o=0,a=Date.now();return i.value=function(...d){const h=Date.now(),p=e?this[e]:t;if(h-a>p.period*1e3&&(a=h,o=0),o>=p.maxInvocations)throw new b(`Method rate limit ${p.maxInvocations} invocations/${p.period}sec exceeded`,"0013");return o+=1,s.apply(this,d)},i}}var TD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,Et=(t,e,r,n)=>{for(var i=n>1?void 0:n?kD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&TD(e,r,i),i};const _D=["text","image","file","custom","poll"],Za={maxInvocations:180,period:60};var oe,Li,tt,xi,Sa,ol,um,hm;let lt=(hm=class extends Yt{constructor(t,e,r,n,i){super(),T(this,ol),f(this,"messages"),f(this,"channels",[]),T(this,oe,void 0),T(this,Li,void 0),T(this,tt,void 0),T(this,xi,void 0),T(this,Sa,void 0),f(this,"maxTextLimit",2e3),S(this,Sa,t),S(this,tt,e),S(this,xi,r),S(this,oe,n),S(this,Li,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get socketJoined(){return c(this,ol,um).socketJoined===!0}sendMessageInternal(t,e,r){return u(this,arguments,function*(n,i,s,o={}){switch(n.type){case"text":{const a=o.replyTo&&o.replyTo.type==="text"?ED(n.message,o.replyTo.message):n.message;yield this.sendTextMessageInternal(a,i,s);break}case"image":yield this.sendImageMessageInternal(n.image,i,s);break;case"file":yield this.sendFileMessageInternal(n.file,i,s);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(t.length>this.maxTextLimit)throw new b("Max character limit breached","0503");if(e&&e.length>0){if(!((n=c(this,oe).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,oe).permissions)!=null&&i.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new b("Could not send message to private chat.","0501")}else if(!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,oe).permissions)==null?void 0:a.chatPublic)!=null&&d.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new b("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new b("Message can not be empty.","0502");if(r){c(this,tt).sendMessageToChannel(t,Mt.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,oe).id),h=c(this,Li).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,oe).userId)),c(this,tt).sendMessage(t,Mt.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,oe).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,oe).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,oe).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=Ke(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,oe).config.viewType);if(yield h.uploadFile(t,m),r){c(this,tt).sendMessageToChannel(p,Mt.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,oe).id),g=c(this,Li).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,oe).userId)),c(this,tt).sendMessage(p,Mt.IMAGE,e)}catch{throw new b("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,oe).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,oe).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,oe).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=Ke(),{getLocation:p,putLocation:m}=yield h.getPresignedUrls(t.name,c(this,oe).config.viewType);if(yield h.uploadFile(t,m),r){c(this,tt).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),Mt.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,oe).id),g=c(this,Li).joined.toArray().filter(_=>e.includes(_.id)).map(_=>_.userId),g.push(c(this,oe).userId));const v=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,tt).sendMessage(v,Mt.FILE,e)}catch{throw new b("Error sending file message.","0500")}})}get rateLimits(){return Za}updateRateLimits(t,e){Za.maxInvocations=t,Za.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,n,i,s,o,a,d,h,p,m,g,v,_,A,C;if(e&&e.length>0){if(!((r=c(this,oe).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,oe).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,oe).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,oe).permissions)==null?void 0:a.chatPublic)!=null&&d.files)||!((p=(h=c(this,oe).permissions)==null?void 0:h.chatPublic)!=null&&p.text)){l.error("sendCustomMessage::permission_denied");return}const M=J=>u(this,null,function*(){try{if(typeof J=="string")return{link:J};const P=Ke(),{getLocation:G,putLocation:W}=yield P.getPresignedUrls(J.name,c(this,oe).config.viewType);return yield P.uploadFile(J,W),{link:G,type:J.type,name:J.name,size:J.size}}catch{throw new b("Error sending image message.","0500")}}),N=Z(B({},t),{files:yield Promise.all((g=(m=t.files)!=null?m:[])==null?void 0:g.map(J=>u(this,null,function*(){return M(J)}))),images:yield Promise.all((_=(v=t.images)!=null?v:[])==null?void 0:_.map(J=>u(this,null,function*(){return M(J)}))),videos:yield Promise.all((C=(A=t.videos)!=null?A:[])==null?void 0:C.map(J=>u(this,null,function*(){return M(J)})))});c(this,tt).sendMessage(JSON.stringify(N),Mt.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(((i=(n=c(this,oe).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new b("Not permitted to edit messages","0501");if(!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,oe).permissions)==null?void 0:a.chatPublic)!=null&&d.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,tt).editMessage(t,e,Mt.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,oe).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const a=Ke(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,oe).config.viewType);yield a.uploadFile(e,h),c(this,tt).editMessage(t,d,Mt.IMAGE,r)}catch{throw new b("Error editing image message.","0500")}})}editFileMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,oe).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,oe).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const a=Ke(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,oe).config.viewType);yield a.uploadFile(e,h),c(this,tt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Mt.FILE,r)}catch{throw new b("Error editing file message.","0500")}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,n;if(((n=(r=c(this,oe).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new b("Not permitted to delete messages","0501");c(this,tt).deleteMessage(t,e)})}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}pin(t){return u(this,null,function*(){if(!this.socketJoined)throw new b("Can`t pin message without joining room","0505");if(!c(this,oe).permissions.pinParticipant)throw new b("You do not have permission to pin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){c(this,tt).setPinState(e,!0);return}throw new b(`No message found with id: ${t}`,"0504")})}unpin(t){return u(this,null,function*(){if(!this.socketJoined)throw new b("Can`t unpin message without joining room","0505");if(!c(this,oe).permissions.pinParticipant)throw new b("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){c(this,tt).setPinState(e,!1);return}throw new b(`No message found with id: ${t}`,"0504")})}getMessages(t,e,r,n=0,i=void 0){return u(this,null,function*(){const s=yield c(this,tt).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(o=>Yr.formatSocketServiceMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const o=(s=c(this,oe).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new b("Not permitted to create channels","0501");if(i.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new b("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new b("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new b("channel name cannot be empty.","0510");const a=[...new Set([...n,c(this,oe).userId])];return yield c(this,xi).createChannel(r.trim(),a,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var r,n,i,s,o;const a=this.channels.find(p=>p.id===t),d=(r=c(this,oe).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new b("Not permitted to update channels","0501");if(a.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new b("Not permitted to update public channels","0501");if(a.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new b("Not permitted to update private channels","0501")}const h={memberIds:(n=e.memberIds)!=null?n:a.memberIds,displayName:(i=e.displayName)!=null?i:a.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:a.displayPictureUrl,visibility:(o=e.visibility)!=null?o:a.visibility};return c(this,xi).updateChannel(t,h)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,n,i={}){return this.sendMessageInternal(r,null,n,i)})}getChannelMembers(t){return u(this,null,function*(){return c(this,xi).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!Q.hasFeature(ie.FEAT_CHAT_SDK_SEARCH))throw new b("searchMessages is temporarily disabled!","0506");return(yield c(this,tt).searchMessages(e,r)).map(Yr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,tt).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=Z(B({},r),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},oe=new WeakMap,Li=new WeakMap,tt=new WeakMap,xi=new WeakMap,Sa=new WeakMap,ol=new WeakSet,um=function(){return c(this,Sa).getValue("connectionHandler")},hm);Et([y.trace("DyteChat.sendTextMessage"),Bt(Za)],lt.prototype,"sendTextMessage",1);Et([y.trace("DyteChat.sendImageMessage"),Bt({maxInvocations:20,period:60})],lt.prototype,"sendImageMessage",1);Et([y.trace("DyteChat.sendFileMessage"),Bt({maxInvocations:20,period:60})],lt.prototype,"sendFileMessage",1);Et([y.trace("DyteChat.sendMessage"),Bt({maxInvocations:180,period:60})],lt.prototype,"sendMessage",1);Et([y.trace("DyteChat.editTextMessage")],lt.prototype,"editTextMessage",1);Et([y.trace("DyteChat.editImageMessage")],lt.prototype,"editImageMessage",1);Et([y.trace("DyteChat.editFileMessage")],lt.prototype,"editFileMessage",1);Et([y.trace("DyteChat.editMessage")],lt.prototype,"editMessage",1);Et([y.trace("DyteChat.deleteMessage")],lt.prototype,"deleteMessage",1);Et([y.trace("DyteChat.createChannel")],lt.prototype,"createChannel",1);Et([y.trace("DyteChat.updateChannel")],lt.prototype,"updateChannel",1);Et([y.trace("DyteChat.sendMessageToChannel")],lt.prototype,"sendMessageToChannel",1);Et([y.trace("DyteChat.getChannelMembers")],lt.prototype,"getChannelMembers",1);Et([y.trace("DyteChat.searchMessages")],lt.prototype,"searchMessages",1);Et([y.trace("DyteChat.markLastReadMessage")],lt.prototype,"markLastReadMessage",1);lt=Et([St("0500")],lt);var bD=Object.defineProperty,wD=Object.getOwnPropertyDescriptor,ID=(t,e,r,n)=>{for(var i=n>1?void 0:n?wD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&bD(e,r,i),i},al,pm;const ti=(pm=class{constructor(t,e,r,n,i){f(this,"chat"),f(this,"chatSocketHandler"),f(this,"chatChannelSocketHandler"),f(this,"self"),T(this,al,void 0),S(this,al,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new lt(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new ti(t,e,r,n,i)})}static formatMessage(t){return Z(B({},t),{time:new Date(t.time),type:_D[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,r={displayName:t.displayName,id:t.chatId,time:e,timeMs:t.createdAtMs,type:t.payloadType,isEdited:t.isEdited,userId:t.userId,targetUserIds:t.targetUserIds,channelId:t.channelId,channelIndex:t.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:t.pinned};switch(r.type){case Mt.TEXT:{r.message=t.payload;break}case Mt.IMAGE:{r.link=t.payload;break}case Mt.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case Mt.CUSTOM:{const{html:n,images:i,message:s,videos:o,files:a}=JSON.parse(t.payload);r.message=s,r.html=n,r.images=i,r.videos=o,r.files=a;break}}return ti.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||Q.hasFeature(ie.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=Pv.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>ti.formatSocketServiceMessage(r))})}setupEvents(){I.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Ue.sendMessageToRoom,t=>{const e=ti.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(n=>n.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ue.sendMessageToPeers,t=>{const e=ti.formatSocketServiceMessage(t.message);this.chat.messages=[...this.chat.messages,e],this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ue.editMessage,t=>{const e=ti.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(n=>n.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Ue.deleteMessage,t=>{if(t.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:t.chatId,channelId:t.channelId},messages:this.chat.messages});return}const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(pi.createChatChannel,t=>{const[e]=t.chatChannels,r=Ei.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(Ue.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(pi.updateChatChannel,t=>{const[e]=t.chatChannels,r=Ei.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},al=new WeakMap,pm);let Yr=ti;ID([y.trace("ChatController.setupEvents")],Yr.prototype,"setupEvents",1);var CD=Object.defineProperty,PD=Object.getOwnPropertyDescriptor,RD=(t,e,r,n)=>{for(var i=n>1?void 0:n?PD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&CD(e,r,i),i},cl,mm,$s,Js,Ea,fm;let Ql=(fm=class extends Yt{constructor(t,e,r){super(),T(this,cl),f(this,"items"),T(this,$s,void 0),T(this,Js,void 0),T(this,Ea,void 0),S(this,Ea,t),S(this,$s,e),S(this,Js,r),this.items=[]}get socketJoined(){var t;return((t=c(this,cl,mm))==null?void 0:t.socketJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(!this.socketJoined)throw new b("Can't create polls without joining room","0705");if(!c(this,$s).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield c(this,Js).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,$s).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,Js).votePoll(t,e)})}},cl=new WeakSet,mm=function(){return c(this,Ea).getValue("connectionHandler")},$s=new WeakMap,Js=new WeakMap,Ea=new WeakMap,fm);Ql=RD([St("0700")],Ql);var AD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,DD=(t,e,r,n)=>{for(var i=n>1?void 0:n?MD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&AD(e,r,i),i},Gs,Ui,gm;const Ki=(gm=class{constructor(t,e,r){f(this,"polls"),T(this,Gs,void 0),T(this,Ui,void 0),this.polls=new Ql(t,e,r),S(this,Gs,e),S(this,Ui,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Ki(t,e,r)})}canViewPolls(){return c(this,Gs).permissions.polls.canView}setupEvents(){const t={[Jr.createPoll]:n=>{n.poll&&this.updatePoll(Ki.formatSocketServicePoll(n.poll))},[Jr.updatePoll]:n=>{n.poll&&this.updatePoll(Ki.formatSocketServicePoll(n.poll))},[Jr.votePoll]:n=>{n.poll&&this.updatePoll(Ki.formatSocketServicePoll(n.poll))}},e=()=>{I.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Ui).on(n,t[n])})},r=()=>{I.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{c(this,Ui).removeListeners(n)})};c(this,Gs).permissions.on("permissionsUpdate",n=>u(this,null,function*(){var i;(i=n==null?void 0:n.polls)!=null&&i.canView?(yield this.getPolls(),e()):(this.polls.items=[],r())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==JSON.stringify(t)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,t],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}getPolls(){return u(this,null,function*(){const t=yield c(this,Ui).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=$M.fromBinary(t.payload);this.polls.items=e.map(r=>Ki.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(n=>({id:n.userId,name:n.name}))}));return{anonymous:t.anonymous,createdBy:t.createdBy,createdByUserId:t.createdByUserId,hideVotes:t.hideVotes,id:t.pollId,options:e,question:t.question,voted:t.votes}}},Gs=new WeakMap,Ui=new WeakMap,gm);let Ov=Ki;DD([y.trace("PollController.setupEvents")],Ov.prototype,"setupEvents",1);var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,LD=(t,e,r,n)=>{for(var i=n>1?void 0:n?ND(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&OD(e,r,i),i},Nv=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Nv||{}),qs,dl,vm,Ta,ll,Fi,ka,ym;let Xl=(ym=class extends Yt{constructor(t,e,r,n,i){super(),T(this,dl),T(this,Ta),f(this,"selfActiveTab"),f(this,"broadcastTabChanges"),T(this,qs,void 0),T(this,Fi,void 0),T(this,ka,void 0),f(this,"viewType"),f(this,"meetingStartedTimestamp"),f(this,"meetingTitle"),f(this,"sessionId"),S(this,qs,t),S(this,Fi,e),this.viewType=r,S(this,ka,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return c(this,Ta,ll).socketState}get mediaState(){return c(this,Ta,ll).mediaState}get meetingId(){var t;return(t=c(this,dl,vm))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,Fi).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new b("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,Fi).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,ka).broadcastMessage("spotlight",{userId:c(this,Fi).userId,currentTab:this.selfActiveTab})}},qs=new WeakMap,dl=new WeakSet,vm=function(){return c(this,qs).getValue("roomNodeClient")},Ta=new WeakSet,ll=function(){return c(this,qs).getValue("connectionHandler")},Fi=new WeakMap,ka=new WeakMap,ym);Xl=LD([St("0800")],Xl);function xD(t){let e="",r=[""];const n=[r];let i=0,s=0,o=!0,a;for(a of t)a==='"'?(o&&a===e&&(r[i]+=a),o=!o):a===","&&o?a=r[++i]="":a===`
29
+ `&&o?(e==="\r"&&(r[i]=r[i].slice(0,-1)),r=n[++s]=[a=""],i=0):r[i]+=a,e=a;return n}var UD=Object.defineProperty,FD=Object.getOwnPropertyDescriptor,Lv=(t,e,r,n)=>{for(var i=n>1?void 0:n?FD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&UD(e,r,i),i};let Ln=class extends Yt{constructor(){super(),f(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new Ln;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,s,o,a]]=xD(t);return{id:bi(),name:o,peerId:n,userId:i,customParticipantId:s,transcript:a,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(`
30
+ `).map(e=>Ln.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=Ke(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Ln.parseTranscripts(e)}catch{}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const n=r.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};Lv([y.trace("DyteAi.getActiveTranscript")],Ln.prototype,"getActiveTranscript",1);Ln=Lv([St("0000")],Ln);var VD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,jD=(t,e,r,n)=>{for(var i=n>1?void 0:n?BD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&VD(e,r,i),i},$n,zs,ul,Sm;const xv=(Sm=class{constructor(t,e,r,n,i,s){f(this,"meta"),f(this,"ai"),T(this,$n,void 0),T(this,zs,void 0),f(this,"aiSocketHandler"),T(this,ul,void 0),S(this,ul,t),this.meta=new Xl(t,e,e.config.viewType,r,s),this.ai=n,S(this,$n,e),S(this,zs,r),this.aiSocketHandler=i,e.config.viewType!==vt.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield Ln.init(e.permissions.transcriptionEnabled);return new xv(t,e,r,s,n,i)})}conditionallySetActiveTab(t){var e;t!=null&&t.currentTab&&((e=this.meta.selfActiveTab)==null?void 0:e.id)!==t.currentTab.id&&(this.meta.setSelfActiveTab(t.currentTab,Nv.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){I.on(w.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),I.on(w.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),I.on(w.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),I.on(w.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,$n).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,zs).broadcastMessage("spotlight",{userId:c(this,$n).userId,currentTab:this.meta.selfActiveTab})),I.on(w.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,$n).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,zs).broadcastToPeers("spotlight",[t.id],{userId:c(this,$n).userId,currentTab:this.meta.selfActiveTab})})),I.on(w.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=B(B({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),I.on(w.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=B(B({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:r,isPartial:n}=t,i=Ln.parseTranscript(r,n);if(!i){l.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:o,transcript:a}=i;l.debug(`${e} Received transcript for peer ${s} - ${o}: ${a}`)})}},$n=new WeakMap,zs=new WeakMap,ul=new WeakMap,Sm);let Uv=xv;jD([y.trace("MetaController.setupEvents")],Uv.prototype,"setupEvents",1);var HD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Mi=(t,e,r,n)=>{for(var i=n>1?void 0:n?WD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&HD(e,r,i),i},ur,ko,Me,ec,Vr,Hr,_o,tc;class Bn extends Yt{constructor(e,r,n,i,s){super(),T(this,_o),T(this,ur,void 0),T(this,ko,void 0),T(this,Me,void 0),T(this,ec,void 0),T(this,Vr,void 0),T(this,Hr,void 0),S(this,Hr,e),S(this,ur,i),S(this,ko,s),S(this,Me,r),S(this,ec,n),S(this,Vr,[]),this.setupEvents()}get status(){return c(this,Hr).getValue("stageStatus")}setupEvents(){const e={[w.GET_STAGE_REQUESTS]:i=>u(this,null,function*(){S(this,Vr,i)}),[w.UPDATE_STAGE_REQUESTS]:i=>u(this,[i],function*({add:s}){const o=c(this,Vr).length,{stageRequests:a}=this.getAccessRequests();(s||a.length>o)&&this.emit("newStageRequest",{count:a.length}),this.emit("stageAccessRequestUpdate",a)})},r=()=>{Object.entries(e).forEach(([i,s])=>{I.onAsync(i,s)})},n=()=>{Object.entries(e).forEach(([i,s])=>{I.removeListener(i,s)})};c(this,Me).permissions.on("permissionsUpdate",i=>{const{canAcceptProductionRequests:s}=i;s!==void 0&&(c(this,Me).permissions.acceptStageRequests?(r(),c(this,ur).getStageRequests()):(n(),S(this,Vr,[]),this.emit("stageAccessRequestUpdate",c(this,Vr))))}),c(this,Me).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(!c(this,Me).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new b("You do not have permission to perform this action","2001");const e=c(this,ec).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return S(this,Vr,e),{stageRequests:c(this,Vr)}}requestAccess(){return u(this,null,function*(){if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new b(`Unable to request access you are currently ${this.status}`,"2006");if(c(this,Me).permissions.stageAccess===K.Allowed){Ye(this,_o,tc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,ur).requestAccess(),Ye(this,_o,tc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");c(this,ur).cancelRequestAccess(),Ye(this,_o,tc).call(this,"OFF_STAGE")})}grantAccess(e){if(!c(this,Me).roomJoined)throw new b("Can`t grant for participant without joining room");if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(!c(this,Me).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new b("You do not have permission to perform this action","2001");return c(this,ur).grantAccess(e)}denyAccess(e){if(!c(this,Me).roomJoined)throw new b("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(!c(this,Me).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new b("You do not have permission to perform this action","2001");return c(this,ur).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,Hr).getValue("viewType");if(this.status==="ON_STAGE")throw new b("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,Me).permissions.stageAccess===K.NotAllowed)throw new b(`Unable to join stage you are currently ${this.status}`,"2006");if(yield c(this,ur).joinStage(),e===vt.Livestream?yield c(this,ko).joinRoom(c(this,Me),e):I.emit(w.RESET_PRODUCER_STATE),c(this,Hr).setValue("stageStatus","ON_STAGE"),e===vt.Livestream){const{peers:r}=yield c(this,ko).getStagePeers();I.emit(w.SOCKET_PEERS,r),I.emit(w.JOIN_MEDIA_ROOM,r)}})}leave(){return u(this,null,function*(){if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new b(`Unable to leave stage you are currently ${this.status}`,"2006");c(this,Me).setIsPinned(!1),yield c(this,ur).leaveStage(c(this,Me).userId),c(this,Hr).setValue("stageStatus","OFF_STAGE",!1),yield I.emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,Hr).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!c(this,Me).roomJoined)throw new b("Can`t kick participant without joining room","2005");if(!c(this,Me).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new b("Stage is disabled","2003");if(!c(this,Me).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new b("You do not have permissions for kick","2001");return c(this,ur).kick(e)})}}ur=new WeakMap,ko=new WeakMap,Me=new WeakMap,ec=new WeakMap,Vr=new WeakMap,Hr=new WeakMap,_o=new WeakSet,tc=function(t){return u(this,null,function*(){this.status!==t&&c(this,Hr).setValue("stageStatus",t)})};Mi([y.trace("DyteStage.getStageRequests")],Bn.prototype,"getAccessRequests",1);Mi([y.trace("DyteStage.requestAccess")],Bn.prototype,"requestAccess",1);Mi([y.trace("DyteStage.cancelRequestAccess")],Bn.prototype,"cancelRequestAccess",1);Mi([y.trace("DyteStage.grantAccess")],Bn.prototype,"grantAccess",1);Mi([y.trace("DyteStage.denyAccess")],Bn.prototype,"denyAccess",1);Mi([y.trace("DyteStage.joinStage")],Bn.prototype,"join",1);Mi([y.trace("DyteStage.leaveStage")],Bn.prototype,"leave",1);function $D(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Ku(t){switch(t){case zr.UNSPECIFIED:return"OFF_STAGE";case zr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case zr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case zr.OFF_STAGE:return"OFF_STAGE";case zr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var JD=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,qD=(t,e,r,n)=>{for(var i=n>1?void 0:n?GD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JD(e,r,i),i},ri,Yi,ni,rc,wn;class Fv{constructor(e,r,n,i,s){f(this,"stage"),T(this,ri,void 0),T(this,Yi,void 0),T(this,ni,void 0),T(this,rc,0),T(this,wn,void 0),S(this,wn,e),this.stage=new Bn(e,i,s,r,n),S(this,ni,r),S(this,ri,i),S(this,Yi,s),this.setupEvents()}setupEvents(){c(this,wn).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,ni).on(j.grantStageAccess,()=>{c(this,ri).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,ni).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,ri).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,ni).on(j.denyStageAccess,()=>{c(this,ri).permissions.stageAccess!==K.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,ni).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,ri).permissions.stageAccess!==K.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield I.emitAsync(w.GET_STAGE_REQUESTS,n),c(this,rc)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),S(this,rc,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Yi).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&c(this,wn).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=Ku(e.stageType),n=c(this,wn).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,wn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:c(this,wn).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Yi).joined.get(e.peerId),n=c(this,Yi).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&I.emit(w.UPDATE_ACTIVE);break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),n&&I.emit(w.UPDATE_ACTIVE);break}I.emit(w.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}ri=new WeakMap,Yi=new WeakMap,ni=new WeakMap,rc=new WeakMap,wn=new WeakMap;qD([y.trace("DyteStage.setupEvents")],Fv.prototype,"setupEvents",1);var zD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,yd=(t,e,r,n)=>{for(var i=n>1?void 0:n?KD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zD(e,r,i),i};const He={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var kt,Zt,Ks,Ys,an,Qs,Xs,Vi,Zs,Em;let ms=(Em=class extends Ss{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:s,organizationId:o,picture:a,private:d,published:h,staggered:p,tags:m,type:g,updatedAt:v},_,A,C,M){super(),T(this,Vi),T(this,kt,void 0),f(this,"baseURL"),f(this,"createdAt"),f(this,"description"),f(this,"id"),f(this,"name"),T(this,Zt,void 0),T(this,Ks,void 0),T(this,Ys,void 0),f(this,"organizationId"),f(this,"picture"),f(this,"private"),f(this,"published"),f(this,"staggered"),f(this,"tags"),f(this,"type"),f(this,"updatedAt"),T(this,an,void 0),f(this,"config"),T(this,Qs,void 0),f(this,"active"),f(this,"iframes"),f(this,"enabledBy"),T(this,Xs,void 0),S(this,Xs,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,S(this,Zt,A),this.organizationId=o,this.picture=a,this.private=d,this.published=h,this.staggered=p,this.tags=m,this.type=g,this.updatedAt=new Date(v),this.active=!1,this.iframes=new Map,S(this,kt,_),S(this,Ks,C),S(this,Ys,M),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:n,uuid:i,type:s}=r;switch(s){case z.customPluginEventToRoom:{c(this,kt).customPluginEventToRoom(this.id,n,i);break}case z.customPluginEventToPeers:{c(this,kt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case z.enablePluginForRoom:{c(this,kt).enablePluginForRoom(this.id,i);break}case z.enablePluginForPeers:{c(this,kt).enablePluginForPeers(this.id,n.peerIds,i);break}case z.disablePluginForRoom:{c(this,kt).disablePluginForRoom(this.id,i);break}case z.disablePluginForPeers:{c(this,kt).disablePluginForPeers(this.id,n.peerIds,i);break}case z.storeInsertKeys:{c(this,kt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case z.storeGetKeys:{c(this,kt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case z.storeDeleteKeys:{c(this,kt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case z.storeDelete:{c(this,kt).storeDelete(this.id,n.store,i);break}case He.chatMessage:{const{messagePayload:o,peerIds:a}=n;if(!c(this,Ys)){this.sendIframeEvent({type:He.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,Ys).sendMessage(o,a),this.sendIframeEvent({type:He.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:He.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case He.getPeer:{let o;const{peerId:a}=n,d=Z(B({},c(this,Zt)),{id:c(this,Zt).id,isRecorder:(e=c(this,Zt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Zt).permissions.hiddenParticipant,stageStatus:c(this,Zt).stageStatus});a?(o=c(this,Ks).joined.get(n.peerId),c(this,Zt).id===a&&(o=d)):o=d,this.sendIframeEvent({type:He.getPeer,payload:{peer:o&&Hc(o)},uuid:r.uuid});break}case He.getPeers:{const o=c(this,Ks).joined.toArray().map(a=>Hc(a));this.sendIframeEvent({type:He.getPeers,payload:{peers:o},uuid:r.uuid});break}case He.getPluginInitiator:{this.sendIframeEvent({type:He.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case He.getDisplayTitle:{this.sendIframeEvent({type:He.getDisplayTitle,payload:{displayTitle:c(this,Vi,Zs).meetingTitle},uuid:r.uuid});break}case He.getRoomName:{this.sendIframeEvent({type:He.getRoomName,payload:{roomName:c(this,Vi,Zs).roomName},uuid:r.uuid});break}case He.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:He.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:n}=(e=this.iframes.get(t))!=null?e:{};(r||n)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!c(this,Qs))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new b("No auth token set for plugin.","0602");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new b("Iframe was not provided.","0603");this.removePluginView(e);const n=t,i=new URL(this.baseURL),s={auth:c(this,Qs),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,Xs).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Vi,Zs).roomName)!=null?r:"",displayTitle:c(this,Vi,Zs).meetingTitle};if(Object.keys(s).forEach(o=>{i.searchParams.set(o,s[o])}),n.src=i.href,n.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",n.title=e,navigator.isReactNative)n.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:n});else{const o=a=>u(this,null,function*(){a.source===t.contentWindow&&(yield this.handleIframeMessage(a.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:n,listener:o})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=Ke(),e=yield t.authorizePlugin(this.id);S(this,Qs,e),S(this,an,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),S(this,an,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=c(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,kt).addPlugin(this.id,this.staggered),S(this,an,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=c(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Zt).id||(c(this,kt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,an)?new Date().getTime()-c(this,an).getTime():0}}),S(this,an,void 0)))})}},kt=new WeakMap,Zt=new WeakMap,Ks=new WeakMap,Ys=new WeakMap,an=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,Vi=new WeakSet,Zs=function(){return c(this,Xs).getValue("roomNodeClient")},Em);yd([Bt({maxInvocations:5,period:1})],ms.prototype,"sendData",1);yd([y.trace("DytePlugin.activatePlugin")],ms.prototype,"activate",1);yd([y.trace("DytePlugin.deactivatePlugin")],ms.prototype,"deactivate",1);ms=yd([St("0600")],ms);var Xe,Qi;class Vv extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),T(this,Xe,void 0),T(this,Qi,void 0),f(this,"onAddEvent"),f(this,"onDeleteEvent"),f(this,"onClearEvent"),S(this,Xe,new Ss),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,S(this,Qi,new Map)}emit(e,...r){return c(this,Xe).emit(e,...r)}on(e,r){return c(this,Xe).on(e,r)}addListener(e,r){return c(this,Xe).addListener(e,r)}off(e,r){return c(this,Xe).off(e,r)}once(e,r){return c(this,Xe).once(e,r)}prependListener(e,r){return c(this,Xe).prependListener(e,r)}prependOnceListener(e,r){return c(this,Xe).prependOnceListener(e,r)}removeListener(e,r){return c(this,Xe).removeListener(e,r)}removeAllListeners(e){return c(this,Xe).removeAllListeners(e)}listeners(e){return c(this,Xe).listeners(e)}listenerCount(e){return c(this,Xe).listenerCount(e)}getMaxListeners(){return c(this,Xe).getMaxListeners()}setMaxListeners(e){return c(this,Xe).setMaxListeners(e)}eventNames(){return c(this,Xe).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),s=(o,...a)=>{this.emit(o,r,...a)};return c(this,Qi).set(e,s),r.on("*",s),n&&c(this,Xe).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,Qi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,Xe).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,Qi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,Xe).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}Xe=new WeakMap,Qi=new WeakMap;class Tm extends Vv{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,XD=(t,e,r,n)=>{for(var i=n>1?void 0:n?QD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&YD(e,r,i),i};let Zl=class{constructor(){f(this,"all"),f(this,"active"),this.all=new Tm,this.active=new Tm}};Zl=XD([St("0600")],Zl);var ZD=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,Sd=(t,e,r,n)=>{for(var i=n>1?void 0:n?e1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&ZD(e,r,i),i},sr,eo,_a,km;const Bv=(km=class{constructor(t,e,r,n){f(this,"plugins"),T(this,sr,void 0),T(this,eo,void 0),T(this,_a,void 0),S(this,sr,e),S(this,eo,r),S(this,_a,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,o){return u(this,null,function*(){const a=new Zl;return e.forEach(d=>{const h=new ms(t,d,r,s,o,i);a.all.add(h)}),new Bv(t,r,n,a)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield c(this,sr).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(r=>{this.disablePlugin({id:r.id})}),yield Promise.all(e.map(r=>this.enablePlugin({id:r.pluginId,enabledBy:r.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,n){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:r,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),I.onAsync(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,sr).on(z.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),c(this,sr).on(z.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[z.enablePluginForPeers,z.enablePluginForRoom].forEach(t=>{c(this,sr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[z.disablePluginForPeers,z.disablePluginForRoom].forEach(t=>{c(this,sr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[z.customPluginEventToPeers,z.customPluginEventToRoom].forEach(t=>{c(this,sr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{c(this,sr).on(t,(e,r)=>u(this,null,function*(){var n;const i=(n=e.storeItems)==null?void 0:n.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:i})}))}),c(this,sr).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,eo).on(Ue.sendMessageToPeers,t=>{const e=Yr==null?void 0:Yr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(He.chatMessage,{message:e})}),c(this,eo).on(Ue.sendMessageToRoom,t=>{const e=Yr==null?void 0:Yr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(He.chatMessage,{message:e})}),I.on(w.PEER_JOINED_INTERNAL,t=>{const e=Hc(t);this.broadcastIframeEvent(He.peerJoined,e)}),I.on(w.PEER_CLOSED,t=>{this.broadcastIframeEvent(He.peerLeft,t)}),I.on(w.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(He.peerStageStatusUpdate,t)}),c(this,_a).subscribe("stageStatus",t=>{this.broadcastIframeEvent(He.stageStatusUpdate,t)})}},sr=new WeakMap,eo=new WeakMap,_a=new WeakMap,km);let ra=Bv;Sd([y.trace("PluginController.getRoomPlugins")],ra.prototype,"getRoomPlugins",1);Sd([y.trace("PluginController.enableForSelf")],ra.prototype,"enablePlugin",1);Sd([y.trace("PluginController.disableForSelf")],ra.prototype,"disablePlugin",1);Sd([y.trace("PluginController.setupEvents")],ra.prototype,"setupEvents",1);class t1{constructor(){f(this,"mediaJoined"),f(this,"socketJoined"),f(this,"socketJoinAttempted"),f(this,"mediaJoinAttempted"),f(this,"socketState"),f(this,"mediaState"),this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,r){let n;const{reconnected:i}=this.socketState;switch(e){case"connected":n={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":n={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":n={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":n={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":n={state:"reconnecting",reconnected:i,reconnectionAttempt:r};break;case"failed":n={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}n&&(I.emit(w.SOCKET_STATE_UPDATE,n),this.socketState=n)}}var r1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,na=(t,e,r,n)=>{for(var i=n>1?void 0:n?n1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&r1(e,r,i),i},to,ba,ro,wa,_m;let Ti=(_m=class extends Yt{constructor(t,e){super(),T(this,ro),T(this,to,void 0),T(this,ba,void 0),f(this,"recordingPeerIds",[]),f(this,"recordings",[]),S(this,ba,t),S(this,to,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!c(this,to).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new b("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new b(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=Ke(),{recording:r={}}=c(this,ba).getValue("defaults"),n=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING",type:"BROWSER"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new b("Error while starting recording","1000")}})}stop(t){return u(this,null,function*(){yield Ye(this,ro,wa).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield Ye(this,ro,wa).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield Ye(this,ro,wa).call(this,"resume",["PAUSED"],t)})}},to=new WeakMap,ba=new WeakMap,ro=new WeakSet,wa=function(t,e,r){return u(this,null,function*(){if(!c(this,to).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new b("User does not have permission to stop recording","1001");let n=[];if(r!==void 0){const i=this.recordings.find(s=>s.id===r);if(i===void 0)throw new b("Could not find the specified recording","1004");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield Ke().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new b("Error while stopping recording","1000")}}))})},_m);na([y.trace("DyteRecording.start")],Ti.prototype,"start",1);na([y.trace("DyteRecording.stop")],Ti.prototype,"stop",1);na([y.trace("DyteRecording.stop")],Ti.prototype,"pause",1);na([y.trace("DyteRecording.stop")],Ti.prototype,"resume",1);Ti=na([St("1000")],Ti);var i1=Object.defineProperty,s1=Object.getOwnPropertyDescriptor,o1=(t,e,r,n)=>{for(var i=n>1?void 0:n?s1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&i1(e,r,i),i},eu;class jv{constructor(e,r,n){f(this,"recording"),f(this,"room"),T(this,eu,void 0),S(this,eu,e),this.recording=new Ti(e,r),this.room=n,this.setupEvents()}getRecordingTypeFromProtoType(e){let r;switch(e){case vi.BROWSER:r="BROWSER";break;case vi.COMPOSITE:r="COMPOSITE";break;case vi.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){I.on(w.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>{const n=this.getRecordingTypeFromProtoType(r.recordingType);return{id:r.recordingId,state:r.recordingStatus,type:n}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let r=!1;const n=[...this.recording.recordings];if(n.forEach(i=>{i.id===e.recordingId&&(r=!0,i.state="RECORDING")}),r===!1){const i=this.getRecordingTypeFromProtoType(e.recordingType);n.push({id:e.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(n)}),this.room.on(j.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(j.recordingStopped,e=>{const r=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(r)})}}eu=new WeakMap;o1([y.trace("RecordingController.setupEvents")],jv.prototype,"setupEvents",1);class a1{static hasFeature(e){var r;return(r=Q.hasFeature(e))!=null?r:!1}static getFeatureValue(e){return Q.getValue(e)}static getAllFeatures(){return Q.getAllFlags()}}class Yu{constructor(e,r,n){f(this,"logger"),f(this,"features"),f(this,"browserSpecs"),f(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Te,this.callStats=n}static init(e){return new Yu(l,a1,e)}}class Qu{constructor(e){f(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=Yu.init($);return new Qu(e)})}}var c1=Object.defineProperty,d1=Object.getOwnPropertyDescriptor,Qt=(t,e,r,n)=>{for(var i=n>1?void 0:n?d1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&c1(e,r,i),i},ot,at,je,Br,hr,nc,tu;class jt extends Ss{constructor(e,r,n=ru,i=!0){super(),T(this,ot,void 0),T(this,at,void 0),T(this,je,void 0),T(this,Br,void 0),T(this,hr,void 0),T(this,nc,void 0),T(this,tu,void 0),f(this,"audioUpdateInProgress"),f(this,"videoUpdateInProgress"),S(this,tu,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,S(this,ot,new Hv(e,r)),S(this,at,new A1(c(this,ot),void 0,n)),S(this,je,new U1(c(this,ot),void 0,n)),S(this,hr,new N1(c(this,ot))),S(this,Br,new D1(c(this,ot))),S(this,nc,i),c(this,at).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,at).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,je).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,je).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,hr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return u(this,null,function*(){$.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?$.browserBackgrounded():($.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:n}){var i;r?$.audioOn():$.audioOff(),n?$.videoOn():$.videoOff();let s,o;if(r&&n)try{const a=yield c(this,ot).getAudioAndVideoTrack();s=a.audioTrack,o=a.videoTrack}catch(a){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:a})}if(!s&&r)try{s=yield c(this,ot).getAudioTrack(!1)}catch(a){l.error("LocalMediaHandler::init::Failed to get audio track",{error:a})}if(!o&&n)try{o=yield c(this,ot).getVideoTrack()}catch(a){l.error("LocalMediaHandler::init::Failed to get video track",{error:a})}r&&!s&&$.audioOff(),n&&!o&&$.videoOff(),yield c(this,at).setMediaTrack(s),yield c(this,je).setMediaTrack(o);try{yield c(this,Br).setupSpeaker()}catch{}if(o){const a=yield this.getDeviceById(o.getSettings().deviceId);$.selectedDevice("VIDEO",a)}if(s){const a=yield this.getDeviceById(s.getSettings().deviceId);$.selectedDevice("AUDIO",a)}(i=c(this,Br).currentDevice)!=null&&i.deviceId&&$.selectedDevice("SPEAKER",c(this,Br).currentDevice),c(this,ot).onDeviceChange((a,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,at).currentDevice,video:c(this,je).currentDevice,speaker:c(this,Br).currentDevice}}get permissions(){return c(this,ot).permissions}getAllDevices(){return c(this,ot).getAvailableDevices()}getDeviceById(e,r){return c(this,ot).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,at).mediaTrack}get audioTrack(){return c(this,at).transformedMediaTrack}get audioEnabled(){return c(this,at).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,at).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,at).muteTrack()}getAudioDevices(e){return c(this,ot).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,at).setDevice(e),e!=null&&e.deviceId&&$.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return c(this,Br).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Br).setupSpeaker(e),e!=null&&e.deviceId&&$.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,je).mediaTrack}get videoTrack(){return c(this,je).transformedMediaTrack}get videoEnabled(){return c(this,je).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,je).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,je).disableTrack()}getVideoDevices(e){return c(this,ot).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,je).setDevice(e),e!=null&&e.deviceId&&$.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield c(this,je).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,hr).audioMediaTrack,video:c(this,hr).videoMediaTrack}}get screenShareEnabled(){return c(this,hr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,hr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,hr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,hr).updateConstraints(e)})}getSpeakerDevices(e){return c(this,ot).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,at).addMiddleware(e)}removeAudioMiddleware(e){return c(this,at).removeMiddleware(e)}removeAllAudioMiddlewares(){return c(this,at).removeAllMiddlewares()}addVideoMiddleware(e){return c(this,je).addMiddleware(e)}removeVideoMiddleware(e){return c(this,je).removeMiddleware(e)}removeAllVideoMiddlewares(){return c(this,je).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return c(this,je).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,at).disableTrack(),c(this,je).disableTrack(),c(this,je).terminateMiddlewareWebWorker(),c(this,hr).disableScreenShare(),c(this,ot).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,nc))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!ru(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const a=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);a&&(yield this.setSpeakerDevice(a))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){c(this,at).disableTrack()}removeVideoTrack(){c(this,je).disableTrack(),c(this,je).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}ot=new WeakMap,at=new WeakMap,je=new WeakMap,Br=new WeakMap,hr=new WeakMap,nc=new WeakMap,tu=new WeakMap;Qt([y.trace("MediaHandler.setupStreams")],jt.prototype,"setupStreams",1);Qt([y.trace("MediaHandler.enableAudio")],jt.prototype,"enableAudio",1);Qt([y.trace("MediaHandler.disableAudio")],jt.prototype,"disableAudio",1);Qt([y.trace("MediaHandler.setAudioDevice")],jt.prototype,"setAudioDevice",1);Qt([y.trace("MediaHandler.enableVideo")],jt.prototype,"enableVideo",1);Qt([y.trace("MediaHandler.disableVideo")],jt.prototype,"disableVideo",1);Qt([y.trace("MediaHandler.setVideoDevice")],jt.prototype,"setVideoDevice",1);Qt([y.trace("MediaHandler.updateVideoConstraints")],jt.prototype,"updateVideoConstraints",1);Qt([y.trace("MediaHandler.enableScreenShare")],jt.prototype,"enableScreenShare",1);Qt([y.trace("MediaHandler.disableScreenShare")],jt.prototype,"disableScreenShare",1);Qt([y.trace("MediaHandler.updateScreenshareConstraints")],jt.prototype,"updateScreenshareConstraints",1);Qt([y.trace("MediaHandler.destruct")],jt.prototype,"destruct",1);Qt([y.trace("MediaHandler.onDeviceChange")],jt.prototype,"onDeviceChange",1);function Ia(t,e,r){switch(!0){case Te.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Te.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Te.isFirefox():switch(e){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const l1=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function ru(t){var e,r;const n=(e=t.label)==null?void 0:e.toLowerCase();return((r=Te._bowser)==null?void 0:r.getOSName())==="macOS"&&n.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):l1.some(i=>n==null?void 0:n.includes(i))}function u1(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const r=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(o=>o(r))),i=r.createMediaStreamSource(new MediaStream([e])),s=r.createMediaStreamDestination();try{let o=i;for(let a=0;a<n.length;a+=1)o.connect(n[a]),o=n[a];o.connect(s)}catch(o){return l.error("getTransformedAudioTrack::middleware_execution_failed",{error:o}),e}return s.stream.getAudioTracks()[0]})}var Xi;class h1{constructor(){T(this,Xi,void 0)}terminateMiddlewareWebWorker(){if(c(this,Xi))try{Ef(c(this,Xi)),S(this,Xi,void 0)}catch{l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,n){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:i,WorkerTimers:US})));if(n.disablePerFrameCanvasRendering)return i.captureStream().getVideoTracks()[0];const o=document.createElement("video"),a=new MediaStream;a.addTrack(r);const d=i.getContext("2d");o.srcObject=a,o.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](i,d))}catch(p){l.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch{}return o.addEventListener("play",()=>{i.width=o.width||r.getSettings().width,i.height=o.width||r.getSettings().height,S(this,Xi,Tf(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}Xi=new WeakMap;const bm={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},wm={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]},p1={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},Im={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]};var ne=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(ne||{});const m1=Ab(),Bi=fr(m1.config.media);function f1(t){var e,r;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),n.video=t.video.quality,n}var Zi,nu;class g1{constructor(e,r){T(this,Zi,void 0),T(this,nu,void 0),f(this,"getScreenShareConstraints",()=>{var n,i,s,o,a,d,h,p,m;const g=(n=c(this,Zi))==null?void 0:n.screenshare,v=(s=(i=g==null?void 0:g.width)==null?void 0:i.max)!=null?s:1920,_=(a=(o=g==null?void 0:g.height)==null?void 0:o.max)!=null?a:1080,A=(h=(d=g==null?void 0:g.frameRate)==null?void 0:d.max)!=null?h:5;let C=(m=(p=g==null?void 0:g.frameRate)==null?void 0:p.ideal)!=null?m:5;const M=g==null?void 0:g.displaySurface,N=g==null?void 0:g.selfBrowserSurface;Q.getValue(ie.VAL_MIN_FRAMERATE)&&(C=parseInt(Q.getValue(ie.VAL_MIN_FRAMERATE),10));let J={width:{max:v},height:{max:_},frameRate:{ideal:C,max:A}};if(Q.hasFeature(ie.SCREENSHARE_CONSTRAINTS)){const P=Q.getValue(ie.SCREENSHARE_CONSTRAINTS);J=JSON.parse(P)}return M!==void 0&&["monitor","browser","window"].includes(M)&&(J=Z(B({},J),{displaySurface:M})),N!==void 0&&(J=Z(B({},J),{selfBrowserSurface:N})),{audio:!0,video:J}}),f(this,"getAudioConstraints",n=>{var i,s,o,a,d,h,p,m;const g={},v=(i=c(this,Zi))==null?void 0:i.audio,_=v!=null&&v.enableStereo?2:1;return Te.isFirefox()||Te.isWebKitBased()?(g.audio={deviceId:n,autoGainControl:(s=v==null?void 0:v.autoGainControl)!=null?s:!0,echoCancellation:(o=v==null?void 0:v.echoCancellation)!=null?o:!0,noiseSuppression:(a=v==null?void 0:v.noiseSupression)!=null?a:!0,channelCount:_},g):(g.audio={},g.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:_},{echoCancellation:(d=v==null?void 0:v.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=v==null?void 0:v.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=v==null?void 0:v.autoGainControl)!=null?p:!0},{googNoiseSuppression:(m=v==null?void 0:v.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],g)}),f(this,"getVideoConstraints",n=>{var i,s,o;const a={},d=(i=c(this,Zi))==null?void 0:i.video;let h=bm.vga;if(typeof d=="string"?h=bm[d]:d!==void 0&&(h.height.ideal=d.height.ideal,h.width.ideal=d.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},Te.isChromiumBased()&&(h.frameRate.max=30),Q.hasFeature(ie.VIDEO_CONSTRAINTS)){const p=Q.getValue(ie.VIDEO_CONSTRAINTS);h=JSON.parse(p)}return a.video=h,typeof a.video=="boolean"||(n?a.video.deviceId={exact:n}:a.video.facingMode="user"),a}),S(this,nu,e),S(this,Zi,r)}getUpdatedVideoConstraints(e){return e}}Zi=new WeakMap,nu=new WeakMap;class hl extends Error{constructor(e,r,n){super(r),f(this,"constraints"),f(this,"name"),this.name=e,this.constraints=n}}class v1{constructor(){f(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audiooutput")})}}var y1=Object.defineProperty,S1=Object.getOwnPropertyDescriptor,Er=(t,e,r,n)=>{for(var i=n>1?void 0:n?S1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&y1(e,r,i),i},no,or,pl,Cm;let Kt=(Cm=class extends v1{constructor(t,e){super(),f(this,"availableDevices"),T(this,no,void 0),T(this,or,void 0),T(this,pl,void 0),S(this,pl,t),S(this,or,new g1(t,e)),S(this,no,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,or)}destruct(){return u(this,null,function*(){var t;(t=c(this,no))==null||t.abort()})}handlePermissionErrors(t,e){const r=Ia(t,e.name,e.message);return this.permissions[t]=r,I.emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,or).getAudioConstraints().audio,video:c(this,or).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=yield navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",Q.hasFeature(ie.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const i=(yield this.getVideoInputDevices()).find(s=>s.label.includes("OBS Virtual"));n=yield this.getVideoTrack(i.deviceId)}return I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new b("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new b("No audio devices available","1606");const n=i=>u(this,null,function*(){let s;try{r=r.filter(a=>a.deviceId!==i),s=c(this,or).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[o]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const a=Ia("audio",o.name,o.message),d=new hl(o.name,o.message,s);if(a==="COULD_NOT_START"){const h=r.shift();if(!h)throw d;l.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:o});const p=c(this,or).getAudioConstraints(h.deviceId);return l.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(p)}),n(h.deviceId)}throw d}});try{const i=yield n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new b(i.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=Q.hasFeature(ie.OBS_QUALITY),n=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),i=r&&n,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new b("No video devices available","1607");const o=a=>u(this,null,function*(){try{let d=a;const{video:h}=d;i&&typeof h!="boolean"&&(d={video:{deviceId:h.deviceId}}),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[p]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(i&&typeof h!="boolean"&&typeof h.width=="object"){const{width:m,height:g}=p.getSettings(),{ideal:v}=h.width;p.applyConstraints({width:{ideal:v},height:{ideal:Math.floor(g*v/m)},frameRate:h.frameRate})}return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),p}catch(d){const h=Ia("video",d.name,d.message),p=new hl(d.name,d.message,a);if(h==="COULD_NOT_START"){const m=s.shift();if(!m)throw p;l.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(a),error:d});const g=c(this,or).getVideoConstraints(m.deviceId);return l.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(g)}),o({video:g.video})}throw p}});try{const a=c(this,or).getVideoConstraints(t),d=yield o(a);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(a){throw a.constraints&&this.handlePermissionErrors("video",a),new b(a.message,"1602")}})}getScreenShareTracks(){return u(this,null,function*(){const t=e=>u(this,null,function*(){try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),$.screenShareRequested();const r=yield navigator.mediaDevices.getDisplayMedia(e);return l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const n=Ia("video",r.name,r.message),i=new hl(r.name,r.message,e),s={video:!0};if(Qw(e,s)||!Q.hasFeature(ie.SCREEENSHARE_CONSTRAINTS_RETRY))throw i;if(n==="COULD_NOT_START")return t(s);throw i}});try{const e=c(this,or).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new b(e.message,"1612")}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new b("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get available devices by kind","1609")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new b("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Te.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,n;const i=p=>`${p.kind}-${p.deviceId}-${p.groupId}`,s=this.availableDevices,o=new Set(s.map(p=>i(p))),a=yield this.getAvailableDevices(),d=new Set(a.map(p=>i(p))),h={added:a.filter(p=>!o.has(i(p))),removed:s.filter(p=>!d.has(i(p))),devices:a};if((r=h.added)!=null&&r.length||(n=h.removed)!=null&&n.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...h.added,...h.removed];p.some(m=>m.kind==="audioinput")&&$.devices("AUDIO",a==null?void 0:a.filter(m=>m.kind==="audioinput")),p.some(m=>m.kind==="videoinput")&&$.devices("VIDEO",a==null?void 0:a.filter(m=>m.kind==="videoinput")),p.some(m=>m.kind==="audiooutput")&&$.devices("SPEAKER",a==null?void 0:a.filter(m=>m.kind==="audiooutput")),t(e,h,!1)}}),{signal:c(this,no).signal})})}},no=new WeakMap,or=new WeakMap,pl=new WeakMap,Cm);Er([y.trace("WebMediaInterface.destruct")],Kt.prototype,"destruct",1);Er([y.trace("WebMediaInterface.handlePermissionErrors")],Kt.prototype,"handlePermissionErrors",1);Er([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Kt.prototype,"getAudioAndVideoTrack",1);Er([y.trace("WebMediaInterface.getAudioTrack")],Kt.prototype,"getAudioTrack",1);Er([y.trace("WebMediaInterface.getVideoTrack")],Kt.prototype,"getVideoTrack",1);Er([y.trace("WebMediaInterface.getScreenShareTracks")],Kt.prototype,"getScreenShareTracks",1);Er([y.trace("WebMediaInterface.getAvailableDevices")],Kt.prototype,"getAvailableDevices",1);Er([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Kt.prototype,"getAvailableDevicesByKind",1);Er([y.trace("WebMediaInterface.getDevice")],Kt.prototype,"getDevice",1);Er([y.trace("WebMediaInterface.onDeviceChange")],Kt.prototype,"onDeviceChange",1);Kt=Er([St("1600")],Kt);const Hv=Kt,ml={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(r){l.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){l.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},E1=(t=0)=>new Promise(e=>setTimeout(e,t)),T1=(t,e,r)=>{const n=typeof r=="number"?r:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const o=new Uint8Array(s.fftSize);let a=!1;setTimeout(()=>{a=!0},n);function d(){return a?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(h=>h!==128&&h!==0)?Promise.resolve(!1):E1().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},k1=typeof AudioContext!="undefined"?AudioContext:null;class Xu{constructor(e){f(this,"_AudioContext"),f(this,"audioContext"),f(this,"_audioContextRefContainers");const r=B({AudioContext:k1},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Xu}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch{}return this.audioContext}release(e){this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.delete(e),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Pm=new Xu,_1=3,b1=250;function w1(t){const e={},r=Pm.getOrCreate(e);let n=_1;function i(){return n-=1,T1(r,t.srcObject,b1).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Pm.release(e)})}function Rm(t){return u(this,null,function*(){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let n=!1;try{const i=e.play();i&&(yield i),n=yield w1(e),n&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return n})}var I1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,Wv=(t,e,r,n)=>{for(var i=n>1?void 0:n?C1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&I1(e,r,i),i};let Wc=class extends Ss{constructor(t,e,r){super(),f(this,"constructorName",this.constructor.name),f(this,"userSelectedDevice"),f(this,"mediaInterface"),f(this,"isNonPreferredDevice"),f(this,"_mediaTrack"),f(this,"transformedMediaTrack"),f(this,"middlewares",[]),f(this,"currentDevice"),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return u(this,null,function*(){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new b("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:r}=this.mediaTrack;switch(r){case"audio":{const n=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=n==null?void 0:n.deviceId)!=null?t:n==null?void 0:n.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}addMiddleware(t){return u(this,null,function*(){if(Te.isWebKitBased()&&!Q.hasFeature(ie.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return u(this,null,function*(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return l.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}})}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Wv([y.trace("BaseMediaHandler.unmuteTrack")],Wc.prototype,"unmuteTrack",1);Wc=Wv([St("1600")],Wc);const $v=Wc;var P1=Object.defineProperty,R1=Object.getOwnPropertyDescriptor,Zu=(t,e,r,n)=>{for(var i=n>1?void 0:n?R1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&P1(e,r,i),i};const fl="[Dyte]nonSilentDeviceLabels";class Ed extends $v{setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("AudioMediaHandler.setDevice No device received"),new b("No device received!","1603");if(e.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new b("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;this.userSelectedDevice=e.deviceId,yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(r){throw l.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new b(r.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const r=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(r)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield u1(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){l.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const o=JSON.parse(ml.getItem(fl));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Rm(n))){const d=(r=o==null?void 0:o.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return ml.setItem(fl,JSON.stringify({devices:d})),n}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==a).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Rm(n))){const h=o.devices.concat({label:n.label});return ml.setItem(fl,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}Zu([y.trace("AudioMediaHandler.setTransformedTrack")],Ed.prototype,"setTransformedTrack",1);Zu([y.trace("AudioMediaHandler.onTrackEnded")],Ed.prototype,"onTrackEnded",1);Zu([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Ed.prototype,"conditionallyChangeTrack",1);const A1=Ed;var bo;class M1{constructor(e){T(this,bo,void 0),f(this,"currentDevice"),S(this,bo,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,bo)instanceof Hv))return;let n=e;if(e||([n]=(yield c(this,bo).getAvailableDevicesByKind("audiooutput")).filter(i=>!ru(i))),!n)throw new b("No speaker found","1608");((r=this.currentDevice)==null?void 0:r.deviceId)!==n.deviceId&&(this.currentDevice=n,document.querySelectorAll("audio").forEach(i=>u(this,null,function*(){if(typeof i.sinkId!="undefined"&&this.currentDevice.deviceId&&i.sinkId!==this.currentDevice.deviceId)try{yield i.setSinkId(this.currentDevice.deviceId)}catch{}})))})}}bo=new WeakMap;const D1=M1;class O1 extends Ss{constructor(e){super(),f(this,"mediaInterface"),f(this,"audioMediaTrack"),f(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:n,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",I.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new b("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Te.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const N1=O1;var L1=Object.defineProperty,x1=Object.getOwnPropertyDescriptor,Td=(t,e,r,n)=>{for(var i=n>1?void 0:n?x1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&L1(e,r,i),i},wo,ic;class ia extends $v{constructor(e,r,n){super(e,r,n),T(this,wo,void 0),T(this,ic,{disablePerFrameCanvasRendering:!1}),S(this,wo,new h1)}setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new b("No device received!","1603");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new b("Non video device received while setting video device!","1603");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new b("Failed to change device","1600")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c(this,wo).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,ic)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){S(this,ic,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new b("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new b("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){c(this,wo).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const n=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),r})}}wo=new WeakMap,ic=new WeakMap;Td([y.trace("VideoMediaHandler.setTransformedTrack")],ia.prototype,"setTransformedTrack",1);Td([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ia.prototype,"setVideoMiddlewareGlobalConfig",1);Td([y.trace("VideoMediaHandler.onTrackEnded")],ia.prototype,"onTrackEnded",1);Td([y.trace("VideoMediaHandler.conditionallyChangeTrack")],ia.prototype,"conditionallyChangeTrack",1);const U1=ia,Am=fr(Vu());var Jt,es,sc,Io;const Co=class{constructor(t){if(T(this,Jt,void 0),T(this,es,void 0),T(this,sc,void 0),T(this,Io,void 0),!t)throw new b("Could not load preset.","0904");S(this,Jt,t.config),S(this,sc,t.name),S(this,es,t.ui||fr(Vu().ui)),S(this,Io,t.permissions.plugins.config)}static fromResponse(t){return new Co(t)}static default(){return new Co(Am)}static init(t,e=!0){return!t||e?new Co(Am):new Co(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:c(this,es).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,Jt).viewType}get livestreamViewerQualities(){return c(this,Jt).livestreamViewerQualities||[]}get maxVideoStreams(){return c(this,Jt).maxVideoStreams}get maxScreenShareCount(){return c(this,Jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Io)).filter(t=>c(this,Io)[t].disabled)}get designTokens(){return c(this,es).designTokens}get configDiff(){return c(this,es).configDiff}get mediaConstraints(){var t,e,r,n,i,s,o,a,d,h,p,m,g,v,_,A,C,M,N,J,P,G,W,ae;return{audio:{enableStereo:(n=(r=(e=(t=c(this,Jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:Bi.audio.enableStereo,enableHighBitrate:(a=(o=(s=(i=c(this,Jt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?a:Bi.audio.enableHighBitrate},video:{quality:(m=(p=(h=(d=c(this,Jt))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?m:Bi.video.quality,frameRate:(A=(_=(v=(g=c(this,Jt))==null?void 0:g.media)==null?void 0:v.video)==null?void 0:_.frameRate)!=null?A:Bi.video.frameRate},screenshare:{quality:(J=(N=(M=(C=c(this,Jt))==null?void 0:C.media)==null?void 0:M.screenshare)==null?void 0:N.quality)!=null?J:Bi.screenshare.quality,frameRate:(ae=(W=(G=(P=c(this,Jt))==null?void 0:P.media)==null?void 0:G.screenshare)==null?void 0:W.frameRate)!=null?ae:Bi.screenshare.frameRate}}}get name(){return c(this,sc)}};let F1=Co;Jt=new WeakMap,es=new WeakMap,sc=new WeakMap,Io=new WeakMap;var V1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,Jv=(t,e,r,n)=>{for(var i=n>1?void 0:n?B1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&V1(e,r,i),i},Po;class eh extends Yt{constructor(e){super(),T(this,Po,void 0),f(this,"state","IDLE"),f(this,"playbackUrl"),f(this,"ingestionCredentials"),f(this,"viewerCount"),S(this,Po,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!c(this,Po).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new b("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Ke(),{playbackUrl:n,ingestionCredentials:i}=yield r.startLivestreaming(e);this.playbackUrl=n,this.ingestionCredentials=i,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new b("Error while starting livestream","1900")}})}stop(){return u(this,null,function*(){if(!c(this,Po).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new b("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw l.error("DyteLivestream::stop::inconsistent_state"),new b("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield Ke().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new b("Error while stopping livestream","1900")}})}}Po=new WeakMap;Jv([y.trace("livestream.start")],eh.prototype,"start",1);Jv([y.trace("livestream.stop")],eh.prototype,"stop",1);var j1=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,W1=(t,e,r,n)=>{for(var i=n>1?void 0:n?H1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&j1(e,r,i),i},Ro,Ao,In;class Gv{constructor(e,r){f(this,"livestream"),T(this,Ro,void 0),T(this,Ao,void 0),T(this,In,void 0),S(this,Ao,e),this.livestream=new eh(e),S(this,In,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=Ke(),{status:r,playbackUrl:n,manualIngest:i,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,this.livestream.ingestionCredentials=s,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){c(this,In).on(j.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{c(this,Ao).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{l.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),c(this,In).on(j.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{c(this,Ao).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{l.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),c(this,In).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),c(this,In).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,In).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),I.on(w.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(S(this,Ro,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),I.on(w.PEER_CLOSED,e=>{e.id===c(this,Ro)&&(S(this,Ro,void 0),this.livestream.setLivestreamState("IDLE"))}),I.onAsync(w.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),I.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{l.error("Error: LivestreamController.fetchLivestream")}}))}}Ro=new WeakMap,Ao=new WeakMap,In=new WeakMap;W1([y.trace("LivestreamController.setupEvents")],Gv.prototype,"setupEvents",1);var $1=Object.defineProperty,J1=Object.getOwnPropertyDescriptor,sa=(t,e,r,n)=>{for(var i=n>1?void 0:n?J1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$1(e,r,i),i},At,ii,si,iu,qv;class ks{constructor({name:e,socketHandler:r,meetingId:n}){T(this,iu),f(this,"name",""),T(this,At,{}),T(this,ii,""),T(this,si,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),f(this,"listeners",{}),this.name=e,S(this,si,r),S(this,ii,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,At)[e]=r,n&&this.remoteSet(e,r),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,At)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,At)[e]})))})}remoteSet(e,r){c(this,si).storeInsertKeys(c(this,ii),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,At)[r]=n}),c(this,si).storeInsertKeys(c(this,ii),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){Ye(this,iu,qv).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,At)[e]&&delete c(this,At)[e],r)return c(this,si).storeDeleteKeys(c(this,ii),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{c(this,At)[r]&&delete c(this,At)[r]}),c(this,si).storeDeleteKeys(c(this,ii),this.name,e)})}get(e){if(c(this,At)[e])return c(this,At)[e]}getAll(){return c(this,At)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,r){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=r}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,r){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=r}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e,r){var n;if(r){this.listeners[e]=((n=this.listeners[e])==null?void 0:n.filter(i=>i!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){S(this,At,e)}}At=new WeakMap,ii=new WeakMap,si=new WeakMap,iu=new WeakSet,qv=function(t,e,r=!0){let n;const i=c(this,At)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n=B(B({},i),e);break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)};sa([Bt(Ts,"rateLimitConfig")],ks.prototype,"remoteSet",1);sa([Bt(Ts,"bulkRateLimitConfig")],ks.prototype,"bulkSet",1);sa([Bt(Ts,"rateLimitConfig")],ks.prototype,"update",1);sa([Bt(Ts,"rateLimitConfig")],ks.prototype,"delete",1);sa([Bt(Ts,"bulkRateLimitConfig")],ks.prototype,"bulkDelete",1);var is,ss,oc,gl,$c,mi,su,zv;class G1{constructor(e,r){T(this,oc),T(this,su),f(this,"stores",new Map),T(this,is,void 0),T(this,ss,""),T(this,$c,void 0),T(this,mi,new Map),S(this,is,r),S(this,ss,e.getValue("meetingId")),S(this,$c,e),Ye(this,su,zv).call(this)}create(e){const r=new ks({name:e,socketHandler:c(this,is),meetingId:c(this,ss)});return c(this,is).storeGetKeys(c(this,ss),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,mi).set(e,{rejectTimeout:s,resolve:n,store:r})})}}is=new WeakMap,ss=new WeakMap,oc=new WeakSet,gl=function(){return c(this,$c).getValue("peerId")},$c=new WeakMap,mi=new WeakMap,su=new WeakSet,zv=function(){[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{c(this,is).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,ss))return;const i=(r=e.storeItems)==null?void 0:r.map(o=>{var a;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((a=o.payload)!=null&&a.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===z.storeGetKeys){const o=c(this,mi).get(e.storeName),a=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,mi).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(a),clearTimeout(o.rejectTimeout),c(this,mi).delete(e.storeName)),i.forEach(d=>{a.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=c(this,mi).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===z.storeInsertKeys&&i.forEach(({key:o,peerId:a,payload:d})=>{a===c(this,oc,gl)&&t!==z.storeGetKeys||s.set(o,d,!1,!0)}),t===z.storeDeleteKeys&&i.forEach(({key:o,peerId:a})=>{a!==c(this,oc,gl)&&s.delete(o,!1,!0)}))}))})};function fi(t){var e,r,n,i,s,o,a,d,h,p,m,g,v;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(a=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:a.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(m=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:m.enabled,trackId:(v=(g=t.screenShareTracks)==null?void 0:g.video)==null?void 0:v.id}}}}:{}}var q1=Object.defineProperty,z1=Object.getOwnPropertyDescriptor,_s=(t,e,r,n)=>{for(var i=n>1?void 0:n?z1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&q1(e,r,i),i};const K1=.8,Y1=1.2;var io,so,Jn,ji,oo,cn,Ca,Gn,ao,Pa,dn,vl,Ra,yl,Mm;let tn=(Mm=class extends Yt{constructor(t,e,r,n){super(),T(this,ji),T(this,ao),T(this,Ra),f(this,"id"),f(this,"userId"),f(this,"name"),f(this,"picture"),f(this,"isHost"),f(this,"customParticipantId"),f(this,"flags"),f(this,"device"),f(this,"videoTrack"),f(this,"audioTrack"),f(this,"screenShareTracks"),f(this,"videoEnabled"),f(this,"audioEnabled"),f(this,"screenShareEnabled"),f(this,"producers"),f(this,"manualProducerConfig"),T(this,io,void 0),f(this,"supportsRemoteControl",!1),T(this,so,void 0),f(this,"presetName"),T(this,Jn,void 0),T(this,cn,void 0),T(this,Ca,void 0),T(this,Gn,new Map),T(this,dn,1),T(this,vl,Zr(P=>{if(!this.videoTrack)return;const{clientWidth:G,clientHeight:W}=P,{width:ae,height:se}=this.videoTrack.getSettings();if(!ae||!se)return;const Ne=se/W,Tt=ae/G,O=Math.max(Ne,Tt);O>Y1&&c(this,dn)===1?(S(this,dn,0),I.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,dn)})):O<K1&&c(this,dn)===0&&(S(this,dn,1),I.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,dn)}))},2e3)),S(this,Jn,t);const{id:i,userId:s,displayName:o,device:a,picture:d,isHost:h,flags:p,clientSpecificId:m,stageStatus:g,customParticipantId:v,audioMuted:_,audioTrack:A,videoEnabled:C=!1,videoTrack:M,producers:N,metadata:J}=e;this.id=i,this.userId=s,this.name=o,this.device=a,this.picture=d,this.isHost=h,this.flags=p,this.manualProducerConfig=aI,S(this,so,g!=null?g:"ON_STAGE"),this.customParticipantId=v!=null?v:m,this.audioEnabled=!_,this.audioTrack=A,this.videoEnabled=C,this.videoTrack=M,this.screenShareTracks={audio:void 0,video:void 0},this.producers=N!=null?N:[],this.presetName=J==null?void 0:J.preset_name,S(this,io,!1),S(this,cn,r),S(this,Ca,n),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),Ye(this,Ra,yl).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,so)}get mediaJoined(){return c(this,Jn).getValue("connectionHandler").mediaJoined}get socketJoined(){return c(this,Jn).getValue("connectionHandler").socketJoined}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",B({},fi(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",B({},fi(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",Ye(this,Ra,yl))}pin(){return u(this,null,function*(){if(!this.mediaJoined)throw new b("Can`t pin participant without joining room","1205");if(!c(this,cn).permissions.pinParticipant)throw new b("You do not have permission to pin participants.","1201");return c(this,ji,oo).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.mediaJoined)throw new b("Can`t unpin participant without joining room","1205");if(!c(this,cn).permissions.pinParticipant)throw new b("You do not have permission to unpin participants.","1201");return c(this,ji,oo).pinPeer(null)})}setIsPinned(t,e=!0){var r;S(this,io,t);const n=t?"pinned":"unpinned";(r=c(this,ao,Pa))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new b("Can`t disable participant audio without joining room","1205");if(c(this,cn).permissions.canDisableParticipantAudio)return c(this,ji,oo).disableAudio(t);throw l.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new b("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.socketJoined)throw new b("Can`t kick participant without joining room","1205");if(c(this,cn).permissions.kickParticipant){yield I.emitAsync(w.KICK_PEER,{peerId:t});return}throw l.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new b("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new b("Can`t disable participant video without joining room","1205");if(c(this,cn).permissions.canDisableParticipantVideo)return c(this,ji,oo).disableVideo(t);throw l.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new b("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return u(this,null,function*(){return c(this,Ca).getUserPermissions(this.userId)})}setStageStatus(t){S(this,so,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,io)}registerVideoElement(t){var e,r,n,i;let s;(r=(e=c(this,Gn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>c(this,vl).call(this,t)),s.observe(t)),c(this,Gn).set(t,{observer:s}),this.updateVideo(t),(i=c(this,ao,Pa))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,n;t!==void 0&&(t.srcObject=void 0,(r=(e=c(this,Gn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,Gn).delete(t),(n=c(this,ao,Pa))==null||n.removeSource(this.id))}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const n=new MediaStream;n.addTrack(this.videoTrack),t.srcObject=n}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},io=new WeakMap,so=new WeakMap,Jn=new WeakMap,ji=new WeakSet,oo=function(){return c(this,Jn).getValue("roomNodeClient")},cn=new WeakMap,Ca=new WeakMap,Gn=new WeakMap,ao=new WeakSet,Pa=function(){return c(this,Jn).getValue("pip")},dn=new WeakMap,vl=new WeakMap,Ra=new WeakSet,yl=function(){Array.from(c(this,Gn).keys()).forEach(this.updateVideo)},Mm);_s([y.trace("DyteParticipant.disableAudio")],tn.prototype,"disableAudio",1);_s([y.trace("DyteParticipant.kick")],tn.prototype,"kick",1);_s([y.trace("DyteParticipant.disableVideo")],tn.prototype,"disableVideo",1);_s([y.trace("DyteParticipant.getPermissions")],tn.prototype,"getPermissions",1);_s([y.trace("DyteParticipant.setStageStatus")],tn.prototype,"setStageStatus",1);tn=_s([St("1200")],tn);class co extends Vv{constructor(e){const{onAddEvent:r="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:n,onClearEvent:i})}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var oi;class Q1 extends Ss{constructor(){super(),T(this,oi,void 0),S(this,oi,new Map)}__set(e,r){return c(this,oi).set(e,r)}__clear(){return c(this,oi).clear()}get(e){return c(this,oi).get(e)}toArray(){return Array.from(c(this,oi).values())}}oi=new WeakMap;var yi={},kd={},Jc={},X1={get exports(){return Jc},set exports(t){Jc=t}},Sl,Dm;function Z1(){if(Dm)return Sl;Dm=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Sl=function(p,m){m=m||{};var g=typeof p;if(g==="string"&&p.length>0)return o(p);if(g==="number"&&isFinite(p))return m.long?d(p):a(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(m){var g=parseFloat(m[1]),v=(m[2]||"ms").toLowerCase();switch(v){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*n;case"hours":case"hour":case"hrs":case"hr":case"h":return g*r;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function a(p){var m=Math.abs(p);return m>=n?Math.round(p/n)+"d":m>=r?Math.round(p/r)+"h":m>=e?Math.round(p/e)+"m":m>=t?Math.round(p/t)+"s":p+"ms"}function d(p){var m=Math.abs(p);return m>=n?h(p,m,n,"day"):m>=r?h(p,m,r,"hour"):m>=e?h(p,m,e,"minute"):m>=t?h(p,m,t,"second"):p+" ms"}function h(p,m,g,v){var _=m>=g*1.5;return Math.round(p/g)+" "+v+(_?"s":"")}return Sl}function eO(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=o,r.humanize=Z1(),r.destroy=h,Object.keys(t).forEach(p=>{r[p]=t[p]}),r.names=[],r.skips=[],r.formatters={};function e(p){let m=0;for(let g=0;g<p.length;g++)m=(m<<5)-m+p.charCodeAt(g),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=e;function r(p){let m,g=null,v,_;function A(...C){if(!A.enabled)return;const M=A,N=Number(new Date),J=N-(m||N);M.diff=J,M.prev=m,M.curr=N,m=N,C[0]=r.coerce(C[0]),typeof C[0]!="string"&&C.unshift("%O");let P=0;C[0]=C[0].replace(/%([a-zA-Z%])/g,(G,W)=>{if(G==="%%")return"%";P++;const ae=r.formatters[W];if(typeof ae=="function"){const se=C[P];G=ae.call(M,se),C.splice(P,1),P--}return G}),r.formatArgs.call(M,C),(M.log||r.log).apply(M,C)}return A.namespace=p,A.useColors=r.useColors(),A.color=r.selectColor(p),A.extend=n,A.destroy=r.destroy,Object.defineProperty(A,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(v!==r.namespaces&&(v=r.namespaces,_=r.enabled(p)),_),set:C=>{g=C}}),typeof r.init=="function"&&r.init(A),A}function n(p,m){const g=r(this.namespace+(typeof m=="undefined"?":":m)+p);return g.log=this.log,g}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let m;const g=(typeof p=="string"?p:"").split(/[\s,]+/),v=g.length;for(m=0;m<v;m++)g[m]&&(p=g[m].replace(/\*/g,".*?"),p[0]==="-"?r.skips.push(new RegExp("^"+p.slice(1)+"$")):r.names.push(new RegExp("^"+p+"$")))}function s(){const p=[...r.names.map(a),...r.skips.map(a).map(m=>"-"+m)].join(",");return r.enable(""),p}function o(p){if(p[p.length-1]==="*")return!0;let m,g;for(m=0,g=r.skips.length;m<g;m++)if(r.skips[m].test(p))return!1;for(m=0,g=r.names.length;m<g;m++)if(r.names[m].test(p))return!0;return!1}function a(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function d(p){return p instanceof Error?p.stack||p.message:p}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var tO=eO;(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){return typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;d.splice(1,0,h,"color: inherit");let p=0,m=0;d[0].replace(/%[a-zA-Z%]/g,g=>{g!=="%%"&&(p++,g==="%c"&&(m=p))}),d.splice(m,0,h)}e.log=console.debug||console.log||(()=>{});function i(d){try{d?e.storage.setItem("debug",d):e.storage.removeItem("debug")}catch{}}function s(){let d;try{d=e.storage.getItem("debug")}catch{}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function o(){try{return localStorage}catch{}}t.exports=tO(e);const{formatters:a}=t.exports;a.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(X1,Jc);var rO=Ph&&Ph.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(kd,"__esModule",{value:!0});kd.Logger=void 0;const Hi=rO(Jc),Wi="awaitqueue";class nO{constructor(e){e?(this._debug=(0,Hi.default)(`${Wi}:${e}`),this._warn=(0,Hi.default)(`${Wi}:WARN:${e}`),this._error=(0,Hi.default)(`${Wi}:ERROR:${e}`)):(this._debug=(0,Hi.default)(Wi),this._warn=(0,Hi.default)(`${Wi}:WARN`),this._error=(0,Hi.default)(`${Wi}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}kd.Logger=nO;Object.defineProperty(yi,"__esModule",{value:!0});var fs=yi.AwaitQueue=yi.AwaitQueueRemovedTaskError=yi.AwaitQueueStoppedError=void 0;const iO=kd,ln=new iO.Logger;class th extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,th)}}yi.AwaitQueueStoppedError=th;class _d extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,_d)}}yi.AwaitQueueRemovedTaskError=_d;class sO{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,r){return u(this,null,function*(){if(r=r!=null?r:e.name,ln.debug(`push() [name:${r}]`),typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch{}return new Promise((n,i)=>{const s={id:this.nextTaskId++,task:e,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:o=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),ln.debug(`resolving task [name:${s.name}]`),n(o);const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)},reject:o=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),ln.debug(`rejecting task [name:${s.name}]: %s`,String(o)),i(o),!this.stopping)){const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){ln.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())ln.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){ln.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){ln.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new _d)}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:r++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}execute(e){return u(this,null,function*(){if(ln.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=yield e.task();e.resolve(r)}catch(r){e.reject(r)}})}}fs=yi.AwaitQueue=sO;var ac;class Kv{constructor(){f(this,"meetingTitle"),f(this,"roomName"),f(this,"roomUUID"),T(this,ac,void 0),f(this,"context"),f(this,"authToken"),f(this,"maxPreferredStreams")}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return!1}set mediaJoined(e){throw new b("Method not implemented.")}get sfuHandler(){return c(this,ac)}get mediaState(){return c(this,ac).transportState}reconnect(){throw new b("Method not implemented.")}partialJoinRoom(e,r,n=!1,i=void 0){return u(this,null,function*(){throw new b("Method not implemented.")})}joinRoom(e,r){return u(this,arguments,function*(n,i,s={},o=!1,a=!1){throw new b("Method not implemented.")})}leaveRoom(){return u(this,null,function*(){throw new b("Method not implemented.")})}reset(e=!0){throw new b("Method not implemented")}handleSocketCallbacks(e){return u(this,null,function*(){throw new b("Method not implemented.")})}handleSockets(e,r){return u(this,null,function*(){throw new b("Method not implemented.")})}shareMic(e){return u(this,null,function*(){throw new b("Method not implemented.")})}shareWebcam(e){return u(this,null,function*(){throw new b("Method not implemented.")})}shareScreen(e){return u(this,null,function*(){throw new b("Method not implemented.")})}unmuteSelf(){return u(this,null,function*(){throw new b("Method not implemented.")})}muteSelf(){return u(this,null,function*(){throw new b("Method not implemented.")})}pauseWebcam(){return u(this,null,function*(){throw new b("Method not implemented.")})}disableScreenShare(){return u(this,null,function*(){throw new b("Method not implemented.")})}acceptWaitingRequest(e){return u(this,null,function*(){throw new b("Method not implemented.")})}rejectWaitingRequest(e){return u(this,null,function*(){throw new b("Method not implemented.")})}muteAll(e){return u(this,null,function*(){throw new b("Method not implemented.")})}muteAllVideo(){return u(this,null,function*(){throw new b("Method not implemented.")})}disableAudio(e){return u(this,null,function*(){throw new b("Method not implemented.")})}disableVideo(e){return u(this,null,function*(){throw new b("Method not implemented.")})}kickAll(){return u(this,null,function*(){throw new b("Method not implemented.")})}kick(e){return u(this,null,function*(){throw new b("Method not implemented.")})}pinPeer(e){return u(this,null,function*(){throw new b("Method not implemented.")})}getConsumers(){throw new b("Method not implemented.")}stopAllProducers(){throw new b("Method not implemented.")}activatePeers(e){return u(this,null,function*(){throw new b("Method not implemented.")})}deactivatePeers(e,r="default"){return u(this,null,function*(){throw new b("Method not implemented.")})}createConsumers(e){return u(this,null,function*(){throw new b("Method not implemented.")})}closeConsumers(e){return u(this,null,function*(){throw new b("Method not implemented.")})}switchConsumersToLayer(e,r){return u(this,null,function*(){throw new b("Method not implemented.")})}}ac=new WeakMap;var Qr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(Qr||{});class Yv extends ft.EventEmitter{}class ki extends ft.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...r){const n=this.listenerCount(e);try{return this.emit(e,...r)}catch(i){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(n)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...r)})}safeEmitAsPromiseWithTimeout(e,r,...n){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...n,i,s)}catch(o){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}function oO(t,e){const r=new Error(e);return r.name=t,r}class _i extends b{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_i):this.stack=new Error(e).stack}}class it extends b{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,it):this.stack=new Error(e).stack}}class Qv extends b{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,it):this.stack=new Error(e).stack}}class Xv extends b{constructor(e){super(e),this.name="DataChannelRequestError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,it):this.stack=new Error(e).stack}}var cc,dc,lc,uc,jr,hc,pc,_r,ts,mc,fc,gc,El,ou,Zv,au,ey;class ty extends ki{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:s,handler:o,track:a,appData:d,paused:h,reuseTrack:p,rtpReceiver:m}){super(),T(this,gc),T(this,ou),T(this,au),f(this,"rtpReceiver"),f(this,"observer"),T(this,cc,void 0),T(this,dc,void 0),T(this,lc,void 0),T(this,uc,void 0),T(this,jr,void 0),T(this,hc,void 0),T(this,pc,void 0),T(this,_r,void 0),T(this,ts,void 0),T(this,mc,void 0),T(this,fc,void 0),S(this,cc,e),S(this,dc,r),S(this,pc,o),S(this,fc,d),S(this,mc,i),S(this,uc,s),S(this,jr,!1),S(this,lc,n),S(this,_r,a),S(this,ts,h!=null?h:!1),S(this,hc,p),this.observer=new ki,this.rtpReceiver=m,Ye(this,ou,Zv).call(this)}get id(){return c(this,cc)}get peerId(){return c(this,mc)}get localId(){return c(this,dc)}get producerId(){return c(this,lc)}get producingTransportId(){return c(this,uc)}get closed(){return c(this,jr)}get kind(){return c(this,_r).kind}get track(){return c(this,_r)}get paused(){return c(this,ts)}get remotelyPaused(){return this.paused}get appData(){return c(this,fc)}close(e){c(this,jr)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),S(this,jr,!0),c(this,hc)||Ye(this,au,ey).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,jr))throw new it("closed");return c(this,pc).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,jr)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,ts,!0),c(this,_r).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,jr)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}S(this,ts,!1),c(this,_r).enabled=!0,this.observer.safeEmit("resume")}}cc=new WeakMap,dc=new WeakMap,lc=new WeakMap,uc=new WeakMap,jr=new WeakMap,hc=new WeakMap,pc=new WeakMap,_r=new WeakMap,ts=new WeakMap,mc=new WeakMap,fc=new WeakMap,gc=new WeakSet,El=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},ou=new WeakSet,Zv=function(){c(this,_r).addEventListener("ended",Ye(this,gc,El).bind(this))},au=new WeakSet,ey=function(){try{c(this,_r).removeEventListener("ended",Ye(this,gc,El)),c(this,_r).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let aO=class extends ty{};const Om=t=>new Promise(e=>setTimeout(e,t));function Ir(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:o}=B({strategy:"linear",maxRetryCount:3,delayTime:10},e);let a=0,d,h=!1;const p=m=>{h=!0,n(m)};for(;a<s;){try{const m=yield t(a,p);return r(m)}catch(m){if(d=m,h)break;if(a<s)i==="linear"?yield Om(o*(a+1)):i==="exponential"&&(yield Om(o*(a+Math.max(0,a-1))));else break}a+=1}return n(d)}))})}function Gc(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(r=>r.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}function cO(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function ry(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function cu(t){return Math.random().toString(36).substring(2,2+t)}const Aa=1;function Nm(t){const e=t;return delete e.payload._bolt,e}function dO(t){return t.payload&&ry(t.payload)}function qc(t){var e,r;return dO(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var ai;const Mo=class extends ft.EventEmitter{constructor(t,e,r){super(),f(this,"channel"),f(this,"queue"),f(this,"serverProtocolVersion"),T(this,ai,new Map),f(this,"respond",(n,i,s=!1)=>{let o;s?o=Mo.createErrorResponse(n,i):o=Mo.createResponse(n,i),this.channel.send(JSON.stringify(o))}),f(this,"notify",n=>{const i=Mo.createNotification(n);this.channel.send(JSON.stringify(i))}),f(this,"request",n=>u(this,null,function*(){const i=Mo.createRequest(n),s=new Promise((o,a)=>{const d=1e3*(5+.1*this.queue.size),{id:h}=i.payload._bolt,p={id:h,method:i.type,resolve:m=>{this.queue.delete(h)&&(clearTimeout(p.timer),o(m))},timer:setTimeout(()=>{this.queue.delete(h)&&a(new Error(`request timeout for message id: ${h}`))},d),cancel:m=>{this.queue.delete(h)&&(clearTimeout(p.timer),a(m))}};this.queue.set(h,p)});return this.channel.send(JSON.stringify(i)),s})),f(this,"send",n=>{const i=JSON.stringify(n),s=16384;if(i.length>s){const o=s-200,a=Math.ceil(i.length/o),d=[];for(let p=0;p<a;p+=1){const m=p*o,g=(p+1)*o;d.push(i.slice(m,g))}const h=bi();for(let p=0;p<a;p+=1){const m=d[p],g=JSON.stringify({id:h,count:a,chunkIndex:p,chunk:m});l.debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else l.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),f(this,"processMessage",n=>{var i;c(this,ai).has(n.id)||c(this,ai).set(n.id,[]);const s=c(this,ai).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(o=>o===void 0)){const o=c(this,ai).get(n.id),a=o==null?void 0:o.reduce((h,p)=>h+p.chunk,"");c(this,ai).delete(n.id);const d=JSON.parse(a);if(!d.payload||!ry(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),f(this,"processResponseMsg",n=>{const{id:i}=n.payload._bolt,s=this.queue.get(i);return s?(l.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(Nm(n)):s.resolve(Nm(n)),!0):!1}),f(this,"processBoltHandshake",n=>{var i,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(i=n.payload._bolt)==null?void 0:i.id)!=null?s:cu(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let Do=Mo;ai=new WeakMap,f(Do,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:Z(B({},t.payload),{_bolt:{id:cu(8),type:"REQUEST",version:Aa}})}}),f(Do,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:Z(B({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Aa}})}}),f(Do,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:Z(B({},t.payload),{bolt:{id:cu(8),type:"NOTIFY",version:Aa}})}}),f(Do,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Aa}}}));const du="transport closed";class ny extends ki{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:o,additionalSettings:a,appData:d,config:h}){var p,m;super(),f(this,"awaitQueue"),f(this,"observer"),f(this,"id"),f(this,"serverId"),f(this,"closed",!1),f(this,"direction"),f(this,"maxSctpMessageSize"),f(this,"handler"),f(this,"connectionState","new"),f(this,"producers"),f(this,"consumers"),f(this,"datachannels"),f(this,"connected",!1),f(this,"eventsDCReadyPromise"),f(this,"eventsDCReadyPromiseResolver"),f(this,"eventsDCFailureTimer"),f(this,"transportConnectionPromise"),f(this,"consumerTrackEvents"),f(this,"unknownTracksMap"),f(this,"consumerTrackPool"),f(this,"appData"),l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const g=cO(a,{});delete g.iceServers,delete g.iceTransportPolicy,delete g.bundlePolicy,delete g.rtcpMuxPolicy,delete g.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new fs,this.observer=new ki,this.handler=n(),this.handler._enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler._enableStereo=(m=h==null?void 0:h.enableStereo)!=null?m:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:s,additionalSettings:a,proprietaryConstraints:o}),this.appData=d||{},this.transportConnectionPromise=new Promise(v=>{this.observer.once("connected",()=>{v(!0)}),this.observer.once("disconnect",()=>{v(!1)}),this.observer.once("close",()=>{v(!1)})}),this.eventsDCReadyPromise=new Promise(v=>{this.eventsDCReadyPromiseResolver=v}),this.handler.on("@connectionstatechange",v=>{v!==this.connectionState&&(l.debug(`connection state changed to ${v}`),this.connectionState=v,v==="connected"&&(this.connected=!0,this.observer.emit("connected")),v==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(v==="failed"||v==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",v))}),this.handler.on("@icecandidate",({candidate:v})=>{this.closed||this.safeEmit("icecandidate",v)}),this.handler.on("dc_open",v=>{let _=this.datachannels.get(v.label);_||(_||(_=new Do(v,v.label,this.serverId),this.datachannels.set(v.label,_)),this.eventsDCFailureTimer=setTimeout(()=>{v.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",v.label))},5e3))}),this.handler.on("datachannel",(v,_)=>{v.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const A=this.datachannels.get(v.label);if(!A){l.error("unregistered datachannel for message",{rtcChannel:{label:v.label,message:_}});return}try{const C=JSON.parse(_);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:C.id,count:C.count,chunkIndex:C.chunkIndex,chunk:C.chunk,transprtId:this.serverId}});const M=A.processMessage(C);if(!M)return;l.debug(`datachannel message with id:${C.id} on transport:${this.serverId}complete - ${JSON.stringify(M)}`),this.emit(`datachannel:${v.label}`,A.label,M)}catch(C){l.error("error parsing message",{error:C})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("Transport close called"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(du).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(du)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new it("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new it("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new it("closed");return this.handler.updateIceServers(e)})}setRemoteOffer(e){return u(this,null,function*(){yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer(),n=bu(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=B({},i),o=s.fmtp.find(a=>a.payload===111);return o&&(o.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(a=>a.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),r.sdp=$S(n),yield this.setLocalDescription(r),r})}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}createConsumersOverDataChannel(e){return u(this,null,function*(){const r=this.getDatachannel("events");if(!r)throw oO("DC_NOT_READY","events datachannel not ready");if(!e||e&&e.length===0)throw new Error("list of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:a,producingTransportId:d})=>({producerId:a,producingTransportId:d}))}},i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=(yield r.request(n)).payload;l.info(`createConsumersOverDataChannel::response ${JSON.stringify(s)}`);const o=new Map;return Object.entries(s).forEach(([a,d])=>{const h=i.get(d.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${d.producerId}`,{consumerState:d});return}o.set(d.producerId,{consumerId:a,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:d.streamId,trackId:d.trackId,screenShare:h.screenShare,appData:{}})}),o})}}class iy extends ki{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,handler:a,appData:d,rtpSender:h}){super(),f(this,"_id"),f(this,"_localId"),f(this,"_closed",!1),f(this,"_handler"),f(this,"_track"),f(this,"_kind"),f(this,"_paused"),f(this,"_maxSpatialLayer"),f(this,"_stopTracks"),f(this,"_disableTrackOnPause"),f(this,"_zeroRtpOnPause"),f(this,"_appData"),f(this,"observer"),f(this,"rtpSender"),this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=s?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=s,this._zeroRtpOnPause=o,this._appData=d||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=a,this.rtpSender=h,this.observer=new ki,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}close(e){return u(this,null,function*(){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===du){this.observer.emit("close");return}const{offerSdp:r,callback:n}=yield this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)})}getStats(){return u(this,null,function*(){if(this._closed)throw new it("closed");return this._handler.getSenderStats(this.localId)})}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}}),this._closed){if(r&&this._stopTracks)try{r.stop()}catch(n){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id},error:n})}throw new it("closed")}else if(r&&r.readyState==="ended")throw new it("track ended");if(r===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}});return}(!this._zeroRtpOnPause||!this._paused)&&(yield this._handler.replaceTrack(this.localId,r)),this._destroyTrack(),this._track=r,this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(this._kind!=="video")throw new _i("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e})}setRtpEncodingParameters(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(typeof e!="object")throw new TypeError("invalid params");yield this._handler.setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let lO=class extends iy{},uO=class extends ny{consume(t){return u(this,null,function*(){if(l.debug(`consume() producers: ${JSON.stringify(t)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new _i("not a receiving transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))throw new Qv("transport not connected");let e;try{e=yield this.createConsumersOverDataChannel(t)}catch(n){throw new Xv(n.message)}const r=[];return e.forEach((n,i)=>{const{consumerId:s,trackId:o,screenShare:a,paused:d,streamId:h,kind:p,appData:m,producingTransportId:g,producingPeerId:v}=n;r.push(this.consumerCreationTask({consumerId:s,trackId:o,streamId:h,kind:p,producerId:i,producingPeerId:v,producingTransportId:g,paused:d,screenShare:a,appData:m}))}),Gc(r)})}connect(){return u(this,null,function*(){try{const{offerSdp:t,callback:e}=yield this.handler.connect(),{answer:r}=yield this.safeEmitAsPromise("connect",{offer:t});if(yield e(r),!(yield this.isConnected))throw new Error("ice connection failed");if(!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}})}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const s=this.consumerTrackEvents.get(i);s?(s(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}consumerCreationTask(t){return u(this,arguments,function*({consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,paused:a,screenShare:d,appData:h,kind:p}){const m=`${s}:${p}`,g={consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,appData:h,kind:p,paused:a,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((v,_)=>{const A=setTimeout(()=>{this.consumerTrackEvents.delete(m),g.isTimedout=!0,_(g)},5e3),C=(J,P)=>{try{if(J.readyState==="ended")clearTimeout(A),_(g);else{const G=J;G.enabled=!0,this.handler.midTransceiverMap.set(P.mid,P);const W=new aO({id:e,localId:P.mid,track:G,paused:a,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:Z(B({},h),{screenShare:d,peerId:n}),reuseTrack:!0,rtpReceiver:P.receiver});this.consumers.set(e,W),W.once("close",()=>{this.consumers.delete(W.id),this.handler.midTransceiverMap.delete(P.mid)}),l.info("consumer created for ",{consumer:{id:e,kind:p,appData:{screenShare:d},peerId:n,producerId:r}}),this.observer.emit("newconsumer",W),clearTimeout(A),v(W)}}catch(G){l.warn("error while creating consumer:",G),clearTimeout(A),_(g)}},M=this.consumerTrackPool.get(e);if((M==null?void 0:M.length)===2){C(M[0],M[1]);return}const N=this.unknownTracksMap.get(m);N?(this.unknownTracksMap.delete(m),C(N.track,N.transceiver)):this.consumerTrackEvents.set(m,C)})})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return Gc(t.map(e=>u(this,null,function*(){return Ir(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(B({},e))}))})))})}produce(){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:s=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new _i("not a sending Transport");if(t.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:a,localId:d,rtpSender:h}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:m,callback:g,sender:v,mid:_}=yield this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:A,producerId:C}=yield this.safeEmitAsPromise("produce",{offer:m,kind:t.kind,paused:i?!t.enabled:!1,appData:Z(B({},o||{}),{mid:_})}),M=yield g(A);return{producerId:C,localId:M,rtpSender:v}}),"producer"),p=new lO({id:a,localId:d,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:s,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(a,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p})}};class rh extends ki{constructor(){super(),f(this,"_mapMidTransceiver",new Map),f(this,"_enableHighBitrate",!1),f(this,"_enableStereo",!1),this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class nh extends rh{constructor(){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1)}static createFactory(){return()=>new nh}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this._pc=new RTCPeerConnection(B({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`send() [kind:${r.kind}, track.id:${r.id}]`);const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(r.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(i){const m=h.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`codecOption.parameters:${JSON.stringify(i.parameters)}`);const g=((o=m.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const v=Array.from(new Set(g).values());m.sdpFmtpLine=v.join(";")}p.push(m)}l.info(`selected codecs: ${JSON.stringify(p)}`),a.setCodecPreferences(p)}const d=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(d),i&&i.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),d.sdp+=`a=rtcp-fb:111 nack\r
31
+ `}return{offerSdp:d,callback:h=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=B(B({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")})}pauseReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")})}resumeReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class zc extends rh{constructor(e){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1),f(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new zc(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection(B({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")})}restartIce(){return u(this,null,function*(){l.debug("Firefox60::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,screenShare:i}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${r.kind}, track.id:${r.id}]`),l.debug("Firefox60::creating new transceiver");const s=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},o=this._pc.addTransceiver(r,B({direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream]},s));if(!this.supportsSendEncodings&&n){n.reverse();const d=o.sender.getParameters();d.encodings=n,yield o.sender.setParameters(d)}const a=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(a),r.kind==="audio"){const d=this._enableStereo,h=this._enableHighBitrate?d?128e3:64e3:d?64e3:32e3;a.sdp=a.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${d?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:a,callback:d=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),yield this._pc.setRemoteDescription(d),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),s=i.encodings.length-1-r;i.encodings.forEach((o,a)=>{a>=s?o.active=!0:o.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=B(B({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})}),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class ih extends rh{constructor(){super(),f(this,"_direction"),f(this,"_pc"),f(this,"_sendWebStream",new MediaStream),f(this,"_sendScreenShareStream",new MediaStream),f(this,"_transportReady",!1)}static createFactory(){return()=>new ih}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection(B({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("Safari12::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${r.kind}, track.id: ${r.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),d=RTCRtpSender.getCapabilities(r.kind);l.info(`Safari12::senders available params: ${JSON.stringify(d)}`);const h=[];if(i){const m=d.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(i.parameters)}`);const g=((o=m.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const v=[...new Set(g).values()];m.sdpFmtpLine=v.join(";")}h.push(m)}l.info(`Safari12::selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h);const p=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(p),r.kind==="audio"){const m=this._enableStereo,g=this._enableHighBitrate?m?128e3:64e3:m?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${m?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${g}`)}return{offerSdp:p,callback:m=>u(this,null,function*(){return l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(m)}]`),yield this._pc.setRemoteDescription(m),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=B(B({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}receive(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}})}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)})}}}function hO(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=uf.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(e.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(e.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"}))return"Safari11";if(e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(r.name&&r.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(n){const i=Number(n[1]);return i>=74?"Chrome74":i>=70?"Chrome70":i>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class sy{constructor({handlerName:e,handlerFactory:r}={}){if(f(this,"handlerFactory"),f(this,"_handlerName"),f(this,"_observer"),l.debug("constructor()"),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)l.debug(`Device::constructor() | handler given: ${e}`);else if(e=hO(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=nh.createFactory();break;case"Safari12":this.handlerFactory=ih.createFactory();break;case"Firefox60":this.handlerFactory=zc.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=zc.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new ft}get handlerName(){return this._handlerName}createSendTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o})}createRecvTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s})}}let pO=class extends sy{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){const a=bi(),d=new uO({id:a,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",d),d}};var Pt;class mO{constructor(e){T(this,Pt,void 0),S(this,Pt,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Pt).sendMessagePromiseWithTimeout({event:ce.joinRoom,protobuf:tv.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(ce.createWebRTCTransport,Qg.toBinary(e))).payload,{transportId:n,description:i}=ju.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Pt).sendMessagePromise(ce.produce,iv.toBinary(e))).payload,s=fv.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(ce.consume,Hu.toBinary(e))).payload,{consumerIdsMap:{map:n}}=mv.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(ce.closeProducer,ov.toBinary(e))).payload,{description:n}=gv.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Pt).sendMessagePromise(ce.closeConsumer,av.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Pt).sendMessagePromise(ce.hostControlPeer,lv.toBinary(n))).payload;if(!i)return!1;const{status:s}=Sv.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Pt).sendMessagePromise(ce.hostControlAllPeers,uv.toBinary(r))).payload;if(!n)return!1;const{status:i}=Ev.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1},r=(yield c(this,Pt).sendMessagePromise(ce.kickAll,Wu.toBinary(e))).payload;if(!r)return!1;const{status:n}=yv.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(ce.kickPeer,cv.toBinary(e))).payload;if(!r)return!1;const{status:n}=vv.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Pt).sendMessagePromise(ce.changeDisplayName,dv.toBinary(e))).payload;if(!r)return!1;const{status:n}=Tv.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Pt).sendMessagePromise(ce.selfJoinComplete,rv.toBinary(e))).payload;return Vc.fromBinary(r)})}}Pt=new WeakMap;var rr=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t))(rr||{}),gs=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(gs||{});const fO=2e3;var rs,Oo,Wr;class gO extends Yv{constructor(e,r){super(),T(this,rs),f(this,"_device"),f(this,"_sendTransport"),f(this,"_recvTransport"),f(this,"_consumers"),f(this,"_producers"),f(this,"_producerStatus"),f(this,"_producerIdToConsumerIdMap"),f(this,"_socket"),f(this,"_socketHandler"),f(this,"_metrics",{sendTransportFailureCount:0,recvTransportFailureCount:0,consumerCreationFailureCount:0,producerCreationFailureCount:0,lastConnectionTime:0}),f(this,"_transportDisconnectedTimer"),f(this,"_iceTransportPolicy","all"),f(this,"_producerNotReadyFailureCount",0),f(this,"transportConnectionStatus"),f(this,"transportState"),f(this,"transportDisconnected"),T(this,Wr,void 0),S(this,Wr,e),this._device=new pO({}),this._socket=r,c(this,rs,Oo).mediaState={recv:{state:rr.NEW,reconnected:!1},send:{state:rr.NEW,reconnected:!1}},this.transportDisconnected={recv:!1,send:!1},this._socketHandler=new mO(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this._transportDisconnectedTimer={recv:void 0,send:void 0}}setupTransports(e){return u(this,null,function*(){var r,n,i,s,o,a,d,h;Q.hasFeature(ie.FORCE_RELAY)&&(l.info("Forcing relay"),this._iceTransportPolicy="relay");const p=yield Ke().getICEServers().catch(g=>(l.warn(`failed to get iceservers from server: ${g.message}`),[])),m=[];if(e.send){const g=this.createSendTransport({iceServers:p,additionalSettings:{encodedInsertableStreams:(r=c(this,Wr).getValue("modules").e2ee)==null?void 0:r.enabled},config:{enableHighBitrate:(s=(i=(n=c(this,Wr).getValue("defaults").mediaConfiguration)==null?void 0:n.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(d=(a=(o=c(this,Wr).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:a.enableStereo)!=null?d:!1},iceTransportPolicy:this._iceTransportPolicy});m.push(g)}if(e.recv){const g=this.createRecvTransport({iceServers:p,additionalSettings:{encodedInsertableStreams:(h=c(this,Wr).getValue("modules").e2ee)==null?void 0:h.enabled},iceTransportPolicy:this._iceTransportPolicy});m.push(g)}yield Promise.all(m)})}stopAllTransports(){var e,r,n,i;l.info("closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n;l.info("sendTransport::initializing_transport",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});const i=this._device.createSendTransport(e);this._transportDisconnectedTimer.send=void 0,l.info("sendTransport::initialized_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),this.handleTransport(i),l.info("sendTransport::connecting_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}});try{yield Ir((s,o)=>u(this,null,function*(){var a,d;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(a=this._sendTransport)==null?void 0:a.id,serverId:(d=this._sendTransport)==null?void 0:d.serverId,type:"send"}});return}if(!this.socket.isConnected){o(new Error("socket is not connected"));return}if(i.connectionState==="closed"){o(new Error("transport is closed"));return}s>0&&l.debug(`retrying transport connect, count: ${s}`,{transport:{id:i.id,serverId:i.serverId,type:"send"}});try{yield i.connect()}catch(h){if(l.error(`failed to connect send transport: ${i.id}`,{error:h,transport:{id:i.id,serverId:i.serverId,type:"send"},country:y.location.country}),h.message==="ice connection failed"){o(h);return}throw this._metrics.sendTransportFailureCount+=1,h}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),this._producerNotReadyFailureCount=0,this._sendTransport=i,$.configureSendTransport(i)}catch(s){throw l.error(`failed to connect send transport after retry:${i.id}`,{error:s,transport:{id:i==null?void 0:i.id,serverId:i==null?void 0:i.serverId,type:"send"}}),i.close(),i.removeAllListeners(),this._metrics.sendTransportFailureCount+=1,this.handleErrors("rejoin"),s}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i;l.info("recvTransport::initializing_transport",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});const s=this._device.createRecvTransport(Z(B({},e),{additionalSettings:Z(B({},(i=e.additionalSettings)!=null?i:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.recv=void 0,l.info("recvTransport::initialized_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),this.handleTransport(s),l.info("recvTransport::connecting_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}});try{yield Ir((o,a)=>u(this,null,function*(){var d,h;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(d=this._recvTransport)==null?void 0:d.id,serverId:(h=this._recvTransport)==null?void 0:h.serverId,type:"recv"}});return}if(!this.socket.isConnected){a(new Error("socket is not connected"));return}if(s.connectionState==="closed"){a(new Error("transport is closed"));return}o>0&&l.debug(`retrying transport connect, count: ${o}`,{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}});try{yield s.connect()}catch(p){if(l.error(`fail to connect recv transport: ${s.id}`,{error:p,transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"},country:y.location.country}),p.message==="ice connection failed"){a(p);return}throw this._metrics.recvTransportFailureCount+=1,p}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),this.producerIdToConsumerIdMap.clear(),this._recvTransport=s,$.configureRecvTransport(s)}catch(o){throw l.error(`failed to connect recv transport after retry:${s.id}`,{error:o,transport:{id:s==null?void 0:s.id,serverId:s==null?void 0:s.serverId,type:"recv"}}),s.close(),s.removeAllListeners(),this._metrics.recvTransportFailureCount+=1,this.handleErrors("rejoin"),o}})}handleTransport(e){const{direction:r,id:n}=e,i=r==="recv";if(e.on("connect",(s,o,a)=>u(this,[s,o,a],function*({offer:d},h,p){try{const m={consuming:i,description:{sdp:d.sdp,type:d.type,target:i?zt.SUBSCRIBER:zt.PUBLISHER}},{transportId:g,answer:v}=yield this._socketHandler.connectTransport(m);e.setServerId(g),h({answer:v})}catch(m){l.error(`${i?"consumer":"producer"} transport connection error:`,{error:m,transport:{id:n,serverId:e.serverId,type:r},country:y.location.country}),p(m)}})),e.on("connectionstatechange",s=>u(this,null,function*(){this.updateTransportState({state:s,direction:r}),l.info(`${i?"consumer":"producer"} transport connectionState:`,{transport:{id:n,serverId:e.serverId,type:r,status:s}});const o=()=>{const a=this._transportDisconnectedTimer[r];a!==void 0&&(clearTimeout(a),this._transportDisconnectedTimer[r]=void 0)};switch(s){case"connected":o(),this._metrics.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r]=setTimeout(()=>{this.triggerTransportReconnection(e)},fO);break;case"failed":if(e.closed)return;o(),this.triggerTransportReconnection(e);break}})),e.on("icecandidate",s=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:s})})),e.on("datachannel:events",(s,o)=>u(this,null,function*(){var a,d;l.debug("got data channel message on event:",{rtcChannel:{label:s,message:o}});try{switch(o.type){case"negotiation":{e.awaitQueue.push(()=>u(this,null,function*(){return this.negotiateOverDC(o,qc(o),s,e)}));break}case"handshake":{const h={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(s,qc(o),h);break}case"consumer_toggle":{this.handleConsumerToggle(o.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(a=o.payload)==null?void 0:a.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":{this.handleErrorOverDC(o.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${o.type}`);break}}catch{l.error(`Unable to handle the incoming datachannel message on channel ${s}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s",{country:y.location.country}),this.handleErrors("reconnectRecvTransport"))}),e.on("negotiate",(s,o,a)=>u(this,[s,o,a],function*({description:d},h,p){try{const m={sdp:d==null?void 0:d.sdp,type:d==null?void 0:d.type},g=yield this.negotiate(e,m);h({answer:g})}catch(m){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:m}),p(m)}})),!i){e.on("produce",(s,o,a)=>u(this,[s,o,a],function*({offer:d,kind:h,paused:p,appData:m},g,v){var _;const A=bu(d.sdp).media.filter(M=>h==="video"?M.type==="video":M.type==="audio").at(-1).msid,C={description:{sdp:d.sdp,type:d.type,target:zt.PUBLISHER},paused:p,kind:h,msid:A,appData:JSON.stringify(m),screenShare:(_=m.screenShare)!=null?_:!1};try{const{answer:M,producerId:N}=yield this._socketHandler.produce(C);g({answer:M,producerId:N})}catch(M){l.error("create producer error:",M),v(M)}}));return}e.on("consume_peer",(s,o,a)=>u(this,[s,o,a],function*({producingPeerId:d,producerId:h},p,m){l.info("consumePeer:",d);const g={producingPeerId:d,producerId:h};try{const v=yield this._socketHandler.consume(g);l.debug(`consumePeer response for ${d}:`,{consumerStateMap:v});const _=new Map;Object.entries(v).forEach(([A,C])=>{var M,N,J;let P={};try{P=JSON.parse(C.producerState.appData)}catch{}_.set(A,{consumerId:C.consumerId,trackId:(M=C.producerTrack)==null?void 0:M.trackId,streamId:C.producerTrack.streamId,kind:C.producerState.kind===Ft.VIDEO?"video":"audio",appData:P,screenShare:(N=C.producerState)==null?void 0:N.screenShare,paused:(J=C.producerState)==null?void 0:J.pause,producingPeerId:d})}),p({consumersMap:_})}catch(v){l.error("consumePeer error:",{error:v}),m(v)}})),e.on("consume",(s,o,a)=>u(this,[s,o,a],function*({producerId:d,producingPeerId:h},p,m){var g,v,_,A,C,M,N,J,P;const G={producingPeerId:h,producerId:d};try{const W=(yield this._socketHandler.consume(G))[d];let ae={};try{ae=JSON.parse((g=W.producerState)==null?void 0:g.appData)}catch{}l.info("consumer create response:",{consumer:{remotelyPaused:(v=W.producerState)==null?void 0:v.pause,producerId:(_=W.producerState)==null?void 0:_.producerId,kind:(C=(A=W.producerState)==null?void 0:A.kind)==null?void 0:C.toString(),appData:Z(B({},ae),{screenShare:(M=W.producerState)==null?void 0:M.screenShare}),id:W.consumerId},consumerState:W}),p({consumerId:W.consumerId,screenShare:(N=W.producerState)==null?void 0:N.screenShare,trackId:(J=W.producerTrack)==null?void 0:J.trackId,streamId:W.producerTrack.streamId,kind:W.producerState.kind===Ft.VIDEO?"video":"audio",paused:(P=W.producerState)==null?void 0:P.pause,appData:ae})}catch(W){l.error("error during consuming on server:",W),m(W)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Qr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Qr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},m){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:zt.PUBLISHER}};try{const v=yield this._socketHandler.closeProducer(g),_={sdp:v==null?void 0:v.sdp,type:v==null?void 0:v.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),m({answer:_})}catch(v){l.error("producer close error",v)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[ne.MIC,ne.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Qr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Qr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),this._metrics.producerCreationFailureCount+=1,o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!Q.hasFeature(ie.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(ne.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(ne.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),I.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),I.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumers(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;if(e.every(i=>this.getProducer(i.producerId))){l.warn("Cancelled consumer creation for local producer");return}const r=3,n=(i,s=0)=>u(this,null,function*(){try{return yield this._recvTransport.consume(i)}catch(o){if(o instanceof Xv){if(this._metrics.consumerCreationFailureCount+=1,s<=r)return n(i,s+1);throw o}throw o instanceof Qv&&(this._metrics.recvTransportFailureCount+=1),l.error("Error in consume request",o),o}});try{let i=yield n(e);yield Ir(s=>u(this,null,function*(){s>0&&l.warn(`retrying consumers: attempt: ${s}`,{peerIds:e.map(({producingPeerId:a})=>a)});const o=[];i.forEach((a,d)=>{if(a.status==="rejected"){this._metrics.consumerCreationFailureCount+=1,o.push(e[d]);return}this._initConsumer(a.value)}),o.length&&(i=yield n(o))}))}catch(i){l.error("failed to create consumers",{error:i}),this._metrics.consumerCreationFailureCount+=1,this.handleErrors("reconnectRecvTransport")}})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&I.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,Wr).getValue("modules").e2ee.enabled&&I.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(ce.toggleConsumer,Fc.toBinary(r)),e.pause(),I.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(ce.toggleConsumer,Fc.toBinary(n)),r.resume(),I.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);d&&(this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0))})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:zt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(ce.renegotiateSessionDescription,Xg.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),I.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),I.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;switch(n){case"consumer":{this._metrics.consumerCreationFailureCount+=1,l.error(`Error in consumer creation, this should not happen: ${n}, ${i}, ${s}`);return}case"producer":{if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleErrors("reconnectSendTransport");return}this._producerNotReadyFailureCount+=1,this._metrics.producerCreationFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&this.handleErrors("reconnectSendTransport");l.error(`Unrecognized error: ${n}, ${i}, ${s}`);break}default:l.error(`Unrecognized error: ${n}, ${i}, ${s}`)}})}handleErrors(e){return u(this,null,function*(){switch(e){case"rejoin":{l.warn("rejoining room"),this.emit("rejoin");break}case"reconnectSendTransport":{l.warn("reconnecting send transport"),this.triggerTransportReconnection(this._sendTransport);break}case"reconnectRecvTransport":{this.triggerTransportReconnection(this._recvTransport);break}default:l.error(`Could not handle error, unrecognized action ${e}`)}})}triggerTransportReconnection(e){l.info("triggerTransportReconnection::reconnecting_transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const r=Q.hasFeature(ie.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),n=Q.hasFeature(ie.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);if(!r)return;const i=e.direction==="send"?"sendTransportFailureCount":"recvTransportFailureCount";n&&this._socket.isConnected&&(this._metrics[i]>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._metrics[i]+=1),this.updateTransportState({state:rr.RECONNECTING,direction:e.direction}),this.emit("reconnect_transport",e)}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,rs,Oo).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,rs,Oo).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),I.emit(w.TRANSPORT_STATE_UPDATE,B({transport:n},c(this,rs,Oo).mediaState[n]))}}rs=new WeakSet,Oo=function(){return c(this,Wr).getValue("connectionHandler")},Wr=new WeakMap;var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,me=(t,e,r,n)=>{for(var i=n>1?void 0:n?yO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&vO(e,r,i),i},_t,fe,Mr,$i,qn,zn,Ma,Da,Oa,un,lo,Dr,hn,Lm;const oy=(Lm=class extends Kv{constructor(t,e){var r,n;super(),T(this,Dr),T(this,_t,void 0),T(this,fe,void 0),T(this,Mr,void 0),T(this,$i,void 0),T(this,qn,void 0),T(this,zn,void 0),T(this,Ma,void 0),T(this,Da,void 0),T(this,Oa,void 0),T(this,un,void 0),T(this,lo,void 0),f(this,"legacyMode"),f(this,"roomNodeUrl"),f(this,"peerDisplayName"),f(this,"e2ee"),f(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.mediaJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,S(this,_t,a),S(this,Mr,!1),S(this,fe,new gO(t,a)),this.maxPreferredStreams=6,S(this,un,new Set),S(this,$i,!1),S(this,qn,0),S(this,zn,new fs),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,$.legacySwitch(o),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),S(this,Ma,Zr(()=>u(this,null,function*(){if(!c(this,Dr,hn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(I.emit(w.RESET_PRODUCER_STATE),I.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,Da,Zr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({send:!0}),l.info("send transport reconected!"),I.emit(w.RESET_PRODUCER_STATE)}),1e3)),S(this,Oa,Zr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports({recv:!0}),l.info("recv transport reconnected!"),I.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Dr,hn).mediaState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new oy(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,fe)}get rejoinRoom(){return c(this,Ma)}get mediaJoined(){return c(this,Dr,hn).mediaJoined}set mediaJoined(t){c(this,Dr,hn).mediaJoined=t}reset(t=!0){var e,r,n,i;(r=(e=c(this,fe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,fe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,un).clear(),t&&(this.partialJoinRoomPromise=void 0,c(this,zn).stop(),c(this,fe).stopAllTransports(),c(this,fe).reset(),S(this,zn,new fs))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,Mr)}`),!(!t||c(this,Mr))&&(t.direction==="send"?yield c(this,Da).call(this,t):yield c(this,Oa).call(this,t))})}setupTransports(){return u(this,null,function*(){yield c(this,fe).setupTransports({send:!0,recv:!0})})}stopAllProducers(){return u(this,null,function*(){yield c(this,fe).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){c(this,Dr,hn).mediaJoinAttempted=!0,S(this,Mr,!0),this.reset(s);const a=Ke().ipInfo;if(a!=null&&a.loc&&!c(this,lo)){const h=a.loc.split(",");S(this,lo,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,zn).push(()=>this._joinRoom(r,n,i,o,c(this,lo)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||I.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const{ipInfo:i}=Ke();let s=n;if(i!=null&&i.loc&&!n){const[o,a]=i.loc.split(",").map(parseFloat);s={latitude:o,longitude:a}}this.maxPreferredStreams=this.context.getValue("maxPreferredStreams"),yield Ir((o,a)=>u(this,null,function*(){if(!c(this,_t).isConnected){a(new Error("socket is not connected"));return}o>0&&l.warn(`retrying sending join room request, count: ${o}`);try{yield this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,s)}catch(d){throw l.error("failed to send join room request, error:",{error:d}),d}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports()})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,zn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o)}catch(a){l.error("error in partial join room",{error:a})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:n,roomViewType:"groupCall",deviceInfo:Z(B({},Te.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};$.roomJoined(a)})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,S(this,$i,!0),S(this,Mr,!1),this.maxPreferredStreams=t!=null?t:6,!0}catch(t){return l.error("error on completing join room:",{error:t}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){c(this,fe).stopAllTransports(),S(this,$i,!1),c(this,Dr,hn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,_t).sendMessagePromise(ce.leaveRoom,nv.toBinary(t)).then(e=>{var r;(r=pv.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),$.callEnded(),y.destruct()})}getConsumers(){return c(this,fe).consumers}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}deactivatePeers(t,e="default"){return u(this,null,function*(){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;yield Promise.all(n.map(i=>{const s=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!s){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(s)}))})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():this.sfuHandler.createConsumers(t)})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){const e=t.reduce((r,n)=>{const i=this.sfuHandler.producerIdToConsumerIdMap.get(n.producerId);return i?(r.push(i),r):(l.warn(`consumer not found in deactivate producers: ${n.producerId}`),r)},[]);yield this.sfuHandler.closeConsumers(e)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;if(c(this,fe).producers.has(ne.WEBCAM)){const i=c(this,fe).producers.get(ne.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,fe).removeProducer(ne.WEBCAM)}const r={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(!Uc(this.context,"disableSimulcast")&&Q.hasFeature(ie.ENABLE_HIVE_SIMULCAST)){let i=t.getConstraints().width;i in wm||(i=320),r.encodings=wm[i],((e=r.encodings)==null?void 0:e.length)===1&&l.info("Simulcast will not be used for the webcam producer")}else l.info("Simulcast will not be used for the webcam producer");const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,fe).createProducer(ne.WEBCAM,r,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,fe).createProducer(ne.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,fe).createProducer(ne.SCREENSHARE_AUDIO,s,i)}$.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,fe).producers.has(ne.MIC)){const n=c(this,fe).producers.get(ne.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,fe).removeProducer(ne.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,fe).createProducer(ne.MIC,e,r)}catch(e){throw new b(e)}})}pauseMic(){const t=c(this,fe).producers.get(ne.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,_t).sendMessage(ce.toggleProducer,Mn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,fe).producers.get(ne.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,_t).sendMessage(ce.toggleProducer,Mn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,fe).producers.get(ne.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,_t).sendMessage(ce.toggleProducer,Mn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,fe).producers.get(ne.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,_t).sendMessage(ce.toggleProducer,Mn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,fe).removeProducer(ne.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,fe).removeProducer(ne.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),$.screenShareStop(),yield c(this,fe).removeProducer(ne.SCREENSHARE_VIDEO),yield c(this,fe).removeProducer(ne.SCREENSHARE_AUDIO),c(this,un).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,fe).removeProducer(ne.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,fe).removeProducer(ne.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.hiveSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.hiveSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,_t).sendMessagePromise(ce.globalPinPeer,sv.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,un).add(t.consumerPeerId),c(this,un).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,_t).on(ce.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=kv.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),I.emit(w.NEW_PRODUCER,{peerId:e,producer:Z(B({},r),{kind:r.kind===Ft.AUDIO?"audio":"video",producingPeerId:e})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,_t).on(ce.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:n,pause:i,producerId:s}}=$l.fromBinary(t),o=n===Ft.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${o}, paused:${i}, payload: ${JSON.stringify($l.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&i&&I.emit(o==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),e===this.peerId)return;I.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:i,kind:o}),Array.from(this.getConsumers().values()).filter(a=>a.producerId===s).forEach(a=>{a.paused!==i&&(l.debug(`consumer state mismatched for ${a.id}. updating consumer pause state ${a.paused} to ${i}`),i?(a.pause(),I.emit(w.CONSUMER_PAUSED,{id:a.id})):(a.resume(),I.emit(w.CONSUMER_RESUMED,{id:a.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,_t).on(ce.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Bc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,un).delete(e),this.sfuHandler.cleanupConsumers(e),I.emit(w.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,_t).on(ce.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=_v.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),I.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),I.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,_t).on(ce.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,Mr)&&!c(this,$i)||(l.warn("media hub termination broadcast received, rejoining room"),I.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSFUEvents(){c(this,fe).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,fe).on("rejoin",t=>{var e;if(((e=c(this,Dr,hn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,qn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Mr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,qn,c(this,qn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,qn)}]`),this.mediaJoined=!1,I.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&I.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),$.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&I.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},_t=new WeakMap,fe=new WeakMap,Mr=new WeakMap,$i=new WeakMap,qn=new WeakMap,zn=new WeakMap,Ma=new WeakMap,Da=new WeakMap,Oa=new WeakMap,un=new WeakMap,lo=new WeakMap,Dr=new WeakSet,hn=function(){return this.context.getValue("connectionHandler")},Lm);let le=oy;me([y.trace("HiveNodeClient.reset",{country:y.location.country})],le.prototype,"reset",1);me([y.trace("HiveNodeClient.reconnect",{country:y.location.country})],le.prototype,"reconnectTransport",1);me([y.trace("HiveNodeClient.setupTransport")],le.prototype,"setupTransports",1);me([y.trace("HiveNodeClient.stopAllProducers")],le.prototype,"stopAllProducers",1);me([y.trace("HiveNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([y.trace("HiveNodeClient.completeJoinRoom")],le.prototype,"completeJoinRoom",1);me([y.trace("HiveNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([y.trace("HiveNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([y.trace("HiveNodeClient.deactivatePeers")],le.prototype,"deactivatePeers",1);me([y.trace("HiveNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([y.trace("HiveNodeClient.pauseConsumers")],le.prototype,"pauseConsumers",1);me([y.trace("HiveNodeClient.resumeConsumers")],le.prototype,"resumeConsumers",1);me([y.trace("HiveNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([y.trace("HiveNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([y.trace("HiveNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([y.trace("HiveNodeClient.shareMic")],le.prototype,"shareMic",1);me([y.trace("HiveNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([y.trace("HiveNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([y.trace("HiveNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([y.trace("HiveNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([y.trace("HiveNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([y.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([y.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([y.trace("HiveNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([y.trace("HiveNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([y.trace("HiveNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([y.trace("HiveNodeClient.kickPeer")],le.prototype,"kick",1);me([y.trace("HiveNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([y.trace("HiveNodeClient.muteAll")],le.prototype,"muteAll",1);me([y.trace("HiveNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([y.trace("HiveNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([y.trace("HiveNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([y.trace("HiveNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([y.trace("HiveNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);me([y.trace("HiveNodeClient.init")],le,"init",1);class SO{constructor(){f(this,"_orderedArray"),f(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const i=this.add(e,r);return n!==i?i:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class EO{constructor(){f(this,"_activeSpeakerPeers"),f(this,"_compulsoryPeers"),this._activeSpeakerPeers=new SO,this._compulsoryPeers=new Set}add(e,r){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,r)}delete(e){l.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}const ay=new EO;var TO=Object.defineProperty,kO=Object.getOwnPropertyDescriptor,Xt=(t,e,r,n)=>{for(var i=n>1?void 0:n?kO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&TO(e,r,i),i};const _O=["ACTIVE_GRID","PAGINATED","MANUAL"];var Or,Nr,pn,Ji,Wt,xm;let Ot=(xm=class extends Yt{constructor(t,e,r){super(),T(this,Nr),f(this,"waitlisted"),f(this,"joined"),f(this,"active"),f(this,"videoSubscribed"),f(this,"audioSubscribed"),f(this,"pinned"),f(this,"all"),T(this,Or,void 0),T(this,Ji,void 0),T(this,Wt,void 0),f(this,"rateLimitConfig",{maxInvocations:5,period:1}),f(this,"viewMode"),f(this,"currentPage"),f(this,"lastActiveSpeaker"),f(this,"selectedPeers",ay),S(this,Or,t),S(this,Ji,e),S(this,Wt,r),this.waitlisted=new co,this.joined=new co,this.videoSubscribed=new co,this.audioSubscribed=new co,this.active=this.videoSubscribed,this.pinned=new co,this.all=new Q1,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return c(this,Or).getValue("pip")}get socketJoined(){var t;return((t=c(this,Or).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0}get mediaJoined(){var t;return((t=c(this,Or).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){I.on(w.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Or).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){return c(this,Nr,pn).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new b("0 <= Max active participants count limit <= 24","1203");c(this,Nr,pn).maxPreferredStreams=t,this.mediaJoined&&I.emit(w.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/(this.maxActiveParticipantsCount-t))}return 0}acceptWaitingRoomRequest(t){var e,r;if(!this.socketJoined)throw new b("Can`t accept waiting room request without joining room","1205");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return c(this,Wt).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,Wt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!this.socketJoined)throw new b("Can`t reject waiting room request without joining room","1205");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;c(this,Wt).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>_O.includes(e))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new b(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,Nr,pn)instanceof le))throw new b("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,I.emit(w.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,I.emit(w.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(r.includes("audio")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(s);const o=s.producers.find(a=>a.kind==="audio"&&!a.screenShare);o&&n.push(o)}if(r.includes("video")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{video:!0}),this.audioSubscribed.add(s);const o=s.producers.find(a=>a.kind==="video"&&!a.screenShare);o&&n.push(o)}if(r.includes("screenshareAudio")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareAudio:!0});const o=s.producers.find(a=>a.kind==="audio"&&a.screenShare);n.push(o)}if(r.includes("screenshareVideo")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareVideo:!0});const o=s.producers.find(a=>a.kind==="video"&&a.screenShare);n.push(o)}}}),yield c(this,Nr,pn).createConsumers(n)})}unsubscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new b("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(r.includes("audio")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{audio:!1});const o=s.producers.find(a=>a.kind==="audio"&&!a.screenShare);o&&n.push(o)}if(r.includes("video")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{video:!1});const o=s.producers.find(a=>a.kind==="video"&&!a.screenShare);o&&n.push(o)}if(r.includes("screenshareAudio")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareAudio:!1});const o=s.producers.find(a=>a.kind==="audio"&&a.screenShare);n.push(o)}if(r.includes("screenshareVideo")){s.manualProducerConfig=Z(B({},s.manualProducerConfig),{screenshareVideo:!1});const o=s.producers.find(a=>a.kind==="video"&&a.screenShare);n.push(o)}}}),yield c(this,Nr,pn).closeConsumers(n)})}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,s))}setPage(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw l.error("DyteParticipants::invalid_page_number"),new b(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,I.emit(w.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.mediaJoined)throw new b("Can`t disable all audio without joining room","1205");if(c(this,Ji).permissions.canAllowParticipantAudio)return c(this,Nr,pn).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new b("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_video"),!this.mediaJoined)throw new b("Can`t disable all video without joining room","1205");if(c(this,Ji).permissions.canAllowParticipantVideo)return c(this,Nr,pn).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new b("Unauthorized: User does not have permission to disable peer video.","1201")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield I.emitAsync(w.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Or).getValue("viewType")!=="LIVESTREAM"&&!this.socketJoined)throw new b("Can`t kick all without joining room","1205");if(!c(this,Ji).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new b("Unauthorized: User does not have permission to kick peers.","1201");const t=Q.hasFeature(ie.PROPAGATE_KICK_ALL);c(this,Wt).kickAll(t)})}broadcastMessage(t,e,r){return u(this,null,function*(){if(l.info("DyteParticipants::broadcastMessage"),!this.socketJoined)throw new b("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new b("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)yield c(this,Wt).broadcastToMeetings(t,r.meetingIds,e);else{let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var s;return(s=r.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),yield c(this,Wt).broadcastToPeers(t,n,e)}else yield c(this,Wt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,Wt).getRoomPeers(t,e,r)).peers.map(on.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];if(!n.length)throw new b("Cannot update permissions, no valid userIDs found","1204");c(this,Wt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,Wt).getRoomPeersNonPaginated()})}},Or=new WeakMap,Nr=new WeakSet,pn=function(){return c(this,Or).getValue("roomNodeClient")},Ji=new WeakMap,Wt=new WeakMap,xm);Xt([y.trace("DyteParticipants.setViewMode")],Ot.prototype,"setViewMode",1);Xt([y.trace("DyteParticipants.setPage")],Ot.prototype,"setPage",1);Xt([y.trace("DyteParticipants.disableAllAudio")],Ot.prototype,"disableAllAudio",1);Xt([y.trace("DyteParticipants.disableAllVideo")],Ot.prototype,"disableAllVideo",1);Xt([y.trace("DyteParticipants.disablePeerAudio")],Ot.prototype,"disableAudio",1);Xt([y.trace("DyteParticipants.disablePeerVideo")],Ot.prototype,"disableVideo",1);Xt([y.trace("DyteParticipants.kickPeer")],Ot.prototype,"kick",1);Xt([y.trace("DyteParticipants.kickAll")],Ot.prototype,"kickAll",1);Xt([y.trace("DyteParticipants.broadcastMessage"),Bt(Ts,"rateLimitConfig")],Ot.prototype,"broadcastMessage",1);Xt([y.trace("DyteParticipants.getAllJoinedPeers"),Bt({maxInvocations:10,period:60})],Ot.prototype,"getAllJoinedPeers",1);Xt([y.trace("DyteParticipant.updatePermissions"),Bt({maxInvocations:1e3,period:60})],Ot.prototype,"updatePermissions",1);Xt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Ot.prototype,"getParticipantsInMeetingPreJoin",1);Ot=Xt([St("1200")],Ot);var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,bs=(t,e,r,n)=>{for(var i=n>1?void 0:n?wO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&bO(e,r,i),i};const cy=class{constructor(t,e,r){f(this,"participants"),f(this,"self"),f(this,"selectedPeers",ay),f(this,"maxSpatialLayerUpdates",new Map),f(this,"consumerPeerMap"),f(this,"roomSocketHandler"),f(this,"context"),f(this,"videoPeerConsumerMap",new Map),f(this,"updateConsumerSpatialLayers",Zr(()=>{const n={},i=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(i.entries()).forEach(([s,o])=>{n[o]===void 0&&(n[o]={layer:o,consumerIds:[]}),n[o].consumerIds.push(s)}),Object.keys(n).forEach(s=>{const o=n[s];l.log(`Switching max spatial layer to ${o.layer}`,{consumerIds:o.consumerIds}),this.roomNodeClient.switchConsumersToLayer(o.consumerIds,o.layer)})},2e3)),f(this,"updateConsumers",(n,i)=>{l.info("Consuming producers",{producers:n}),l.info("Closing consumers for producers",{producers:i}),this.roomNodeClient.closeConsumers(i).then(()=>{this.roomNodeClient.createConsumers(n).catch(s=>l.error("Error activating peers",{error:s}))}).catch(s=>l.error("Error deactivating peers",{error:s}))}),f(this,"updateConsumersDebounced",Zr(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=r,this.participants=new Ot(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,e.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}waitingRoomRequestHandler(t){const e=t.requests.filter(n=>!this.participants.waitlisted.toArray().find(i=>i.userId===n.userId)),r=this.participants.waitlisted.toArray().filter(n=>!t.requests.find(i=>i.userId===n.userId));e.forEach(n=>this.participants.waitlisted.add(new tn(this.context,{id:n.peerId,displayName:n.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:n.userId,flags:{},isHost:!1,customParticipantId:n.customParticipantId,picture:n.picture,metadata:{preset_name:n.presetName}},this.self,this.roomSocketHandler))),r.forEach(n=>this.participants.waitlisted.delete(n.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return u(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,r=e.filter(a=>this.participants.joined.has(a)),n=Array.from(this.participants.pinned.keys()).filter(a=>!r.includes(a)),i=Array.from(this.participants.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),s=Math.max((t-1)*(this.roomNodeClient.maxPreferredStreams-r.length-n.length)),o=t*(this.roomNodeClient.maxPreferredStreams-r.length-n.length);return r.concat(n,i.slice(s,o))})}selectActivePeers(){return u(this,null,function*(){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(h=>h.stageStatus==="ON_STAGE").map(h=>(t.set(h.id,!0),h.id))),r=this.selectedPeers.peers,n=this.participants.pinned.toArray().reduce((h,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):h.push(p.id),h),[]),i=this.self.stageStatus==="ON_STAGE"?1:0,s=this.participants.maxActiveParticipantsCount-i,o=new Set(r.concat(n).filter(h=>h!==this.self.id&&t.has(h)));let a=Array.from(o);const d=s-o.size;if(d>=0){const h=e.filter(p=>!o.has(p)&&p!==this.self.id).slice(0,d);a=Array.from(o).concat(h)}else a=a.slice(0,s);return a})}updateActive(t,e){return u(this,null,function*(){const{page:r,createAllConsumers:n}=e!=null?e:{};let{strategies:i}=e!=null?e:{},s,o;switch(t){case"PAGINATED":{if(!r)return;s=yield this.selectPagePeers(r),l.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMap.bind(this)}),o=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{s=yield this.selectActivePeers(),l.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),o=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let a,d;const h=this.updateGrid(s,i);n?(a=this.mapPeerIdsToProducers(s,["audio","video","screenshare"]),d=[]):(a=[...this.mapPeerIdsToProducers([...h.video.add],["video"]),...this.mapPeerIdsToProducers([...h.audio.add],["audio"])],d=[...this.mapPeerIdsToProducers([...h.video.remove],["video"]),...this.mapPeerIdsToProducers([...h.audio.remove],["audio"])]),!(a.length===0&&d.length===0)&&o(a,d)})}computeActivateParticipants(t,e){const r=t.map((i,s)=>({peerId:i,priority:s+1})),n=e==null?void 0:e.map((i,s)=>({peerId:i,priority:-(s+1)}));r.push(...n!=null?n:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}fromSocketService(t){const e=cy.formatSocketServiceMessage(t);return new tn(this.context,Z(B({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var r,n;e?(r=this.pip)==null||r.enableSource(t):(n=this.pip)==null||n.disableSource(t)}onMediaJoined(t,e){if(!this.mediaJoined||t===this.self.id)return;const r=this.participants.joined.get(t);if(!r){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(n=>{n.kind===Ft.AUDIO&&!n.screenShare?r.setAudioEnabled(!n.pause):n.kind===Ft.VIDEO&&!n.screenShare&&(r.setVideoEnabled(!n.pause),this.updatePipSource(r.id,!n.pause)),r.producers.push(Z(B({},n),{producingTransportId:n.producingTransportId,kind:n.kind===Ft.AUDIO?"audio":"video",producingPeerId:t}))})}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),n=new Map(t),i=[],s=[],o=new Set(e),a=[];return r.forEach((d,h)=>{(!o.has(d)||!this.participants.joined.get(d))&&a.push(h)}),e.forEach(d=>{if(t.get(d))return;if(r.length<e.length){r.push(d),i.push(d);return}const h=a.shift();s.push(r[h]),r[h]=d,i.push(r[h])}),r.forEach((d,h)=>{o.has(d)||s.concat(r.splice(h,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!o.has(d))}),r.forEach(d=>{if(!this.participants.joined.get(d)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!n.get(d))}),t.emit("participantsUpdate"),[i,s]}updateParticipantsMap(t,e){const r=Array.from(t.keys()),n=[],i=[];return r.forEach(s=>{e.includes(s)||(t.delete(s,!0),i.push(s))}),e.forEach(s=>{t.get(s)||(t.add(this.participants.joined.get(s)),n.push(s))}),t.emit("participantsUpdate"),[n,i]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=Q.hasFeature(ie.DEBUG_SOCKET_JOIN);e&&l.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&l.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(j.leaveRoom,t=>{this.selectedPeers.delete(t.peer.peerId),this.onParticipantLeave(t.peer.peerId)}),I.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",t=>{const{acceptWaitingRequests:e}=t;e!==void 0&&(e?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),I.on(w.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),I.on(w.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),I.on(w.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),I.on(w.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),I.on(w.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),I.on(w.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),I.on(w.MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:n}){r!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:n})})),I.on(w.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:r})=>{const n=this.participants.joined.get(t);n&&(n.emit("poorConnection",{score:e,kind:r}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:r}))}),I.on(w.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:r,peerId:n,scoreStats:i})=>{var s;const o=e==="video"&&((s=r==null?void 0:r.screenShare)!=null?s:!1),a=this.participants.joined.get(n);a&&(a.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:n,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:n,scoreStats:i}))}),I.onAsync(w.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const r=this.participants.joined.get(e);yield this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),r?r.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),I.on(w.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({page:e,createAllConsumers:r}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:r})}))}onParticipantPinned(t){return u(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return u(this,null,function*(){var e,r,n;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((r=t.flags)!=null&&r.hidden_participant)&&!((n=t.flags)!=null&&n.hiddenParticipant)&&(this.participants.videoSubscribed.delete(t.id),this.participants.audioSubscribed.delete(t.id),this.participants.joined.add(t),this.participants.waitlisted.delete(t.id),t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&I.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),I.emit(w.PEER_JOINED_INTERNAL,t),this.self.config.viewType===vt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.roomNodeClient.maxPreferredStreams)return;const i=this.participants.currentPage;this.updateActive(i?"PAGINATED":"ACTIVE_GRID",{page:i})})}onParticipantLeave(t){return u(this,null,function*(){const e=this.participants.joined.get(t);this.participants.joined.delete(t,!0,!0),this.participants.pinned.delete(t,!0,!0),this.participants.waitlisted.delete(t,!0,!0),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&I.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:r}=this.participants,n=this.maxPreferredStreams*(r-1),i=this.participants.videoSubscribed.get(t);n===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=n?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):i&&this.updateActive(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:n,kind:i,appData:s,remotelyPaused:o,track:a,producerId:d,rtpReceiver:h}=(e=r.get(t))!=null?e:{};if(!n)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:i,peerId:n,appData:{supportsRemoteControl:s==null?void 0:s.supportsRemoteControl,screenShare:s==null?void 0:s.screenShare},remotelyPaused:o,producerId:d}}),{};const p=s;return i==="video"&&p.screenShare!==!0&&this.videoPeerConsumerMap.set(n,t),l.info("ParticipantController::processMedia",{consumer:{id:t,peerId:n,kind:i,appData:p,remotelyPaused:o,producerId:d}}),this.consumerPeerMap.set(t,{type:i,peerId:n,appData:p,remotelyPaused:o,producerId:d}),{peerId:n,kind:i,appData:p,remotelyPaused:o,track:a,producerId:d,rtpReceiver:h}}processConsumerClosed(t){const{peerId:e,type:r,appData:n,remotelyPaused:i,producerId:s}=this.consumerPeerMap.get(t)||{},o=this.participants.joined.get(e);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:n,kind:r,remotelyPaused:i,producerId:s}}),this.consumerPeerMap.delete(t),r==="video"&&n.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const a=[];n&&n.screenShare?(o.setScreenShareEnabled(!1),$.consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&a.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&a.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&a.push(o.audioTrack.id),$.consumerSharedMediaState(t,{audio:!1}),o.audioTrack=void 0):r==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&a.push(o.videoTrack.id),$.consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),n.e2ee&&a.forEach(d=>{I.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:r,appData:n,track:i,remotelyPaused:s,producerId:o,rtpReceiver:a}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:r,appData:n,remotelyPaused:s,producerId:o}});const d=this.participants.joined.get(e);if(d){if(n.e2ee&&I.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:a,track:i}),n.screenShare){r==="video"?d.screenShareTracks.video=i:r==="audio"&&(d.screenShareTracks.audio=i),d.setScreenShareEnabled(!0),$.consumerSharedMediaState(t,{screen:!0});return}r==="video"?(d.videoTrack=i,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),$.consumerSharedMediaState(t,{video:!0})):r==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),$.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:n,appData:i,remotelyPaused:s,producerId:o}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:i,remotelyPaused:s,producerId:o}});const a=this.participants.joined.get(e);a&&(n&&i.e2ee&&I.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:n.id}),r==="video"?(a.videoTrack=n,a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),$.consumerSharedMediaState(t,{video:!1})):r==="audio"&&(a.audioTrack=n,a.setAudioEnabled(a.audioEnabled),$.consumerSharedMediaState(t,{audio:a.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:n,track:i,appData:s,producerId:o,rtpReceiver:a}=this.processMedia(t);if(!e)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:n,appData:s,producerId:o}});const d=this.participants.joined.get(e);if(d){if(s.screenShare){r==="video"?d.screenShareTracks.video=i:r==="audio"&&(d.screenShareTracks.audio=i),(!n||this.self.permissions.isRecorder||Q.hasFeature(ie.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),s.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:n,appData:s,producerId:o}});return}r==="video"?(d.videoTrack=i,n||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),$.consumerSharedMediaState(t,{video:!n})):r==="audio"&&(d.audioTrack=i,n||d.setAudioEnabled(!0),$.consumerSharedMediaState(t,{audio:!n})),!n&&s.e2ee&&I.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:a,track:i})}}static formatSocketServiceMessage(t){var e,r,n,i,s,o;if(!t)return;const a=Ku(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:a,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:a,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(r=t.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(n=t.flags)==null?void 0:n.hiddenParticipant,hidden_participant:(i=t.flags)==null?void 0:i.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((o=t.flags)==null?void 0:o.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const r=(n,i)=>n.filter(({kind:s,screenShare:o})=>i.includes(s)||o&&i.includes("screenshare"));return t.flatMap(n=>{const i=this.participants.joined.get(n);if(i)return r(i.producers,e)}).filter(n=>!!n)}updateGrid(t,e){let r=[],n=[],i=[],s=[];return e.video&&([r,i]=e.video(this.participants.videoSubscribed,t)),e.audio&&([n,s]=e.audio(this.participants.audioSubscribed,t)),{video:{add:r,remove:i},audio:{add:n,remove:s}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(n=>{this.selectedPeers.add(n.peerId,n.priority)});const r=this.selectedPeers.activeSpeakerPeers.at(0);r!==void 0&&r!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=r,this.participants.emit("activeSpeaker",{peerId:r,volume:1})),e&&(this.participants.viewMode==="ACTIVE_GRID"?this.updateActive("ACTIVE_GRID"):this.participants.viewMode==="PAGINATED"&&this.updateActive("ACTIVE_GRID",{strategies:{audio:this.updateParticipantsMap.bind(this)}}))}};let on=cy;bs([y.trace("ParticipantController.setupEvents")],on.prototype,"setupEventsGlobal",1);bs([y.trace("ParticipantController.processMedia")],on.prototype,"processMedia",1);bs([y.trace("ParticipantController.processConsumerClosed")],on.prototype,"processConsumerClosed",1);bs([y.trace("ParticipantController.processConsumerResumed")],on.prototype,"processConsumerResumed",1);bs([y.trace("ParticipantController.processConsumerPaused")],on.prototype,"processConsumerPaused",1);bs([y.trace("ParticipantController.processNewConsumer")],on.prototype,"processNewConsumer",1);var IO=Object.defineProperty,CO=Object.getOwnPropertyDescriptor,PO=(t,e,r,n)=>{for(var i=n>1?void 0:n?CO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&IO(e,r,i),i};class dy extends on{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n){super(e,r,n),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),I.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(de.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(de.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),I.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),I.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),I.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumers([r]).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),I.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),I.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(de.globalPeerPinBroadcast,({participantId:e})=>{if(!this.mediaJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);this.roomNodeClient.activatePeers(n.producers).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(de.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(de.selectedPeerDiff,({entries:e})=>{if(!this.mediaJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}PO([y.trace("ParticipantController.setupEvents")],dy.prototype,"setupEvents",1);var RO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,MO=(t,e,r,n)=>{for(var i=n>1?void 0:n?AO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&RO(e,r,i),i};class ly extends on{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n){super(e,r,n),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),I.on(w.SOCKET_PEERS,e=>u(this,null,function*(){const r=Q.hasFeature(ie.DEBUG_SOCKET_JOIN);if(r){const n=e&&(e==null?void 0:e.length)<20?{peers:JSON.stringify(e.map(i=>i.peerId))}:void 0;l.info("Processing socket peers",n)}e==null||e.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),r&&l.info("Processed socket peers")})),this.roomSocketHandler.on(ce.peerJoinedBroadcast,({participant:e})=>{Q.hasFeature(ie.DEBUG_SOCKET_JOIN)&&l.info("mediaEvents.peerJoinedBroadcast",{peers:e.peerId}),this.onMediaJoined(e.peerId,e.producerStates)}),this.roomSocketHandler.on(ce.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{if(Q.hasFeature(ie.DEBUG_SOCKET_JOIN)){const o=e&&(e==null?void 0:e.length)<20?{peers:JSON.stringify(e.map(a=>a.peerId))}:void 0;l.info("mediaEvents.selfJoinComplete",o)}e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),I.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),I.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),I.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}if(n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=r.kind==="audio",o=r.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!r.screenShare||a.screenshareAudio&&r.screenShare)||o&&(a.video&&!r.screenShare||a.screenshareVideo&&r.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([r]):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}});return}(r==null?void 0:r.kind)==="audio"&&this.participants.audioSubscribed.get(e)||(r==null?void 0:r.kind)==="video"&&this.participants.videoSubscribed.get(e)||r!=null&&r.screenShare?this.roomNodeClient.createConsumers([r]).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),I.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::PRODUCER_CLOSED::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),I.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(ce.globalPeerPinBroadcast,e=>{let r;if(e&&(r=e.participantId),!this.mediaJoined)return;const n=r;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers(i.producers).catch(s=>{l.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(ce.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.mediaJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ce.selectedPeerDiff,({entries:e})=>{if(!this.mediaJoined)return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}MO([y.trace("ParticipantController.setupEvents")],ly.prototype,"setupEvents",1);const Ce=fr(Vu().permissions);var q,No,jo,lu,Ut,Gt;const Lo=class extends Yt{constructor(t,e,r,n=!1){if(super(),T(this,Ut),T(this,q,void 0),T(this,No,void 0),T(this,jo,void 0),T(this,lu,i=>{var s,o,a;const d=i,{chat:h,connectedMeetings:p,plugins:m,polls:g,media:v}=d,_=nd(d,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&En(c(this,q).chat.private,h.private),h.public&&En(c(this,q).chat.public,h.public),this.emit("chatUpdate")),p&&En(c(this,q).connectedMeetings,p),v){const A=M=>{switch(M){case Dn.NONE:return K.Allowed;case Dn.ALLOWED:return K.Allowed;case Dn.NOT_ALLOWED:return K.NotAllowed;case Dn.CAN_REQUEST:return K.CanRequest;default:return}},C={audio:void 0,video:void 0,screenshare:void 0};(s=v.audio)!=null&&s.canProduce&&(C.audio={canProduce:A(v.audio.canProduce)}),(o=v.video)!=null&&o.canProduce&&(C.video={canProduce:A(v.video.canProduce)}),(a=v.screenshare)!=null&&a.canProduce&&(C.screenshare={canProduce:A(v.screenshare.canProduce)}),En(c(this,q).media,C)}m&&(En(c(this,q).plugins,m),this.emit("pluginsUpdate")),g&&(En(c(this,q).polls,g),this.emit("pollsUpdate")),Object.keys(_).length!==0&&En(c(this,q),_),this.emit("permissionsUpdate",i)}),!e)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new b("Could not load preset permissions.","0904");S(this,jo,t),S(this,No,r),S(this,q,e),n&&this.setupEvents()}setupEvents(){I.on(w.UPDATE_PERMISSIONS,c(this,lu))}static fromResponse(t,e,r){return new Lo(r,t,e,!0)}static default(t,e){return new Lo(t,Ce,e)}static init(t,e,r){let n;return r?n=new Lo(t,r,e,!0):n=new Lo(t,Ce,e),n}get mediaRoomType(){const{sfu:t}=c(this,jo).getValue("roomNodeOptions");return t===gs.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,q))==null?void 0:t.stageEnabled)||c(this,No)===vt.Webinar||c(this,No)===vt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=c(this,q))==null?void 0:t.acceptStageRequests)||((e=c(this,q))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=c(this,q))==null?void 0:t.stageAccess)===K.NotAllowed?K.NotAllowed:((e=c(this,q))==null?void 0:e.stageAccess)===K.CanRequest?K.CanRequest:((r=c(this,q))==null?void 0:r.stageAccess)===K.Allowed||c(this,q).media.audio.canProduce===K.Allowed||c(this,q).media.video.canProduce===K.Allowed||c(this,q).media.screenshare.canProduce===K.Allowed?K.Allowed:c(this,q).media.audio.canProduce===K.CanRequest||c(this,q).media.video.canProduce===K.CanRequest||c(this,q).media.screenshare.canProduce===K.CanRequest?K.CanRequest:K.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=c(this,q))==null?void 0:t.acceptWaitingRequests)!=null?e:Ce.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===K.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===K.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=c(this,q))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===K.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=c(this,q))==null?void 0:t.disableParticipantAudio)!=null?e:Ce.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canAcceptProductionRequests)!=null?e:Ce.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,q))==null?void 0:t.disableParticipantVideo)!=null?e:Ce.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.kickParticipant)!=null?e:Ce.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.pinParticipant)!=null?e:Ce.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canRecord)!=null?e:Ce.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Ce.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,q))==null?void 0:t.waitingRoomType)!=null?e:Ce.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,q))==null?void 0:t.plugins)!=null?e:Ce.plugins}get polls(){var t,e;return(e=(t=c(this,q))==null?void 0:t.polls)!=null?e:Ce.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,q).media.audio.canProduce===K.CanRequest||c(this,q).media.video.canProduce===K.CanRequest||c(this,q).media.screenshare.canProduce===K.CanRequest}get canProduceVideo(){var t;const e=(t=c(this,q).media.video.canProduce)!=null?t:Ce.media.video.canProduce;return this.stageEnabled&&(c(this,Ut,Gt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Ut,Gt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Ut,Gt)==="OFF_STAGE"||c(this,Ut,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=c(this,q).media.screenshare.canProduce)!=null?t:Ce.media.screenshare.canProduce;return this.stageEnabled&&(c(this,Ut,Gt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Ut,Gt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Ut,Gt)==="OFF_STAGE"||c(this,Ut,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=c(this,q).media.audio.canProduce)!=null?t:Ce.media.audio.canProduce;return this.stageEnabled&&(c(this,Ut,Gt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Ut,Gt)==="ON_STAGE")&&e===K.CanRequest?K.Allowed:this.stageEnabled&&(c(this,Ut,Gt)==="OFF_STAGE"||c(this,Ut,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===K.Allowed?K.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:Ce.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:Ce.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:Ce.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=c(this,q))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:Ce.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,q))==null?void 0:t.connectedMeetings)!=null?e:Ce==null?void 0:Ce.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,q))==null?void 0:t.hiddenParticipant)!=null?e:Ce.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,q).showParticipantList)!=null?t:Ce.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ce.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ce.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,q).media.audio.canProduce===K.Allowed||c(this,q).media.video.canProduce===K.Allowed||c(this,q).media.screenshare.canProduce===K.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=c(this,q).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,q).isRecorder}get canSpotlight(){return c(this,q).canSpotlight}get canLivestream(){return c(this,q).canLivestream}get transcriptionEnabled(){return c(this,q).transcriptionEnabled}};let DO=Lo;q=new WeakMap,No=new WeakMap,jo=new WeakMap,lu=new WeakMap,Ut=new WeakSet,Gt=function(){return c(this,jo).getValue("stageStatus")};var uy;class OO extends Yt{constructor(){super(...arguments),f(this,"localMediaHandler"),T(this,uy,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const n=(h,p)=>{this.mediaPermissions[h]=p;const m={message:this.mediaPermissions[h],kind:h};p==="DENIED"?I.emit(w.MEDIA_PERMISSION_ERROR,m):I.emit(w.MEDIA_PERMISSION_UPDATE,m)};if(Te.getName()==="firefox")return;const i="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),a=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:s}),d=(h,p)=>{switch(p){case"granted":n(h,"ACCEPTED");break;case"denied":n(h,"DENIED");break;case"prompt":n(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};o&&(o.onchange=()=>d("audio",o.state)),a&&(a.onchange=()=>d("video",a.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:n}){switch(n){case"audio":{$.mediaPermission("AUDIO",r),$.mediaPermission("SPEAKER",r);break}case"video":{$.mediaPermission("VIDEO",r);break}case"screenshare":{$.mediaPermission("SCREENSHARE",r);break}}})}init(){return u(this,arguments,function*(e={},r=!1,n=null){var i,s,o,a,d,h;if(Te.init(),!this.localMediaHandler)try{let p=!0;if(n!=null&&n.getValue("defaults").mediaHandler)p=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:m}=navigator;this.localMediaHandler=yield m.init()}else this.localMediaHandler=new jt(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(I.on(w.MEDIA_PERMISSION_UPDATE,m=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:m.message,kind:m.kind}),m.message==="NOT_REQUESTED")switch(m==null?void 0:m.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",m)})),I.on(w.MEDIA_PERMISSION_ERROR,m=>u(this,null,function*(){const{kind:g,message:v,constraints:_}=m;this.populateMediaPermissionsInCallstats({message:v,kind:g}),g==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):g==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:v},constraints:_,mediaPermissionsErrors:{kind:g,message:v}}),this.emit("mediaPermissionError",m),this.emit("mediaPermissionUpdate",{message:v,kind:g})})),p){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${(o=e==null?void 0:e.audio)!=null?o:!0} video:${(a=e==null?void 0:e.video)!=null?a:!0}`);const m=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||(yield m)}}catch(p){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:p.name,message:p.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllVideoMiddlewares()})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch{}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(e)}catch{}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}uy=new WeakMap;const uo={},jn={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const o=s.value;return s.value=function(...a){if(uo[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}uo[e]=!0;const d=setTimeout(()=>delete uo[e],r),h=o.apply(this,a);return Promise.resolve(h).then(()=>{delete uo[e],clearTimeout(d)}).catch(()=>{delete uo[e],clearTimeout(d)}),h},s}}};var NO=Object.defineProperty,LO=Object.getOwnPropertyDescriptor,Nt=(t,e,r,n)=>{for(var i=n>1?void 0:n?LO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&NO(e,r,i),i},ho,Lt,po,Lr,mn,Kn,st,ht,Qe,rt,mo,fo,Na,Tl,Um;let ut=(Um=class extends OO{constructor(t,e,r,n,i){var s;super(),T(this,mn),T(this,st),T(this,Qe),T(this,Na),f(this,"name"),f(this,"picture"),f(this,"customParticipantId"),f(this,"waitlistStatus"),T(this,ho,void 0),T(this,Lt,void 0),T(this,po,void 0),f(this,"role"),f(this,"userId"),f(this,"organizationId"),f(this,"supportsRemoteControl",!1),f(this,"device"),T(this,Lr,void 0),f(this,"hidden",!1),f(this,"presetName"),f(this,"roomState","init"),T(this,mo,new Set),T(this,fo,new Set),S(this,Lr,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",S(this,Lt,r),S(this,ho,n),this.hidden=!1,S(this,po,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Te.isElectron(),this.device=Te.getDeviceInfo(),this.presetName=i,n.viewType!==vt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),Ye(this,Na,Tl).call(this)}get stageStatus(){return c(this,Lr).getValue("stageStatus")}get id(){return c(this,Lr).getValue("peerId")}static __init__(t,e,r,n,i,s=!1){return u(this,null,function*(){var o,a,d,h,p;let m=(a=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?a:!0,g=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;r.canProduceAudio!=="ALLOWED"&&(m=!1),r.canProduceVideo!=="ALLOWED"&&(g=!1);const v=new ut(t,e,r,n,i);if(n.viewType===vt.Chat)return v;const _=f1(n.mediaConstraints);return En(_,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield v.init({audio:m,video:g,constraints:_},s,t),v.setupEvents(),v})}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),c(this,Lt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",Ye(this,Na,Tl)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",B({},fi(this))),c(this,Qe,rt)&&this.audioEnabled&&this.stageStatus==="ON_STAGE")try{yield c(this,st,ht).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",B({},fi(this))),c(this,Qe,rt)&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&c(this,Qe,rt)&&this.stageStatus==="ON_STAGE")try{const t=yield c(this,st,ht).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,st,ht).shareWebcam(this.videoTrack))}catch(t){l.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>u(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!c(this,Qe,rt)){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,st,ht).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",B({},fi(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){l.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",B({},fi(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{$.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){c(this,Qe,rt)&&(yield c(this,st,ht).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),$.videoOff()})),c(this,Lt).on("permissionsUpdate",t=>{var e,r,n;(e=t==null?void 0:t.media)!=null&&e.audio&&c(this,Lt).canProduceAudio!==K.Allowed&&(this.disableAudio(),l.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(r=t==null?void 0:t.media)!=null&&r.video&&c(this,Lt).canProduceVideo!==K.Allowed&&(this.disableVideo(),l.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=t==null?void 0:t.media)!=null&&n.screenshare&&c(this,Lt).canProduceScreenshare!==K.Allowed&&(this.disableScreenShare(),l.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return c(this,Lt)}get config(){return c(this,ho)}get roomJoined(){var t;return c(this,ho).viewType===vt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=c(this,Lr).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:c(this,Qe,rt)}setName(t){if(!t)throw new b("Name cannot be empty.","1103");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){t.forceReset,yield this.disableAudio(),yield this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&(yield this.enableAudio()),t.video&&(yield this.enableVideo())})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==K.NotAllowed&&!(c(this,Lt).canProduceAudio===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if($.audioOn(),yield this.localMediaHandler.enableAudio(),c(this,Qe,rt)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,st,ht).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,st,ht).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(c(this,Lt).canProduceVideo!==K.NotAllowed&&!(c(this,Lt).canProduceVideo===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if($.videoOn(),yield this.localMediaHandler.enableVideo(),c(this,Qe,rt)&&this.stageStatus==="ON_STAGE")try{yield c(this,st,ht).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",B({},fi(this)))}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new b("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!c(this,Qe,rt))throw new b("Can`t enable screenshare without joining room","1105");if(c(this,Lt).canProduceScreenshare!==K.NotAllowed&&!(c(this,Lt).canProduceScreenshare===K.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield c(this,st,ht).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new b("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),c(this,Qe,rt)&&c(this,st,ht).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),$.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),c(this,Qe,rt)&&(yield c(this,st,ht).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),$.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),c(this,Qe,rt)&&(yield c(this,st,ht).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;S(this,po,t);const n=t?"pinned":"unpinned";(r=c(this,mn,Kn))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}get isPinned(){return c(this,po)}pin(){return u(this,null,function*(){if(!c(this,Qe,rt))throw new b("Can`t pin participants without joining room","1105");return this.show(),c(this,st,ht).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!c(this,Qe,rt))throw new b("Can`t unpin participants without joining room","1105");return c(this,st,ht).pinPeer(null)})}hide(){return u(this,null,function*(){if(!c(this,Qe,rt))throw new b("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!c(this,Qe,rt))throw new b("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return u(this,null,function*(){var e,r,n;if(!t)throw new b("No device selected","1104");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((r=i==null?void 0:i.video)==null?void 0:r.deviceId)===t.deviceId||((n=i==null?void 0:i.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),Q.hasFeature(ie.SKIP_SETTING_IN_USE_DEVICE)))throw new b("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch{c(this,Qe,rt)&&(yield c(this,st,ht).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch{c(this,Qe,rt)&&(yield c(this,st,ht).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t,e=!1){var r,n;e?c(this,mo).add(t):c(this,fo).add(t),this.updateVideo(t),e||(n=c(this,mn,Kn))==null||n.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1)}deregisterVideoElement(t,e=!1){if(t===void 0){c(this,mn,Kn).removeSource(this.id);return}t.srcObject=void 0,e?c(this,mo).delete(t):(c(this,fo).delete(t),c(this,mn,Kn).removeSource(this.id))}updateVideo(t,e=!1){var r,n,i;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(n=c(this,mn,Kn))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(i=c(this,mn,Kn))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},ho=new WeakMap,Lt=new WeakMap,po=new WeakMap,Lr=new WeakMap,mn=new WeakSet,Kn=function(){return c(this,Lr).getValue("pip")},st=new WeakSet,ht=function(){return c(this,Lr).getValue("roomNodeClient")},Qe=new WeakSet,rt=function(){var t;return((t=c(this,Lr).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},mo=new WeakMap,fo=new WeakMap,Na=new WeakSet,Tl=function(){Array.from(c(this,fo)).forEach(t=>this.updateVideo(t,!1)),Array.from(c(this,mo)).forEach(t=>this.updateVideo(t,!0))},Um);Nt([y.trace("DyteSelf.cleanupEvents")],ut.prototype,"cleanupEvents",1);Nt([y.trace("DyteSelf.setupEvents")],ut.prototype,"setupEvents",1);Nt([y.trace("DyteSelf.setupTracks")],ut.prototype,"setupTracks",1);Nt([y.trace("DyteSelf.destructMediaHandler")],ut.prototype,"destructMediaHandler",1);Nt([y.trace("DyteSelf.removeDocumentEventListeners")],ut.prototype,"removeDocumentEventListeners",1);Nt([jn.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],ut.prototype,"enableAudio",1);Nt([jn.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],ut.prototype,"enableVideo",1);Nt([y.trace("DyteSelf.updateVideoConstraints")],ut.prototype,"updateVideoConstraints",1);Nt([y.trace("DyteSelf.enableScreenShare"),jn.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ut.prototype,"enableScreenShare",1);Nt([y.trace("DyteSelf.updateScreenshareConstraints")],ut.prototype,"updateScreenshareConstraints",1);Nt([jn.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],ut.prototype,"disableAudio",1);Nt([jn.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],ut.prototype,"disableVideo",1);Nt([jn.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],ut.prototype,"disableScreenShare",1);Nt([y.trace("DyteSelf.setDevice")],ut.prototype,"setDevice",1);ut=Nt([St("1100")],ut);class xO extends ty{constructor(e){super(e),f(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class UO extends iy{}class FO extends ny{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return Gc(e.map(r=>u(this,null,function*(){return Ir(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(B({},r))}))})))})}consumerCreationTask(e){return u(this,arguments,function*({consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,paused:d,screenShare:h,appData:p,kind:m,sessionDescription:g}){const v=`${o}:${m}`,_={consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,sessionDescription:g,appData:p,kind:m,paused:d,screenShare:h,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((A,C)=>u(this,null,function*(){const M=setTimeout(()=>{this.consumerTrackEvents.delete(v),_.isTimedout=!0,C(_)},5e3),N=(G,W)=>{try{if(G.readyState==="ended")clearTimeout(M),C(_);else{const ae=G;ae.enabled=!0,this.handler.midTransceiverMap.set(W.mid,W);const se=new xO({id:r,localId:W.mid,track:ae,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:Z(B({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:W.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,se),se.once("close",()=>{this.consumers.delete(se.id),this.handler.midTransceiverMap.delete(W.mid)}),l.info("consumer created for ",{consumer:{id:r,kind:m,appData:{screenShare:h},peerId:i,producerId:n}}),this.observer.emit("newconsumer",se),clearTimeout(M),A(se)}}catch(ae){l.warn("error while creating consumer:",ae),clearTimeout(M),C(_)}},J=this.consumerTrackPool.get(r);if((J==null?void 0:J.length)===2){N(J[0],J[1]);return}const P=this.unknownTracksMap.get(v);P?(this.unknownTracksMap.delete(v),N(P.track,P.transceiver)):this.consumerTrackEvents.set(v,N),g&&(yield this.safeEmitAsPromise("negotiate",{description:g}))}))})}connect(){return u(this,null,function*(){try{const{offerSdp:e,callback:r}=yield this.handler.connect(),{answer:n}=yield this.safeEmitAsPromise("connect",{offer:e});if(yield r(n),!(yield this.isConnected))throw new Error("ice connection failed")}catch(e){throw l.error("transport failed to connect:",e),e}})}_ontrack(e){const{track:r,transceiver:n}=e;l.info(`track event received [trackId: ${r.id}]`);const i=`${n.mid}:${r.kind}`;r.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${r.id}]`),this.consumerTrackPool.delete(r.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(r.id,[r,n]);const s=this.consumerTrackEvents.get(i);s?(s(r,n),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,e))}consume(e){return u(this,null,function*(){if(l.debug(`consume() producers: ${JSON.stringify(e)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new _i("not a receiving Transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const r=[],n=new Map;return e.forEach(i=>{var s;const o=(s=n.get(i.producingPeerId))!=null?s:[];n.set(i.producingPeerId,o.concat([i]))}),n.forEach((i,s)=>u(this,null,function*(){const{consumersMap:o}=yield this.safeEmitAsPromise("consume_peer",{producingPeerId:s});o.forEach((a,d)=>{const{consumerId:h,trackId:p,screenShare:m,paused:g,streamId:v,kind:_,appData:A,producingTransportId:C,sessionDescription:M}=a;r.push(this.consumerCreationTask({consumerId:h,trackId:p,streamId:v,kind:_,producerId:d,producingPeerId:s,producingTransportId:C,paused:g,screenShare:m,appData:A,sessionDescription:M}))})})),Gc(r)})}produce(){return u(this,arguments,function*({track:e,encodings:r,codecOptions:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,appData:a={}}={}){if(l.debug(`produce() [track:${e.id}]`),e){if(this.direction!=="send")throw new _i("not a sending Transport");if(e.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:g,callback:v,sender:_,mid:A}=yield this.handler.send({track:e,encodings:r,codecOption:n,screenShare:a==null?void 0:a.screenShare}),{answer:C,producerId:M}=yield this.safeEmitAsPromise("produce",{offer:g,kind:e.kind,paused:s?!e.enabled:!1,appData:Z(B({},a||{}),{mid:A})}),N=yield v(C);return{producerId:M,localId:N,rtpSender:_}}),"producer"),m=new UO({id:d,localId:h,track:e,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:a,handler:this.handler,rtpSender:p});return this.producers.set(d,m),m.observer.on("close",()=>{this.producers.delete(m.id)}),this.emit("newproducer",m),this.observer.emit("newproducer",m),m})}}class VO extends sy{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,config:a}){const d=bi(),h=new FO({id:d,direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,handlerFactory:this.handlerFactory,config:a});return this._observer.emit("newtransport",h),h}}var Rt;class BO{constructor(e){T(this,Rt,void 0),S(this,Rt,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Rt).sendMessagePromiseWithTimeout({event:de.joinRoom,protobuf:tv.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Rt).sendMessagePromise(de.createWebRTCTransport,Qg.toBinary(e))).payload,{transportId:n,description:i}=ju.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Rt).sendMessagePromise(de.produce,iv.toBinary(e))).payload,s=fv.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Rt).sendMessagePromise(de.consume,Hu.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=mv.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Rt).sendMessagePromise(de.closeProducer,ov.toBinary(e))).payload,{description:n}=gv.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Rt).sendMessagePromise(de.closeConsumer,av.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Rt).sendMessagePromise(de.hostControlPeer,lv.toBinary(n))).payload;if(!i)return!1;const{status:s}=Sv.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Rt).sendMessagePromise(de.hostControlAllPeers,uv.toBinary(r))).payload;if(!n)return!1;const{status:i}=Ev.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Rt).sendMessagePromise(de.kickAll,Wu.toBinary(e))).payload;if(!r)return!1;const{status:n}=yv.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Rt).sendMessagePromise(de.kickPeer,cv.toBinary(e))).payload;if(!r)return!1;const{status:n}=vv.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Rt).sendMessagePromise(de.changeDisplayName,dv.toBinary(e))).payload;if(!r)return!1;const{status:n}=Tv.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Rt).sendMessagePromise(de.selfJoinComplete,rv.toBinary(e))).payload;return Vc.fromBinary(r)})}}Rt=new WeakMap;const jO=Error("task execution aborted");class HO{constructor(e,r){f(this,"id"),f(this,"executor"),f(this,"cancel"),this.id=e,this.executor=r}execute(){return u(this,null,function*(){return new Promise((e,r)=>{this.cancel=()=>r(jO),this.executor.then(n=>e(n))})})}}let Fm=0;const La=new Map;class kl{static execute(e){const r=Fm;Fm+=1;const n=new HO(r,e);return La.set(r,n),{id:r,value:n.execute().finally(()=>La.delete(r))}}static stop(e){const r=La.get(e);r&&(r.cancel(),La.delete(e))}}const WO=2e3;var ns,xo,$r;class $O extends Yv{constructor(e,r){super(),T(this,ns),f(this,"_device"),f(this,"_sendTransport"),f(this,"_recvTransport"),f(this,"_consumers"),f(this,"_producers"),f(this,"_producerStatus"),f(this,"_producerIdToConsumerIdMap"),f(this,"_socket"),f(this,"_socketHandler"),f(this,"_totalTransportReconnectionCount"),f(this,"_transportReconnectFailureCount"),f(this,"_consumerCreationFailureCount"),f(this,"_producerNotReadyFailureCount"),f(this,"_consumerNotBoundFailureCount"),f(this,"_transportDisconnectedTimer"),f(this,"_iceTransportPolicy","all"),f(this,"_transportConnectionFailCount",0),f(this,"lastConnectionTime",0),f(this,"transportConnectionStatus"),f(this,"transportDisconnected"),T(this,$r,void 0),S(this,$r,e),this._device=new VO({}),this._socket=r,c(this,ns,xo).mediaState={recv:{state:rr.NEW,reconnected:!1},send:{state:rr.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new BO(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield Ke().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,m,g,v;const _=this.transportConnectionStatus.get(s);if(_&&!r)return _;switch(_&&r&&kl.stop(_.id),s){case"send":{const A=kl.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,$r).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,$r).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(m=(p=c(this,$r).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:m.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,A),A.value}case"recv":{const A=kl.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(v=c(this,$r).getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,A),A.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield Ir((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,$.configureSendTransport(o)}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(Z(B({},e),{additionalSettings:Z(B({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield Ir((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,$.configureRecvTransport(a)}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?zt.SUBSCRIBER:zt.PUBLISHER}},{transportId:p,answer:m}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:m})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},WO);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,qc(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,qc(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch{l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,m){var g;const v=bu(o.sdp).media.filter(A=>a==="video"?A.type==="video":A.type==="audio").at(-1).msid,_={description:{sdp:o.sdp,type:o.type,target:zt.PUBLISHER},paused:d,kind:a,msid:v,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:A,producerId:C}=yield this._socketHandler.produce(_);p({answer:A,producerId:C})}catch(A){l.error("create producer error:",{error:A}),m(A)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o},a,d){l.info("consumePeer:",o);const h={producingPeerId:o};try{const p=yield this._socketHandler.consume(h);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:p.consumerStateMap});const m=new Map;Object.entries(p.consumerStateMap).forEach(([g,v])=>{var _,A,C;let M={};try{M=JSON.parse(v.producerState.appData)}catch{}m.set(g,{consumerId:v.consumerId,trackId:(_=v.producerTrack)==null?void 0:_.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===Ft.VIDEO?"video":"audio",appData:M,screenShare:(A=v.producerState)==null?void 0:A.screenShare,paused:(C=v.producerState)==null?void 0:C.pause,sessionDescription:p.sessionDescription,producingPeerId:o})}),a({consumersMap:m})}catch(p){l.error("consumePeer error:",{error:p}),d(p)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,m,g,v,_,A,C,M,N;const J={producingPeerId:a,producerId:o};try{const P=yield this._socketHandler.consume(J),G=P.consumerStateMap[o];let W={};try{W=JSON.parse((p=G.producerState)==null?void 0:p.appData)}catch{}l.info("consumer create response:",{consumer:{remotelyPaused:(m=G.producerState)==null?void 0:m.pause,producerId:(g=G.producerState)==null?void 0:g.producerId,kind:(_=(v=G.producerState)==null?void 0:v.kind)==null?void 0:_.toString(),appData:Z(B({},W),{screenShare:(A=G.producerState)==null?void 0:A.screenShare}),id:G.consumerId,sessionDescription:P.sessionDescription},consumerState:G}),d({consumerId:G.consumerId,screenShare:(C=G.producerState)==null?void 0:C.screenShare,trackId:(M=G.producerTrack)==null?void 0:M.trackId,streamId:G.producerTrack.streamId,kind:G.producerState.kind===Ft.VIDEO?"video":"audio",paused:(N=G.producerState)==null?void 0:N.pause,appData:W,sessionDescription:P.sessionDescription})}catch(P){l.error("error during consuming on server:",P),h(P)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Qr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Qr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},m){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:zt.PUBLISHER}};try{const v=yield this._socketHandler.closeProducer(g),_={sdp:v==null?void 0:v.sdp,type:v==null?void 0:v.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),m({answer:_})}catch(v){l.error("producer close error",v)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[ne.MIC,ne.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Qr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Qr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!Q.hasFeature(ie.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(ne.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(ne.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),I.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),I.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumers(e){return u(this,null,function*(){if(!(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)){if(e.every(r=>this.getProducer(r.producerId))){l.warn("why are you creating a consumer for local producer?");return}yield Ir(r=>u(this,null,function*(){r>0&&l.debug(`retrying consume call, retryCount: ${r}`),(yield this._recvTransport.consume(e).catch(n=>{throw l.error("failed to consume:",{error:n}),n})).forEach(n=>{n.status==="rejected"?(l.error("consumer creation task is failing",n.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(n.value)})})).catch(r=>{l.error("create consumer failed after retries",{error:r}),this._consumerCreationFailureCount+=1,this.handleFailure()})}})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&I.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,$r).getValue("modules").e2ee.enabled&&I.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(de.toggleConsumer,Fc.toBinary(r)),e.pause(),I.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(de.toggleConsumer,Fc.toBinary(n)),r.resume(),I.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:zt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(de.renegotiateSessionDescription,Xg.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),I.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),I.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumers([{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare,producingPeerId:o.peerId}])}catch{l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:rr.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),Q.hasFeature(ie.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),Q.hasFeature(ie.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:rr.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:rr.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=Q.hasFeature(ie.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=Q.hasFeature(ie.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>20*1e3&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:rr.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),c(this,ns,xo).mediaState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:c(this,ns,xo).mediaState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),I.emit(w.TRANSPORT_STATE_UPDATE,B({transport:n},c(this,ns,xo).mediaState[n]))}}ns=new WeakSet,xo=function(){return c(this,$r).getValue("connectionHandler")},$r=new WeakMap;var JO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,pe=(t,e,r,n)=>{for(var i=n>1?void 0:n?GO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JO(e,r,i),i},bt,ve,xr,Gi,Yn,Qn,xa,Ua,Fa,fn,go,Ur,gn,Vm;const hy=(Vm=class extends Kv{constructor(t,e){var r,n;super(),T(this,Ur),T(this,bt,void 0),T(this,ve,void 0),T(this,xr,void 0),T(this,Gi,void 0),T(this,Yn,void 0),T(this,Qn,void 0),T(this,xa,void 0),T(this,Ua,void 0),T(this,Fa,void 0),T(this,fn,void 0),T(this,go,void 0),f(this,"legacyMode"),f(this,"roomNodeUrl"),f(this,"peerDisplayName"),f(this,"activatedProducingPeerIds"),f(this,"e2ee"),f(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.mediaJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,S(this,bt,a),S(this,xr,!1),S(this,ve,new $O(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,S(this,fn,new Set),S(this,Gi,!1),S(this,Yn,0),S(this,Qn,new fs),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,$.legacySwitch(o),this.handleSocketEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),S(this,xa,Zr(()=>u(this,null,function*(){if(!c(this,Ur,gn).mediaJoinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(I.emit(w.RESET_PRODUCER_STATE),I.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),S(this,Ua,Zr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),I.emit(w.RESET_PRODUCER_STATE)}),1e3)),S(this,Fa,Zr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,I.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0})}),1e3))}get mediaState(){return c(this,Ur,gn).mediaState}get mediaJoined(){return c(this,Ur,gn).mediaJoined}set mediaJoined(t){c(this,Ur,gn).mediaJoined=t}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new hy(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,ve)}get rejoinRoom(){return c(this,xa)}reset(t=!0){var e,r,n,i;(r=(e=c(this,ve))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,ve))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,fn).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Qn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),S(this,Qn,new fs))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,xr)}`),!(!t||c(this,xr))&&(t.direction==="send"?yield c(this,Ua).call(this,t):yield c(this,Fa).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,ve).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,ve).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){c(this,Ur,gn).mediaJoinAttempted=!0,S(this,xr,!0),this.reset(s);const a=Ke().ipInfo;if(a!=null&&a.loc&&!c(this,go)){const h=a.loc.split(",");S(this,go,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Qn).push(()=>this._joinRoom(r,n,i,o,c(this,go)),"joinRoom"),d}catch{d={roomJoined:!1}}return d.roomJoined||I.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=Ke().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield Ir((o,a)=>(c(this,bt).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ie.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Qn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:n,roomViewType:"groupCall",deviceInfo:Z(B({},Te.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};$.roomJoined(a)})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,S(this,xr,!1),S(this,Gi,!0),this.mediaJoined=!0,I.emit(w.UPDATE_ACTIVE,{createAllConsumers:!0}),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}})}leaveRoom(){return u(this,null,function*(){c(this,ve).stopAllTransports(),S(this,Gi,!1),c(this,Ur,gn).mediaJoinAttempted=!1;const t={closeRoom:!1};c(this,bt).sendMessagePromise(de.leaveRoom,nv.toBinary(t)).then(e=>{var r;(r=pv.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),$.callEnded(),y.destruct()})}getConsumers(){return c(this,ve).consumers}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}deactivatePeers(t,e="default"){return u(this,null,function*(){const r=new Set;t.forEach(i=>{i.screenShare&&i.kind==="video"&&r.add(i.producingPeerId)});const n=e==="default"?t.filter(i=>!r.has(i.producingPeerId)).filter(i=>i.kind!=="audio"):t;yield Promise.all(n.map(i=>{const s=this.sfuHandler.producerIdToConsumerIdMap.get(i.producerId);if(!s){l.warn(`consumer not found in deactivate producers: ${i.producerId}`);return}return this.sfuHandler.closeConsumer(s)}))})}createConsumers(t){return u(this,null,function*(){return this.sfuHandler.createConsumers(t)})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){yield Promise.all(t.map(e=>{const r=this.sfuHandler.producerIdToConsumerIdMap.get(e.producerId);if(!r){l.warn(`consumer not found in deactivate producers: ${e.producerId}`);return}return this.sfuHandler.closeConsumer(r)}))})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,ve).createConsumers(e),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,ve).producers.has(ne.WEBCAM)){const i=c(this,ve).producers.get(ne.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,ve).removeProducer(ne.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in Im||(r=640),e.encodings=p1[r],Q.hasFeature(ie.ENABLE_CF_SIMULCAST)&&(e.encodings=Im[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,ve).createProducer(ne.WEBCAM,e,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,ve).createProducer(ne.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,ve).createProducer(ne.SCREENSHARE_AUDIO,s,i)}$.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,ve).producers.has(ne.MIC)){const n=c(this,ve).producers.get(ne.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,ve).removeProducer(ne.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,ve).createProducer(ne.MIC,e,r)}catch(e){throw new b(e)}})}pauseMic(){const t=c(this,ve).producers.get(ne.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,bt).sendMessage(de.toggleProducer,Mn.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,bt).sendMessage(de.toggleProducer,Mn.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,bt).sendMessage(de.toggleProducer,Mn.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,ve).producers.get(ne.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&I.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,bt).sendMessage(de.toggleProducer,Mn.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,ve).removeProducer(ne.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,ve).removeProducer(ne.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),$.screenShareStop(),yield c(this,ve).removeProducer(ne.SCREENSHARE_VIDEO),yield c(this,ve).removeProducer(ne.SCREENSHARE_AUDIO),c(this,fn).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,ve).removeProducer(ne.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,ve).removeProducer(ne.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.cfSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.cfSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,bt).sendMessagePromise(de.globalPinPeer,sv.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,fn).add(t.consumerPeerId),c(this,fn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,bt).on(de.peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=kv.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),I.emit(w.NEW_PRODUCER,{peerId:e,producer:Z(B({},r),{kind:r.kind===Ft.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,bt).on(de.peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=$l.fromBinary(t),s=r===Ft.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),I.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),I.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),I.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,bt).on(de.peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Bc.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,fn).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,bt).on(de.peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=_v.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),I.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),I.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,bt).on(de.mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!c(this,xr)&&!c(this,Gi)||(l.warn("media hub termination broadcast received, rejoining room"),I.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSFUEvents(){c(this,ve).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,ve).on("rejoin",t=>{var e;if(((e=c(this,Ur,gn).socketState)==null?void 0:e.state)!=="connected"){l.warn("Ignoring rejoin attempt because socket is not connected");return}if(c(this,Yn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,xr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}S(this,Yn,c(this,Yn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Yn)}]`),this.mediaJoined=!1,I.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){$.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&I.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:e.score,scoreStats:e})})}),$.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&I.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:e.score,scoreStats:e})})})}},bt=new WeakMap,ve=new WeakMap,xr=new WeakMap,Gi=new WeakMap,Yn=new WeakMap,Qn=new WeakMap,xa=new WeakMap,Ua=new WeakMap,Fa=new WeakMap,fn=new WeakMap,go=new WeakMap,Ur=new WeakSet,gn=function(){return this.context.getValue("connectionHandler")},Vm);let ue=hy;pe([y.trace("CFNodeClient.reset")],ue.prototype,"reset",1);pe([y.trace("CFNodeClient.reconnect")],ue.prototype,"reconnectTransport",1);pe([y.trace("CFNodeClient.setupTransport")],ue.prototype,"setupTransports",1);pe([y.trace("CFNodeClient.stopAllProducers")],ue.prototype,"stopAllProducers",1);pe([y.trace("CFNodeClient.joinRoom")],ue.prototype,"joinRoom",1);pe([y.trace("CFNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1);pe([y.trace("CFNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1);pe([y.trace("CFNodeClient.activatePeers")],ue.prototype,"activatePeers",1);pe([y.trace("CFNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1);pe([y.trace("CFNodeClient.createConsumers")],ue.prototype,"createConsumers",1);pe([y.trace("CFNodeClient.pauseConsumers")],ue.prototype,"pauseConsumers",1);pe([y.trace("CFNodeClient.resumeConsumers")],ue.prototype,"resumeConsumers",1);pe([y.trace("CFNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1);pe([y.trace("CFNodeClient.consumePeer")],ue.prototype,"consumePeer",1);pe([y.trace("CFNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1);pe([y.trace("CFNodeClient.shareScreen")],ue.prototype,"shareScreen",1);pe([y.trace("CFNodeClient.shareMic")],ue.prototype,"shareMic",1);pe([y.trace("CFNodeClient.pauseMic")],ue.prototype,"pauseMic",1);pe([y.trace("CFNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1);pe([y.trace("CFNodeClient.resumeMic")],ue.prototype,"resumeMic",1);pe([y.trace("CFNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1);pe([y.trace("CFNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1);pe([y.trace("CFClient.disableMic")],ue.prototype,"disableMic",1);pe([y.trace("CFClient.disableScreenShare")],ue.prototype,"disableScreenShare",1);pe([y.trace("CFNodeClient.muteSelf")],ue.prototype,"muteSelf",1);pe([y.trace("CFNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1);pe([y.trace("CFNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1);pe([y.trace("CFNodeClient.kickPeer")],ue.prototype,"kick",1);pe([y.trace("CFNodeClient.kickAllPeers")],ue.prototype,"kickAll",1);pe([y.trace("CFNodeClient.muteAll")],ue.prototype,"muteAll",1);pe([y.trace("CFNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1);pe([y.trace("CFNodeClient.disableAudio")],ue.prototype,"disableAudio",1);pe([y.trace("CFNodeClient.disableVideo")],ue.prototype,"disableVideo",1);pe([y.trace("CFNodeClient.pinPeer")],ue.prototype,"pinPeer",1);pe([y.trace("CFNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);pe([y.trace("CFNodeClient.init")],ue,"init",1);function qO(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof le)return r;throw new Error("Room Node Client already setup")}const n=yield le.init(t,e);return t.setValue("roomNodeClient",n),n})}function zO(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ue)return r;throw new Error("Room Node Client already setup")}const n=yield ue.init(t,e);return t.setValue("roomNodeClient",n),n})}function py(t,e){return u(this,arguments,function*(r,n,i=gs.HIVE){return i===gs.CF?zO(r,n):qO(r,n)})}function my(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var KO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,QO=(t,e,r,n)=>{for(var i=n>1?void 0:n?YO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&KO(e,r,i),i};let qi;var Va,Bm;const fy=(Bm=class{constructor(t,e){f(this,"socket"),T(this,Va,void 0),S(this,Va,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return qi||(qi=new fy(t,e)),qi}static cleanup(){var t;try{(t=qi==null?void 0:qi.socket)==null||t.disconnect()}catch{l.error("roomSocketHandler::cleanup")}qi=void 0}joinRoom(t,e){return u(this,null,function*(){var r;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(r=t.name)!=null?r:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},i=this.socket.sendMessagePromise(j.joinRoom,wP.toBinary(n));try{const{peer:s}=zi.fromBinary((yield i).payload);c(this,Va).getValue("connectionHandler").socketJoined=!0,I.emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),a=this.getRoomPeersNonPaginated(),[{room:d},{peers:h}]=yield Promise.all([o,a]);return I.emit(w.ROOM_STATE,d),I.emit(w.SOCKET_PEERS,h),{peer:s}}catch(s){throw l.error("RoomSocketHandler.joinRoom.failed",{error:s}),new b("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return dR.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=nd(e,["id"]);return Z(B({},n),{userId:r})})}catch{return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let n;try{const i={seachQuery:t,limit:e,offset:r},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,fP.toBinary(i));n=el.fromBinary(s.payload)}catch(i){l.error("getRoomPeers::binary_decode_error",{error:i})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=el.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=el.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(j.getPeerInfo,wv.toBinary({peerId:t}));e=zi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Yp.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Yp.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=em.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=em.fromBinary(e.payload)}catch(e){l.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(j.broadcastMessage,Ws.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(j.broadcastToEntity,Ws.toBinary(n))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(j.broadcastToEntity,Ws.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(j.leaveRoom,CP.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,pR.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(j.kickAll,Wu.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,gR.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,yR.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(Xa.updateUserPreset,qR.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=Ws.fromBinary(t);I.emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToEntity,({payload:t})=>{try{const e=Ws.fromBinary(t);I.emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,n;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{r=zi.fromBinary.bind(zi),n=zi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?Zp.fromBinary(i,s):{requests:[]},n=Zp.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=dm.fromBinary.bind(dm);break}case Xa.updateUserPreset:{r=tm.fromBinary.bind(tm);break}case de.peerJoinedBroadcast:case ce.peerJoinedBroadcast:{r=Jp.fromBinary.bind(Jp);break}case de.selfJoinComplete:case ce.selfJoinComplete:{r=Vc.fromBinary.bind(Vc);break}case de.globalPeerPinBroadcast:case ce.globalPeerPinBroadcast:{r=qp.fromBinary.bind(qp);break}case de.selectedPeer:case ce.selectedPeer:{r=Wl.fromBinary.bind(Wl);break}case de.selectedPeerDiff:case ce.selectedPeerDiff:{r=$p.fromBinary.bind($p);break}case de.leaveRoom:case ce.leaveRoom:{r=Bc.fromBinary.bind(Bc);break}}this.socket.on(t,({payload:i})=>{let s=n;if(!r)return e(void 0);try{s=r(i)}catch(o){l.error("roomSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(Xa.getUserPresets,BR.toBinary(e)),n=$R.fromBinary(r.payload).peerPresets[0],i=new TextDecoder().decode(n.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(r){throw l.error("Error in getting user preset",{error:r}),r}})}},Va=new WeakMap,Bm);let Kc=fy;QO([y.trace("RoomSocketHandler.joinRoom")],Kc.prototype,"joinRoom",1);var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,Di=(t,e,r,n)=>{for(var i=n>1?void 0:n?ZO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&XO(e,r,i),i},Xn,Tr,gt,$t,er,jm;const gy=(jm=class{constructor(t,e,r,n){T(this,$t),f(this,"self"),f(this,"authToken"),T(this,Xn,void 0),f(this,"viewType"),T(this,Tr,void 0),T(this,gt,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,S(this,gt,t),this.viewType=n,this.authToken=s,S(this,Xn,i),S(this,Tr,r),e.config.viewType!==vt.Chat&&this.setupEvents()}get peerId(){return c(this,gt).getValue("peerId")}get mediaJoined(){return c(this,gt).getValue("connectionHandler").mediaJoined}static init(t,e,r,n,i){return u(this,null,function*(){const s=Ke(),o=t.getValue("peerId"),a=!!t.getValue("cachedUserDetails"),d=yield ut.__init__(t,r,n,i,i.name,a);if(navigator.product!=="ReactNative"){const h=!Q.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),$.devices("AUDIO",p==null?void 0:p.filter(m=>m.kind==="audioinput")),$.devices("VIDEO",p==null?void 0:p.filter(m=>m.kind==="videoinput")),$.devices("SPEAKER",p==null?void 0:p.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield $.initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:l,apiHostnames:zg(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new gy(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:n,audioEnabled:i,videoEnabled:s,screenShareEnabled:o,screenShareTracks:a}=this.self;if(n.canProduceAudio&&i)try{yield c(this,$t,er).shareMic(e)}catch{this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,$t,er).shareWebcam(r);d&&d.id!==r.id&&Q.hasFeature(ie.EXP_RESHARE)&&(yield c(this,$t,er).shareWebcam(d))}catch{this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=c(this,$t,er))==null?void 0:t.shareScreen({video:a.video,audio:a.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){$.callEnded(),c(this,$t,er).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){I.on(w.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),I.on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),I.on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),I.on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),I.on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),I.on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=bi()),c(this,Xn).updateURL(e),y.resetPeerId(e),Ke().setHeader("dyte-tracing-id",e),gi.remapContext(e,c(this,gt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),I.on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,Tr).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,Tr).on(Xa.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&I.emit(w.UPDATE_PERMISSIONS,e.patch)})}),c(this,Tr).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,Tr).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,Tr).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),I.onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),I.on(w.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r,scoreStats:n})=>{var i;const s=(i=r==null?void 0:r.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),I.on(w.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),$.audioOff())})),I.on(w.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),$.videoOff())})),I.onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),I.on(w.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,Tr).joinRoom(this.self,this.self.config.viewType);c(this,Tr).socket.flush();const r=Ku(e.stageType);if(c(this,gt).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,gt).notify("stageStatus")}catch(e){throw l.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(t==="rejected"){try{(e=c(this,Xn))==null||e.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),c(this,gt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,gt).notify("stageStatus");try{(r=c(this,Xn))==null||r.disconnect()}catch{l.error("SelfController::leaveRoom::socketDisconnect")}my(c(this,gt)),Kc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,$t,er))==null||t.partialJoinRoom(this.self.name,c(this,gt).getValue("meetingId"),void 0)}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:n,viewType:i,meetingId:s,authToken:o,stageStatus:a,roomNodeOptions:d}=c(this,gt).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:m}=d;try{if(i===vt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield py(c(this,gt),{socket:c(this,Xn),peerId:n,meetingId:s,authToken:o,roomNodeUrl:p,meetingTitle:m},h)}const{roomJoined:g}=(r=yield(e=c(this,$t,er))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?r:{};if(!g)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(g){throw l.error("Error:SelfController.mediaRoomJoin",g),new b("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=c(this,gt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===vt.Webinar)&&c(this,$t,er)&&(c(this,$t,er).mediaJoined&&t!=="disconnected"&&(yield c(this,$t,er).leaveRoom()),!(t==="stageLeft"&&e===vt.Livestream)&&(c(this,$t,er).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Xn=new WeakMap,Tr=new WeakMap,gt=new WeakMap,$t=new WeakSet,er=function(){return c(this,gt).getValue("roomNodeClient")},jm);let Hn=gy;Di([y.trace("SelfController.resetSelf")],Hn.prototype,"resetSelf",1);Di([y.trace("SelfController.setupEvents")],Hn.prototype,"setupEvents",1);Di([y.trace("SelfController.joinRoom")],Hn.prototype,"joinRoom",1);Di([y.trace("SelfController.leaveRoom")],Hn.prototype,"leaveRoom",1);Di([y.trace("SelfController.joinMediaRoom")],Hn.prototype,"joinMediaRoom",1);Di([y.trace("SelfController.leaveMediaRoom")],Hn.prototype,"leaveMediaRoom",1);Di([y.trace("SelfController.init")],Hn,"init",1);var vc;class eN{constructor(e){T(this,vc,void 0),S(this,vc,e)}on(e,r){let n;e===j.roomPeerCount?n=Kp.fromBinary.bind(Kp):n=om.fromBinary.bind(om),c(this,vc).on(e,({payload:i})=>{const s=n(i);return r(s)})}}vc=new WeakMap;var yc;class tN{constructor(e){T(this,yc,void 0),S(this,yc,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=Zd.fromBinary.bind(Zd),i=Zd.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,yc).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}yc=new WeakMap;var rN=Object.defineProperty,nN=Object.getOwnPropertyDescriptor,sh=(t,e,r,n)=>{for(var i=n>1?void 0:n?nN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&rN(e,r,i),i},Cn;class bd{constructor(e){T(this,Cn,void 0),S(this,Cn,e)}getPolls(){return c(this,Cn).sendMessagePromise(Jr.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,Cn).sendMessage(Jr.createPoll,VM.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,Cn).sendMessage(Jr.votePoll,jM.toBinary(n))}on(e,r){let n,i;switch(e){case Jr.updatePoll:case Jr.createPoll:case Jr.votePoll:{n=sl.fromBinary.bind(sl),i=sl.create();break}}c(this,Cn).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("pollSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}removeListeners(e){c(this,Cn).removeListeners(e)}}Cn=new WeakMap;sh([y.trace("PollSocketHandler.getPolls")],bd.prototype,"getPolls",1);sh([y.trace("PollSocketHandler.createPoll")],bd.prototype,"createPoll",1);sh([y.trace("PollSocketHandler.votePoll")],bd.prototype,"votePoll",1);var qt;class iN{constructor(e){T(this,qt,void 0),S(this,qt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,qt).sendMessagePromise(j.getStageRequests);return e?il.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,qt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,qt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,qt).sendMessage(j.grantStageAccess,RM.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,qt).sendMessage(j.denyStageAccess,MM.toBinary(r))})}joinStage(){return c(this,qt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,qt).sendMessagePromise(j.leaveStage,cm.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,qt).sendMessagePromise(j.leaveStage,cm.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=am.fromBinary.bind(am);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=il.fromBinary.bind(il);break}case j.peerStageStatusUpdate:{n=zp.fromBinary.bind(zp);break}}c(this,qt).on(e,({payload:i,id:s})=>{if(!i||!n)return r(void 0,s);const o=n(i);return r(o,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield c(this,qt).sendMessagePromise(j.getPeerInfo,wv.toBinary({peerId:e}));return zi.fromBinary(r.payload)})}}qt=new WeakMap;var ct;class sN{constructor(e){T(this,ct,void 0),S(this,ct,e)}addPlugin(e,r){c(this,ct).sendMessage(z.addPlugin,GA.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,ct).sendMessage(z.removePlugin,zA.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,ct).sendMessagePromise(z.getPlugins);return e?vM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,ct).sendMessage(z.customPluginEventToRoom,iM.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,ct).sendMessage(z.customPluginEventToPeers,oM.toBinary(s),i)}enablePluginForRoom(e,r){c(this,ct).sendMessage(z.enablePluginForRoom,YA.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,ct).sendMessage(z.enablePluginForPeers,eM.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,ct).sendMessage(z.disablePluginForRoom,XA.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,ct).sendMessage(z.disablePluginForPeers,rM.toBinary({pluginId:e,peerIds:r}),n)}storeInsertKeys(e,r,n,i){const s={pluginId:e,storeName:r,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};c(this,ct).sendMessage(z.storeInsertKeys,rm.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(o=>({storeKey:o.key}))};c(this,ct).sendMessage(z.storeGetKeys,lM.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(o=>({storeKey:o.key}))};c(this,ct).sendMessage(z.storeDeleteKeys,hM.toBinary(s),i)}storeDelete(e,r,n){c(this,ct).sendMessage(z.storeDelete,mM.toBinary({pluginId:e,storeName:r}),n)}getPluginDataOld(e,r){l.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,n){const i={pluginId:e,storeName:r,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};c(this,ct).sendMessage(z.storeInsertKeys,rm.toBinary(i))}on(e,r){let n;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{n=zl.fromBinary.bind(zl);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{n=nm.fromBinary.bind(nm);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{n=sm.fromBinary.bind(sm);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{n=im.fromBinary.bind(im);break}}c(this,ct).on(e,({payload:i,id:s})=>{const o=n(i);return r(o,s)})}}ct=new WeakMap;var oN=Object.defineProperty,aN=(t,e,r)=>e in t?oN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,cN=(t,e,r)=>(aN(t,typeof e!="symbol"?e+"":e,r),r),oh=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},U=(t,e,r)=>(oh(t,e,"read from private field"),r?r.call(t):e.get(t)),De=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},Ee=(t,e,r,n)=>(oh(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),xe=(t,e,r)=>(oh(t,e,"access private method"),r),Pn,ci,di,We,li,Le,ze,Rn,dt,Kr,On,mr,cs,Gr,uu,vy,Uo,Sc,hu,yy,ah,Sy,Yc,ch,pu,Ey,qo,Qc,Ho,Xc,Zc,dh,ds,zo,Wo,ed,lh={exports:{}},ls=typeof Reflect=="object"?Reflect:null,Hm=ls&&typeof ls.apply=="function"?ls.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ec;ls&&typeof ls.ownKeys=="function"?Ec=ls.ownKeys:Object.getOwnPropertySymbols?Ec=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ec=function(t){return Object.getOwnPropertyNames(t)};function dN(t){console&&console.warn&&console.warn(t)}var Ty=Number.isNaN||function(t){return t!==t};function _e(){_e.init.call(this)}lh.exports=_e;lh.exports.once=pN;_e.EventEmitter=_e;_e.prototype._events=void 0;_e.prototype._eventsCount=0;_e.prototype._maxListeners=void 0;var Wm=10;function wd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(_e,"defaultMaxListeners",{enumerable:!0,get:function(){return Wm},set:function(t){if(typeof t!="number"||t<0||Ty(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wm=t}});_e.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};_e.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ty(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function ky(t){return t._maxListeners===void 0?_e.defaultMaxListeners:t._maxListeners}_e.prototype.getMaxListeners=function(){return ky(this)};_e.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")Hm(a,this,e);else for(var d=a.length,h=Cy(a,d),r=0;r<d;++r)Hm(h[r],this,e);return!0};function _y(t,e,r,n){var i,s,o;if(wd(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=ky(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,dN(a)}return t}_e.prototype.addListener=function(t,e){return _y(this,t,e,!1)};_e.prototype.on=_e.prototype.addListener;_e.prototype.prependListener=function(t,e){return _y(this,t,e,!0)};function lN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function by(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=lN.bind(n);return i.listener=r,n.wrapFn=i,i}_e.prototype.once=function(t,e){return wd(e),this.on(t,by(this,t,e)),this};_e.prototype.prependOnceListener=function(t,e){return wd(e),this.prependListener(t,by(this,t,e)),this};_e.prototype.removeListener=function(t,e){var r,n,i,s,o;if(wd(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():uN(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};_e.prototype.off=_e.prototype.removeListener;_e.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function wy(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?hN(i):Cy(i,i.length)}_e.prototype.listeners=function(t){return wy(this,t,!0)};_e.prototype.rawListeners=function(t){return wy(this,t,!1)};_e.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Iy.call(t,e)};_e.prototype.listenerCount=Iy;function Iy(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}_e.prototype.eventNames=function(){return this._eventsCount>0?Ec(this._events):[]};function Cy(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function uN(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function hN(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function pN(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Py(t,e,s,{once:!0}),e!=="error"&&mN(t,i,{once:!0})})}function mN(t,e,r){typeof t.on=="function"&&Py(t,"error",e,r)}function Py(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var fN=lh.exports;class gN extends E{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const $m=new gN;class Ry{static encode(e){return $m.toBinary(e)}static decode(e){return $m.fromBinary(new Uint8Array(e))}}function vN(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class yN{constructor(e={}){cN(this,"opts"),De(this,Pn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},Ee(this,Pn,0)}wait(){return u(this,null,function*(){Ee(this,Pn,U(this,Pn)+1);const e=vN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*YS(2,U(this,Pn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return U(this,Pn)}reset(){Ee(this,Pn,0)}}Pn=new WeakMap;const vn={debug:0,info:1,warn:2,error:3};class SN{constructor(e){De(this,ci,void 0),De(this,di,void 0),Ee(this,ci,console),Ee(this,di,e)}debug(...e){vn[U(this,di)]>vn.debug||U(this,ci).debug("[Sockrates]:",...e)}info(...e){vn[U(this,di)]>vn.info||U(this,ci).info("[Sockrates]:",...e)}warn(...e){vn[U(this,di)]>vn.warn||U(this,ci).warn("[Sockrates]:",...e)}error(...e){vn[U(this,di)]>vn.error||U(this,ci).error("[Sockrates]:",...e)}}ci=new WeakMap;di=new WeakMap;var Ay=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Ay||{});const EN="2",TN="3";class kN{constructor(e,r){De(this,uu),De(this,Uo),De(this,hu),De(this,ah),De(this,Yc),De(this,pu),De(this,qo),De(this,Ho),De(this,Zc),De(this,ds),De(this,Wo),De(this,We,void 0),De(this,li,void 0),De(this,Le,void 0),De(this,ze,void 0),De(this,Rn,void 0),De(this,dt,void 0),De(this,Kr,void 0),De(this,On,void 0),De(this,mr,void 0),De(this,cs,void 0),De(this,Gr,void 0);var n,i,s,o,a,d,h,p,m,g;Ee(this,li,e),Ee(this,Rn,[]),Ee(this,dt,new fN),Ee(this,Kr,!0),Ee(this,mr,!1),Ee(this,Le,r!=null?r:{}),(n=U(this,Le)).autoReconnect!=null||(n.autoReconnect=!0),(i=U(this,Le)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=U(this,Le)).pingTimeout!=null||(s.pingTimeout=3e4),(o=U(this,Le)).connectionTimeout!=null||(o.connectionTimeout=5e3),(a=U(this,Le)).debug!=null||(a.debug=!0),(d=U(this,Le)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=U(this,Le)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=U(this,Le)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(m=U(this,Le)).flushOnReconnect!=null||(m.flushOnReconnect=!1),Ee(this,On,{code:void 0,reason:void 0}),Ee(this,ze,(g=U(this,Le).logger)!=null?g:new SN(U(this,Le).debug?"debug":"info")),Ee(this,Gr,new yN)}get readyState(){var e;return(e=U(this,We))==null?void 0:e.readyState}get url(){return U(this,li)}updateURL(e){Ee(this,li,e),xe(this,pu,Ey).call(this)}get config(){return U(this,Le)}get sendQueue(){return U(this,Rn)}flush(){if(!U(this,Le).queueOnDisconnect)return!1;const e=[];return U(this,Rn).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),Ee(this,Rn,e),U(this,Rn)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){U(this,ze).debug("Websocket was already connecting or connected.");return}if(U(this,Kr)!==!1)return new Promise((r,n)=>{xe(this,ds,zo).call(this),xe(this,Wo,ed).call(this);try{Ee(this,We,new WebSocket(xe(this,uu,vy).call(this,U(this,li)))),U(this,We).binaryType="arraybuffer",U(this,ze).debug("Connecting to",U(this,li));const i=setTimeout(()=>{U(this,ze).debug("Connection timeout. Closing socket"),Ee(this,Kr,!0),xe(this,Wo,ed).call(this),U(this,We).close(3001,"Connection Timeout"),U(this,Le).autoReconnect&&!U(this,mr)&&(U(this,dt).emit("reconnecting"),xe(this,qo,Qc).call(this)),n(new Error("Connection timed out!"))},U(this,Le).connectionTimeout);U(this,We).onopen=()=>{U(this,ze).debug(`Ready State: ${Ay[U(this,We).readyState]}`),i&&clearTimeout(i),xe(this,Zc,dh).call(this),Ee(this,On,{code:void 0,reason:void 0}),U(this,dt).emit("connected"),U(this,Le).flushOnReconnect&&this.flush(),r()},U(this,We).onclose=s=>{try{i&&clearTimeout(i);const{code:o,reason:a}=s;n(a),U(this,ze).debug("Socket closed. Close event:",s),U(this,ze).debug("Connection closed code:",o),U(this,ze).debug("Connection closed reason:",a),U(this,mr)||xe(this,Yc,ch).call(this,o,a)}catch(o){xe(this,Uo,Sc).call(this,o)}},U(this,We).onerror=s=>{xe(this,Uo,Sc).call(this,s)},U(this,We).onmessage=s=>xe(this,hu,yy).call(this,s)}catch(i){xe(this,Uo,Sc).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(U(this,Le).queueOnDisconnect&&(!U(this,We)||U(this,We).readyState!==1))return U(this,ze).debug("Queuing message since socket is not connected!",s),U(this,Rn).push(s),!1;const o=Ry.encode(s);return xe(this,Ho,Xc).call(this,o)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return xe(this,Ho,Xc).call(this,e)}receive(e,r){return U(this,dt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){U(this,dt).on(e,r);return}this.receive(e,r)}removeAllListeners(){U(this,dt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){U(this,dt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){U(this,dt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){Ee(this,Kr,!1),xe(this,ds,zo).call(this),this.removeAllListeners(),Ee(this,On,{code:1e3,reason:"Sockrates disconnect method called"}),U(this,We).close(1e3,"Sockrates disconnect method called.")}}We=new WeakMap;li=new WeakMap;Le=new WeakMap;ze=new WeakMap;Rn=new WeakMap;dt=new WeakMap;Kr=new WeakMap;On=new WeakMap;mr=new WeakMap;cs=new WeakMap;Gr=new WeakMap;uu=new WeakSet;vy=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")};Uo=new WeakSet;Sc=function(t,e){U(this,ze).error("Error:",{error:t}),U(this,dt).emit("errored",{error:t}),e==null||e(t)};hu=new WeakSet;yy=function(t){if(xe(this,Zc,dh).call(this),t.data===EN){U(this,ze).debug("Received ping from server"),xe(this,Ho,Xc).call(this,TN);return}const e=Ry.decode(t.data),{id:r,payload:n}=e;U(this,ze).debug("Received message",{event:e.event,messageID:r}),U(this,dt).emit(e.event.toString(),{id:r,payload:n})};ah=new WeakSet;Sy=function(){return U(this,We).readyState===1};Yc=new WeakSet;ch=function(t,e){Ee(this,On,{reason:e,code:t}),U(this,dt).emit("disconnected",{code:t,reason:e})};pu=new WeakSet;Ey=function(){const{reason:t,code:e}=U(this,On);e&&e!==1e3&&U(this,Kr)&&U(this,Le).autoReconnect&&!U(this,mr)&&(U(this,ze).debug(`Triggering reconnection due to ${t}.`),U(this,dt).emit("reconnecting"),xe(this,qo,Qc).call(this))};qo=new WeakSet;Qc=function(t=!0){return u(this,null,function*(){if(t&&U(this,mr)){U(this,ze).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(U(this,mr)||U(this,Gr).reset(),U(this,Le).maxReconnectionAttempts!==null&&U(this,Gr).getAttempts()>=U(this,Le).maxReconnectionAttempts){U(this,dt).emit("failed"),Ee(this,mr,!1);return}Ee(this,mr,!0),xe(this,Wo,ed).call(this),xe(this,ds,zo).call(this);try{if(yield U(this,Gr).wait(),U(this,Kr)===!1)return;if(U(this,ze).debug(`Reconnection attempt ${U(this,Gr).getAttempts()}`),U(this,dt).emit("reconnectAttempt",{attempt:U(this,Gr).getAttempts()}),yield this.connect(),!xe(this,ah,Sy).call(this))throw Error("Reconnect Failed");Ee(this,mr,!1),Ee(this,On,{code:void 0,reason:void 0}),U(this,dt).emit("reconnected")}catch{U(this,ze).debug("Failed to reconnect."),U(this,dt).emit("reconnectFailure",{attempt:U(this,Gr).getAttempts()}),xe(this,qo,Qc).call(this,!1)}})};Ho=new WeakSet;Xc=function(t){try{return U(this,We).send(t),!0}catch(e){return U(this,ze).error(e.message),!1}};Zc=new WeakSet;dh=function(){this.config.disconnectOnPingTimeout&&(U(this,ze).debug("Resetting ping timeout"),xe(this,ds,zo).call(this),Ee(this,cs,setTimeout(()=>{var t;U(this,ze).debug("Disconnecting the socket due to ping timeout"),Ee(this,Kr,!0);const e=3002,r="Ping timeout";(t=U(this,We))==null||t.close(e,r),xe(this,Yc,ch).call(this,e,r)},U(this,Le).pingTimeout)))};ds=new WeakSet;zo=function(){U(this,cs)&&(clearTimeout(U(this,cs)),Ee(this,cs,void 0))};Wo=new WeakSet;ed=function(){U(this,We)&&(U(this,We).onopen=void 0,U(this,We).onerror=void 0,U(this,We).onmessage=void 0,U(this,We).onclose=void 0)};var _N=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Id=(t,e,r,n)=>{for(var i=n>1?void 0:n?bN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&_N(e,r,i),i};const Jm=65535,wN=3e3;var Zn,Ve,Be,$e,ar,yn,Ba,_l,ja,bl,Gm;const My=(Gm=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){T(this,Be),T(this,Ba),T(this,ja),T(this,Zn,void 0),T(this,Ve,void 0),f(this,"roomName"),f(this,"authToken"),f(this,"capabilities"),T(this,ar,void 0),T(this,yn,void 0);var s;if(!e||!r||!n)throw new b("peerId, meetingId, or authToken can not be empty","0404");S(this,ar,void 0),S(this,yn,t),this.capabilities=i,this.roomName=r,this.authToken=n,S(this,Zn,Ye(this,Ba,_l).call(this,e)),S(this,Ve,new kN(c(this,Zn),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l})),this.handleSocketConnectionEvents()}get joinAttempted(){return c(this,Be,$e).socketJoinAttempted}set joinAttempted(t){c(this,Be,$e).socketJoinAttempted=t}get peerId(){return c(this,yn).getValue("peerId")}updateURL(t){t!==this.peerId&&(S(this,Zn,Ye(this,Ba,_l).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,Ve).updateURL(c(this,Zn))}static getSocketEdgeDomain(t){return as({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,Zn)}connect(){return u(this,null,function*(){c(this,Be,$e).socketJoinAttempted=!0,yield c(this,Ve).connect(),c(this,Be,$e).socketJoinAttempted=!0,c(this,Be,$e).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){c(this,Be,$e).socketJoinAttempted=!1,c(this,Ve).disconnect(),c(this,Be,$e).socketJoinAttempted=!0,c(this,Be,$e).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return c(this,Ve).readyState===1}catch{return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,Ve).send(t,r!=null?r:Ye(this,ja,bl).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,r,n){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:r,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:n,resp:i}){const s=i!=null?i:t;return new Promise((o,a)=>{const d=(v,_)=>{c(this,Ve).removeListener(s,v),c(this,Ve).removeListener(Jm,_),c(this,Ve).removeListener(ce.errorResponse,_),c(this,Ve).removeListener(de.errorResponse,_)},h=n!=null?n:Ye(this,ja,bl).call(this),p={};y.injectContext(p);const m=({id:v,payload:_})=>{if(h===v){let A;try{const C=vC.fromBinary(_);A=new Error(C.errorMessage)}catch(C){A=new Error("failed to parse error message",{cause:C});try{const M=cP.fromBinary(_);A=new Error(M.message)}catch(M){A=new Error("failed to parse error message",{cause:M})}}a(A),d(g,m)}},g=({id:v,payload:_})=>{h===v&&(o({id:v,payload:_}),d(g,m))};c(this,Ve).on(s,g),c(this,Ve).on(Jm,m),c(this,Ve).on(ce.errorResponse,m),c(this,Ve).on(de.errorResponse,m),setTimeout(()=>{d(g,m),a(new Error(`request timeout for callback eventId:${t}`))},e),c(this,Ve).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,Ve).on(t,e)}onStateEvent(t,e){c(this,Ve).on(t,e)}removeListener(t,e){c(this,Ve).removeListener(t,e)}removeListeners(t){c(this,Ve).removeListeners(t)}flush(){return c(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,ar)&&(clearTimeout(c(this,ar)),S(this,ar,void 0)),c(this,Be,$e).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var r;l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:y.location.country});const{recv:n,send:i}=(r=c(this,Be,$e).mediaState)!=null?r:{};n!=null&&n.state&&(n==null?void 0:n.state)!==rr.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==rr.CONNECTED?I.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Be,$e).joinAttempted}):S(this,ar,setTimeout(()=>{I.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:c(this,Be,$e).joinAttempted}),S(this,ar,void 0)},wN)),c(this,Be,$e).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),c(this,Be,$e).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),c(this,Be,$e).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),c(this,Be,$e).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:c(this,Be,$e).joinAttempted}}),c(this,ar)&&(clearTimeout(c(this,ar)),S(this,ar,void 0)),I.emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:c(this,Be,$e).joinAttempted}),c(this,Be,$e).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),I.emit(w.SOCKET_SERVICE_FAILED),c(this,Be,$e).updateSocketConnectionState("failed")}))}},Zn=new WeakMap,Ve=new WeakMap,Be=new WeakSet,$e=function(){return c(this,yn).getValue("connectionHandler")},ar=new WeakMap,yn=new WeakMap,Ba=new WeakSet,_l=function(t){let e=My.getSocketEdgeDomain(c(this,yn).getValue("baseURI"));typeof Uc(c(this,yn),"socket_server_base")=="string"&&(e=Uc(c(this,yn),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=Z(B({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>jc[o]).join(" "),joinWithDetails:!0});return Object.entries(s).forEach(([o,a])=>{n.searchParams.append(o,a.toString())}),n.href},ja=new WeakSet,bl=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Gm);let oa=My;Id([y.trace("SocketService.connect")],oa.prototype,"connect",1);Id([y.trace("SocketService.disconnect")],oa.prototype,"disconnect",1);Id([y.trace("SocketService.sendMessagePromise")],oa.prototype,"sendMessagePromise",1);Id([y.trace("SocketService.sendMessagePromiseWithTimeout")],oa.prototype,"sendMessagePromiseWithTimeout",1);const ui=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=LP.fromBinary(t),n=r.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(e=r.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=aR.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=Iv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Xp.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return QP.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield ui.socketService.sendMessagePromise(j.getConnectedRoomsDump);return ui.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield ui.socketService.sendMessagePromise(j.createConnectedRooms,VP.toBinary({payloads:t}));return Xp.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),r=yield ui.socketService.sendMessagePromise(j.deleteConnectedRooms,KP.toBinary({payloads:e}));return ui.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield ui.socketService.sendMessagePromise(j.movePeers,nR.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Fe=ui;f(Fe,"socketService"),f(Fe,"currentMeetingId");var IN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,Cd=(t,e,r,n)=>{for(var i=n>1?void 0:n?CN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&IN(e,r,i),i};const hi=class{constructor(t,e){f(this,"apiBase"),f(this,"selfController"),f(this,"pollController"),f(this,"chatController"),f(this,"metaController"),f(this,"storesManager"),f(this,"stageController"),f(this,"pluginController"),f(this,"internalsController"),f(this,"recordingController"),f(this,"livestreamController"),f(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e;const{peerId:r,apiBase:n,authToken:i,meetingId:s,organizationId:o,cachedUserDetails:a}=t.getAllValues();if(I.reset(),Kc.cleanup(),my(t),Te.isSupported()===!1)throw new b("Browser not supported","0010",!0);const d=SD(t,{authToken:i,baseURL:n,cachedUserDetails:a});d.setRoomName(s),d.setRoomUUID(s),d.setOrganizationId(o),d.setHeader("dyte-tracing-id",r),t.setValue("apiClient",d);const h=new t1;t.setValue("connectionHandler",h);const p=hi.createSocketService(t),m=p.connect(),g=d.getPlugins(),[{sfu:v,userResponse:_,meetingTitle:A,roomNodeUrl:C}]=yield Promise.all([hi.getRoomMetadata(),hi.setupFlagsmith(t)]);y.location.country=(e=d.ipInfo)==null?void 0:e.country,t.setValue("roomNodeOptions",{sfu:v,meetingTitle:A,roomNodeUrl:C});const{theme:M,controllers:N}=yield hi.setupControllers(p,t,_,g);$D(M)&&hi.createRoomNodeClient(t,p),SI();try{yield m,N.selfController.partialMediaRoom()}catch(J){throw l.error("[Socket Service] Failed to connect to socket server:",{error:J}),new b("Failed to connect to websocket","0012")}return new hi(n,N)})}static getRoomMetadata(){return u(this,null,function*(){const t=Ke(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=gs.HIVE},i]=yield Promise.all([t.getRoomNodeData(),t.getUserDetails()]);return{sfu:n,roomNodeUrl:e,meetingTitle:r,userResponse:i}})}static setupFlagsmith(t){return u(this,null,function*(){const{peerId:e,baseURI:r,overrides:n,meetingId:i,organizationId:s}=t.getAllValues(),o=vI(i),a=Z(B({entity:Hl.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:o,roomName:i},Te.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?as({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield Q.identify(`${Hl.PEER}_${e}`,JSON.parse(JSON.stringify(a)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch{l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,n){return u(this,null,function*(){var i,s,o;const a=e.getValue("modules"),{preset:d,participant:h}=r,p=e.getValue("defaults"),{sfu:m,meetingTitle:g}=e.getValue("roomNodeOptions"),v=F1.init(d,!a.theme),{viewType:_,mediaConstraints:{audio:A}}=v;e.setValue("viewType",_),e.setValue("defaults",B({mediaConfiguration:{audio:{enableHighBitrate:(i=A.enableHighBitrate)!=null?i:!1,enableStereo:(s=A.enableStereo)!=null?s:!1}}},p));const C=DO.init(e,_,d.permissions);e.setValue("maxPreferredStreams",Te.isMobile()?v.maxVideoStreams.mobile:v.maxVideoStreams.desktop);let M,N,J,P,G,W,ae,se;const Ne=new tN(t);Fe.socketService=t;const Tt=new bd(t),O=new nr(t),k=new iN(t),R=Kc.create(t,e),H=new sN(t),Ae=new eN(t),Ze=new Ei(t),V=yield Hn.init(e,R,h,C,v),D=yield Uv.init(e,V.self,R,Ne,g);if(a.participant&&(m===gs.CF&&(se=new dy(e,V.self,R)),se=new ly(e,V.self,R)),(o=a.e2ee)!=null&&o.enabled&&a.e2ee.manager.init(l,I),a.chat&&(N=yield Yr.init(e,O,Ze,V.self,se.participants)),a.internals&&(G=yield Qu.init()),a.livestream&&v.viewType===vt.Livestream&&Q.hasFeature(ie.LIVESTREAM)&&(ae=new Gv(V.self,Ae)),v.viewType!==vt.Chat){if(a.poll&&(M=yield Ov.init(e,V.self,Tt)),a.recording&&(W=new jv(e,V.self,R)),a.stage&&(J=new Fv(e,k,R,V.self,se.participants)),a.plugin){if(!se)throw new b("The plugin module cannot be initialized without the `participant` module","0102");const Ar=yield n;P=yield ra.init(e,Ar,H,O,N==null?void 0:N.chat,V.self,se.participants)}if(a.pip){const Ar=yield kI._init(e,V.self);e.setValue("pip",Ar)}}const et={storesManager:new G1(e,H),pollController:M,selfController:V,metaController:D,chatController:N,stageController:J,pluginController:P,recordingController:W,internalsController:G,livestreamController:ae,participantController:se};return{theme:v,permissions:C,controllers:et}})}static createRoomNodeClient(t,e){return u(this,null,function*(){const{peerId:r,meetingId:n,authToken:i,roomNodeOptions:s}=t.getAllValues(),{sfu:o,roomNodeUrl:a,meetingTitle:d}=s;return py(t,{socket:e,peerId:r,meetingId:n,authToken:i,roomNodeUrl:a,meetingTitle:d},o)})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:n}=t.getAllValues(),i=["PING"];return new oa(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let aa=hi;Cd([y.trace("Controller.init")],aa,"init",1);Cd([y.trace("setupFlagsmith")],aa,"setupFlagsmith",1);Cd([y.trace("Controller.createSocketServiceAndRoomNodeClient")],aa,"createRoomNodeClient",1);Cd([y.trace("Controller.createSocketService")],aa,"createSocketService",1);var PN=Object.defineProperty,RN=Object.getOwnPropertyDescriptor,AN=(t,e,r,n)=>{for(var i=n>1?void 0:n?RN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&PN(e,r,i),i},Tc,mu;class Dy extends Yt{constructor(e,r){super(),T(this,Tc,void 0),f(this,"meetings",[]),f(this,"parentMeeting",null),T(this,mu,void 0),S(this,mu,e),S(this,Tc,r.self)}get supportsConnectedMeetings(){return c(this,Tc).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Fe.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
32
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Fe.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Fe.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Fe.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(r),yield Fe.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Fe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,r,n),i})}moveParticipantsWithCustomPreset(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Fe.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(s=>s.id)),i})}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(r===s.id){const o=s.participants.concat(n.map(a=>i.get(a)));return Z(B({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(a=>!n.includes(a.id));return Z(B({},s),{participants:o})}return s})}}Tc=new WeakMap,mu=new WeakMap;AN([Bt({maxInvocations:60,period:60})],Dy.prototype,"getConnectedMeetings",1);var MN=Object.defineProperty,DN=Object.getOwnPropertyDescriptor,uh=(t,e,r,n)=>{for(var i=n>1?void 0:n?DN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&MN(e,r,i),i},vo,cr,wl,Il;const An=(wl=class{constructor(t,e,r){f(this,"connectedMeetings"),T(this,vo,void 0),T(this,cr,void 0),T(this,Il,void 0),S(this,Il,t),S(this,vo,r),this.connectedMeetings=new Dy(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return An.instance||(An.instance=new An(t,e,r)),An.instance.connectedMeetings.supportsConnectedMeetings&&(An.instance.setupEvents(),e.self.once("roomJoined",()=>An.instance.getConnectedMeetings())),An.instance}setCurrentMeeting(t){S(this,cr,t),Fe.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Fe.socketService&&(Fe.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Fe.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Fe.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Fe.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Fe.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Fe.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){var n,i,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
33
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);l.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",r);const a={video:c(this,cr).self.videoEnabled,audio:c(this,cr).self.audioEnabled};try{c(this,cr).self.cleanupEvents(),yield c(this,cr).leave("connected-meeting")}catch(h){l.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(n=c(this,cr))==null?void 0:n.meta)==null?void 0:i.meetingId}`,{error:h})}Fe.socketService=void 0,l.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${r}`);const d=yield Oy.init(Z(B({},c(this,vo)),{cachedUserDetails:null,defaults:Z(B(B({},c(this,vo).defaults),a),{mediaHandler:c(this,cr).self}),authToken:e}));l.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:h}=c(this,cr).self;d.self.setName(c(this,cr).self.name),yield d.join(),h&&d.self.hide()}catch(h){l.error("ConnectedMeetingsController.joinRoom",{error:h})}return l.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Fe.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Fe.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Fe.handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(n=>{r.set(n.id,n)}),e.forEach(n=>{r.has(n.id)?r.get(n.id).title=n.title:r.set(n.id,Z(B({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Fe.handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},vo=new WeakMap,cr=new WeakMap,Il=new WeakMap,f(wl,"instance"),wl);let Pd=An;uh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Pd.prototype,"getConnectedMeetings",1);uh([y.trace("ConnectedMeetingsController.setupEvents")],Pd.prototype,"setupEvents",1);uh([y.trace("ConnectedMeetingsController.switchMeeting")],Pd.prototype,"switchMeeting",1);class ON{constructor(){f(this,"battery"),f(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),f(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),f(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),f(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const qm=new ON;function NN(t,e){try{const{meetingId:r,orgId:n,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://api.${s}`;return{meetingId:r,orgId:n,participantId:i,baseURI:s,apiBase:o}}catch(r){throw l.error("constants::decodeAuthToken",{error:r,debuggingHint:`Unable to decode auth token: ${t}`},!0),new b("Invalid auth token","0004")}}var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,Rd=(t,e,r,n)=>{for(var i=n>1?void 0:n?xN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&LN(e,r,i),i},pt,Ha,Wa,Cl,zm,Km;let Fn=(Km=class{constructor(t,e){T(this,Cl),T(this,pt,void 0),T(this,Ha,void 0),T(this,Wa,void 0),S(this,Wa,t),S(this,pt,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;mI(),Te.init();const o=bi();qm.init();const{authToken:a,baseURI:d}=t,h=NN(a,d),{meetingId:p}=h,m=nd(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=Fn.setupContext(o,t,p,m);y.meetingMetadata.roomName=p,y.meetingMetadata.userId=m.participantId,y.meetingMetadata.organizationId=m.orgId,y.init(g,(r=(e=t.modules)==null?void 0:e.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:Z(B({},t),{authToken:`${(n=t.authToken)==null?void 0:n.slice(0,10)}...
34
+ ${(i=t.authToken)==null?void 0:i.slice(-10)}`})});const v=yield aa.init(g),_=new Fn(g,v);return Ye(s=_,Cl,zm).call(s,t),_})}static setupContext(t,e,r,n){var i;const s=gi.createContext(t,e),o=B(B({},cI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",r),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",dI({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",fr(e.cachedUserDetails)),s.setValue("sdkVersion","2.4.4"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,pt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){qm.cleanup();const{selfController:e}=c(this,pt);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,pt).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,pt).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,pt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,pt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,pt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,pt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,pt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,Ha))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,pt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,pt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,pt).stageController)==null?void 0:t.stage}get stores(){return c(this,pt).storesManager}get __internals__(){var t;return(t=c(this,pt).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},pt=new WeakMap,Ha=new WeakMap,Wa=new WeakMap,Cl=new WeakSet,zm=function(t){S(this,Ha,Pd.init(c(this,Wa),this,t))},Km);Rd([St("0002"),jn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Fn.prototype,"join",1);Rd([St("0003")],Fn.prototype,"leave",1);Rd([St("0001"),jn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Fn,"init",1);Fn=Rd([St("0000")],Fn);const Oy=Fn;var UN=Object.defineProperty,FN=(t,e,r)=>e in t?UN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pl=(t,e,r)=>(FN(t,typeof e!="symbol"?e+"":e,r),r);class VN{constructor(e){Pl(this,"meeting"),Pl(this,"l"),Pl(this,"onUpdate",()=>{this.l.forEach(P=>{P()})});var r,n,i,s,o,a,d,h,p,m,g,v,_,A,C,M,N,J;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(n=this.meeting.meta)==null||n.addListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.addListener("*",this.onUpdate),(o=(s=this.meeting.participants)==null?void 0:s.joined)==null||o.addListener("*",this.onUpdate),(d=(a=this.meeting.participants)==null?void 0:a.active)==null||d.addListener("*",this.onUpdate),(p=(h=this.meeting.participants)==null?void 0:h.waitlisted)==null||p.addListener("*",this.onUpdate),(m=this.meeting.stage)==null||m.addListener("*",this.onUpdate),(g=this.meeting.livestream)==null||g.addListener("*",this.onUpdate),(v=this.meeting.chat)==null||v.addListener("*",this.onUpdate),(_=this.meeting.plugins)==null||_.all.addListener("*",this.onUpdate),(A=this.meeting.recording)==null||A.addListener("*",this.onUpdate),(C=this.meeting.connectedMeetings)==null||C.addListener("*",this.onUpdate),(M=this.meeting.spotlight)==null||M.addListener("*",this.onUpdate),(N=this.meeting.remote)==null||N.addListener("*",this.onUpdate),(J=this.meeting.polls)==null||J.addListener("*",this.onUpdate)}clean(){var e,r,n,i,s,o,a,d,h,p,m,g,v,_,A,C,M,N;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(n=this.meeting.participants)==null||n.removeListener("*",this.onUpdate),(s=(i=this.meeting.participants)==null?void 0:i.joined)==null||s.removeListener("*",this.onUpdate),(a=(o=this.meeting.participants)==null?void 0:o.active)==null||a.removeListener("*",this.onUpdate),(h=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||h.removeListener("*",this.onUpdate),(p=this.meeting.stage)==null||p.removeListener("*",this.onUpdate),(m=this.meeting.livestream)==null||m.removeListener("*",this.onUpdate),(g=this.meeting.chat)==null||g.removeListener("*",this.onUpdate),(v=this.meeting.plugins)==null||v.all.removeListener("*",this.onUpdate),(_=this.meeting.recording)==null||_.removeListener("*",this.onUpdate),(A=this.meeting.connectedMeetings)==null||A.removeListener("*",this.onUpdate),(C=this.meeting.spotlight)==null||C.removeListener("*",this.onUpdate),(M=this.meeting.remote)==null||M.removeListener("*",this.onUpdate),(N=this.meeting.polls)==null||N.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const hh=Dt.exports.createContext({meeting:void 0,updates:void 0});function BN({value:t,children:e,fallback:r}){const[n,i]=Dt.exports.useState(),s=Dt.exports.useRef();return Dt.exports.useEffect(()=>(t&&i(new VN(t)),()=>{var o;(o=s.current)==null||o.clean()}),[t]),$y.createElement(hh.Provider,{value:{meeting:t,updates:n}},t?e:r)}const jN=()=>{const{meeting:t}=Dt.exports.useContext(hh);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},HN=t=>{const e=Dt.exports.useRef(!1),[r,n]=Dt.exports.useState(),i=t==null?void 0:t.resetOnLeave,s=async o=>{if(!e.current)return e.current=!0,Oy.init(o).then(a=>(n(a),a)).finally(()=>{e.current=!1})};return Dt.exports.useEffect(()=>{if(!r||!i)return()=>{};const o=({state:a})=>{a!=="connected-meeting"&&a!=="disconnected"&&n(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),Dt.exports.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=a=>{n(void 0),setTimeout(()=>{n(a)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,s]},WN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),$N=t=>{const{meeting:e,updates:r}=Dt.exports.useContext(hh);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const n=Dt.exports.useRef(t(e)),[,i]=Dt.exports.useReducer(s=>s+1,0);return Dt.exports.useEffect(()=>{const s=e&&t(e),o=()=>{const a=e&&t(e);WN(n.current,a)&&(n.current=a,i())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",i),()=>{s.removeListener("*",i)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),n.current},JN=t=>HN(t),GN=BN,qN=jN,zN=$N,KN=()=>qN,YN=t=>zN(t);exports.RealtimeKitProvider=GN;exports.useRTKSelector=YN;exports.useRealtimeKitClient=JN;exports.useRealtimeKitMeeting=KN;