@cloudflare/realtimekit 0.5.0-staging.102 → 0.5.0-staging.103

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/browser.js CHANGED
@@ -1,28 +1,22 @@
1
- var RealtimeKitClient=function(){"use strict";var Cc,kE=new Uint8Array(16);function wE(){if(!Cc&&(Cc=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Cc))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Cc(kE)}var _E=/^(?:[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 iu(t){return typeof t=="string"&&_E.test(t)}for(var _t=[],su=0;su<256;++su)_t.push((su+256).toString(16).substr(1));function IE(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=(_t[t[e+0]]+_t[t[e+1]]+_t[t[e+2]]+_t[t[e+3]]+"-"+_t[t[e+4]]+_t[t[e+5]]+"-"+_t[t[e+6]]+_t[t[e+7]]+"-"+_t[t[e+8]]+_t[t[e+9]]+"-"+_t[t[e+10]]+_t[t[e+11]]+_t[t[e+12]]+_t[t[e+13]]+_t[t[e+14]]+_t[t[e+15]]).toLowerCase();if(!iu(n))throw TypeError("Stringified UUID is invalid");return n}function Ar(t,e,n){t=t||{};var i=t.random||(t.rng||wE)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){n=n||0;for(var s=0;s<16;++s)e[n+s]=i[s];return e}return IE(i)}const CE={"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"},Em={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"},Xe={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Vt={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"},Ni={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class j{static getFirstMatch(e,n){const i=n.match(e);return i&&i.length>0&&i[1]||""}static getSecondMatch(e,n){const i=n.match(e);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(e,n,i){if(e.test(n))return i}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 n=e.split(".").splice(0,2).map(i=>parseInt(i,10)||0);if(n.push(0),n[0]===10)switch(n[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 n=e.split(".").splice(0,2).map(i=>parseInt(i,10)||0);if(n.push(0),!(n[0]===1&&n[1]<5)){if(n[0]===1&&n[1]<6)return"Cupcake";if(n[0]===1&&n[1]>=6)return"Donut";if(n[0]===2&&n[1]<2)return"Eclair";if(n[0]===2&&n[1]===2)return"Froyo";if(n[0]===2&&n[1]>2)return"Gingerbread";if(n[0]===3)return"Honeycomb";if(n[0]===4&&n[1]<1)return"Ice Cream Sandwich";if(n[0]===4&&n[1]<4)return"Jelly Bean";if(n[0]===4&&n[1]>=4)return"KitKat";if(n[0]===5)return"Lollipop";if(n[0]===6)return"Marshmallow";if(n[0]===7)return"Nougat";if(n[0]===8)return"Oreo";if(n[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,n,i=!1){const s=j.getVersionPrecision(e),r=j.getVersionPrecision(n);let a=Math.max(s,r),c=0;const d=j.map([e,n],h=>{const u=a-j.getVersionPrecision(h),g=h+new Array(u+1).join(".0");return j.map(g.split("."),E=>new Array(20-E.length).join("0")+E).reverse()});for(i&&(c=a-Math.min(s,r)),a-=1;a>=c;){if(d[0][a]>d[1][a])return 1;if(d[0][a]===d[1][a]){if(a===c)return 0;a-=1}else if(d[0][a]<d[1][a])return-1}}static map(e,n){const i=[];let s;if(Array.prototype.map)return Array.prototype.map.call(e,n);for(s=0;s<e.length;s+=1)i.push(n(e[s]));return i}static find(e,n){let i,s;if(Array.prototype.find)return Array.prototype.find.call(e,n);for(i=0,s=e.length;i<s;i+=1){const r=e[i];if(n(r,i))return r}}static assign(e,...n){const i=e;let s,r;if(Object.assign)return Object.assign(e,...n);for(s=0,r=n.length;s<r;s+=1){const a=n[s];typeof a=="object"&&a!==null&&Object.keys(a).forEach(d=>{i[d]=a[d]})}return e}static getBrowserAlias(e){return CE[e]}static getBrowserTypeByAlias(e){return Em[e]||""}}const Ie=/version\/(\d+(\.?_?\d+)+)/i,RE=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},n=j.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},n=j.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},n=j.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},n=j.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},n=j.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},n=j.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},n=j.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},n=j.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},n=j.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},n=j.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},n=j.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},n=j.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},n=j.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},n=j.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},n=j.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return n&&(e.version=n),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},n=j.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},n=j.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},n=j.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},n=j.getFirstMatch(Ie,t)||j.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},n=j.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},n=j.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},n=j.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},n=j.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},n=j.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},n=j.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},n=j.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},n=j.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},n=j.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){const e=!t.test(/like android/i),n=t.test(/android/i);return e&&n},describe(t){const e={name:"Android Browser"},n=j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},n=j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},n=j.getFirstMatch(Ie,t);return n&&(e.version=n),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,n=/^(.*)\/(.*)[ \t]\((.*)/,s=t.search("\\(")!==-1?n:e;return{name:j.getFirstMatch(s,t),version:j.getSecondMatch(s,t)}}}];var PE=[{test:[/Roku\/DVP/],describe(t){const e=j.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:Vt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=j.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:Vt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=j.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),n=j.getWindowsVersionName(e);return{name:Vt.Windows,version:e,versionName:n}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:Vt.iOS},n=j.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return n&&(e.version=n),e}},{test:[/macintosh/i],describe(t){const e=j.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),n=j.getMacOSVersionName(e),i={name:Vt.MacOS,version:e};return n&&(i.versionName=n),i}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=j.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:Vt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),n=t.test(/android/i);return e&&n},describe(t){const e=j.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),n=j.getAndroidVersionName(e),i={name:Vt.Android,version:e};return n&&(i.versionName=n),i}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=j.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),n={name:Vt.WebOS};return e&&e.length&&(n.version=e),n}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=j.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||j.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||j.getFirstMatch(/\bbb(\d+)/i,t);return{name:Vt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=j.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:Vt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=j.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:Vt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:Vt.Linux}}},{test:[/CrOS/],describe(){return{name:Vt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=j.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:Vt.PlayStation4,version:e}}}],AE=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=j.getFirstMatch(/(can-l01)/i,t)&&"Nova",n={type:Xe.mobile,vendor:"Huawei"};return e&&(n.model=e),n}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Xe.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Xe.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Xe.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Xe.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Xe.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Xe.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),n=t.test(/like (ipod|iphone)/i);return e&&!n},describe(t){const e=j.getFirstMatch(/(ipod|iphone)/i,t);return{type:Xe.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Xe.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Xe.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Xe.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Xe.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Xe.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Xe.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Xe.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Xe.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Xe.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Xe.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Xe.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Xe.tv}}}],ME=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Ni.Blink};const n=j.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Ni.EdgeHTML,version:n}}},{test:[/trident/i],describe(t){const e={name:Ni.Trident},n=j.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Ni.Presto},n=j.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test(t){const e=t.test(/gecko/i),n=t.test(/like gecko/i);return e&&!n},describe(t){const e={name:Ni.Gecko},n=j.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ni.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Ni.WebKit},n=j.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return n&&(e.version=n),e}}];class Sm{constructor(e,n=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},n!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=j.find(RE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));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=j.find(PE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));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:n}=this.getOS();return e?String(n).toLowerCase()||"":n||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:n}=this.getPlatform();return e?String(n).toLowerCase()||"":n||""}parsePlatform(){this.parsedResult.platform={};const e=j.find(AE,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));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=j.find(ME,n=>{if(typeof n.test=="function")return n.test(this);if(n.test instanceof Array)return n.test.some(i=>this.test(i));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 j.assign({},this.parsedResult)}satisfies(e){const n={};let i=0;const s={};let r=0;if(Object.keys(e).forEach(c=>{const d=e[c];typeof d=="string"?(s[c]=d,r+=1):typeof d=="object"&&(n[c]=d,i+=1)}),i>0){const c=Object.keys(n),d=j.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(n[d]);if(u!==void 0)return u}const h=j.find(c,u=>this.isPlatform(u));if(h){const u=this.satisfies(n[h]);if(u!==void 0)return u}}if(r>0){const c=Object.keys(s),d=j.find(c,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(s[d])}}isBrowser(e,n=!1){const i=this.getBrowserName().toLowerCase();let s=e.toLowerCase();const r=j.getBrowserTypeByAlias(s);return n&&r&&(s=r.toLowerCase()),s===i}compareVersion(e){let n=[0],i=e,s=!1;const r=this.getBrowserVersion();if(typeof r=="string")return e[0]===">"||e[0]==="<"?(i=e.substr(1),e[1]==="="?(s=!0,i=e.substr(2)):n=[],e[0]===">"?n.push(1):n.push(-1)):e[0]==="="?i=e.substr(1):e[0]==="~"&&(s=!0,i=e.substr(1)),n.indexOf(j.compareVersions(r,i,s))>-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,n=!1){return this.isBrowser(e,n)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(n=>this.is(n))}}/*!
1
+ var RealtimeKitClient=function(){"use strict";var $o,ly=new Uint8Array(16);function uy(){if(!$o&&($o=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!$o))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return $o(ly)}var hy=/^(?:[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 pl(t){return typeof t=="string"&&hy.test(t)}for(var st=[],ml=0;ml<256;++ml)st.push((ml+256).toString(16).substr(1));function py(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=(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(!pl(i))throw TypeError("Stringified UUID is invalid");return i}function Br(t,e,i){t=t||{};var n=t.random||(t.rng||uy)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){i=i||0;for(var r=0;r<16;++r)e[i+r]=n[r];return e}return py(n)}const my={"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"},ip={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"},Ue={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},vt={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"},cn={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class O{static getFirstMatch(e,i){const n=i.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,i){const n=i.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,i,n){if(e.test(i))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 i=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(i.push(0),i[0]===10)switch(i[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 i=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(i.push(0),!(i[0]===1&&i[1]<5)){if(i[0]===1&&i[1]<6)return"Cupcake";if(i[0]===1&&i[1]>=6)return"Donut";if(i[0]===2&&i[1]<2)return"Eclair";if(i[0]===2&&i[1]===2)return"Froyo";if(i[0]===2&&i[1]>2)return"Gingerbread";if(i[0]===3)return"Honeycomb";if(i[0]===4&&i[1]<1)return"Ice Cream Sandwich";if(i[0]===4&&i[1]<4)return"Jelly Bean";if(i[0]===4&&i[1]>=4)return"KitKat";if(i[0]===5)return"Lollipop";if(i[0]===6)return"Marshmallow";if(i[0]===7)return"Nougat";if(i[0]===8)return"Oreo";if(i[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,i,n=!1){const r=O.getVersionPrecision(e),s=O.getVersionPrecision(i);let o=Math.max(r,s),c=0;const d=O.map([e,i],l=>{const p=o-O.getVersionPrecision(l),g=l+new Array(p+1).join(".0");return O.map(g.split("."),y=>new Array(20-y.length).join("0")+y).reverse()});for(n&&(c=o-Math.min(r,s)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(e,i){const n=[];let r;if(Array.prototype.map)return Array.prototype.map.call(e,i);for(r=0;r<e.length;r+=1)n.push(i(e[r]));return n}static find(e,i){let n,r;if(Array.prototype.find)return Array.prototype.find.call(e,i);for(n=0,r=e.length;n<r;n+=1){const s=e[n];if(i(s,n))return s}}static assign(e,...i){const n=e;let r,s;if(Object.assign)return Object.assign(e,...i);for(r=0,s=i.length;r<s;r+=1){const o=i[r];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{n[d]=o[d]})}return e}static getBrowserAlias(e){return my[e]}static getBrowserTypeByAlias(e){return ip[e]||""}}const fe=/version\/(\d+(\.?_?\d+)+)/i,gy=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},i=O.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},i=O.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},i=O.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},i=O.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},i=O.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},i=O.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},i=O.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},i=O.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},i=O.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},i=O.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},i=O.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},i=O.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},i=O.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},i=O.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},i=O.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return i&&(e.version=i),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},i=O.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},i=O.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},i=O.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},i=O.getFirstMatch(fe,t)||O.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},i=O.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},i=O.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},i=O.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},i=O.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},i=O.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},i=O.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},i=O.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},i=O.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},i=O.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test(t){const e=!t.test(/like android/i),i=t.test(/android/i);return e&&i},describe(t){const e={name:"Android Browser"},i=O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},i=O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},i=O.getFirstMatch(fe,t);return i&&(e.version=i),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,i=/^(.*)\/(.*)[ \t]\((.*)/,r=t.search("\\(")!==-1?i:e;return{name:O.getFirstMatch(r,t),version:O.getSecondMatch(r,t)}}}];var fy=[{test:[/Roku\/DVP/],describe(t){const e=O.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:vt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=O.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:vt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=O.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),i=O.getWindowsVersionName(e);return{name:vt.Windows,version:e,versionName:i}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:vt.iOS},i=O.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return i&&(e.version=i),e}},{test:[/macintosh/i],describe(t){const e=O.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),i=O.getMacOSVersionName(e),n={name:vt.MacOS,version:e};return i&&(n.versionName=i),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=O.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:vt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),i=t.test(/android/i);return e&&i},describe(t){const e=O.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),i=O.getAndroidVersionName(e),n={name:vt.Android,version:e};return i&&(n.versionName=i),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=O.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),i={name:vt.WebOS};return e&&e.length&&(i.version=e),i}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=O.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||O.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||O.getFirstMatch(/\bbb(\d+)/i,t);return{name:vt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=O.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:vt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=O.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:vt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:vt.Linux}}},{test:[/CrOS/],describe(){return{name:vt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=O.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:vt.PlayStation4,version:e}}}],vy=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=O.getFirstMatch(/(can-l01)/i,t)&&"Nova",i={type:Ue.mobile,vendor:"Huawei"};return e&&(i.model=e),i}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ue.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ue.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ue.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ue.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ue.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ue.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),i=t.test(/like (ipod|iphone)/i);return e&&!i},describe(t){const e=O.getFirstMatch(/(ipod|iphone)/i,t);return{type:Ue.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ue.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ue.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Ue.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Ue.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Ue.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Ue.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Ue.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Ue.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Ue.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Ue.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Ue.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Ue.tv}}}],yy=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:cn.Blink};const i=O.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:cn.EdgeHTML,version:i}}},{test:[/trident/i],describe(t){const e={name:cn.Trident},i=O.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:cn.Presto},i=O.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test(t){const e=t.test(/gecko/i),i=t.test(/like gecko/i);return e&&!i},describe(t){const e={name:cn.Gecko},i=O.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:cn.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:cn.WebKit},i=O.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return i&&(e.version=i),e}}];class np{constructor(e,i=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},i!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=O.find(gy,i=>{if(typeof i.test=="function")return i.test(this);if(i.test instanceof Array)return i.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=O.find(fy,i=>{if(typeof i.test=="function")return i.test(this);if(i.test instanceof Array)return i.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:i}=this.getOS();return e?String(i).toLowerCase()||"":i||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:i}=this.getPlatform();return e?String(i).toLowerCase()||"":i||""}parsePlatform(){this.parsedResult.platform={};const e=O.find(vy,i=>{if(typeof i.test=="function")return i.test(this);if(i.test instanceof Array)return i.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=O.find(yy,i=>{if(typeof i.test=="function")return i.test(this);if(i.test instanceof Array)return i.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 O.assign({},this.parsedResult)}satisfies(e){const i={};let n=0;const r={};let s=0;if(Object.keys(e).forEach(c=>{const d=e[c];typeof d=="string"?(r[c]=d,s+=1):typeof d=="object"&&(i[c]=d,n+=1)}),n>0){const c=Object.keys(i),d=O.find(c,p=>this.isOS(p));if(d){const p=this.satisfies(i[d]);if(p!==void 0)return p}const l=O.find(c,p=>this.isPlatform(p));if(l){const p=this.satisfies(i[l]);if(p!==void 0)return p}}if(s>0){const c=Object.keys(r),d=O.find(c,l=>this.isBrowser(l,!0));if(d!==void 0)return this.compareVersion(r[d])}}isBrowser(e,i=!1){const n=this.getBrowserName().toLowerCase();let r=e.toLowerCase();const s=O.getBrowserTypeByAlias(r);return i&&s&&(r=s.toLowerCase()),r===n}compareVersion(e){let i=[0],n=e,r=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(r=!0,n=e.substr(2)):i=[],e[0]===">"?i.push(1):i.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(r=!0,n=e.substr(1)),i.indexOf(O.compareVersions(s,n,r))>-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,i=!1){return this.isBrowser(e,i)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(i=>this.is(i))}}/*!
2
2
  * Bowser - a browser detector
3
3
  * https://github.com/lancedikson/bowser
4
4
  * MIT License | (c) Dustin Diaz 2012-2015
5
5
  * MIT License | (c) Denis Demchenko 2015-2019
6
- */class Tm{static getParser(e,n=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new Sm(e,n)}static parse(e){return new Sm(e).getResult()}static get BROWSER_MAP(){return Em}static get ENGINE_MAP(){return Ni}static get OS_MAP(){return Vt}static get PLATFORMS_MAP(){return Xe}}function ru(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function OE(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let hi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Rc=[];for(let t=0;t<hi.length;t++)Rc[hi[t].charCodeAt(0)]=t;Rc["-".charCodeAt(0)]=hi.indexOf("+"),Rc["_".charCodeAt(0)]=hi.indexOf("/");function DE(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let n=new Uint8Array(e),i=0,s=0,r,a=0;for(let c=0;c<t.length;c++){if(r=Rc[t.charCodeAt(c)],r===void 0)switch(t[c]){case"=":s=0;case`
7
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:n[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:n[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:n[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return n.subarray(0,i)}function NE(t){let e="",n=0,i,s=0;for(let r=0;r<t.length;r++)switch(i=t[r],n){case 0:e+=hi[i>>2],s=(i&3)<<4,n=1;break;case 1:e+=hi[s|i>>4],s=(i&15)<<2,n=2;break;case 2:e+=hi[s|i>>6],e+=hi[i&63],n=0;break}return n&&(e+=hi[s],e+="=",n==1&&(e+="=")),e}var Pc;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(n,i,s,r,a)=>{(e(i)?i[t.symbol]:i[t.symbol]=[]).push({no:s,wireType:r,data:a})},t.onWrite=(n,i,s)=>{for(let{no:r,wireType:a,data:c}of t.list(i))s.tag(r,a).raw(c)},t.list=(n,i)=>{if(e(n)){let s=n[t.symbol];return i?s.filter(r=>r.no==i):s}return[]},t.last=(n,i)=>t.list(n,i).slice(-1)[0];const e=n=>n&&Array.isArray(n[t.symbol])})(Pc||(Pc={}));var Ze;(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"})(Ze||(Ze={}));function LE(){let t=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(t|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function au(t,e,n){for(let r=0;r<28;r=r+7){const a=t>>>r,c=!(a>>>7==0&&e==0),d=(c?a|128:a)&255;if(n.push(d),!c)return}const i=t>>>28&15|(e&7)<<4,s=e>>3!=0;if(n.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,c=a>>>7!=0,d=(c?a|128:a)&255;if(n.push(d),!c)return}n.push(e>>>31&1)}}const Ac=(1<<16)*(1<<16);function bm(t){let e=t[0]=="-";e&&(t=t.slice(1));const n=1e6;let i=0,s=0;function r(a,c){const d=Number(t.slice(a,c));s*=n,i=i*n+d,i>=Ac&&(s=s+(i/Ac|0),i=i%Ac)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),[e,i,s]}function ou(t,e){if(e>>>0<=2097151)return""+(Ac*e+(t>>>0));let n=t&16777215,i=(t>>>24|e<<8)>>>0&16777215,s=e>>16&65535,r=n+i*6777216+s*6710656,a=i+s*8147497,c=s*2,d=1e7;r>=d&&(a+=Math.floor(r/d),r%=d),a>=d&&(c+=Math.floor(a/d),a%=d);function h(u,g){let E=u?String(u):"";return g?"0000000".slice(E.length)+E:E}return h(c,0)+h(a,c)+h(r,1)}function km(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function xE(){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 n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let Ce;function VE(){const t=new DataView(new ArrayBuffer(8));Ce=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}VE();function wm(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const _m=/^-?[0-9]+$/,Mc=4294967296,Oc=2147483648;class Im{constructor(e,n){this.lo=e|0,this.hi=n|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Mc+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class At extends Im{static from(e){if(Ce)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Ce.C(e);case"number":if(e===0)return this.ZERO;e=Ce.C(e);case"bigint":if(!e)return this.ZERO;if(e<Ce.UMIN)throw new Error("signed value for ulong");if(e>Ce.UMAX)throw new Error("ulong too large");return Ce.V.setBigUint64(0,e,!0),new At(Ce.V.getInt32(0,!0),Ce.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!_m.test(e))throw new Error("string is no integer");let[n,i,s]=bm(e);if(n)throw new Error("signed value for ulong");return new At(i,s);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 At(e,e/Mc)}throw new Error("unknown value "+typeof e)}toString(){return Ce?this.toBigInt().toString():ou(this.lo,this.hi)}toBigInt(){return wm(Ce),Ce.V.setInt32(0,this.lo,!0),Ce.V.setInt32(4,this.hi,!0),Ce.V.getBigUint64(0,!0)}}At.ZERO=new At(0,0);class Pe extends Im{static from(e){if(Ce)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=Ce.C(e);case"number":if(e===0)return this.ZERO;e=Ce.C(e);case"bigint":if(!e)return this.ZERO;if(e<Ce.MIN)throw new Error("signed long too small");if(e>Ce.MAX)throw new Error("signed long too large");return Ce.V.setBigInt64(0,e,!0),new Pe(Ce.V.getInt32(0,!0),Ce.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!_m.test(e))throw new Error("string is no integer");let[n,i,s]=bm(e);if(n){if(s>Oc||s==Oc&&i!=0)throw new Error("signed long too small")}else if(s>=Oc)throw new Error("signed long too large");let r=new Pe(i,s);return n?r.negate():r;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new Pe(e,e/Mc):new Pe(-e,-e/Mc).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&Oc)!==0}negate(){let e=~this.hi,n=this.lo;return n?n=~n+1:e+=1,new Pe(n,e)}toString(){if(Ce)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+ou(e.lo,e.hi)}return ou(this.lo,this.hi)}toBigInt(){return wm(Ce),Ce.V.setInt32(0,this.lo,!0),Ce.V.setInt32(4,this.hi,!0),Ce.V.getBigInt64(0,!0)}}Pe.ZERO=new Pe(0,0);const Cm={readUnknownField:!0,readerFactory:t=>new BE(t)};function UE(t){return t?Object.assign(Object.assign({},Cm),t):Cm}class BE{constructor(e,n){this.varint64=LE,this.uint32=xE,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=n!=null?n:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),n=e>>>3,i=e&7;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e){let n=this.pos;switch(e){case Ze.Varint:for(;this.buf[this.pos++]&128;);break;case Ze.Bit64:this.pos+=4;case Ze.Bit32:this.pos+=4;break;case Ze.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Ze.StartGroup:let s;for(;(s=this.tag()[1])!==Ze.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,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 Pe(...this.varint64())}uint64(){return new At(...this.varint64())}sint64(){let[e,n]=this.varint64(),i=-(e&1);return e=(e>>>1|(n&1)<<31)^i,n=n>>>1^i,new Pe(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new At(this.sfixed32(),this.sfixed32())}sfixed64(){return new Pe(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(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(){return this.textDecoder.decode(this.bytes())}}function ye(t,e){if(!t)throw new Error(e)}const FE=34028234663852886e22,jE=-34028234663852886e22,WE=4294967295,HE=2147483647,qE=-2147483648;function Oa(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>HE||t<qE)throw new Error("invalid int 32: "+t)}function Dc(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>WE||t<0)throw new Error("invalid uint 32: "+t)}function cu(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>FE||t<jE))throw new Error("invalid float 32: "+t)}const Rm={writeUnknownFields:!0,writerFactory:()=>new JE};function GE(t){return t?Object.assign(Object.assign({},Rm),t):Rm}class JE{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let n=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)n.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Dc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Oa(e),km(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 n=this.textEncoder.encode(e);return this.uint32(n.byteLength),this.raw(n)}float(e){cu(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){Dc(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Oa(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Oa(e),e=(e<<1^e>>31)>>>0,km(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),s=Pe.from(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),i=new DataView(n.buffer),s=At.from(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(n)}int64(e){let n=Pe.from(e);return au(n.lo,n.hi,this.buf),this}sint64(e){let n=Pe.from(e),i=n.hi>>31,s=n.lo<<1^i,r=(n.hi<<1|n.lo>>>31)^i;return au(s,r,this.buf),this}uint64(e){let n=At.from(e);return au(n.lo,n.hi,this.buf),this}}const Pm={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Am={ignoreUnknownFields:!1};function $E(t){return t?Object.assign(Object.assign({},Am),t):Am}function KE(t){return t?Object.assign(Object.assign({},Pm),t):Pm}const Mm=Symbol.for("protobuf-ts/message-type");function Om(t){let e=!1;const n=[];for(let i=0;i<t.length;i++){let s=t.charAt(i);s=="_"?e=!0:/\d/.test(s)?(n.push(s),e=!0):e?(n.push(s.toUpperCase()),e=!1):i==0?n.push(s.toLowerCase()):n.push(s)}return n.join("")}var B;(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"})(B||(B={}));var Yn;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(Yn||(Yn={}));var Nc;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(Nc||(Nc={}));function zE(t){var e,n,i,s;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Om(t.name),t.jsonName=(n=t.jsonName)!==null&&n!==void 0?n:Om(t.name),t.repeat=(i=t.repeat)!==null&&i!==void 0?i:Nc.NO,t.opt=(s=t.opt)!==null&&s!==void 0?s:t.repeat||t.oneof?!1:t.kind=="message",t}function YE(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 QE{constructor(e){var n;this.fields=(n=e.fields)!==null&&n!==void 0?n:[]}prepare(){if(this.data)return;const e=[],n=[],i=[];for(let s of this.fields)if(s.oneof)i.includes(s.oneof)||(i.push(s.oneof),e.push(s.oneof),n.push(s.oneof));else switch(n.push(s.localName),s.kind){case"scalar":case"enum":(!s.opt||s.repeat)&&e.push(s.localName);break;case"message":s.repeat&&e.push(s.localName);break;case"map":e.push(s.localName);break}this.data={req:e,known:n,oneofs:Object.values(i)}}is(e,n,i=!1){if(n<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let s=Object.keys(e),r=this.data;if(s.length<r.req.length||r.req.some(a=>!s.includes(a))||!i&&s.some(a=>!r.known.includes(a)))return!1;if(n<1)return!0;for(const a of r.oneofs){const c=e[a];if(!YE(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,i,n))return!1}for(const a of this.fields)if(a.oneof===void 0&&!this.field(e[a.localName],a,i,n))return!1;return!0}field(e,n,i,s){let r=n.repeat;switch(n.kind){case"scalar":return e===void 0?n.opt:r?this.scalars(e,n.T,s,n.L):this.scalar(e,n.T,n.L);case"enum":return e===void 0?n.opt:r?this.scalars(e,B.INT32,s):this.scalar(e,B.INT32);case"message":return e===void 0?!0:r?this.messages(e,n.T(),i,s):this.message(e,n.T(),i,s);case"map":if(typeof e!="object"||e===null)return!1;if(s<2)return!0;if(!this.mapKeys(e,n.K,s))return!1;switch(n.V.kind){case"scalar":return this.scalars(Object.values(e),n.V.T,s,n.V.L);case"enum":return this.scalars(Object.values(e),B.INT32,s);case"message":return this.messages(Object.values(e),n.V.T(),i,s)}break}return!0}message(e,n,i,s){return i?n.isAssignable(e,s):n.is(e,s)}messages(e,n,i,s){if(!Array.isArray(e))return!1;if(s<2)return!0;if(i){for(let r=0;r<e.length&&r<s;r++)if(!n.isAssignable(e[r],s-1))return!1}else for(let r=0;r<e.length&&r<s;r++)if(!n.is(e[r],s-1))return!1;return!0}scalar(e,n,i){let s=typeof e;switch(n){case B.UINT64:case B.FIXED64:case B.INT64:case B.SFIXED64:case B.SINT64:switch(i){case Yn.BIGINT:return s=="bigint";case Yn.NUMBER:return s=="number"&&!isNaN(e);default:return s=="string"}case B.BOOL:return s=="boolean";case B.STRING:return s=="string";case B.BYTES:return e instanceof Uint8Array;case B.DOUBLE:case B.FLOAT:return s=="number"&&!isNaN(e);default:return s=="number"&&Number.isInteger(e)}}scalars(e,n,i,s){if(!Array.isArray(e))return!1;if(i<2)return!0;if(Array.isArray(e)){for(let r=0;r<e.length&&r<i;r++)if(!this.scalar(e[r],n,s))return!1}return!0}mapKeys(e,n,i){let s=Object.keys(e);switch(n){case B.INT32:case B.FIXED32:case B.SFIXED32:case B.SINT32:case B.UINT32:return this.scalars(s.slice(0,i).map(r=>parseInt(r)),n,i);case B.BOOL:return this.scalars(s.slice(0,i).map(r=>r=="true"?!0:r=="false"?!1:r),n,i);default:return this.scalars(s,n,i,Yn.STRING)}}}function Rn(t,e){switch(e){case Yn.BIGINT:return t.toBigInt();case Yn.NUMBER:return t.toNumber();default:return t.toString()}}class XE{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const n=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const i of n)this.fMap[i.name]=i,this.fMap[i.jsonName]=i,this.fMap[i.localName]=i}}assert(e,n,i){if(!e){let s=ru(i);throw(s=="number"||s=="boolean")&&(s=i.toString()),new Error(`Cannot parse JSON ${s} for ${this.info.typeName}#${n}`)}}read(e,n,i){this.prepare();const s=[];for(const[r,a]of Object.entries(e)){const c=this.fMap[r];if(!c){if(!i.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${r}`);continue}const d=c.localName;let h;if(c.oneof){if(a===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(s.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);s.push(c.oneof),h=n[c.oneof]={oneofKind:d}}else h=n;if(c.kind=="map"){if(a===null)continue;this.assert(OE(a),c.name,a);const u=h[d];for(const[g,E]of Object.entries(a)){this.assert(E!==null,c.name+" map value",null);let b;switch(c.V.kind){case"message":b=c.V.T().internalJsonRead(E,i);break;case"enum":if(b=this.enum(c.V.T(),E,c.name,i.ignoreUnknownFields),b===!1)continue;break;case"scalar":b=this.scalar(E,c.V.T,c.V.L,c.name);break}this.assert(b!==void 0,c.name+" map value",E);let w=g;c.K==B.BOOL&&(w=w=="true"?!0:w=="false"?!1:w),w=this.scalar(w,c.K,Yn.STRING,c.name).toString(),u[w]=b}}else if(c.repeat){if(a===null)continue;this.assert(Array.isArray(a),c.name,a);const u=h[d];for(const g of a){this.assert(g!==null,c.name,null);let E;switch(c.kind){case"message":E=c.T().internalJsonRead(g,i);break;case"enum":if(E=this.enum(c.T(),g,c.name,i.ignoreUnknownFields),E===!1)continue;break;case"scalar":E=this.scalar(g,c.T,c.L,c.name);break}this.assert(E!==void 0,c.name,a),u.push(E)}}else switch(c.kind){case"message":if(a===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}h[d]=c.T().internalJsonRead(a,i,h[d]);break;case"enum":if(a===null)continue;let u=this.enum(c.T(),a,c.name,i.ignoreUnknownFields);if(u===!1)continue;h[d]=u;break;case"scalar":if(a===null)continue;h[d]=this.scalar(a,c.T,c.L,c.name);break}}}enum(e,n,i,s){if(e[0]=="google.protobuf.NullValue"&&ye(n===null||n==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${i}, enum ${e[0]} only accepts null.`),n===null)return 0;switch(typeof n){case"number":return ye(Number.isInteger(n),`Unable to parse field ${this.info.typeName}#${i}, enum can only be integral number, got ${n}.`),n;case"string":let r=n;e[2]&&n.substring(0,e[2].length)===e[2]&&(r=n.substring(e[2].length));let a=e[1][r];return typeof a=="undefined"&&s?!1:(ye(typeof a=="number",`Unable to parse field ${this.info.typeName}#${i}, enum ${e[0]} has no value for "${n}".`),a)}ye(!1,`Unable to parse field ${this.info.typeName}#${i}, cannot parse enum value from ${typeof n}".`)}scalar(e,n,i,s){let r;try{switch(n){case B.DOUBLE:case B.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===""){r="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){r="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let a=Number(e);if(Number.isNaN(a)){r="not a number";break}if(!Number.isFinite(a)){r="too large or small";break}return n==B.FLOAT&&cu(a),a;case B.INT32:case B.FIXED32:case B.SFIXED32:case B.SINT32:case B.UINT32:if(e===null)return 0;let c;if(typeof e=="number"?c=e:e===""?r="empty string":typeof e=="string"&&(e.trim().length!==e.length?r="extra whitespace":c=Number(e)),c===void 0)break;return n==B.UINT32?Dc(c):Oa(c),c;case B.INT64:case B.SFIXED64:case B.SINT64:if(e===null)return Rn(Pe.ZERO,i);if(typeof e!="number"&&typeof e!="string")break;return Rn(Pe.from(e),i);case B.FIXED64:case B.UINT64:if(e===null)return Rn(At.ZERO,i);if(typeof e!="number"&&typeof e!="string")break;return Rn(At.from(e),i);case B.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case B.STRING:if(e===null)return"";if(typeof e!="string"){r="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case B.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return DE(e)}}catch(a){r=a.message}this.assert(!1,s+(r?" - "+r:""),e)}}class ZE{constructor(e){var n;this.fields=(n=e.fields)!==null&&n!==void 0?n:[]}write(e,n){const i={},s=e;for(const r of this.fields){if(!r.oneof){let h=this.field(r,s[r.localName],n);h!==void 0&&(i[n.useProtoFieldName?r.name:r.jsonName]=h);continue}const a=s[r.oneof];if(a.oneofKind!==r.localName)continue;const c=r.kind=="scalar"||r.kind=="enum"?Object.assign(Object.assign({},n),{emitDefaultValues:!0}):n;let d=this.field(r,a[r.localName],c);ye(d!==void 0),i[n.useProtoFieldName?r.name:r.jsonName]=d}return i}field(e,n,i){let s;if(e.kind=="map"){ye(typeof n=="object"&&n!==null);const r={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(n)){const u=this.scalar(e.V.T,h,e.name,!1,!0);ye(u!==void 0),r[d.toString()]=u}break;case"message":const a=e.V.T();for(const[d,h]of Object.entries(n)){const u=this.message(a,h,e.name,i);ye(u!==void 0),r[d.toString()]=u}break;case"enum":const c=e.V.T();for(const[d,h]of Object.entries(n)){ye(h===void 0||typeof h=="number");const u=this.enum(c,h,e.name,!1,!0,i.enumAsInteger);ye(u!==void 0),r[d.toString()]=u}break}(i.emitDefaultValues||Object.keys(r).length>0)&&(s=r)}else if(e.repeat){ye(Array.isArray(n));const r=[];switch(e.kind){case"scalar":for(let d=0;d<n.length;d++){const h=this.scalar(e.T,n[d],e.name,e.opt,!0);ye(h!==void 0),r.push(h)}break;case"enum":const a=e.T();for(let d=0;d<n.length;d++){ye(n[d]===void 0||typeof n[d]=="number");const h=this.enum(a,n[d],e.name,e.opt,!0,i.enumAsInteger);ye(h!==void 0),r.push(h)}break;case"message":const c=e.T();for(let d=0;d<n.length;d++){const h=this.message(c,n[d],e.name,i);ye(h!==void 0),r.push(h)}break}(i.emitDefaultValues||r.length>0||i.emitDefaultValues)&&(s=r)}else switch(e.kind){case"scalar":s=this.scalar(e.T,n,e.name,e.opt,i.emitDefaultValues);break;case"enum":s=this.enum(e.T(),n,e.name,e.opt,i.emitDefaultValues,i.enumAsInteger);break;case"message":s=this.message(e.T(),n,e.name,i);break}return s}enum(e,n,i,s,r,a){if(e[0]=="google.protobuf.NullValue")return!r&&!s?void 0:null;if(n===void 0){ye(s);return}if(!(n===0&&!r&&!s))return ye(typeof n=="number"),ye(Number.isInteger(n)),a||!e[1].hasOwnProperty(n)?n:e[2]?e[2]+e[1][n]:e[1][n]}message(e,n,i,s){return n===void 0?s.emitDefaultValues?null:void 0:e.internalJsonWrite(n,s)}scalar(e,n,i,s,r){if(n===void 0){ye(s);return}const a=r||s;switch(e){case B.INT32:case B.SFIXED32:case B.SINT32:return n===0?a?0:void 0:(Oa(n),n);case B.FIXED32:case B.UINT32:return n===0?a?0:void 0:(Dc(n),n);case B.FLOAT:cu(n);case B.DOUBLE:return n===0?a?0:void 0:(ye(typeof n=="number"),Number.isNaN(n)?"NaN":n===Number.POSITIVE_INFINITY?"Infinity":n===Number.NEGATIVE_INFINITY?"-Infinity":n);case B.STRING:return n===""?a?"":void 0:(ye(typeof n=="string"),n);case B.BOOL:return n===!1?a?!1:void 0:(ye(typeof n=="boolean"),n);case B.UINT64:case B.FIXED64:ye(typeof n=="number"||typeof n=="string"||typeof n=="bigint");let c=At.from(n);return c.isZero()&&!a?void 0:c.toString();case B.INT64:case B.SFIXED64:case B.SINT64:ye(typeof n=="number"||typeof n=="string"||typeof n=="bigint");let d=Pe.from(n);return d.isZero()&&!a?void 0:d.toString();case B.BYTES:return ye(n instanceof Uint8Array),n.byteLength?NE(n):a?"":void 0}}}function du(t,e=Yn.STRING){switch(t){case B.BOOL:return!1;case B.UINT64:case B.FIXED64:return Rn(At.ZERO,e);case B.INT64:case B.SFIXED64:case B.SINT64:return Rn(Pe.ZERO,e);case B.DOUBLE:case B.FLOAT:return 0;case B.BYTES:return new Uint8Array(0);case B.STRING:return"";default:return 0}}class eS{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const n=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(n.map(i=>[i.no,i]))}}read(e,n,i,s){this.prepare();const r=s===void 0?e.len:e.pos+s;for(;e.pos<r;){const[a,c]=e.tag(),d=this.fieldNoToField.get(a);if(!d){let E=i.readUnknownField;if(E=="throw")throw new Error(`Unknown field ${a} (wire type ${c}) for ${this.info.typeName}`);let b=e.skip(c);E!==!1&&(E===!0?Pc.onRead:E)(this.info.typeName,n,a,c,b);continue}let h=n,u=d.repeat,g=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==g&&(h=n[d.oneof]={oneofKind:g})),d.kind){case"scalar":case"enum":let E=d.kind=="enum"?B.INT32:d.T,b=d.kind=="scalar"?d.L:void 0;if(u){let D=h[g];if(c==Ze.LengthDelimited&&E!=B.STRING&&E!=B.BYTES){let F=e.uint32()+e.pos;for(;e.pos<F;)D.push(this.scalar(e,E,b))}else D.push(this.scalar(e,E,b))}else h[g]=this.scalar(e,E,b);break;case"message":if(u){let D=h[g],F=d.T().internalBinaryRead(e,e.uint32(),i);D.push(F)}else h[g]=d.T().internalBinaryRead(e,e.uint32(),i,h[g]);break;case"map":let[w,M]=this.mapEntry(d,e,i);h[g][w]=M;break}}}mapEntry(e,n,i){let s=n.uint32(),r=n.pos+s,a,c;for(;n.pos<r;){let[d,h]=n.tag();switch(d){case 1:e.K==B.BOOL?a=n.bool().toString():a=this.scalar(n,e.K,Yn.STRING);break;case 2:switch(e.V.kind){case"scalar":c=this.scalar(n,e.V.T,e.V.L);break;case"enum":c=n.int32();break;case"message":c=e.V.T().internalBinaryRead(n,n.uint32(),i);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(a===void 0){let d=du(e.K);a=e.K==B.BOOL?d.toString():d}if(c===void 0)switch(e.V.kind){case"scalar":c=du(e.V.T,e.V.L);break;case"enum":c=0;break;case"message":c=e.V.T().create();break}return[a,c]}scalar(e,n,i){switch(n){case B.INT32:return e.int32();case B.STRING:return e.string();case B.BOOL:return e.bool();case B.DOUBLE:return e.double();case B.FLOAT:return e.float();case B.INT64:return Rn(e.int64(),i);case B.UINT64:return Rn(e.uint64(),i);case B.FIXED64:return Rn(e.fixed64(),i);case B.FIXED32:return e.fixed32();case B.BYTES:return e.bytes();case B.UINT32:return e.uint32();case B.SFIXED32:return e.sfixed32();case B.SFIXED64:return Rn(e.sfixed64(),i);case B.SINT32:return e.sint32();case B.SINT64:return Rn(e.sint64(),i)}}}class tS{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((n,i)=>n.no-i.no)}}write(e,n,i){this.prepare();for(const r of this.fields){let a,c,d=r.repeat,h=r.localName;if(r.oneof){const u=e[r.oneof];if(u.oneofKind!==h)continue;a=u[h],c=!0}else a=e[h],c=!1;switch(r.kind){case"scalar":case"enum":let u=r.kind=="enum"?B.INT32:r.T;if(d)if(ye(Array.isArray(a)),d==Nc.PACKED)this.packed(n,u,r.no,a);else for(const g of a)this.scalar(n,u,r.no,g,!0);else a===void 0?ye(r.opt):this.scalar(n,u,r.no,a,c||r.opt);break;case"message":if(d){ye(Array.isArray(a));for(const g of a)this.message(n,i,r.T(),r.no,g)}else this.message(n,i,r.T(),r.no,a);break;case"map":ye(typeof a=="object"&&a!==null);for(const[g,E]of Object.entries(a))this.mapEntry(n,i,r,g,E);break}}let s=i.writeUnknownFields;s!==!1&&(s===!0?Pc.onWrite:s)(this.info.typeName,e,n)}mapEntry(e,n,i,s,r){e.tag(i.no,Ze.LengthDelimited),e.fork();let a=s;switch(i.K){case B.INT32:case B.FIXED32:case B.UINT32:case B.SFIXED32:case B.SINT32:a=Number.parseInt(s);break;case B.BOOL:ye(s=="true"||s=="false"),a=s=="true";break}switch(this.scalar(e,i.K,1,a,!0),i.V.kind){case"scalar":this.scalar(e,i.V.T,2,r,!0);break;case"enum":this.scalar(e,B.INT32,2,r,!0);break;case"message":this.message(e,n,i.V.T(),2,r);break}e.join()}message(e,n,i,s,r){r!==void 0&&(i.internalBinaryWrite(r,e.tag(s,Ze.LengthDelimited).fork(),n),e.join())}scalar(e,n,i,s,r){let[a,c,d]=this.scalarInfo(n,s);(!d||r)&&(e.tag(i,a),e[c](s))}packed(e,n,i,s){if(!s.length)return;ye(n!==B.BYTES&&n!==B.STRING),e.tag(i,Ze.LengthDelimited),e.fork();let[,r]=this.scalarInfo(n);for(let a=0;a<s.length;a++)e[r](s[a]);e.join()}scalarInfo(e,n){let i=Ze.Varint,s,r=n===void 0,a=n===0;switch(e){case B.INT32:s="int32";break;case B.STRING:a=r||!n.length,i=Ze.LengthDelimited,s="string";break;case B.BOOL:a=n===!1,s="bool";break;case B.UINT32:s="uint32";break;case B.DOUBLE:i=Ze.Bit64,s="double";break;case B.FLOAT:i=Ze.Bit32,s="float";break;case B.INT64:a=r||Pe.from(n).isZero(),s="int64";break;case B.UINT64:a=r||At.from(n).isZero(),s="uint64";break;case B.FIXED64:a=r||At.from(n).isZero(),i=Ze.Bit64,s="fixed64";break;case B.BYTES:a=r||!n.byteLength,i=Ze.LengthDelimited,s="bytes";break;case B.FIXED32:i=Ze.Bit32,s="fixed32";break;case B.SFIXED32:i=Ze.Bit32,s="sfixed32";break;case B.SFIXED64:a=r||Pe.from(n).isZero(),i=Ze.Bit64,s="sfixed64";break;case B.SINT32:s="sint32";break;case B.SINT64:a=r||Pe.from(n).isZero(),s="sint64";break}return[i,s,r||a]}}function nS(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},Mm,{value:t});for(let n of t.fields){let i=n.localName;if(!n.opt)if(n.oneof)e[n.oneof]={oneofKind:void 0};else if(n.repeat)e[i]=[];else switch(n.kind){case"scalar":e[i]=du(n.T,n.L);break;case"enum":e[i]=0;break;case"map":e[i]={};break}}return e}function lu(t,e,n){let i,s=n,r;for(let a of t.fields){let c=a.localName;if(a.oneof){const d=s[a.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(i=d[c],r=e[a.oneof],r.oneofKind=d.oneofKind,i==null){delete r[c];continue}}else if(i=s[c],r=e,i==null)continue;switch(a.repeat&&(r[c].length=i.length),a.kind){case"scalar":case"enum":if(a.repeat)for(let h=0;h<i.length;h++)r[c][h]=i[h];else r[c]=i;break;case"message":let d=a.T();if(a.repeat)for(let h=0;h<i.length;h++)r[c][h]=d.create(i[h]);else r[c]===void 0?r[c]=d.create(i):d.mergePartial(r[c],i);break;case"map":switch(a.V.kind){case"scalar":case"enum":Object.assign(r[c],i);break;case"message":let h=a.V.T();for(let u of Object.keys(i))r[c][u]=h.create(i[u]);break}break}}}function iS(t,e,n){if(e===n)return!0;if(!e||!n)return!1;for(let i of t.fields){let s=i.localName,r=i.oneof?e[i.oneof][s]:e[s],a=i.oneof?n[i.oneof][s]:n[s];switch(i.kind){case"enum":case"scalar":let c=i.kind=="enum"?B.INT32:i.T;if(!(i.repeat?Nm(c,r,a):Dm(c,r,a)))return!1;break;case"map":if(!(i.V.kind=="message"?Lm(i.V.T(),Lc(r),Lc(a)):Nm(i.V.kind=="enum"?B.INT32:i.V.T,Lc(r),Lc(a))))return!1;break;case"message":let d=i.T();if(!(i.repeat?Lm(d,r,a):d.equals(r,a)))return!1;break}}return!0}const Lc=Object.values;function Dm(t,e,n){if(e===n)return!0;if(t!==B.BYTES)return!1;let i=e,s=n;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!=s[r])return!1;return!0}function Nm(t,e,n){if(e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(!Dm(t,e[i],n[i]))return!1;return!0}function Lm(t,e,n){if(e.length!==n.length)return!1;for(let i=0;i<e.length;i++)if(!t.equals(e[i],n[i]))return!1;return!0}const sS=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class _{constructor(e,n,i){this.defaultCheckDepth=16,this.typeName=e,this.fields=n.map(zE),this.options=i!=null?i:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},sS),{[Mm]:{value:this}})),this.refTypeCheck=new QE(this),this.refJsonReader=new XE(this),this.refJsonWriter=new ZE(this),this.refBinReader=new eS(this),this.refBinWriter=new tS(this)}create(e){let n=nS(this);return e!==void 0&&lu(this,n,e),n}clone(e){let n=this.create();return lu(this,n,e),n}equals(e,n){return iS(this,e,n)}is(e,n=this.defaultCheckDepth){return this.refTypeCheck.is(e,n,!1)}isAssignable(e,n=this.defaultCheckDepth){return this.refTypeCheck.is(e,n,!0)}mergePartial(e,n){lu(this,e,n)}fromBinary(e,n){let i=UE(n);return this.internalBinaryRead(i.readerFactory(e),e.byteLength,i)}fromJson(e,n){return this.internalJsonRead(e,$E(n))}fromJsonString(e,n){let i=JSON.parse(e);return this.fromJson(i,n)}toJson(e,n){return this.internalJsonWrite(e,KE(n))}toJsonString(e,n){var i;let s=this.toJson(e,n);return JSON.stringify(s,null,(i=n==null?void 0:n.prettySpaces)!==null&&i!==void 0?i:0)}toBinary(e,n){let i=GE(n);return this.internalBinaryWrite(e,i.writerFactory(),i).finish()}internalJsonRead(e,n,i){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let s=i!=null?i:this.create();return this.refJsonReader.read(e,s,n),s}throw new Error(`Unable to parse message ${this.typeName} from JSON ${ru(e)}.`)}internalJsonWrite(e,n){return this.refJsonWriter.write(e,n)}internalBinaryWrite(e,n,i){return this.refBinWriter.write(e,n,i),n}internalBinaryRead(e,n,i,s){let r=s!=null?s:this.create();return this.refBinReader.read(e,r,i,n),r}}const rS=t=>(e,n)=>(t.set(e,n),n),xm=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Vm=536870912,Um=Vm*2,aS=(t,e)=>n=>{const i=e.get(n);let s=i===void 0?n.size:i<Um?i+1:0;if(!n.has(s))return t(n,s);if(n.size<Vm){for(;n.has(s);)s=Math.floor(Math.random()*Um);return t(n,s)}if(n.size>xm)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;n.has(s);)s=Math.floor(Math.random()*xm);return t(n,s)},Bm=new WeakMap,oS=rS(Bm),xc=aS(oS,Bm),cS=t=>t.method!==void 0&&t.method==="call",dS=t=>t.error===null&&typeof t.id=="number",Vc=((t,e)=>{let n=null;return()=>{if(n!==null)return n;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return n=t(s),setTimeout(()=>URL.revokeObjectURL(s)),n}})(t=>{const e=new Map([[0,()=>{}]]),n=new Map([[0,()=>{}]]),i=new Map,s=new Worker(t);return s.addEventListener("message",({data:h})=>{if(cS(h)){const{params:{timerId:u,timerType:g}}=h;if(g==="interval"){const E=e.get(u);if(typeof E=="number"){const b=i.get(E);if(b===void 0||b.timerId!==u||b.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof E!="undefined")E();else throw new Error("The timer is in an undefined state.")}else if(g==="timeout"){const E=n.get(u);if(typeof E=="number"){const b=i.get(E);if(b===void 0||b.timerId!==u||b.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof E!="undefined")E(),n.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(dS(h)){const{id:u}=h,g=i.get(u);if(g===void 0)throw new Error("The timer is in an undefined state.");const{timerId:E,timerType:b}=g;i.delete(u),b==="interval"?e.delete(E):n.delete(E)}else{const{error:{message:u}}=h;throw new Error(u)}}),{clearInterval:h=>{const u=xc(i);i.set(u,{timerId:h,timerType:"interval"}),e.set(h,u),s.postMessage({id:u,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const u=xc(i);i.set(u,{timerId:h,timerType:"timeout"}),n.set(h,u),s.postMessage({id:u,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,u=0)=>{const g=xc(e);return e.set(g,()=>{h(),typeof e.get(g)=="function"&&s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"interval"}}),g},setTimeout:(h,u=0)=>{const g=xc(n);return n.set(g,h),s.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:g,timerType:"timeout"}}),g}}},`(()=>{"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})}}))})();`),Mr=t=>Vc().clearInterval(t),lS=t=>Vc().clearTimeout(t),Uc=(t,e)=>Vc().setInterval(t,e);var uS=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Mr,clearTimeout:lS,setInterval:Uc,setTimeout:(t,e)=>Vc().setTimeout(t,e)},Symbol.toStringTag,{value:"Module"})),Fm={},uu={exports:{}},jm=uu.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(jm).forEach(function(t){var e=jm[t];e.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),function(t){var e=function(c){return String(Number(c))===c?Number(c):c},n=function(c,d,h,u){if(u&&!h)d[u]=e(c[1]);else for(var g=0;g<h.length;g+=1)c[g+1]!=null&&(d[h[g]]=e(c[g+1]))},i=function(c,d,h){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var g=c.push?{}:u?d[c.name]:d;n(h.match(c.reg),g,c.names,c.name),c.push&&d[c.push].push(g)},s=uu.exports,r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(c){var d={},h=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(r).forEach(function(g){var E=g[0],b=g.slice(2);E==="m"&&(h.push({rtp:[],fmtp:[]}),u=h[h.length-1]);for(var w=0;w<(s[E]||[]).length;w+=1){var M=s[E][w];if(M.reg.test(b))return i(M,u,b)}}),d.media=h,d};var a=function(c,d){var h=d.split(/=(.+)/,2);return h.length===2?c[h[0]]=e(h[1]):h.length===1&&d.length>1&&(c[h[0]]=void 0),c};t.parseParams=function(c){return c.split(/;\s?/).reduce(a,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(c){return c.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(c){for(var d=[],h=c.split(" ").map(e),u=0;u<h.length;u+=3)d.push({component:h[u],ip:h[u+1],port:h[u+2]});return d},t.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},t.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(h){var u,g=!1;return h[0]!=="~"?u=e(h):(u=e(h.substring(1,h.length)),g=!0),{scid:u,paused:g}})})}}(Fm);var hu=uu.exports,hS=/%[sdv%]/g,pS=function(t){var e=1,n=arguments,i=n.length;return t.replace(hS,function(s){if(e>=i)return s;var r=n[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}})},Da=function(t,e,n){var i=e.format instanceof Function?e.format(e.push?n:n[e.name]):e.format,s=[t+"="+i];if(e.names)for(var r=0;r<e.names.length;r+=1){var a=e.names[r];e.name?s.push(n[e.name][a]):s.push(n[e.names[r]])}else s.push(n[e.name]);return pS.apply(null,s)},mS=["v","o","s","i","u","e","p","c","b","t","r","z","a"],fS=["i","c","b","a"],gS=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(r){r.payloads==null&&(r.payloads="")});var n=e.outerOrder||mS,i=e.innerOrder||fS,s=[];return n.forEach(function(r){hu[r].forEach(function(a){a.name in t&&t[a.name]!=null?s.push(Da(r,a,t)):a.push in t&&t[a.push]!=null&&t[a.push].forEach(function(c){s.push(Da(r,a,c))})})}),t.media.forEach(function(r){s.push(Da("m",hu.m[0],r)),i.forEach(function(a){hu[a].forEach(function(c){c.name in r&&r[c.name]!=null?s.push(Da(a,c,r)):c.push in r&&r[c.push]!=null&&r[c.push].forEach(function(d){s.push(Da(a,c,d))})})})}),s.join(`\r
6
+ */class rp{static getParser(e,i=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new np(e,i)}static parse(e){return new np(e).getResult()}static get BROWSER_MAP(){return ip}static get ENGINE_MAP(){return cn}static get OS_MAP(){return vt}static get PLATFORMS_MAP(){return Ue}}function gl(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function Sy(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let Fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Ko=[];for(let t=0;t<Fi.length;t++)Ko[Fi[t].charCodeAt(0)]=t;Ko["-".charCodeAt(0)]=Fi.indexOf("+"),Ko["_".charCodeAt(0)]=Fi.indexOf("/");function Ey(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let i=new Uint8Array(e),n=0,r=0,s,o=0;for(let c=0;c<t.length;c++){if(s=Ko[t.charCodeAt(c)],s===void 0)switch(t[c]){case"=":r=0;case`
7
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:i[n++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:i[n++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:i[n++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return i.subarray(0,n)}function Ty(t){let e="",i=0,n,r=0;for(let s=0;s<t.length;s++)switch(n=t[s],i){case 0:e+=Fi[n>>2],r=(n&3)<<4,i=1;break;case 1:e+=Fi[r|n>>4],r=(n&15)<<2,i=2;break;case 2:e+=Fi[r|n>>6],e+=Fi[n&63],i=0;break}return i&&(e+=Fi[r],e+="=",i==1&&(e+="=")),e}var zo;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(i,n,r,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:r,wireType:s,data:o})},t.onWrite=(i,n,r)=>{for(let{no:s,wireType:o,data:c}of t.list(n))r.tag(s,o).raw(c)},t.list=(i,n)=>{if(e(i)){let r=i[t.symbol];return n?r.filter(s=>s.no==n):r}return[]},t.last=(i,n)=>t.list(i,n).slice(-1)[0];const e=i=>i&&Array.isArray(i[t.symbol])})(zo||(zo={}));var Fe;(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"})(Fe||(Fe={}));function ky(){let t=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[t,e]}let i=this.buf[this.pos++];if(t|=(i&15)<<28,e=(i&112)>>4,(i&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function fl(t,e,i){for(let s=0;s<28;s=s+7){const o=t>>>s,c=!(o>>>7==0&&e==0),d=(c?o|128:o)&255;if(i.push(d),!c)return}const n=t>>>28&15|(e&7)<<4,r=e>>3!=0;if(i.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,c=o>>>7!=0,d=(c?o|128:o)&255;if(i.push(d),!c)return}i.push(e>>>31&1)}}const Yo=(1<<16)*(1<<16);function sp(t){let e=t[0]=="-";e&&(t=t.slice(1));const i=1e6;let n=0,r=0;function s(o,c){const d=Number(t.slice(o,c));r*=i,n=n*i+d,n>=Yo&&(r=r+(n/Yo|0),n=n%Yo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,r]}function vl(t,e){if(e>>>0<=2097151)return""+(Yo*e+(t>>>0));let i=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,r=e>>16&65535,s=i+n*6777216+r*6710656,o=n+r*8147497,c=r*2,d=1e7;s>=d&&(o+=Math.floor(s/d),s%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(p,g){let y=p?String(p):"";return g?"0000000".slice(y.length)+y:y}return l(c,0)+l(o,c)+l(s,1)}function ap(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let i=0;i<9;i++)e.push(t&127|128),t=t>>7;e.push(1)}}function by(){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 i=5;(t&128)!==0&&i<10;i++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let ve;function _y(){const t=new DataView(new ArrayBuffer(8));ve=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}_y();function op(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const cp=/^-?[0-9]+$/,Qo=4294967296,Xo=2147483648;class dp{constructor(e,i){this.lo=e|0,this.hi=i|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*Qo+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class dt extends dp{static from(e){if(ve)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ve.C(e);case"number":if(e===0)return this.ZERO;e=ve.C(e);case"bigint":if(!e)return this.ZERO;if(e<ve.UMIN)throw new Error("signed value for ulong");if(e>ve.UMAX)throw new Error("ulong too large");return ve.V.setBigUint64(0,e,!0),new dt(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!cp.test(e))throw new Error("string is no integer");let[i,n,r]=sp(e);if(i)throw new Error("signed value for ulong");return new dt(n,r);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 dt(e,e/Qo)}throw new Error("unknown value "+typeof e)}toString(){return ve?this.toBigInt().toString():vl(this.lo,this.hi)}toBigInt(){return op(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigUint64(0,!0)}}dt.ZERO=new dt(0,0);class Se extends dp{static from(e){if(ve)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ve.C(e);case"number":if(e===0)return this.ZERO;e=ve.C(e);case"bigint":if(!e)return this.ZERO;if(e<ve.MIN)throw new Error("signed long too small");if(e>ve.MAX)throw new Error("signed long too large");return ve.V.setBigInt64(0,e,!0),new Se(ve.V.getInt32(0,!0),ve.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!cp.test(e))throw new Error("string is no integer");let[i,n,r]=sp(e);if(i){if(r>Xo||r==Xo&&n!=0)throw new Error("signed long too small")}else if(r>=Xo)throw new Error("signed long too large");let s=new Se(n,r);return i?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 Se(e,e/Qo):new Se(-e,-e/Qo).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&Xo)!==0}negate(){let e=~this.hi,i=this.lo;return i?i=~i+1:e+=1,new Se(i,e)}toString(){if(ve)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+vl(e.lo,e.hi)}return vl(this.lo,this.hi)}toBigInt(){return op(ve),ve.V.setInt32(0,this.lo,!0),ve.V.setInt32(4,this.hi,!0),ve.V.getBigInt64(0,!0)}}Se.ZERO=new Se(0,0);const lp={readUnknownField:!0,readerFactory:t=>new Iy(t)};function wy(t){return t?Object.assign(Object.assign({},lp),t):lp}class Iy{constructor(e,i){this.varint64=ky,this.uint32=by,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=i!=null?i:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),i=e>>>3,n=e&7;if(i<=0||n<0||n>5)throw new Error("illegal tag: field no "+i+" wire type "+n);return[i,n]}skip(e){let i=this.pos;switch(e){case Fe.Varint:for(;this.buf[this.pos++]&128;);break;case Fe.Bit64:this.pos+=4;case Fe.Bit32:this.pos+=4;break;case Fe.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Fe.StartGroup:let r;for(;(r=this.tag()[1])!==Fe.EndGroup;)this.skip(r);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 Se(...this.varint64())}uint64(){return new dt(...this.varint64())}sint64(){let[e,i]=this.varint64(),n=-(e&1);return e=(e>>>1|(i&1)<<31)^n,i=i>>>1^n,new Se(e,i)}bool(){let[e,i]=this.varint64();return e!==0||i!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new Se(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(),i=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(i,i+e)}string(){return this.textDecoder.decode(this.bytes())}}function de(t,e){if(!t)throw new Error(e)}const Cy=34028234663852886e22,Py=-34028234663852886e22,Ry=4294967295,My=2147483647,Ay=-2147483648;function Fs(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>My||t<Ay)throw new Error("invalid int 32: "+t)}function Zo(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Ry||t<0)throw new Error("invalid uint 32: "+t)}function yl(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>Cy||t<Py))throw new Error("invalid float 32: "+t)}const up={writeUnknownFields:!0,writerFactory:()=>new Oy};function Dy(t){return t?Object.assign(Object.assign({},up),t):up}class Oy{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 r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let i=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)i.set(this.chunks[r],n),n+=this.chunks[r].length;return this.chunks=[],i}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),i=this.stack.pop();if(!i)throw new Error("invalid state, fork stack empty");return this.chunks=i.chunks,this.buf=i.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,i){return this.uint32((e<<3|i)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Zo(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Fs(e),ap(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 i=this.textEncoder.encode(e);return this.uint32(i.byteLength),this.raw(i)}float(e){yl(e);let i=new Uint8Array(4);return new DataView(i.buffer).setFloat32(0,e,!0),this.raw(i)}double(e){let i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,e,!0),this.raw(i)}fixed32(e){Zo(e);let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,e,!0),this.raw(i)}sfixed32(e){Fs(e);let i=new Uint8Array(4);return new DataView(i.buffer).setInt32(0,e,!0),this.raw(i)}sint32(e){return Fs(e),e=(e<<1^e>>31)>>>0,ap(e,this.buf),this}sfixed64(e){let i=new Uint8Array(8),n=new DataView(i.buffer),r=Se.from(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(i)}fixed64(e){let i=new Uint8Array(8),n=new DataView(i.buffer),r=dt.from(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(i)}int64(e){let i=Se.from(e);return fl(i.lo,i.hi,this.buf),this}sint64(e){let i=Se.from(e),n=i.hi>>31,r=i.lo<<1^n,s=(i.hi<<1|i.lo>>>31)^n;return fl(r,s,this.buf),this}uint64(e){let i=dt.from(e);return fl(i.lo,i.hi,this.buf),this}}const hp={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},pp={ignoreUnknownFields:!1};function Ny(t){return t?Object.assign(Object.assign({},pp),t):pp}function Ly(t){return t?Object.assign(Object.assign({},hp),t):hp}const mp=Symbol.for("protobuf-ts/message-type");function gp(t){let e=!1;const i=[];for(let n=0;n<t.length;n++){let r=t.charAt(n);r=="_"?e=!0:/\d/.test(r)?(i.push(r),e=!0):e?(i.push(r.toUpperCase()),e=!1):n==0?i.push(r.toLowerCase()):i.push(r)}return i.join("")}var D;(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"})(D||(D={}));var wi;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(wi||(wi={}));var ec;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(ec||(ec={}));function xy(t){var e,i,n,r;return t.localName=(e=t.localName)!==null&&e!==void 0?e:gp(t.name),t.jsonName=(i=t.jsonName)!==null&&i!==void 0?i:gp(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:ec.NO,t.opt=(r=t.opt)!==null&&r!==void 0?r:t.repeat||t.oneof?!1:t.kind=="message",t}function Vy(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 Uy{constructor(e){var i;this.fields=(i=e.fields)!==null&&i!==void 0?i:[]}prepare(){if(this.data)return;const e=[],i=[],n=[];for(let r of this.fields)if(r.oneof)n.includes(r.oneof)||(n.push(r.oneof),e.push(r.oneof),i.push(r.oneof));else switch(i.push(r.localName),r.kind){case"scalar":case"enum":(!r.opt||r.repeat)&&e.push(r.localName);break;case"message":r.repeat&&e.push(r.localName);break;case"map":e.push(r.localName);break}this.data={req:e,known:i,oneofs:Object.values(n)}}is(e,i,n=!1){if(i<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let r=Object.keys(e),s=this.data;if(r.length<s.req.length||s.req.some(o=>!r.includes(o))||!n&&r.some(o=>!s.known.includes(o)))return!1;if(i<1)return!0;for(const o of s.oneofs){const c=e[o];if(!Vy(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,n,i))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,i))return!1;return!0}field(e,i,n,r){let s=i.repeat;switch(i.kind){case"scalar":return e===void 0?i.opt:s?this.scalars(e,i.T,r,i.L):this.scalar(e,i.T,i.L);case"enum":return e===void 0?i.opt:s?this.scalars(e,D.INT32,r):this.scalar(e,D.INT32);case"message":return e===void 0?!0:s?this.messages(e,i.T(),n,r):this.message(e,i.T(),n,r);case"map":if(typeof e!="object"||e===null)return!1;if(r<2)return!0;if(!this.mapKeys(e,i.K,r))return!1;switch(i.V.kind){case"scalar":return this.scalars(Object.values(e),i.V.T,r,i.V.L);case"enum":return this.scalars(Object.values(e),D.INT32,r);case"message":return this.messages(Object.values(e),i.V.T(),n,r)}break}return!0}message(e,i,n,r){return n?i.isAssignable(e,r):i.is(e,r)}messages(e,i,n,r){if(!Array.isArray(e))return!1;if(r<2)return!0;if(n){for(let s=0;s<e.length&&s<r;s++)if(!i.isAssignable(e[s],r-1))return!1}else for(let s=0;s<e.length&&s<r;s++)if(!i.is(e[s],r-1))return!1;return!0}scalar(e,i,n){let r=typeof e;switch(i){case D.UINT64:case D.FIXED64:case D.INT64:case D.SFIXED64:case D.SINT64:switch(n){case wi.BIGINT:return r=="bigint";case wi.NUMBER:return r=="number"&&!isNaN(e);default:return r=="string"}case D.BOOL:return r=="boolean";case D.STRING:return r=="string";case D.BYTES:return e instanceof Uint8Array;case D.DOUBLE:case D.FLOAT:return r=="number"&&!isNaN(e);default:return r=="number"&&Number.isInteger(e)}}scalars(e,i,n,r){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],i,r))return!1}return!0}mapKeys(e,i,n){let r=Object.keys(e);switch(i){case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.UINT32:return this.scalars(r.slice(0,n).map(s=>parseInt(s)),i,n);case D.BOOL:return this.scalars(r.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),i,n);default:return this.scalars(r,i,n,wi.STRING)}}}function ri(t,e){switch(e){case wi.BIGINT:return t.toBigInt();case wi.NUMBER:return t.toNumber();default:return t.toString()}}class Fy{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const i=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of i)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,i,n){if(!e){let r=gl(n);throw(r=="number"||r=="boolean")&&(r=n.toString()),new Error(`Cannot parse JSON ${r} for ${this.info.typeName}#${i}`)}}read(e,i,n){this.prepare();const r=[];for(const[s,o]of Object.entries(e)){const c=this.fMap[s];if(!c){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(r.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);r.push(c.oneof),l=i[c.oneof]={oneofKind:d}}else l=i;if(c.kind=="map"){if(o===null)continue;this.assert(Sy(o),c.name,o);const p=l[d];for(const[g,y]of Object.entries(o)){this.assert(y!==null,c.name+" map value",null);let T;switch(c.V.kind){case"message":T=c.V.T().internalJsonRead(y,n);break;case"enum":if(T=this.enum(c.V.T(),y,c.name,n.ignoreUnknownFields),T===!1)continue;break;case"scalar":T=this.scalar(y,c.V.T,c.V.L,c.name);break}this.assert(T!==void 0,c.name+" map value",y);let b=g;c.K==D.BOOL&&(b=b=="true"?!0:b=="false"?!1:b),b=this.scalar(b,c.K,wi.STRING,c.name).toString(),p[b]=T}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const p=l[d];for(const g of o){this.assert(g!==null,c.name,null);let y;switch(c.kind){case"message":y=c.T().internalJsonRead(g,n);break;case"enum":if(y=this.enum(c.T(),g,c.name,n.ignoreUnknownFields),y===!1)continue;break;case"scalar":y=this.scalar(g,c.T,c.L,c.name);break}this.assert(y!==void 0,c.name,o),p.push(y)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,n,l[d]);break;case"enum":if(o===null)continue;let p=this.enum(c.T(),o,c.name,n.ignoreUnknownFields);if(p===!1)continue;l[d]=p;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(e,i,n,r){if(e[0]=="google.protobuf.NullValue"&&de(i===null||i==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),i===null)return 0;switch(typeof i){case"number":return de(Number.isInteger(i),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${i}.`),i;case"string":let s=i;e[2]&&i.substring(0,e[2].length)===e[2]&&(s=i.substring(e[2].length));let o=e[1][s];return typeof o=="undefined"&&r?!1:(de(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${i}".`),o)}de(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof i}".`)}scalar(e,i,n,r){let s;try{switch(i){case D.DOUBLE:case D.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 i==D.FLOAT&&yl(o),o;case D.INT32:case D.FIXED32:case D.SFIXED32:case D.SINT32:case D.UINT32:if(e===null)return 0;let c;if(typeof e=="number"?c=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":c=Number(e)),c===void 0)break;return i==D.UINT32?Zo(c):Fs(c),c;case D.INT64:case D.SFIXED64:case D.SINT64:if(e===null)return ri(Se.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return ri(Se.from(e),n);case D.FIXED64:case D.UINT64:if(e===null)return ri(dt.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return ri(dt.from(e),n);case D.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case D.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 D.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return Ey(e)}}catch(o){s=o.message}this.assert(!1,r+(s?" - "+s:""),e)}}class By{constructor(e){var i;this.fields=(i=e.fields)!==null&&i!==void 0?i:[]}write(e,i){const n={},r=e;for(const s of this.fields){if(!s.oneof){let l=this.field(s,r[s.localName],i);l!==void 0&&(n[i.useProtoFieldName?s.name:s.jsonName]=l);continue}const o=r[s.oneof];if(o.oneofKind!==s.localName)continue;const c=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},i),{emitDefaultValues:!0}):i;let d=this.field(s,o[s.localName],c);de(d!==void 0),n[i.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,i,n){let r;if(e.kind=="map"){de(typeof i=="object"&&i!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,l]of Object.entries(i)){const p=this.scalar(e.V.T,l,e.name,!1,!0);de(p!==void 0),s[d.toString()]=p}break;case"message":const o=e.V.T();for(const[d,l]of Object.entries(i)){const p=this.message(o,l,e.name,n);de(p!==void 0),s[d.toString()]=p}break;case"enum":const c=e.V.T();for(const[d,l]of Object.entries(i)){de(l===void 0||typeof l=="number");const p=this.enum(c,l,e.name,!1,!0,n.enumAsInteger);de(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(r=s)}else if(e.repeat){de(Array.isArray(i));const s=[];switch(e.kind){case"scalar":for(let d=0;d<i.length;d++){const l=this.scalar(e.T,i[d],e.name,e.opt,!0);de(l!==void 0),s.push(l)}break;case"enum":const o=e.T();for(let d=0;d<i.length;d++){de(i[d]===void 0||typeof i[d]=="number");const l=this.enum(o,i[d],e.name,e.opt,!0,n.enumAsInteger);de(l!==void 0),s.push(l)}break;case"message":const c=e.T();for(let d=0;d<i.length;d++){const l=this.message(c,i[d],e.name,n);de(l!==void 0),s.push(l)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(r=s)}else switch(e.kind){case"scalar":r=this.scalar(e.T,i,e.name,e.opt,n.emitDefaultValues);break;case"enum":r=this.enum(e.T(),i,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":r=this.message(e.T(),i,e.name,n);break}return r}enum(e,i,n,r,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!r?void 0:null;if(i===void 0){de(r);return}if(!(i===0&&!s&&!r))return de(typeof i=="number"),de(Number.isInteger(i)),o||!e[1].hasOwnProperty(i)?i:e[2]?e[2]+e[1][i]:e[1][i]}message(e,i,n,r){return i===void 0?r.emitDefaultValues?null:void 0:e.internalJsonWrite(i,r)}scalar(e,i,n,r,s){if(i===void 0){de(r);return}const o=s||r;switch(e){case D.INT32:case D.SFIXED32:case D.SINT32:return i===0?o?0:void 0:(Fs(i),i);case D.FIXED32:case D.UINT32:return i===0?o?0:void 0:(Zo(i),i);case D.FLOAT:yl(i);case D.DOUBLE:return i===0?o?0:void 0:(de(typeof i=="number"),Number.isNaN(i)?"NaN":i===Number.POSITIVE_INFINITY?"Infinity":i===Number.NEGATIVE_INFINITY?"-Infinity":i);case D.STRING:return i===""?o?"":void 0:(de(typeof i=="string"),i);case D.BOOL:return i===!1?o?!1:void 0:(de(typeof i=="boolean"),i);case D.UINT64:case D.FIXED64:de(typeof i=="number"||typeof i=="string"||typeof i=="bigint");let c=dt.from(i);return c.isZero()&&!o?void 0:c.toString();case D.INT64:case D.SFIXED64:case D.SINT64:de(typeof i=="number"||typeof i=="string"||typeof i=="bigint");let d=Se.from(i);return d.isZero()&&!o?void 0:d.toString();case D.BYTES:return de(i instanceof Uint8Array),i.byteLength?Ty(i):o?"":void 0}}}function Sl(t,e=wi.STRING){switch(t){case D.BOOL:return!1;case D.UINT64:case D.FIXED64:return ri(dt.ZERO,e);case D.INT64:case D.SFIXED64:case D.SINT64:return ri(Se.ZERO,e);case D.DOUBLE:case D.FLOAT:return 0;case D.BYTES:return new Uint8Array(0);case D.STRING:return"";default:return 0}}class Wy{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const i=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(i.map(n=>[n.no,n]))}}read(e,i,n,r){this.prepare();const s=r===void 0?e.len:e.pos+r;for(;e.pos<s;){const[o,c]=e.tag(),d=this.fieldNoToField.get(o);if(!d){let y=n.readUnknownField;if(y=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let T=e.skip(c);y!==!1&&(y===!0?zo.onRead:y)(this.info.typeName,i,o,c,T);continue}let l=i,p=d.repeat,g=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==g&&(l=i[d.oneof]={oneofKind:g})),d.kind){case"scalar":case"enum":let y=d.kind=="enum"?D.INT32:d.T,T=d.kind=="scalar"?d.L:void 0;if(p){let M=l[g];if(c==Fe.LengthDelimited&&y!=D.STRING&&y!=D.BYTES){let F=e.uint32()+e.pos;for(;e.pos<F;)M.push(this.scalar(e,y,T))}else M.push(this.scalar(e,y,T))}else l[g]=this.scalar(e,y,T);break;case"message":if(p){let M=l[g],F=d.T().internalBinaryRead(e,e.uint32(),n);M.push(F)}else l[g]=d.T().internalBinaryRead(e,e.uint32(),n,l[g]);break;case"map":let[b,N]=this.mapEntry(d,e,n);l[g][b]=N;break}}}mapEntry(e,i,n){let r=i.uint32(),s=i.pos+r,o,c;for(;i.pos<s;){let[d,l]=i.tag();switch(d){case 1:e.K==D.BOOL?o=i.bool().toString():o=this.scalar(i,e.K,wi.STRING);break;case 2:switch(e.V.kind){case"scalar":c=this.scalar(i,e.V.T,e.V.L);break;case"enum":c=i.int32();break;case"message":c=e.V.T().internalBinaryRead(i,i.uint32(),n);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let d=Sl(e.K);o=e.K==D.BOOL?d.toString():d}if(c===void 0)switch(e.V.kind){case"scalar":c=Sl(e.V.T,e.V.L);break;case"enum":c=0;break;case"message":c=e.V.T().create();break}return[o,c]}scalar(e,i,n){switch(i){case D.INT32:return e.int32();case D.STRING:return e.string();case D.BOOL:return e.bool();case D.DOUBLE:return e.double();case D.FLOAT:return e.float();case D.INT64:return ri(e.int64(),n);case D.UINT64:return ri(e.uint64(),n);case D.FIXED64:return ri(e.fixed64(),n);case D.FIXED32:return e.fixed32();case D.BYTES:return e.bytes();case D.UINT32:return e.uint32();case D.SFIXED32:return e.sfixed32();case D.SFIXED64:return ri(e.sfixed64(),n);case D.SINT32:return e.sint32();case D.SINT64:return ri(e.sint64(),n)}}}class jy{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((i,n)=>i.no-n.no)}}write(e,i,n){this.prepare();for(const s of this.fields){let o,c,d=s.repeat,l=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==l)continue;o=p[l],c=!0}else o=e[l],c=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?D.INT32:s.T;if(d)if(de(Array.isArray(o)),d==ec.PACKED)this.packed(i,p,s.no,o);else for(const g of o)this.scalar(i,p,s.no,g,!0);else o===void 0?de(s.opt):this.scalar(i,p,s.no,o,c||s.opt);break;case"message":if(d){de(Array.isArray(o));for(const g of o)this.message(i,n,s.T(),s.no,g)}else this.message(i,n,s.T(),s.no,o);break;case"map":de(typeof o=="object"&&o!==null);for(const[g,y]of Object.entries(o))this.mapEntry(i,n,s,g,y);break}}let r=n.writeUnknownFields;r!==!1&&(r===!0?zo.onWrite:r)(this.info.typeName,e,i)}mapEntry(e,i,n,r,s){e.tag(n.no,Fe.LengthDelimited),e.fork();let o=r;switch(n.K){case D.INT32:case D.FIXED32:case D.UINT32:case D.SFIXED32:case D.SINT32:o=Number.parseInt(r);break;case D.BOOL:de(r=="true"||r=="false"),o=r=="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,D.INT32,2,s,!0);break;case"message":this.message(e,i,n.V.T(),2,s);break}e.join()}message(e,i,n,r,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(r,Fe.LengthDelimited).fork(),i),e.join())}scalar(e,i,n,r,s){let[o,c,d]=this.scalarInfo(i,r);(!d||s)&&(e.tag(n,o),e[c](r))}packed(e,i,n,r){if(!r.length)return;de(i!==D.BYTES&&i!==D.STRING),e.tag(n,Fe.LengthDelimited),e.fork();let[,s]=this.scalarInfo(i);for(let o=0;o<r.length;o++)e[s](r[o]);e.join()}scalarInfo(e,i){let n=Fe.Varint,r,s=i===void 0,o=i===0;switch(e){case D.INT32:r="int32";break;case D.STRING:o=s||!i.length,n=Fe.LengthDelimited,r="string";break;case D.BOOL:o=i===!1,r="bool";break;case D.UINT32:r="uint32";break;case D.DOUBLE:n=Fe.Bit64,r="double";break;case D.FLOAT:n=Fe.Bit32,r="float";break;case D.INT64:o=s||Se.from(i).isZero(),r="int64";break;case D.UINT64:o=s||dt.from(i).isZero(),r="uint64";break;case D.FIXED64:o=s||dt.from(i).isZero(),n=Fe.Bit64,r="fixed64";break;case D.BYTES:o=s||!i.byteLength,n=Fe.LengthDelimited,r="bytes";break;case D.FIXED32:n=Fe.Bit32,r="fixed32";break;case D.SFIXED32:n=Fe.Bit32,r="sfixed32";break;case D.SFIXED64:o=s||Se.from(i).isZero(),n=Fe.Bit64,r="sfixed64";break;case D.SINT32:r="sint32";break;case D.SINT64:o=s||Se.from(i).isZero(),r="sint64";break}return[n,r,s||o]}}function Hy(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},mp,{value:t});for(let i of t.fields){let n=i.localName;if(!i.opt)if(i.oneof)e[i.oneof]={oneofKind:void 0};else if(i.repeat)e[n]=[];else switch(i.kind){case"scalar":e[n]=Sl(i.T,i.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function El(t,e,i){let n,r=i,s;for(let o of t.fields){let c=o.localName;if(o.oneof){const d=r[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[c],s=e[o.oneof],s.oneofKind=d.oneofKind,n==null){delete s[c];continue}}else if(n=r[c],s=e,n==null)continue;switch(o.repeat&&(s[c].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<n.length;l++)s[c][l]=n[l];else s[c]=n;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<n.length;l++)s[c][l]=d.create(n[l]);else s[c]===void 0?s[c]=d.create(n):d.mergePartial(s[c],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[c],n);break;case"message":let l=o.V.T();for(let p of Object.keys(n))s[c][p]=l.create(n[p]);break}break}}}function Gy(t,e,i){if(e===i)return!0;if(!e||!i)return!1;for(let n of t.fields){let r=n.localName,s=n.oneof?e[n.oneof][r]:e[r],o=n.oneof?i[n.oneof][r]:i[r];switch(n.kind){case"enum":case"scalar":let c=n.kind=="enum"?D.INT32:n.T;if(!(n.repeat?vp(c,s,o):fp(c,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?yp(n.V.T(),tc(s),tc(o)):vp(n.V.kind=="enum"?D.INT32:n.V.T,tc(s),tc(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?yp(d,s,o):d.equals(s,o)))return!1;break}}return!0}const tc=Object.values;function fp(t,e,i){if(e===i)return!0;if(t!==D.BYTES)return!1;let n=e,r=i;if(n.length!==r.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=r[s])return!1;return!0}function vp(t,e,i){if(e.length!==i.length)return!1;for(let n=0;n<e.length;n++)if(!fp(t,e[n],i[n]))return!1;return!0}function yp(t,e,i){if(e.length!==i.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],i[n]))return!1;return!0}const qy=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class E{constructor(e,i,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=i.map(xy),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},qy),{[mp]:{value:this}})),this.refTypeCheck=new Uy(this),this.refJsonReader=new Fy(this),this.refJsonWriter=new By(this),this.refBinReader=new Wy(this),this.refBinWriter=new jy(this)}create(e){let i=Hy(this);return e!==void 0&&El(this,i,e),i}clone(e){let i=this.create();return El(this,i,e),i}equals(e,i){return Gy(this,e,i)}is(e,i=this.defaultCheckDepth){return this.refTypeCheck.is(e,i,!1)}isAssignable(e,i=this.defaultCheckDepth){return this.refTypeCheck.is(e,i,!0)}mergePartial(e,i){El(this,e,i)}fromBinary(e,i){let n=wy(i);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,i){return this.internalJsonRead(e,Ny(i))}fromJsonString(e,i){let n=JSON.parse(e);return this.fromJson(n,i)}toJson(e,i){return this.internalJsonWrite(e,Ly(i))}toJsonString(e,i){var n;let r=this.toJson(e,i);return JSON.stringify(r,null,(n=i==null?void 0:i.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,i){let n=Dy(i);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,i,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let r=n!=null?n:this.create();return this.refJsonReader.read(e,r,i),r}throw new Error(`Unable to parse message ${this.typeName} from JSON ${gl(e)}.`)}internalJsonWrite(e,i){return this.refJsonWriter.write(e,i)}internalBinaryWrite(e,i,n){return this.refBinWriter.write(e,i,n),i}internalBinaryRead(e,i,n,r){let s=r!=null?r:this.create();return this.refBinReader.read(e,s,n,i),s}}const Jy=t=>(e,i)=>(t.set(e,i),i),Sp=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ep=536870912,Tp=Ep*2,$y=(t,e)=>i=>{const n=e.get(i);let r=n===void 0?i.size:n<Tp?n+1:0;if(!i.has(r))return t(i,r);if(i.size<Ep){for(;i.has(r);)r=Math.floor(Math.random()*Tp);return t(i,r)}if(i.size>Sp)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;i.has(r);)r=Math.floor(Math.random()*Sp);return t(i,r)},kp=new WeakMap,Ky=Jy(kp),ic=$y(Ky,kp),zy=t=>t.method!==void 0&&t.method==="call",Yy=t=>t.error===null&&typeof t.id=="number",nc=((t,e)=>{let i=null;return()=>{if(i!==null)return i;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=URL.createObjectURL(n);return i=t(r),setTimeout(()=>URL.revokeObjectURL(r)),i}})(t=>{const e=new Map([[0,()=>{}]]),i=new Map([[0,()=>{}]]),n=new Map,r=new Worker(t);return r.addEventListener("message",({data:l})=>{if(zy(l)){const{params:{timerId:p,timerType:g}}=l;if(g==="interval"){const y=e.get(p);if(typeof y=="number"){const T=n.get(y);if(T===void 0||T.timerId!==p||T.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof y!="undefined")y();else throw new Error("The timer is in an undefined state.")}else if(g==="timeout"){const y=i.get(p);if(typeof y=="number"){const T=n.get(y);if(T===void 0||T.timerId!==p||T.timerType!==g)throw new Error("The timer is in an undefined state.")}else if(typeof y!="undefined")y(),i.delete(p);else throw new Error("The timer is in an undefined state.")}}else if(Yy(l)){const{id:p}=l,g=n.get(p);if(g===void 0)throw new Error("The timer is in an undefined state.");const{timerId:y,timerType:T}=g;n.delete(p),T==="interval"?e.delete(y):i.delete(y)}else{const{error:{message:p}}=l;throw new Error(p)}}),{clearInterval:l=>{const p=ic(n);n.set(p,{timerId:l,timerType:"interval"}),e.set(l,p),r.postMessage({id:p,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const p=ic(n);n.set(p,{timerId:l,timerType:"timeout"}),i.set(l,p),r.postMessage({id:p,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,p=0)=>{const g=ic(e);return e.set(g,()=>{l(),typeof e.get(g)=="function"&&r.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:g,timerType:"interval"}})}),r.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:g,timerType:"interval"}}),g},setTimeout:(l,p=0)=>{const g=ic(i);return i.set(g,l),r.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:g,timerType:"timeout"}}),g}}},`(()=>{"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})}}))})();`),Wr=t=>nc().clearInterval(t),Qy=t=>nc().clearTimeout(t),rc=(t,e)=>nc().setInterval(t,e);var Xy=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Wr,clearTimeout:Qy,setInterval:rc,setTimeout:(t,e)=>nc().setTimeout(t,e)},Symbol.toStringTag,{value:"Module"})),bp={},Tl={exports:{}},_p=Tl.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(_p).forEach(function(t){var e=_p[t];e.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),function(t){var e=function(c){return String(Number(c))===c?Number(c):c},i=function(c,d,l,p){if(p&&!l)d[p]=e(c[1]);else for(var g=0;g<l.length;g+=1)c[g+1]!=null&&(d[l[g]]=e(c[g+1]))},n=function(c,d,l){var p=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:p&&!d[c.name]&&(d[c.name]={});var g=c.push?{}:p?d[c.name]:d;i(l.match(c.reg),g,c.names,c.name),c.push&&d[c.push].push(g)},r=Tl.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(c){var d={},l=[],p=d;return c.split(/(\r\n|\r|\n)/).filter(s).forEach(function(g){var y=g[0],T=g.slice(2);y==="m"&&(l.push({rtp:[],fmtp:[]}),p=l[l.length-1]);for(var b=0;b<(r[y]||[]).length;b+=1){var N=r[y][b];if(N.reg.test(T))return n(N,p,T)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=e(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};t.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(c){return c.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(e),p=0;p<l.length;p+=3)d.push({component:l[p],ip:l[p+1],port:l[p+2]});return d},t.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var p,g=!1;return l[0]!=="~"?p=e(l):(p=e(l.substring(1,l.length)),g=!0),{scid:p,paused:g}})})}}(bp);var kl=Tl.exports,Zy=/%[sdv%]/g,eS=function(t){var e=1,i=arguments,n=i.length;return t.replace(Zy,function(r){if(e>=n)return r;var s=i[e];switch(e+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Bs=function(t,e,i){var n=e.format instanceof Function?e.format(e.push?i:i[e.name]):e.format,r=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?r.push(i[e.name][o]):r.push(i[e.names[s]])}else r.push(i[e.name]);return eS.apply(null,r)},tS=["v","o","s","i","u","e","p","c","b","t","r","z","a"],iS=["i","c","b","a"],nS=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 i=e.outerOrder||tS,n=e.innerOrder||iS,r=[];return i.forEach(function(s){kl[s].forEach(function(o){o.name in t&&t[o.name]!=null?r.push(Bs(s,o,t)):o.push in t&&t[o.push]!=null&&t[o.push].forEach(function(c){r.push(Bs(s,o,c))})})}),t.media.forEach(function(s){r.push(Bs("m",kl.m[0],s)),n.forEach(function(o){kl[o].forEach(function(c){c.name in s&&s[c.name]!=null?r.push(Bs(o,c,s)):c.push in s&&s[c.push]!=null&&s[c.push].forEach(function(d){r.push(Bs(o,c,d))})})})}),r.join(`\r
8
8
  `)+`\r
9
- `},Ps=Fm,vS=gS,pu=vS,Na=Ps.parse;Ps.parseParams,Ps.parseFmtpConfig,Ps.parsePayloads,Ps.parseRemoteCandidates,Ps.parseImageAttributes,Ps.parseSimulcastStreamList;var yS=Object.defineProperty,ES=Object.defineProperties,SS=Object.getOwnPropertyDescriptors,Bc=Object.getOwnPropertySymbols,TS=Object.getPrototypeOf,Wm=Object.prototype.hasOwnProperty,Hm=Object.prototype.propertyIsEnumerable,bS=Reflect.get,Ae=Math.pow,mu=(t,e,n)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,H=(t,e)=>{for(var n in e||(e={}))Wm.call(e,n)&&mu(t,n,e[n]);if(Bc)for(var n of Bc(e))Hm.call(e,n)&&mu(t,n,e[n]);return t},ee=(t,e)=>ES(t,SS(e)),Fc=(t,e)=>{var n={};for(var i in t)Wm.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&Bc)for(var i of Bc(t))e.indexOf(i)<0&&Hm.call(t,i)&&(n[i]=t[i]);return n},y=(t,e,n)=>(mu(t,typeof e!="symbol"?e+"":e,n),n),fu=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},o=(t,e,n)=>(fu(t,e,"read from private field"),n?n.call(t):e.get(t)),S=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},T=(t,e,n,i)=>(fu(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),Q=(t,e,n)=>(fu(t,e,"access private method"),n),kS=(t,e,n)=>bS(TS(t),n,e),p=(t,e,n)=>new Promise((i,s)=>{var r=d=>{try{c(n.next(d))}catch(h){s(h)}},a=d=>{try{c(n.throw(d))}catch(h){s(h)}},c=d=>d.done?i(d.value):Promise.resolve(d.value).then(r,a);c((n=n.apply(t,e)).next())});function wS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Mt={},_S={get exports(){return Mt},set exports(t){Mt=t}},Or=typeof Reflect=="object"?Reflect:null,qm=Or&&typeof Or.apply=="function"?Or.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},jc;Or&&typeof Or.ownKeys=="function"?jc=Or.ownKeys:Object.getOwnPropertySymbols?jc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:jc=function(t){return Object.getOwnPropertyNames(t)};function IS(t){console&&console.warn&&console.warn(t)}var Gm=Number.isNaN||function(t){return t!==t};function we(){we.init.call(this)}_S.exports=we,Mt.once=AS,we.EventEmitter=we,we.prototype._events=void 0,we.prototype._eventsCount=0,we.prototype._maxListeners=void 0;var Jm=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(we,"defaultMaxListeners",{enumerable:!0,get:function(){return Jm},set:function(t){if(typeof t!="number"||t<0||Gm(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Jm=t}}),we.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},we.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Gm(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 $m(t){return t._maxListeners===void 0?we.defaultMaxListeners:t._maxListeners}we.prototype.getMaxListeners=function(){return $m(this)},we.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")qm(c,this,e);else for(var d=c.length,h=Xm(c,d),n=0;n<d;++n)qm(h[n],this,e);return!0};function Km(t,e,n,i){var s,r,a;if(Wc(n),r=t._events,r===void 0?(r=t._events=Object.create(null),t._eventsCount=0):(r.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),r=t._events),a=r[e]),a===void 0)a=r[e]=n,++t._eventsCount;else if(typeof a=="function"?a=r[e]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),s=$m(t),s>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,IS(c)}return t}we.prototype.addListener=function(t,e){return Km(this,t,e,!1)},we.prototype.on=we.prototype.addListener,we.prototype.prependListener=function(t,e){return Km(this,t,e,!0)};function CS(){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 zm(t,e,n){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},s=CS.bind(i);return s.listener=n,i.wrapFn=s,s}we.prototype.once=function(t,e){return Wc(e),this.on(t,zm(this,t,e)),this},we.prototype.prependOnceListener=function(t,e){return Wc(e),this.prependListener(t,zm(this,t,e)),this},we.prototype.removeListener=function(t,e){var n,i,s,r,a;if(Wc(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(s=-1,r=n.length-1;r>=0;r--)if(n[r]===e||n[r].listener===e){a=n[r].listener,s=r;break}if(s<0)return this;s===0?n.shift():RS(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},we.prototype.off=we.prototype.removeListener,we.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),r;for(i=0;i<s.length;++i)r=s[i],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Ym(t,e,n){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?PS(s):Xm(s,s.length)}we.prototype.listeners=function(t){return Ym(this,t,!0)},we.prototype.rawListeners=function(t){return Ym(this,t,!1)},we.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Qm.call(t,e)},we.prototype.listenerCount=Qm;function Qm(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}we.prototype.eventNames=function(){return this._eventsCount>0?jc(this._events):[]};function Xm(t,e){for(var n=new Array(e),i=0;i<e;++i)n[i]=t[i];return n}function RS(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function PS(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function AS(t,e){return new Promise(function(n,i){function s(a){t.removeListener(e,r),i(a)}function r(){typeof t.removeListener=="function"&&t.removeListener("error",s),n([].slice.call(arguments))}Zm(t,e,r,{once:!0}),e!=="error"&&MS(t,s,{once:!0})})}function MS(t,e,n){typeof t.on=="function"&&Zm(t,"error",e,n)}function Zm(t,e,n,i){if(typeof t.on=="function")i.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(r){i.once&&t.removeEventListener(e,s),n(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var oe;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(oe||(oe={}));var G;(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"})(G||(G={}));const OS=new Map([[G.PRECALL_TEST_BEGIN,oe.MINOR_EVENT],[G.PRECALL_TEST_COMPLETE,oe.MINOR_EVENT],[G.CALL_JOIN_BEGIN,oe.MAJOR_EVENT],[G.NET_QUALITY_TEST_BEGIN,oe.MINOR_EVENT],[G.NET_QUALITY_TEST_END,oe.MINOR_EVENT],[G.WEBSOCKET_CONNECTED,oe.MINOR_EVENT],[G.TRANSPORT_CONNECTED,oe.MAJOR_EVENT],[G.AUDIO_ON,oe.MINOR_EVENT],[G.AUDIO_OFF,oe.MINOR_EVENT],[G.VIDEO_ON,oe.MINOR_EVENT],[G.VIDEO_OFF,oe.MINOR_EVENT],[G.PARTICIPANT_ROLE,oe.MINOR_EVENT],[G.PING_STAT,oe.MAJOR_EVENT],[G.DISCONNECT,oe.MAJOR_EVENT],[G.RECONNECT_ATTEMPT,oe.MAJOR_EVENT],[G.SCREENSHARE_START_REQUESTED,oe.MINOR_EVENT],[G.SCREENSHARE_STARTED,oe.MINOR_EVENT],[G.SCREENSHARE_STOPPED,oe.MINOR_EVENT],[G.TAB_CHANGE,oe.MINOR_EVENT],[G.BROWSER_BACKGROUNDED,oe.MINOR_EVENT],[G.BROWSER_FOREGROUNDED,oe.MINOR_EVENT],[G.DOMINANT_SPEAKER,oe.MINOR_EVENT],[G.AUDIO_DEVICES_UPDATES,oe.MINOR_EVENT],[G.VIDEO_DEVICES_UPDATES,oe.MINOR_EVENT],[G.SPEAKER_DEVICES_UPDATES,oe.MINOR_EVENT],[G.SELECTED_MICROHPONE_UPDATE,oe.MINOR_EVENT],[G.SELECTED_CAMERA_UPDATE,oe.MINOR_EVENT],[G.SELECTED_SPEAKER_UPDATE,oe.MINOR_EVENT],[G.MEDIA_PERMISSION,oe.MINOR_EVENT],[G.LEGACY_SWITCH,oe.MINOR_EVENT],[G.AUDIO_PLAY_FAILED,oe.MINOR_EVENT],[G.VIDEO_PLAY_FAILED,oe.MINOR_EVENT],[G.AUDIO_TRACK_MUTED,oe.MINOR_EVENT],[G.VIDEO_TRACK_MUTED,oe.MINOR_EVENT],[G.IVS_PLAYER_REBUFFERING,oe.MAJOR_EVENT],[G.IVS_PLAYER_AUDIO_BLOCKED,oe.MAJOR_EVENT],[G.IVS_PLAYER_PLAYBACK_BLOCKED,oe.MAJOR_EVENT],[G.IVS_PLAYER_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_RECOVERABLE_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_WORKER_ERROR,oe.MAJOR_EVENT],[G.IVS_PLAYER_NETWORK_UNAVAILABLE,oe.MAJOR_EVENT],[G.LIVESTREAM_LATENCY,oe.MAJOR_EVENT],[G.IVS_PLAYER_ANALYTICS_EVENT,oe.MINOR_EVENT],[G.IVS_PLAYER_PLAYBACK_RATE_CHANGED,oe.MINOR_EVENT],[G.IVS_PLAYER_QUALITY_CHANGED,oe.MINOR_EVENT],[G.IVS_PLAYER_INITIALIZED,oe.MINOR_EVENT],[G.EXPECTED_VIDEO_RESOLUTION,oe.MINOR_EVENT],[G.EXPECTED_SCREENSHARE_RESOLUTION,oe.MINOR_EVENT]]);class DS{constructor(){y(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class NS extends Mt{constructor({logger:e,peerId:n,apiHostnames:i}){super(),y(this,"logger"),y(this,"peerId"),y(this,"eventStore"),y(this,"apiEndpoint"),this.logger=e,this.peerId=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new DS}sendEventsChunkToServer(e){return p(this,null,function*(){var n;const i={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(i)}),!0}catch(s){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:s}),(n=e.entries)==null||n.forEach(r=>{this.eventStore.add(r)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),OS.get(e.event)===oe.MAJOR_EVENT&&this.flush()}flush(){return p(this,null,function*(){var e;const n=this.eventStore.flush();return(e=n==null?void 0:n.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(n),!0):!1})}}var ef;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(ef||(ef={}));const La={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var En;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(En||(En={}));var tf;(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"})(tf||(tf={}));function Li(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Hc({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function qc({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const nf=240,sf=720,rf=8,af=3,Gc=10,Jc=.02,$c=.03;function pi({stat:t,weight:e,rangeMin:n,rangeMax:i,rangeRankingDirection:s}){return t==null?e:n===i?s==="UP"?t<=n?e:0:t>=i?e:0:s==="UP"?(1-Math.max(Math.min(i,Math.abs(t))-n,0)/(i-n))*e:s==="DOWN"?Math.max(Math.min(i,Math.abs(t))-n,0)/(i-n)*e:e}function of({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:n,jitterQuality:i,packetsLostQuality:s}){const r=.8*((t?.85:1)*(n?.7:1)*(e?.5:1))+.2*(i*s);return Math.round((r+Number.EPSILON)*100)/100}function cf({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function df({packetsLost:t,packetsSent:e,jitter:n}){const i=pi({stat:cf({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Gc,rangeRankingDirection:"UP"}),s=pi({stat:n,weight:.3,rangeMin:Jc,rangeMax:$c,rangeRankingDirection:"UP"});return i+s}function LS({frameWidth:t,isScreenShare:e}){return t<(e?sf:nf)}function xS({framesPerSecond:t,isScreenShare:e}){return t<(e?af:rf)}function VS({framesEncoded:t}){return t===0}function lf({frameWidth:t,framesPerSecond:e,packetsLost:n,packetsSent:i,jitter:s,isScreenShare:r,framesEncoded:a}){const c=pi({stat:cf({packetsLost:n,packetsSent:i}),weight:1,rangeMin:0,rangeMax:Gc,rangeRankingDirection:"UP"}),d=pi({stat:s,weight:1,rangeMin:Jc,rangeMax:$c,rangeRankingDirection:"UP"}),h=LS({frameWidth:t,isScreenShare:r}),u=xS({framesPerSecond:e,isScreenShare:r}),g=VS({framesEncoded:a,isScreenShare:r});return of({isLowQualityVideo:h,isVideoLagging:u,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}function uf({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function hf({concealmentEvents:t,packetsLost:e,packetsReceived:n,jitter:i}){const s=pi({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),r=.5,a=pi({stat:uf({packetsLost:e,packetsReceived:n}),weight:r,rangeMin:0,rangeMax:Gc,rangeRankingDirection:"UP"}),c=pi({stat:i,weight:.3,rangeMin:Jc,rangeMax:$c,rangeRankingDirection:"UP"});return s+a+c}function US({framesDecoded:t}){return t===0}function BS({framesPerSecond:t,isScreenShare:e}){return t<(e?af:rf)}function FS({frameWidth:t,isScreenShare:e}){return t<(e?sf:nf)}function pf({frameWidth:t,framesPerSecond:e,packetsLost:n,packetsReceived:i,jitter:s,isScreenShare:r,framesDecoded:a}){const c=pi({stat:uf({packetsLost:n,packetsReceived:i}),weight:1,rangeMin:0,rangeMax:Gc,rangeRankingDirection:"UP"}),d=pi({stat:s,weight:1,rangeMin:Jc,rangeMax:$c,rangeRankingDirection:"UP"}),h=FS({frameWidth:t,isScreenShare:r}),u=BS({framesPerSecond:e,isScreenShare:r}),g=US({framesDecoded:a,isScreenShare:r});return of({isLowQualityVideo:h,isVideoLagging:u,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}class mi{constructor(e){y(this,"pc1"),y(this,"pc2"),y(this,"constrainVideoBitrateKbps"),y(this,"constrainOfferToRemoveVideoFec",!1),y(this,"iceCandidateFilter");const n=new RTCPeerConnection(e),i=new RTCPeerConnection(e);this.pc1=n,this.pc2=i,this.iceCandidateFilter=mi.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 n="candidate:",i=e.indexOf(n)+n.length,s=e.substr(i).split(" ");return{type:s[7],protocol:s[2],address:s[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,n){if(n.candidate){const i=mi.parseCandidate(n.candidate.candidate);this.iceCandidateFilter(i)&&e.addIceCandidate(n.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
9
+ `},qn=bp,rS=nS,bl=rS,Ws=qn.parse;qn.parseParams,qn.parseFmtpConfig,qn.parsePayloads,qn.parseRemoteCandidates,qn.parseImageAttributes,qn.parseSimulcastStreamList;var sS=Object.defineProperty,aS=Object.defineProperties,oS=Object.getOwnPropertyDescriptors,sc=Object.getOwnPropertySymbols,cS=Object.getPrototypeOf,wp=Object.prototype.hasOwnProperty,Ip=Object.prototype.propertyIsEnumerable,dS=Reflect.get,lS=Math.pow,_l=(t,e,i)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,x=(t,e)=>{for(var i in e||(e={}))wp.call(e,i)&&_l(t,i,e[i]);if(sc)for(var i of sc(e))Ip.call(e,i)&&_l(t,i,e[i]);return t},q=(t,e)=>aS(t,oS(e)),ac=(t,e)=>{var i={};for(var n in t)wp.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&sc)for(var n of sc(t))e.indexOf(n)<0&&Ip.call(t,n)&&(i[n]=t[n]);return i},m=(t,e,i)=>(_l(t,typeof e!="symbol"?e+"":e,i),i),wl=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},a=(t,e,i)=>(wl(t,e,"read from private field"),i?i.call(t):e.get(t)),f=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},v=(t,e,i,n)=>(wl(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),j=(t,e,i)=>(wl(t,e,"access private method"),i),uS=(t,e,i)=>dS(cS(t),i,e),u=(t,e,i)=>new Promise((n,r)=>{var s=d=>{try{c(i.next(d))}catch(l){r(l)}},o=d=>{try{c(i.throw(d))}catch(l){r(l)}},c=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,o);c((i=i.apply(t,e)).next())}),lt={},hS={get exports(){return lt},set exports(t){lt=t}},jr=typeof Reflect=="object"?Reflect:null,Cp=jr&&typeof jr.apply=="function"?jr.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},oc;jr&&typeof jr.ownKeys=="function"?oc=jr.ownKeys:Object.getOwnPropertySymbols?oc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:oc=function(t){return Object.getOwnPropertyNames(t)};function pS(t){console&&console.warn&&console.warn(t)}var Pp=Number.isNaN||function(t){return t!==t};function me(){me.init.call(this)}hS.exports=me,lt.once=vS,me.EventEmitter=me,me.prototype._events=void 0,me.prototype._eventsCount=0,me.prototype._maxListeners=void 0;var Rp=10;function cc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(me,"defaultMaxListeners",{enumerable:!0,get:function(){return Rp},set:function(t){if(typeof t!="number"||t<0||Pp(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Rp=t}}),me.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},me.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Pp(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 Mp(t){return t._maxListeners===void 0?me.defaultMaxListeners:t._maxListeners}me.prototype.getMaxListeners=function(){return Mp(this)},me.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.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 c=r[t];if(c===void 0)return!1;if(typeof c=="function")Cp(c,this,e);else for(var d=c.length,l=Lp(c,d),i=0;i<d;++i)Cp(l[i],this,e);return!0};function Ap(t,e,i,n){var r,s,o;if(cc(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=Mp(t),r>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,pS(c)}return t}me.prototype.addListener=function(t,e){return Ap(this,t,e,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(t,e){return Ap(this,t,e,!0)};function mS(){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 Dp(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=mS.bind(n);return r.listener=i,n.wrapFn=r,r}me.prototype.once=function(t,e){return cc(e),this.on(t,Dp(this,t,e)),this},me.prototype.prependOnceListener=function(t,e){return cc(e),this.prependListener(t,Dp(this,t,e)),this},me.prototype.removeListener=function(t,e){var i,n,r,s,o;if(cc(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():gS(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},me.prototype.off=me.prototype.removeListener,me.prototype.removeAllListeners=function(t){var e,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[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 Op(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?fS(r):Lp(r,r.length)}me.prototype.listeners=function(t){return Op(this,t,!0)},me.prototype.rawListeners=function(t){return Op(this,t,!1)},me.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Np.call(t,e)},me.prototype.listenerCount=Np;function Np(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}me.prototype.eventNames=function(){return this._eventsCount>0?oc(this._events):[]};function Lp(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function gS(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function fS(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function vS(t,e){return new Promise(function(i,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}xp(t,e,s,{once:!0}),e!=="error"&&yS(t,r,{once:!0})})}function yS(t,e,i){typeof t.on=="function"&&xp(t,"error",e,i)}function xp(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var Z;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(Z||(Z={}));var V;(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"})(V||(V={}));const SS=new Map([[V.PRECALL_TEST_BEGIN,Z.MINOR_EVENT],[V.PRECALL_TEST_COMPLETE,Z.MINOR_EVENT],[V.CALL_JOIN_BEGIN,Z.MAJOR_EVENT],[V.NET_QUALITY_TEST_BEGIN,Z.MINOR_EVENT],[V.NET_QUALITY_TEST_END,Z.MINOR_EVENT],[V.WEBSOCKET_CONNECTED,Z.MINOR_EVENT],[V.TRANSPORT_CONNECTED,Z.MAJOR_EVENT],[V.AUDIO_ON,Z.MINOR_EVENT],[V.AUDIO_OFF,Z.MINOR_EVENT],[V.VIDEO_ON,Z.MINOR_EVENT],[V.VIDEO_OFF,Z.MINOR_EVENT],[V.PARTICIPANT_ROLE,Z.MINOR_EVENT],[V.PING_STAT,Z.MAJOR_EVENT],[V.DISCONNECT,Z.MAJOR_EVENT],[V.RECONNECT_ATTEMPT,Z.MAJOR_EVENT],[V.SCREENSHARE_START_REQUESTED,Z.MINOR_EVENT],[V.SCREENSHARE_STARTED,Z.MINOR_EVENT],[V.SCREENSHARE_STOPPED,Z.MINOR_EVENT],[V.TAB_CHANGE,Z.MINOR_EVENT],[V.BROWSER_BACKGROUNDED,Z.MINOR_EVENT],[V.BROWSER_FOREGROUNDED,Z.MINOR_EVENT],[V.DOMINANT_SPEAKER,Z.MINOR_EVENT],[V.AUDIO_DEVICES_UPDATES,Z.MINOR_EVENT],[V.VIDEO_DEVICES_UPDATES,Z.MINOR_EVENT],[V.SPEAKER_DEVICES_UPDATES,Z.MINOR_EVENT],[V.SELECTED_MICROHPONE_UPDATE,Z.MINOR_EVENT],[V.SELECTED_CAMERA_UPDATE,Z.MINOR_EVENT],[V.SELECTED_SPEAKER_UPDATE,Z.MINOR_EVENT],[V.MEDIA_PERMISSION,Z.MINOR_EVENT],[V.LEGACY_SWITCH,Z.MINOR_EVENT],[V.AUDIO_PLAY_FAILED,Z.MINOR_EVENT],[V.VIDEO_PLAY_FAILED,Z.MINOR_EVENT],[V.AUDIO_TRACK_MUTED,Z.MINOR_EVENT],[V.VIDEO_TRACK_MUTED,Z.MINOR_EVENT],[V.IVS_PLAYER_REBUFFERING,Z.MAJOR_EVENT],[V.IVS_PLAYER_AUDIO_BLOCKED,Z.MAJOR_EVENT],[V.IVS_PLAYER_PLAYBACK_BLOCKED,Z.MAJOR_EVENT],[V.IVS_PLAYER_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_RECOVERABLE_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_WORKER_ERROR,Z.MAJOR_EVENT],[V.IVS_PLAYER_NETWORK_UNAVAILABLE,Z.MAJOR_EVENT],[V.LIVESTREAM_LATENCY,Z.MAJOR_EVENT],[V.IVS_PLAYER_ANALYTICS_EVENT,Z.MINOR_EVENT],[V.IVS_PLAYER_PLAYBACK_RATE_CHANGED,Z.MINOR_EVENT],[V.IVS_PLAYER_QUALITY_CHANGED,Z.MINOR_EVENT],[V.IVS_PLAYER_INITIALIZED,Z.MINOR_EVENT],[V.EXPECTED_VIDEO_RESOLUTION,Z.MINOR_EVENT],[V.EXPECTED_SCREENSHARE_RESOLUTION,Z.MINOR_EVENT]]);class ES{constructor(){m(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class TS extends lt{constructor({logger:e,peerId:i,apiHostnames:n}){super(),m(this,"logger"),m(this,"peerId"),m(this,"eventStore"),m(this,"apiEndpoint"),this.logger=e,this.peerId=i,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new ES}sendEventsChunkToServer(e){return u(this,null,function*(){var i;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(r){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:r}),(i=e.entries)==null||i.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),SS.get(e.event)===Z.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const i=this.eventStore.flush();return(e=i==null?void 0:i.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(i),!0):!1})}}var Vp;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(Vp||(Vp={}));const js={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Qt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Qt||(Qt={}));var Up;(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"})(Up||(Up={}));function dn(t){return t?t.split(".").slice(0,2).concat(["0","0"]).join("."):""}function dc({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function lc({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}const Fp=240,Bp=720,Wp=8,jp=3,uc=10,hc=.02,pc=.03;function Bi({stat:t,weight:e,rangeMin:i,rangeMax:n,rangeRankingDirection:r}){return t==null?e:i===n?r==="UP"?t<=i?e:0:t>=n?e:0:r==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-i,0)/(n-i))*e:r==="DOWN"?Math.max(Math.min(n,Math.abs(t))-i,0)/(n-i)*e:e}function Hp({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:i,jitterQuality:n,packetsLostQuality:r}){const s=.8*((t?.85:1)*(i?.7:1)*(e?.5:1))+.2*(n*r);return Math.round((s+Number.EPSILON)*100)/100}function Gp({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function qp({packetsLost:t,packetsSent:e,jitter:i}){const n=Bi({stat:Gp({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),r=Bi({stat:i,weight:.3,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"});return n+r}function kS({frameWidth:t,isScreenShare:e}){return t<(e?Bp:Fp)}function bS({framesPerSecond:t,isScreenShare:e}){return t<(e?jp:Wp)}function _S({framesEncoded:t}){return t===0}function Jp({frameWidth:t,framesPerSecond:e,packetsLost:i,packetsSent:n,jitter:r,isScreenShare:s,framesEncoded:o}){const c=Bi({stat:Gp({packetsLost:i,packetsSent:n}),weight:1,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),d=Bi({stat:r,weight:1,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"}),l=kS({frameWidth:t,isScreenShare:s}),p=bS({framesPerSecond:e,isScreenShare:s}),g=_S({framesEncoded:o,isScreenShare:s});return Hp({isLowQualityVideo:l,isVideoLagging:p,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}function $p({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function Kp({concealmentEvents:t,packetsLost:e,packetsReceived:i,jitter:n}){const r=Bi({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=Bi({stat:$p({packetsLost:e,packetsReceived:i}),weight:s,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),c=Bi({stat:n,weight:.3,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"});return r+o+c}function wS({framesDecoded:t}){return t===0}function IS({framesPerSecond:t,isScreenShare:e}){return t<(e?jp:Wp)}function CS({frameWidth:t,isScreenShare:e}){return t<(e?Bp:Fp)}function zp({frameWidth:t,framesPerSecond:e,packetsLost:i,packetsReceived:n,jitter:r,isScreenShare:s,framesDecoded:o}){const c=Bi({stat:$p({packetsLost:i,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:uc,rangeRankingDirection:"UP"}),d=Bi({stat:r,weight:1,rangeMin:hc,rangeMax:pc,rangeRankingDirection:"UP"}),l=CS({frameWidth:t,isScreenShare:s}),p=IS({framesPerSecond:e,isScreenShare:s}),g=wS({framesDecoded:o,isScreenShare:s});return Hp({isLowQualityVideo:l,isVideoLagging:p,isVideoStuck:g,jitterQuality:d,packetsLostQuality:c})}class Wi{constructor(e){m(this,"pc1"),m(this,"pc2"),m(this,"constrainVideoBitrateKbps"),m(this,"constrainOfferToRemoveVideoFec",!1),m(this,"iceCandidateFilter");const i=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=i,this.pc2=n,this.iceCandidateFilter=Wi.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 i="candidate:",n=e.indexOf(i)+i.length,r=e.substr(n).split(" ");return{type:r[7],protocol:r[2],address:r[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,i){if(i.candidate){const n=Wi.parseCandidate(i.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(i.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
10
10
  `),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
11
11
  b=AS:${this.constrainVideoBitrateKbps}\r
12
- `)),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 p(this,null,function*(){const[e,n]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let i,s;if(e.forEach(r=>{r.type==="candidate-pair"&&r.nominated===!0&&r.bytesSent>0&&(i=r)}),n.forEach(r=>{r.type==="candidate-pair"&&r.nominated===!0&&r.bytesReceived>0&&(s=r)}),i&&s)try{if(i.currentRoundTripTime&&s.currentRoundTripTime)return{rtt:i.currentRoundTripTime,backendRTT:s.currentRoundTripTime};const r=(s.lastPacketReceivedTimestamp-i.lastPacketSentTimestamp)/1e3;return{rtt:r,backendRTT:r}}catch(r){return}})}close(){this.pc1.close(),this.pc2.close()}}class mf extends Mt{constructor(e){super(),y(this,"call"),y(this,"timeOut"),this.call=new mi(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 jS=8,WS=1/1e3;class HS extends mf{constructor(e){super(e),y(this,"senderChannel"),y(this,"recieveChannel"),y(this,"startTime"),y(this,"lastBitrateMeasureTime"),y(this,"sentPayloadBytes",0),y(this,"recievedPayloadBytes",0),y(this,"lastReceivedPayloadBytes",0),y(this,"stopSending",!1),y(this,"testProgress",0),y(this,"samplePacket",""),y(this,"finalBitrateSum",0),y(this,"bitRateSampels",0),y(this,"maxNumberOfPacketsToSend",0),y(this,"bytesToKeepBuffered",0),y(this,"testDurationSeconds",5),this.call.setIceCandidateFilter(mi.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let n=0;n<262144;n+=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 i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(s){}}const n=e.getTime()-this.startTime.getTime();n>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=n/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const n=new Date,i=n.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const s=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*jS/(i/1e3);this.finalBitrateSum+=s,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=n}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const s=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(s*WS)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:n,backendRTT:i})=>super.testComplete({RTT:n,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class gu extends mf{constructor(e,n=mi.noFilter){super(e),y(this,"ch1"),y(this,"ch2"),this.call.setIceCandidateFilter(n);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.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(n){}}dataChannelHandler(e){const n=e.channel;this.ch2=n,n.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class qS extends gu{constructor(e){super(e,mi.isHost)}}class GS extends gu{constructor(e){super(e,mi.isRelay)}}class JS extends gu{constructor(e){super(e,mi.isReflexive)}}class $S{constructor(){y(this,"ipInformation",null)}getIPDetails(e){return p(this,arguments,function*({peerId:n,apiHostnames:i,logger:s}){var r,a,c;if(!this.ipInformation){try{const d=`https://${i.location}`,h=yield(yield fetch(d)).json();if(((r=h.loc)==null?void 0:r.length)>5)return this.ipInformation=h,(a=this.ipInformation)!=null&&a.ip&&(this.ipInformation.ip=Li(this.ipInformation.ip)),h;throw Error("Insufficient data")}catch(d){s.error("callstats::ipDetails:: failed to fetch ip using location service",{error:d})}try{const d=yield fetch(`https://${i.locationLegacy}/?token=3c493932b0624c&peerId=${n}`,{method:"POST"});this.ipInformation=yield d.json(),(c=this.ipInformation)!=null&&c.ip&&(this.ipInformation.ip=Li(this.ipInformation.ip))}catch(d){s.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:d})}}return this.ipInformation})}resetCache(){this.ipInformation=null}}const vu=new $S,ff=[{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 gf(t){const[e,n]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(n)}}}class vf{constructor(){y(this,"transport"),y(this,"candidatePair"),y(this,"outboundVideoRtp",new Map),y(this,"inboundVideoRtp",new Map),y(this,"outboundAudioRtp",new Map),y(this,"inboundAudioRtp",new Map),y(this,"remoteInboundRtp",new Map),y(this,"producerStreamMap",new Map),y(this,"consumerStreamMap",new Map),y(this,"staleProducerStreamMap",!1),y(this,"staleConsumerStreamMap",!1)}}class yf extends Mt{constructor(){super(),y(this,"observer"),y(this,"outboundProducerMap",new Map),y(this,"inboundConsumerMap",new Map),y(this,"consumerPeerIdMap",new Map),y(this,"pausedConsumerMap",new Map),y(this,"pausedProducerMap",new Map),y(this,"overallProducingTransportsStatsMap",{}),y(this,"overallConsumingTransportsStatsMap",{}),y(this,"overallConsumersStatsMap",{}),y(this,"overallProducersStatsMap",{}),y(this,"videoProducerToStatsMap",new Map),y(this,"audioProducerToStatsMap",new Map),y(this,"videoConsumerToStatsMap",new Map),y(this,"audioConsumerToStatsMap",new Map),y(this,"consumerIdsWithFreezedVideo",new Set),y(this,"consumerIdsWithFreezedAudio",new Set),y(this,"producerIdsWithFreezedVideo",new Set),y(this,"producerIdsWithFreezedAudio",new Set),y(this,"freezedProducingTransportIds",new Set),y(this,"freezedConsumingTransportIds",new Set),y(this,"screenShareProducers",new Set),y(this,"screenShareConsumers",new Set),y(this,"ipDetails"),y(this,"callStatsInstance"),this.observer=new Mt}registerProducer(e){return p(this,null,function*(){yield this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.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,n,i){var s,r;const a=((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.get(e))||{};n.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(n.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&a.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,n,i){var s,r;const a=((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.get(e))||{};n.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(n.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&a.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{};n.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&r.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(n.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&r.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{};n.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&r.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(n.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&r.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,n,i){var s;const r=((s=this==null?void 0:this.callStatsInstance)==null?void 0:s.currentUserMediaStates)||{},{audio:a,video:c,screen:d}=r,h=a||c||d;n.totalPacketsSent===i.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))):(n.totalPacketsSent=i.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,n,i){var s,r;const a=!!Array.from(((r=(s=this==null?void 0:this.callStatsInstance)==null?void 0:s.consumerSharedMediaStatesMap)==null?void 0:r.values())||[]).reduce((c,d)=>c||d.audio||d.video||d.screen,!1);n.totalPacketsReceived===i.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(n.totalPacketsReceived=i.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&a&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return p(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.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,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=n?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const r of i.values())switch(r.type){case"outbound-rtp":{this.outboundProducerMap.set(r.id,e.id);break}}return s})}generateConsumerStreamMap(e,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=n?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const r of i.values())switch(r.type){case"inbound-rtp":{this.inboundConsumerMap.set(r.id,e.id);break}}return s})}deregisterProducer(e){this.outboundProducerMap.forEach((n,i)=>{n===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((n,i)=>{n===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var n;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(n=e.relayProtocol)!=null?n:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(n=>{const i=n.framesEncoded>0,s=n.packetsSent>0,r=n.frameWidth&&n.frameHeight;return i&&s&&!!r})||e[e.length-1]}parseRTCReport(e,n=[],i=!1,s=void 0,r=void 0){var a,c,d,h,u,g,E,b,w,M,D,F,Y;const X=e,A=new vf,J=n.length?new Set(n):void 0,me=[],Re=[],fe=[],Qe=new Map,vt=new Map;for(const V of X.values()){if(J){if(J.size===0)break;if(J.has(V.type))i&&J.delete(V.type);else continue}switch(V.type){case"local-candidate":{me.push(this.getIceCandidateStats(V));break}case"remote-candidate":{Re.push(this.getIceCandidateStats(V));break}case"candidate-pair":{const{nominated:I}=V,{selected:P}=V,K=V,Se={nominated:I!=null?I:P,currentRoundTripTime:K.currentRoundTripTime,totalRoundTripTime:K.totalRoundTripTime,bytesReceived:K.bytesReceived,bytesSent:K.bytesSent,availableOutgoingBitrate:K.availableOutgoingBitrate,availableIncomingBitrate:K.availableIncomingBitrate,lastPacketReceivedTimestamp:K.lastPacketReceivedTimestamp,lastPacketSentTimestamp:K.lastPacketSentTimestamp,localCandidateId:K.localCandidateId,remoteCandidateId:K.remoteCandidateId,bytesDiscardedOnSend:K.bytesDiscardedOnSend,packetsSent:K.packetsSent,packetsReceived:K.packetsReceived,packetsDiscardedOnSend:K.packetsDiscardedOnSend};fe.push(Se),(V.nominated===!0||V.selected===!0)&&(A.candidatePair=Se);break}case"transport":{const I=V;r&&(r.producing&&(this.overallProducingTransportsStatsMap[r.id]||(this.overallProducingTransportsStatsMap[r.id]={totalPacketsSent:0})),r.consuming&&(this.overallConsumingTransportsStatsMap[r.id]||(this.overallConsumingTransportsStatsMap[r.id]={totalPacketsReceived:0})));const P={bytesReceived:I.bytesReceived,bytesSent:I.bytesSent,packetsSent:I.packetsSent,packetsReceived:I.packetsReceived,dtlsCipher:I.dtlsCipher,dtlsState:I.dtlsState,iceRole:I.iceRole};if(A.transport=P,r){if(r.producing){const K=this.overallProducingTransportsStatsMap[r.id];this.processProducingTransportStats(r.id,K,P)}if(r.consuming){const K=this.overallConsumingTransportsStatsMap[r.id];this.processConsumingTransportStats(r.id,K,P)}}break}case"remote-inbound-rtp":{const I=V,P={jitter:I.jitter,fractionLost:I.fractionLost,roundTripTime:I.roundTripTime,roundTripTimeMeasurements:I.roundTripTimeMeasurements,totalRoundTripTime:I.totalRoundTripTime,packetsLost:I.packetsLost};A.remoteInboundRtp.set(I.localId,P);break}case"outbound-rtp":{const I=V,P=s||this.outboundProducerMap.get(V.id),K=this.pausedProducerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Se=this.overallProducersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.outboundProducerMap.has(V.id)){A.staleProducerStreamMap=!0;break}const st=this.callStatsInstance.producers.get(P);if(((a=st==null?void 0:st.track)==null?void 0:a.readyState)==="ended")break;A.producerStreamMap.has(P)||A.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const q={bytesSent:I.bytesSent,packetsSent:I.packetsSent,nackCount:I.nackCount,ssrc:I.ssrc,mid:I.mid,active:I.active,codecId:I.codecId,headerBytesSent:I.headerBytesSent||0,totalPacketSendDelay:I.totalPacketSendDelay||0};if(I.mediaType==="video"||I.kind==="video"){const N=I,rt=H({frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesEncoded:N.framesEncoded,framesDropped:N.framesDropped,framesPerSecond:N.framesPerSecond,framesSent:N.framesSent,keyFramesEncoded:N.keyFramesEncoded,firCount:N.firCount,encoderImplementation:N.encoderImplementation,hugeFramesSent:N.hugeFramesSent,pliCount:N.pliCount,qpSum:N.qpSum,qualityLimitationDurations:N.qualityLimitationDurations,qualityLimitationReason:N.qualityLimitationReason,qualityLimitationResolutionChanges:N.qualityLimitationResolutionChanges,totalEncodeTime:N.targetBitrate,totalPacketSendDelay:N.totalPacketSendDelay,retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent,scalabilityMode:N.scalabilityMode,powerEfficientEncoder:N.powerEfficientEncoder},q);A.outboundVideoRtp.set(V.id,rt),A.producerStreamMap.get(P).outboundVideoRtpId.push(V.id),this.processOutboundProducerVideoStats(P,Se,rt)}else if(I.mediaType==="audio"||I.kind==="audio"){const N=I,rt=H({retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent},q);A.outboundAudioRtp.set(V.id,rt),A.producerStreamMap.get(P).outboundAudioRtpId.push(V.id),this.processOutboundProducerAudioStats(P,Se,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}case"inbound-rtp":{const I=V,P=s||this.inboundConsumerMap.get(V.id),K=this.pausedConsumerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(I.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Se=this.overallConsumersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.inboundConsumerMap.has(V.id)){A.staleConsumerStreamMap=!0;break}A.consumerStreamMap.has(P)||A.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const st={bytesReceived:I.bytesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost>=0?I.packetsLost:0,jitter:I.jitter,nackCount:I.nackCount,jitterBufferDelay:I.jitterBufferDelay,jitterBufferEmittedCount:I.jitterBufferEmittedCount,lastPacketReceivedTimestamp:I.lastPacketReceivedTimestamp,ssrc:I.ssrc,mid:I.mid,codecId:I.codecId,headerBytesReceived:I.headerBytesReceived||0,packetsDiscarded:I.packetsDiscarded||0,jitterBufferMinimumDelay:I.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:I.jitterBufferTargetDelay||0};if(I.mediaType==="video"||I.kind==="video"){const q=I,N=H({frameHeight:q.frameHeight,frameWidth:q.frameWidth,framesDecoded:q.framesDecoded,framesDropped:q.framesDropped,framesPerSecond:q.framesPerSecond,framesReceived:q.framesReceived,keyFramesDecoded:q.keyFramesDecoded,firCount:q.firCount,decoderImplementation:q.decoderImplementation,pliCount:q.pliCount,totalProcessingDelay:q.totalProcessingDelay,qpSum:q.qpSum||0,totalAssemblyTime:q.totalAssemblyTime||0,totalDecodeTime:q.totalDecodeTime||0,totalFreezesDuration:q.totalFreezesDuration||0,totalInterFrameDelay:q.totalInterFrameDelay||0,totalPausesDuration:q.totalPausesDuration||0,totalSquaredInterFrameDelay:q.totalSquaredInterFrameDelay||0,freezeCount:q.freezeCount||0,pauseCount:q.pauseCount||0,powerEfficientDecoder:q.powerEfficientDecoder},st);N.score=pf({frameWidth:N.frameWidth||0,framesDecoded:(N.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(P))==null?void 0:c.framesDecoded)||0),framesPerSecond:N.framesPerSecond||0,packetsLost:(N.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),vt.set(P,{score:+(N.score*10).toFixed(),frameWidth:N.frameWidth||0,frameHeight:N.frameHeight||0,framesPerSecond:N.framesPerSecond||0,packetsLostPercentage:qc({packetsLost:(N.packetsLost||0)-(((u=this.videoConsumerToStatsMap.get(P))==null?void 0:u.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((E=this.videoConsumerToStatsMap.get(P))==null?void 0:E.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,N),A.inboundVideoRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundVideoRtpId.push(V.id),this.processInboundConsumerVideoStats(P,Se,N)}else if(I.mediaType==="audio"||I.kind==="audio"){const q=I,N=H({audioLevel:q.audioLevel,concealedSamples:q.concealedSamples,concealmentEvents:q.concealmentEvents,totalAudioEnergy:q.totalAudioEnergy,totalSamplesDuration:q.totalSamplesDuration,totalSamplesReceived:q.totalSamplesReceived,fecPacketsDiscarded:q.fecPacketsDiscarded||0,fecPacketsReceived:q.fecPacketsReceived||0,insertedSamplesForDeceleration:q.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:q.removedSamplesForAcceleration||0,silentConcealedSamples:q.silentConcealedSamples||0,playoutId:q.playoutId},st);N.score=hf({concealmentEvents:(N.concealmentEvents||0)-(((b=this.audioConsumerToStatsMap.get(P))==null?void 0:b.concealmentEvents)||0),packetsLost:(N.packetsLost||0)-(((w=this.audioConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:N.jitter||0}),vt.set(P,{score:+(N.score*10).toFixed(),packetsLostPercentage:qc({packetsLost:(N.packetsLost||0)-(((D=this.audioConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,N),A.inboundAudioRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundAudioRtpId.push(V.id),this.processInboundConsumerAudioStats(P,Se,N)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}}}if(A.producerStreamMap.forEach((V,I)=>{var P,K,Se,st,q,N,rt,zn,Ir,Cr,Rr,He,lt,Ts,bs,ks,ws,_s,Cn,Di,Is,Pr,Cs;if(V.outboundVideoRtpId.length>0){const ve=[];V.outboundVideoRtpId.forEach(Ic=>{ve.push(A.outboundVideoRtp.get(Ic))});const pe=this.getWorkingSimulcastVideoStats(ve);pe.score=lf({frameWidth:pe.frameWidth||0,framesPerSecond:pe.framesPerSecond||0,jitter:((P=pe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsSent:(pe.packetsSent||0)-(((K=this.videoProducerToStatsMap.get(I))==null?void 0:K.packetsSent)||0),packetsLost:(((Se=pe.remoteData)==null?void 0:Se.packetsLost)||0)-(((q=(st=this.videoProducerToStatsMap.get(I))==null?void 0:st.remoteData)==null?void 0:q.packetsLost)||0),framesEncoded:(pe.framesEncoded||0)-(((N=this.videoProducerToStatsMap.get(I))==null?void 0:N.framesEncoded)||0)}),Qe.set(I,{score:+(pe.score*10).toFixed(),frameWidth:pe.frameWidth||0,frameHeight:pe.frameHeight||0,framesPerSecond:pe.framesPerSecond||0,jitter:((rt=pe.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsLostPercentage:Hc({packetsSent:(pe.packetsSent||0)-(((zn=this.videoProducerToStatsMap.get(I))==null?void 0:zn.packetsSent)||0),packetsLost:(((Ir=pe.remoteData)==null?void 0:Ir.packetsLost)||0)-(((Rr=(Cr=this.videoProducerToStatsMap.get(I))==null?void 0:Cr.remoteData)==null?void 0:Rr.packetsLost)||0)}),bitrate:((pe.bytesSent||0)-(((He=this.videoProducerToStatsMap.get(I))==null?void 0:He.bytesSent)||0))*8/7,cpuLimitations:pe.qualityLimitationReason==="cpu",bandwidthLimitations:pe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(I,pe)}else if(V.outboundAudioRtpId.length>0){const ve=A.outboundAudioRtp.get(V.outboundAudioRtpId[0]);ve.score=df({packetsSent:(ve.packetsSent||0)-(((lt=this.audioProducerToStatsMap.get(I))==null?void 0:lt.packetsSent)||0),packetsLost:(((Ts=ve.remoteData)==null?void 0:Ts.packetsLost)||0)-(((ks=(bs=this.audioProducerToStatsMap.get(I))==null?void 0:bs.remoteData)==null?void 0:ks.packetsLost)||0),jitter:((ws=ve.remoteData)==null?void 0:ws.jitter)||0}),Qe.set(I,{score:+(ve.score*10).toFixed(),bitrate:((ve.bytesSent||0)-(((_s=this.audioProducerToStatsMap.get(I))==null?void 0:_s.bytesSent)||0))*8/7,packetsLostPercentage:Hc({packetsSent:(ve.packetsSent||0)-(((Cn=this.audioProducerToStatsMap.get(I))==null?void 0:Cn.packetsSent)||0),packetsLost:(((Di=ve.remoteData)==null?void 0:Di.packetsLost)||0)-(((Pr=(Is=this.audioProducerToStatsMap.get(I))==null?void 0:Is.remoteData)==null?void 0:Pr.packetsLost)||0)}),jitter:((Cs=ve.remoteData)==null?void 0:Cs.jitter)||0,isScreenShare:this.screenShareProducers.has(I)}),this.audioProducerToStatsMap.set(I,ve)}}),fe.forEach(V=>{const I=me.find(K=>K.id===V.localCandidateId?(V.localCandidateId=K.id,K):null),P=Re.find(K=>K.id===V.remoteCandidateId?(V.remoteCandidateId=K.id,K):null);I&&(V.localCandidateType=I.type,V.localCandidateAddress=Li(I.address),V.localCandidatePort=I.port,V.localCandidateProtocol=I.protocol,V.localCandidateUrl=I.url,V.localCandidateNetworkType=I.networkType,V.localCandidateRelatedAddress=Li(I.relatedAddress),V.localCandidateRelatedPort=I.relatedPort),P&&(V.remoteCandidateType=P.type,V.remoteCandidateAddress=Li(P.address),V.remoteCandidatePort=P.port,V.remoteCandidateProtocol=P.protocol,V.remoteCandidateUrl=P.url)}),A.candidatePair&&(A.transport?(A.transport.totalRoundTripTime=A.candidatePair.totalRoundTripTime,A.transport.availableOutgoingBitrate=A.candidatePair.availableOutgoingBitrate,A.transport.availableIncomingBitrate=A.candidatePair.availableIncomingBitrate,A.transport.roundTripTime=A.candidatePair.currentRoundTripTime):A.transport={bytesReceived:A.candidatePair.bytesReceived,bytesSent:A.candidatePair.bytesSent,totalRoundTripTime:A.candidatePair.totalRoundTripTime,availableOutgoingBitrate:A.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:A.candidatePair.availableIncomingBitrate,roundTripTime:A.candidatePair.currentRoundTripTime}),A.transport&&(A.transport.candidatePairs=fe),A.transport&&!A.transport.roundTripTime){let V=0,I=0;A.remoteInboundRtp.forEach((P,K)=>{P.roundTripTime&&P.roundTripTime>V&&(V=P.roundTripTime,I=P.totalRoundTripTime)}),A.transport.roundTripTime=V,A.transport.totalRoundTripTime=I}if(vt.size>0)try{this.observer.emit("consumer_score",vt)}catch(V){}if(Qe.size>0)try{this.observer.emit("producer_score",Qe)}catch(V){}return A}getProducersReport(e){return p(this,null,function*(){const n=e.map(i=>this.generateProducerStreamMap(i,!0));return n.length>0?Promise.all(n):void 0})}getConsumersReport(e){return p(this,null,function*(){const n=e.map(i=>this.generateConsumerStreamMap(i,!0));return n.length>0?Promise.all(n):void 0})}getTransportReport(e){return p(this,null,function*(){return e.getStats()})}getProcessedStats(e,n,i){return p(this,null,function*(){const s=yield this.getTransportReport(e),r={producing:i,consuming:n,id:e.id},a=s,c=this.parseRTCReport(a,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,r);if(!c)return;const d={stats:c.transport,transportId:e.id,consuming:n,producing:i},h=c.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(c),u=c.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(c);return{transportReport:d,producerReport:h,consumerReport:u}})}getProducerStatsFromReport(e){const n=[];try{e.producerStreamMap.forEach((i,s)=>{var r,a;n.push({producerId:s,videoStats:i.outboundVideoRtpId.map(c=>e.outboundVideoRtp.get(c)),audioStats:i.outboundAudioRtpId.map(c=>e.outboundAudioRtp.get(c)),appData:((a=(r=this.callStatsInstance.producers)==null?void 0:r.get(s))==null?void 0:a.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return n}getConsumerStatsFromReport(e){const n=[];try{e.consumerStreamMap.forEach((i,s)=>{const{peerId:r,producerId:a,appData:c}=this.consumerPeerIdMap.get(s);n.push({consumerId:s,peerId:r,producerId:a,appData:c,videoStats:i.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:i.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(i){console.error("getConsumersReport: ",i,e)}return n}getUserLocation(){return p(this,null,function*(){return new Promise((e,n)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):n()}catch(i){n(i)}})})}getConnectivity(e){return p(this,null,function*(){try{const n={iceServers:e||ff},i=new Promise((h,u)=>{try{const g=new qS(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),s=new Promise((h,u)=>{try{const g=new GS(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),r=new Promise((h,u)=>{try{const g=new JS(n);g.addListener("done",h),g.addListener("failed",()=>{h({connectivity:!1})}),g.start(2e3)}catch(g){u(g)}}),[a,c,d]=yield Promise.all([i,s,r]);return{host:a==null?void 0:a.connectivity,relay:c==null?void 0:c.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(n){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return p(this,null,function*(){try{const n=yield new Promise((i,s)=>{try{const r={iceServers:e||ff},a=new HS(r);a.addListener("done",i),a.addListener("failed",s),a.start(1e4)}catch(r){s(r)}});return{throughput:n.throughput,fractionalLoss:0,RTT:n.RTT,jitter:0,backendRTT:n.backendRTT}}catch(n){return}})}getIPDetails(){return p(this,null,function*(){var e,n;try{return this.ipDetails||(this.ipDetails=yield vu.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(n=this.callStatsInstance)==null?void 0:n.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}})}getNetworkQuality(e){return p(this,null,function*(){const[n,i]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:n,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}})}getNetworkInfo(e,n=!1){return p(this,null,function*(){var i,s;if(n){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:d!=null&&d.loc?gf(d==null?void 0:d.loc):void 0}}const[r,a,c]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:c,effectiveNetworkType:(s=navigator.connection)==null?void 0:s.effectiveType,location:c!=null&&c.loc?gf(c==null?void 0:c.loc):void 0,turnConnectivity:r?r.host||r.relay||r.reflexive:!1,connectivity:r,throughput:a==null?void 0:a.throughput,fractionalLoss:a==null?void 0:a.fractionalLoss,RTT:a==null?void 0:a.RTT,jitter:a==null?void 0:a.jitter,backendRTT:a==null?void 0:a.backendRTT}})}}class KS extends yf{}class Ef extends yf{constructor(){super(...arguments),y(this,"producerMap",new Map),y(this,"consumerMap",new Map)}registerProducer(e){return p(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return p(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.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,n=!1){return p(this,null,function*(){const i=yield e.getStats(),s=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),r=[...s.consumerStreamMap.values()][0],a=n?this.getConsumerStatsFromParsedConsumerStats(s,r,e.id):void 0;for(const c of i.values())switch(c.type){case"inbound-rtp":{this.inboundConsumerMap.set(c.id,e.id);break}}return a})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((n,i)=>{n===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((n,i)=>{n===e.id&&this.inboundConsumerMap.delete(i)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var n;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(n=e.relayProtocol)!=null?n:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,n=[],i=!1,s=void 0,r=void 0){var a,c,d,h,u,g,E,b,w,M,D,F,Y;const X=e,A=new vf,J=n.length?new Set(n):void 0,me=[],Re=[],fe=[],Qe=new Map,vt=new Map;for(const V of X.values()){if(J){if(J.size===0)break;if(J.has(V.type))i&&J.delete(V.type);else continue}switch(V.type){case"local-candidate":{me.push(this.getIceCandidateStats(V));break}case"remote-candidate":{Re.push(this.getIceCandidateStats(V));break}case"candidate-pair":{const{nominated:I}=V,{selected:P}=V,K=V,Se={nominated:I!=null?I:P,currentRoundTripTime:K.currentRoundTripTime,totalRoundTripTime:K.totalRoundTripTime,bytesReceived:K.bytesReceived,bytesSent:K.bytesSent,availableOutgoingBitrate:K.availableOutgoingBitrate,availableIncomingBitrate:K.availableIncomingBitrate,lastPacketReceivedTimestamp:K.lastPacketReceivedTimestamp,lastPacketSentTimestamp:K.lastPacketSentTimestamp,localCandidateId:K.localCandidateId,remoteCandidateId:K.remoteCandidateId,bytesDiscardedOnSend:K.bytesDiscardedOnSend,packetsSent:K.packetsSent,packetsReceived:K.packetsReceived,packetsDiscardedOnSend:K.packetsDiscardedOnSend};fe.push(Se),(V.nominated===!0||V.selected===!0)&&(A.candidatePair=Se);break}case"transport":{const I=V;r&&(r.producing&&(this.overallProducingTransportsStatsMap[r.id]||(this.overallProducingTransportsStatsMap[r.id]={totalPacketsSent:0})),r.consuming&&(this.overallConsumingTransportsStatsMap[r.id]||(this.overallConsumingTransportsStatsMap[r.id]={totalPacketsReceived:0})));const P={bytesReceived:I.bytesReceived,bytesSent:I.bytesSent,packetsSent:I.packetsSent,packetsReceived:I.packetsReceived,dtlsCipher:I.dtlsCipher,dtlsState:I.dtlsState,iceRole:I.iceRole};if(A.transport=P,r){if(r.producing){const K=this.overallProducingTransportsStatsMap[r.id];this.processProducingTransportStats(r.id,K,P)}if(r.consuming){const K=this.overallConsumingTransportsStatsMap[r.id];this.processConsumingTransportStats(r.id,K,P)}}break}case"remote-inbound-rtp":{const I=V,P={jitter:I.jitter,fractionLost:I.fractionLost,roundTripTime:I.roundTripTime,roundTripTimeMeasurements:I.roundTripTimeMeasurements,totalRoundTripTime:I.totalRoundTripTime,packetsLost:I.packetsLost};A.remoteInboundRtp.set(I.localId,P);break}case"outbound-rtp":{const I=V,P=s||this.outboundProducerMap.get(V.id),K=this.pausedProducerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Se=this.overallProducersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.outboundProducerMap.has(V.id)){A.staleProducerStreamMap=!0;break}const st=this.callStatsInstance.producers.get(P);if(((a=st==null?void 0:st.track)==null?void 0:a.readyState)==="ended")break;A.producerStreamMap.has(P)||A.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const q={bytesSent:I.bytesSent,packetsSent:I.packetsSent,nackCount:I.nackCount,ssrc:I.ssrc,mid:I.mid,active:I.active,codecId:I.codecId,headerBytesSent:I.headerBytesSent||0,totalPacketSendDelay:I.totalPacketSendDelay||0};if(I.mediaType==="video"||I.kind==="video"){const N=I,rt=H({frameHeight:N.frameHeight,frameWidth:N.frameWidth,framesEncoded:N.framesEncoded,framesDropped:N.framesDropped?N.framesDropped:N.droppedFrames,framesPerSecond:N.framesPerSecond?N.framesPerSecond:N.framerateMean,framesSent:N.framesSent,keyFramesEncoded:N.keyFramesEncoded,firCount:N.firCount,encoderImplementation:N.encoderImplementation,hugeFramesSent:N.hugeFramesSent,pliCount:N.pliCount,qpSum:N.qpSum,qualityLimitationReason:N.qualityLimitationReason,qualityLimitationDurations:N.qualityLimitationDurations,qualityLimitationResolutionChanges:N.qualityLimitationResolutionChanges,totalEncodeTime:N.totalEncodeTime,totalPacketSendDelay:N.totalEncodeTime,retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent,scalabilityMode:N.scalabilityMode,powerEfficientEncoder:N.powerEfficientEncoder},q);A.outboundVideoRtp.set(V.id,rt),A.producerStreamMap.get(P).outboundVideoRtpId.push(V.id),this.processOutboundProducerVideoStats(P,Se,rt)}else if(I.mediaType==="audio"||I.kind==="audio"){const N=I,rt=H({retransmittedBytesSent:N.retransmittedBytesSent,retransmittedPacketsSent:N.retransmittedPacketsSent},q);A.outboundAudioRtp.set(V.id,rt),A.producerStreamMap.get(P).outboundAudioRtpId.push(V.id),this.processOutboundProducerAudioStats(P,Se,rt)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}case"inbound-rtp":{const I=V,P=s||this.inboundConsumerMap.get(V.id),K=this.pausedConsumerMap.get(P);if(K){if(K.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(I.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Se=this.overallConsumersStatsMap[P];if(["video","audio"].includes(I.mediaType)||["video","audio"].includes(I.kind)){if(!this.inboundConsumerMap.has(V.id)){A.staleConsumerStreamMap=!0;break}A.consumerStreamMap.has(P)||A.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const st={bytesReceived:I.bytesReceived,packetsReceived:I.packetsReceived,packetsLost:I.packetsLost>=0?I.packetsLost:0,jitter:I.jitter,nackCount:I.nackCount,jitterBufferDelay:I.jitterBufferDelay,jitterBufferEmittedCount:I.jitterBufferEmittedCount,lastPacketReceivedTimestamp:I.lastPacketReceivedTimestamp,ssrc:I.ssrc,mid:I.mid,codecId:I.codecId,headerBytesReceived:I.headerBytesReceived||0,packetsDiscarded:I.packetsDiscarded||0,jitterBufferMinimumDelay:I.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:I.jitterBufferTargetDelay||0};if(I.mediaType==="video"||I.kind==="video"){const q=I,N=H({frameHeight:q.frameHeight,frameWidth:q.frameWidth,framesDecoded:q.framesDecoded,framesDropped:q.framesDropped?q.framesDropped:q.droppedFrames,framesPerSecond:q.framesPerSecond?q.framesPerSecond:q.framerateMean,framesReceived:q.framesReceived,keyFramesDecoded:q.keyFramesDecoded,firCount:q.firCount,decoderImplementation:q.decoderImplementation,pliCount:q.pliCount,totalProcessingDelay:q.totalProcessingDelay,qpSum:q.qpSum||0,totalAssemblyTime:q.totalAssemblyTime||0,totalDecodeTime:q.totalDecodeTime||0,totalFreezesDuration:q.totalFreezesDuration||0,totalInterFrameDelay:q.totalInterFrameDelay||0,totalPausesDuration:q.totalPausesDuration||0,totalSquaredInterFrameDelay:q.totalSquaredInterFrameDelay||0,freezeCount:q.freezeCount||0,pauseCount:q.pauseCount||0,powerEfficientDecoder:q.powerEfficientDecoder},st);N.score=pf({frameWidth:N.frameWidth||0,framesDecoded:(N.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(P))==null?void 0:c.framesDecoded)||0),framesPerSecond:N.framesPerSecond||0,packetsLost:(N.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),vt.set(P,{score:+(N.score*10).toFixed(),frameWidth:N.frameWidth||0,frameHeight:N.frameHeight||0,framesPerSecond:N.framesPerSecond||0,packetsLostPercentage:qc({packetsLost:(N.packetsLost||0)-(((u=this.videoConsumerToStatsMap.get(P))==null?void 0:u.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((E=this.videoConsumerToStatsMap.get(P))==null?void 0:E.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,N),A.inboundVideoRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundVideoRtpId.push(V.id),this.processInboundConsumerVideoStats(P,Se,N)}else if(I.mediaType==="audio"||I.kind==="audio"){const q=I,N=H({audioLevel:q.audioLevel,concealedSamples:q.concealedSamples,concealmentEvents:q.concealmentEvents,totalAudioEnergy:q.totalAudioEnergy,totalSamplesDuration:q.totalSamplesDuration,totalSamplesReceived:q.totalSamplesReceived,fecPacketsDiscarded:q.fecPacketsDiscarded||0,fecPacketsReceived:q.fecPacketsReceived||0,insertedSamplesForDeceleration:q.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:q.removedSamplesForAcceleration||0,silentConcealedSamples:q.silentConcealedSamples||0,playoutId:q.playoutId},st);N.score=hf({concealmentEvents:(N.concealmentEvents||0)-(((b=this.audioConsumerToStatsMap.get(P))==null?void 0:b.concealmentEvents)||0),packetsLost:(N.packetsLost||0)-(((w=this.audioConsumerToStatsMap.get(P))==null?void 0:w.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((M=this.audioConsumerToStatsMap.get(P))==null?void 0:M.packetsReceived)||0),jitter:N.jitter||0}),vt.set(P,{score:+(N.score*10).toFixed(),packetsLostPercentage:qc({packetsLost:(N.packetsLost||0)-(((D=this.audioConsumerToStatsMap.get(P))==null?void 0:D.packetsLost)||0),packetsReceived:(N.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.packetsReceived)||0)}),jitter:N.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((N.bytesReceived||0)-(((Y=this.audioConsumerToStatsMap.get(P))==null?void 0:Y.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,N),A.inboundAudioRtp.set(V.id,N),A.consumerStreamMap.get(P).inboundAudioRtpId.push(V.id),this.processInboundConsumerAudioStats(P,Se,N)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${I.mediaType} kind: ${I.kind}`);break}}}if(A.producerStreamMap.forEach((V,I)=>{var P,K,Se,st,q,N,rt,zn,Ir,Cr,Rr,He,lt,Ts,bs,ks,ws,_s,Cn,Di,Is,Pr,Cs;if(V.outboundVideoRtpId.length>0){const ve=[];V.outboundVideoRtpId.forEach(Ic=>{ve.push(A.outboundVideoRtp.get(Ic))});const pe=this.getWorkingSimulcastVideoStats(ve);pe.score=lf({frameWidth:pe.frameWidth||0,framesPerSecond:pe.framesPerSecond||0,jitter:((P=pe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsSent:(pe.packetsSent||0)-(((K=this.videoProducerToStatsMap.get(I))==null?void 0:K.packetsSent)||0),packetsLost:(((Se=pe.remoteData)==null?void 0:Se.packetsLost)||0)-(((q=(st=this.videoProducerToStatsMap.get(I))==null?void 0:st.remoteData)==null?void 0:q.packetsLost)||0),framesEncoded:(pe.framesEncoded||0)-(((N=this.videoProducerToStatsMap.get(I))==null?void 0:N.framesEncoded)||0)}),Qe.set(I,{score:+(pe.score*10).toFixed(),frameWidth:pe.frameWidth||0,frameHeight:pe.frameHeight||0,framesPerSecond:pe.framesPerSecond||0,jitter:((rt=pe.remoteData)==null?void 0:rt.jitter)||0,isScreenShare:this.screenShareProducers.has(I),packetsLostPercentage:Hc({packetsSent:(pe.packetsSent||0)-(((zn=this.videoProducerToStatsMap.get(I))==null?void 0:zn.packetsSent)||0),packetsLost:(((Ir=pe.remoteData)==null?void 0:Ir.packetsLost)||0)-(((Rr=(Cr=this.videoProducerToStatsMap.get(I))==null?void 0:Cr.remoteData)==null?void 0:Rr.packetsLost)||0)}),bitrate:((pe.bytesSent||0)-(((He=this.videoProducerToStatsMap.get(I))==null?void 0:He.bytesSent)||0))*8/7,cpuLimitations:pe.qualityLimitationReason==="cpu",bandwidthLimitations:pe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(I,pe)}else if(V.outboundAudioRtpId.length>0){const ve=A.outboundAudioRtp.get(V.outboundAudioRtpId[0]);ve.score=df({packetsSent:(ve.packetsSent||0)-(((lt=this.audioProducerToStatsMap.get(I))==null?void 0:lt.packetsSent)||0),packetsLost:(((Ts=ve.remoteData)==null?void 0:Ts.packetsLost)||0)-(((ks=(bs=this.audioProducerToStatsMap.get(I))==null?void 0:bs.remoteData)==null?void 0:ks.packetsLost)||0),jitter:((ws=ve.remoteData)==null?void 0:ws.jitter)||0}),Qe.set(I,{score:+(ve.score*10).toFixed(),bitrate:((ve.bytesSent||0)-(((_s=this.audioProducerToStatsMap.get(I))==null?void 0:_s.bytesSent)||0))*8/7,packetsLostPercentage:Hc({packetsSent:(ve.packetsSent||0)-(((Cn=this.audioProducerToStatsMap.get(I))==null?void 0:Cn.packetsSent)||0),packetsLost:(((Di=ve.remoteData)==null?void 0:Di.packetsLost)||0)-(((Pr=(Is=this.audioProducerToStatsMap.get(I))==null?void 0:Is.remoteData)==null?void 0:Pr.packetsLost)||0)}),jitter:((Cs=ve.remoteData)==null?void 0:Cs.jitter)||0,isScreenShare:this.screenShareProducers.has(I)}),this.audioProducerToStatsMap.set(I,ve)}}),fe.forEach(V=>{const I=me.find(K=>K.id===V.localCandidateId?(V.localCandidateId=K.id,K):null),P=Re.find(K=>K.id===V.remoteCandidateId?(V.remoteCandidateId=K.id,K):null);I&&(V.localCandidateType=I.type,V.localCandidateAddress=Li(I.address),V.localCandidatePort=I.port,V.localCandidateProtocol=I.protocol,V.localCandidateUrl=I.url,V.localCandidateNetworkType=I.networkType,V.localCandidateRelatedAddress=Li(I.relatedAddress),V.localCandidateRelatedPort=I.relatedPort),P&&(V.remoteCandidateType=P.type,V.remoteCandidateAddress=Li(P.address),V.remoteCandidatePort=P.port,V.remoteCandidateProtocol=P.protocol,V.remoteCandidateUrl=P.url)}),A.candidatePair&&(A.transport?(A.transport.bytesReceived=A.candidatePair.bytesReceived,A.transport.bytesSent=A.candidatePair.bytesSent,A.transport.totalRoundTripTime=A.candidatePair.totalRoundTripTime,A.transport.availableOutgoingBitrate=A.candidatePair.availableOutgoingBitrate,A.transport.availableIncomingBitrate=A.candidatePair.availableIncomingBitrate,A.transport.roundTripTime=A.candidatePair.currentRoundTripTime):A.transport={bytesReceived:A.candidatePair.bytesReceived,bytesSent:A.candidatePair.bytesSent,totalRoundTripTime:A.candidatePair.totalRoundTripTime,availableOutgoingBitrate:A.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:A.candidatePair.availableIncomingBitrate,roundTripTime:A.candidatePair.currentRoundTripTime}),A.transport&&(A.transport.candidatePairs=fe),A.transport&&!A.transport.roundTripTime){let V=0,I=0;A.remoteInboundRtp.forEach((P,K)=>{P.roundTripTime&&P.roundTripTime>V&&(V=P.roundTripTime,I=P.totalRoundTripTime)}),A.transport.roundTripTime=V,A.transport.totalRoundTripTime=I}if(vt.size>0)try{this.observer.emit("consumer_score",vt)}catch(V){}if(Qe.size>0)try{this.observer.emit("producer_score",Qe)}catch(V){}return A}getProducerStatsFromReport(e){const n=[];try{e.producerStreamMap.forEach((i,s)=>{const r=this.producerMap.get(s),a=r.track.getSettings(),c=i.outboundVideoRtpId.map(h=>{const u=e.outboundVideoRtp.get(h);return u.frameHeight||(u.frameHeight=a.height,u.frameWidth=a.width,u.framesPerSecond=a.frameRate),u}),d={producerId:s,appData:r.appData,videoStats:c,audioStats:i.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};n.push(d)})}catch(i){console.error("getProducersReport: ",i,e)}return n}getConsumerStatsFromParsedConsumerStats(e,n,i){let s;try{const{peerId:r,producerId:a,appData:c}=this.consumerPeerIdMap.get(i),d=n==null?void 0:n.inboundVideoRtpId.map(h=>{const u=this.consumerMap.get(i).track.getSettings(),g=e.inboundVideoRtp.get(h);return g.frameHeight||(g.frameHeight=u.height,g.frameWidth=u.width,g.framesPerSecond=u.frameRate),g});s={consumerId:i,peerId:r,producerId:a,appData:c,videoStats:d,audioStats:n==null?void 0:n.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(r){console.error("getConsumerStatsFromParsedConsumerStats: ",r,e)}return s}getConsumerStatsFromReport(e){const n=[];try{e.consumerStreamMap.forEach((i,s)=>{n.push(this.getConsumerStatsFromParsedConsumerStats(e,i,s))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return n}}class zS extends Ef{}function Kc(t,e,n,i){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:i}),typeof n=="function"&&i instanceof e)n.call(null,i,t);else throw i}function Sf(t,e,n){const i=t.value;return t.value=function(...s){try{const r=i.apply(this,s);return r&&r instanceof Promise?r.catch(a=>{Kc(this,e,n,a)}):r}catch(r){Kc(this,e,n,r)}return null},t}const le=(t,e)=>(n,i,s)=>{const r=s.value;return s.value=function(...a){try{const c=r.apply(this,a);return c&&c instanceof Promise?c.catch(d=>{Kc(this,t,e,d)}):c}catch(c){Kc(this,t,e,c)}return null},s},YS=(t,e)=>(n,i,s)=>{if(s)return Sf(s,t,e);for(const r of Reflect.ownKeys(n.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(n.prototype,r);a.value instanceof Function&&Object.defineProperty(n.prototype,r,Sf(a,t,e))}};var ce=globalThis&&globalThis.__decorate||function(t,e,n,i){var s=arguments.length,r=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,n):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(t,e,n,i);else for(var c=t.length-1;c>=0;c--)(a=t[c])&&(r=(s<3?a(r):s>3?a(e,n,r):a(e,n))||r);return s>3&&r&&Object.defineProperty(e,n,r),r};const de=console;let ae=class extends Mt{constructor(t="https://api.testingv3.dyte.in",e="Blink",n=La.PROD,i,s,r,a){switch(super(),y(this,"observer"),y(this,"eventHandler"),y(this,"measurements"),y(this,"producingTransport"),y(this,"consumingTransport"),y(this,"producers",new Map),y(this,"consumers",new Map),y(this,"iceServers"),y(this,"connectionInfoPromise"),y(this,"pingStatsTimeout"),y(this,"logger"),y(this,"env"),y(this,"apiHostnames"),y(this,"peerId"),y(this,"consumerSharedMediaStatesMap",new Map),y(this,"currentUserMediaStates",{}),this.env=n,this.apiHostnames=a,this.logger=s,this.peerId=r,this.eventHandler=new NS({logger:s,peerId:r,apiHostnames:a}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new KS;break;case"Gecko":this.measurements=new Ef;break;case"WebKit":this.measurements=new zS;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 Mt,this.measurements.observer.on("consumer_score",c=>{s.debug(`callStats::consumer_score ${[...c.entries()]}`),this.eventHandler.emit("consumer_score",c)}),this.measurements.observer.on("producer_score",c=>{s.debug(`callStats::producer_score ${[...c.entries()]}`),this.eventHandler.emit("producer_score",c)})}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.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.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const n=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(n,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(n=>{this.registerProducer(n)}),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(n=>{this.registerConsumer(n)}),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:G.PRECALL_TEST_BEGIN,timestamp:e}),this.connectionInfoPromise&&this.connectionInfoPromise.then(n=>{this.eventHandler.callEvent({event:G.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:n},timestamp:e})})}sendScreenShareToggleEvent(t,e=null,n){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?G.SCREENSHARE_STARTED:G.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:n})}sendScreenShareRequestedEvent(t){this.eventHandler.callEvent({event:G.SCREENSHARE_START_REQUESTED,timestamp:t})}sendActiveSpeakerEvent(t,e){this.eventHandler.callEvent({event:G.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:e})}devices(t,e,n){this.eventHandler.callEvent({event:t===En.AUDIO&&G.AUDIO_DEVICES_UPDATES||t===En.VIDEO&&G.VIDEO_DEVICES_UPDATES||t===En.SPEAKER&&G.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:n})}selectedDevice(t,e,n){this.eventHandler.callEvent({event:t===En.AUDIO&&G.SELECTED_MICROHPONE_UPDATE||t===En.VIDEO&&G.SELECTED_CAMERA_UPDATE||t===En.SPEAKER&&G.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:n})}mediaPermission(t,e,n){this.eventHandler.callEvent({event:G.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:n})}mediaPlaybackFailed(t,e){this.eventHandler.callEvent({event:t===En.AUDIO&&G.AUDIO_PLAY_FAILED||t===En.VIDEO&&G.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===En.AUDIO&&G.AUDIO_TRACK_MUTED||t===En.VIDEO&&G.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:e})}tabChanged(t,e){this.eventHandler.callEvent({event:G.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:e})}browserBackgrounded(t){this.eventHandler.callEvent({event:G.BROWSER_BACKGROUNDED,timestamp:t})}browserForegrounded(t){this.eventHandler.callEvent({event:G.BROWSER_FOREGROUNDED,timestamp:t})}legacySwitch(t,e){this.eventHandler.callEvent({event:G.LEGACY_SWITCH,metadata:{on:t},timestamp:e})}getPreCallTestResults(){return p(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t,e){t=ee(H({},t),{meetingEnv:this.env}),t.deviceInfo=ee(H({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:G.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:e})}sendNetworkQualityTestBeginEvent(t,e){this.eventHandler.callEvent({event:G.NET_QUALITY_TEST_BEGIN,timestamp:e}),new Promise((n,i)=>p(this,null,function*(){const s=[];try{for(const r of t)try{if(r.iceServers&&r.iceServers.length>0){const a=yield this.measurements.getNetworkQuality(r.iceServers);s.push(ee(H({},r),{networkResults:a}))}}catch(a){console.warn("Error handling ",a)}n({regionData:s})}catch(r){console.warn("Error in callstats, ",r),i(r)}})).then(n=>{this.eventHandler.callEvent({event:G.NET_QUALITY_TEST_END,timestamp:e,metaData:n})})}sendWebSocketConnectedEvent(t){this.eventHandler.callEvent({event:G.WEBSOCKET_CONNECTED,timestamp:t})}sendTransportConnectedEvent(t){this.eventHandler.callEvent({event:G.TRANSPORT_CONNECTED,timestamp:t})}sendAudioToggleEvent(t,e){this.currentUserMediaStates.audio=t;let n;t?n=G.AUDIO_ON:n=G.AUDIO_OFF,this.eventHandler.callEvent({event:n,timestamp:e})}sendVideoToggleEvent(t,e){this.currentUserMediaStates.video=t;let n;t?n=G.VIDEO_ON:n=G.VIDEO_OFF,this.eventHandler.callEvent({event:n,timestamp:e})}sendParticipantRoleToggleEvent(t,e){this.eventHandler.callEvent({event:G.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 p(this,null,function*(){let n,i;if(this.producingTransport&&(n=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!n||!(n!=null&&n.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const r=yield this.measurements.getProducersReport([...this.producers.values()]);n&&r?n.producerReport=r:(n=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!n||!(n!=null&&n.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(i=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!i||!i.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const r=yield this.measurements.getConsumersReport([...this.consumers.values()]);i&&r?i.consumerReport=r:(i=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!i||!i.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const s={producingTransportStats:n?n==null?void 0:n.transportReport:void 0,consumingTransportStats:i?i==null?void 0:i.transportReport:void 0,producerStats:[].concat((n==null?void 0:n.producerReport)||[]).concat((i==null?void 0:i.producerReport)||[]),consumerStats:[].concat((i==null?void 0:i.consumerReport)||[]).concat((n==null?void 0:n.consumerReport)||[])};if(t&&s.producerStats.length===0&&s.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:G.PING_STAT,metaData:s,timestamp:e})})}sendIVSPlayerRebufferEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_REBUFFERING,timestamp:t})}sendIVSPlayerAudioBlockEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_AUDIO_BLOCKED,timestamp:t})}sendIVSPlayerPlaybackBlockedEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:t})}sendIVSPlayerNetworkUnavailableEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:t})}sendIVSPlayerInitializedEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_INITIALIZED,timestamp:t})}sendIVSPlayerWorkerErrorEvent(t){this.eventHandler.callEvent({event:G.IVS_PLAYER_WORKER_ERROR,timestamp:t})}sendIVSPlayerErrorEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_ERROR,timestamp:e,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:e,metaData:t})}sendIVSPlayerAnalyticsEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_ANALYTICS_EVENT,timestamp:e,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:e,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t,e){this.eventHandler.callEvent({event:G.IVS_PLAYER_QUALITY_CHANGED,timestamp:e,metaData:t})}sendPlayerLiveLatency(t,e){this.eventHandler.callEvent({event:G.LIVESTREAM_LATENCY,timestamp:e,metaData:{latency:t}})}sendDisconnectEvent(t){this.eventHandler.callEvent({event:G.DISCONNECT,timestamp:t})}sendReconnectEvent(t){this.eventHandler.callEvent({event:G.RECONNECT_ATTEMPT,timestamp:t})}expectedVideoResolution(t,e,n){this.eventHandler.callEvent({event:G.EXPECTED_VIDEO_RESOLUTION,timestamp:n,metaData:{frameWidth:t,frameHeight:e}})}expectedScreenshareResolution(t,e,n){this.eventHandler.callEvent({event:G.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:n,metaData:{frameWidth:t,frameHeight:e}})}};ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerIceServers",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerConsumer",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerProducer",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendConsumerSharedMediaStateEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerProducingTransport",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"registerConsumingTransport",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"deRegisterConsumer",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"deRegisterProducer",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"disconnectConsumingTransport",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"disconnectProducingTransport",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPreCallTestBeginEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendScreenShareToggleEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendScreenShareRequestedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendActiveSpeakerEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"devices",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"selectedDevice",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaPermission",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaPlaybackFailed",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"mediaTrackMuted",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"tabChanged",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"browserBackgrounded",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"browserForegrounded",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"legacySwitch",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"getPreCallTestResults",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendCallJoinBeginEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendNetworkQualityTestBeginEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendWebSocketConnectedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendTransportConnectedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendAudioToggleEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendVideoToggleEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendParticipantRoleToggleEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"startPingStats",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"stopPingStats",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPingStatsEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerRebufferEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerAudioBlockEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerInitializedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerWorkerErrorEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerErrorEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerRecoverableErrorEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerAnalyticsEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendIVSPlayerQualityChanged",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendPlayerLiveLatency",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendDisconnectEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"sendReconnectEvent",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"expectedVideoResolution",null),ce([le(TypeError,(t,e)=>de.error(e,t))],ae.prototype,"expectedScreenshareResolution",null),ae=ce([YS(TypeError,(t,e)=>de.error(e,t))],ae);const QS=ae;class XS extends Mt{constructor(){super(...arguments),y(this,"stats"),y(this,"peerId"),y(this,"backend"),y(this,"iceServers"),y(this,"initialized",!1),y(this,"stalled",!1),y(this,"ipInformation"),y(this,"logger")}initialize(e){return p(this,arguments,function*({peerId:n,engineName:i,env:s=La.PROD,iceServers:r,apiBase:a="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:h,skipConnectivityChecks:u=!1}){var g,E,b;try{this.peerId=n,this.logger=d,this.ipInformation=yield vu.getIPDetails({peerId:n,apiHostnames:h,logger:d}),this.backend=new QS(a,i,s,c,d,n,h),this.iceServers=r,(g=this.backend)==null||g.registerIceServers(this.iceServers),this.initialized=!0,(b=(E=this.backend)==null?void 0:E.eventHandler)==null||b.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(w){this.logger.error("callStats::CallStatsIntegration: ",{error:w}),this.stallCallStats()}})}configureSendTransport(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.registerConsumingTransport(e)})}candidateRegionalNetworkQualityTest(e){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,n)}catch(s){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:s.reason}})}})})}roomJoined(e){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i,s;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,n),this.backend,(s=this.backend)==null||s.startPingStats()})})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var n,i;(n=this.backend)==null||n.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,n)})}consumerSharedMediaState(e,n){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,n)})}screenShareStop(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,n)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,n)})}devices(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.devices(e,n,i)})}selectedDevice(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.selectedDevice(e,n,i)})}mediaPermission(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.mediaPermission(e,n,i)})}mediaPlaybackFailed(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,n)})}mediaTrackMuted(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,n)})}tabChanged(e=!1){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,n)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.browserForegrounded(e)})}legacySwitch(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,n)})}startPreCallTest(e=!1){return p(this,null,function*(){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,n)})})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const n=i=>{e(i,!0)};return this.once("initialized",n),n}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,n){const i=new Date;this.onSafeInitialization(()=>{var s,r,a,c,d,h,u,g,E,b,w;switch(e){case"PlayerRebuffering":(s=this.backend)==null||s.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(r=this.backend)==null||r.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(a=this.backend)==null||a.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(c=this.backend)==null||c.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(h=this.backend)==null||h.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(u=this.backend)==null||u.sendIVSPlayerErrorEvent(n,i);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(n,i);break;case"PlayerAnalyticsEvent":(E=this.backend)==null||E.sendIVSPlayerAnalyticsEvent(n,i);break;case"PlayerPlaybackRateChanged":(b=this.backend)==null||b.sendIVSPlayerPlaybackRateChangedEvent(n,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.sendIVSPlayerQualityChanged(n,i);break}})}livestreamLatency(e){const n=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,n)})}expectedVideoResolution(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.expectedVideoResolution(e,n,i)})}expectedScreenshareResolution(e,n){const i=new Date;this.onSafeInitialization(()=>{var s;(s=this.backend)==null||s.expectedScreenshareResolution(e,n,i)})}}const te=new XS;te.setMaxListeners(30);function ZS(t){const{length:e}=this,n=t>=0?t:e+t;return n<0||n>=e?void 0:this[n]}Array.prototype.at||Object.assign(Array.prototype,{at:ZS});function eT(t){const{length:e}=this,n=t>=0?t:e+t;return n<0||n>=e?void 0:this[n]}String.prototype.at||Object.assign(String.prototype,{at:eT});function tT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Tf={exports:{}},et=Tf.exports={},Qn,Xn;function yu(){throw new Error("setTimeout has not been defined")}function Eu(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Qn=setTimeout:Qn=yu}catch(t){Qn=yu}try{typeof clearTimeout=="function"?Xn=clearTimeout:Xn=Eu}catch(t){Xn=Eu}})();function bf(t){if(Qn===setTimeout)return setTimeout(t,0);if((Qn===yu||!Qn)&&setTimeout)return Qn=setTimeout,setTimeout(t,0);try{return Qn(t,0)}catch(e){try{return Qn.call(null,t,0)}catch(n){return Qn.call(this,t,0)}}}function nT(t){if(Xn===clearTimeout)return clearTimeout(t);if((Xn===Eu||!Xn)&&clearTimeout)return Xn=clearTimeout,clearTimeout(t);try{return Xn(t)}catch(e){try{return Xn.call(null,t)}catch(n){return Xn.call(this,t)}}}var fi=[],Dr=!1,As,zc=-1;function iT(){!Dr||!As||(Dr=!1,As.length?fi=As.concat(fi):zc=-1,fi.length&&kf())}function kf(){if(!Dr){var t=bf(iT);Dr=!0;for(var e=fi.length;e;){for(As=fi,fi=[];++zc<e;)As&&As[zc].run();zc=-1,e=fi.length}As=null,Dr=!1,nT(t)}}et.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];fi.push(new wf(t,e)),fi.length===1&&!Dr&&bf(kf)};function wf(t,e){this.fun=t,this.array=e}wf.prototype.run=function(){this.fun.apply(null,this.array)},et.title="browser",et.browser=!0,et.env={},et.argv=[],et.version="",et.versions={};function gi(){}et.on=gi,et.addListener=gi,et.once=gi,et.off=gi,et.removeListener=gi,et.removeAllListeners=gi,et.emit=gi,et.prependListener=gi,et.prependOnceListener=gi,et.listeners=function(t){return[]},et.binding=function(t){throw new Error("process.binding is not supported")},et.cwd=function(){return"/"},et.chdir=function(t){throw new Error("process.chdir is not supported")},et.umask=function(){return 0};var sT=Tf.exports;const Ms=tT(sT);var Su={},rT={get exports(){return Su},set exports(t){Su=t}},Yc={},aT={get exports(){return Yc},set exports(t){Yc=t}},_f=function(t,e){return function(){return t.apply(e,arguments)}},oT=_f,Tu=Object.prototype.toString,bu=function(t){return function(e){var n=Tu.call(e);return t[n]||(t[n]=n.slice(8,-1).toLowerCase())}}(Object.create(null));function xi(t){return t=t.toLowerCase(),function(e){return bu(e)===t}}function Qc(t){return Array.isArray(t)}function ku(t){return typeof t=="undefined"}function cT(t){return t!==null&&!ku(t)&&t.constructor!==null&&!ku(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}var If=xi("ArrayBuffer");function dT(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&If(t.buffer),e}function lT(t){return typeof t=="string"}function Cf(t){return typeof t=="number"}function Rf(t){return t!==null&&typeof t=="object"}function Xc(t){if(bu(t)!=="object")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function uT(t){return t&&Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}var hT=xi("Date"),pT=xi("File"),mT=xi("Blob"),fT=xi("FileList");function wu(t){return Tu.call(t)==="[object Function]"}function gT(t){return Rf(t)&&wu(t.pipe)}function vT(t){var e="[object FormData]";return t&&(typeof FormData=="function"&&t instanceof FormData||Tu.call(t)===e||wu(t.toString)&&t.toString()===e)}var yT=xi("URLSearchParams");function ET(t){return t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}function ST(){var t;return typeof navigator!="undefined"&&((t=navigator.product)==="ReactNative"||t==="NativeScript"||t==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function _u(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),Qc(t))for(var n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.call(null,t[s],s,t)}function Iu(){var t={};function e(s,r){Xc(t[r])&&Xc(s)?t[r]=Iu(t[r],s):Xc(s)?t[r]=Iu({},s):Qc(s)?t[r]=s.slice():t[r]=s}for(var n=0,i=arguments.length;n<i;n++)_u(arguments[n],e);return t}function TT(t,e,n){return _u(e,function(i,s){n&&typeof i=="function"?t[s]=oT(i,n):t[s]=i}),t}function bT(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}function kT(t,e,n,i){t.prototype=Object.create(e.prototype,i),t.prototype.constructor=t,n&&Object.assign(t.prototype,n)}function wT(t,e,n,i){var s,r,a,c={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),r=s.length;r-- >0;)a=s[r],(!i||i(a,t,e))&&!c[a]&&(e[a]=t[a],c[a]=!0);t=n!==!1&&Object.getPrototypeOf(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e}function _T(t,e,n){t=String(t),(n===void 0||n>t.length)&&(n=t.length),n-=e.length;var i=t.indexOf(e,n);return i!==-1&&i===n}function IT(t){if(!t)return null;if(Qc(t))return t;var e=t.length;if(!Cf(e))return null;for(var n=new Array(e);e-- >0;)n[e]=t[e];return n}var CT=function(t){return function(e){return t&&e instanceof t}}(typeof Uint8Array!="undefined"&&Object.getPrototypeOf(Uint8Array));function RT(t,e){for(var n=t&&t[Symbol.iterator],i=n.call(t),s;(s=i.next())&&!s.done;){var r=s.value;e.call(t,r[0],r[1])}}function PT(t,e){for(var n,i=[];(n=t.exec(e))!==null;)i.push(n);return i}var AT=xi("HTMLFormElement"),MT=function(t){return function(e,n){return t.call(e,n)}}(Object.prototype.hasOwnProperty),ht={isArray:Qc,isArrayBuffer:If,isBuffer:cT,isFormData:vT,isArrayBufferView:dT,isString:lT,isNumber:Cf,isObject:Rf,isPlainObject:Xc,isEmptyObject:uT,isUndefined:ku,isDate:hT,isFile:pT,isBlob:mT,isFunction:wu,isStream:gT,isURLSearchParams:yT,isStandardBrowserEnv:ST,forEach:_u,merge:Iu,extend:TT,trim:ET,stripBOM:bT,inherits:kT,toFlatObject:wT,kindOf:bu,kindOfTest:xi,endsWith:_T,toArray:IT,isTypedArray:CT,isFileList:fT,forEachEntry:RT,matchAll:PT,isHTMLForm:AT,hasOwnProperty:MT},pt={},Zc={};Zc.byteLength=NT,Zc.toByteArray=xT,Zc.fromByteArray=BT;for(var Zn=[],Sn=[],OT=typeof Uint8Array!="undefined"?Uint8Array:Array,Cu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Nr=0,DT=Cu.length;Nr<DT;++Nr)Zn[Nr]=Cu[Nr],Sn[Cu.charCodeAt(Nr)]=Nr;Sn["-".charCodeAt(0)]=62,Sn["_".charCodeAt(0)]=63;function Pf(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var i=n===e?0:4-n%4;return[n,i]}function NT(t){var e=Pf(t),n=e[0],i=e[1];return(n+i)*3/4-i}function LT(t,e,n){return(e+n)*3/4-n}function xT(t){var e,n=Pf(t),i=n[0],s=n[1],r=new OT(LT(t,i,s)),a=0,c=s>0?i-4:i,d;for(d=0;d<c;d+=4)e=Sn[t.charCodeAt(d)]<<18|Sn[t.charCodeAt(d+1)]<<12|Sn[t.charCodeAt(d+2)]<<6|Sn[t.charCodeAt(d+3)],r[a++]=e>>16&255,r[a++]=e>>8&255,r[a++]=e&255;return s===2&&(e=Sn[t.charCodeAt(d)]<<2|Sn[t.charCodeAt(d+1)]>>4,r[a++]=e&255),s===1&&(e=Sn[t.charCodeAt(d)]<<10|Sn[t.charCodeAt(d+1)]<<4|Sn[t.charCodeAt(d+2)]>>2,r[a++]=e>>8&255,r[a++]=e&255),r}function VT(t){return Zn[t>>18&63]+Zn[t>>12&63]+Zn[t>>6&63]+Zn[t&63]}function UT(t,e,n){for(var i,s=[],r=e;r<n;r+=3)i=(t[r]<<16&16711680)+(t[r+1]<<8&65280)+(t[r+2]&255),s.push(VT(i));return s.join("")}function BT(t){for(var e,n=t.length,i=n%3,s=[],r=16383,a=0,c=n-i;a<c;a+=r)s.push(UT(t,a,a+r>c?c:a+r));return i===1?(e=t[n-1],s.push(Zn[e>>2]+Zn[e<<4&63]+"==")):i===2&&(e=(t[n-2]<<8)+t[n-1],s.push(Zn[e>>10]+Zn[e>>4&63]+Zn[e<<2&63]+"=")),s.join("")}var Ru={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Ru.read=function(t,e,n,i,s){var r,a,c=s*8-i-1,d=(1<<c)-1,h=d>>1,u=-7,g=n?s-1:0,E=n?-1:1,b=t[e+g];for(g+=E,r=b&(1<<-u)-1,b>>=-u,u+=c;u>0;r=r*256+t[e+g],g+=E,u-=8);for(a=r&(1<<-u)-1,r>>=-u,u+=i;u>0;a=a*256+t[e+g],g+=E,u-=8);if(r===0)r=1-h;else{if(r===d)return a?NaN:(b?-1:1)*(1/0);a=a+Math.pow(2,i),r=r-h}return(b?-1:1)*a*Math.pow(2,r-i)},Ru.write=function(t,e,n,i,s,r){var a,c,d,h=r*8-s-1,u=(1<<h)-1,g=u>>1,E=s===23?Math.pow(2,-24)-Math.pow(2,-77):0,b=i?0:r-1,w=i?1:-1,M=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(d=Math.pow(2,-a))<1&&(a--,d*=2),a+g>=1?e+=E/d:e+=E*Math.pow(2,1-g),e*d>=2&&(a++,d/=2),a+g>=u?(c=0,a=u):a+g>=1?(c=(e*d-1)*Math.pow(2,s),a=a+g):(c=e*Math.pow(2,g-1)*Math.pow(2,s),a=0));s>=8;t[n+b]=c&255,b+=w,c/=256,s-=8);for(a=a<<s|c,h+=s;h>0;t[n+b]=a&255,b+=w,a/=256,h-=8);t[n+b-w]|=M*128};/*!
13
- * The buffer module from node.js, for the browser.
14
- *
15
- * @author Feross Aboukhadijeh <https://feross.org>
16
- * @license MIT
17
- */(function(t){const e=Zc,n=Ru,i=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=u,t.SlowBuffer=J,t.INSPECT_MAX_BYTES=50;const s=2147483647;t.kMaxLength=s;const{Uint8Array:r,ArrayBuffer:a,SharedArrayBuffer:c}=globalThis;u.TYPED_ARRAY_SUPPORT=d(),!u.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function d(){try{const l=new r(1),f={foo:function(){return 42}};return Object.setPrototypeOf(f,r.prototype),Object.setPrototypeOf(l,f),l.foo()===42}catch(l){return!1}}Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}});function h(l){if(l>s)throw new RangeError('The value "'+l+'" is invalid for option "size"');const f=new r(l);return Object.setPrototypeOf(f,u.prototype),f}function u(l,f,v){if(typeof l=="number"){if(typeof f=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return w(l)}return g(l,f,v)}u.poolSize=8192;function g(l,f,v){if(typeof l=="string")return M(l,f);if(a.isView(l))return F(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(ui(l,a)||l&&ui(l.buffer,a)||typeof c!="undefined"&&(ui(l,c)||l&&ui(l.buffer,c)))return Y(l,f,v);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const C=l.valueOf&&l.valueOf();if(C!=null&&C!==l)return u.from(C,f,v);const R=X(l);if(R)return R;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return u.from(l[Symbol.toPrimitive]("string"),f,v);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}u.from=function(l,f,v){return g(l,f,v)},Object.setPrototypeOf(u.prototype,r.prototype),Object.setPrototypeOf(u,r);function E(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function b(l,f,v){return E(l),l<=0?h(l):f!==void 0?typeof v=="string"?h(l).fill(f,v):h(l).fill(f):h(l)}u.alloc=function(l,f,v){return b(l,f,v)};function w(l){return E(l),h(l<0?0:A(l)|0)}u.allocUnsafe=function(l){return w(l)},u.allocUnsafeSlow=function(l){return w(l)};function M(l,f){if((typeof f!="string"||f==="")&&(f="utf8"),!u.isEncoding(f))throw new TypeError("Unknown encoding: "+f);const v=me(l,f)|0;let C=h(v);const R=C.write(l,f);return R!==v&&(C=C.slice(0,R)),C}function D(l){const f=l.length<0?0:A(l.length)|0,v=h(f);for(let C=0;C<f;C+=1)v[C]=l[C]&255;return v}function F(l){if(ui(l,r)){const f=new r(l);return Y(f.buffer,f.byteOffset,f.byteLength)}return D(l)}function Y(l,f,v){if(f<0||l.byteLength<f)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<f+(v||0))throw new RangeError('"length" is outside of buffer bounds');let C;return f===void 0&&v===void 0?C=new r(l):v===void 0?C=new r(l,f):C=new r(l,f,v),Object.setPrototypeOf(C,u.prototype),C}function X(l){if(u.isBuffer(l)){const f=A(l.length)|0,v=h(f);return v.length===0||l.copy(v,0,0,f),v}if(l.length!==void 0)return typeof l.length!="number"||ym(l.length)?h(0):D(l);if(l.type==="Buffer"&&Array.isArray(l.data))return D(l.data)}function A(l){if(l>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return l|0}function J(l){return+l!=l&&(l=0),u.alloc(+l)}u.isBuffer=function(l){return l!=null&&l._isBuffer===!0&&l!==u.prototype},u.compare=function(l,f){if(ui(l,r)&&(l=u.from(l,l.offset,l.byteLength)),ui(f,r)&&(f=u.from(f,f.offset,f.byteLength)),!u.isBuffer(l)||!u.isBuffer(f))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(l===f)return 0;let v=l.length,C=f.length;for(let R=0,U=Math.min(v,C);R<U;++R)if(l[R]!==f[R]){v=l[R],C=f[R];break}return v<C?-1:C<v?1:0},u.isEncoding=function(l){switch(String(l).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(l,f){if(!Array.isArray(l))throw new TypeError('"list" argument must be an Array of Buffers');if(l.length===0)return u.alloc(0);let v;if(f===void 0)for(f=0,v=0;v<l.length;++v)f+=l[v].length;const C=u.allocUnsafe(f);let R=0;for(v=0;v<l.length;++v){let U=l[v];if(ui(U,r))R+U.length>C.length?(u.isBuffer(U)||(U=u.from(U)),U.copy(C,R)):r.prototype.set.call(C,U,R);else if(u.isBuffer(U))U.copy(C,R);else throw new TypeError('"list" argument must be an Array of Buffers');R+=U.length}return C};function me(l,f){if(u.isBuffer(l))return l.length;if(a.isView(l)||ui(l,a))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);const v=l.length,C=arguments.length>2&&arguments[2]===!0;if(!C&&v===0)return 0;let R=!1;for(;;)switch(f){case"ascii":case"latin1":case"binary":return v;case"utf8":case"utf-8":return vm(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return v*2;case"hex":return v>>>1;case"base64":return bE(l).length;default:if(R)return C?-1:vm(l).length;f=(""+f).toLowerCase(),R=!0}}u.byteLength=me;function Re(l,f,v){let C=!1;if((f===void 0||f<0)&&(f=0),f>this.length||((v===void 0||v>this.length)&&(v=this.length),v<=0)||(v>>>=0,f>>>=0,v<=f))return"";for(l||(l="utf8");;)switch(l){case"hex":return Cr(this,f,v);case"utf8":case"utf-8":return q(this,f,v);case"ascii":return zn(this,f,v);case"latin1":case"binary":return Ir(this,f,v);case"base64":return st(this,f,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Rr(this,f,v);default:if(C)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),C=!0}}u.prototype._isBuffer=!0;function fe(l,f,v){const C=l[f];l[f]=l[v],l[v]=C}u.prototype.swap16=function(){const l=this.length;if(l%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let f=0;f<l;f+=2)fe(this,f,f+1);return this},u.prototype.swap32=function(){const l=this.length;if(l%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let f=0;f<l;f+=4)fe(this,f,f+3),fe(this,f+1,f+2);return this},u.prototype.swap64=function(){const l=this.length;if(l%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let f=0;f<l;f+=8)fe(this,f,f+7),fe(this,f+1,f+6),fe(this,f+2,f+5),fe(this,f+3,f+4);return this},u.prototype.toString=function(){const l=this.length;return l===0?"":arguments.length===0?q(this,0,l):Re.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(l){if(!u.isBuffer(l))throw new TypeError("Argument must be a Buffer");return this===l?!0:u.compare(this,l)===0},u.prototype.inspect=function(){let l="";const f=t.INSPECT_MAX_BYTES;return l=this.toString("hex",0,f).replace(/(.{2})/g,"$1 ").trim(),this.length>f&&(l+=" ... "),"<Buffer "+l+">"},i&&(u.prototype[i]=u.prototype.inspect),u.prototype.compare=function(l,f,v,C,R){if(ui(l,r)&&(l=u.from(l,l.offset,l.byteLength)),!u.isBuffer(l))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof l);if(f===void 0&&(f=0),v===void 0&&(v=l?l.length:0),C===void 0&&(C=0),R===void 0&&(R=this.length),f<0||v>l.length||C<0||R>this.length)throw new RangeError("out of range index");if(C>=R&&f>=v)return 0;if(C>=R)return-1;if(f>=v)return 1;if(f>>>=0,v>>>=0,C>>>=0,R>>>=0,this===l)return 0;let U=R-C,$=v-f;const Le=Math.min(U,$),Pt=this.slice(C,R),qe=l.slice(f,v);for(let xe=0;xe<Le;++xe)if(Pt[xe]!==qe[xe]){U=Pt[xe],$=qe[xe];break}return U<$?-1:$<U?1:0};function Qe(l,f,v,C,R){if(l.length===0)return-1;if(typeof v=="string"?(C=v,v=0):v>2147483647?v=2147483647:v<-2147483648&&(v=-2147483648),v=+v,ym(v)&&(v=R?0:l.length-1),v<0&&(v=l.length+v),v>=l.length){if(R)return-1;v=l.length-1}else if(v<0)if(R)v=0;else return-1;if(typeof f=="string"&&(f=u.from(f,C)),u.isBuffer(f))return f.length===0?-1:vt(l,f,v,C,R);if(typeof f=="number")return f=f&255,typeof r.prototype.indexOf=="function"?R?r.prototype.indexOf.call(l,f,v):r.prototype.lastIndexOf.call(l,f,v):vt(l,[f],v,C,R);throw new TypeError("val must be string, number or Buffer")}function vt(l,f,v,C,R){let U=1,$=l.length,Le=f.length;if(C!==void 0&&(C=String(C).toLowerCase(),C==="ucs2"||C==="ucs-2"||C==="utf16le"||C==="utf-16le")){if(l.length<2||f.length<2)return-1;U=2,$/=2,Le/=2,v/=2}function Pt(xe,ut){return U===1?xe[ut]:xe.readUInt16BE(ut*U)}let qe;if(R){let xe=-1;for(qe=v;qe<$;qe++)if(Pt(l,qe)===Pt(f,xe===-1?0:qe-xe)){if(xe===-1&&(xe=qe),qe-xe+1===Le)return xe*U}else xe!==-1&&(qe-=qe-xe),xe=-1}else for(v+Le>$&&(v=$-Le),qe=v;qe>=0;qe--){let xe=!0;for(let ut=0;ut<Le;ut++)if(Pt(l,qe+ut)!==Pt(f,ut)){xe=!1;break}if(xe)return qe}return-1}u.prototype.includes=function(l,f,v){return this.indexOf(l,f,v)!==-1},u.prototype.indexOf=function(l,f,v){return Qe(this,l,f,v,!0)},u.prototype.lastIndexOf=function(l,f,v){return Qe(this,l,f,v,!1)};function V(l,f,v,C){v=Number(v)||0;const R=l.length-v;C?(C=Number(C),C>R&&(C=R)):C=R;const U=f.length;C>U/2&&(C=U/2);let $;for($=0;$<C;++$){const Le=parseInt(f.substr($*2,2),16);if(ym(Le))return $;l[v+$]=Le}return $}function I(l,f,v,C){return nu(vm(f,l.length-v),l,v,C)}function P(l,f,v,C){return nu(Rx(f),l,v,C)}function K(l,f,v,C){return nu(bE(f),l,v,C)}function Se(l,f,v,C){return nu(Px(f,l.length-v),l,v,C)}u.prototype.write=function(l,f,v,C){if(f===void 0)C="utf8",v=this.length,f=0;else if(v===void 0&&typeof f=="string")C=f,v=this.length,f=0;else if(isFinite(f))f=f>>>0,isFinite(v)?(v=v>>>0,C===void 0&&(C="utf8")):(C=v,v=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const R=this.length-f;if((v===void 0||v>R)&&(v=R),l.length>0&&(v<0||f<0)||f>this.length)throw new RangeError("Attempt to write outside buffer bounds");C||(C="utf8");let U=!1;for(;;)switch(C){case"hex":return V(this,l,f,v);case"utf8":case"utf-8":return I(this,l,f,v);case"ascii":case"latin1":case"binary":return P(this,l,f,v);case"base64":return K(this,l,f,v);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Se(this,l,f,v);default:if(U)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function st(l,f,v){return f===0&&v===l.length?e.fromByteArray(l):e.fromByteArray(l.slice(f,v))}function q(l,f,v){v=Math.min(l.length,v);const C=[];let R=f;for(;R<v;){const U=l[R];let $=null,Le=U>239?4:U>223?3:U>191?2:1;if(R+Le<=v){let Pt,qe,xe,ut;switch(Le){case 1:U<128&&($=U);break;case 2:Pt=l[R+1],(Pt&192)===128&&(ut=(U&31)<<6|Pt&63,ut>127&&($=ut));break;case 3:Pt=l[R+1],qe=l[R+2],(Pt&192)===128&&(qe&192)===128&&(ut=(U&15)<<12|(Pt&63)<<6|qe&63,ut>2047&&(ut<55296||ut>57343)&&($=ut));break;case 4:Pt=l[R+1],qe=l[R+2],xe=l[R+3],(Pt&192)===128&&(qe&192)===128&&(xe&192)===128&&(ut=(U&15)<<18|(Pt&63)<<12|(qe&63)<<6|xe&63,ut>65535&&ut<1114112&&($=ut))}}$===null?($=65533,Le=1):$>65535&&($-=65536,C.push($>>>10&1023|55296),$=56320|$&1023),C.push($),R+=Le}return rt(C)}const N=4096;function rt(l){const f=l.length;if(f<=N)return String.fromCharCode.apply(String,l);let v="",C=0;for(;C<f;)v+=String.fromCharCode.apply(String,l.slice(C,C+=N));return v}function zn(l,f,v){let C="";v=Math.min(l.length,v);for(let R=f;R<v;++R)C+=String.fromCharCode(l[R]&127);return C}function Ir(l,f,v){let C="";v=Math.min(l.length,v);for(let R=f;R<v;++R)C+=String.fromCharCode(l[R]);return C}function Cr(l,f,v){const C=l.length;(!f||f<0)&&(f=0),(!v||v<0||v>C)&&(v=C);let R="";for(let U=f;U<v;++U)R+=Ax[l[U]];return R}function Rr(l,f,v){const C=l.slice(f,v);let R="";for(let U=0;U<C.length-1;U+=2)R+=String.fromCharCode(C[U]+C[U+1]*256);return R}u.prototype.slice=function(l,f){const v=this.length;l=~~l,f=f===void 0?v:~~f,l<0?(l+=v,l<0&&(l=0)):l>v&&(l=v),f<0?(f+=v,f<0&&(f=0)):f>v&&(f=v),f<l&&(f=l);const C=this.subarray(l,f);return Object.setPrototypeOf(C,u.prototype),C};function He(l,f,v){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+f>v)throw new RangeError("Trying to access beyond buffer length")}u.prototype.readUintLE=u.prototype.readUIntLE=function(l,f,v){l=l>>>0,f=f>>>0,v||He(l,f,this.length);let C=this[l],R=1,U=0;for(;++U<f&&(R*=256);)C+=this[l+U]*R;return C},u.prototype.readUintBE=u.prototype.readUIntBE=function(l,f,v){l=l>>>0,f=f>>>0,v||He(l,f,this.length);let C=this[l+--f],R=1;for(;f>0&&(R*=256);)C+=this[l+--f]*R;return C},u.prototype.readUint8=u.prototype.readUInt8=function(l,f){return l=l>>>0,f||He(l,1,this.length),this[l]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(l,f){return l=l>>>0,f||He(l,2,this.length),this[l]|this[l+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(l,f){return l=l>>>0,f||He(l,2,this.length),this[l]<<8|this[l+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(l,f){return l=l>>>0,f||He(l,4,this.length),(this[l]|this[l+1]<<8|this[l+2]<<16)+this[l+3]*16777216},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(l,f){return l=l>>>0,f||He(l,4,this.length),this[l]*16777216+(this[l+1]<<16|this[l+2]<<8|this[l+3])},u.prototype.readBigUInt64LE=Rs(function(l){l=l>>>0,ve(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=f+this[++l]*Ae(2,8)+this[++l]*Ae(2,16)+this[++l]*Ae(2,24),R=this[++l]+this[++l]*Ae(2,8)+this[++l]*Ae(2,16)+v*Ae(2,24);return BigInt(C)+(BigInt(R)<<BigInt(32))}),u.prototype.readBigUInt64BE=Rs(function(l){l=l>>>0,ve(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=f*Ae(2,24)+this[++l]*Ae(2,16)+this[++l]*Ae(2,8)+this[++l],R=this[++l]*Ae(2,24)+this[++l]*Ae(2,16)+this[++l]*Ae(2,8)+v;return(BigInt(C)<<BigInt(32))+BigInt(R)}),u.prototype.readIntLE=function(l,f,v){l=l>>>0,f=f>>>0,v||He(l,f,this.length);let C=this[l],R=1,U=0;for(;++U<f&&(R*=256);)C+=this[l+U]*R;return R*=128,C>=R&&(C-=Math.pow(2,8*f)),C},u.prototype.readIntBE=function(l,f,v){l=l>>>0,f=f>>>0,v||He(l,f,this.length);let C=f,R=1,U=this[l+--C];for(;C>0&&(R*=256);)U+=this[l+--C]*R;return R*=128,U>=R&&(U-=Math.pow(2,8*f)),U},u.prototype.readInt8=function(l,f){return l=l>>>0,f||He(l,1,this.length),this[l]&128?(255-this[l]+1)*-1:this[l]},u.prototype.readInt16LE=function(l,f){l=l>>>0,f||He(l,2,this.length);const v=this[l]|this[l+1]<<8;return v&32768?v|4294901760:v},u.prototype.readInt16BE=function(l,f){l=l>>>0,f||He(l,2,this.length);const v=this[l+1]|this[l]<<8;return v&32768?v|4294901760:v},u.prototype.readInt32LE=function(l,f){return l=l>>>0,f||He(l,4,this.length),this[l]|this[l+1]<<8|this[l+2]<<16|this[l+3]<<24},u.prototype.readInt32BE=function(l,f){return l=l>>>0,f||He(l,4,this.length),this[l]<<24|this[l+1]<<16|this[l+2]<<8|this[l+3]},u.prototype.readBigInt64LE=Rs(function(l){l=l>>>0,ve(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=this[l+4]+this[l+5]*Ae(2,8)+this[l+6]*Ae(2,16)+(v<<24);return(BigInt(C)<<BigInt(32))+BigInt(f+this[++l]*Ae(2,8)+this[++l]*Ae(2,16)+this[++l]*Ae(2,24))}),u.prototype.readBigInt64BE=Rs(function(l){l=l>>>0,ve(l,"offset");const f=this[l],v=this[l+7];(f===void 0||v===void 0)&&pe(l,this.length-8);const C=(f<<24)+this[++l]*Ae(2,16)+this[++l]*Ae(2,8)+this[++l];return(BigInt(C)<<BigInt(32))+BigInt(this[++l]*Ae(2,24)+this[++l]*Ae(2,16)+this[++l]*Ae(2,8)+v)}),u.prototype.readFloatLE=function(l,f){return l=l>>>0,f||He(l,4,this.length),n.read(this,l,!0,23,4)},u.prototype.readFloatBE=function(l,f){return l=l>>>0,f||He(l,4,this.length),n.read(this,l,!1,23,4)},u.prototype.readDoubleLE=function(l,f){return l=l>>>0,f||He(l,8,this.length),n.read(this,l,!0,52,8)},u.prototype.readDoubleBE=function(l,f){return l=l>>>0,f||He(l,8,this.length),n.read(this,l,!1,52,8)};function lt(l,f,v,C,R,U){if(!u.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(f>R||f<U)throw new RangeError('"value" argument is out of bounds');if(v+C>l.length)throw new RangeError("Index out of range")}u.prototype.writeUintLE=u.prototype.writeUIntLE=function(l,f,v,C){if(l=+l,f=f>>>0,v=v>>>0,!C){const $=Math.pow(2,8*v)-1;lt(this,l,f,v,$,0)}let R=1,U=0;for(this[f]=l&255;++U<v&&(R*=256);)this[f+U]=l/R&255;return f+v},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(l,f,v,C){if(l=+l,f=f>>>0,v=v>>>0,!C){const $=Math.pow(2,8*v)-1;lt(this,l,f,v,$,0)}let R=v-1,U=1;for(this[f+R]=l&255;--R>=0&&(U*=256);)this[f+R]=l/U&255;return f+v},u.prototype.writeUint8=u.prototype.writeUInt8=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,1,255,0),this[f]=l&255,f+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,2,65535,0),this[f]=l&255,this[f+1]=l>>>8,f+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,2,65535,0),this[f]=l>>>8,this[f+1]=l&255,f+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,4,4294967295,0),this[f+3]=l>>>24,this[f+2]=l>>>16,this[f+1]=l>>>8,this[f]=l&255,f+4},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,4,4294967295,0),this[f]=l>>>24,this[f+1]=l>>>16,this[f+2]=l>>>8,this[f+3]=l&255,f+4};function Ts(l,f,v,C,R){Cs(f,C,R,l,v,7);let U=Number(f&BigInt(4294967295));l[v++]=U,U=U>>8,l[v++]=U,U=U>>8,l[v++]=U,U=U>>8,l[v++]=U;let $=Number(f>>BigInt(32)&BigInt(4294967295));return l[v++]=$,$=$>>8,l[v++]=$,$=$>>8,l[v++]=$,$=$>>8,l[v++]=$,v}function bs(l,f,v,C,R){Cs(f,C,R,l,v,7);let U=Number(f&BigInt(4294967295));l[v+7]=U,U=U>>8,l[v+6]=U,U=U>>8,l[v+5]=U,U=U>>8,l[v+4]=U;let $=Number(f>>BigInt(32)&BigInt(4294967295));return l[v+3]=$,$=$>>8,l[v+2]=$,$=$>>8,l[v+1]=$,$=$>>8,l[v]=$,v+8}u.prototype.writeBigUInt64LE=Rs(function(l,f=0){return Ts(this,l,f,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeBigUInt64BE=Rs(function(l,f=0){return bs(this,l,f,BigInt(0),BigInt("0xffffffffffffffff"))}),u.prototype.writeIntLE=function(l,f,v,C){if(l=+l,f=f>>>0,!C){const Le=Math.pow(2,8*v-1);lt(this,l,f,v,Le-1,-Le)}let R=0,U=1,$=0;for(this[f]=l&255;++R<v&&(U*=256);)l<0&&$===0&&this[f+R-1]!==0&&($=1),this[f+R]=(l/U>>0)-$&255;return f+v},u.prototype.writeIntBE=function(l,f,v,C){if(l=+l,f=f>>>0,!C){const Le=Math.pow(2,8*v-1);lt(this,l,f,v,Le-1,-Le)}let R=v-1,U=1,$=0;for(this[f+R]=l&255;--R>=0&&(U*=256);)l<0&&$===0&&this[f+R+1]!==0&&($=1),this[f+R]=(l/U>>0)-$&255;return f+v},u.prototype.writeInt8=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,1,127,-128),l<0&&(l=255+l+1),this[f]=l&255,f+1},u.prototype.writeInt16LE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,2,32767,-32768),this[f]=l&255,this[f+1]=l>>>8,f+2},u.prototype.writeInt16BE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,2,32767,-32768),this[f]=l>>>8,this[f+1]=l&255,f+2},u.prototype.writeInt32LE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,4,2147483647,-2147483648),this[f]=l&255,this[f+1]=l>>>8,this[f+2]=l>>>16,this[f+3]=l>>>24,f+4},u.prototype.writeInt32BE=function(l,f,v){return l=+l,f=f>>>0,v||lt(this,l,f,4,2147483647,-2147483648),l<0&&(l=4294967295+l+1),this[f]=l>>>24,this[f+1]=l>>>16,this[f+2]=l>>>8,this[f+3]=l&255,f+4},u.prototype.writeBigInt64LE=Rs(function(l,f=0){return Ts(this,l,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),u.prototype.writeBigInt64BE=Rs(function(l,f=0){return bs(this,l,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function ks(l,f,v,C,R,U){if(v+C>l.length)throw new RangeError("Index out of range");if(v<0)throw new RangeError("Index out of range")}function ws(l,f,v,C,R){return f=+f,v=v>>>0,R||ks(l,f,v,4),n.write(l,f,v,C,23,4),v+4}u.prototype.writeFloatLE=function(l,f,v){return ws(this,l,f,!0,v)},u.prototype.writeFloatBE=function(l,f,v){return ws(this,l,f,!1,v)};function _s(l,f,v,C,R){return f=+f,v=v>>>0,R||ks(l,f,v,8),n.write(l,f,v,C,52,8),v+8}u.prototype.writeDoubleLE=function(l,f,v){return _s(this,l,f,!0,v)},u.prototype.writeDoubleBE=function(l,f,v){return _s(this,l,f,!1,v)},u.prototype.copy=function(l,f,v,C){if(!u.isBuffer(l))throw new TypeError("argument should be a Buffer");if(v||(v=0),!C&&C!==0&&(C=this.length),f>=l.length&&(f=l.length),f||(f=0),C>0&&C<v&&(C=v),C===v||l.length===0||this.length===0)return 0;if(f<0)throw new RangeError("targetStart out of bounds");if(v<0||v>=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");C>this.length&&(C=this.length),l.length-f<C-v&&(C=l.length-f+v);const R=C-v;return this===l&&typeof r.prototype.copyWithin=="function"?this.copyWithin(f,v,C):r.prototype.set.call(l,this.subarray(v,C),f),R},u.prototype.fill=function(l,f,v,C){if(typeof l=="string"){if(typeof f=="string"?(C=f,f=0,v=this.length):typeof v=="string"&&(C=v,v=this.length),C!==void 0&&typeof C!="string")throw new TypeError("encoding must be a string");if(typeof C=="string"&&!u.isEncoding(C))throw new TypeError("Unknown encoding: "+C);if(l.length===1){const U=l.charCodeAt(0);(C==="utf8"&&U<128||C==="latin1")&&(l=U)}}else typeof l=="number"?l=l&255:typeof l=="boolean"&&(l=Number(l));if(f<0||this.length<f||this.length<v)throw new RangeError("Out of range index");if(v<=f)return this;f=f>>>0,v=v===void 0?this.length:v>>>0,l||(l=0);let R;if(typeof l=="number")for(R=f;R<v;++R)this[R]=l;else{const U=u.isBuffer(l)?l:u.from(l,C),$=U.length;if($===0)throw new TypeError('The value "'+l+'" is invalid for argument "value"');for(R=0;R<v-f;++R)this[R+f]=U[R%$]}return this};const Cn={};function Di(l,f,v){Cn[l]=class extends v{constructor(){super(),Object.defineProperty(this,"message",{value:f.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(C){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:C,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}Di("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Di("ERR_INVALID_ARG_TYPE",function(l,f){return`The "${l}" argument must be of type number. Received type ${typeof f}`},TypeError),Di("ERR_OUT_OF_RANGE",function(l,f,v){let C=`The value of "${l}" is out of range.`,R=v;return Number.isInteger(v)&&Math.abs(v)>Ae(2,32)?R=Is(String(v)):typeof v=="bigint"&&(R=String(v),(v>Ae(BigInt(2),BigInt(32))||v<-Ae(BigInt(2),BigInt(32)))&&(R=Is(R)),R+="n"),C+=` It must be ${f}. Received ${R}`,C},RangeError);function Is(l){let f="",v=l.length;const C=l[0]==="-"?1:0;for(;v>=C+4;v-=3)f=`_${l.slice(v-3,v)}${f}`;return`${l.slice(0,v)}${f}`}function Pr(l,f,v){ve(f,"offset"),(l[f]===void 0||l[f+v]===void 0)&&pe(f,l.length-(v+1))}function Cs(l,f,v,C,R,U){if(l>v||l<f){const $=typeof f=="bigint"?"n":"";let Le;throw U>3?f===0||f===BigInt(0)?Le=`>= 0${$} and < 2${$} ** ${(U+1)*8}${$}`:Le=`>= -(2${$} ** ${(U+1)*8-1}${$}) and < 2 ** ${(U+1)*8-1}${$}`:Le=`>= ${f}${$} and <= ${v}${$}`,new Cn.ERR_OUT_OF_RANGE("value",Le,l)}Pr(C,R,U)}function ve(l,f){if(typeof l!="number")throw new Cn.ERR_INVALID_ARG_TYPE(f,"number",l)}function pe(l,f,v){throw Math.floor(l)!==l?(ve(l,v),new Cn.ERR_OUT_OF_RANGE(v||"offset","an integer",l)):f<0?new Cn.ERR_BUFFER_OUT_OF_BOUNDS:new Cn.ERR_OUT_OF_RANGE(v||"offset",`>= ${v?1:0} and <= ${f}`,l)}const Ic=/[^+/0-9A-Za-z-_]/g;function Cx(l){if(l=l.split("=")[0],l=l.trim().replace(Ic,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function vm(l,f){f=f||1/0;let v;const C=l.length;let R=null;const U=[];for(let $=0;$<C;++$){if(v=l.charCodeAt($),v>55295&&v<57344){if(!R){if(v>56319){(f-=3)>-1&&U.push(239,191,189);continue}else if($+1===C){(f-=3)>-1&&U.push(239,191,189);continue}R=v;continue}if(v<56320){(f-=3)>-1&&U.push(239,191,189),R=v;continue}v=(R-55296<<10|v-56320)+65536}else R&&(f-=3)>-1&&U.push(239,191,189);if(R=null,v<128){if((f-=1)<0)break;U.push(v)}else if(v<2048){if((f-=2)<0)break;U.push(v>>6|192,v&63|128)}else if(v<65536){if((f-=3)<0)break;U.push(v>>12|224,v>>6&63|128,v&63|128)}else if(v<1114112){if((f-=4)<0)break;U.push(v>>18|240,v>>12&63|128,v>>6&63|128,v&63|128)}else throw new Error("Invalid code point")}return U}function Rx(l){const f=[];for(let v=0;v<l.length;++v)f.push(l.charCodeAt(v)&255);return f}function Px(l,f){let v,C,R;const U=[];for(let $=0;$<l.length&&!((f-=2)<0);++$)v=l.charCodeAt($),C=v>>8,R=v%256,U.push(R),U.push(C);return U}function bE(l){return e.toByteArray(Cx(l))}function nu(l,f,v,C){let R;for(R=0;R<C&&!(R+v>=f.length||R>=l.length);++R)f[R+v]=l[R];return R}function ui(l,f){return l instanceof f||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===f.name}function ym(l){return l!==l}const Ax=function(){const l="0123456789abcdef",f=new Array(256);for(let v=0;v<16;++v){const C=v*16;for(let R=0;R<16;++R)f[C+R]=l[v]+l[R]}return f}();function Rs(l){return typeof BigInt=="undefined"?Mx:l}function Mx(){throw new Error("BigInt not supported")}})(pt);const FT=pt.Buffer;pt.Blob,pt.BlobOptions,pt.Buffer,pt.File,pt.FileOptions,pt.INSPECT_MAX_BYTES,pt.SlowBuffer,pt.TranscodeEncoding,pt.atob,pt.btoa,pt.constants,pt.isAscii,pt.isUtf8,pt.kMaxLength,pt.kStringMaxLength,pt.resolveObjectURL,pt.transcode;var Af=ht;function Lr(t,e,n,i,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),i&&(this.request=i),s&&(this.response=s)}Af.inherits(Lr,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var Mf=Lr.prototype,Of={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(function(t){Of[t]={value:t}}),Object.defineProperties(Lr,Of),Object.defineProperty(Mf,"isAxiosError",{value:!0}),Lr.from=function(t,e,n,i,s,r){var a=Object.create(Mf);return Af.toFlatObject(t,a,function(c){return c!==Error.prototype}),Lr.call(a,t.message,e,n,i,s),a.cause=t,a.name=t.name,r&&Object.assign(a,r),a};var Os=Lr,Pu={},jT={get exports(){return Pu},set exports(t){Pu=t}},WT=typeof self=="object"?self.FormData:window.FormData;(function(t){t.exports=WT})(jT);var Me=ht,HT=Os,qT=Pu;function Au(t){return Me.isPlainObject(t)||Me.isArray(t)}function Df(t){return Me.endsWith(t,"[]")?t.slice(0,-2):t}function Nf(t,e,n){return t?t.concat(e).map(function(i,s){return i=Df(i),!n&&s?"["+i+"]":i}).join(n?".":""):e}function GT(t){return Me.isArray(t)&&!t.some(Au)}var JT=Me.toFlatObject(Me,{},null,function(t){return/^is[A-Z]/.test(t)});function $T(t){return t&&Me.isFunction(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator]}function KT(t,e,n){if(!Me.isObject(t))throw new TypeError("target must be an object");e=e||new(qT||FormData),n=Me.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,M){return!Me.isUndefined(M[w])});var i=n.metaTokens,s=n.visitor||u,r=n.dots,a=n.indexes,c=n.Blob||typeof Blob!="undefined"&&Blob,d=c&&$T(e);if(!Me.isFunction(s))throw new TypeError("visitor must be a function");function h(w){if(w===null)return"";if(Me.isDate(w))return w.toISOString();if(!d&&Me.isBlob(w))throw new HT("Blob is not supported. Use a Buffer instead.");return Me.isArrayBuffer(w)||Me.isTypedArray(w)?d&&typeof Blob=="function"?new Blob([w]):FT.from(w):w}function u(w,M,D){var F=w;if(w&&!D&&typeof w=="object"){if(Me.endsWith(M,"{}"))M=i?M:M.slice(0,-2),w=JSON.stringify(w);else if(Me.isArray(w)&&GT(w)||Me.isFileList(w)||Me.endsWith(M,"[]")&&(F=Me.toArray(w)))return M=Df(M),F.forEach(function(Y,X){!Me.isUndefined(Y)&&e.append(a===!0?Nf([M],X,r):a===null?M:M+"[]",h(Y))}),!1}return Au(w)?!0:(e.append(Nf(D,M,r),h(w)),!1)}var g=[],E=Object.assign(JT,{defaultVisitor:u,convertValue:h,isVisitable:Au});function b(w,M){if(!Me.isUndefined(w)){if(g.indexOf(w)!==-1)throw Error("Circular reference detected in "+M.join("."));g.push(w),Me.forEach(w,function(D,F){var Y=!Me.isUndefined(D)&&s.call(e,D,Me.isString(F)?F.trim():F,M,E);Y===!0&&b(D,M?M.concat(F):[F])}),g.pop()}}if(!Me.isObject(t))throw new TypeError("data must be an object");return b(t),e}var ed=KT,zT=ed;function Lf(t){var e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'\(\)~]|%20|%00/g,function(n){return e[n]})}function xf(t,e){this._pairs=[],t&&zT(t,this,e)}var Vf=xf.prototype;Vf.append=function(t,e){this._pairs.push([t,e])},Vf.toString=function(t){var e=t?function(n){return t.call(this,n,Lf)}:Lf;return this._pairs.map(function(n){return e(n[0])+"="+e(n[1])},"").join("&")};var Uf=xf,YT=ht,QT=Uf;function XT(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Bf=function(t,e,n){if(!e)return t;var i=t.indexOf("#");i!==-1&&(t=t.slice(0,i));var s=n&&n.encode||XT,r=n&&n.serialize,a;return r?a=r(e,n):a=YT.isURLSearchParams(e)?e.toString():new QT(e,n).toString(s),a&&(t+=(t.indexOf("?")===-1?"?":"&")+a),t},ZT=ht;function xa(){this.handlers=[]}xa.prototype.use=function(t,e,n){return this.handlers.push({fulfilled:t,rejected:e,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1},xa.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},xa.prototype.clear=function(){this.handlers&&(this.handlers=[])},xa.prototype.forEach=function(t){ZT.forEach(this.handlers,function(e){e!==null&&t(e)})};var eb=xa,tb=ht,Ff=function(t,e){tb.forEach(t,function(n,i){i!==e&&i.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[i])})},jf={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Va={},nb={get exports(){return Va},set exports(t){Va=t}},ib=Uf,sb=typeof URLSearchParams!="undefined"?URLSearchParams:ib,rb=FormData,ab={isBrowser:!0,classes:{URLSearchParams:sb,FormData:rb,Blob},protocols:["http","https","file","blob","url","data"]};(function(t){t.exports=ab})(nb);var ob=ht,cb=ed,Wf=Va,db=function(t,e){return cb(t,new Wf.classes.URLSearchParams,Object.assign({visitor:function(n,i,s,r){return Wf.isNode&&ob.isBuffer(n)?(this.append(i,n.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))},Vi=ht;function lb(t){return Vi.matchAll(/\w+|\[(\w*)]/g,t).map(function(e){return e[0]==="[]"?"":e[1]||e[0]})}function ub(t){var e={},n=Object.keys(t),i,s=n.length,r;for(i=0;i<s;i++)r=n[i],e[r]=t[r];return e}function hb(t){function e(i,s,r,a){var c=i[a++],d=Number.isFinite(+c),h=a>=i.length;if(c=!c&&Vi.isArray(r)?r.length:c,h)return Vi.hasOwnProperty(r,c)?r[c]=[r[c],s]:r[c]=s,!d;(!r[c]||!Vi.isObject(r[c]))&&(r[c]=[]);var u=e(i,s,r[c],a);return u&&Vi.isArray(r[c])&&(r[c]=ub(r[c])),!d}if(Vi.isFormData(t)&&Vi.isFunction(t.entries)){var n={};return Vi.forEachEntry(t,function(i,s){e(lb(i),s,n,0)}),n}return null}var Hf=hb,Mu,qf;function pb(){if(qf)return Mu;qf=1;var t=Os;return Mu=function(e,n,i){var s=i.config.validateStatus;!i.status||!s||s(i.status)?e(i):n(new t("Request failed with status code "+i.status,[t.ERR_BAD_REQUEST,t.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i))},Mu}var Ou,Gf;function mb(){if(Gf)return Ou;Gf=1;var t=ht;return Ou=t.isStandardBrowserEnv()?function(){return{write:function(e,n,i,s,r,a){var c=[];c.push(e+"="+encodeURIComponent(n)),t.isNumber(i)&&c.push("expires="+new Date(i).toGMTString()),t.isString(s)&&c.push("path="+s),t.isString(r)&&c.push("domain="+r),a===!0&&c.push("secure"),document.cookie=c.join("; ")},read:function(e){var n=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return n?decodeURIComponent(n[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),Ou}var fb=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)},gb=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t},vb=fb,yb=gb,Jf=function(t,e){return t&&!vb(e)?yb(t,e):e},Du,$f;function Eb(){if($f)return Du;$f=1;var t=ht,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 Du=function(n){var i={},s,r,a;return n&&t.forEach(n.split(`
18
- `),function(c){if(a=c.indexOf(":"),s=t.trim(c.slice(0,a)).toLowerCase(),r=t.trim(c.slice(a+1)),s){if(i[s]&&e.indexOf(s)>=0)return;s==="set-cookie"?i[s]=(i[s]?i[s]:[]).concat([r]):i[s]=i[s]?i[s]+", "+r:r}}),i},Du}var Nu,Kf;function Sb(){if(Kf)return Nu;Kf=1;var t=ht;return Nu=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a"),i;function s(r){var a=r;return e&&(n.setAttribute("href",a),a=n.href),n.setAttribute("href",a),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return i=s(window.location.href),function(r){var a=t.isString(r)?s(r):r;return a.protocol===i.protocol&&a.host===i.host}}():function(){return function(){return!0}}(),Nu}var Lu,zf;function td(){if(zf)return Lu;zf=1;var t=Os,e=ht;function n(i,s,r){t.call(this,i==null?"canceled":i,t.ERR_CANCELED,s,r),this.name="CanceledError"}return e.inherits(n,t,{__CANCEL__:!0}),Lu=n,Lu}var Yf,Qf;function Tb(){return Qf||(Qf=1,Yf=function(t){var e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}),Yf}var xu,Xf;function bb(){if(Xf)return xu;Xf=1;var t=ht,e=pb(),n=mb(),i=Bf,s=Jf,r=Eb(),a=Sb(),c=jf,d=Os,h=td(),u=Tb(),g=Va;return xu=function(E){return new Promise(function(b,w){var M=E.data,D=E.headers,F=E.responseType,Y=E.withXSRFToken,X;function A(){E.cancelToken&&E.cancelToken.unsubscribe(X),E.signal&&E.signal.removeEventListener("abort",X)}t.isFormData(M)&&t.isStandardBrowserEnv()&&delete D["Content-Type"];var J=new XMLHttpRequest;if(E.auth){var me=E.auth.username||"",Re=E.auth.password?unescape(encodeURIComponent(E.auth.password)):"";D.Authorization="Basic "+btoa(me+":"+Re)}var fe=s(E.baseURL,E.url);J.open(E.method.toUpperCase(),i(fe,E.params,E.paramsSerializer),!0),J.timeout=E.timeout;function Qe(){if(J){var I="getAllResponseHeaders"in J?r(J.getAllResponseHeaders()):null,P=!F||F==="text"||F==="json"?J.responseText:J.response,K={data:P,status:J.status,statusText:J.statusText,headers:I,config:E,request:J};e(function(Se){b(Se),A()},function(Se){w(Se),A()},K),J=null}}if("onloadend"in J?J.onloadend=Qe:J.onreadystatechange=function(){!J||J.readyState!==4||J.status===0&&!(J.responseURL&&J.responseURL.indexOf("file:")===0)||setTimeout(Qe)},J.onabort=function(){J&&(w(new d("Request aborted",d.ECONNABORTED,E,J)),J=null)},J.onerror=function(){w(new d("Network Error",d.ERR_NETWORK,E,J)),J=null},J.ontimeout=function(){var I=E.timeout?"timeout of "+E.timeout+"ms exceeded":"timeout exceeded",P=E.transitional||c;E.timeoutErrorMessage&&(I=E.timeoutErrorMessage),w(new d(I,P.clarifyTimeoutError?d.ETIMEDOUT:d.ECONNABORTED,E,J)),J=null},t.isStandardBrowserEnv()&&(Y&&t.isFunction(Y)&&(Y=Y(E)),Y||Y!==!1&&a(fe))){var vt=E.xsrfHeaderName&&E.xsrfCookieName&&n.read(E.xsrfCookieName);vt&&(D[E.xsrfHeaderName]=vt)}"setRequestHeader"in J&&t.forEach(D,function(I,P){typeof M=="undefined"&&P.toLowerCase()==="content-type"?delete D[P]:J.setRequestHeader(P,I)}),t.isUndefined(E.withCredentials)||(J.withCredentials=!!E.withCredentials),F&&F!=="json"&&(J.responseType=E.responseType),typeof E.onDownloadProgress=="function"&&J.addEventListener("progress",E.onDownloadProgress),typeof E.onUploadProgress=="function"&&J.upload&&J.upload.addEventListener("progress",E.onUploadProgress),(E.cancelToken||E.signal)&&(X=function(I){J&&(w(!I||I.type?new h(null,E,J):I),J.abort(),J=null)},E.cancelToken&&E.cancelToken.subscribe(X),E.signal&&(E.signal.aborted?X():E.signal.addEventListener("abort",X))),!M&&M!==!1&&M!==0&&M!==""&&(M=null);var V=u(fe);if(V&&g.protocols.indexOf(V)===-1){w(new d("Unsupported protocol "+V+":",d.ERR_BAD_REQUEST,E));return}J.send(M)})},xu}var mt=ht,Zf=Ff,eg=Os,kb=jf,wb=ed,_b=db,tg=Va,Ib=Hf,Cb={"Content-Type":"application/x-www-form-urlencoded"};function ng(t,e){!mt.isUndefined(t)&&mt.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}function Rb(){var t;return(typeof XMLHttpRequest!="undefined"||typeof Ms!="undefined"&&Object.prototype.toString.call(Ms)==="[object process]")&&(t=bb()),t}function Pb(t,e,n){if(mt.isString(t))try{return(e||JSON.parse)(t),mt.trim(t)}catch(i){if(i.name!=="SyntaxError")throw i}return(n||JSON.stringify)(t)}var nd={transitional:kb,adapter:Rb(),transformRequest:[function(t,e){Zf(e,"Accept"),Zf(e,"Content-Type");var n=e&&e["Content-Type"]||"",i=n.indexOf("application/json")>-1,s=mt.isObject(t);s&&mt.isHTMLForm(t)&&(t=new FormData(t));var r=mt.isFormData(t);if(r)return i?JSON.stringify(Ib(t)):t;if(mt.isArrayBuffer(t)||mt.isBuffer(t)||mt.isStream(t)||mt.isFile(t)||mt.isBlob(t))return t;if(mt.isArrayBufferView(t))return t.buffer;if(mt.isURLSearchParams(t))return ng(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString();var a;if(s){if(n.indexOf("application/x-www-form-urlencoded")!==-1)return _b(t,this.formSerializer).toString();if((a=mt.isFileList(t))||n.indexOf("multipart/form-data")>-1){var c=this.env&&this.env.FormData;return wb(a?{"files[]":t}:t,c&&new c,this.formSerializer)}}return s||i?(ng(e,"application/json"),Pb(t)):t}],transformResponse:[function(t){var e=this.transitional||nd.transitional,n=e&&e.forcedJSONParsing,i=this.responseType==="json";if(t&&mt.isString(t)&&(n&&!this.responseType||i)){var s=e&&e.silentJSONParsing,r=!s&&i;try{return JSON.parse(t)}catch(a){if(r)throw a.name==="SyntaxError"?eg.from(a,eg.ERR_BAD_RESPONSE,this,null,this.response):a}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:tg.classes.FormData,Blob:tg.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};mt.forEach(["delete","get","head"],function(t){nd.headers[t]={}}),mt.forEach(["post","put","patch"],function(t){nd.headers[t]=mt.merge(Cb)});var Vu=nd,Ab=ht,Mb=Vu,Ob=function(t,e,n,i){var s=this||Mb;return Ab.forEach(i,function(r){t=r.call(s,t,e,n)}),t},ig,sg;function rg(){return sg||(sg=1,ig=function(t){return!!(t&&t.__CANCEL__)}),ig}var ag=ht,Uu=Ob,Db=rg(),Nb=Vu,Lb=td(),og=Ff;function Bu(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new Lb}var xb=function(t){Bu(t),t.headers=t.headers||{},t.data=Uu.call(t,t.data,t.headers,null,t.transformRequest),og(t.headers,"Accept"),og(t.headers,"Content-Type"),t.headers=ag.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),ag.forEach(["delete","get","head","post","put","patch","common"],function(n){delete t.headers[n]});var e=t.adapter||Nb.adapter;return e(t).then(function(n){return Bu(t),n.data=Uu.call(t,n.data,n.headers,n.status,t.transformResponse),n},function(n){return Db(n)||(Bu(t),n&&n.response&&(n.response.data=Uu.call(t,n.response.data,n.response.headers,n.response.status,t.transformResponse))),Promise.reject(n)})},Ut=ht,cg=function(t,e){e=e||{};var n={};function i(h,u){return Ut.isPlainObject(h)&&Ut.isPlainObject(u)?Ut.merge(h,u):Ut.isEmptyObject(u)?Ut.merge({},h):Ut.isPlainObject(u)?Ut.merge({},u):Ut.isArray(u)?u.slice():u}function s(h){if(Ut.isUndefined(e[h])){if(!Ut.isUndefined(t[h]))return i(void 0,t[h])}else return i(t[h],e[h])}function r(h){if(!Ut.isUndefined(e[h]))return i(void 0,e[h])}function a(h){if(Ut.isUndefined(e[h])){if(!Ut.isUndefined(t[h]))return i(void 0,t[h])}else return i(void 0,e[h])}function c(h){if(h in e)return i(t[h],e[h]);if(h in t)return i(void 0,t[h])}var d={url:r,method:r,data:r,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:c};return Ut.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var u=d[h]||s,g=u(h);Ut.isUndefined(g)&&u!==c||(n[h]=g)}),n},dg,lg;function ug(){return lg||(lg=1,dg={version:"0.28.1"}),dg}var Vb=ug().version,Ui=Os,Fu={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){Fu[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var hg={};Fu.transitional=function(t,e,n){function i(s,r){return"[Axios v"+Vb+"] Transitional option '"+s+"'"+r+(n?". "+n:"")}return function(s,r,a){if(t===!1)throw new Ui(i(r," has been removed"+(e?" in "+e:"")),Ui.ERR_DEPRECATED);return e&&!hg[r]&&(hg[r]=!0,console.warn(i(r," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(s,r,a):!0}};function Ub(t,e,n){if(typeof t!="object")throw new Ui("options must be an object",Ui.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(t),s=i.length;s-- >0;){var r=i[s],a=e[r];if(a){var c=t[r],d=c===void 0||a(c,r,t);if(d!==!0)throw new Ui("option "+r+" must be "+d,Ui.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ui("Unknown option "+r,Ui.ERR_BAD_OPTION)}}var Bb={assertOptions:Ub,validators:Fu},ju=ht,Fb=Bf,pg=eb,mg=xb,id=cg,jb=Jf,Wu=Bb,Bi=Wu.validators;function xr(t){this.defaults=t,this.interceptors={request:new pg,response:new pg}}xr.prototype.request=function(t,e){typeof t=="string"?(e=e||{},e.url=t):e=t||{},e=id(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var n=e.transitional;n!==void 0&&Wu.assertOptions(n,{silentJSONParsing:Bi.transitional(Bi.boolean),forcedJSONParsing:Bi.transitional(Bi.boolean),clarifyTimeoutError:Bi.transitional(Bi.boolean)},!1);var i=e.paramsSerializer;i!==void 0&&Wu.assertOptions(i,{encode:Bi.function,serialize:Bi.function},!0),ju.isFunction(i)&&(e.paramsSerializer={serialize:i});var s=[],r=!0;this.interceptors.request.forEach(function(E){typeof E.runWhen=="function"&&E.runWhen(e)===!1||(r=r&&E.synchronous,s.unshift(E.fulfilled,E.rejected))});var a=[];this.interceptors.response.forEach(function(E){a.push(E.fulfilled,E.rejected)});var c;if(!r){var d=[mg,void 0];for(Array.prototype.unshift.apply(d,s),d=d.concat(a),c=Promise.resolve(e);d.length;)c=c.then(d.shift(),d.shift());return c}for(var h=e;s.length;){var u=s.shift(),g=s.shift();try{h=u(h)}catch(E){g(E);break}}try{c=mg(h)}catch(E){return Promise.reject(E)}for(;a.length;)c=c.then(a.shift(),a.shift());return c},xr.prototype.getUri=function(t){t=id(this.defaults,t);var e=jb(t.baseURL,t.url);return Fb(e,t.params,t.paramsSerializer)},ju.forEach(["delete","get","head","options"],function(t){xr.prototype[t]=function(e,n){return this.request(id(n||{},{method:t,url:e,data:(n||{}).data}))}}),ju.forEach(["post","put","patch"],function(t){function e(n){return function(i,s,r){return this.request(id(r||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}xr.prototype[t]=e(),xr.prototype[t+"Form"]=e(!0)});var Wb=xr,Hu,fg;function Hb(){if(fg)return Hu;fg=1;var t=td();function e(n){if(typeof n!="function")throw new TypeError("executor must be a function.");var i;this.promise=new Promise(function(r){i=r});var s=this;this.promise.then(function(r){if(s._listeners){for(var a=s._listeners.length;a-- >0;)s._listeners[a](r);s._listeners=null}}),this.promise.then=function(r){var a,c=new Promise(function(d){s.subscribe(d),a=d}).then(r);return c.cancel=function(){s.unsubscribe(a)},c},n(function(r,a,c){s.reason||(s.reason=new t(r,a,c),i(s.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(n){if(this.reason){n(this.reason);return}this._listeners?this._listeners.push(n):this._listeners=[n]},e.prototype.unsubscribe=function(n){if(this._listeners){var i=this._listeners.indexOf(n);i!==-1&&this._listeners.splice(i,1)}},e.source=function(){var n,i=new e(function(s){n=s});return{token:i,cancel:n}},Hu=e,Hu}var gg,vg;function qb(){return vg||(vg=1,gg=function(t){return function(e){return t.apply(null,e)}}),gg}var qu,yg;function Gb(){if(yg)return qu;yg=1;var t=ht;return qu=function(e){return t.isObject(e)&&e.isAxiosError===!0},qu}var Gu=ht,Jb=_f,sd=Wb,$b=cg,Kb=Vu,zb=Hf;function Eg(t){var e=new sd(t),n=Jb(sd.prototype.request,e);return Gu.extend(n,sd.prototype,e),Gu.extend(n,e),n.create=function(i){return Eg($b(t,i))},n}var Bt=Eg(Kb);Bt.Axios=sd,Bt.CanceledError=td(),Bt.CancelToken=Hb(),Bt.isCancel=rg(),Bt.VERSION=ug().version,Bt.toFormData=ed,Bt.AxiosError=Os,Bt.Cancel=Bt.CanceledError,Bt.all=function(t){return Promise.all(t)},Bt.spread=qb(),Bt.isAxiosError=Gb(),Bt.formToJSON=function(t){return zb(Gu.isHTMLForm(t)?new FormData(t):t)},aT.exports=Bt,Yc.default=Bt,function(t){t.exports=Yc}(rT);const Yb=wS(Su);function Qb(){this.__data__=[],this.size=0}function Ua(t,e){return t===e||t!==t&&e!==e}function rd(t,e){for(var n=t.length;n--;)if(Ua(t[n][0],e))return n;return-1}var Xb=Array.prototype,Zb=Xb.splice;function ek(t){var e=this.__data__,n=rd(e,t);if(n<0)return!1;var i=e.length-1;return n==i?e.pop():Zb.call(e,n,1),--this.size,!0}function tk(t){var e=this.__data__,n=rd(e,t);return n<0?void 0:e[n][1]}function nk(t){return rd(this.__data__,t)>-1}function ik(t,e){var n=this.__data__,i=rd(n,t);return i<0?(++this.size,n.push([t,e])):n[i][1]=e,this}function vi(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}vi.prototype.clear=Qb,vi.prototype.delete=ek,vi.prototype.get=tk,vi.prototype.has=nk,vi.prototype.set=ik;function sk(){this.__data__=new vi,this.size=0}function rk(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function ak(t){return this.__data__.get(t)}function ok(t){return this.__data__.has(t)}const ad=globalThis||void 0||self;var ck=typeof ad=="object"&&ad&&ad.Object===Object&&ad;const Sg=ck;var dk=typeof self=="object"&&self&&self.Object===Object&&self,lk=Sg||dk||Function("return this")();const Pn=lk;var uk=Pn.Symbol;const Fi=uk;var Tg=Object.prototype,hk=Tg.hasOwnProperty,pk=Tg.toString,Ba=Fi?Fi.toStringTag:void 0;function mk(t){var e=hk.call(t,Ba),n=t[Ba];try{t[Ba]=void 0;var i=!0}catch(r){}var s=pk.call(t);return i&&(e?t[Ba]=n:delete t[Ba]),s}var fk=Object.prototype,gk=fk.toString;function vk(t){return gk.call(t)}var yk="[object Null]",Ek="[object Undefined]",bg=Fi?Fi.toStringTag:void 0;function Ds(t){return t==null?t===void 0?Ek:yk:bg&&bg in Object(t)?mk(t):vk(t)}function An(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Sk="[object AsyncFunction]",Tk="[object Function]",bk="[object GeneratorFunction]",kk="[object Proxy]";function Ju(t){if(!An(t))return!1;var e=Ds(t);return e==Tk||e==bk||e==Sk||e==kk}var wk=Pn["__core-js_shared__"];const $u=wk;var kg=function(){var t=/[^.]+$/.exec($u&&$u.keys&&$u.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function _k(t){return!!kg&&kg in t}var Ik=Function.prototype,Ck=Ik.toString;function Ns(t){if(t!=null){try{return Ck.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var Rk=/[\\^$.*+?()[\]{}|]/g,Pk=/^\[object .+?Constructor\]$/,Ak=Function.prototype,Mk=Object.prototype,Ok=Ak.toString,Dk=Mk.hasOwnProperty,Nk=RegExp("^"+Ok.call(Dk).replace(Rk,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Lk(t){if(!An(t)||_k(t))return!1;var e=Ju(t)?Nk:Pk;return e.test(Ns(t))}function xk(t,e){return t==null?void 0:t[e]}function Ls(t,e){var n=xk(t,e);return Lk(n)?n:void 0}var Vk=Ls(Pn,"Map");const Fa=Vk;var Uk=Ls(Object,"create");const ja=Uk;function Bk(){this.__data__=ja?ja(null):{},this.size=0}function Fk(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var jk="__lodash_hash_undefined__",Wk=Object.prototype,Hk=Wk.hasOwnProperty;function qk(t){var e=this.__data__;if(ja){var n=e[t];return n===jk?void 0:n}return Hk.call(e,t)?e[t]:void 0}var Gk=Object.prototype,Jk=Gk.hasOwnProperty;function $k(t){var e=this.__data__;return ja?e[t]!==void 0:Jk.call(e,t)}var Kk="__lodash_hash_undefined__";function zk(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=ja&&e===void 0?Kk:e,this}function xs(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}xs.prototype.clear=Bk,xs.prototype.delete=Fk,xs.prototype.get=qk,xs.prototype.has=$k,xs.prototype.set=zk;function Yk(){this.size=0,this.__data__={hash:new xs,map:new(Fa||vi),string:new xs}}function Qk(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function od(t,e){var n=t.__data__;return Qk(e)?n[typeof e=="string"?"string":"hash"]:n.map}function Xk(t){var e=od(this,t).delete(t);return this.size-=e?1:0,e}function Zk(t){return od(this,t).get(t)}function ew(t){return od(this,t).has(t)}function tw(t,e){var n=od(this,t),i=n.size;return n.set(t,e),this.size+=n.size==i?0:1,this}function Vs(t){var e=-1,n=t==null?0:t.length;for(this.clear();++e<n;){var i=t[e];this.set(i[0],i[1])}}Vs.prototype.clear=Yk,Vs.prototype.delete=Xk,Vs.prototype.get=Zk,Vs.prototype.has=ew,Vs.prototype.set=tw;var nw=200;function iw(t,e){var n=this.__data__;if(n instanceof vi){var i=n.__data__;if(!Fa||i.length<nw-1)return i.push([t,e]),this.size=++n.size,this;n=this.__data__=new Vs(i)}return n.set(t,e),this.size=n.size,this}function ei(t){var e=this.__data__=new vi(t);this.size=e.size}ei.prototype.clear=sk,ei.prototype.delete=rk,ei.prototype.get=ak,ei.prototype.has=ok,ei.prototype.set=iw;function sw(t,e){for(var n=-1,i=t==null?0:t.length;++n<i&&e(t[n],n,t)!==!1;);return t}var rw=function(){try{var t=Ls(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const cd=rw;function Ku(t,e,n){e=="__proto__"&&cd?cd(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}var aw=Object.prototype,ow=aw.hasOwnProperty;function wg(t,e,n){var i=t[e];(!(ow.call(t,e)&&Ua(i,n))||n===void 0&&!(e in t))&&Ku(t,e,n)}function Wa(t,e,n,i){var s=!n;n||(n={});for(var r=-1,a=e.length;++r<a;){var c=e[r],d=i?i(n[c],t[c],c,n,t):void 0;d===void 0&&(d=t[c]),s?Ku(n,c,d):wg(n,c,d)}return n}function cw(t,e){for(var n=-1,i=Array(t);++n<t;)i[n]=e(n);return i}function ti(t){return t!=null&&typeof t=="object"}var dw="[object Arguments]";function _g(t){return ti(t)&&Ds(t)==dw}var Ig=Object.prototype,lw=Ig.hasOwnProperty,uw=Ig.propertyIsEnumerable,hw=_g(function(){return arguments}())?_g:function(t){return ti(t)&&lw.call(t,"callee")&&!uw.call(t,"callee")};const dd=hw;var pw=Array.isArray;const ji=pw;function mw(){return!1}var Cg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Rg=Cg&&typeof module=="object"&&module&&!module.nodeType&&module,fw=Rg&&Rg.exports===Cg,Pg=fw?Pn.Buffer:void 0,gw=Pg?Pg.isBuffer:void 0,vw=gw||mw;const Vr=vw;var yw=9007199254740991,Ew=/^(?:0|[1-9]\d*)$/;function Ag(t,e){var n=typeof t;return e=e==null?yw:e,!!e&&(n=="number"||n!="symbol"&&Ew.test(t))&&t>-1&&t%1==0&&t<e}var Sw=9007199254740991;function Mg(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Sw}var Tw="[object Arguments]",bw="[object Array]",kw="[object Boolean]",ww="[object Date]",_w="[object Error]",Iw="[object Function]",Cw="[object Map]",Rw="[object Number]",Pw="[object Object]",Aw="[object RegExp]",Mw="[object Set]",Ow="[object String]",Dw="[object WeakMap]",Nw="[object ArrayBuffer]",Lw="[object DataView]",xw="[object Float32Array]",Vw="[object Float64Array]",Uw="[object Int8Array]",Bw="[object Int16Array]",Fw="[object Int32Array]",jw="[object Uint8Array]",Ww="[object Uint8ClampedArray]",Hw="[object Uint16Array]",qw="[object Uint32Array]",Ve={};Ve[xw]=Ve[Vw]=Ve[Uw]=Ve[Bw]=Ve[Fw]=Ve[jw]=Ve[Ww]=Ve[Hw]=Ve[qw]=!0,Ve[Tw]=Ve[bw]=Ve[Nw]=Ve[kw]=Ve[Lw]=Ve[ww]=Ve[_w]=Ve[Iw]=Ve[Cw]=Ve[Rw]=Ve[Pw]=Ve[Aw]=Ve[Mw]=Ve[Ow]=Ve[Dw]=!1;function Gw(t){return ti(t)&&Mg(t.length)&&!!Ve[Ds(t)]}function zu(t){return function(e){return t(e)}}var Og=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ha=Og&&typeof module=="object"&&module&&!module.nodeType&&module,Jw=Ha&&Ha.exports===Og,Yu=Jw&&Sg.process,$w=function(){try{var t=Ha&&Ha.require&&Ha.require("util").types;return t||Yu&&Yu.binding&&Yu.binding("util")}catch(e){}}();const Ur=$w;var Dg=Ur&&Ur.isTypedArray,Kw=Dg?zu(Dg):Gw;const ld=Kw;var zw=Object.prototype,Yw=zw.hasOwnProperty;function Ng(t,e){var n=ji(t),i=!n&&dd(t),s=!n&&!i&&Vr(t),r=!n&&!i&&!s&&ld(t),a=n||i||s||r,c=a?cw(t.length,String):[],d=c.length;for(var h in t)(e||Yw.call(t,h))&&!(a&&(h=="length"||s&&(h=="offset"||h=="parent")||r&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||Ag(h,d)))&&c.push(h);return c}var Qw=Object.prototype;function ud(t){var e=t&&t.constructor,n=typeof e=="function"&&e.prototype||Qw;return t===n}function Lg(t,e){return function(n){return t(e(n))}}var Xw=Lg(Object.keys,Object);const Zw=Xw;var e_=Object.prototype,t_=e_.hasOwnProperty;function xg(t){if(!ud(t))return Zw(t);var e=[];for(var n in Object(t))t_.call(t,n)&&n!="constructor"&&e.push(n);return e}function qa(t){return t!=null&&Mg(t.length)&&!Ju(t)}function Qu(t){return qa(t)?Ng(t):xg(t)}function n_(t,e){return t&&Wa(e,Qu(e),t)}function i_(t){var e=[];if(t!=null)for(var n in Object(t))e.push(n);return e}var s_=Object.prototype,r_=s_.hasOwnProperty;function a_(t){if(!An(t))return i_(t);var e=ud(t),n=[];for(var i in t)i=="constructor"&&(e||!r_.call(t,i))||n.push(i);return n}function Ga(t){return qa(t)?Ng(t,!0):a_(t)}function o_(t,e){return t&&Wa(e,Ga(e),t)}var Vg=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ug=Vg&&typeof module=="object"&&module&&!module.nodeType&&module,c_=Ug&&Ug.exports===Vg,Bg=c_?Pn.Buffer:void 0,Fg=Bg?Bg.allocUnsafe:void 0;function jg(t,e){if(e)return t.slice();var n=t.length,i=Fg?Fg(n):new t.constructor(n);return t.copy(i),i}function Wg(t,e){var n=-1,i=t.length;for(e||(e=Array(i));++n<i;)e[n]=t[n];return e}function d_(t,e){for(var n=-1,i=t==null?0:t.length,s=0,r=[];++n<i;){var a=t[n];e(a,n,t)&&(r[s++]=a)}return r}function Hg(){return[]}var l_=Object.prototype,u_=l_.propertyIsEnumerable,qg=Object.getOwnPropertySymbols,h_=qg?function(t){return t==null?[]:(t=Object(t),d_(qg(t),function(e){return u_.call(t,e)}))}:Hg;const Xu=h_;function p_(t,e){return Wa(t,Xu(t),e)}function Gg(t,e){for(var n=-1,i=e.length,s=t.length;++n<i;)t[s+n]=e[n];return t}var m_=Lg(Object.getPrototypeOf,Object);const Zu=m_;var f_=Object.getOwnPropertySymbols,g_=f_?function(t){for(var e=[];t;)Gg(e,Xu(t)),t=Zu(t);return e}:Hg;const Jg=g_;function v_(t,e){return Wa(t,Jg(t),e)}function $g(t,e,n){var i=e(t);return ji(t)?i:Gg(i,n(t))}function eh(t){return $g(t,Qu,Xu)}function y_(t){return $g(t,Ga,Jg)}var E_=Ls(Pn,"DataView");const th=E_;var S_=Ls(Pn,"Promise");const nh=S_;var T_=Ls(Pn,"Set");const ih=T_;var b_=Ls(Pn,"WeakMap");const sh=b_;var Kg="[object Map]",k_="[object Object]",zg="[object Promise]",Yg="[object Set]",Qg="[object WeakMap]",Xg="[object DataView]",w_=Ns(th),__=Ns(Fa),I_=Ns(nh),C_=Ns(ih),R_=Ns(sh),Us=Ds;(th&&Us(new th(new ArrayBuffer(1)))!=Xg||Fa&&Us(new Fa)!=Kg||nh&&Us(nh.resolve())!=zg||ih&&Us(new ih)!=Yg||sh&&Us(new sh)!=Qg)&&(Us=function(t){var e=Ds(t),n=e==k_?t.constructor:void 0,i=n?Ns(n):"";if(i)switch(i){case w_:return Xg;case __:return Kg;case I_:return zg;case C_:return Yg;case R_:return Qg}return e});const Br=Us;var P_=Object.prototype,A_=P_.hasOwnProperty;function M_(t){var e=t.length,n=new t.constructor(e);return e&&typeof t[0]=="string"&&A_.call(t,"index")&&(n.index=t.index,n.input=t.input),n}var O_=Pn.Uint8Array;const hd=O_;function rh(t){var e=new t.constructor(t.byteLength);return new hd(e).set(new hd(t)),e}function D_(t,e){var n=e?rh(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}var N_=/\w*$/;function L_(t){var e=new t.constructor(t.source,N_.exec(t));return e.lastIndex=t.lastIndex,e}var Zg=Fi?Fi.prototype:void 0,ev=Zg?Zg.valueOf:void 0;function x_(t){return ev?Object(ev.call(t)):{}}function tv(t,e){var n=e?rh(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}var V_="[object Boolean]",U_="[object Date]",B_="[object Map]",F_="[object Number]",j_="[object RegExp]",W_="[object Set]",H_="[object String]",q_="[object Symbol]",G_="[object ArrayBuffer]",J_="[object DataView]",$_="[object Float32Array]",K_="[object Float64Array]",z_="[object Int8Array]",Y_="[object Int16Array]",Q_="[object Int32Array]",X_="[object Uint8Array]",Z_="[object Uint8ClampedArray]",eI="[object Uint16Array]",tI="[object Uint32Array]";function nI(t,e,n){var i=t.constructor;switch(e){case G_:return rh(t);case V_:case U_:return new i(+t);case J_:return D_(t,n);case $_:case K_:case z_:case Y_:case Q_:case X_:case Z_:case eI:case tI:return tv(t,n);case B_:return new i;case F_:case H_:return new i(t);case j_:return L_(t);case W_:return new i;case q_:return x_(t)}}var nv=Object.create,iI=function(){function t(){}return function(e){if(!An(e))return{};if(nv)return nv(e);t.prototype=e;var n=new t;return t.prototype=void 0,n}}();const sI=iI;function iv(t){return typeof t.constructor=="function"&&!ud(t)?sI(Zu(t)):{}}var rI="[object Map]";function aI(t){return ti(t)&&Br(t)==rI}var sv=Ur&&Ur.isMap,oI=sv?zu(sv):aI;const cI=oI;var dI="[object Set]";function lI(t){return ti(t)&&Br(t)==dI}var rv=Ur&&Ur.isSet,uI=rv?zu(rv):lI;const hI=uI;var pI=1,mI=2,fI=4,av="[object Arguments]",gI="[object Array]",vI="[object Boolean]",yI="[object Date]",EI="[object Error]",ov="[object Function]",SI="[object GeneratorFunction]",TI="[object Map]",bI="[object Number]",cv="[object Object]",kI="[object RegExp]",wI="[object Set]",_I="[object String]",II="[object Symbol]",CI="[object WeakMap]",RI="[object ArrayBuffer]",PI="[object DataView]",AI="[object Float32Array]",MI="[object Float64Array]",OI="[object Int8Array]",DI="[object Int16Array]",NI="[object Int32Array]",LI="[object Uint8Array]",xI="[object Uint8ClampedArray]",VI="[object Uint16Array]",UI="[object Uint32Array]",Oe={};Oe[av]=Oe[gI]=Oe[RI]=Oe[PI]=Oe[vI]=Oe[yI]=Oe[AI]=Oe[MI]=Oe[OI]=Oe[DI]=Oe[NI]=Oe[TI]=Oe[bI]=Oe[cv]=Oe[kI]=Oe[wI]=Oe[_I]=Oe[II]=Oe[LI]=Oe[xI]=Oe[VI]=Oe[UI]=!0,Oe[EI]=Oe[ov]=Oe[CI]=!1;function pd(t,e,n,i,s,r){var a,c=e&pI,d=e&mI,h=e&fI;if(n&&(a=s?n(t,i,s,r):n(t)),a!==void 0)return a;if(!An(t))return t;var u=ji(t);if(u){if(a=M_(t),!c)return Wg(t,a)}else{var g=Br(t),E=g==ov||g==SI;if(Vr(t))return jg(t,c);if(g==cv||g==av||E&&!s){if(a=d||E?{}:iv(t),!c)return d?v_(t,o_(a,t)):p_(t,n_(a,t))}else{if(!Oe[g])return s?t:{};a=nI(t,g,c)}}r||(r=new ei);var b=r.get(t);if(b)return b;r.set(t,a),hI(t)?t.forEach(function(D){a.add(pd(D,e,n,D,t,r))}):cI(t)&&t.forEach(function(D,F){a.set(F,pd(D,e,n,F,t,r))});var w=h?d?y_:eh:d?Ga:Qu,M=u?void 0:w(t);return sw(M||t,function(D,F){M&&(F=D,D=t[F]),wg(a,F,pd(D,e,n,F,t,r))}),a}var BI=1,FI=4;function ah(t){return pd(t,BI|FI)}var jI="[object Symbol]";function WI(t){return typeof t=="symbol"||ti(t)&&Ds(t)==jI}var HI=Object.defineProperty,qI=(t,e)=>{for(var n in e)HI(t,n,{get:e[n],enumerable:!0})},GI={};qI(GI,{permissions:()=>JI,theme:()=>$I});var Ft=(t=>(t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT",t))(Ft||{}),se=(t=>(t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST",t))(se||{}),JI={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},$I={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}},dv="hXgU8Wc8pwuGNq9ms5q9Hh",lv;typeof Ms!="undefined"&&(lv=Ms==null?void 0:Ms.env)!=null&&lv.FLAGSMITH_ENVIRONMENT_KEY&&(dv=Ms.env.FLAGSMITH_ENVIRONMENT_KEY);function KI(t=[]){const e={};return t.forEach(n=>{e[n.feature.name]={enabled:n.enabled,value:n.feature_state_value}}),e}var zI=class{constructor(t=dv){y(this,"flags",{}),y(this,"environmentKey",null),this.environmentKey=t}identifyAndFetchFlagsWithRetry(t){return p(this,arguments,function*({primaryEndpoint:e,secondaryEndpoint:n,forceEvaluate:i,timeout:s,uniqueIdentifier:r,traitsObj:a,logger:c}){const d=JSON.parse(JSON.stringify(a)),h=Object.entries(d).map(g=>({trait_key:g[0],trait_value:g[1]})),u=[e,n,n];for(const g of u)try{const E="_"+(Math.random()+1).toString(36).substring(2),b=yield Yb.post(`https://${g}/api/v1/identities/`,{identifier:r+(i?E:""),traits:h},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:s});return KI(b.data.flags||[])}catch(E){c.error("Flagsmith identify failed!!",{error:E,url:g})}return{}})}identify(t){return p(this,arguments,function*(e,n={},i=!1,s=5e3,r="edge.api.flagsmith.com",a=console){return this.flags=yield this.identifyAndFetchFlagsWithRetry({traitsObj:n,uniqueIdentifier:e,forceEvaluate:i,timeout:s,primaryEndpoint:r,secondaryEndpoint:"edge.api.flagsmith.com",logger:a}),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}},re=new zI,uv=[-2,-1,0,1,2],YI=[0,1,2,3,4];function QI(t){t=t.trim();let e="0",n="0",i="0";return t.length==4?(e="0x"+t[1]+t[1],n="0x"+t[2]+t[2],i="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],n="0x"+t[3]+t[4],i="0x"+t[5]+t[6]),[+e,+n,+i]}var XI=(t,e,n)=>{let i,s,r;if(e==0)i=s=r=n;else{const a=(h,u,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?h+(u-h)*6*g:g<.5?u:g<.6666666666666666?h+(u-h)*(.6666666666666666-g)*6:h),c=n<.5?n*(1+e):n+e-n*e,d=2*n-c;i=a(d,c,t+1/3),s=a(d,c,t),r=a(d,c,t-1/3)}return[Math.round(i*255),Math.round(s*255),Math.round(r*255)]},ZI=(t,e,n)=>{t/=255,e/=255,n/=255;const i=Math.max(t,e,n),s=Math.min(t,e,n);let r,a;const c=(i+s)/2;if(i==s)r=a=0;else{const d=i-s;switch(a=c>.5?d/(2-i-s):d/(i+s),i){case t:r=(e-n)/d+(e<n?6:0);break;case e:r=(n-t)/d+2;break;case n:r=(t-e)/d+4;break}r/=6}return[r,a,c]},eC=(t,e,n)=>{const i=s=>s.toString(16).padStart(2,"0");return`#${i(t)}${i(e)}${i(n)}`},hv=(t,e=uv,n=.4)=>{const i=[],[s,r,a]=QI(t),[c,d,h]=ZI(s,r,a),u=Math.round(h*100);u>70?n=.8:u>60?n=.9:u<10?n=.075:u<42&&(n=.3);const g=e.findIndex(D=>D===0);if(g===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const E=5-g,b=g+1,w=(100-u)/E,M=u/b;for(const D of e){let F;D<0?F=u+D*M*n:D>0?F=u+D*w*n:F=u;const[Y,X,A]=XI(c,d,F/100);i.push(eC(Y,X,A))}return i},pv={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"}},tC=t=>{const[e,n,i,s,r]=hv(t,uv);return{300:e,400:n,500:i,600:s,700:r}},nC=t=>{if(t==="#FFFFFF")return pv.light.background;if(t==="#000000")return pv.dark.background;const[e,n,i,s,r]=hv(t,YI);return{1e3:e,900:n,800:i,700:s,600:r}},iC={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:tC("#2160FD"),background:nC("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function mv(){return ah(iC)}var sC={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:mv(),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,track_recording:{subscriptions:[]}},version:"hybrid"};function rC(){return ah(sC)}var aC={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:mv(),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,track_recording:{subscriptions:[]}},version:"2.0.0"};function oh(){return ah(aC)}var oC=/\s/;function cC(t){for(var e=t.length;e--&&oC.test(t.charAt(e)););return e}var dC=/^\s+/;function lC(t){return t&&t.slice(0,cC(t)+1).replace(dC,"")}var fv=0/0,uC=/^[-+]0x[0-9a-f]+$/i,hC=/^0b[01]+$/i,pC=/^0o[0-7]+$/i,mC=parseInt;function gv(t){if(typeof t=="number")return t;if(WI(t))return fv;if(An(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=An(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=lC(t);var n=hC.test(t);return n||pC.test(t)?mC(t.slice(2),n?2:8):uC.test(t)?fv:+t}function vv(t){return t}function fC(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}var gC=800,vC=16,yC=Date.now;function EC(t){var e=0,n=0;return function(){var i=yC(),s=vC-(i-n);if(n=i,s>0){if(++e>=gC)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function SC(t){return function(){return t}}var TC=cd?function(t,e){return cd(t,"toString",{configurable:!0,enumerable:!1,value:SC(e),writable:!0})}:vv,bC=EC(TC);const kC=bC;var yv=Math.max;function wC(t,e,n){return e=yv(e===void 0?t.length-1:e,0),function(){for(var i=arguments,s=-1,r=yv(i.length-e,0),a=Array(r);++s<r;)a[s]=i[e+s];s=-1;for(var c=Array(e+1);++s<e;)c[s]=i[s];return c[e]=n(a),fC(t,this,c)}}function _C(t,e){return kC(wC(t,e,vv),t+"")}function IC(t,e,n){if(!An(n))return!1;var i=typeof e;return(i=="number"?qa(n)&&Ag(e,n.length):i=="string"&&e in n)?Ua(n[e],t):!1}function CC(t){return _C(function(e,n){var i=-1,s=n.length,r=s>1?n[s-1]:void 0,a=s>2?n[2]:void 0;for(r=t.length>3&&typeof r=="function"?(s--,r):void 0,a&&IC(n[0],n[1],a)&&(r=s<3?void 0:r,s=1),e=Object(e);++i<s;){var c=n[i];c&&t(e,c,i,r)}return e})}var RC="[object Object]",PC=Function.prototype,AC=Object.prototype,Ev=PC.toString,MC=AC.hasOwnProperty,OC=Ev.call(Object);function DC(t){if(!ti(t)||Ds(t)!=RC)return!1;var e=Zu(t);if(e===null)return!0;var n=MC.call(e,"constructor")&&e.constructor;return typeof n=="function"&&n instanceof n&&Ev.call(n)==OC}var NC="__lodash_hash_undefined__";function LC(t){return this.__data__.set(t,NC),this}function xC(t){return this.__data__.has(t)}function md(t){var e=-1,n=t==null?0:t.length;for(this.__data__=new Vs;++e<n;)this.add(t[e])}md.prototype.add=md.prototype.push=LC,md.prototype.has=xC;function VC(t,e){for(var n=-1,i=t==null?0:t.length;++n<i;)if(e(t[n],n,t))return!0;return!1}function UC(t,e){return t.has(e)}var BC=1,FC=2;function Sv(t,e,n,i,s,r){var a=n&BC,c=t.length,d=e.length;if(c!=d&&!(a&&d>c))return!1;var h=r.get(t),u=r.get(e);if(h&&u)return h==e&&u==t;var g=-1,E=!0,b=n&FC?new md:void 0;for(r.set(t,e),r.set(e,t);++g<c;){var w=t[g],M=e[g];if(i)var D=a?i(M,w,g,e,t,r):i(w,M,g,t,e,r);if(D!==void 0){if(D)continue;E=!1;break}if(b){if(!VC(e,function(F,Y){if(!UC(b,Y)&&(w===F||s(w,F,n,i,r)))return b.push(Y)})){E=!1;break}}else if(!(w===M||s(w,M,n,i,r))){E=!1;break}}return r.delete(t),r.delete(e),E}function jC(t){var e=-1,n=Array(t.size);return t.forEach(function(i,s){n[++e]=[s,i]}),n}function WC(t){var e=-1,n=Array(t.size);return t.forEach(function(i){n[++e]=i}),n}var HC=1,qC=2,GC="[object Boolean]",JC="[object Date]",$C="[object Error]",KC="[object Map]",zC="[object Number]",YC="[object RegExp]",QC="[object Set]",XC="[object String]",ZC="[object Symbol]",eR="[object ArrayBuffer]",tR="[object DataView]",Tv=Fi?Fi.prototype:void 0,ch=Tv?Tv.valueOf:void 0;function nR(t,e,n,i,s,r,a){switch(n){case tR:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case eR:return!(t.byteLength!=e.byteLength||!r(new hd(t),new hd(e)));case GC:case JC:case zC:return Ua(+t,+e);case $C:return t.name==e.name&&t.message==e.message;case YC:case XC:return t==e+"";case KC:var c=jC;case QC:var d=i&HC;if(c||(c=WC),t.size!=e.size&&!d)return!1;var h=a.get(t);if(h)return h==e;i|=qC,a.set(t,e);var u=Sv(c(t),c(e),i,s,r,a);return a.delete(t),u;case ZC:if(ch)return ch.call(t)==ch.call(e)}return!1}var iR=1,sR=Object.prototype,rR=sR.hasOwnProperty;function aR(t,e,n,i,s,r){var a=n&iR,c=eh(t),d=c.length,h=eh(e),u=h.length;if(d!=u&&!a)return!1;for(var g=d;g--;){var E=c[g];if(!(a?E in e:rR.call(e,E)))return!1}var b=r.get(t),w=r.get(e);if(b&&w)return b==e&&w==t;var M=!0;r.set(t,e),r.set(e,t);for(var D=a;++g<d;){E=c[g];var F=t[E],Y=e[E];if(i)var X=a?i(Y,F,E,e,t,r):i(F,Y,E,t,e,r);if(!(X===void 0?F===Y||s(F,Y,n,i,r):X)){M=!1;break}D||(D=E=="constructor")}if(M&&!D){var A=t.constructor,J=e.constructor;A!=J&&"constructor"in t&&"constructor"in e&&!(typeof A=="function"&&A instanceof A&&typeof J=="function"&&J instanceof J)&&(M=!1)}return r.delete(t),r.delete(e),M}var oR=1,bv="[object Arguments]",kv="[object Array]",fd="[object Object]",cR=Object.prototype,wv=cR.hasOwnProperty;function dR(t,e,n,i,s,r){var a=ji(t),c=ji(e),d=a?kv:Br(t),h=c?kv:Br(e);d=d==bv?fd:d,h=h==bv?fd:h;var u=d==fd,g=h==fd,E=d==h;if(E&&Vr(t)){if(!Vr(e))return!1;a=!0,u=!1}if(E&&!u)return r||(r=new ei),a||ld(t)?Sv(t,e,n,i,s,r):nR(t,e,d,n,i,s,r);if(!(n&oR)){var b=u&&wv.call(t,"__wrapped__"),w=g&&wv.call(e,"__wrapped__");if(b||w){var M=b?t.value():t,D=w?e.value():e;return r||(r=new ei),s(M,D,n,i,r)}}return E?(r||(r=new ei),aR(t,e,n,i,s,r)):!1}function _v(t,e,n,i,s){return t===e?!0:t==null||e==null||!ti(t)&&!ti(e)?t!==t&&e!==e:dR(t,e,n,i,_v,s)}function lR(t){return function(e,n,i){for(var s=-1,r=Object(e),a=i(e),c=a.length;c--;){var d=a[t?c:++s];if(n(r[d],d,r)===!1)break}return e}}var uR=lR();const hR=uR;var pR=function(){return Pn.Date.now()};const dh=pR;var mR="Expected a function",fR=Math.max,gR=Math.min;function gd(t,e,n){var i,s,r,a,c,d,h=0,u=!1,g=!1,E=!0;if(typeof t!="function")throw new TypeError(mR);e=gv(e)||0,An(n)&&(u=!!n.leading,g="maxWait"in n,r=g?fR(gv(n.maxWait)||0,e):r,E="trailing"in n?!!n.trailing:E);function b(me){var Re=i,fe=s;return i=s=void 0,h=me,a=t.apply(fe,Re),a}function w(me){return h=me,c=setTimeout(F,e),u?b(me):a}function M(me){var Re=me-d,fe=me-h,Qe=e-Re;return g?gR(Qe,r-fe):Qe}function D(me){var Re=me-d,fe=me-h;return d===void 0||Re>=e||Re<0||g&&fe>=r}function F(){var me=dh();if(D(me))return Y(me);c=setTimeout(F,M(me))}function Y(me){return c=void 0,E&&i?b(me):(i=s=void 0,a)}function X(){c!==void 0&&clearTimeout(c),h=0,i=d=s=c=void 0}function A(){return c===void 0?a:Y(dh())}function J(){var me=dh(),Re=D(me);if(i=arguments,s=this,d=me,Re){if(c===void 0)return w(d);if(g)return clearTimeout(c),c=setTimeout(F,e),b(d)}return c===void 0&&(c=setTimeout(F,e)),a}return J.cancel=X,J.flush=A,J}function lh(t,e,n){(n!==void 0&&!Ua(t[e],n)||n===void 0&&!(e in t))&&Ku(t,e,n)}function vR(t){return ti(t)&&qa(t)}function uh(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function yR(t){return Wa(t,Ga(t))}function ER(t,e,n,i,s,r,a){var c=uh(t,n),d=uh(e,n),h=a.get(d);if(h){lh(t,n,h);return}var u=r?r(c,d,n+"",t,e,a):void 0,g=u===void 0;if(g){var E=ji(d),b=!E&&Vr(d),w=!E&&!b&&ld(d);u=d,E||b||w?ji(c)?u=c:vR(c)?u=Wg(c):b?(g=!1,u=jg(d,!0)):w?(g=!1,u=tv(d,!0)):u=[]:DC(d)||dd(d)?(u=c,dd(c)?u=yR(c):(!An(c)||Ju(c))&&(u=iv(d))):g=!1}g&&(a.set(d,u),s(u,d,i,r,a),a.delete(d)),lh(t,n,u)}function Iv(t,e,n,i,s){t!==e&&hR(e,function(r,a){if(s||(s=new ei),An(r))ER(t,e,a,n,Iv,i,s);else{var c=i?i(uh(t,a),r,a+"",t,e,s):void 0;c===void 0&&(c=r),lh(t,a,c)}},Ga)}var SR="[object Map]",TR="[object Set]",bR=Object.prototype,kR=bR.hasOwnProperty;function wR(t){if(t==null)return!0;if(qa(t)&&(ji(t)||typeof t=="string"||typeof t.splice=="function"||Vr(t)||ld(t)||dd(t)))return!t.length;var e=Br(t);if(e==SR||e==TR)return!t.size;if(ud(t))return!xg(t).length;for(var n in t)if(kR.call(t,n))return!1;return!0}function _R(t,e){return _v(t,e)}var IR=CC(function(t,e,n){Iv(t,e,n)});const Wi=IR;var hh=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(hh||{});const ue={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",USE_EXPERIMENTAL_SFU_HANDLER:"use_experimental_sfu_handler",TRACK_HINT:"track_hint",OVERRIDE_HIVE_SIMULCAST_DYNAMIC:"override_hive_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs"};function vd(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 CR(t){var e,n,i,s;const r=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((n=window.location.host)==null?void 0:n.includes("dyte.io")),a=!!((s=(i=t==null?void 0:t.getValue("modules"))==null?void 0:i.devTools)!=null&&s.logs);return r||a}function RR(t){var e;if(re.hasFeature(ue.LOG_LEVEL)){let n=((e=re.getValue(ue.LOG_LEVEL))==null?void 0:e.toString())||"all";if(n=n.toLowerCase().trim(),n==="off")return!1;if(n!=="all"){const i=["debug","log","info","warn","error"],s=i.indexOf(t),r=i.indexOf(n);if(s<r)return!1}}return!0}function Cv(t,e,n={}){return Object.getOwnPropertyNames(t).forEach(i=>{var s;if([null,void 0,NaN].includes(t[i])||e&&(((s=e.match(/\./g))==null?void 0:s.length)||0)>=10)return;const r=e?`${e}.${i}`:i;typeof t[i]=="object"?Cv(t[i],r,n):["number","string","boolean"].includes(typeof t[i])&&(n[r]=t[i])}),n}function Rv(t,e,n={},i=""){const s={};try{const r=JSON.stringify(n),a=JSON.parse(r),c=Cv(a,i),d=JSON.stringify(c);return JSON.parse(d)}catch(r){const a=vd(r);s[`${i}.error.message`]=a.message||"",s[`${i}.error.stack`]=a.stack||"",s[`${i}.error.reason`]=a.reason||"",s[`${i}.error.source`]="safelyFlattenObjForOpenTelemetry"}return s}const Ja="chrome",Pv="opera",Av="firefox",Mv="iexplorer",Ov="safari",Dv="nwjs",Nv="electron",Lv="react-native",ph="unknown",yd={Chrome:Ja,Chromium:Ja,Opera:Pv,Firefox:Av,"Internet Explorer":Mv,Safari:Ov};function PR(){const{userAgent:t}=navigator,e={name:ph,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const n=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(n,10)>72&&(e.name=Ja,e.version=n)}else e.name=Ja,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function AR(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:Nv,version:e}}return null}function MR(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Dv,version:e}}}function OR(){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:Lv,version:e}}function DR(t){let e;const n=[OR,AR,MR];for(let s=0;s<n.length;s+=1)if(e=n[s](),e)return e;const i=t.getBrowserName();return i in yd?{name:yd[i],version:t.getBrowserVersion()}:(e=PR(),e||{name:ph,version:void 0})}class NR{constructor(){y(this,"_bowser"),y(this,"_name"),y(this,"_version"),y(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 n,i;if(this._bowser=Tm.getParser(navigator.userAgent),typeof e=="undefined"){const s=DR(this._bowser);n=s.name,i=s.version}else e.name in yd?(n=yd[e.name],i=e.version):(n=ph,i=void 0);this._name=n,this._version=i}getName(){return this._name}isChrome(){return this._name===Ja}isOpera(){return this._name===Pv}isFirefox(){return this._name===Av}isIExplorer(){return this._name===Mv}isSafari(){return this._name===Ov}isNWJS(){return this._name===Dv}isElectron(){return this._name===Nv}isReactNative(){return this._name===Lv||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 LR extends NR{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(n){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(Ms.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 Ue=new LR,xR={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},$a={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"},VR={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 Ed(t,e){const n=t.getValue("overrides");return n&&n[e]?n[e]:!1}function UR({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?La.PREPROD:t!=null&&t.includes("devel.dyte")?La.DEVEL:La.PROD}function Fr({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function xv(t){const e=t.getValue("baseURI");return{location:Fr({servicePrefix:"location",baseURI:e}),locationLegacy:Fr({servicePrefix:"location-legacy",baseURI:e}),daCollector:Fr({servicePrefix:"da-collector",baseURI:e})}}const BR='<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>',FR='<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>',Sd=t=>{if(!t)return;if(!t.startsWith("<svg"))return new Promise(s=>{s(t)});const e=new Blob([t],{type:"image/svg+xml"}),n=new Image,i=window.URL.createObjectURL(e);return new Promise((s,r)=>{n.onload=()=>{s(n),window.URL.revokeObjectURL(i)},n.onerror=()=>{r(),window.URL.revokeObjectURL(i)},n.src=i})};function jR(t){const e=H({},t),n=new Map,i=(a,c)=>(n.has(a)||n.set(a,new Set),n.get(a).add(c),()=>{var d;return(d=n.get(a))==null?void 0:d.delete(c)}),s=(a,c)=>{var d;(d=n.get(a))==null||d.delete(c)},r=a=>{var c;(c=n.get(a))==null||c.forEach(d=>{try{d(e[a])}catch(h){m.error(`Error in notifying for "${a.toString()}"`,h)}})};return{subscribe:i,unsubscribe:s,notify:r,setValue:(a,c,d=!0)=>{e[a]=c,d&&r(a)},getValue:a=>e[a],getAllValues:()=>e}}class WR{constructor(){y(this,"contexts",new Map),y(this,"mostRecentPeerId",null)}createContext(e,n){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,jR(n)),this.mostRecentPeerId=e,this.contexts.get(e))}remapContext(e,n){const i=n.getValue("peerId");i!==e&&(n.setValue("peerId",e),this.mostRecentPeerId=e,this.contexts.set(e,n),this.contexts.delete(i))}getContext(e){return this.contexts.get(e)}getMostRecentPeerId(){return this.mostRecentPeerId}}const Bs=new WR,ge=class{static get logsEndpoint(){const t=Bs.getContext(ge.meetingMetadata.peerId);return`https://${Fr({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){ge.meetingMetadata.peerId=t}static init(t,e){const n=t.getValue("peerId");ge.tracingEnabled=e,ge.meetingMetadata.peerId=n,ge.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),ge.meetingMetadata.deviceInfo=Ue.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(n,i,s)=>{const r=s.value;return s.value=function(...a){if(!ge.initialized||navigator.isReactNative||!ge.tracingEnabled||re.hasFeature(ue.SKIP_OTEL_TRACES))return r.apply(this,a);ge.addLogInCurrentSpan("info",t,e);const c=performance.now(),d=r.apply(this,a);return Promise.resolve(d).then(()=>{const h=performance.now();h-c>10&&ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-c,country:ge.location.country})}).catch(()=>{const h=performance.now();ge.addLogInCurrentSpan("info",`${t}_timing`,{execTime:h-c})}),d},s}}static injectContext(t){var e;const n=Ar().replace(/-/g,"").substring(0,16),i=(e=ge.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${i}-${n}-01`}static addLogInCurrentSpan(t,e,n={},i=!1){n!=null&&n.error&&Object.assign(n,{error:vd(n.error)});const s=Bs.getContext(ge.meetingMetadata.peerId);if(CR(s)&&(wR(n)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,n)),!!RR(t))try{const r=Rv(s,e,n,"metadata"),a=new Date,c=ee(H({message:e,level:t},r),{loggedAt:a.toISOString(),loggedAtTzOffset:a.getTimezoneOffset()});i?ge.sendOtelLogsToNewRelic([c]):ge.logsCache.push(c)}catch(r){ge.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:vd(r)})}}static sendOtelLogsToNewRelic(t){const e=Bs.getContext(ge.meetingMetadata.peerId);fetch(ge.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:Rv(e,"sendOtelLogsToNewRelic",ge.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(n=>{ge.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:vd(n)}),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 k=ge;y(k,"logsCache",[]),y(k,"logsProcessorTimer"),y(k,"location",{country:void 0}),y(k,"tracingEnabled",!0),y(k,"initialized",!1),y(k,"logsProcessingInterval",7e3),y(k,"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"]),y(k,"meetingMetadata",{});class m{static info(e,n,i){k.addLogInCurrentSpan("info",e,n,i)}static error(e,n,i){k.addLogInCurrentSpan("error",e,n,i)}static debug(e,n,i){k.addLogInCurrentSpan("debug",e,n,i)}static log(e,n,i){k.addLogInCurrentSpan("log",e,n,i)}static warn(e,n,i){k.addLogInCurrentSpan("warn",e,n,i)}}const HR=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&m.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,n,i,s,r,a,c,d;m.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(n=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:n.url,baseURL:(s=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:s.baseURL,method:(a=(r=t==null?void 0:t.reason)==null?void 0:r.config)==null?void 0:a.method,status:(c=t==null?void 0:t.reason)==null?void 0:c.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{m.info("window::offline")}),window.addEventListener("online",()=>{m.info("window::online")}))},qR={"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"},Td={"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(Td).forEach(t=>{Td[t]=`{${qR[t.slice(0,2)]}} ${Td[t]}`});class O extends Error{constructor(e,n,i=!1){super(e),y(this,"code"),this.code=n,this.name="DyteError",this.message=`[ERR${this.code}]: ${Td[this.code]}
19
- ${this.message}`;try{let s=i;n&&n.endsWith("00")&&(s=!0),s&&m.error("DyteError",{error:{message:this.message,name:this.name,code:n}});const r=Bs.getContext(Bs.getMostRecentPeerId());if(r){const a=r.getValue("onError");try{a(this)}catch(c){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("dyteError",{detail:this}))}catch(s){}}}function bd(t,e,n,i){if(i instanceof O)throw i;if(i instanceof e){const s=new O(i.message,n);throw s.stack=i.stack,s}else throw i}function Vv(t,e,n){if(!t.value){const s=t.get,r=t.set;return s&&(t.get=function(){try{return s.apply(this)}catch(a){bd(this,e,n,a)}}),r&&(t.set=function(a){try{return r.apply(this,[a])}catch(c){bd(this,e,n,c)}}),t}const i=t.value;return t.value=function(...s){try{const r=i.apply(this,s);return r&&r instanceof Promise?r.catch(a=>{bd(this,e,n,a)}):r}catch(r){bd(this,e,n,r)}},t}function GR(t,e){return(n,i,s)=>{if(s)return Vv(s,t,e);for(const r of Reflect.ownKeys(n.prototype).filter(a=>a!=="constructor")){const a=Object.getOwnPropertyDescriptor(n.prototype,r);(a.value instanceof Function||a.get instanceof Function||a.set instanceof Function)&&Object.defineProperty(n.prototype,r,Vv(a,t,e))}}}const Ot=t=>GR(Error,t);function JR(t){let e=0,n,i;if(!t)return e;for(n=0;n<t.length;n+=1)i=t.charCodeAt(n),e=(e<<5)-e+i,e|=0;return Math.abs(e)%100+1}var Hi,qi;const Uv=class extends Mt.EventEmitter{constructor(){super(),S(this,Hi,void 0),S(this,qi,void 0),y(this,"asyncPromiseTimeout"),T(this,Hi,new Map),T(this,qi,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return p(this,null,function*(){o(this,Hi).set(t,[]);const n=o(this,qi).get(t).map(()=>new Promise(i=>{o(this,Hi).get(t).push(i)}));kS(Uv.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(n),new Promise((i,s)=>setTimeout(()=>s(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),o(this,Hi).delete(t)})}onAsync(t,e){const n=o(this,Hi),i=(...s)=>p(this,null,function*(){var r;try{yield e(...s)}catch(c){m.error("[onAsync]",{error:c})}const a=(r=n.get(t))==null?void 0:r.shift();a==null||a()});return o(this,qi).get(t)||o(this,qi).set(t,[]),o(this,qi).get(t).push(i),super.on(t,i)}reset(){T(this,Hi,new Map),T(this,qi,new Map),super.removeAllListeners()}};let $R=Uv;Hi=new WeakMap,qi=new WeakMap;const L=new $R;function KR(){Ue.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>p(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 n=e.find(s=>{var r;return(r=s.id)==null?void 0:r.includes("screen")});n=n!=null?n:e[0];const i={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n.id}}};return yield navigator.mediaDevices.getUserMedia(i)}))}var x=(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))(x||{});class jr extends Mt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...n){return super.emit("*",e,...n),super.emit(e,...n)}on(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.on(e,n)}addListener(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.addListener(e,n)}off(e,n){return super.off(e,n)}once(e,n){return super.once(e,n)}prependListener(e,n){return super.prependListener(e,n)}prependOnceListener(e,n){return super.prependOnceListener(e,n)}removeListener(e,n){return super.removeListener(e,n)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class cn extends Mt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...n){return super.emit("*",e,...n),super.emit(e,...n)}on(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.on(e,n)}addListener(e,n){try{const i=this.listenerCount(e);i>25&&i%25===0&&m.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(i){}return super.addListener(e,n)}off(e,n){return super.off(e,n)}once(e,n){return super.once(e,n)}prependListener(e,n){return super.prependListener(e,n)}prependOnceListener(e,n){return super.prependOnceListener(e,n)}removeListener(e,n){return super.removeListener(e,n)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function zR(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(n=>n.charAt(0)).join("").toUpperCase()}const Bv=1080,Fv=1920,YR=(t,e,n,i,s,r)=>{let a=.5,c=.5;const d=s,h=r,u=Math.min(n/d,i/h);let g=d*u,E=h*u,b,w,M,D,F=1;return g<n&&(F=n/g),Math.abs(F-1)<1e-14&&E<i&&(F=i/E),g*=F,E*=F,M=d/(g/n),D=h/(E/i),b=(d-M)*a,w=(h-D)*c,b<0&&(b=0),w<0&&(w=0),M>d&&(M=d),D>h&&(D=h),[b,w,M,D,t,e,n,i]};var Mn,Ka,jt,On,tt,ni,Gi,Zt,at,za,Ya,Ji,Qa;const jv=class extends cn{constructor(t,e,n,i){super(),S(this,Mn,void 0),S(this,Ka,void 0),S(this,jt,void 0),S(this,On,void 0),S(this,tt,{height:Bv,width:Fv}),S(this,ni,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),S(this,Gi,void 0),S(this,Zt,{}),S(this,at,void 0),S(this,za,void 0),S(this,Ya,void 0),S(this,Ji,void 0),S(this,Qa,!1),y(this,"cleanupEventListeners",()=>{o(this,Ka).unsubscribe("stageStatus",this.handlePipMediaControls),o(this,at).removeListener("videoUpdate",this.onSelfVideoUpdateListener),o(this,at).removeListener("audioUpdate",this.onSelfAudioUpdateListener),o(this,at).removeListener("roomLeft",()=>this.disable())}),y(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),y(this,"onSelfVideoUpdateListener",({videoEnabled:s})=>{this.updateMediaSession("CAMERA",s)}),y(this,"onSelfAudioUpdateListener",({audioEnabled:s})=>{this.updateMediaSession("MIC",s)}),y(this,"handlePipMediaControls",s=>{s==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),y(this,"eventCallback",s=>{s==="CAMERA"&&(o(this,at).videoEnabled?o(this,at).disableVideo():o(this,at).enableVideo(),this.emit("cameraToggled")),s==="MIC"&&(o(this,at).audioEnabled?o(this,at).disableAudio():o(this,at).enableAudio(),this.emit("micToggled")),s==="END"&&(L.emit(x.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),y(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),y(this,"animate",()=>{if(!this.isActive&&o(this,Ji)==="active"){this.disable(!0);return}o(this,Zt)!==void 0&&this.paintCanvas(),o(this,Gi)!==void 0&&T(this,Gi,requestAnimationFrame(()=>this.animate()))}),y(this,"disable",(s=!1)=>{T(this,Ji,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(o(this,Gi)),s!==!0&&document.body.removeChild(o(this,jt)),T(this,Gi,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),T(this,Ka,t),T(this,Ji,"idle"),T(this,at,e),T(this,ni,{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}),n&&this.setupIcon("pin",n),i&&this.setupIcon("handRaise",i)}static _init(t,e){return p(this,null,function*(){let n,i;try{n=yield Sd(BR),i=yield Sd(FR)}catch(s){}return new jv(t,e,n,i)})}setupIcon(t,e){return p(this,null,function*(){switch(t){case"handRaise":T(this,Ya,e);break;case"pin":T(this,za,e);break}})}overrideIcon(t,e){return p(this,null,function*(){switch(t){case"handRaise":T(this,Ya,yield Sd(e));break;case"pin":T(this,za,yield Sd(e));break}})}constructImage(t){const e=new Image,n=new Blob([t],{type:"image/svg+xml"}),i=window.URL.createObjectURL(n);return new Promise(s=>{e.onload=()=>{s(e),window.URL.revokeObjectURL(i)},e.src=i})}createVideoContainer(){T(this,jt,document.createElement("div")),o(this,jt).style.width="0.1px",o(this,jt).style.height="0.1px",o(this,jt).style.overflow="hidden",o(this,jt).style.position="absolute",o(this,jt).style.bottom="0",o(this,jt).style.right="0",o(this,jt).style.opacity="0",o(this,jt).appendChild(o(this,On))}setupEventListeners(){o(this,Ka).subscribe("stageStatus",this.handlePipMediaControls),o(this,at).addListener("videoUpdate",this.onSelfVideoUpdateListener),o(this,at).addListener("audioUpdate",this.onSelfAudioUpdateListener),o(this,at).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=o(this,tt).height,t.width=o(this,tt).width,T(this,Mn,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||o(this,at).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||o(this,at).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const t=Object.values(o(this,Zt)).reduce((e,n)=>(e[n.pinned?"pinned":"regular"].push(n),e),{pinned:[],regular:[]});return[...t.pinned,...t.regular]}drawEmptyTile(t,e,n,i){if(o(this,Mn)===void 0)return;const s=o(this,Mn).getContext("2d"),r=o(this,Mn).width,a=0,c=0,d=e-a*2,h=n-a*2,u=Math.floor(r/d),g=Math.floor(t/u),E=t%u*(d+a)+a,b=g*(h+a)+a,{displayText:w,image:M}=i!=null?i:{};s.fillStyle=w||M?o(this,ni).videoBackground:o(this,ni).background,s.strokeStyle=o(this,ni).brand,s.beginPath(),s.moveTo(E+c,b),s.arcTo(E+d,b,E+d,b+c,c),s.arcTo(E+d,b+h,E+d-c,b+h,c),s.arcTo(E,b+h,E,b+h-c,c),s.arcTo(E,b,E+c,b,c),s.closePath(),s.fill(),s.stroke();const D=d/6,F=d/2+E,Y=h/2+b;s.save(),(w||M)&&(s.beginPath(),s.arc(F,Y,D,0,Math.PI*2),s.fillStyle=o(this,ni).brand,s.fill(),M?(s.clip(),s.drawImage(M,F-D,Y-D,D*2,D*2),s.restore()):w&&(s.fillStyle=o(this,ni).textOnBrand,s.font=`${D/2}px sans-serif`,s.textAlign="center",s.textBaseline="middle",s.fillText(w,F,Y)),this.drawIcons(i,E,b,Math.max(d,h)))}drawIcons(t,e,n,i){const s=Math.min(Math.max(i*.15,100),200),r=s*.2,a=s*.2;let c=e+r;const d=n+r,h=u=>{const g=o(this,Mn).getContext("2d");g.save(),g.fillStyle=o(this,ni).background,g.beginPath(),g.moveTo(c+a,d),g.arcTo(c+s,d,c+s,d+a,a),g.arcTo(c+s,d+s,c+s-a,d+s,a),g.arcTo(c,d+s,c,d+s-a,a),g.arcTo(c,d,c+a,d,a),g.closePath(),g.fill(),typeof u=="string"?(g.font=`${s/1.5}px sans-serif`,g.fillStyle=o(this,ni).text,g.textAlign="center",g.textBaseline="top",g.fillText(u,s/2+c,d+r)):g.drawImage(u,c+r,d+r,s-r*2,s-r*2),c+=s+r,g.restore()};t.pinned&&h(o(this,za)),t.handRaised&&h(o(this,Ya))}drawTile(t,e,n){var i,s;if(o(this,Mn)===void 0)return;const r=o(this,Mn).getContext("2d"),a=this.getSources();let c=0,d=0;for(;c<o(this,tt).height-5;){let h=0;for(;h<o(this,tt).width-5&&d<n;){if((i=a[d])!=null&&i.enabled){const u=a[d].element,[g,E,b,w,M,D,F,Y]=YR(h,c,t,e,u.videoWidth,u.videoHeight);(s=u==null?void 0:u.classList)!=null&&s.contains("mirror")?(r.save(),r.scale(-1,1),r.drawImage(u,g,E,b,w,-1*M,D,-1*F,Y),r.restore()):r.drawImage(u,g,E,b,w,M,D,F,Y),this.drawIcons(a[d],M,D,Math.max(F,Y))}else this.drawEmptyTile(d,t,e,a[d]);d+=1,h+=t}c+=e}}calcGridElemSize(t){switch(t){case 0:case 1:return[o(this,tt).width,o(this,tt).height];case 2:return[Math.floor(o(this,tt).width/2),o(this,tt).height];case 3:case 4:return[Math.floor(o(this,tt).width/2),Math.floor(o(this,tt).height/2)];case 5:case 6:return[Math.floor(o(this,tt).width/3),Math.floor(o(this,tt).height/2)];case 7:case 8:case 9:return[Math.floor(o(this,tt).width/3),Math.floor(o(this,tt).height/3)];default:return[Math.floor(o(this,tt).width/3),Math.floor(o(this,tt).height/2)]}}paintCanvas(){let t=this.getSources().length;t!==1&&(t=t%2>0?t+1:t);const[e,n]=this.calcGridElemSize(t);this.drawTile(e,n,t)}isSupported(){var t;return!!window.chrome&&document.pictureInPictureEnabled&&((t=o(this,at).config)==null?void 0:t.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(T(this,Qa,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),o(this,jt))try{document.body.removeChild(o(this,jt))}catch(t){}this.removeAllSources(),T(this,Mn,void 0),T(this,On,void 0),T(this,Gi,void 0)}init({height:t,width:e}={}){if(!this.isSupported())throw m.error("DytePip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(o(this,Qa))return;T(this,Qa,!0),this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,tt,{height:t!=null?t:Bv,width:e!=null?e:Fv}),n.height=o(this,tt).height,n.width=o(this,tt).width,n.autoplay=!0,n.muted=!0,n.srcObject=o(this,Mn).captureStream(24),T(this,On,n),o(this,On).onloadedmetadata=()=>{try{this.emit("pipStarted"),o(this,On).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){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){o(this,Zt)[t]!==void 0&&(o(this,Zt)[t].enabled=!0)}disableSource(t){o(this,Zt)[t]!==void 0&&(o(this,Zt)[t].enabled=!1)}generateAvatar(t,e){return p(this,null,function*(){if(!e)return;const n=new Image;try{const i=yield(yield fetch(e)).blob(),s=window.URL.createObjectURL(i);n.onload=()=>{this.updateSource(t,{image:n}),window.URL.revokeObjectURL(s)},n.src=s}catch(i){m.error("DytePip::GenerateAvatar",{error:i})}})}addSource(t,e,n,i=!1,s=void 0,r=void 0,a=!1){m.debug("DytePIP::AddSource",{pip:{id:t,handRaised:a}}),o(this,Zt)[t]={id:t,element:e,enabled:n,pinned:i,displayText:s?zR(s):void 0,imageUrl:r,handRaised:a},r&&this.generateAvatar(t,r)}updateSource(t,e){m.info("DytePIP::UpdateSource",{pip:{id:t,handRaised:e.handRaised}});const n=o(this,Zt)[t];n&&(o(this,Zt)[t]=H(H({},n),e))}removeSource(t){delete o(this,Zt)[t]}removePinnedSource(){Object.values(o(this,Zt)).forEach(t=>{t.pinned&&this.removeSource(t.id)})}removeAllSources(){T(this,Zt,{})}enable(){T(this,Ji,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",o(this,at).videoEnabled),this.updateMediaSession("MIC",o(this,at).audioEnabled),document.body.appendChild(o(this,jt)),T(this,Gi,requestAnimationFrame(()=>this.animate())),o(this,On).onloadedmetadata=()=>{o(this,On).requestPictureInPicture().then(()=>{T(this,Ji,"active")})},o(this,On).readyState===4&&o(this,On).requestPictureInPicture().then(()=>{T(this,Ji,"active")})}};let QR=jv;Mn=new WeakMap,Ka=new WeakMap,jt=new WeakMap,On=new WeakMap,tt=new WeakMap,ni=new WeakMap,Gi=new WeakMap,Zt=new WeakMap,at=new WeakMap,za=new WeakMap,Ya=new WeakMap,Ji=new WeakMap,Qa=new WeakMap;var yi;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(yi||(yi={}));var ii;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(ii||(ii={}));class XR extends _{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},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Wv=new XR;class ZR extends _{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const eP=new ZR;class tP extends _{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new tP;class nP extends _{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",yi]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Dn=new nP;class iP extends _{constructor(){super("media.ProducerPayload",[{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:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const sP=new iP;class rP 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:()=>Dn},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>sP}])}}const aP=new rP;class oP extends _{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const cP=new oP;class dP extends _{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Dn},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Hv=new dP;class lP extends _{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Dn}])}}const uP=new lP;class hP extends _{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Dn}])}}new hP;class pP 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 mP=new pP;class fP 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 gP=new fP;class vP 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 vP;class yP 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 yP;class EP extends _{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",ii]},{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},{no:8,name:"codec",kind:"message",T:()=>Wv}])}}const Xa=new EP;class SP extends _{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Xa},{no:3,name:"producer_track",kind:"message",T:()=>gP},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const TP=new SP;class bP extends _{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>TP}}])}}const qv=new bP;class kP extends _{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>$v},{no:2,name:"receiver",kind:"message",T:()=>$v}])}}const Gv=new kP;class wP extends _{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Wv},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>eP}])}}const Jv=new wP;class _P extends _{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Jv},{no:2,name:"video",kind:"message",T:()=>Jv}])}}const $v=new _P;class IP extends _{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 CP=new IP;class RP 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 PP=new RP;class AP 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:()=>PP},{no:9,name:"capabilities",kind:"message",T:()=>Gv}])}}const MP=new AP;class OP extends _{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const DP=new OP;class NP extends _{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const LP=new NP;class xP 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 xP;class VP 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},{no:4,name:"preferred_codec",kind:"message",T:()=>CP},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const UP=new VP;class BP extends _{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>UP},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const FP=new BP;class jP 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:()=>Dn},{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},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const WP=new jP;class HP extends _{constructor(){super("media.edge.SelectedPeersRequest",[])}}new HP;class qP extends _{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const GP=new qP;class JP extends _{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const kd=new JP;class $P extends _{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new $P;class KP extends _{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Dn},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const zP=new KP;class YP extends _{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Dn},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const QP=new YP;class XP extends _{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new XP;class ZP extends _{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Kv=new ZP;class e1 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 t1=new e1;class n1 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 i1=new n1;class s1 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 r1=new s1;class a1 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 o1=new a1;class c1 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 d1=new c1;class l1 extends _{constructor(){super("media.edge.EmptyResponse",[])}}new l1;class u1 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:()=>Xa},{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:()=>Gv}])}}const zv=new u1;class h1 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 mh=new h1;class p1 extends _{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const m1=new p1;class f1 extends _{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>m1}])}}const Yv=new f1;class g1 extends _{constructor(){super("media.edge.PeerJoinResponse",[])}}new g1;class v1 extends _{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>o1},{no:2,name:"participants",kind:"message",repeat:1,T:()=>zv},{no:3,name:"selected_peers",kind:"message",T:()=>mh},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const fh=new v1;class y1 extends _{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const E1=new y1;class S1 extends _{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>qv}])}}new S1;class T1 extends _{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>qv},{no:3,name:"description",kind:"message",T:()=>Dn}])}}const b1=new T1;class k1 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:()=>Dn}])}}const w1=new k1;class _1 extends _{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>mP}])}}new _1;class I1 extends _{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new I1;class C1 extends _{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new C1;class R1 extends _{constructor(){super("media.edge.ProducerToggleResponse",[])}}new R1;class P1 extends _{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new P1;class A1 extends _{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Dn}])}}const M1=new A1;class O1 extends _{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Dn}])}}const D1=new O1;class N1 extends _{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new N1;class L1 extends _{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new L1;class x1 extends _{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new x1;class V1 extends _{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const U1=new V1;class B1 extends _{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const F1=new B1;class j1 extends _{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const W1=new j1;class H1 extends _{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>zv}])}}const Qv=new H1;class q1 extends _{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Xv=new q1;class G1 extends _{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Xv},{no:3,name:"screenshare",kind:"message",T:()=>Xv}])}}const J1=new G1;class $1 extends _{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Hv},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>J1}])}}new $1;class K1 extends _{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Xa}])}}const z1=new K1;class Y1 extends _{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Xa},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Zv=new Y1;class Q1 extends _{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Xa}])}}const X1=new Q1;class Z1 extends _{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const gh=new Z1;class eA extends _{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ey=new eA;class tA extends _{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new tA;class nA extends _{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new nA;class iA extends _{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new iA;class sA 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 sA;class rA extends _{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new rA;class aA extends _{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new aA;class oA 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 vh=new oA;class cA 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 cA;class dA 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 lA=new dA;var Fs;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(Fs||(Fs={}));var Ei;(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"})(Ei||(Ei={}));var yh;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(yh||(yh={}));var Eh;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(Eh||(Eh={}));var wd;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(wd||(wd={}));class uA 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 hA=new uA;class pA 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",Ei,"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:()=>hA}])}}const _d=new pA;class mA extends _{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>_d}])}}const Wr=new mA;class fA 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",Ei,"STAGE_TYPE_"]}])}}const ty=new fA;class gA 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 vA=new gA;class yA extends _{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>_d}])}}const Sh=new yA;class EA extends _{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const ny=new EA;class SA 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:()=>bA},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const iy=new SA;class TA 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",Fs]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const bA=new TA;class kA extends _{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>iy}])}}const sy=new kA;class wA extends _{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const ry=new wA;class _A 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 _A;class IA extends _{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>_d},{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",wd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const CA=new IA;class RA extends _{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>_d},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const PA=new RA;class AA extends _{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>iy}])}}new AA;class MA extends _{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new MA;class OA 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 Th=new OA;class DA 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 NA=new DA;class LA 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:()=>NA}])}}const ay=new LA;class xA extends _{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>ay},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>ay}])}}const VA=new xA;class UA extends _{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const BA=new UA;class FA extends _{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>BA}])}}const jA=new FA;class WA 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:()=>Th}])}}const HA=new WA;class qA extends _{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>HA}])}}const oy=new qA;class GA 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 JA=new GA;class $A extends _{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>JA}])}}new $A;class KA extends _{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const zA=new KA;class YA extends _{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zA}])}}const QA=new YA;class XA extends _{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>tM}])}}const ZA=new XA;class eM 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:()=>Th}])}}const tM=new eM;class nM 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 iM=new nM;class sM 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:()=>iM}])}}const rM=new sM;class aM 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:()=>Th}])}}const cy=new aM;class oM extends _{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>cy}])}}new oM;class cM 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 dM=new cM;class lM extends _{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>pM}])}}const uM=new lM;class hM 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 pM=new hM;class mM extends _{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const dy=new mM;class fM 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:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",Eh,"BROADCAST_TYPE_"]}])}}const Za=new fM;class gM extends _{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const vM=new gM;class yM extends _{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const EM=new yM;class SM 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},{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 TM=new SM;class bM extends _{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>TM}])}}const ly=new bM;class kM 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 uy=new kM;var bh;(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"})(bh||(bh={}));var $i;(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"})($i||($i={}));class wM 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 _M=new wM;class IM 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 CM=new IM;class RM 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 PM=new RM;class AM 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 MM=new AM;class OM extends _{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>PM},{no:2,name:"private",kind:"message",T:()=>MM}])}}const DM=new OM;class NM 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 LM=new NM;class xM extends _{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$i,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",$i,"STREAM_PERMISSION_TYPE_"]}])}}const kh=new xM;class VM extends _{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>kh},{no:2,name:"audio",kind:"message",T:()=>kh},{no:3,name:"screenshare",kind:"message",T:()=>kh}])}}const UM=new VM;class BM extends _{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>_M},{no:2,name:"plugins",kind:"message",T:()=>CM},{no:3,name:"chat",kind:"message",T:()=>DM},{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",bh,"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",yh,"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:()=>LM},{no:23,name:"media",kind:"message",T:()=>UM}])}}const wh=new BM;class FM extends _{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const jM=new FM;class WM 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 HM=new WM;class qM extends _{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>HM}])}}const GM=new qM;class JM extends _{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>wh}])}}const hy=new JM;class $M extends _{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>hy}])}}const KM=new $M;class zM extends _{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>hy}])}}const py=new zM;class YM 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 QM=new YM;class XM extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>QM},{no:2,name:"patch",kind:"message",T:()=>wh}])}}new XM;class ZM extends _{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>wh}])}}new ZM;class eO 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 js=new eO;class tO 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 nO=new tO;class iO extends _{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>js},{no:2,name:"next",kind:"scalar",T:8}])}}const sO=new iO;class rO extends _{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>js}])}}const my=new rO;class aO extends _{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const oO=new aO;class cO extends _{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>js}])}}const _h=new cO;class dO 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 lO=new dO;class uO extends _{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>js}])}}const Ih=new uO;class hO 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 pO=new hO;class mO extends _{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>js}])}}new mO;class fO 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 gO=new fO;class vO 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 yO=new vO;class EO 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 Id=new EO;class SO extends _{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>js}])}}const Cd=new SO;class TO 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 bO=new TO;class kO 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 Rd=new kO;class wO 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 _O=new wO;class IO 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 CO=new IO;class RO extends _{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const PO=new RO;class AO 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 MO=new AO;class OO 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 DO=new OO;class NO extends _{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new NO;class LO extends _{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const xO=new LO;class VO extends _{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>js},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const UO=new VO;class BO 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:()=>UO},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const FO=new BO;class jO extends _{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>FO}])}}const Si=new jO;class WO 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 HO=new WO;class qO extends _{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>HO}])}}const GO=new qO;class JO extends _{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const $O=new JO;class KO extends _{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const zO=new KO;class YO extends _{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const QO=new YO;class XO extends _{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const ZO=new XO;class eD 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 tD=new eD;class nD 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 iD=new nD;class sD 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 rD=new sD;class aD 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 oD=new aD;class cD 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 Ch=new cD;class dD 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:()=>Ch}])}}const fy=new dD;class lD 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:()=>Ch}])}}const uD=new lD;class hD 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:()=>Ch}])}}const pD=new hD;class mD 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 fD=new mD;class gD 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 Rh=new gD;class vD extends _{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>Rh}])}}const yD=new vD;class ED 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 gy=new ED;class SD 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 TD=new SD;class bD 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:()=>TD}])}}const vy=new bD;class kD 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 yy=new kD;class wD 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},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const Ey=new wD;class _D extends _{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const Sy=new _D;class ID 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 CD=new ID;class RD extends _{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>CD}])}}const Ph=new RD;class PD extends _{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const AD=new PD;class MD extends _{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const OD=new MD;class DD extends _{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const Ty=new DD;class ND 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:()=>xD},{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 by=new ND;class LD 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:()=>UD}])}}const xD=new LD;class VD extends _{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const UD=new VD;class BD 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 FD=new BD;class jD 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 WD=new jD;class HD extends _{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>by}])}}const Ah=new HD;class qD extends _{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>by}])}}const GD=new qD;class JD 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",Fs]}])}}const ky=new JD;class $D 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(),n=Date.now();return e.seconds=Pe.from(Math.floor(n/1e3)).toBigInt(),e.nanos=n%1e3*1e6,e}toDate(e){return new Date(Pe.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const n=this.create(),i=e.getTime();return n.seconds=Pe.from(Math.floor(i/1e3)).toBigInt(),n.nanos=i%1e3*1e6,n}internalJsonWrite(e,n){let i=Pe.from(e.seconds).toNumber()*1e3;if(i<Date.parse("0001-01-01T00:00:00Z")||i>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 s="Z";if(e.nanos>0){let r=(e.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?s="."+r.substring(0,3)+"Z":r.substring(6)==="000"?s="."+r.substring(0,6)+"Z":s="."+r+"Z"}return new Date(i).toISOString().replace(".000Z",s)}internalJsonRead(e,n,i){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+ru(e)+".");let s=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(!s)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let r=Date.parse(s[1]+"-"+s[2]+"-"+s[3]+"T"+s[4]+":"+s[5]+":"+s[6]+(s[8]?s[8]:"Z"));if(Number.isNaN(r))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(r<Date.parse("0001-01-01T00:00:00Z")||r>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 i||(i=this.create()),i.seconds=Pe.from(r/1e3).toBigInt(),i.nanos=0,s[7]&&(i.nanos=parseInt("1"+s[7]+"0".repeat(9-s[7].length))-1e9),i}}new $D;class KD extends _{constructor(){super("common.BaseHubMessage",[{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},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9}])}}const Mh=new KD;class zD extends _{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Mh}])}}new zD;class YD extends _{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>Mh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>Mh}])}}new YD;const QD=0,XD=1,ZD=2,eN=3,tN=4,nN=5,iN={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},sN={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},rN={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},aN={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},wy={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,audioActivity:100},oN={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},cN={getUserPresets:0,updateUserPreset:1};function Hr(t,e){return Object.keys(e).reduce((n,i)=>(n[i]=(t<<16)+e[i],n),{})}function _y(t,e){return Object.keys(t).reduce((n,i)=>(n[i]=e|t[i],n),{})}const z=Hr(QD,iN),Ge=Hr(XD,sN),ie=Hr(ZD,rN),Ti=Hr(eN,aN),Ws=Hr(tN,oN),Tn=_y(wy,16777216),Nn=_y(wy,50331648),Pd=Hr(nN,cN);var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,Oh=(t,e,n,i)=>{for(var s=i>1?void 0:i?lN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&dN(e,n,s),s},Hs,Iy;const Dh=(Iy=class{constructor(t){S(this,Hs,void 0),T(this,Hs,t)}createChannel(t,e,n,i="public",s=!1){return p(this,null,function*(){const r={displayName:t,targetUserIds:e,displayPictureUrl:n,visibility:i,isDirectMessage:s};s&&(r.visibility="private");const a=yield o(this,Hs).sendMessagePromise(Ws.createChatChannel,MO.toBinary(r)),c=Si.fromBinary(a.payload).chatChannels;return Dh.formatChannel(c[0])})}updateChannel(t,e){return p(this,null,function*(){const n=yield o(this,Hs).sendMessagePromise(Ws.updateChatChannel,DO.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),i=Si.fromBinary(n.payload).chatChannels;return Dh.formatChannel(i[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:n}=t,i=ee(H({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=n==null?void 0:n.unreadCount)!=null?e:0});return n!=null&&n.message&&(i.latestMessage=bi.formatSocketServiceMessage(n.message)),delete i.chatChannelId,delete i.targetUserIds,delete i.latestMessageAndUnreadCount,i}getChannelMembers(t){return p(this,null,function*(){try{const e=yield o(this,Hs).sendMessagePromise(Ws.getChannelMembers,xO.toBinary({chatChannelId:t}));return GO.fromBinary(e.payload).channelMembers.map(n=>{var i=n,{id:s}=i,r=Fc(i,["id"]);return ee(H({},r),{userId:s})})}catch(e){return[]}})}on(t,e){let n,i;switch(t){case Ws.createChatChannel:{n=Si.fromBinary.bind(Si),i=Si.create();break}case Ws.updateChatChannel:{n=Si.fromBinary.bind(Si),i=Si.create();break}}if(!n){m.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}o(this,Hs).on(t,({payload:s})=>{let r=i;try{r=n(s)}catch(a){m.error("ChatChannelSocketHandler::on::binary_decode_error",{error:a})}return e(r)})}},Hs=new WeakMap,Iy);let qs=Dh;Oh([k.trace("ChatChannelHandler.createChannel")],qs.prototype,"createChannel",1),Oh([k.trace("ChatChannelHandler.updateChannel")],qs.prototype,"updateChannel",1),Oh([k.trace("ChatChannelHandler.getChannelMembers")],qs.prototype,"getChannelMembers",1);var uN=Object.defineProperty,hN=Object.getOwnPropertyDescriptor,Ln=(t,e,n,i)=>{for(var s=i>1?void 0:i?hN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&uN(e,n,s),s},Wt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(Wt||{}),Ht;class bn{constructor(e){S(this,Ht,void 0),T(this,Ht,e)}getChatMessages(){return o(this,Ht).sendMessagePromise(Ge.getMessages)}getChatMessagesPaginated(e,n,i,s=0,r=""){return p(this,null,function*(){const a={timeStamp:e,size:n,from:s,reversed:i,channelId:r},c=yield o(this,Ht).sendMessagePromise(Ge.getPaginatedMessages,nO.toBinary(a));return c.payload?sO.fromBinary(c.payload):{messages:[],next:!1}})}sendMessageToRoom(e,n){const i={payloadType:n,payload:e};o(this,Ht).sendMessage(Ge.sendMessageToRoom,oO.toBinary(i))}sendMessageToPeers(e,n,i){const s={payloadType:n,peerIds:i,payload:e};o(this,Ht).sendMessage(Ge.sendMessageToPeers,lO.toBinary(s))}sendMessageToChannel(e,n,i){const s={payloadType:n,channelId:i,payload:e};o(this,Ht).sendMessage(Ge.sendMessageToChannel,pO.toBinary(s))}sendMessage(e,n,i,s){if(s&&this.sendMessageToChannel(e,n,s),i&&i.length>0){this.sendMessageToPeers(e,n,i);return}this.sendMessageToRoom(e,n)}editMessage(e,n,i,s,r){return p(this,null,function*(){const a={chatId:e,payloadType:i,payload:n};s&&(a.channelId=s),r!==void 0&&(a.pinned=r);const c=yield o(this,Ht).sendMessagePromise(Ge.editMessage,gO.toBinary(a));return Cd.fromBinary(c.payload).message})}deleteMessage(e,n){return p(this,null,function*(){const i={chatId:e};n&&(i.channelId=n);const s=yield o(this,Ht).sendMessagePromise(Ge.deleteMessage,bO.toBinary(i)),r=Rd.fromBinary(s.payload);return H({id:r.chatId},r.channelId?{channelId:r.channelId}:{})})}searchMessages(e,n){return p(this,null,function*(){var i,s,r;const a={searchTerm:e,timeStamp:(i=n.timestamp)!=null?i:Date.now(),size:(s=n.size)!=null?s:75,from:0,reversed:(r=n.reversed)!=null?r:!0};n.channelId&&(a.channelId=n.channelId);try{const c=yield o(this,Ht).sendMessagePromise(Ge.searchChannelMessages,_O.toBinary(a));return my.fromBinary(c.payload).messages}catch(c){return[]}})}getAllChannels(){return p(this,null,function*(){try{const e=yield o(this,Ht).sendMessagePromise(Ge.getAllChatChannels);return Si.fromBinary(e.payload).chatChannels.map(qs.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,n){return p(this,null,function*(){const i=yield o(this,Ht).sendMessagePromise(Ge.markChannelIndexAsRead,CO.toBinary({channelId:e,userId:n.userId,channelIndex:n.channelIndex}));return PO.fromBinary(i.payload).channelIndex})}setPinState(e,n){return p(this,null,function*(){const i={chatId:e.id,pinned:n,channelId:e.channelId},s=yield o(this,Ht).sendMessagePromise(Ge.pinMessage,yO.toBinary(i));return Id.fromBinary(s.payload)})}on(e,n){let i,s;switch(e){case Ge.sendMessageToRoom:{i=_h.fromBinary.bind(_h),s=_h.create();break}case Ge.sendMessageToPeers:{i=Ih.fromBinary.bind(Ih),s=Ih.create();break}case Ge.editMessage:{i=Cd.fromBinary.bind(Cd),s=Cd.create();break}case Ge.pinMessage:{i=Id.fromBinary.bind(Id),s=Id.create();break}case Ge.deleteMessage:{i=Rd.fromBinary.bind(Rd),s=Rd.create();break}}if(!i){m.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}o(this,Ht).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}Ht=new WeakMap,Ln([k.trace("SocketService.getChatMessages")],bn.prototype,"getChatMessages",1),Ln([k.trace("SocketService.getChatMessagesPaginated")],bn.prototype,"getChatMessagesPaginated",1),Ln([k.trace("SocketService.sendMessageToRoom")],bn.prototype,"sendMessageToRoom",1),Ln([k.trace("SocketService.sendMessageToPeers")],bn.prototype,"sendMessageToPeers",1),Ln([k.trace("SocketService.sendMessageToChannel")],bn.prototype,"sendMessageToChannel",1),Ln([k.trace("SocketService.sendMessage")],bn.prototype,"sendMessage",1),Ln([k.trace("SocketService.editMessage")],bn.prototype,"editMessage",1),Ln([k.trace("SocketService.deleteMessage")],bn.prototype,"deleteMessage",1),Ln([k.trace("SocketService.searchMessages")],bn.prototype,"searchMessages",1),Ln([k.trace("SocketService.getAllChannels")],bn.prototype,"getAllChannels",1),Ln([k.trace("SocketService.markLastReadMessage")],bn.prototype,"markLastReadMessage",1);function pN(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function xn(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>xn(n));const e={};return Object.keys(t).forEach(n=>{const i=iu(n)?n:pN(n);e[i]=xn(t[n])}),e}function mN(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Cy(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>Cy(n));const e={};return Object.keys(t).forEach(n=>{const i=iu(n)?n:mN(n);e[i]=t[n]}),e}function Ad(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(n=>{if(typeof t[n]!="function"){if(typeof t[n]=="object"){Ad(t[n],e[n]={});return}e[n]=t[n]}}),e)}class Ry{constructor(e){y(this,"defaults"),this.defaults={baseURL:e.baseURL,headers:{common:{}},timeout:e.timeout,retry:e.retry,retryDelay:e.retryDelay}}buildURL(e,n){const{baseURL:i}=this.defaults,s=e.startsWith("http")?e:`${i}${e.startsWith("/")?e:`/${e}`}`;if(n){const r=new URLSearchParams;return Object.entries(n).forEach(([a,c])=>{r.append(a,c)}),`${s}${s.includes("?")?"&":"?"}${r.toString()}`}return s}request(e){return p(this,null,function*(){var n;const i=((n=e.method)==null?void 0:n.toUpperCase())||"GET",s=this.buildURL(e.url||"",e.params),r=H(H({},this.defaults.headers.common),e.headers);i!=="GET"&&i!=="HEAD"&&e.data&&!r["Content-Type"]&&(r["Content-Type"]="application/json");const a=r["Content-Type"]==="application/json"?JSON.stringify(e.data):e.data,c={method:i,headers:r,body:i!=="GET"&&i!=="HEAD"&&e.data?a:void 0},d=e.timeout||this.defaults.timeout,h=e.retry!==void 0?e.retry:this.defaults.retry,u=e.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,E=setTimeout(()=>g.abort(),d);c.signal=g.signal;const b=yield fetch(s,c);clearTimeout(E);let w=null;const M=b.headers.get("content-type");M&&M.includes("application/json")?w=yield b.json():w=yield b.text();const D={};b.headers.forEach((Y,X)=>{D[X]=Y});const F={data:w,status:b.status,statusText:b.statusText,headers:D,config:e};if(!b.ok)throw F;return F}catch(g){if(g instanceof Error&&h>0)return yield new Promise(E=>setTimeout(E,u)),this.defaults.baseURL==="https://api.dyte.io"?this.defaults.baseURL="https://api.cluster.dyte.in":this.defaults.baseURL==="https://api.cluster.dyte.in"&&(this.defaults.baseURL="https://api.dyte.io"),this.request(ee(H({},e),{retry:h-1}));throw g}})}get(e){return p(this,arguments,function*(n,i={}){return this.request(ee(H({},i),{method:"GET",url:n}))})}post(e,n){return p(this,arguments,function*(i,s,r={}){return this.request(ee(H({},r),{method:"POST",url:i,data:s}))})}put(e,n){return p(this,arguments,function*(i,s,r={}){return this.request(ee(H({},r),{method:"PUT",url:i,data:s}))})}}const fN=3,gN=30,vN=8e3;class yN{constructor(e,n){y(this,"ipInfo"),y(this,"fetchClient"),y(this,"requests"),y(this,"roomName"),y(this,"roomUUID"),y(this,"authToken"),y(this,"organizationId"),y(this,"iceServers"),y(this,"pluginInformation"),y(this,"userDetails"),y(this,"roomDetails"),y(this,"context"),this.context=e;const{timeout:i=vN,retry:s=fN,retryDelay:r=gN,baseURL:a="https://api.dyte.io",authToken:c,cachedUserDetails:d}=n||{};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=new Ry({baseURL:a,timeout:i,retry:s,retryDelay:r,responseType:"json"}),this.fetchClient=new Ry({baseURL:"",timeout:i,retry:s,retryDelay:r,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const h=this.requests.request.bind(this.requests);this.requests.request=u=>p(this,null,function*(){var g,E,b,w,M;try{k.injectContext(this.requests.defaults.headers.common);const D=yield h(u);return u.url!==k.logsEndpoint&&m.debug("xhr::fetch",{networkCall:{status:D.status,statusText:D.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),D}catch(D){throw D?(((g=D.config)==null?void 0:g.url)!==k.logsEndpoint&&m.error("xhr::fetch",{error:D,networkCall:{status:D.status,statusText:D.statusText,baseURL:((E=D.config)==null?void 0:E.baseURL)||this.requests.defaults.baseURL,url:(b=D.config)==null?void 0:b.url,retries:(w=D.config)==null?void 0:w.retry,method:(M=D.config)==null?void 0:M.method,isOnline:navigator.onLine?"online":"offline"}}),new O(D.message||"Network request failed","0011")):new O("Unknown network error occurred","0011")}})}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,n){const{bearer:i}=n||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=i?`Bearer ${e}`:e}setHeader(e,n){this.requests.defaults.headers.common[e]=n}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var EN=Object.defineProperty,SN=Object.getOwnPropertyDescriptor,kn=(t,e,n,i)=>{for(var s=i>1?void 0:i?SN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&EN(e,n,s),s};class dn extends yN{constructor(e,n){super(e,n),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return p(this,null,function*(){var e;const{peerId:n}=this;try{const i=yield vu.getIPDetails({peerId:n,apiHostnames:xv(this.context),logger:m});if(m.log("ipInfo",{ipInfo:i}),((e=i==null?void 0:i.loc)==null?void 0:e.length)>5)return i;throw Error("Insufficient data")}catch(i){m.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:i.name,message:i.message}});return}})}getICEServers(){return p(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:n}=(yield this.requests.get("/iceservers")).data;if(e)return(n==null?void 0:n.length)>0&&(this.iceServers=n),n})}getPlugins(){return p(this,null,function*(){var e,n,i,s,r,a,c;if(this.pluginInformation)return this.pluginInformation;const{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data,h=((n=(e=re.getValue(ue.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:n.split(","))||[],u=d.reduce((g,E)=>(g[h.includes(E.id)?"v1":"v2"].push(ee(H({},E),{name:E.name.replace("v2","")})),g),{v1:[],v2:[]});return(r=(s=(i=this.context.getValue("modules"))==null?void 0:i.devTools)==null?void 0:s.plugins)!=null&&r.length&&((c=(a=this.context.getValue("modules"))==null?void 0:a.devTools)==null||c.plugins.forEach(g=>{var E,b,w;const M=ee(H({},$a),{tags:[...$a.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(E=g.picture)!=null?E:$a.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(b=g.description)!=null?b:$a.description,staggered:(w=g.staggered)!=null?w:$a.staggered});u.v2.push(M)})),u.v2})}getPluginDetails(e){return p(this,null,function*(){const{plugin:n}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return n})}getPluginConfig(e){return p(this,null,function*(){return(yield this.fetchClient.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return p(this,null,function*(){const n={peerId:this.peerId},{token:i}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,n)).data.data;return i})}getPresignedUrls(e,n){return p(this,null,function*(){const i=Ed(this.context,"chat_upload_expiry"),s={roomUUID:this.roomUUID,filename:e,expiry:typeof i=="number"?i:void 0};re.hasFeature(ue.FEAT_CHAT_SDK)&&(s.viewType=n);const{getLocation:r,putLocation:a}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",s)).data.data;return{getLocation:r,putLocation:a}})}uploadFile(e,n){return p(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(n,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){m.error(`sendFileMessage::${i}`)}else yield this.fetchClient.put(n,e,{headers:{"Content-Type":e.type}})})}startLivestreaming(e){return p(this,arguments,function*({manualIngestion:n}){const i=xn(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!n})).data.data;return{playbackUrl:i.playbackUrl,status:i.status,manualIngest:i.manualIngest,ingestionCredentials:i.streamKey?{ingestionServer:i.ingestServer,streamKey:i.streamKey}:null}})}stopLivestreaming(){return p(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return p(this,null,function*(){const e=xn((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 p(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return xn(e)})}startRecording(e,n){return p(this,null,function*(){return(yield this.requests.post("/v2/recordings",ee(H({},Cy(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!n}))).data.data.id})}updateRecording(e,n){return p(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:n})})}getActiveRecording(){return p(this,null,function*(){const{status:e,id:n}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:n}})}getActiveTranscript(){return p(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.fetchClient.get(e)).data}}catch(n){throw new O("Cant fetch transcript s3 url","1801")}})}getRoomNodeData(){return p(this,null,function*(){const e=yield this.getIPDetails();if(this.ipInfo=e,this.roomDetails)return this.roomDetails;const{roomNodeLink:n,title:i,useHiveMedia:s,sfu:r}=xn((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:n,meetingTitle:i,useHiveMedia:s!=null?s:!1,sfu:r}})}}kn([k.trace("APIClient.getIPDetails")],dn.prototype,"getIPDetails",1),kn([k.trace("APIClient.getICEServers")],dn.prototype,"getICEServers",1),kn([k.trace("APIClient.getPlugins")],dn.prototype,"getPlugins",1),kn([k.trace("APIClient.startLivestreaming")],dn.prototype,"startLivestreaming",1),kn([k.trace("APIClient.stopLivestreaming")],dn.prototype,"stopLivestreaming",1),kn([k.trace("APIClient.getActiveLivestream")],dn.prototype,"getActiveLivestream",1),kn([k.trace("APIClient.getUserDetails")],dn.prototype,"getUserDetails",1),kn([k.trace("APIClient.startRecording")],dn.prototype,"startRecording",1),kn([k.trace("APIClient.stopRecording")],dn.prototype,"updateRecording",1),kn([k.trace("APIClient.getActiveRecording")],dn.prototype,"getActiveRecording",1),kn([k.trace("APIClient.getActiveTranscript")],dn.prototype,"getActiveTranscript",1),kn([k.trace("APIClient.getRoomNodeData")],dn.prototype,"getRoomNodeData",1);let Nh;function TN(t,e){return Nh=new dn(t,e),Nh}function It(){return Nh}function bN(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
20
- ${t}`}const qr={maxInvocations:5,period:1};function en(t,e){return function(n,i,s){const r=s.value;let a=0,c=Date.now();return s.value=function(...d){const h=Date.now(),u=e?this[e]:t;if(h-c>u.period*1e3&&(c=h,a=0),a>=u.maxInvocations)throw new O(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return a+=1,r.apply(this,d)},s}}var kN=Object.defineProperty,wN=Object.getOwnPropertyDescriptor,Dt=(t,e,n,i)=>{for(var s=i>1?void 0:i?wN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&kN(e,n,s),s};const _N=["text","image","file","custom","poll"],Md={maxInvocations:180,period:60};var he,Gr,ft,Jr,Od,Lh,Py,Dd,xh,Ay;let yt=(Ay=class extends cn{constructor(t,e,n,i,s){super(),S(this,Lh),S(this,Dd),y(this,"messages"),y(this,"channels",[]),S(this,he,void 0),S(this,Gr,void 0),S(this,ft,void 0),S(this,Jr,void 0),S(this,Od,void 0),y(this,"maxTextLimit",2e3),T(this,Od,t),T(this,ft,e),T(this,Jr,n),T(this,he,i),T(this,Gr,s),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,n){return p(this,arguments,function*(i,s,r,a={}){switch(i.type){case"text":{const c=a.replyTo&&a.replyTo.type==="text"?bN(i.message,a.replyTo.message):i.message;yield this.sendTextMessageInternal(c,s,r);break}case"image":yield this.sendImageMessageInternal(i.image,s,r);break;case"file":yield this.sendFileMessageInternal(i.file,s,r);break;default:m.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:i.type}});break}})}sendTextMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(t.length>this.maxTextLimit)throw new O("Max character limit breached","0503");if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.text))throw m.error("sendTextMessage::private_chat_permission_denied"),new O("Could not send message to private chat.","0501")}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.text))throw m.error("sendTextMessage::public_chat_permission_denied"),new O("Could not send message to public chat.","0501");if(!t)throw m.error("sendTextMessage::message_can_not_be_empty"),new O("Message can not be empty.","0502");if(n){o(this,ft).sendMessageToChannel(t,Wt.TEXT,n);return}let h=[];e&&e.length>0&&(e.push(o(this,he).id),h=o(this,Gr).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),h.push(o(this,he).userId)),o(this,ft).sendMessage(t,Wt.TEXT,e)})}sendImageMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.files)){m.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){m.error("sendImageMessage::permission_denied");return}if(!t){m.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){m.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=It(),{getLocation:u,putLocation:g}=yield h.getPresignedUrls(t.name,o(this,he).config.viewType);if(yield h.uploadFile(t,g),n){o(this,ft).sendMessageToChannel(u,Wt.IMAGE,n);return}let E=[];e&&e.length>0&&(e.push(o(this,he).id),E=o(this,Gr).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),E.push(o(this,he).userId)),o(this,ft).sendMessage(u,Wt.IMAGE,e)}catch(h){throw new O("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(e&&e.length>0){if(!((i=o(this,he).permissions)!=null&&i.chatPrivate.canSend)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.files)){m.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){m.error("sendFileMessage::permission_denied");return}if(!t){m.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=It(),{getLocation:u,putLocation:g}=yield h.getPresignedUrls(t.name,o(this,he).config.viewType);if(yield h.uploadFile(t,g),n){o(this,ft).sendMessageToChannel(JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0}),Wt.FILE,n);return}let E=[];e&&e.length>0&&(e.push(o(this,he).id),E=o(this,Gr).joined.toArray().filter(w=>e.includes(w.id)).map(w=>w.userId),E.push(o(this,he).userId));const b=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});o(this,ft).sendMessage(b,Wt.FILE,e)}catch(h){throw new O("Error sending file message.","0500")}})}get rateLimits(){return Md}updateRateLimits(t,e){Md.maxInvocations=t,Md.period=e}sendTextMessage(t,e){return p(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return p(this,null,function*(){var n,i,s,r,a,c,d,h,u,g,E,b,w,M,D;if(e&&e.length>0){if(!((n=o(this,he).permissions)!=null&&n.chatPrivate.canSend)||!((i=o(this,he).permissions)!=null&&i.chatPrivate.files)||!((s=o(this,he).permissions)!=null&&s.chatPrivate.text)){m.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((u=(h=o(this,he).permissions)==null?void 0:h.chatPublic)!=null&&u.text)){m.error("sendCustomMessage::permission_denied");return}const F=X=>p(this,null,function*(){try{if(typeof X=="string")return{link:X};const A=It(),{getLocation:J,putLocation:me}=yield A.getPresignedUrls(X.name,o(this,he).config.viewType);return yield A.uploadFile(X,me),{link:J,type:X.type,name:X.name,size:X.size}}catch(A){throw new O("Error sending image message.","0500")}}),Y=ee(H({},t),{files:yield Promise.all((E=(g=t.files)!=null?g:[])==null?void 0:E.map(X=>p(this,null,function*(){return F(X)}))),images:yield Promise.all((w=(b=t.images)!=null?b:[])==null?void 0:w.map(X=>p(this,null,function*(){return F(X)}))),videos:yield Promise.all((D=(M=t.videos)!=null?M:[])==null?void 0:D.map(X=>p(this,null,function*(){return F(X)})))});o(this,ft).sendMessage(JSON.stringify(Y),Wt.CUSTOM,e)})}sendImageMessage(t,e){return p(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return p(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return p(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,n){return p(this,null,function*(){var i,s,r,a,c,d;if(((s=(i=o(this,he).permissions)==null?void 0:i.chatMessage)==null?void 0:s.canEdit)==="NONE")throw new O("Not permitted to edit messages","0501");if(!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,he).permissions)==null?void 0:c.chatPublic)!=null&&d.text)){m.error("editTextMessage::permission_denied");return}if(!e){m.error("editTextMessage::message_can_not_be_empty");return}o(this,ft).editMessage(t,e,Wt.TEXT,n)})}editImageMessage(t,e,n){return p(this,null,function*(){var i,s,r,a;if(!((s=(i=o(this,he).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.files)){m.error("editImageMessage::permission_denied");return}if(!e){m.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){m.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const c=It(),{getLocation:d,putLocation:h}=yield c.getPresignedUrls(e.name,o(this,he).config.viewType);yield c.uploadFile(e,h),o(this,ft).editMessage(t,d,Wt.IMAGE,n)}catch(c){throw new O("Error editing image message.","0500")}})}editFileMessage(t,e,n){return p(this,null,function*(){var i,s,r,a;if(!((s=(i=o(this,he).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((a=(r=o(this,he).permissions)==null?void 0:r.chatPublic)!=null&&a.files)){m.error("sendFileMessage::permission_denied");return}if(!e){m.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=It(),{getLocation:d,putLocation:h}=yield c.getPresignedUrls(e.name,o(this,he).config.viewType);yield c.uploadFile(e,h),o(this,ft).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Wt.FILE,n)}catch(c){throw new O("Error editing file message.","0500")}})}editMessage(t,e,n){return p(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,n);break}case"image":{this.editImageMessage(t,e.image,n);break}case"file":{this.editFileMessage(t,e.file,n);break}default:{m.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return p(this,null,function*(){var n,i;if(((i=(n=o(this,he).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new O("Not permitted to delete messages","0501");o(this,ft).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 p(this,null,function*(){if(!o(this,Dd,xh))throw new O("Can`t pin message without joining room","0505");if(!o(this,he).permissions.pinParticipant)throw new O("You do not have permission to pin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,ft).setPinState(e,!0);return}throw new O(`No message found with id: ${t}`,"0504")})}unpin(t){return p(this,null,function*(){if(!o(this,Dd,xh))throw new O("Can`t unpin message without joining room","0505");if(!o(this,he).permissions.pinParticipant)throw new O("You do not have permission to unpin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,ft).setPinState(e,!1);return}throw new O(`No message found with id: ${t}`,"0504")})}getMessages(t,e,n,i=0,s=void 0){return p(this,null,function*(){const r=yield o(this,ft).getChatMessagesPaginated(t,e,n,i,s);return{messages:r.messages.map(a=>bi.formatSocketServiceMessage(a)),next:r.next}})}createChannel(t,e){return p(this,arguments,function*(n,i,s={}){var r;const a=(r=o(this,he).permissions)==null?void 0:r.chatChannel;if(a){if(a.canCreate==="NONE")throw new O("Not permitted to create channels","0501");if(s.visibility==="public"&&!(a.canCreate==="PUBLIC"||a.canCreate==="ALL"))throw new O("Not permitted to create public channels","0501");if(s.visibility==="private"&&!(a.canCreate==="PRIVATE"||a.canCreate==="ALL"))throw new O("Not permitted to create private channels","0501")}if(!n||n.trim().length===0)throw new O("channel name cannot be empty.","0510");const c=[...new Set([...i,o(this,he).userId])];return yield o(this,Jr).createChannel(n.trim(),c,s.displayPictureUrl,s.visibility,s.isDirectMessage)})}updateChannel(t,e){var n,i,s,r,a;const c=this.channels.find(u=>u.id===t),d=(n=o(this,he).permissions)==null?void 0:n.chatChannel;if(d){if(d.canUpdate==="NONE")throw new O("Not permitted to update channels","0501");if(c.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new O("Not permitted to update public channels","0501");if(c.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new O("Not permitted to update private channels","0501")}const h={memberIds:(i=e.memberIds)!=null?i:c.memberIds,displayName:(s=e.displayName)!=null?s:c.displayName,displayPictureUrl:(r=e.displayPictureUrl)!=null?r:c.displayPictureUrl,visibility:(a=e.visibility)!=null?a:c.visibility};return o(this,Jr).updateChannel(t,h)}sendMessageToChannel(t,e){return p(this,arguments,function*(n,i,s={}){return this.sendMessageInternal(n,null,i,s)})}getChannelMembers(t){return p(this,null,function*(){return o(this,Jr).getChannelMembers(t)})}searchMessages(t){return p(this,arguments,function*(e,n={}){if(!re.hasFeature(ue.FEAT_CHAT_SDK_SEARCH))throw new O("searchMessages is temporarily disabled!","0506");return(yield o(this,ft).searchMessages(e,n)).map(bi.formatSocketServiceMessage)})}markLastReadMessage(t,e){return p(this,null,function*(){yield o(this,ft).markLastReadMessage(t,e);const n=this.channels.find(i=>i.id===t);if(n){const i=ee(H({},n),{unreadCount:0});this.channels=this.channels.map(s=>s.id===t?i:s),this.emit("channelMessageUpdate",i)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},he=new WeakMap,Gr=new WeakMap,ft=new WeakMap,Jr=new WeakMap,Od=new WeakMap,Lh=new WeakSet,Py=function(){return o(this,Od).getValue("connectionHandler")},Dd=new WeakSet,xh=function(){return o(this,Lh,Py).socketJoined===!0},Ay);Dt([k.trace("DyteChat.sendTextMessage"),en(Md)],yt.prototype,"sendTextMessage",1),Dt([k.trace("DyteChat.sendImageMessage"),en({maxInvocations:20,period:60})],yt.prototype,"sendImageMessage",1),Dt([k.trace("DyteChat.sendFileMessage"),en({maxInvocations:20,period:60})],yt.prototype,"sendFileMessage",1),Dt([k.trace("DyteChat.sendMessage"),en({maxInvocations:180,period:60})],yt.prototype,"sendMessage",1),Dt([k.trace("DyteChat.editTextMessage")],yt.prototype,"editTextMessage",1),Dt([k.trace("DyteChat.editImageMessage")],yt.prototype,"editImageMessage",1),Dt([k.trace("DyteChat.editFileMessage")],yt.prototype,"editFileMessage",1),Dt([k.trace("DyteChat.editMessage")],yt.prototype,"editMessage",1),Dt([k.trace("DyteChat.deleteMessage")],yt.prototype,"deleteMessage",1),Dt([k.trace("DyteChat.createChannel")],yt.prototype,"createChannel",1),Dt([k.trace("DyteChat.updateChannel")],yt.prototype,"updateChannel",1),Dt([k.trace("DyteChat.sendMessageToChannel")],yt.prototype,"sendMessageToChannel",1),Dt([k.trace("DyteChat.getChannelMembers")],yt.prototype,"getChannelMembers",1),Dt([k.trace("DyteChat.searchMessages")],yt.prototype,"searchMessages",1),Dt([k.trace("DyteChat.markLastReadMessage")],yt.prototype,"markLastReadMessage",1),yt=Dt([Ot("0500")],yt);var IN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(t,e,n,i)=>{for(var s=i>1?void 0:i?CN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&IN(e,n,s),s},Vh,My;const Gs=(My=class{constructor(t,e,n,i,s){y(this,"chat"),y(this,"chatSocketHandler"),y(this,"chatChannelSocketHandler"),y(this,"self"),S(this,Vh,void 0),T(this,Vh,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=n,this.chat=new yt(t,e,n,i,s),this.self=i,this.setupEvents()}static init(t,e,n,i,s){return p(this,null,function*(){return new Gs(t,e,n,i,s)})}static formatMessage(t){return ee(H({},t),{time:new Date(t.time),type:_N[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,n={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(n.type){case Wt.TEXT:{n.message=t.payload;break}case Wt.IMAGE:{n.link=t.payload;break}case Wt.FILE:{const{link:i,name:s,size:r}=JSON.parse(t.payload);n.link=i,n.name=s,n.size=r;break}case Wt.CUSTOM:{const{html:i,images:s,message:r,videos:a,files:c}=JSON.parse(t.payload);n.message=r,n.html=i,n.images=s,n.videos=a,n.files=c;break}}return Gs.formatMessage(n)}getChatMessages(){return p(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||re.hasFeature(ue.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=my.fromBinary(t.payload).messages;this.chat.messages=e.map(n=>Gs.formatSocketServiceMessage(n))})}setupEvents(){L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Ge.sendMessageToRoom,t=>{const e=Gs.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const n=this.chat.channels.find(i=>i.id===e.channelId);n&&(n.latestMessage=e,n.unreadCount+=1,this.chat.emit("channelMessageUpdate",n))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Ge.sendMessageToPeers,t=>{const e=Gs.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(Ge.editMessage,t=>{const e=Gs.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const n=this.chat.messages.findIndex(i=>i.id===e.id);n!==-1&&(this.chat.messages[n]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Ge.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(i=>i.id===t.chatId);if(e===-1)return;const[n]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ws.createChatChannel,t=>{const[e]=t.chatChannels,n=qs.formatChannel(e);this.chat.channels.push(n),this.chat.emit("channelCreate",n)}),this.chatSocketHandler.on(Ge.pinMessage,t=>{const e=this.chat.messages.findIndex(i=>i.id===t.chatId);if(e===-1)return;const n=this.chat.messages[e];n.pinned=t.pinned,this.chat.messages[e]=n,this.chat.emit("chatUpdate",{action:"edit",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Ws.updateChatChannel,t=>{const[e]=t.chatChannels,n=qs.formatChannel(e);this.chat.channels=this.chat.channels.map(i=>i.id===n.id?n:i),this.chat.emit("channelUpdate",n)})}},Vh=new WeakMap,My);let bi=Gs;RN([k.trace("ChatController.setupEvents")],bi.prototype,"setupEvents",1);var PN=Object.defineProperty,AN=Object.getOwnPropertyDescriptor,MN=(t,e,n,i)=>{for(var s=i>1?void 0:i?AN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&PN(e,n,s),s},Uh,Oy,Bh,Dy,eo,to,Nd,Ny;let Fh=(Ny=class extends cn{constructor(t,e,n){super(),S(this,Uh),S(this,Bh),y(this,"items"),S(this,eo,void 0),S(this,to,void 0),S(this,Nd,void 0),T(this,Nd,t),T(this,eo,e),T(this,to,n),this.items=[]}create(t,e,n=!1,i=!1){return p(this,null,function*(){if(!o(this,Bh,Dy))throw new O("Can't create polls without joining room","0705");if(!o(this,eo).permissions.polls.canCreate){m.error("DytePolls::create::permission_denied");return}if(!t||!e){m.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){m.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield o(this,to).createPoll(t,e,n,i)})}vote(t,e){return p(this,null,function*(){if(!o(this,eo).permissions.polls.canVote){m.error("DytePolls::vote::permission_denied");return}yield o(this,to).votePoll(t,e)})}},Uh=new WeakSet,Oy=function(){return o(this,Nd).getValue("connectionHandler")},Bh=new WeakSet,Dy=function(){var t;return((t=o(this,Uh,Oy))==null?void 0:t.socketJoined)===!0},eo=new WeakMap,to=new WeakMap,Nd=new WeakMap,Ny);Fh=MN([Ot("0700")],Fh);var ON=Object.defineProperty,DN=Object.getOwnPropertyDescriptor,NN=(t,e,n,i)=>{for(var s=i>1?void 0:i?DN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&ON(e,n,s),s},no,$r,Ly;const Kr=(Ly=class{constructor(t,e,n){y(this,"polls"),S(this,no,void 0),S(this,$r,void 0),this.polls=new Fh(t,e,n),T(this,no,e),T(this,$r,n),this.setupEvents()}static init(t,e,n){return p(this,null,function*(){return new Kr(t,e,n)})}canViewPolls(){return o(this,no).permissions.polls.canView}setupEvents(){const t={[Ti.createPoll]:i=>{i.poll&&this.updatePoll(Kr.formatSocketServicePoll(i.poll))},[Ti.updatePoll]:i=>{i.poll&&this.updatePoll(Kr.formatSocketServicePoll(i.poll))},[Ti.votePoll]:i=>{i.poll&&this.updatePoll(Kr.formatSocketServicePoll(i.poll))}},e=()=>{L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{o(this,$r).on(i,t[i])})},n=()=>{L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{o(this,$r).removeListeners(i)})};o(this,no).permissions.on("permissionsUpdate",i=>p(this,null,function*(){var s;(s=i==null?void 0:i.polls)!=null&&s.canView?(yield this.getPolls(),e()):(this.polls.items=[],n())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(n=>n.id===t.id);if(e>-1){const n=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,n!==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 p(this,null,function*(){const t=yield o(this,$r).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=GD.fromBinary(t.payload);this.polls.items=e.map(n=>Kr.formatSocketServicePoll(n))})}static formatSocketServicePoll(t){const e=t.options.map(n=>({count:n.count,text:n.text,votes:n.votes.map(i=>({id:i.userId,name:i.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}}},no=new WeakMap,$r=new WeakMap,Ly);let xy=Kr;NN([k.trace("PollController.setupEvents")],xy.prototype,"setupEvents",1);var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,VN=(t,e,n,i)=>{for(var s=i>1?void 0:i?xN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&LN(e,n,s),s},Vy=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Vy||{}),io,Ld,jh,zr,xd,Uy;let Wh=(Uy=class extends cn{constructor(t,e,n,i,s){super(),S(this,Ld),y(this,"selfActiveTab"),y(this,"broadcastTabChanges"),S(this,io,void 0),S(this,zr,void 0),S(this,xd,void 0),y(this,"viewType"),y(this,"meetingStartedTimestamp"),y(this,"meetingTitle"),y(this,"sessionId"),T(this,io,t),T(this,zr,e),this.viewType=n,T(this,xd,i),this.meetingTitle=s,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return o(this,Ld,jh).socketState}get mediaState(){return o(this,Ld,jh).mediaState}get meetingId(){return o(this,io).getValue("meetingId")}setBroadcastTabChanges(t){if(!o(this,zr).permissions.canSpotlight)throw m.error("DyteSpotlight::setSpotlighted::permission_denied"),new O("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 n;m.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(n=o(this,zr).permissions)!=null&&n.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){o(this,xd).broadcastMessage("spotlight",{userId:o(this,zr).userId,currentTab:this.selfActiveTab})}},io=new WeakMap,Ld=new WeakSet,jh=function(){return o(this,io).getValue("connectionHandler")},zr=new WeakMap,xd=new WeakMap,Uy);Wh=VN([Ot("0800")],Wh);function UN(t){let e="",n=[""];const i=[n];let s=0,r=0,a=!0,c;for(c of t)c==='"'?(a&&c===e&&(n[s]+=c),a=!a):c===","&&a?c=n[++s]="":c===`
21
- `&&a?(e==="\r"&&(n[s]=n[s].slice(0,-1)),n=i[++r]=[c=""],s=0):n[s]+=c,e=c;return i}var BN=Object.defineProperty,FN=Object.getOwnPropertyDescriptor,By=(t,e,n,i)=>{for(var s=i>1?void 0:i?FN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&BN(e,n,s),s};let Ki=class extends cn{constructor(){super(),y(this,"transcripts"),this.transcripts=[]}static init(t){return p(this,null,function*(){const e=new Ki;try{t&&e.getActiveTranscript()}catch(n){m.error("Error fetching active transcriptions ",n)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[n,i,s,r,a,c]]=UN(t);return{id:Ar(),name:a,peerId:i,userId:s,customParticipantId:r,transcript:c,isPartialTranscript:e,date:new Date(parseInt(n,10)*1e3)}}catch(n){m.error(`Failed to parse transcript: ${t}`,n);return}}static parseTranscripts(t){return t?t.split(`
22
- `).map(e=>Ki.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return p(this,null,function*(){try{const t=It(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Ki.parseTranscripts(e)}catch(t){}})}onTranscript(t){return p(this,null,function*(){var e;const n=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((e=n==null?void 0:n.at(-1))!=null&&e.isPartialTranscript){const i=n.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};By([k.trace("DyteAi.getActiveTranscript")],Ki.prototype,"getActiveTranscript",1),Ki=By([Ot("0000")],Ki);var jN=Object.defineProperty,WN=Object.getOwnPropertyDescriptor,HN=(t,e,n,i)=>{for(var s=i>1?void 0:i?WN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&jN(e,n,s),s},Js,so,Hh,Fy;const jy=(Fy=class{constructor(t,e,n,i,s,r){y(this,"meta"),y(this,"ai"),S(this,Js,void 0),S(this,so,void 0),y(this,"aiSocketHandler"),S(this,Hh,void 0),T(this,Hh,t),this.meta=new Wh(t,e,e.config.viewType,n,r),this.ai=i,T(this,Js,e),T(this,so,n),this.aiSocketHandler=s,e.config.viewType!==Ft.Chat&&this.setupEvents()}static init(t,e,n,i,s){return p(this,null,function*(){const r=yield Ki.init(e.permissions.transcriptionEnabled);return new jy(t,e,n,r,i,s)})}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,Vy.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){L.on(x.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),L.on(x.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),L.on(x.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const n=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!n){const i=new Date(t*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),L.on(x.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),o(this,Js).permissions.canSpotlight&&(m.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&o(this,so).broadcastMessage("spotlight",{userId:o(this,Js).userId,currentTab:this.meta.selfActiveTab})),L.on(x.PEER_JOINED_INTERNAL,t=>p(this,null,function*(){o(this,Js).permissions.canSpotlight&&this.meta.selfActiveTab&&o(this,so).broadcastToPeers("spotlight",[t.id],{userId:o(this,Js).userId,currentTab:this.meta.selfActiveTab})})),L.on(x.ROOM_MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=H(H({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;m.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),L.on(x.MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=H(H({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;m.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),this.aiSocketHandler.on(z.transcript,t=>{const{meetingId:e,transcript:n,isPartial:i}=t,s=Ki.parseTranscript(n,i);if(!s){m.warn("Received empty transcript data");return}this.ai.onTranscript(s),this.meta.emit("transcript",s);const{peerId:r,name:a,transcript:c}=s;m.debug(`${e} Received transcript for peer ${r} - ${a}: ${c}`)})}},Js=new WeakMap,so=new WeakMap,Hh=new WeakMap,Fy);let Wy=jy;HN([k.trace("MetaController.setupEvents")],Wy.prototype,"setupEvents",1);var qN=Object.defineProperty,GN=Object.getOwnPropertyDescriptor,$s=(t,e,n,i)=>{for(var s=i>1?void 0:i?GN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&qN(e,n,s),s},Vn,ro,be,Vd,ki,si,Ud,qh,ao,Bd;class zi extends cn{constructor(e,n,i,s,r){super(),S(this,Ud),S(this,ao),S(this,Vn,void 0),S(this,ro,void 0),S(this,be,void 0),S(this,Vd,void 0),S(this,ki,void 0),S(this,si,void 0),T(this,si,e),T(this,Vn,s),T(this,ro,r),T(this,be,n),T(this,Vd,i),T(this,ki,[]),this.setupEvents()}get status(){return o(this,si).getValue("stageStatus")}setupEvents(){const e={[x.GET_STAGE_REQUESTS]:s=>p(this,null,function*(){T(this,ki,s)}),[x.UPDATE_STAGE_REQUESTS]:s=>p(this,[s],function*({add:r}){const a=o(this,ki).length,{stageRequests:c}=this.getAccessRequests();(r||c.length>a)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},n=()=>{Object.entries(e).forEach(([s,r])=>{L.onAsync(s,r)})},i=()=>{Object.entries(e).forEach(([s,r])=>{L.removeListener(s,r)})};o(this,be).permissions.on("permissionsUpdate",s=>{const{canAcceptProductionRequests:r}=s;r!==void 0&&(o(this,be).permissions.acceptStageRequests?(n(),o(this,Vn).getStageRequests()):(i(),T(this,ki,[]),this.emit("stageAccessRequestUpdate",o(this,ki))))}),o(this,be).permissions.acceptStageRequests&&n()}getAccessRequests(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::get_access_request::permission_denied"),new O("You do not have permission to perform this action","2001");const e=o(this,Vd).joined.toArray().filter(n=>n.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(n=>({displayName:n.name,userId:n.userId,peerId:n.id}));return T(this,ki,e),{stageRequests:o(this,ki)}}requestAccess(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new O(`Unable to request access you are currently ${this.status}`,"2006");if(o(this,be).permissions.stageAccess===se.Allowed){Q(this,ao,Bd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}o(this,Vn).requestAccess(),Q(this,ao,Bd).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");o(this,Vn).cancelRequestAccess(),Q(this,ao,Bd).call(this,"OFF_STAGE")})}grantAccess(e){if(!o(this,be).roomJoined)throw new O("Can`t grant for participant without joining room");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::grant_access::permission_denied"),new O("You do not have permission to perform this action","2001");return o(this,Vn).grantAccess(e)}denyAccess(e){if(!o(this,be).roomJoined)throw new O("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::deny_access::permission_denied"),new O("You do not have permission to perform this action","2001");return o(this,Vn).denyAccess(e)}join(){return p(this,null,function*(){const e=o(this,si).getValue("viewType");if(this.status==="ON_STAGE")throw new O("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||o(this,be).permissions.stageAccess===se.NotAllowed)throw new O(`Unable to join stage you are currently ${this.status}`,"2006");if(yield o(this,Vn).joinStage(),e===Ft.Livestream){yield o(this,ro).joinRoom(o(this,be));const{peers:n}=yield o(this,ro).getStagePeers();L.emit(x.SOCKET_PEERS,n)}o(this,si).setValue("stageStatus","ON_STAGE"),o(this,be).audioEnabled&&o(this,Ud,qh).shareMic(o(this,be).audioTrack),o(this,be).videoEnabled&&o(this,Ud,qh).shareWebcam(o(this,be).videoTrack)})}leave(){return p(this,null,function*(){if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new O(`Unable to leave stage you are currently ${this.status}`,"2006");o(this,be).setIsPinned(!1),yield o(this,Vn).leaveStage(o(this,be).userId),o(this,si).setValue("stageStatus","OFF_STAGE",!1),yield L.emitAsync(x.LEAVE_MEDIA_ROOM,"stageLeft"),o(this,si).notify("stageStatus")})}kick(e){return p(this,null,function*(){if(!o(this,be).roomJoined)throw new O("Can`t kick participant without joining room","2005");if(!o(this,be).permissions.stageEnabled)throw m.error("DyteStage::stage_disabled"),new O("Stage is disabled","2003");if(!o(this,be).permissions.acceptStageRequests)throw m.error("DyteStage::kick::permission_denied"),new O("You do not have permissions for kick","2001");return o(this,Vn).kick(e)})}}Vn=new WeakMap,ro=new WeakMap,be=new WeakMap,Vd=new WeakMap,ki=new WeakMap,si=new WeakMap,Ud=new WeakSet,qh=function(){return o(this,si).getValue("roomNodeClient")},ao=new WeakSet,Bd=function(t){return p(this,null,function*(){this.status!==t&&o(this,si).setValue("stageStatus",t)})},$s([k.trace("DyteStage.getStageRequests")],zi.prototype,"getAccessRequests",1),$s([k.trace("DyteStage.requestAccess")],zi.prototype,"requestAccess",1),$s([k.trace("DyteStage.cancelRequestAccess")],zi.prototype,"cancelRequestAccess",1),$s([k.trace("DyteStage.grantAccess")],zi.prototype,"grantAccess",1),$s([k.trace("DyteStage.denyAccess")],zi.prototype,"denyAccess",1),$s([k.trace("DyteStage.joinStage")],zi.prototype,"join",1),$s([k.trace("DyteStage.leaveStage")],zi.prototype,"leave",1);function JN(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Gh(t){switch(t){case Ei.UNSPECIFIED:return"OFF_STAGE";case Ei.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Ei.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Ei.OFF_STAGE:return"OFF_STAGE";case Ei.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var $N=Object.defineProperty,KN=Object.getOwnPropertyDescriptor,zN=(t,e,n,i)=>{for(var s=i>1?void 0:i?KN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&$N(e,n,s),s},Ks,Yr,zs,Fd,Yi;class Hy{constructor(e,n,i,s,r){y(this,"stage"),S(this,Ks,void 0),S(this,Yr,void 0),S(this,zs,void 0),S(this,Fd,0),S(this,Yi,void 0),T(this,Yi,e),this.stage=new zi(e,s,r,n,i),T(this,zs,n),T(this,Ks,s),T(this,Yr,r),this.setupEvents()}setupEvents(){o(this,Yi).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),o(this,zs).on(z.grantStageAccess,()=>{o(this,Ks).permissions.stageAccess!==se.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),o(this,zs).on(z.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===o(this,Ks).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),o(this,zs).on(z.denyStageAccess,()=>{o(this,Ks).permissions.stageAccess!==se.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),o(this,zs).on(z.getStageRequests,e=>p(this,null,function*(){var n;if(o(this,Ks).permissions.stageAccess!==se.Allowed)return;const i=(n=e==null?void 0:e.stageRequests)!=null?n:[];yield L.emitAsync(x.GET_STAGE_REQUESTS,i),o(this,Fd)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),T(this,Fd,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return o(this,Yr).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return p(this,null,function*(){this.stage.status!==e&&o(this,Yi).setValue("stageStatus",e)})}selfStageStatusHandler(e){const n=Gh(e.stageType),i=o(this,Yi).getValue("stageStatus");if(i!==n)switch(e.stageType){case 1:o(this,Yi).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(i);break;case 0:case 4:default:o(this,Yi).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return p(this,null,function*(){const n=o(this,Yr).joined.get(e.peerId),i=o(this,Yr).viewMode==="ACTIVE_GRID";if(!n){m.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:n.setStageStatus("ON_STAGE"),i&&L.emit(x.UPDATE_ACTIVE);break;case 2:n.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:n.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:n.setStageStatus("OFF_STAGE"),i&&L.emit(x.UPDATE_ACTIVE);break}L.emit(x.UPDATE_PEER_STAGE_STATUS,{id:n.id,status:n.stageStatus})})}}Ks=new WeakMap,Yr=new WeakMap,zs=new WeakMap,Fd=new WeakMap,Yi=new WeakMap,zN([k.trace("DyteStage.setupEvents")],Hy.prototype,"setupEvents",1);var YN=Object.defineProperty,QN=Object.getOwnPropertyDescriptor,jd=(t,e,n,i)=>{for(var s=i>1?void 0:i?QN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&YN(e,n,s),s};const $e={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 qt,wn,oo,co,Qi,lo,Qr,uo,qy;let Xr=(qy=class extends jr{constructor(t,{baseURL:e,createdAt:n,description:i,id:s,name:r,organizationId:a,picture:c,private:d,published:h,staggered:u,tags:g,type:E,updatedAt:b},w,M,D,F,Y){super(),S(this,qt,void 0),y(this,"baseURL"),y(this,"createdAt"),y(this,"description"),y(this,"id"),y(this,"name"),S(this,wn,void 0),S(this,oo,void 0),S(this,co,void 0),y(this,"organizationId"),y(this,"picture"),y(this,"private"),y(this,"published"),y(this,"staggered"),y(this,"tags"),y(this,"type"),y(this,"updatedAt"),S(this,Qi,void 0),y(this,"config"),S(this,lo,void 0),y(this,"active"),y(this,"iframes"),y(this,"enabledBy"),S(this,Qr,void 0),S(this,uo,void 0),T(this,Qr,t),this.baseURL=e,this.createdAt=new Date(n),this.description=i,this.id=s,this.name=r,T(this,wn,M),this.organizationId=a,this.picture=c,this.private=d,this.published=h,this.staggered=u,this.tags=g,this.type=E,this.updatedAt=new Date(b),this.active=!1,this.iframes=new Map,T(this,qt,w),T(this,oo,D),T(this,co,F),this.enabledBy="",T(this,uo,Y)}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:n}=e;n&&(navigator.isReactNative?n.postMessage(JSON.stringify(t)):n.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return p(this,null,function*(){var e;if(!this.active)return;const n=t,{payload:i,uuid:s,type:r}=n;switch(r){case ie.customPluginEventToRoom:{o(this,qt).customPluginEventToRoom(this.id,i,s);break}case ie.customPluginEventToPeers:{o(this,qt).customPluginEventToPeers(this.id,i.peerIds,i,s);break}case ie.enablePluginForRoom:{o(this,qt).enablePluginForRoom(this.id,s);break}case ie.enablePluginForPeers:{o(this,qt).enablePluginForPeers(this.id,i.peerIds,s);break}case ie.disablePluginForRoom:{o(this,qt).disablePluginForRoom(this.id,s);break}case ie.disablePluginForPeers:{o(this,qt).disablePluginForPeers(this.id,i.peerIds,s);break}case ie.storeInsertKeys:{o(this,qt).storeInsertKeys(this.id,i.store,i.insertKeys,s);break}case ie.storeGetKeys:{o(this,qt).storeGetKeys(this.id,i.store,i.getKeys,s);break}case ie.storeDeleteKeys:{o(this,qt).storeDeleteKeys(this.id,i.store,i.deleteKeys,s);break}case ie.storeDelete:{o(this,qt).storeDelete(this.id,i.store,s);break}case $e.chatMessage:{const{messagePayload:a,peerIds:c}=i;if(!o(this,co)){this.sendIframeEvent({type:$e.chatMessage,uuid:n.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield o(this,co).sendMessage(a,c),this.sendIframeEvent({type:$e.chatMessage,uuid:n.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:$e.chatMessage,uuid:n.uuid,payload:{error:d}})}break}case $e.getPeer:{let a;const{peerId:c}=i,d=ee(H({},o(this,wn)),{id:o(this,wn).id,isRecorder:(e=o(this,wn).permissions)==null?void 0:e.isRecorder,isHidden:o(this,wn).permissions.hiddenParticipant,stageStatus:o(this,wn).stageStatus});c?(a=o(this,oo).joined.get(i.peerId),o(this,wn).id===c&&(a=d)):a=d,this.sendIframeEvent({type:$e.getPeer,payload:{peer:a&&Ad(a)},uuid:n.uuid});break}case $e.getPeers:{const a=o(this,oo).joined.toArray().map(c=>Ad(c));this.sendIframeEvent({type:$e.getPeers,payload:{peers:a},uuid:n.uuid});break}case $e.getPluginInitiator:{this.sendIframeEvent({type:$e.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:n.uuid});break}case $e.getDisplayTitle:{this.sendIframeEvent({type:$e.getDisplayTitle,payload:{displayTitle:o(this,uo)},uuid:n.uuid});break}case $e.getRoomName:{this.sendIframeEvent({type:$e.getRoomName,payload:{roomName:o(this,Qr).getValue("meetingId")},uuid:n.uuid});break}case $e.customPluginEventToParent:{this.emit(n.payload.eventName,n.payload.data);break}}})}sendData(t){this.active&&(m.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:$e.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:n,listener:i}=(e=this.iframes.get(t))!=null?e:{};(n||i)&&(navigator.isReactNative?n.props.onMessage=void 0:window.removeEventListener("message",i),this.iframes.delete(t))}addPluginView(t,e="default"){var n;if(!o(this,lo))throw m.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new O("No auth token set for plugin.","0602");if(!t)throw m.error("DytePlugin::addPluginView::iframe_was_not_provided"),new O("Iframe was not provided.","0603");this.removePluginView(e);const i=t,s=new URL(this.baseURL),r={auth:o(this,lo),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:o(this,Qr).getValue("apiBase"),pluginId:this.id,roomName:(n=o(this,Qr).getValue("meetingId"))!=null?n:"",displayTitle:o(this,uo)};if(Object.keys(r).forEach(a=>{s.searchParams.set(a,r[a])}),i.src=s.href,i.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",i.title=e,navigator.isReactNative)i.props.onMessage=a=>{this.handleIframeMessage(JSON.parse(a.nativeEvent.data))},this.iframes.set(e,{iframe:i});else{const a=c=>p(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",a),this.iframes.set(e,{iframe:i,listener:a})}}setActive(t){var e,n;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:(n=this.config)==null?void 0:n.views})}activateForSelf(){return p(this,null,function*(){const t=It(),e=yield t.authorizePlugin(this.id);T(this,lo,e),T(this,Qi,new Date);try{const n=yield t.getPluginConfig(this.baseURL);this.config=n}catch(n){m.error("DytePlugin::activateForSelf",{error:n})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),T(this,Qi,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return p(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return p(this,null,function*(){var t,e;this.active||(e=(t=o(this,wn).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(o(this,qt).addPlugin(this.id,this.staggered),T(this,Qi,new Date),m.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return p(this,null,function*(){var t,e;this.active&&(!((e=(t=o(this,wn).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==o(this,wn).id||(o(this,qt).removePlugin(this.id),m.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:o(this,Qi)?new Date().getTime()-o(this,Qi).getTime():0}}),T(this,Qi,void 0)))})}},qt=new WeakMap,wn=new WeakMap,oo=new WeakMap,co=new WeakMap,Qi=new WeakMap,lo=new WeakMap,Qr=new WeakMap,uo=new WeakMap,qy);jd([en({maxInvocations:5,period:1})],Xr.prototype,"sendData",1),jd([k.trace("DytePlugin.activatePlugin")],Xr.prototype,"activate",1),jd([k.trace("DytePlugin.deactivatePlugin")],Xr.prototype,"deactivate",1),Xr=jd([Ot("0600")],Xr);var ot,Zr;class Gy extends Map{constructor(e){const{onAddEvent:n,onDeleteEvent:i,onClearEvent:s}=e;super(),S(this,ot,void 0),S(this,Zr,void 0),y(this,"onAddEvent"),y(this,"onDeleteEvent"),y(this,"onClearEvent"),T(this,ot,new jr),this.onAddEvent=n,this.onDeleteEvent=i,this.onClearEvent=s,T(this,Zr,new Map)}emit(e,...n){return o(this,ot).emit(e,...n)}on(e,n){return o(this,ot).on(e,n)}addListener(e,n){return o(this,ot).addListener(e,n)}off(e,n){return o(this,ot).off(e,n)}once(e,n){return o(this,ot).once(e,n)}prependListener(e,n){return o(this,ot).prependListener(e,n)}prependOnceListener(e,n){return o(this,ot).prependOnceListener(e,n)}removeListener(e,n){return o(this,ot).removeListener(e,n)}removeAllListeners(e){return o(this,ot).removeAllListeners(e)}listeners(e){return o(this,ot).listeners(e)}listenerCount(e){return o(this,ot).listenerCount(e)}getMaxListeners(){return o(this,ot).getMaxListeners()}setMaxListeners(e){return o(this,ot).setMaxListeners(e)}eventNames(){return o(this,ot).eventNames()}add(e,n=!0){return this.set(e.id,e,n)}set(e,n,i=!0){const s=super.set(e,n),r=(a,...c)=>{this.emit(a,n,...c)};return o(this,Zr).set(e,r),n.on("*",r),i&&o(this,ot).emit(this.onAddEvent,n),s}delete(e,n=!0,i=!1){const s=this.get(e);if(!s)return!1;s.removeListener("*",o(this,Zr).get(e));const r=super.delete(e);return i&&s.removeAllListeners(),n&&o(this,ot).emit(this.onDeleteEvent,s),r}clear(e=!0,n=!1){this.forEach(s=>{s.removeListener("*",o(this,Zr).get(s.id)),n&&s.removeAllListeners()});const i=super.clear();return e&&o(this,ot).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}ot=new WeakMap,Zr=new WeakMap;class Jy extends Gy{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,n=!0){return super.add(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var XN=Object.defineProperty,ZN=Object.getOwnPropertyDescriptor,eL=(t,e,n,i)=>{for(var s=i>1?void 0:i?ZN(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&XN(e,n,s),s};let Jh=class{constructor(){y(this,"all"),y(this,"active"),this.all=new Jy,this.active=new Jy}};Jh=eL([Ot("0600")],Jh);var tL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,Wd=(t,e,n,i)=>{for(var s=i>1?void 0:i?nL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&tL(e,n,s),s},Un,ho,Hd,$y;const Ky=($y=class{constructor(t,e,n,i){y(this,"plugins"),S(this,Un,void 0),S(this,ho,void 0),S(this,Hd,void 0),T(this,Un,e),T(this,ho,n),T(this,Hd,t),this.plugins=i,this.setupEvents()}static init(t,e,n,i,s,r,a,c){return p(this,null,function*(){const d=new Jh;return e.forEach(h=>{const u=new Xr(t,h,n,r,a,s,c);d.all.add(u)}),new Ky(t,n,i,d)})}getRoomPlugins(){return p(this,null,function*(){var t;const{plugins:e}=yield o(this,Un).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(n=>{this.disablePlugin({id:n.id})}),yield Promise.all(e.map(n=>this.enablePlugin({id:n.pluginId,enabledBy:n.enabledBy})))})}enablePlugin(t){return p(this,arguments,function*({id:e,enabledBy:n}){const i=this.plugins.all.get(e);i&&(yield i.activateForSelf(),i.enabledBy=n)})}disablePlugin(t){return p(this,arguments,function*({id:e}){const n=this.plugins.all.get(e);n&&n.deactivateForSelf()})}sendIframeEvent(t,e,n,i){const s=this.plugins.all.get(e);s&&s.sendIframeEvent({type:t,uuid:n,payload:i})}broadcastIframeEvent(t,e){this.plugins.active.forEach(n=>{this.sendIframeEvent(t,n.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)}),L.onAsync(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){yield this.getRoomPlugins(),m.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),o(this,Un).on(ie.addPlugin,t=>p(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active||(yield this.enablePlugin({id:n,enabledBy:t.enabledBy}))})),o(this,Un).on(ie.removePlugin,t=>p(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active&&(yield this.disablePlugin({id:n}))})),[ie.enablePluginForPeers,ie.enablePluginForRoom].forEach(t=>{o(this,Un).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{enabledBy:e.enabledBy})}))}),[ie.disablePluginForPeers,ie.disablePluginForRoom].forEach(t=>{o(this,Un).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{disabledBy:e.disabledBy})}))}),[ie.customPluginEventToPeers,ie.customPluginEventToRoom].forEach(t=>{o(this,Un).on(t,(e,n)=>p(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[ie.storeInsertKeys,ie.storeGetKeys,ie.storeDeleteKeys].forEach(t=>{o(this,Un).on(t,(e,n)=>p(this,null,function*(){var i;const s=(i=e.storeItems)==null?void 0:i.map(r=>{var a;return{timestamp:r.timestamp,peerId:r.peerId,payload:JSON.parse((a=r.payload)!=null&&a.length?new TextDecoder().decode(r.payload):"{}"),key:r.storeKey}});this.sendIframeEvent(t,e.pluginId,n,{storeName:e.storeName,storeItems:s})}))}),o(this,Un).on(ie.storeDelete,(t,e)=>p(this,null,function*(){this.sendIframeEvent(ie.storeDelete,t.pluginId,e,{storeName:t.storeName})})),o(this,ho).on(Ge.sendMessageToPeers,t=>{const e=bi==null?void 0:bi.formatSocketServiceMessage(t.message);this.broadcastIframeEvent($e.chatMessage,{message:e})}),o(this,ho).on(Ge.sendMessageToRoom,t=>{const e=bi==null?void 0:bi.formatSocketServiceMessage(t.message);this.broadcastIframeEvent($e.chatMessage,{message:e})}),L.on(x.PEER_JOINED_INTERNAL,t=>{const e=Ad(t);this.broadcastIframeEvent($e.peerJoined,e)}),L.on(x.PEER_CLOSED,t=>{this.broadcastIframeEvent($e.peerLeft,t)}),L.on(x.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent($e.peerStageStatusUpdate,t)}),o(this,Hd).subscribe("stageStatus",t=>{this.broadcastIframeEvent($e.stageStatusUpdate,t)})}},Un=new WeakMap,ho=new WeakMap,Hd=new WeakMap,$y);let po=Ky;Wd([k.trace("PluginController.getRoomPlugins")],po.prototype,"getRoomPlugins",1),Wd([k.trace("PluginController.enableForSelf")],po.prototype,"enablePlugin",1),Wd([k.trace("PluginController.disableForSelf")],po.prototype,"disablePlugin",1),Wd([k.trace("PluginController.setupEvents")],po.prototype,"setupEvents",1);class iL{constructor(){y(this,"mediaJoined"),y(this,"socketJoined"),y(this,"socketJoinAttempted"),y(this,"mediaJoinAttempted"),y(this,"socketState"),y(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,n){let i;const{reconnected:s}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:s,reconnectionAttempt:void 0};break;case"disconnected":i={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":i={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":i={state:"reconnecting",reconnected:s,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:s,reconnectionAttempt:n};break;case"failed":i={state:"failed",reconnected:s,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(L.emit(x.SOCKET_STATE_UPDATE,i),this.socketState=i)}}var sL=Object.defineProperty,rL=Object.getOwnPropertyDescriptor,mo=(t,e,n,i)=>{for(var s=i>1?void 0:i?rL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&sL(e,n,s),s},fo,qd,go,Gd,zy;let Ys=(zy=class extends cn{constructor(t,e){super(),S(this,go),S(this,fo,void 0),S(this,qd,void 0),y(this,"recordingPeerIds",[]),y(this,"recordings",[]),T(this,qd,t),T(this,fo,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 p(this,null,function*(){if(!o(this,fo).permissions.canRecord)throw m.error("DyteRecording::start::permission_denied"),new O("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 m.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new O(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=It(),{recording:n={}}=o(this,qd).getValue("defaults"),i=yield e.startRecording(n,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw m.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new O("Error while starting recording","1000")}})}stop(t){return p(this,null,function*(){yield Q(this,go,Gd).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return p(this,null,function*(){yield Q(this,go,Gd).call(this,"pause",["RECORDING"],t)})}resume(t){return p(this,null,function*(){yield Q(this,go,Gd).call(this,"resume",["PAUSED"],t)})}},fo=new WeakMap,qd=new WeakMap,go=new WeakSet,Gd=function(t,e,n){return p(this,null,function*(){if(!o(this,fo).permissions.canRecord)throw m.error("DyteRecording::stop::permission_denied"),new O("User does not have permission to stop recording","1001");let i=[];if(n!==void 0){const s=this.recordings.find(r=>r.id===n);if(s===void 0)throw new O("Could not find the specified recording","1004");if(e.includes(s.state)){m.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:s.state}});return}i.push(s)}else i=this.recordings.filter(s=>e.includes(s.state));i.forEach(s=>p(this,null,function*(){const r=s.state;t==="stop"&&(s.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield It().updateRecording(s.id,t)}catch(a){throw m.error("DyteRecording::stop::recording_failed_to_stop",{error:a}),s.state!==r&&(s.state=r,this.emit("recordingUpdate",r)),new O("Error while stopping recording","1000")}}))})},zy);mo([k.trace("DyteRecording.start")],Ys.prototype,"start",1),mo([k.trace("DyteRecording.stop")],Ys.prototype,"stop",1),mo([k.trace("DyteRecording.stop")],Ys.prototype,"pause",1),mo([k.trace("DyteRecording.stop")],Ys.prototype,"resume",1),Ys=mo([Ot("1000")],Ys);var aL=Object.defineProperty,oL=Object.getOwnPropertyDescriptor,cL=(t,e,n,i)=>{for(var s=i>1?void 0:i?oL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&aL(e,n,s),s},$h;class Yy{constructor(e,n,i){y(this,"recording"),y(this,"room"),S(this,$h,void 0),T(this,$h,e),this.recording=new Ys(e,n),this.room=i,this.setupEvents()}getRecordingTypeFromProtoType(e){let n;switch(e){case Fs.BROWSER:n="BROWSER";break;case Fs.COMPOSITE:n="COMPOSITE";break;case Fs.TRACK:n="TRACK";break;default:n="BROWSER"}return n}setupEvents(){L.on(x.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(n=>{const i=this.getRecordingTypeFromProtoType(n.recordingType);return{id:n.recordingId,state:n.recordingStatus,type:i}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(z.recordingStarted,e=>{let n=!1;const i=[...this.recording.recordings];if(i.forEach(s=>{s.id===e.recordingId&&(n=!0,s.state="RECORDING")}),n===!1){const s=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:s})}this.recording.updateRecordings(i)}),this.room.on(z.recordingPaused,e=>{const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(i.state="PAUSED")}),this.recording.updateRecordings(n)}),this.room.on(z.recordingStopped,e=>{const n=[...this.recording.recordings.filter(i=>i.id!==e.recordingId)];this.recording.updateRecordings(n)})}}$h=new WeakMap,cL([k.trace("RecordingController.setupEvents")],Yy.prototype,"setupEvents",1);class dL{static hasFeature(e){var n;return(n=re.hasFeature(e))!=null?n:!1}static getFeatureValue(e){return re.getValue(e)}static getAllFeatures(){return re.getAllFlags()}}class Kh{constructor(e,n,i){y(this,"logger"),y(this,"features"),y(this,"browserSpecs"),y(this,"callStats"),this.logger=e,this.features=n,this.browserSpecs=Ue,this.callStats=i}static init(e){return new Kh(m,dL,e)}}class zh{constructor(e){y(this,"internals"),this.internals=e}static init(){return p(this,null,function*(){const e=Kh.init(te);return new zh(e)})}}var lL=Object.defineProperty,uL=Object.getOwnPropertyDescriptor,ln=(t,e,n,i)=>{for(var s=i>1?void 0:i?uL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&lL(e,n,s),s},Et,ct,Fe,wi,Bn,Jd,Yh;class tn extends jr{constructor(e,n,i=Qh,s=!0){super(),S(this,Et,void 0),S(this,ct,void 0),S(this,Fe,void 0),S(this,wi,void 0),S(this,Bn,void 0),S(this,Jd,void 0),S(this,Yh,void 0),y(this,"audioUpdateInProgress"),y(this,"videoUpdateInProgress"),T(this,Yh,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,Et,new Zy(e,n)),T(this,ct,new DL(o(this,Et),void 0,i)),T(this,Fe,new FL(o(this,Et),void 0,i)),T(this,Bn,new VL(o(this,Et))),T(this,wi,new LL(o(this,Et))),T(this,Jd,s),o(this,ct).on("trackMuted",this.onAudioTrackMuted.bind(this)),o(this,ct).on("trackChanged",this.onAudioTrackChanged.bind(this)),o(this,Fe).on("trackChanged",this.onVideoTrackChanged.bind(this)),o(this,Fe).on("trackEnded",this.onVideoTrackEnded.bind(this)),o(this,Bn).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return p(this,null,function*(){te.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?te.browserBackgrounded():(te.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return p(this,null,function*(){return!0})}setupStreams(e){return p(this,arguments,function*({audio:n,video:i}){var s;n?te.audioOn():te.audioOff(),i?te.videoOn():te.videoOff();let r,a;if(n&&i)try{const c=yield o(this,Et).getAudioAndVideoTrack(o(this,ct).userSelectedDevice,o(this,Fe).userSelectedDevice);r=c.audioTrack,a=c.videoTrack}catch(c){m.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!r&&n)try{r=yield o(this,Et).getAudioTrack(!1,o(this,ct).userSelectedDevice)}catch(c){m.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&i)try{a=yield o(this,Et).getVideoTrack(o(this,Fe).userSelectedDevice)}catch(c){m.error("LocalMediaHandler::init::Failed to get video track",{error:c})}n&&!r&&te.audioOff(),i&&!a&&te.videoOff(),yield o(this,ct).setMediaTrack(r),yield o(this,Fe).setMediaTrack(a);try{yield o(this,wi).setupSpeaker()}catch(c){}if(a){const c=yield this.getDeviceById(a.getSettings().deviceId);te.selectedDevice("VIDEO",c)}if(r){const c=yield this.getDeviceById(r.getSettings().deviceId);te.selectedDevice("AUDIO",c)}(s=o(this,wi).currentDevice)!=null&&s.deviceId&&te.selectedDevice("SPEAKER",o(this,wi).currentDevice),o(this,Et).onDeviceChange((c,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:o(this,ct).currentDevice,video:o(this,Fe).currentDevice,speaker:o(this,wi).currentDevice}}get permissions(){return o(this,Et).permissions}getAllDevices(){return o(this,Et).getAvailableDevices()}getDeviceById(e,n){return o(this,Et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return o(this,ct).mediaTrack}get audioTrack(){return o(this,ct).transformedMediaTrack}get audioEnabled(){return o(this,ct).trackEnabled}enableAudio(){return p(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield o(this,ct).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){o(this,ct).muteTrack()}getAudioDevices(e){return o(this,Et).getAudioInputDevices(e)}setAudioDevice(e){return p(this,null,function*(){yield o(this,ct).setDevice(e),e!=null&&e.deviceId&&te.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return o(this,wi).setupSpeaker()}setSpeakerDevice(e){return p(this,null,function*(){yield o(this,wi).setupSpeaker(e),e!=null&&e.deviceId&&te.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return o(this,Fe).mediaTrack}get videoTrack(){return o(this,Fe).transformedMediaTrack}get videoEnabled(){return o(this,Fe).trackEnabled}enableVideo(){return p(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield o(this,Fe).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){o(this,Fe).disableTrack()}getVideoDevices(e){return o(this,Et).getVideoInputDevices(e)}setVideoDevice(e){return p(this,null,function*(){yield o(this,Fe).setDevice(e),e!=null&&e.deviceId&&te.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return p(this,null,function*(){yield o(this,Fe).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:o(this,Bn).audioMediaTrack,video:o(this,Bn).videoMediaTrack}}get screenShareEnabled(){return o(this,Bn).trackEnabled}enableScreenShare(){return p(this,null,function*(){yield o(this,Bn).enableScreenShare()})}disableScreenShare(){return p(this,null,function*(){o(this,Bn).disableScreenShare()})}updateScreenshareConstraints(e){return p(this,null,function*(){yield o(this,Bn).updateConstraints(e)})}getSpeakerDevices(e){return o(this,Et).getAudioOutputDevices(e)}addAudioMiddleware(e){return o(this,ct).addMiddleware(e)}removeAudioMiddleware(e){return o(this,ct).removeMiddleware(e)}removeAllAudioMiddlewares(){return o(this,ct).removeAllMiddlewares()}addVideoMiddleware(e){return o(this,Fe).addMiddleware(e)}removeVideoMiddleware(e){return o(this,Fe).removeMiddleware(e)}removeAllVideoMiddlewares(){return o(this,Fe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return o(this,Fe).setVideoMiddlewareGlobalConfig(e)}destruct(){o(this,ct).disableTrack(),o(this,Fe).disableTrack(),o(this,Fe).terminateMiddlewareWebWorker(),o(this,Bn).disableScreenShare(),o(this,Et).destruct()}onDeviceChange(e,n){return p(this,null,function*(){var i,s;this.emit("DEVICE_LIST_UPDATED",e),!(n||!o(this,Jd))&&((i=e==null?void 0:e.added)==null||i.forEach(r=>p(this,null,function*(){var a;r&&!Qh(r)&&(r.kind==="audioinput"&&((a=this.audioTrack)==null?void 0:a.enabled)===!0?yield this.setAudioDevice(r):r.kind==="audiooutput"&&(yield this.setSpeakerDevice(r)))})),(s=e==null?void 0:e.removed)==null||s.forEach(r=>p(this,null,function*(){var a;if(r.kind==="audiooutput"&&((a=this.getCurrentDevices().speaker)==null?void 0:a.deviceId)===r.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==r.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){o(this,ct).disableTrack()}removeVideoTrack(){o(this,Fe).disableTrack(),o(this,Fe).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return p(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}Et=new WeakMap,ct=new WeakMap,Fe=new WeakMap,wi=new WeakMap,Bn=new WeakMap,Jd=new WeakMap,Yh=new WeakMap,ln([k.trace("MediaHandler.setupStreams")],tn.prototype,"setupStreams",1),ln([k.trace("MediaHandler.enableAudio")],tn.prototype,"enableAudio",1),ln([k.trace("MediaHandler.disableAudio")],tn.prototype,"disableAudio",1),ln([k.trace("MediaHandler.setAudioDevice")],tn.prototype,"setAudioDevice",1),ln([k.trace("MediaHandler.enableVideo")],tn.prototype,"enableVideo",1),ln([k.trace("MediaHandler.disableVideo")],tn.prototype,"disableVideo",1),ln([k.trace("MediaHandler.setVideoDevice")],tn.prototype,"setVideoDevice",1),ln([k.trace("MediaHandler.updateVideoConstraints")],tn.prototype,"updateVideoConstraints",1),ln([k.trace("MediaHandler.enableScreenShare")],tn.prototype,"enableScreenShare",1),ln([k.trace("MediaHandler.disableScreenShare")],tn.prototype,"disableScreenShare",1),ln([k.trace("MediaHandler.updateScreenshareConstraints")],tn.prototype,"updateScreenshareConstraints",1),ln([k.trace("MediaHandler.destruct")],tn.prototype,"destruct",1),ln([k.trace("MediaHandler.onDeviceChange")],tn.prototype,"onDeviceChange",1);function $d(t,e,n){switch(!0){case Ue.isChromiumBased():switch(e){case"NotAllowedError":return n.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ue.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Ue.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 hL=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Qh(t){var e,n;const i=(e=t.label)==null?void 0:e.toLowerCase();return((n=Ue._bowser)==null?void 0:n.getOSName())==="macOS"&&i.includes("iphone")?(m.log("isVirtualDevice::ignore_macos_continuity"),!0):hL.some(s=>i==null?void 0:i.includes(s))}function pL(t,e){return p(this,null,function*(){if(!(t!=null&&t.length))return e;const n=new AudioContext,i=yield Promise.all(t==null?void 0:t.map(a=>a(n))),s=n.createMediaStreamSource(new MediaStream([e])),r=n.createMediaStreamDestination();try{let a=s;for(let c=0;c<i.length;c+=1)a.connect(i[c]),a=i[c];a.connect(r)}catch(a){return m.error("getTransformedAudioTrack::middleware_execution_failed",{error:a}),e}return r.stream.getAudioTracks()[0]})}var ea;class mL{constructor(){S(this,ea,void 0)}terminateMiddlewareWebWorker(){if(o(this,ea))try{Mr(o(this,ea)),T(this,ea,void 0)}catch(e){m.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,n,i){return p(this,null,function*(){if(!(e!=null&&e.length))return n;const s=document.createElement("canvas"),r=yield Promise.all(e==null?void 0:e.map(g=>g({canvas:s,WorkerTimers:uS})));if(i.disablePerFrameCanvasRendering){const g=s.captureStream().getVideoTracks()[0];return Object.defineProperty(g,"originalSettings",{value:n.getSettings()}),g}const a=document.createElement("video"),c=new MediaStream;c.addTrack(n);const d=s.getContext("2d");a.srcObject=c,a.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>p(this,null,function*(){if(n.enabled===!1||n.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),s.remove();return}try{d.drawImage(a,0,0);for(let g=0;g<r.length;g+=1)typeof r[g]=="function"&&(yield r[g](s,d))}catch(g){m.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}});try{a.play()}catch(g){}a.addEventListener("play",()=>{s.width=a.width||n.getSettings().width,s.height=a.width||n.getSettings().height,T(this,ea,Uc(h,50))},!1);const u=s.captureStream().getVideoTracks()[0];return Object.defineProperty(u,"originalSettings",{value:n.getSettings()}),u})}}ea=new WeakMap;const Qy={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}}},fL=[[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"}]],[1920,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:9e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:15e5,maxFramerate:30,scalabilityMode:"L1T1"}]]],gL=t=>{var e;const n="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((e=t.originalSettings)==null?void 0:e.width);let i=fL;re.hasFeature(ue.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(i=JSON.parse(re.getValue(ue.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const s=i.map(([c])=>c).sort((c,d)=>c-d);let r=Number.MAX_VALUE,a=0;return s.forEach((c,d)=>{Math.abs(c-n)<r&&(r=Math.abs(c-n),a=d)}),i[a][1]};var De=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(De||{});const vL=rC(),ta=xn(vL.config.media);function yL(t){var e,n;const i={};return t.audio&&(i.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(n=t.audio.enableHighBitrate)!=null?n:!1}),i.video=t.video.quality,i}var na,Xh;class EL{constructor(e,n){S(this,na,void 0),S(this,Xh,void 0),y(this,"getScreenShareConstraints",()=>{var i,s,r,a,c,d,h,u,g,E,b;const w=(i=o(this,na))==null?void 0:i.screenshare,M=(r=(s=w==null?void 0:w.width)==null?void 0:s.max)!=null?r:1920,D=(c=(a=w==null?void 0:w.height)==null?void 0:a.max)!=null?c:1080,F=(h=(d=w==null?void 0:w.frameRate)==null?void 0:d.max)!=null?h:5;let Y=(g=(u=w==null?void 0:w.frameRate)==null?void 0:u.ideal)!=null?g:5;const X=w==null?void 0:w.displaySurface,A=w==null?void 0:w.selfBrowserSurface;re.getValue(ue.VAL_MIN_FRAMERATE)&&(Y=parseInt((E=re.getValue(ue.VAL_MIN_FRAMERATE))==null?void 0:E.toString(),10));let J={width:{max:M},height:{max:D},frameRate:{ideal:Y,max:F}};if(re.hasFeature(ue.SCREENSHARE_CONSTRAINTS)){const me=(b=re.getValue(ue.SCREENSHARE_CONSTRAINTS))==null?void 0:b.toString();J=JSON.parse(me)}return X!==void 0&&["monitor","browser","window"].includes(X)&&(J=ee(H({},J),{displaySurface:X})),A!==void 0&&(J=ee(H({},J),{selfBrowserSurface:A})),{audio:!0,video:J}}),y(this,"getAudioConstraints",i=>{var s,r,a,c,d,h,u,g;const E={},b=(s=o(this,na))==null?void 0:s.audio,w=b!=null&&b.enableStereo?2:1;return Ue.isFirefox()||Ue.isWebKitBased()?(E.audio={deviceId:i,autoGainControl:(r=b==null?void 0:b.autoGainControl)!=null?r:!0,echoCancellation:(a=b==null?void 0:b.echoCancellation)!=null?a:!0,noiseSuppression:(c=b==null?void 0:b.noiseSupression)!=null?c:!0,channelCount:w},E):(E.audio={},E.audio.optional=[i?{sourceId:i}:{sourceId:"default"},{channelCount:w},{echoCancellation:(d=b==null?void 0:b.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=b==null?void 0:b.echoCancellation)!=null?h:!0},{googAutoGainControl:(u=b==null?void 0:b.autoGainControl)!=null?u:!0},{googNoiseSuppression:(g=b==null?void 0:b.noiseSupression)!=null?g:!0},{googHighpassFilter:!0}],E)}),y(this,"getVideoConstraints",i=>{var s,r,a,c;const d={},h=(s=o(this,na))==null?void 0:s.video;let u=Qy.vga;if(typeof h=="string"?u=Qy[h]:h!==void 0&&(u.height.ideal=h.height.ideal,u.width.ideal=h.width.ideal),u.frameRate={ideal:(a=(r=u.frameRate)==null?void 0:r.ideal)!=null?a:24},Ue.isChromiumBased()&&(u.frameRate.max=30),re.hasFeature(ue.VIDEO_CONSTRAINTS)){const g=(c=re.getValue(ue.VIDEO_CONSTRAINTS))==null?void 0:c.toString();u=JSON.parse(g)}return d.video=u,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),T(this,Xh,e),T(this,na,n)}getUpdatedVideoConstraints(e){return e}}na=new WeakMap,Xh=new WeakMap;class Zh extends Error{constructor(e,n,i){super(n),y(this,"constraints"),y(this,"name"),this.name=e,this.constraints=i}}class SL{constructor(){y(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audioinput")})}getVideoInputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="videoinput")})}getAudioOutputDevices(e){return p(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audiooutput")})}}var TL=Object.defineProperty,bL=Object.getOwnPropertyDescriptor,Fn=(t,e,n,i)=>{for(var s=i>1?void 0:i?bL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&TL(e,n,s),s},vo,jn,ep,Xy;let un=(Xy=class extends SL{constructor(t,e){super(),y(this,"availableDevices"),S(this,vo,void 0),S(this,jn,void 0),S(this,ep,void 0),T(this,ep,t),T(this,jn,new EL(t,e)),T(this,vo,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return o(this,jn)}destruct(){return p(this,null,function*(){var t;(t=o(this,vo))==null||t.abort()})}handlePermissionErrors(t,e){const n=$d(t,e.name,e.message);return this.permissions[t]=n,L.emit(x.MEDIA_PERMISSION_ERROR,{message:n,constraints:e.constraints,kind:t}),n}getAudioAndVideoTrack(t,e){return p(this,null,function*(){const n={audio:o(this,jn).getAudioConstraints(t).audio,video:o(this,jn).getVideoConstraints(e).video};try{m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const i=yield navigator.mediaDevices.getUserMedia(n);m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)});const s=i.getAudioTracks()[0];let r=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",re.hasFeature(ue.OBS_QUALITY)&&r.label.includes("OBS Virtual")){const a=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));r=yield this.getVideoTrack(a.deviceId)}return L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:s,videoTrack:r}}catch(i){throw m.error("WebMediaInterface.getAudioAndVideoTrack",{error:i}),new O("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return p(this,null,function*(){let n=yield this.getAudioInputDevices();if(n.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new O("No audio devices available","1606");const i=s=>p(this,null,function*(){let r;try{n=n.filter(c=>c.deviceId!==s),r=o(this,jn).getAudioConstraints(s),m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(r)});const[a]=(yield navigator.mediaDevices.getUserMedia(r)).getAudioTracks();return m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(r)}),a}catch(a){const c=$d("audio",a.name,a.message),d=new Zh(a.name,a.message,r);if(c==="COULD_NOT_START"){const h=n.shift();if(!h)throw d;m.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(r),error:a});const u=o(this,jn).getAudioConstraints(h.deviceId);return m.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(u)}),i(h.deviceId)}throw d}});try{const s=yield i(e);return s.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),s}catch(s){throw s.constraints&&this.handlePermissionErrors("audio",s),new O(s.message,"1601")}})}getVideoTrack(t){return p(this,null,function*(){var e;const n=re.hasFeature(ue.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),s=n&&i,r=yield this.getVideoInputDevices();if(r.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new O("No video devices available","1607");const a=c=>p(this,null,function*(){try{let d=c;const{video:h}=d;s&&typeof h!="boolean"&&(d={video:{deviceId:h.deviceId}}),m.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[u]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(s&&typeof h!="boolean"&&typeof h.width=="object"){const{width:g,height:E}=u.getSettings(),{ideal:b}=h.width;u.applyConstraints({width:{ideal:b},height:{ideal:Math.floor(E*b/g)},frameRate:h.frameRate})}return m.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),u}catch(d){const h=$d("video",d.name,d.message),u=new Zh(d.name,d.message,c);if(h==="COULD_NOT_START"){const g=r.shift();if(!g)throw u;m.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const E=o(this,jn).getVideoConstraints(g.deviceId);return m.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(E)}),a({video:E.video})}throw u}});try{const c=o(this,jn).getVideoConstraints(t),d=yield a(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(c){throw c.constraints&&this.handlePermissionErrors("video",c),new O(c.message,"1602")}})}getScreenShareTracks(){return p(this,null,function*(){const t=e=>p(this,null,function*(){try{m.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),te.screenShareRequested();const n=yield navigator.mediaDevices.getDisplayMedia(e);return m.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),n}catch(n){const i=$d("video",n.name,n.message),s=new Zh(n.name,n.message,e),r={video:!0};if(_R(e,r)||!re.hasFeature(ue.SCREEENSHARE_CONSTRAINTS_RETRY))throw s;if(i==="COULD_NOT_START")return t(r);throw s}});try{const e=o(this,jn).getScreenShareConstraints(),n=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new O(e.message,"1612")}})}getCurrentDeviceLabel(t){return p(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return p(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw m.error("enumerate_devices_failed",{error:t}),new O("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return p(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw m.error("enumerate_devices_failed",{error:e}),new O("Failed to get available devices by kind","1609")}})}getDevice(t){return p(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw m.error("enumerate_devices_failed",{error:e}),new O("Failed to get device","1609")}})}onDeviceChange(t){return p(this,null,function*(){Ue.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>p(this,null,function*(){var n,i;const s=u=>`${u.kind}-${u.deviceId}-${u.groupId}`,r=this.availableDevices,a=new Set(r.map(u=>s(u))),c=yield this.getAvailableDevices(),d=new Set(c.map(u=>s(u))),h={added:c.filter(u=>!a.has(s(u))),removed:r.filter(u=>!d.has(s(u))),devices:c};if((n=h.added)!=null&&n.length||(i=h.removed)!=null&&i.length){m.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const u=[...h.added,...h.removed];u.some(g=>g.kind==="audioinput")&&te.devices("AUDIO",c==null?void 0:c.filter(g=>g.kind==="audioinput")),u.some(g=>g.kind==="videoinput")&&te.devices("VIDEO",c==null?void 0:c.filter(g=>g.kind==="videoinput")),u.some(g=>g.kind==="audiooutput")&&te.devices("SPEAKER",c==null?void 0:c.filter(g=>g.kind==="audiooutput")),t(e,h,!1)}}),{signal:o(this,vo).signal})})}},vo=new WeakMap,jn=new WeakMap,ep=new WeakMap,Xy);Fn([k.trace("WebMediaInterface.destruct")],un.prototype,"destruct",1),Fn([k.trace("WebMediaInterface.handlePermissionErrors")],un.prototype,"handlePermissionErrors",1),Fn([k.trace("WebMediaInterface.getAudioAndVideoTrack")],un.prototype,"getAudioAndVideoTrack",1),Fn([k.trace("WebMediaInterface.getAudioTrack")],un.prototype,"getAudioTrack",1),Fn([k.trace("WebMediaInterface.getVideoTrack")],un.prototype,"getVideoTrack",1),Fn([k.trace("WebMediaInterface.getScreenShareTracks")],un.prototype,"getScreenShareTracks",1),Fn([k.trace("WebMediaInterface.getAvailableDevices")],un.prototype,"getAvailableDevices",1),Fn([k.trace("WebMediaInterface.getAvailableDevicesByKind")],un.prototype,"getAvailableDevicesByKind",1),Fn([k.trace("WebMediaInterface.getDevice")],un.prototype,"getDevice",1),Fn([k.trace("WebMediaInterface.onDeviceChange")],un.prototype,"onDeviceChange",1),un=Fn([Ot("1600")],un);const Zy=un,yo={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(n){m.error("LocalStorage::setItem::crashed",{error:n,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){m.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},kL=(t=0)=>new Promise(e=>setTimeout(e,t)),wL=(t,e,n)=>{const i=typeof n=="number"?n:250,s=t.createMediaStreamSource(e),r=t.createAnalyser();r.fftSize=2048,s.connect(r);const a=new Uint8Array(r.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(r.getByteTimeDomainData(a),a.some(h=>h!==128&&h!==0)?Promise.resolve(!1):kL().then(d))}return d().then(h=>(s.disconnect(),h),h=>{throw s.disconnect(),h})},_L=typeof AudioContext!="undefined"?AudioContext:null;class tp{constructor(e){y(this,"_AudioContext"),y(this,"audioContext"),y(this,"_audioContextRefContainers");const n=H({AudioContext:_L},e);Object.defineProperties(this,{_AudioContext:{value:n.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:tp}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(n){}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 e0=new tp,IL=3,CL=250;function RL(t){const e={},n=e0.getOrCreate(e);let i=IL;function s(){return i-=1,wL(n,t.srcObject,CL).then(r=>r?i>0?s():!0:!1).catch(()=>!0)}return s().finally(()=>{e0.release(e)})}function t0(t){return p(this,null,function*(){const e=new Audio,n=new MediaStream;n.addTrack(t),e.srcObject=n;let i=!1;try{const s=e.play();s&&(yield s),i=yield RL(e),i&&m.info("checkIfAudioTrackIsSilent::silence_detected")}catch(s){m.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:s})}finally{e.pause(),e.remove()}return i})}var PL=Object.defineProperty,AL=Object.getOwnPropertyDescriptor,n0=(t,e,n,i)=>{for(var s=i>1?void 0:i?AL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&PL(e,n,s),s};let Kd=class extends jr{constructor(t,e,n){var i;super(),y(this,"constructorName",this.constructor.name),y(this,"userSelectedDevice"),y(this,"mediaInterface"),y(this,"isNonPreferredDevice"),y(this,"_mediaTrack"),y(this,"transformedMediaTrack"),y(this,"middlewares",[]),y(this,"currentDevice"),y(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),y(this,"setUserPreferredDevice",s=>yo.setItem(this.userPreferredDeviceKey,s)),y(this,"getUserPreferredDevice",()=>yo.getItem(this.userPreferredDeviceKey)),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=(i=this.getUserPreferredDevice())!=null?i:void 0,this.isNonPreferredDevice=n,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 p(this,null,function*(){const e=n=>{m.error(`${this.constructorName}.setMediaTrack.error`,{error:n})};try{this.disableTrack()}catch(n){e(n)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){e(n)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){m.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return p(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw m.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new O("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:n}=this.mediaTrack;switch(n){case"audio":{const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=i==null?void 0:i.deviceId)!=null?t:i==null?void 0:i.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return p(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))})}setDevice(t){return p(this,null,function*(){if(!t)throw m.warn(`${this.constructorName}.setDevice No device received`),new O("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),yield this.onSetDevice(t)})}addMiddleware(t){return p(this,null,function*(){if(Ue.isWebKitBased()&&!re.hasFeature(ue.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 m.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return p(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(n){return m.error("While removing middleware",{error:n}),{success:!1,message:n==null?void 0:n.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return p(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 m.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,n;this.mediaTrack&&(m.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,n;this.mediaTrack&&(m.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),m.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};n0([k.trace("BaseMediaHandler.unmuteTrack")],Kd.prototype,"unmuteTrack",1),Kd=n0([Ot("1600")],Kd);const i0=Kd;var ML=Object.defineProperty,OL=Object.getOwnPropertyDescriptor,np=(t,e,n,i)=>{for(var s=i>1?void 0:i?OL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&ML(e,n,s),s};const ip="[Dyte]nonSilentDeviceLabels";class zd extends i0{onSetDevice(e){return p(this,null,function*(){if(!e)throw m.warn("AudioMediaHandler.setDevice No device received"),new O("No device received!","1603");if(e.kind!=="audioinput")throw m.warn("AudioMediaHandler.setDevice Received non audio device"),new O("Non audio device received while setting device!","1603");try{const n=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!n,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(n){throw m.error("AudioMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new O(n.message,"1604")}})}enableTrack(e){return p(this,null,function*(){if(this.trackEnabled){m.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const n=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(n)})}setTransformedTrack(e){return p(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield pL(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(i){m.error("AudioMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return p(this,null,function*(){m.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){m.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return p(this,null,function*(){var n;if(!e||this.userSelectedDevice)return e;let i=e;const s=yield this.mediaInterface.getAudioInputDevices(),r=this.isNonPreferredDevice?s.filter(d=>d&&!this.isNonPreferredDevice(d)):s;if(!(r!=null&&r.length))return i;r.find(d=>d.deviceId===e.getSettings().deviceId)||(i.stop(),m.info("localmediahandler::setupstreams::found_audio_non_preferred"),i=yield this.mediaInterface.getAudioTrack(!1,r[0].deviceId));const a=JSON.parse(yo.getItem(ip));if(a!=null&&a.devices.some(d=>d.label===i.label))return i;if(!(yield t0(i))){const d=(n=a==null?void 0:a.devices.concat({label:i.label}))!=null?n:[{label:i.label}];return yo.setItem(ip,JSON.stringify({devices:d})),i}m.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=i.getSettings().deviceId;return r.filter(d=>d.deviceId!==c).some(d=>p(this,null,function*(){if(i=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield t0(i))){const h=a.devices.concat({label:i.label});return yo.setItem(ip,JSON.stringify({devices:h})),m.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return m.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),i})}}np([k.trace("AudioMediaHandler.setTransformedTrack")],zd.prototype,"setTransformedTrack",1),np([k.trace("AudioMediaHandler.onTrackEnded")],zd.prototype,"onTrackEnded",1),np([k.trace("AudioMediaHandler.conditionallyChangeTrack")],zd.prototype,"conditionallyChangeTrack",1);const DL=zd;var Eo;class NL{constructor(e){S(this,Eo,void 0),y(this,"currentDevice"),T(this,Eo,e)}setupSpeaker(e){return p(this,null,function*(){var n,i;if(!(o(this,Eo)instanceof Zy))return;let s=e;if(e||([s]=(yield o(this,Eo).getAvailableDevicesByKind("audiooutput")).filter(a=>!Qh(a))),!s)throw new O("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===s.deviceId)return;this.currentDevice=s;const r=document.querySelectorAll("audio");(i=r[0])!=null&&i.setSinkId&&r.forEach(a=>p(this,null,function*(){if(typeof a.sinkId!="undefined"&&this.currentDevice.deviceId&&a.sinkId!==this.currentDevice.deviceId)try{yield a.setSinkId(this.currentDevice.deviceId)}catch(c){}}))})}}Eo=new WeakMap;const LL=NL;class xL extends jr{constructor(e){super(),y(this,"mediaInterface"),y(this,"audioMediaTrack"),y(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return p(this,null,function*(){var e,n;try{const{audioTrack:i,videoTrack:s}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=s,this.addMediaTrackListeners(),((n=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:n.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",L.emit(x.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}})}disableScreenShare(){var e,n;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(n=this.videoMediaTrack)==null||n.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return p(this,null,function*(){if(!this.videoMediaTrack)throw new O("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new O("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){m.error("ScreenShareHandler.updateConstraints.error",{error:i})}})}addMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Ue.isWebKitBased()&&((n=this.videoMediaTrack)==null||n.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(n=this.videoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const VL=xL;var UL=Object.defineProperty,BL=Object.getOwnPropertyDescriptor,Yd=(t,e,n,i)=>{for(var s=i>1?void 0:i?BL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&UL(e,n,s),s},So,Qd;class To extends i0{constructor(e,n,i){super(e,n,i),S(this,So,void 0),S(this,Qd,{disablePerFrameCanvasRendering:!1}),T(this,So,new mL)}onSetDevice(e){return p(this,null,function*(){if(!e)throw m.warn("VideoMediaHandler.setDevice No device received"),new O("No device received!","1603");if(e.kind!=="videoinput")throw m.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new O("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){m.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(n){throw m.error("VideoMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new O("Failed to change device","1600")}})}enableTrack(){return p(this,null,function*(){if(this.trackEnabled){m.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return p(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield o(this,So).getTransformedVideoTrack(this.middlewares,this.mediaTrack,o(this,Qd)),this.emit("trackChanged")}catch(i){m.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return p(this,null,function*(){T(this,Qd,e)})}updateConstraints(e){return p(this,null,function*(){if(!this._mediaTrack)throw new O("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new O("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){m.error("VideoMediaHandler.updateConstraints.error",{error:i})}})}terminateMiddlewareWebWorker(){o(this,So).terminateMiddlewareWebWorker()}onTrackEnded(){return p(this,null,function*(){m.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){m.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return p(this,null,function*(){if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getVideoInputDevices(),s=this.isNonPreferredDevice?i.filter(r=>!this.isNonPreferredDevice(r)):i;return!(s!=null&&s.length)||window.FAST_DYTE||s.find(r=>r.deviceId===e.getSettings().deviceId)||(n.stop(),m.info("localmediahandler::setupstreams::found_video_non_preferred"),n=yield this.mediaInterface.getVideoTrack(s[0].deviceId)),n})}}So=new WeakMap,Qd=new WeakMap,Yd([k.trace("VideoMediaHandler.setTransformedTrack")],To.prototype,"setTransformedTrack",1),Yd([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],To.prototype,"setVideoMiddlewareGlobalConfig",1),Yd([k.trace("VideoMediaHandler.onTrackEnded")],To.prototype,"onTrackEnded",1),Yd([k.trace("VideoMediaHandler.conditionallyChangeTrack")],To.prototype,"conditionallyChangeTrack",1);const FL=To,s0=xn(oh());var hn,ia,Xd,bo;const ko=class{constructor(t){if(S(this,hn,void 0),S(this,ia,void 0),S(this,Xd,void 0),S(this,bo,void 0),!t)throw new O("Could not load preset.","0904");T(this,hn,t.config),T(this,Xd,t.name),T(this,ia,t.ui||xn(oh().ui)),T(this,bo,t.permissions.plugins.config)}static fromResponse(t){return new ko(t)}static default(){return new ko(s0)}static init(t,e=!0){return!t||e?new ko(s0):new ko(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:o(this,ia).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return o(this,hn).viewType}get livestreamViewerQualities(){return o(this,hn).livestreamViewerQualities||[]}get maxVideoStreams(){return o(this,hn).maxVideoStreams}get maxScreenShareCount(){return o(this,hn).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(o(this,bo)).filter(t=>o(this,bo)[t].disabled)}get designTokens(){return o(this,ia).designTokens}get configDiff(){return o(this,ia).configDiff}get mediaConstraints(){var t,e,n,i,s,r,a,c,d,h,u,g,E,b,w,M,D,F,Y,X,A,J,me,Re;return{audio:{enableStereo:(i=(n=(e=(t=o(this,hn))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.enableStereo)!=null?i:ta.audio.enableStereo,enableHighBitrate:(c=(a=(r=(s=o(this,hn))==null?void 0:s.media)==null?void 0:r.audio)==null?void 0:a.enableHighBitrate)!=null?c:ta.audio.enableHighBitrate},video:{quality:(g=(u=(h=(d=o(this,hn))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:u.quality)!=null?g:ta.video.quality,frameRate:(M=(w=(b=(E=o(this,hn))==null?void 0:E.media)==null?void 0:b.video)==null?void 0:w.frameRate)!=null?M:ta.video.frameRate},screenshare:{quality:(X=(Y=(F=(D=o(this,hn))==null?void 0:D.media)==null?void 0:F.screenshare)==null?void 0:Y.quality)!=null?X:ta.screenshare.quality,frameRate:(Re=(me=(J=(A=o(this,hn))==null?void 0:A.media)==null?void 0:J.screenshare)==null?void 0:me.frameRate)!=null?Re:ta.screenshare.frameRate}}}get name(){return o(this,Xd)}};let jL=ko;hn=new WeakMap,ia=new WeakMap,Xd=new WeakMap,bo=new WeakMap;var WL=Object.defineProperty,HL=Object.getOwnPropertyDescriptor,r0=(t,e,n,i)=>{for(var s=i>1?void 0:i?HL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&WL(e,n,s),s},wo;class sp extends cn{constructor(e){super(),S(this,wo,void 0),y(this,"state","IDLE"),y(this,"playbackUrl"),y(this,"ingestionCredentials"),y(this,"viewerCount"),T(this,wo,e),this.viewerCount=0}setLivestreamState(e){const n=this.state;this.state=e,n!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return p(this,arguments,function*(e={manualIngestion:!1}){if(!o(this,wo).permissions.canLivestream)throw m.error("DyteLivestream::start::permission_denied"),new O("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const n=It(),{playbackUrl:i,ingestionCredentials:s}=yield n.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=s,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(n){throw m.error("DyteRecording::stop::livestream_failed_to_start",{error:n}),this.setLivestreamState("IDLE"),new O("Error while starting livestream","1900")}})}stop(){return p(this,null,function*(){if(!o(this,wo).permissions.canLivestream)throw m.error("DyteLivestream::stop::permission_denied"),new O("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw m.error("DyteLivestream::stop::inconsistent_state"),new O("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield It().stopLivestreaming()}catch(e){throw m.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new O("Error while stopping livestream","1900")}})}}wo=new WeakMap,r0([k.trace("livestream.start")],sp.prototype,"start",1),r0([k.trace("livestream.stop")],sp.prototype,"stop",1);var qL=Object.defineProperty,GL=Object.getOwnPropertyDescriptor,JL=(t,e,n,i)=>{for(var s=i>1?void 0:i?GL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&qL(e,n,s),s},_o,Io,Xi;class a0{constructor(e,n){y(this,"livestream"),S(this,_o,void 0),S(this,Io,void 0),S(this,Xi,void 0),T(this,Io,e),this.livestream=new sp(e),T(this,Xi,n),this.setupEvents()}fetchInitialLivestreamingState(){return p(this,null,function*(){const e=It(),{status:n,playbackUrl:i,manualIngest:s,ingestionCredentials:r}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=r,n==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),n==="INVOKED"&&s&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){o(this,Xi).on(z.startedLivestream,e=>p(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{o(this,Io).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){m.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),o(this,Xi).on(z.livestreamingInvoked,e=>p(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{o(this,Io).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){m.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),o(this,Xi).on(z.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),o(this,Xi).on(z.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),o(this,Xi).on(z.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),L.on(x.PEER_JOINED_INTERNAL,e=>p(this,null,function*(){var n;((n=e.flags)==null?void 0:n.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,_o,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),L.on(x.PEER_CLOSED,e=>{e.id===o(this,_o)&&(T(this,_o,void 0),this.livestream.setLivestreamState("IDLE"))}),L.onAsync(x.LEAVE_MEDIA_ROOM,()=>p(this,null,function*(){this.livestream.playbackUrl||(m.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),L.on(x.SOCKET_SERVICE_ROOM_JOINED,()=>p(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){m.error("Error: LivestreamController.fetchLivestream")}}))}}_o=new WeakMap,Io=new WeakMap,Xi=new WeakMap,JL([k.trace("LivestreamController.setupEvents")],a0.prototype,"setupEvents",1);var $L=Object.defineProperty,KL=Object.getOwnPropertyDescriptor,Co=(t,e,n,i)=>{for(var s=i>1?void 0:i?KL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&$L(e,n,s),s},Gt,Qs,Xs,rp,o0;class sa{constructor({name:e,socketHandler:n,meetingId:i}){S(this,rp),y(this,"name",""),S(this,Gt,{}),S(this,Qs,""),S(this,Xs,void 0),y(this,"rateLimitConfig",{maxInvocations:5,period:1}),y(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),y(this,"listeners",{}),this.name=e,T(this,Xs,n),T(this,Qs,i)}set(e,n,i=!0,s=!1){return p(this,null,function*(){o(this,Gt)[e]=n,i&&this.remoteSet(e,n),s&&(this.listeners[e]&&this.listeners[e].forEach(r=>r({[e]:o(this,Gt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(r=>r({[e]:o(this,Gt)[e]})))})}remoteSet(e,n){o(this,Xs).storeInsertKeys(o(this,Qs),this.name,[{key:e,payload:n}])}bulkSet(e){return p(this,null,function*(){e.forEach(({key:n,payload:i})=>{o(this,Gt)[n]=i}),o(this,Xs).storeInsertKeys(o(this,Qs),this.name,e)})}update(e,n,i=!0){return p(this,null,function*(){Q(this,rp,o0).call(this,e,n,i)})}delete(e,n=!0,i=!1){return p(this,null,function*(){if(o(this,Gt)[e]&&delete o(this,Gt)[e],n)return o(this,Xs).storeDeleteKeys(o(this,Qs),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(s=>s({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:void 0})))})}bulkDelete(e){return p(this,null,function*(){return e.forEach(({key:n})=>{o(this,Gt)[n]&&delete o(this,Gt)[n]}),o(this,Xs).storeDeleteKeys(o(this,Qs),this.name,e)})}get(e){if(o(this,Gt)[e])return o(this,Gt)[e]}getAll(){return o(this,Gt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,n){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=n}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,n){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=n}subscribe(e,n){if(this.listeners[e]){this.listeners[e].push(n);return}this.listeners[e]=[n]}unsubscribe(e,n){var i;if(n){this.listeners[e]=((i=this.listeners[e])==null?void 0:i.filter(s=>s!==n))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){T(this,Gt,e)}}Gt=new WeakMap,Qs=new WeakMap,Xs=new WeakMap,rp=new WeakSet,o0=function(t,e,n=!0){let i;const s=o(this,Gt)[t],r=Object.prototype.toString.call(e),a=Object.prototype.toString.call(s);if(r!==a){this.set(t,e);return}switch(a){case"[object Array]":i=[...s,...e];break;case"[object Object]":i=H(H({},s),e);break;case"[object Map]":i=new Map([...s,...e]);break;case"[object Set]":i=new Set([...s,...e]);break;default:i=e;break}this.set(t,i,n)},Co([en(qr,"rateLimitConfig")],sa.prototype,"remoteSet",1),Co([en(qr,"bulkRateLimitConfig")],sa.prototype,"bulkSet",1),Co([en(qr,"rateLimitConfig")],sa.prototype,"update",1),Co([en(qr,"rateLimitConfig")],sa.prototype,"delete",1),Co([en(qr,"bulkRateLimitConfig")],sa.prototype,"bulkDelete",1);var ra,aa,Zd,ap,el,Zs,op,c0;class zL{constructor(e,n){S(this,Zd),S(this,op),y(this,"stores",new Map),S(this,ra,void 0),S(this,aa,""),S(this,el,void 0),S(this,Zs,new Map),T(this,ra,n),T(this,aa,e.getValue("meetingId")),T(this,el,e),Q(this,op,c0).call(this)}create(e){const n=new sa({name:e,socketHandler:o(this,ra),meetingId:o(this,aa)});return o(this,ra).storeGetKeys(o(this,aa),e,[]),new Promise((i,s)=>{const r=setTimeout(()=>s(Error("Failed")),3e3);o(this,Zs).set(e,{rejectTimeout:r,resolve:i,store:n})})}}ra=new WeakMap,aa=new WeakMap,Zd=new WeakSet,ap=function(){return o(this,el).getValue("peerId")},el=new WeakMap,Zs=new WeakMap,op=new WeakSet,c0=function(){[ie.storeInsertKeys,ie.storeGetKeys,ie.storeDeleteKeys].forEach(t=>{o(this,ra).on(t,e=>p(this,null,function*(){var n,i;if(e.pluginId!==o(this,aa))return;const s=(n=e.storeItems)==null?void 0:n.map(a=>{var c;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((c=a.payload)!=null&&c.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});if(t===ie.storeGetKeys){const a=o(this,Zs).get(e.storeName),c=this.stores.get(e.storeName)||(a==null?void 0:a.store);o(this,Zs).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(c),clearTimeout(a.rejectTimeout),o(this,Zs).delete(e.storeName)),s.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const r=this.stores.get(e.storeName)||((i=o(this,Zs).get(e.storeName))==null?void 0:i.store);r!==void 0&&(t===ie.storeInsertKeys&&s.forEach(({key:a,peerId:c,payload:d})=>{c!==o(this,Zd,ap)&&r.set(a,d,!1,!0)}),t===ie.storeDeleteKeys&&s.forEach(({key:a,peerId:c})=>{c!==o(this,Zd,ap)&&r.delete(a,!1,!0)}))}))})};function er(t){var e,n,i,s,r,a,c,d,h,u,g,E,b;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.audio:null},video:{enabled:t.videoEnabled,trackId:(i=t.videoTrack)==null?void 0:i.id,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.screenshare:null,audio:{enabled:(c=(a=t.screenShareTracks)==null?void 0:a.audio)==null?void 0:c.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(g=(u=t.screenShareTracks)==null?void 0:u.video)==null?void 0:g.enabled,trackId:(b=(E=t.screenShareTracks)==null?void 0:E.video)==null?void 0:b.id}}}}:{}}var YL=Object.defineProperty,QL=Object.getOwnPropertyDescriptor,oa=(t,e,n,i)=>{for(var s=i>1?void 0:i?QL(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&YL(e,n,s),s};const XL=.8,ZL=1.2;var Ro,Po,tr,ca,Ao,da,Mo,cp,d0,Zi,tl,nr,Oo,nl,es,dp,il,lp,l0;let _i=(l0=class extends cn{constructor(t,e,n,i){super(),S(this,ca),S(this,da),S(this,cp),S(this,Oo),S(this,il),y(this,"id"),y(this,"userId"),y(this,"name"),y(this,"picture"),y(this,"isHost"),y(this,"customParticipantId"),y(this,"flags"),y(this,"device"),y(this,"videoTrack"),y(this,"audioTrack"),y(this,"screenShareTracks"),y(this,"videoEnabled"),y(this,"audioEnabled"),y(this,"screenShareEnabled"),y(this,"producers"),y(this,"manualProducerConfig"),S(this,Ro,void 0),y(this,"supportsRemoteControl",!1),S(this,Po,void 0),y(this,"presetName"),S(this,tr,void 0),S(this,Zi,void 0),S(this,tl,void 0),S(this,nr,new Map),S(this,es,1),S(this,dp,gd(A=>{if(!this.videoTrack)return;const{clientWidth:J,clientHeight:me}=A,{width:Re,height:fe}=this.videoTrack.getSettings();if(!Re||!fe)return;const Qe=fe/me,vt=Re/J,V=Math.max(Qe,vt);V>ZL&&o(this,es)===1?(T(this,es,0),L.emit(x.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,es)})):V<XL&&o(this,es)===0&&(T(this,es,1),L.emit(x.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,es)}))},2e3)),T(this,tr,t);const{id:s,userId:r,displayName:a,device:c,picture:d,isHost:h,flags:u,clientSpecificId:g,stageStatus:E,customParticipantId:b,audioMuted:w,audioTrack:M,videoEnabled:D=!1,videoTrack:F,producers:Y,metadata:X}=e;this.id=s,this.userId=r,this.name=a,this.device=c,this.picture=d,this.isHost=h,this.flags=u,this.manualProducerConfig=xR,T(this,Po,E!=null?E:"ON_STAGE"),this.customParticipantId=b!=null?b:g,this.audioEnabled=!w,this.audioTrack=M,this.videoEnabled=D,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=Y!=null?Y:[],this.presetName=X==null?void 0:X.preset_name,T(this,Ro,!1),T(this,Zi,n),T(this,tl,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),Q(this,il,lp).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return o(this,Po)}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(m.info("DyteParticipant::setVideoEnabled::videoUpdate",H({},er(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(m.info("DyteParticipant::setAudioEnabled::audioUpdate",H({},er(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",Q(this,il,lp))}pin(){return p(this,null,function*(){if(!o(this,da,Mo))throw new O("Can`t pin participant without joining room","1205");if(!o(this,Zi).permissions.pinParticipant)throw new O("You do not have permission to pin participants.","1201");return o(this,ca,Ao).pinPeer(this.id)})}unpin(){return p(this,null,function*(){if(!o(this,da,Mo))throw new O("Can`t unpin participant without joining room","1205");if(!o(this,Zi).permissions.pinParticipant)throw new O("You do not have permission to unpin participants.","1201");return o(this,ca,Ao).pinPeer(null)})}setIsPinned(t,e=!0){var n;T(this,Ro,t);const i=t?"pinned":"unpinned";(n=o(this,Oo,nl))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}disableAudio(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!o(this,da,Mo))throw new O("Can`t disable participant audio without joining room","1205");if(o(this,Zi).permissions.canDisableParticipantAudio)return o(this,ca,Ao).disableAudio(t);throw m.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!o(this,cp,d0))throw new O("Can`t kick participant without joining room","1205");if(o(this,Zi).permissions.kickParticipant){yield L.emitAsync(x.KICK_PEER,{peerId:t});return}throw m.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return p(this,null,function*(){const t=this.id;if(m.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!o(this,da,Mo))throw new O("Can`t disable participant video without joining room","1205");if(o(this,Zi).permissions.canDisableParticipantVideo)return o(this,ca,Ao).disableVideo(t);throw m.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new O("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return p(this,null,function*(){return o(this,tl).getUserPermissions(this.userId)})}setStageStatus(t){T(this,Po,t),this.emit("stageStatusUpdate",this)}get isPinned(){return o(this,Ro)}registerVideoElement(t){var e,n,i,s;let r;(n=(e=o(this,nr).get(t))==null?void 0:e.observer)==null||n.disconnect(),"ResizeObserver"in window&&(r=new ResizeObserver(()=>o(this,dp).call(this,t)),r.observe(t)),o(this,nr).set(t,{observer:r}),this.updateVideo(t),(s=o(this,Oo,nl))==null||s.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,n,i;t.srcObject=void 0,(n=(e=o(this,nr).get(t))==null?void 0:e.observer)==null||n.disconnect(),o(this,nr).delete(t),(i=o(this,Oo,nl))==null||i.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Ro=new WeakMap,Po=new WeakMap,tr=new WeakMap,ca=new WeakSet,Ao=function(){return o(this,tr).getValue("roomNodeClient")},da=new WeakSet,Mo=function(){return o(this,tr).getValue("connectionHandler").mediaJoined},cp=new WeakSet,d0=function(){return o(this,tr).getValue("connectionHandler").socketJoined},Zi=new WeakMap,tl=new WeakMap,nr=new WeakMap,Oo=new WeakSet,nl=function(){return o(this,tr).getValue("pip")},es=new WeakMap,dp=new WeakMap,il=new WeakSet,lp=function(){Array.from(o(this,nr).keys()).forEach(this.updateVideo)},l0);oa([k.trace("DyteParticipant.disableAudio")],_i.prototype,"disableAudio",1),oa([k.trace("DyteParticipant.kick")],_i.prototype,"kick",1),oa([k.trace("DyteParticipant.disableVideo")],_i.prototype,"disableVideo",1),oa([k.trace("DyteParticipant.getPermissions")],_i.prototype,"getPermissions",1),oa([k.trace("DyteParticipant.setStageStatus")],_i.prototype,"setStageStatus",1),_i=oa([Ot("1200")],_i);class Do extends Gy{constructor(e){const{onAddEvent:n="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:s="participantsCleared"}=e!=null?e:{};super({onAddEvent:n,onDeleteEvent:i,onClearEvent:s})}add(e,n=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,n)}clear(e=!0,n=!1){return super.clear(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var ir;class e2 extends jr{constructor(){super(),S(this,ir,void 0),T(this,ir,new Map)}__set(e,n){return o(this,ir).set(e,n)}__clear(){return o(this,ir).clear()}get(e){return o(this,ir).get(e)}toArray(){return Array.from(o(this,ir).values())}}ir=new WeakMap;class t2{constructor(){y(this,"_orderedArray"),y(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,n){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:n}),this._orderedArray.splice(Math.max(n-1,0),0,e),this.index(e);const i=this.index(e);this.delete(e);const s=this.add(e,n);return i!==s?s:-1}delete(e){if(this._map.has(e)){const n=this.index(e);this._map.delete(e),this._orderedArray.splice(n,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class n2{constructor(){y(this,"_activeSpeakerPeers"),y(this,"_compulsoryPeers"),this._activeSpeakerPeers=new t2,this._compulsoryPeers=new Set}add(e,n){if(!e)return-1;if(n<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(n>0||n===246267631)){if(m.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),n===246267631)return-1}else if(n===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,n)}delete(e){m.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 u0=new n2;var i2=Object.defineProperty,s2=Object.getOwnPropertyDescriptor,pn=(t,e,n,i)=>{for(var s=i>1?void 0:i?s2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&i2(e,n,s),s};const r2=["ACTIVE_GRID","PAGINATED","MANUAL"];var Wn,la,No,ua,Lo,xo,sl,ha,mn,h0;let Jt=(h0=class extends cn{constructor(t,e,n){super(),S(this,la),S(this,ua),S(this,xo),y(this,"waitlisted"),y(this,"joined"),y(this,"active"),y(this,"videoSubscribed"),y(this,"audioSubscribed"),y(this,"pinned"),y(this,"all"),S(this,Wn,void 0),S(this,ha,void 0),S(this,mn,void 0),y(this,"rateLimitConfig",{maxInvocations:5,period:1}),y(this,"viewMode"),y(this,"currentPage"),y(this,"lastActiveSpeaker"),y(this,"selectedPeers",u0),T(this,Wn,t),T(this,ha,e),T(this,mn,n),this.waitlisted=new Do,this.joined=new Do,this.videoSubscribed=new Do,this.audioSubscribed=new Do,this.active=this.videoSubscribed,this.pinned=new Do,this.all=new e2,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return o(this,Wn).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){L.on(x.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=o(this,Wn).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(){var t;return(t=o(this,Wn))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new O("0 <= Max active participants count limit <= 24","1203");o(this,Wn).setValue("maxPreferredStreams",t),o(this,xo,sl)&&L.emit(x.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(n=>n.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,n;if(!o(this,ua,Lo))throw new O("Can`t accept waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;return o(this,mn).acceptWaitingRoomRequest([i])}acceptAllWaitingRoomRequest(t){return p(this,null,function*(){const e=t.map(n=>{var i,s;return(s=(i=this.waitlisted.get(n))==null?void 0:i.userId)!=null?s:n});return o(this,mn).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return p(this,null,function*(){var e,n;if(!o(this,ua,Lo))throw new O("Can`t reject waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;o(this,mn).rejectWaitingRoomRequest([i])})}setViewMode(t){return p(this,null,function*(){if(m.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>r2.includes(e))(t))throw m.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new O(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){m.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL")throw new O("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,L.emit(x.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,L.emit(x.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return p(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new O("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(s=>{const r=this.joined.get(s);if(r){if(n.includes("audio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(r);const a=r.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{video:!0}),this.audioSubscribed.add(r);const a=r.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareAudio:!0});const a=r.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareVideo:!0});const a=r.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,la,No).createConsumers(i)})}unsubscribe(t){return p(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new O("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(s=>{const r=this.joined.get(s);if(r){if(n.includes("audio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{audio:!1});const a=r.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{video:!1});const a=r.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareAudio:!1});const a=r.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){r.manualProducerConfig=ee(H({},r.manualProducerConfig),{screenshareVideo:!1});const a=r.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,la,No).closeConsumers(i)})}getPeerIdsForCurrentPage(){m.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(a=>this.joined.has(a)),n=Array.from(this.pinned.keys()).filter(a=>!e.includes(a)),i=Array.from(this.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),s=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-n.length)),r=this.currentPage*(this.maxActiveParticipantsCount-e.length-n.length);return e.concat(n,i.slice(s,r))}setPage(t){return p(this,null,function*(){if(m.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 m.error("DyteParticipants::invalid_page_number"),new O(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,L.emit(x.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return p(this,null,function*(){if(m.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!o(this,xo,sl))throw new O("Can`t disable all audio without joining room","1205");if(o(this,ha).permissions.canAllowParticipantAudio)return o(this,la,No).muteAll(t);throw m.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new O("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return p(this,null,function*(){if(m.info("DyteParticipants::disable_all_video"),!o(this,xo,sl))throw new O("Can`t disable all video without joining room","1205");if(o(this,ha).permissions.canAllowParticipantVideo)return o(this,la,No).muteAllVideo();throw m.error("DyteParticipants::unauthorized_disable_all_video"),new O("Unauthorized: User does not have permission to disable peer video.","1201")})}disableAudio(t){return p(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return p(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return p(this,null,function*(){yield L.emitAsync(x.KICK_PEER,{peerId:t})})}kickAll(){return p(this,null,function*(){if(m.info("DyteParticipants::kick_all"),o(this,Wn).getValue("viewType")!=="LIVESTREAM"&&!o(this,ua,Lo))throw new O("Can`t kick all without joining room","1205");if(!o(this,ha).permissions.kickParticipant)throw m.error("DyteParticipants::unauthorized_kick_all"),new O("Unauthorized: User does not have permission to kick peers.","1201");const t=re.hasFeature(ue.PROPAGATE_KICK_ALL);o(this,mn).kickAll(t)})}broadcastMessage(t,e,n){return p(this,null,function*(){if(m.info("DyteParticipants::broadcastMessage"),!o(this,ua,Lo))throw new O("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new O("`type` must be a non-empty string.","1209");if(n)if("meetingIds"in n)yield o(this,mn).broadcastToMeetings(t,n.meetingIds,e);else{let i=[];"participantIds"in n?i=n.participantIds:i=this.joined.toArray().filter(s=>{var r;return(r=n.presetNames)==null?void 0:r.includes(s.presetName)}).map(s=>s.id),yield o(this,mn).broadcastToPeers(t,i,e)}else yield o(this,mn).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,n){return p(this,null,function*(){return(yield o(this,mn).getRoomPeers(t,e,n)).peers.map(Ii.formatSocketServiceMessage)})}updatePermissions(t,e){return p(this,null,function*(){const n=this.joined.toArray().filter(s=>t.includes(s.id)).map(s=>s.userId),i=[...new Set(n)];if(!i.length)throw new O("Cannot update permissions, no valid userIDs found","1204");o(this,mn).updatePermissions(i,e)})}getParticipantsInMeetingPreJoin(){return p(this,null,function*(){return o(this,mn).getRoomPeersNonPaginated()})}},Wn=new WeakMap,la=new WeakSet,No=function(){return o(this,Wn).getValue("roomNodeClient")},ua=new WeakSet,Lo=function(){var t;return((t=o(this,Wn).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},xo=new WeakSet,sl=function(){var t;return((t=o(this,Wn).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ha=new WeakMap,mn=new WeakMap,h0);pn([k.trace("DyteParticipants.setViewMode")],Jt.prototype,"setViewMode",1),pn([k.trace("DyteParticipants.setPage")],Jt.prototype,"setPage",1),pn([k.trace("DyteParticipants.disableAllAudio")],Jt.prototype,"disableAllAudio",1),pn([k.trace("DyteParticipants.disableAllVideo")],Jt.prototype,"disableAllVideo",1),pn([k.trace("DyteParticipants.disablePeerAudio")],Jt.prototype,"disableAudio",1),pn([k.trace("DyteParticipants.disablePeerVideo")],Jt.prototype,"disableVideo",1),pn([k.trace("DyteParticipants.kickPeer")],Jt.prototype,"kick",1),pn([k.trace("DyteParticipants.kickAll")],Jt.prototype,"kickAll",1),pn([k.trace("DyteParticipants.broadcastMessage"),en(qr,"rateLimitConfig")],Jt.prototype,"broadcastMessage",1),pn([k.trace("DyteParticipants.getAllJoinedPeers"),en({maxInvocations:10,period:60})],Jt.prototype,"getAllJoinedPeers",1),pn([k.trace("DyteParticipant.updatePermissions"),en({maxInvocations:1e3,period:60})],Jt.prototype,"updatePermissions",1),pn([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Jt.prototype,"getParticipantsInMeetingPreJoin",1),Jt=pn([Ot("1200")],Jt);var ts=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(ts||{}),St=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(St||{}),a2=Object.defineProperty,o2=Object.getOwnPropertyDescriptor,sr=(t,e,n,i)=>{for(var s=i>1?void 0:i?o2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&a2(e,n,s),s};const p0=class{constructor(t,e,n,i){switch(y(this,"participants"),y(this,"self"),y(this,"selectedPeers",u0),y(this,"maxSpatialLayerUpdates",new Map),y(this,"consumerPeerMap"),y(this,"events"),y(this,"roomSocketHandler"),y(this,"context"),y(this,"videoPeerConsumerMap",new Map),y(this,"updateConsumerSpatialLayers",gd(()=>{const s={},r=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(r.entries()).forEach(([a,c])=>{s[c]===void 0&&(s[c]={layer:c,consumerIds:[]}),s[c].consumerIds.push(a)}),Object.keys(s).forEach(a=>{const c=s[a];m.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),y(this,"updateConsumers",(s,r)=>{let a=Promise.resolve();r.length>0&&(m.info("Closing consumers for producers",{producers:r}),a=this.roomNodeClient.closeConsumers(r)),a.then(()=>{s.length!==0&&(m.info("Consuming producers",{producers:s}),this.roomNodeClient.createConsumers(s).catch(c=>m.error("Error activating peers",{error:c})))}).catch(c=>m.error("Error deactivating peers",{error:c}))}),y(this,"updateConsumersDebounced",gd(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=n,this.participants=new Jt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case St.HIVE:{this.events=Tn;break}case St.CF:{this.events=Nn;break}default:this.events=Tn}e.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}setupEvents(){this.roomSocketHandler.on(z.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),L.on(x.SOCKET_PEERS,t=>p(this,null,function*(){const e=re.hasFeature(ue.DEBUG_SOCKET_JOIN);if(e){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(i=>i.peerId))}:void 0;m.info("Processing socket peers",n)}t==null||t.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),e&&m.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{re.hasFeature(ue.DEBUG_SOCKET_JOIN)&&m.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:n})=>{if(re.hasFeature(ue.DEBUG_SOCKET_JOIN)){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(a=>a.peerId))}:void 0;m.info("events.selfJoinComplete",r)}t.forEach(({peerId:r,producerStates:a,capabilities:c})=>this.onMediaJoined(r,a,c));const{audioPeers:i,compulsoryPeers:s}=e!=null?e:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),L.emit(x.UPDATE_ACTIVE,{createAllConsumers:!0})}),L.on(x.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const n=this.videoPeerConsumerMap.get(t);n&&(this.maxSpatialLayerUpdates.set(n,e),this.updateConsumerSpatialLayers())}),L.on(x.NEW_PRODUCER,({peerId:t,producer:e})=>{const n=this.participants.joined.get(t);if(!n){m.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(n.producers.push(e),m.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=e.kind==="audio",r=e.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!e.screenShare||a.screenshareAudio&&e.screenShare)||r&&(a.video&&!e.screenShare||a.screenshareVideo&&e.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([e]):m.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(i=>{m.error("ParticipantController::createConsumer failed",{error:i})}):m.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),L.on(x.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const n=this.participants.joined.get(t);if(!n){m.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}n.producers=n.producers.filter(i=>i.producerId!==e)}),L.on(x.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:n,kind:i})=>{const s=this.participants.joined.get(t);if(s){i==="audio"&&s.setAudioEnabled(!n);const r=s.producers.find(a=>a.producerId===e);r&&(r.pause=n)}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const n=e;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers(i.producers).catch(s=>{m.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.mediaJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:t})=>{if(!this.mediaJoined)return;const e=t.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(i=>!this.participants.waitlisted.toArray().find(s=>s.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(s=>s.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new _i(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,customParticipantId:i.customParticipantId,picture:i.picture,metadata:{preset_name:i.presetName}},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return p(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,n=e.filter(c=>this.participants.joined.has(c)),i=Array.from(this.participants.pinned.keys()).filter(c=>!n.includes(c)),s=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),r=Math.max((t-1)*(this.maxPreferredStreams-n.length-i.length)),a=t*(this.maxPreferredStreams-n.length-i.length);return n.concat(i,s.slice(r,a))})}selectActivePeers(){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))),n=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((h,u)=>(u.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(u.id):h.push(u.id),h),[]),s=this.self.stageStatus==="ON_STAGE"?1:0,r=this.participants.maxActiveParticipantsCount-s,a=new Set(n.concat(i).filter(h=>h!==this.self.id&&t.has(h)));let c=Array.from(a);const d=r-a.size;if(d>=0){const h=e.filter(u=>!a.has(u)&&u!==this.self.id).slice(0,d);c=Array.from(a).concat(h)}else c=c.slice(0,r);return c}updateActive(t,e){return p(this,null,function*(){const{page:n,createAllConsumers:i}=e!=null?e:{};let{strategies:s}=e!=null?e:{},r,a;switch(t){case"PAGINATED":{if(!n)return;r=yield this.selectPagePeers(n),m.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:r}),s!=null||(s={video:this.updateParticipantsMap.bind(this)}),a=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{r=this.selectActivePeers(),m.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:r}),s!=null||(s={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),a=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let c,d;const h=this.updateGrid(r,s);i?(c=this.mapPeerIdsToProducers(r,["audio","video","screenshare"]),d=[]):(c=[...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"])]),!(c.length===0&&d.length===0)&&a(c,d)})}computeActivateParticipants(t,e){const n=t.map((s,r)=>({peerId:s,priority:r+1})),i=e==null?void 0:e.map((s,r)=>({peerId:s,priority:-(r+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(t){const e=p0.formatSocketServiceMessage(t);return new _i(this.context,ee(H({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var n,i;e?(n=this.pip)==null||n.enableSource(t):(i=this.pip)==null||i.disableSource(t)}onMediaJoined(t,e,n){if(!this.mediaJoined||t===this.self.id)return;const i=this.participants.joined.get(t);if(!i){m.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(s=>{s.kind===ii.AUDIO&&!s.screenShare?i.setAudioEnabled(!s.pause):s.kind===ii.VIDEO&&!s.screenShare&&(i.setVideoEnabled(!s.pause),this.updatePipSource(i.id,!s.pause)),i.producers.push(ee(H({},s),{producingTransportId:s.producingTransportId,kind:s.kind===ii.AUDIO?"audio":"video",producingPeerId:t,mimeType:s.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,n),re.hasFeature(ue.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack)}updateParticipantsMapMinReplacement(t,e){const n=Array.from(t.keys()),i=new Map(t),s=[],r=[],a=new Set(e),c=[];return n.forEach((d,h)=>{(!a.has(d)||!this.participants.joined.get(d))&&c.push(h)}),e.forEach(d=>{if(t.get(d))return;if(n.length<e.length){n.push(d),s.push(d);return}const h=c.shift();r.push(n[h]),n[h]=d,s.push(n[h])}),n.forEach((d,h)=>{a.has(d)||r.concat(n.splice(h,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!a.has(d))}),n.forEach(d=>{if(!this.participants.joined.get(d)){m.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!i.get(d))}),t.emit("participantsUpdate"),[s,r]}updateParticipantsMap(t,e){const n=Array.from(t.keys()),i=[],s=[];return n.forEach(r=>{e.includes(r)||(t.delete(r,!0),s.push(r))}),e.forEach(r=>{t.get(r)||(t.add(this.participants.joined.get(r)),i.push(r))}),t.emit("participantsUpdate"),[i,s]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(z.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=re.hasFeature(ue.DEBUG_SOCKET_JOIN);e&&m.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&m.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(z.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e),this.onParticipantLeave(e)}),L.on(x.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())}),L.on(x.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})}),L.on(x.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),L.on(x.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),L.on(x.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),L.on(x.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),L.on(x.ROOM_MESSAGE,t=>p(this,[t],function*({payload:e,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),L.on(x.MESSAGE,t=>p(this,[t],function*({payload:e,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),L.on(x.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:n})=>{const i=this.participants.joined.get(t);i&&(i.emit("poorConnection",{score:e,kind:n}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:n}))}),L.on(x.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:n,peerId:i,scoreStats:s})=>{var r;const a=e==="video"&&((r=n==null?void 0:n.screenShare)!=null?r:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:s}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:s}))}),L.onAsync(x.KICK_PEER,t=>p(this,[t],function*({peerId:e}){const n=this.participants.joined.get(e);this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),L.on(x.UPDATE_ACTIVE,(...t)=>p(this,[...t],function*({page:e,createAllConsumers:n}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:n})}))}onParticipantPinned(t){return p(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 p(this,null,function*(){var e,n,i;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((n=t.flags)!=null&&n.hidden_participant)&&!((i=t.flags)!=null&&i.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"&&L.emit(x.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),L.emit(x.PEER_JOINED_INTERNAL,t),this.self.config.viewType===Ft.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.maxPreferredStreams)return;const s=this.participants.currentPage;this.updateActive(s?"PAGINATED":"ACTIVE_GRID",{page:s})})}onParticipantLeave(t){return p(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),this.roomNodeClient&&(this.roomNodeClient.handlePeerLeaving(t),this.roomNodeClient.closeConsumers(e==null?void 0:e.producers)),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&L.emit(x.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),s=this.participants.videoSubscribed.get(t);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(n?"PAGINATED":"ACTIVE_GRID",{page:n})})}processMedia(t){var e;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:r,track:a,producerId:c,rtpReceiver:d,paused:h}=(e=n.get(t))!=null?e:{};if(!i)return m.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:s,peerId:i,appData:{supportsRemoteControl:!!(r!=null&&r.supportsRemoteControl),screenShare:!!(r!=null&&r.screenShare)},remotelyPaused:h,producerId:c}}),{};const u=r;return s==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),m.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:s,appData:u,remotelyPaused:h,producerId:c}}),this.consumerPeerMap.set(t,{type:s,peerId:i,appData:u,remotelyPaused:h,producerId:c}),{peerId:i,kind:s,appData:u,remotelyPaused:h,track:a,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:n,appData:i,remotelyPaused:s,producerId:r}=this.consumerPeerMap.get(t)||{},a=this.participants.joined.get(e);if(m.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:i,kind:n,remotelyPaused:s,producerId:r}}),this.consumerPeerMap.delete(t),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!a)return;const c=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),te.consumerSharedMediaState(t,{screen:!1}),a.screenShareTracks.video&&c.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&c.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&c.push(a.audioTrack.id),te.consumerSharedMediaState(t,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&c.push(a.videoTrack.id),te.consumerSharedMediaState(t,{video:!1}),a.videoTrack=void 0),i.e2ee&&c.forEach(d=>{L.emit(x.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:n,appData:i,track:s,remotelyPaused:r,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:n,appData:i,remotelyPaused:r,producerId:a}});const d=this.participants.joined.get(e);if(d){if(i.e2ee&&L.emit(x.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s}),i.screenShare){n==="video"?d.screenShareTracks.video=s:n==="audio"&&(d.screenShareTracks.audio=s),d.setScreenShareEnabled(!0),te.consumerSharedMediaState(t,{screen:!0});return}n==="video"?(d.videoTrack=s,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),te.consumerSharedMediaState(t,{video:!0})):n==="audio"&&(d.audioTrack=s,d.setAudioEnabled(d.audioEnabled),te.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){m.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:n,track:i,appData:s,remotelyPaused:r,producerId:a}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:n,appData:s,remotelyPaused:r,producerId:a}});const c=this.participants.joined.get(e);c&&(i&&s.e2ee&&L.emit(x.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),n==="video"?(c.videoTrack=i,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),te.consumerSharedMediaState(t,{video:!1})):n==="audio"&&(c.audioTrack=i,c.setAudioEnabled(c.audioEnabled),te.consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:n,remotelyPaused:i,track:s,appData:r,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;m.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:r,producerId:a}});const d=this.participants.joined.get(e);if(d){if(r.screenShare){n==="video"?d.screenShareTracks.video=s:n==="audio"&&(d.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||re.hasFeature(ue.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),r.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),m.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:r,producerId:a}});return}n==="video"?(d.videoTrack=s,i||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),te.consumerSharedMediaState(t,{video:!i})):n==="audio"&&(d.audioTrack=s,i||d.setAudioEnabled(!0),te.consumerSharedMediaState(t,{audio:!i})),!i&&r.e2ee&&L.emit(x.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s})}}static formatSocketServiceMessage(t){var e,n,i,s,r,a;if(!t)return;const c=Gh(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:c,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:c,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(n=t.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=t.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(s=t.flags)==null?void 0:s.hiddenParticipant,recorder:((r=t.flags)==null?void 0:r.recorderType)!==void 0&&((a=t.flags)==null?void 0:a.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const n=(i,s)=>i.filter(({kind:r,screenShare:a})=>s.includes(r)||a&&s.includes("screenshare"));return t.flatMap(i=>{const s=this.participants.joined.get(i);if(s)return n(s.producers,e)}).filter(i=>!!i)}updateGrid(t,e){let n=[],i=[],s=[],r=[];return e.video&&([n,s]=e.video(this.participants.videoSubscribed,t)),e.audio&&([i,r]=e.audio(this.participants.audioSubscribed,t)),{video:{add:n,remove:s},audio:{add:i,remove:r}}}onSelectedPeers(t,e){return p(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){m.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority)});const n=this.selectedPeers.activeSpeakerPeers.at(0);n!==void 0&&n!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n,this.participants.emit("activeSpeaker",{peerId:n,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 Ii=p0;sr([k.trace("ParticipantController.setupEvents")],Ii.prototype,"setupEvents",1),sr([k.trace("ParticipantController.setupEvents")],Ii.prototype,"setupEventsGlobal",1),sr([k.trace("ParticipantController.processMedia")],Ii.prototype,"processMedia",1),sr([k.trace("ParticipantController.processConsumerClosed")],Ii.prototype,"processConsumerClosed",1),sr([k.trace("ParticipantController.processConsumerResumed")],Ii.prototype,"processConsumerResumed",1),sr([k.trace("ParticipantController.processConsumerPaused")],Ii.prototype,"processConsumerPaused",1),sr([k.trace("ParticipantController.processNewConsumer")],Ii.prototype,"processNewConsumer",1);const Ne=xn(oh().permissions);var Z,Vo,Uo,up,nn,fn;const Bo=class extends cn{constructor(t,e,n,i=!1){if(super(),S(this,nn),S(this,Z,void 0),S(this,Vo,void 0),S(this,Uo,void 0),S(this,up,s=>{var r,a,c;const d=s,{chat:h,connectedMeetings:u,plugins:g,polls:E,media:b}=d,w=Fc(d,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&Wi(o(this,Z).chat.private,h.private),h.public&&Wi(o(this,Z).chat.public,h.public),this.emit("chatUpdate")),u&&Wi(o(this,Z).connectedMeetings,u),b){const M=F=>{switch(F){case $i.NONE:return se.Allowed;case $i.ALLOWED:return se.Allowed;case $i.NOT_ALLOWED:return se.NotAllowed;case $i.CAN_REQUEST:return se.CanRequest;default:return}},D={audio:void 0,video:void 0,screenshare:void 0};(r=b.audio)!=null&&r.canProduce&&(D.audio={canProduce:M(b.audio.canProduce)}),(a=b.video)!=null&&a.canProduce&&(D.video={canProduce:M(b.video.canProduce)}),(c=b.screenshare)!=null&&c.canProduce&&(D.screenshare={canProduce:M(b.screenshare.canProduce)}),Wi(o(this,Z).media,D)}g&&(Wi(o(this,Z).plugins,g),this.emit("pluginsUpdate")),E&&(Wi(o(this,Z).polls,E),this.emit("pollsUpdate")),Object.keys(w).length!==0&&Wi(o(this,Z),w),this.emit("permissionsUpdate",s)}),!e)throw m.error("DytePermissionsPreset::load_preset_permissions_failed"),new O("Could not load preset permissions.","0904");T(this,Uo,t),T(this,Vo,n),T(this,Z,e),i&&this.setupEvents()}setupEvents(){L.on(x.UPDATE_PERMISSIONS,o(this,up))}static fromResponse(t,e,n){return new Bo(n,t,e,!0)}static default(t,e){return new Bo(t,Ne,e)}static init(t,e,n){let i;return n?i=new Bo(t,n,e,!0):i=new Bo(t,Ne,e),i}get mediaRoomType(){const{sfu:t}=o(this,Uo).getValue("roomNodeOptions");return t===St.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=o(this,Z))==null?void 0:t.stageEnabled)||o(this,Vo)===Ft.Webinar||o(this,Vo)===Ft.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=o(this,Z))==null?void 0:t.acceptStageRequests)||((e=o(this,Z))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,n;return((t=o(this,Z))==null?void 0:t.stageAccess)===se.NotAllowed?se.NotAllowed:((e=o(this,Z))==null?void 0:e.stageAccess)===se.CanRequest?se.CanRequest:((n=o(this,Z))==null?void 0:n.stageAccess)===se.Allowed||o(this,Z).media.audio.canProduce===se.Allowed||o(this,Z).media.video.canProduce===se.Allowed||o(this,Z).media.screenshare.canProduce===se.Allowed?se.Allowed:o(this,Z).media.audio.canProduce===se.CanRequest||o(this,Z).media.video.canProduce===se.CanRequest||o(this,Z).media.screenshare.canProduce===se.CanRequest?se.CanRequest:se.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.acceptWaitingRequests)!=null?e:Ne.acceptWaitingRequests}get requestProduceVideo(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:n.canProduce)===se.CanRequest}get requestProduceAudio(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.canProduce)===se.CanRequest}get requestProduceScreenshare(){var t,e,n;return((n=(e=(t=o(this,Z))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:n.canProduce)===se.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.disableParticipantAudio)!=null?e:Ne.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canAcceptProductionRequests)!=null?e:Ne.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.disableParticipantVideo)!=null?e:Ne.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.kickParticipant)!=null?e:Ne.kickParticipant}get pinParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.pinParticipant)!=null?e:Ne.pinParticipant}get canRecord(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canRecord)!=null?e:Ne.canRecord}get waitingRoomType(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.waitingRoomType)!=null?e:Ne.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.waitingRoomType)!=null?e:Ne.waitingRoomType}get plugins(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.plugins)!=null?e:Ne.plugins}get polls(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.polls)!=null?e:Ne.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return o(this,Z).media.audio.canProduce===se.CanRequest||o(this,Z).media.video.canProduce===se.CanRequest||o(this,Z).media.screenshare.canProduce===se.CanRequest}get canProduceVideo(){var t;const e=(t=o(this,Z).media.video.canProduce)!=null?t:Ne.media.video.canProduce;return this.stageEnabled&&(o(this,nn,fn)==="ACCEPTED_TO_JOIN_STAGE"||o(this,nn,fn)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,nn,fn)==="OFF_STAGE"||o(this,nn,fn)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=o(this,Z).media.screenshare.canProduce)!=null?t:Ne.media.screenshare.canProduce;return this.stageEnabled&&(o(this,nn,fn)==="ACCEPTED_TO_JOIN_STAGE"||o(this,nn,fn)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,nn,fn)==="OFF_STAGE"||o(this,nn,fn)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=o(this,Z).media.audio.canProduce)!=null?t:Ne.media.audio.canProduce;return this.stageEnabled&&(o(this,nn,fn)==="ACCEPTED_TO_JOIN_STAGE"||o(this,nn,fn)==="ON_STAGE")&&e===se.CanRequest?se.Allowed:this.stageEnabled&&(o(this,nn,fn)==="OFF_STAGE"||o(this,nn,fn)==="REQUESTED_TO_JOIN_STAGE")&&e===se.Allowed?se.NotAllowed:e}get chatPublic(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.public)!=null?n:Ne.chat.public}get chatPrivate(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.private)!=null?n:Ne.chat.private}get chatChannel(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.channel)!=null?n:Ne.chat.channel}get chatMessage(){var t,e,n;return(n=(e=(t=o(this,Z))==null?void 0:t.chat)==null?void 0:e.message)!=null?n:Ne.chat.message}get connectedMeetings(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.connectedMeetings)!=null?e:Ne==null?void 0:Ne.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.hiddenParticipant)!=null?e:Ne.hiddenParticipant}get showParticipantList(){var t;return(t=o(this,Z).showParticipantList)!=null?t:Ne.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ne.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=o(this,Z))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Ne.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return o(this,Z).media.audio.canProduce===se.Allowed||o(this,Z).media.video.canProduce===se.Allowed||o(this,Z).media.screenshare.canProduce===se.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=o(this,Z).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return o(this,Z).isRecorder}get canSpotlight(){return o(this,Z).canSpotlight}get canLivestream(){return o(this,Z).canLivestream}get transcriptionEnabled(){return o(this,Z).transcriptionEnabled}};let c2=Bo;Z=new WeakMap,Vo=new WeakMap,Uo=new WeakMap,up=new WeakMap,nn=new WeakSet,fn=function(){return o(this,Uo).getValue("stageStatus")};var m0;class d2 extends cn{constructor(){super(...arguments),y(this,"localMediaHandler"),S(this,m0,void 0)}updatePermission(){return p(this,null,function*(){var e,n;const i=(h,u)=>{this.mediaPermissions[h]=u;const g={message:this.mediaPermissions[h],kind:h};u==="DENIED"?L.emit(x.MEDIA_PERMISSION_ERROR,g):L.emit(x.MEDIA_PERMISSION_UPDATE,g)};if(Ue.getName()==="firefox")return;const s="microphone",r="camera",a=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:s}),c=yield(n=navigator==null?void 0:navigator.permissions)==null?void 0:n.query({name:r}),d=(h,u)=>{switch(u){case"granted":i(h,"ACCEPTED");break;case"denied":i(h,"DENIED");break;case"prompt":i(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>d("audio",a.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return p(this,arguments,function*({message:n,kind:i}){switch(i){case"audio":{te.mediaPermission("AUDIO",n),te.mediaPermission("SPEAKER",n);break}case"video":{te.mediaPermission("VIDEO",n);break}case"screenshare":{te.mediaPermission("SCREENSHARE",n);break}}})}init(){return p(this,arguments,function*(e={},n=!1,i=null){var s,r,a,c,d,h;if(Ue.init(),!this.localMediaHandler)try{let u=!0;if(i!=null&&i.getValue("defaults").mediaHandler)u=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:g}=navigator;this.localMediaHandler=yield g.init()}else this.localMediaHandler=new tn(i,e.constraints,(s=i==null?void 0:i.getValue("defaults"))==null?void 0:s.isNonPreferredDevice,(r=i==null?void 0:i.getValue("defaults"))==null?void 0:r.autoSwitchAudioDevice);if(L.on(x.MEDIA_PERMISSION_UPDATE,g=>p(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:g.message,kind:g.kind}),g.message==="NOT_REQUESTED")switch(g==null?void 0:g.kind){case"audio":this.rawAudioTrack&&(m.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(m.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",g)})),L.on(x.MEDIA_PERMISSION_ERROR,g=>p(this,null,function*(){const{kind:E,message:b,constraints:w}=g;this.populateMediaPermissionsInCallstats({message:b,kind:E}),E==="audio"?(m.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):E==="video"&&(m.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),m.error("SelfController::mediaPermissionError",{error:{message:b},constraints:w,mediaPermissionsErrors:{kind:E,message:b}}),this.emit("mediaPermissionError",g),this.emit("mediaPermissionUpdate",{message:b,kind:E})})),u){m.info(`Setting up DyteSelfMedia streams using media handler. audio:${(a=e==null?void 0:e.audio)!=null?a:!0} video:${(c=e==null?void 0:e.video)!=null?c:!0}`);const g=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});n||(yield g)}}catch(u){m.error("DyteSelf::init::Failed To Setup Streams",{error:{name:u.name,message:u.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return p(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return p(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return p(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return p(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 p(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return p(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return p(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return p(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return p(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return p(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return p(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,n){let i;return n==="audio"?i="audioinput":n==="video"?i="videoinput":n==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}setDevice(e){return p(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(n){}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(n){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}m0=new WeakMap;const Fo={},ns={executeWithLock({methodName:t,lockName:e,timeout:n}){return(i,s,r)=>{const a=r.value;return r.value=function(...c){if(Fo[e]){const u=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw u.name="UnsupportedConcurrentMethodExecution",m.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:u.stack},dyteLocker:{methodName:t,lockName:e}}),u}Fo[e]=!0;const d=setTimeout(()=>delete Fo[e],n),h=a.apply(this,c);return Promise.resolve(h).then(()=>{delete Fo[e],clearTimeout(d)}).catch(()=>{delete Fo[e],clearTimeout(d)}),h},r}}};var l2=Object.defineProperty,u2=Object.getOwnPropertyDescriptor,$t=(t,e,n,i)=>{for(var s=i>1?void 0:i?u2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&l2(e,n,s),s},jo,sn,Wo,Ci,rr,pa,Tt,Ct,dt,gt,Ho,qo,rl,hp,f0;let bt=(f0=class extends d2{constructor(t,e,n,i,s){var r;super(),S(this,rr),S(this,Tt),S(this,dt),S(this,rl),y(this,"name"),y(this,"picture"),y(this,"customParticipantId"),y(this,"waitlistStatus"),S(this,jo,void 0),S(this,sn,void 0),S(this,Wo,void 0),y(this,"role"),y(this,"userId"),y(this,"organizationId"),y(this,"supportsRemoteControl",!1),y(this,"device"),S(this,Ci,void 0),y(this,"hidden",!1),y(this,"presetName"),y(this,"roomState","init"),S(this,Ho,new Set),S(this,qo,new Set),T(this,Ci,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(r=e.customParticipantId)!=null?r:e.clientSpecificId,this.waitlistStatus="none",T(this,sn,n),T(this,jo,i),this.hidden=!1,T(this,Wo,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ue.isElectron(),this.device=Ue.getDeviceInfo(),this.presetName=s,i.viewType!==Ft.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),Q(this,rl,hp).call(this)}get stageStatus(){return o(this,Ci).getValue("stageStatus")}get id(){return o(this,Ci).getValue("peerId")}static __init__(t,e,n,i,s,r=!1){return p(this,null,function*(){var a,c,d,h,u;let g=(c=(a=t.getValue("defaults"))==null?void 0:a.audio)!=null?c:!0,E=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;n.canProduceAudio!=="ALLOWED"&&(g=!1),n.canProduceVideo!=="ALLOWED"&&(E=!1);const b=new bt(t,e,n,i,s);if(i.viewType===Ft.Chat)return b;const w=yL(i.mediaConstraints);return Wi(w,(u=t.getValue("defaults"))==null?void 0:u.mediaConfiguration),yield b.init({audio:g,video:E,constraints:w},r,t),b.setupEvents(),b})}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"),o(this,sn).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",Q(this,rl,hp)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>p(this,null,function*(){if(m.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",H({},er(this))),o(this,dt,gt)&&this.audioEnabled)try{yield o(this,Tt,Ct).shareMic(this.audioTrack)}catch(t){m.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",()=>p(this,null,function*(){if(m.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",H({},er(this))),o(this,dt,gt)&&this.rawVideoTrack===void 0)m.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&o(this,dt,gt))try{const t=yield o(this,Tt,Ct).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&re.hasFeature(ue.EXP_RESHARE)&&(yield o(this,Tt,Ct).shareWebcam(this.videoTrack))}catch(t){m.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=>p(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",()=>p(this,null,function*(){if(!o(this,dt,gt)){m.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield o(this,Tt,Ct).shareScreen(this.screenShareTracks)}catch(t){m.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}m.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",H({},er(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>p(this,null,function*(){m.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),m.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",H({},er(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{te.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>p(this,null,function*(){o(this,dt,gt)&&(yield o(this,Tt,Ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),te.videoOff()})),o(this,sn).on("permissionsUpdate",t=>{var e,n,i;(e=t==null?void 0:t.media)!=null&&e.audio&&o(this,sn).canProduceAudio!==se.Allowed&&(this.disableAudio(),m.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(n=t==null?void 0:t.media)!=null&&n.video&&o(this,sn).canProduceVideo!==se.Allowed&&(this.disableVideo(),m.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(i=t==null?void 0:t.media)!=null&&i.screenshare&&o(this,sn).canProduceScreenshare!==se.Allowed&&(this.disableScreenShare(),m.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return o(this,sn)}get config(){return o(this,jo)}get roomJoined(){var t;return o(this,jo).viewType===Ft.Livestream&&this.stageStatus!=="ON_STAGE"?((t=o(this,Ci).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:o(this,dt,gt)}setName(t){if(!t)throw new O("Name cannot be empty.","1103");this.name=t}setupTracks(){return p(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 p(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return p(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return p(this,null,function*(){if(this.permissions.canProduceAudio!==se.NotAllowed&&!(o(this,sn).canProduceAudio===se.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(te.audioOn(),yield this.localMediaHandler.enableAudio(),o(this,dt,gt)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield o(this,Tt,Ct).shareMic(this.audioTrack)}catch(t){m.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;o(this,Tt,Ct).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return p(this,null,function*(){if(o(this,sn).canProduceVideo!==se.NotAllowed&&!(o(this,sn).canProduceVideo===se.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(te.videoOn(),yield this.localMediaHandler.enableVideo(),o(this,dt,gt)&&this.stageStatus==="ON_STAGE")try{yield o(this,Tt,Ct).shareWebcam(this.videoTrack)}catch(t){m.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),m.info("DyteSelf.enableVideo",H({},er(this)))}})}updateVideoConstraints(t){return p(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new O("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return p(this,null,function*(){if(!o(this,dt,gt))throw new O("Can`t enable screenshare without joining room","1105");if(o(this,sn).canProduceScreenshare!==se.NotAllowed&&!(o(this,sn).canProduceScreenshare===se.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 o(this,Tt,Ct).shareScreen(this.screenShareTracks)}catch(t){m.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 p(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new O("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return p(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),o(this,dt,gt)&&o(this,Tt,Ct).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),te.audioOff())})}disableVideo(){return p(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),o(this,dt,gt)&&(yield o(this,Tt,Ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),te.videoOff())})}disableScreenShare(){return p(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),o(this,dt,gt)&&(yield o(this,Tt,Ct).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;T(this,Wo,t);const i=t?"pinned":"unpinned";(n=o(this,rr,pa))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return o(this,Wo)}pin(){return p(this,null,function*(){if(!o(this,dt,gt))throw new O("Can`t pin participants without joining room","1105");return this.show(),o(this,Tt,Ct).pinPeer(this.id)})}unpin(){return p(this,null,function*(){if(!o(this,dt,gt))throw new O("Can`t unpin participants without joining room","1105");return o(this,Tt,Ct).pinPeer(null)})}hide(){return p(this,null,function*(){if(!o(this,dt,gt))throw new O("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!o(this,dt,gt))throw new O("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return p(this,null,function*(){var e,n,i;if(!t)throw new O("No device selected","1104");const s=this.getCurrentDevices();if(t.deviceId&&(((e=s==null?void 0:s.audio)==null?void 0:e.deviceId)===t.deviceId||((n=s==null?void 0:s.video)==null?void 0:n.deviceId)===t.deviceId||((i=s==null?void 0:s.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(m.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),re.hasFeature(ue.SKIP_SETTING_IN_USE_DEVICE)))throw new O("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(r){o(this,dt,gt)&&(yield o(this,Tt,Ct).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(r){o(this,dt,gt)&&(yield o(this,Tt,Ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,n,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(n=this.videoTrack)==null||n.stop(),(i=this.rawVideoTrack)==null||i.stop()}registerVideoElement(t,e=!1){var n,i;e?o(this,Ho).add(t):o(this,qo).add(t),this.updateVideo(t),e||(i=o(this,rr,pa))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?o(this,Ho).delete(t):(o(this,qo).delete(t),o(this,rr,pa).removeSource(this.id))}updateVideo(t,e=!1){var n,i,s;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(n=t.srcObject)==null?void 0:n.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const a=new MediaStream;a.addTrack(this.videoTrack),t.srcObject=a,e||(i=o(this,rr,pa))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(s=o(this,rr,pa))==null||s.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},jo=new WeakMap,sn=new WeakMap,Wo=new WeakMap,Ci=new WeakMap,rr=new WeakSet,pa=function(){return o(this,Ci).getValue("pip")},Tt=new WeakSet,Ct=function(){return o(this,Ci).getValue("roomNodeClient")},dt=new WeakSet,gt=function(){var t;return((t=o(this,Ci).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ho=new WeakMap,qo=new WeakMap,rl=new WeakSet,hp=function(){Array.from(o(this,qo)).forEach(t=>this.updateVideo(t,!1)),Array.from(o(this,Ho)).forEach(t=>this.updateVideo(t,!0))},f0);$t([k.trace("DyteSelf.cleanupEvents")],bt.prototype,"cleanupEvents",1),$t([k.trace("DyteSelf.setupEvents")],bt.prototype,"setupEvents",1),$t([k.trace("DyteSelf.setupTracks")],bt.prototype,"setupTracks",1),$t([k.trace("DyteSelf.destructMediaHandler")],bt.prototype,"destructMediaHandler",1),$t([k.trace("DyteSelf.removeDocumentEventListeners")],bt.prototype,"removeDocumentEventListeners",1),$t([ns.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],bt.prototype,"enableAudio",1),$t([ns.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],bt.prototype,"enableVideo",1),$t([k.trace("DyteSelf.updateVideoConstraints")],bt.prototype,"updateVideoConstraints",1),$t([k.trace("DyteSelf.enableScreenShare"),ns.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],bt.prototype,"enableScreenShare",1),$t([k.trace("DyteSelf.updateScreenshareConstraints")],bt.prototype,"updateScreenshareConstraints",1),$t([ns.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],bt.prototype,"disableAudio",1),$t([ns.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],bt.prototype,"disableVideo",1),$t([ns.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],bt.prototype,"disableScreenShare",1),$t([k.trace("DyteSelf.setDevice")],bt.prototype,"setDevice",1),bt=$t([Ot("1100")],bt);var h2=Object.defineProperty,p2=Object.getOwnPropertyDescriptor,m2=(t,e,n,i)=>{for(var s=i>1?void 0:i?p2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&h2(e,n,s),s};let ma;var al,g0;const v0=(g0=class{constructor(t,e){y(this,"socket"),S(this,al,void 0),T(this,al,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return ma||(ma=new v0(t,e)),ma}static cleanup(){var t;try{(t=ma==null?void 0:ma.socket)==null||t.disconnect()}catch(e){m.error("roomSocketHandler::cleanup")}ma=void 0}joinRoom(t){return p(this,null,function*(){var e;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(e=t.name)!=null?e:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},i=this.socket.sendMessagePromise(z.joinRoom,CA.toBinary(n));try{const{peer:s}=Wr.fromBinary((yield i).payload);o(this,al).getValue("connectionHandler").socketJoined=!0,L.emit(x.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const r=this.getRoomState(),a=this.getRoomPeersNonPaginated(),[{room:c},{peers:d}]=yield Promise.all([r,a]);return L.emit(x.ROOM_STATE,c),L.emit(x.SOCKET_PEERS,d),{peer:s}}catch(s){throw m.error("RoomSocketHandler.joinRoom.failed",{error:s}),new O("Error: RoomSocketHandler.joinRoom failed.","0002",s)}})}getAllAddedParticipants(){return p(this,null,function*(){try{return uM.fromBinary((yield this.socket.sendMessagePromise(z.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:n}=e,i=Fc(e,["id"]);return ee(H({},i),{userId:n})})}catch(t){return[]}})}getRoomPeers(t,e,n){return p(this,null,function*(){let i;try{const s={seachQuery:t,limit:e,offset:n},r=yield this.socket.sendMessagePromise(z.getRoomPeersInfo,vA.toBinary(s));i=Sh.fromBinary(r.payload)}catch(s){m.error("getRoomPeers::binary_decode_error",{error:s})}return i})}getRoomPeersNonPaginated(){return p(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(z.getRoomPeersInfo);t=Sh.fromBinary(e.payload)}catch(e){m.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return p(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(z.getRoomPeersInfo);t=Sh.fromBinary(e.payload)}catch(e){m.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return p(this,null,function*(){let e;try{const n=yield this.socket.sendMessagePromise(z.getPeerInfo,ry.toBinary({peerId:t}));e=Wr.fromBinary(n.payload)}catch(n){m.error("getPeerInfo::binary_decode_error",{error:n})}return e})}getRoomState(){return p(this,null,function*(){let t=sy.create();try{const e=yield this.socket.sendMessagePromise(z.getRoomInfo);t=sy.fromBinary(e.payload)}catch(e){m.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return p(this,null,function*(){let t=uy.create();try{const e=yield this.socket.sendMessagePromise(z.getRoomStageState);t=uy.fromBinary(e.payload)}catch(e){m.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return p(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(z.broadcastMessage,Za.toBinary(n))})}broadcastToMeetings(t,e,n){return p(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(z.broadcastToEntity,Za.toBinary(i))})}broadcastToPeers(t,e,n){return p(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(z.broadcastToEntity,Za.toBinary(i))})}leaveRoom(){return p(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(z.leaveRoom,PA.toBinary({}))})}kick(t){return p(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(z.kick,dy.toBinary(e))})}kickAll(t=!1){return p(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(z.kickAll,Kv.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(z.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(z.acceptWaitingRoomRequests,vM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(z.denyWaitingRoomRequests,EM.toBinary(e))}updatePermissions(t,e){return p(this,null,function*(){const n={updatePeersPresets:[]};return t.forEach(i=>{n.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Pd.updateUserPreset,KM.toBinary(n))})}handleSocketEvents(){this.socket.on(z.broadcastMessage,({payload:t})=>{try{const e=Za.fromBinary(t);L.emit(x.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){m.error("failed to decode broadcast message:",e)}}),this.socket.on(z.broadcastToEntity,({payload:t})=>{try{const e=Za.fromBinary(t);L.emit(x.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){m.error("failed to decode peer broadcast message:",e)}})}on(t,e){let n,i;switch(t){case z.joinRoom:case z.leaveRoom:case z.kick:case z.kickAll:{n=Wr.fromBinary.bind(Wr),i=Wr.create();break}case z.getWaitingRoomRequests:{n=(s,r)=>s?ly.fromBinary(s,r):{requests:[]},i=ly.create();break}case z.recordingPaused:case z.recordingStarted:case z.recordingStopped:{n=ky.fromBinary.bind(ky);break}case Pd.updateUserPreset:{n=py.fromBinary.bind(py);break}case Nn.peerJoinedBroadcast:case Tn.peerJoinedBroadcast:{n=Qv.fromBinary.bind(Qv);break}case Nn.selfJoinComplete:case Tn.selfJoinComplete:{n=fh.fromBinary.bind(fh);break}case Nn.globalPeerPinBroadcast:case Tn.globalPeerPinBroadcast:{n=ey.fromBinary.bind(ey);break}case Nn.selectedPeer:case Tn.selectedPeer:{n=mh.fromBinary.bind(mh);break}case Nn.selectedPeerDiff:case Tn.selectedPeerDiff:{n=Yv.fromBinary.bind(Yv);break}case Nn.leaveRoom:case Tn.leaveRoom:{n=gh.fromBinary.bind(gh);break}}this.socket.on(t,({payload:s})=>{let r=i;if(!n)return e(void 0);try{r=n(s)}catch(a){m.error("roomSocketHandler::on::binary_decode_error",{error:a})}return e(r)})}getUserPermissions(t){return p(this,null,function*(){const e={userIds:[t]};try{const n=yield this.socket.sendMessagePromise(Pd.getUserPresets,jM.toBinary(e)),i=GM.fromBinary(n.payload).peerPresets[0],s=new TextDecoder().decode(i.preset),r=JSON.parse(s).permissions;return{chat:r.chat,polls:r.polls,plugins:r.plugins}}catch(n){throw m.error("Error in getting user preset",{error:n}),n}})}},al=new WeakMap,g0);let ol=v0;m2([k.trace("RoomSocketHandler.joinRoom")],ol.prototype,"joinRoom",1);var ar={},cl={};Object.defineProperty(cl,"__esModule",{value:!0}),cl.Logger=void 0;class f2{constructor(e){}debug(){}warn(){}error(){}}cl.Logger=f2,Object.defineProperty(ar,"__esModule",{value:!0});var dl=ar.AwaitQueue=ar.AwaitQueueRemovedTaskError=ar.AwaitQueueStoppedError=void 0;const g2=cl,is=new g2.Logger;class pp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,pp)}}ar.AwaitQueueStoppedError=pp;class ll extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ll)}}ar.AwaitQueueRemovedTaskError=ll;class v2{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,n){return p(this,null,function*(){if(n=n!=null?n:e.name,is.debug(`push() [name:${n}]`),typeof e!="function")throw new TypeError("given task is not a function");if(n)try{Object.defineProperty(e,"name",{value:n})}catch(i){}return new Promise((i,s)=>{const r={id:this.nextTaskId++,task:e,name:n,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(r.completed)return;r.completed=!0,this.pendingTasks.delete(r.id),is.debug(`resolving task [name:${r.name}]`),i(a);const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:a=>{if(!r.completed&&(r.completed=!0,this.pendingTasks.delete(r.id),is.debug(`rejecting task [name:${r.name}]: %s`,String(a)),s(a),!this.stopping)){const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)}}};this.pendingTasks.set(r.id,r),this.pendingTasks.size===1&&this.execute(r)})})}stop(){is.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())is.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){is.debug(`remove() [taskIdx:${e}]`);const n=Array.from(this.pendingTasks.values())[e];if(!n){is.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}n.reject(new ll)}dump(){const e=Date.now();let n=0;return Array.from(this.pendingTasks.values()).map(i=>({idx:n++,task:i.task,name:i.name,enqueuedTime:i.executedAt?i.executedAt-i.enqueuedAt:e-i.enqueuedAt,executionTime:i.executedAt?e-i.executedAt:0}))}execute(e){return p(this,null,function*(){if(is.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const n=yield e.task();e.resolve(n)}catch(n){e.reject(n)}})}}dl=ar.AwaitQueue=v2;function y2(t,e){const n=new Error(e);return n.name=t,n}class Go extends O{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Go):this.stack=new Error(e).stack}}class rn extends O{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,rn):this.stack=new Error(e).stack}}class or extends O{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,rn):this.stack=new Error(e).stack}}const y0=t=>new Promise(e=>setTimeout(e,t));function mp(t,e){return p(this,null,function*(){return new Promise((n,i)=>p(this,null,function*(){const{strategy:s,maxRetryCount:r,delayTime:a}=H({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,h=!1;const u=g=>{h=!0,i(g)};for(;c<r;){try{const g=yield t(c,u);return n(g)}catch(g){if(d=g,h)break;if(c<r)s==="linear"?yield y0(a*(c+1)):s==="exponential"&&(yield y0(a*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function E2(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function S2(t){return t.map(e=>({uri:e.uri}))}function ul(t){return{codecs:E2(t.codecs),headerExtensions:S2(t.headerExtensions?t.headerExtensions:[])}}function T2(t){const e=RTCRtpReceiver.getCapabilities("audio"),n=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),s=RTCRtpSender.getCapabilities("video");t&&(n.codecs=n.codecs.filter(({mimeType:a})=>t===a),s.codecs=s.codecs.filter(({mimeType:a})=>t===a));const r={audio:ul(e),video:ul(n)};return{sender:{audio:ul(i),video:ul(s)},receiver:r}}var Nt;class b2{constructor(e,n){S(this,Nt,void 0),y(this,"events"),y(this,"sfuType"),T(this,Nt,e),this.sfuType=n,this.events=n===St.CF?Nn:Tn}joinRoom(e,n,i,s=!1,r=null){return p(this,null,function*(){const a={roomUuid:e,displayName:n,prejoined:s,capabilities:i};return r&&(a.location=r),(yield o(this,Nt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:MP.toBinary(a),timeout:5e3})).payload})}connectTransport(e){return p(this,null,function*(){const n=(yield o(this,Nt).sendMessagePromise(this.events.createWebRTCTransport,aP.toBinary(e))).payload,{transportId:i,description:s,producerIds:r}=Hv.fromBinary(n),a={sdp:s==null?void 0:s.sdp,type:s.type};return{transportId:i,answer:a,producerIds:r}})}produce(e){return p(this,null,function*(){var n,i;const s=(yield o(this,Nt).sendMessagePromise(this.events.produce,WP.toBinary(e))).payload,r=w1.fromBinary(s);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(i=r==null?void 0:r.description)==null?void 0:i.type},producerId:r.producerId}})}consume(e){return p(this,null,function*(){if(this.sfuType===St.HIVE)throw new Error("Hive does not support socket consumer operations");const n=(yield o(this,Nt).sendMessagePromise(this.events.consume,FP.toBinary(e))).payload,{consumerIdsMap:{map:i},description:s}=b1.fromBinary(n);return{consumerStateMap:i,sessionDescription:s}})}closeProducer(e){return p(this,null,function*(){const n=(yield o(this,Nt).sendMessagePromise(this.events.closeProducer,zP.toBinary(e))).payload,{description:i}=M1.fromBinary(n);return i})}closeConsumer(e){return p(this,null,function*(){if(this.sfuType===St.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield o(this,Nt).sendMessagePromise(this.events.closeConsumer,QP.toBinary(e))).payload})}hostControlForPeer(e,n){return p(this,null,function*(){const i={audio:n==="audio",screeShare:!1,video:n==="video",participantId:e},s=(yield o(this,Nt).sendMessagePromise(this.events.hostControlPeer,i1.toBinary(i))).payload;if(!s)return!1;const{status:r}=U1.fromBinary(s);return r==="success"})}hostControlForAll(e){return p(this,null,function*(){const n={audio:e==="audio",screenShare:!1,video:e==="video"},i=(yield o(this,Nt).sendMessagePromise(this.events.hostControlAllPeers,r1.toBinary(n))).payload;if(!i)return!1;const{status:s}=F1.fromBinary(i);return s==="success"})}kickAll(){return p(this,null,function*(){const e={propagateKickAcrossRooms:!1};o(this,Nt).sendMessagePromise(z.kickAll,Kv.toBinary(e))})}kickPeer(e){return p(this,null,function*(){o(this,Nt).sendMessagePromise(z.kick,dy.toBinary(e))})}changeDisplayName(e){return p(this,null,function*(){const n=(yield o(this,Nt).sendMessagePromise(this.events.changeDisplayName,t1.toBinary(e))).payload;if(!n)return!1;const{status:i}=W1.fromBinary(n);return i==="success"})}notifySelfJoinComplete(){return p(this,null,function*(){const e={},n=(yield o(this,Nt).sendMessagePromise(this.events.selfJoinComplete,DP.toBinary(e))).payload;return fh.fromBinary(n)})}audioActivity(e){return p(this,null,function*(){o(this,Nt).sendMessage(this.events.audioActivity,cP.toBinary(e))})}}Nt=new WeakMap;class Jo extends Mt.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...n){const i=this.listenerCount(e);try{return this.emit(e,...n)}catch(s){return m.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:s}),Boolean(i)}}safeEmitAsPromise(e,...n){return p(this,null,function*(){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...n)})}safeEmitAsPromiseWithTimeout(e,n,...i){return p(this,null,function*(){return new Promise((s,r)=>{setTimeout(r,n,"event request timeout");try{this.emit(e.toString(),...i,s,r)}catch(a){m.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:a}),r(a)}})})}}class fp extends Jo{constructor(){super(...arguments),y(this,"_sendWebStream",new MediaStream),y(this,"_sendScreenShareStream",new MediaStream),y(this,"_direction"),y(this,"pc"),y(this,"_transportReady",!1),y(this,"_mapMidTransceiver",new Map),y(this,"enableHighBitrate",!1),y(this,"enableStereo",!1),y(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(m.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){m.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return p(this,null,function*(){m.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return m.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:n=>p(this,null,function*(){m.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n)})}})}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:r,onTrackHandler:a}){m.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(H({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},s),r),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}connect(){return p(this,null,function*(){const e=this.pc.createDataChannel("dyte"),n=yield this.pc.createOffer();return yield this.pc.setLocalDescription(n),m.info(`connect offer: ${JSON.stringify(n)}`),{offerSdp:n,callback:i=>p(this,null,function*(){m.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),e.close()})}})}getTransportStats(){return p(this,null,function*(){return this.pc.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')}getReceiverStats(e){return p(this,null,function*(){this._assertRecvDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.receiver.getStats()})}stopSending(e){return p(this,null,function*(){this._assertSendDirection(),m.debug(`stopSending() [localId:${e}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");n.sender.replaceTrack(null),this.pc.removeTrack(n.sender),n.direction="inactive";const i=yield this.pc.createOffer();return m.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),yield this.pc.setLocalDescription(i),{offerSdp:i,callback:s=>p(this,null,function*(){m.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(s)}]`),yield this.pc.setRemoteDescription(s),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,n){return p(this,null,function*(){this._assertSendDirection(),n?m.debug(`replaceTrack() [localId:${e}, track.id:${n.id}]`):m.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");yield i.sender.replaceTrack(n)})}setMaxSpatialLayer(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters();s.encodings.forEach((r,a)=>{a<=n?r.active=!0:r.active=!1}),yield i.sender.setParameters(s)})}setRtpEncodingParameters(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(n)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters();s.encodings.forEach((r,a)=>{s.encodings[a]=H(H({},r),n)}),yield i.sender.setParameters(s)})}getSenderStats(e){this._assertSendDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),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:m.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),m.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":m.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":m.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:m.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{m.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{m.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:n}=e;n.onopen=()=>{m.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},n.onclose=()=>{m.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},n.onerror=()=>{m.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class gp extends fp{static createFactory(){return()=>new gp}get name(){return"Chrome74"}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:r,onTrackHandler:a}){this._direction=e,this.pc=new RTCPeerConnection(H({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},s),r),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection();const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i});if(!navigator.isReactNative){m.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);m.info(`senders available params: ${JSON.stringify(h)}`);const u=[];s&&s.length&&s.forEach(g=>{var E;const b=h.codecs.find(w=>w.mimeType.includes(g.name));if(g.parameters){m.debug(`codecOption.parameters:${JSON.stringify(g.parameters)}`);const w=((E=b.sdpFmtpLine)==null?void 0:E.split(";"))||[];w.push(...g.parameters);const M=Array.from(new Set(w).values());b.sdpFmtpLine=M.join(";")}u.push(b)}),m.info(`selected codecs: ${JSON.stringify(u)}`),a.setCodecPreferences(u)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),s&&s.findIndex(({name:h})=>h==="opus")>=0){const{enableDtx:h,enableStereo:u}=this,g=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${g}`),c.sdp+=`a=rtcp-fb:111 nack\r
23
- `}this.midTransceiverMap.set(a.mid,a);const d=h=>p(this,null,function*(){return m.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),a.mid});return m.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i.data)))}})}}class hl extends fp{constructor(e){super(),y(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new hl(e)}get name(){return"Firefox60"}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection();const a=this.supportsSendEncodings&&i!==void 0?{sendEncodings:i}:{},c=this.pc.addTransceiver(n,H({direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream]},a));if(!this.supportsSendEncodings&&i){i.reverse();const u=c.sender.getParameters();u.encodings=i,yield c.sender.setParameters(u)}const d=(u,g)=>{var E;const b=Na(u),w=b.media[b.media.length-1],M=w.rtp.filter(X=>g.some(A=>A.name===X.codec)),D=w.fmtp.filter(X=>M.some(A=>A.payload===X.payload)),F=(E=w.rtcpFb)==null?void 0:E.filter(X=>M.some(A=>A.payload===X.payload)),Y=M.map(X=>X.payload);return b.media[b.media.length-1].rtp=M,b.media[b.media.length-1].fmtp=D,b.media[b.media.length-1].rtcpFb=F,b.media[b.media.length-1].payloads=Y.join(" "),pu(b)},h=yield this.pc.createOffer();if(h.sdp=d(h.sdp,s),m.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(h)}]`),yield this.pc.setLocalDescription(h),n==="audio"||n.kind==="audio"){const{enableDtx:u,enableStereo:g}=this,E=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;h.sdp=h.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${u?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${E}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:h,callback:u=>p(this,null,function*(){return m.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),yield this.pc.setRemoteDescription(u),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,n){return p(this,null,function*(){this._assertSendDirection(),m.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const s=i.sender.getParameters(),r=s.encodings.length-1-n;s.encodings.forEach((a,c)=>{c>=r?a.active=!0:a.active=!1}),yield i.sender.setParameters(s)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>p(this,null,function*(){const s=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(s)))})})}}class vp extends fp{static createFactory(){return()=>new vp}get name(){return"Safari12"}send(e){return p(this,arguments,function*({track:n,encodings:i,codecOptions:s,screenShare:r}){this._assertSendDirection(),m.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[r?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i}),c=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);m.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];s&&s.length>0&&s.forEach(u=>{var g;const E=c.codecs.find(b=>b.mimeType.includes(u.name));if(u.parameters){m.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const b=((g=E.sdpFmtpLine)==null?void 0:g.split(";"))||[];b.push(...u.parameters);const w=[...new Set(b).values()];E.sdpFmtpLine=w.join(";")}d.push(E)}),m.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const h=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(h),n==="audio"||n.kind==="audio"){const{enableStereo:u,enableDtx:g}=this,E=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;h.sdp=h.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${g?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${E}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:h,callback:u=>p(this,null,function*(){return m.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),yield this.pc.setRemoteDescription(u),a.mid}),sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:n}=e;n.onmessage=i=>p(this,null,function*(){const s=String.fromCharCode(...new Uint8Array(i.data));this.safeEmit("datachannel",e.channel,s)})}}}function k2(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var pl,fa,Ri,Pi,ss,ml,yp,Ep,E0,Sp,S0;class w2 extends Jo{constructor(e){var n;super(),S(this,Pi),S(this,ml),S(this,Ep),S(this,Sp),y(this,"rtpReceiver"),y(this,"id"),y(this,"localId"),y(this,"producerId"),y(this,"producingTransportId"),y(this,"mimeType"),y(this,"track"),y(this,"peerId"),y(this,"appData"),y(this,"transceiver"),S(this,pl,void 0),S(this,fa,void 0),S(this,Ri,void 0),this.id=e.id,this.localId=e.localId,T(this,pl,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,T(this,Ri,!1),this.producerId=e.producerId,this.track=e.track,T(this,fa,(n=e.paused)!=null?n:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,Q(this,Ep,E0).call(this)}get closed(){return o(this,Ri)}get kind(){return this.track.kind}get paused(){return o(this,fa)}close(e,n){o(this,Ri)||(m.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,o(this,Pi,ss)),T(this,Ri,!0),n&&(Q(this,Sp,S0).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return p(this,null,function*(){if(o(this,Ri))throw new rn("closed");return o(this,pl).getReceiverStats(this.localId)})}pause(){if(m.debug("consumer::pause()",o(this,Pi,ss)),o(this,Ri)){m.error("consumer::pause() | Consumer closed",o(this,Pi,ss));return}T(this,fa,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(m.debug("consumer::resume()",o(this,Pi,ss)),o(this,Ri)){m.error("Consumer::resume() | Consumer closed",o(this,Pi,ss));return}T(this,fa,!1),this.track.enabled=!0,this.safeEmit("resume")}}pl=new WeakMap,fa=new WeakMap,Ri=new WeakMap,Pi=new WeakSet,ss=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},ml=new WeakSet,yp=function(){m.debug('Consumer::track "ended" event',o(this,Pi,ss)),this.safeEmit("trackended")},Ep=new WeakSet,E0=function(){this.track.addEventListener("ended",Q(this,ml,yp).bind(this))},Sp=new WeakSet,S0=function(){try{this.track.removeEventListener("ended",Q(this,ml,yp)),this.track.stop()}catch(t){m.error("Consumer::destroyTrack()",ee(H({},o(this,Pi,ss)),{error:t}))}};var ri,$o,Ko,ga,Hn,Lt,cr,zo,_n,qn;class _2 extends Jo{constructor(e){var n,i;super(),S(this,_n),y(this,"id"),y(this,"localId"),S(this,ri,void 0),y(this,"kind"),y(this,"appData"),y(this,"rtpSender"),S(this,$o,void 0),S(this,Ko,void 0),S(this,ga,void 0),S(this,Hn,!1),S(this,Lt,void 0),S(this,cr,void 0),S(this,zo,void 0),this.id=e.id,this.localId=e.localId,T(this,Lt,e.track),this.kind=(n=e.track)==null?void 0:n.kind,T(this,cr,e.disableTrackOnPause?!((i=e.track)!=null&&i.enabled):!1),T(this,zo,void 0),T(this,$o,e.stopTracks),T(this,Ko,e.disableTrackOnPause),T(this,ga,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),T(this,ri,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return o(this,Hn)}get track(){return o(this,Lt)}get paused(){return o(this,cr)}get maxSpatialLayer(){return o(this,zo)}close(e){return p(this,null,function*(){if(o(this,Hn))return;if(m.debug(`Producer::close() ${e?`with reason ${e}`:""}`,o(this,_n,qn)),T(this,Hn,!0),this._destroyTrack(),e===gl){this.safeEmit("close",{reason:e});return}const{offerSdp:n,callback:i}=yield o(this,ri).stopSending(this.localId),{answer:s}=yield this.safeEmitAsPromise("close",{offer:n,reason:e});i(s)})}getStats(){return p(this,null,function*(){if(o(this,Hn))throw new rn("closed");return o(this,ri).getSenderStats(this.localId)})}pause(){m.debug("Producer::pause()",o(this,_n,qn)),o(this,Hn)&&m.error("Producer::pause() | Producer closed",o(this,_n,qn)),T(this,cr,!0),o(this,Lt)&&o(this,Ko)&&(o(this,Lt).enabled=!1),o(this,ga)&&o(this,ri).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(m.debug("Producer::resume()",o(this,_n,qn)),o(this,Hn)){m.error("Producer::resume() | Producer closed",o(this,_n,qn));return}T(this,cr,!1),o(this,Lt)&&o(this,Ko)&&(o(this,Lt).enabled=!0),o(this,ga)&&o(this,ri).replaceTrack(this.localId,o(this,Lt)),this.emit("resume")}replaceTrack(e){return p(this,arguments,function*({track:n}){if(m.debug(`Producer::replaceTrack() trackId: ${n==null?void 0:n.id}`,o(this,_n,qn)),o(this,Hn)){if(n&&o(this,$o))try{n.stop()}catch(i){m.error("Producer::replaceTrack",ee(H({},o(this,_n,qn)),{error:i}))}throw new rn("closed")}else if(n&&n.readyState==="ended")throw new rn("track ended");if(n===o(this,Lt)){m.debug(`replaceTrack() | same track, ignored trackId: ${n.id}`,o(this,_n,qn));return}(!o(this,ga)||!o(this,cr))&&(yield o(this,ri).replaceTrack(this.localId,n)),this._destroyTrack(),T(this,Lt,n),this._handleTrack()})}setMaxSpatialLayer(e){return p(this,null,function*(){if(o(this,Hn))throw new rn("closed");if(this.kind!=="video")throw new Go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield o(this,ri).setMaxSpatialLayer(this.localId,e),T(this,zo,e)})}setRtpEncodingParameters(e){return p(this,null,function*(){if(o(this,Hn))throw new rn("closed");if(typeof e!="object")throw new TypeError("invalid params");yield o(this,ri).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){m.debug(`Producer::track "ended" event trackId: ${this.track.id}`,o(this,_n,qn)),this.safeEmit("trackended",this.track.id)}_handleTrack(){o(this,Lt)&&o(this,Lt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(o(this,Lt))try{o(this,Lt).removeEventListener("ended",this._onTrackEnded),o(this,$o)&&o(this,Lt).stop()}catch(n){m.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,ee(H({},o(this,_n,qn)),{error:n}))}}}ri=new WeakMap,$o=new WeakMap,Ko=new WeakMap,ga=new WeakMap,Hn=new WeakMap,Lt=new WeakMap,cr=new WeakMap,zo=new WeakMap,_n=new WeakSet,qn=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function T0(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Tp(t){return Math.random().toString(36).substring(2,2+t)}const fl=1;function b0(t){const e=t;return delete e.payload._bolt,e}function I2(t){return t.payload&&T0(t.payload)}function k0(t){var e,n;return I2(t)&&(n=(e=t.payload._bolt)==null?void 0:e.id)!=null?n:""}var dr;const Yo=class extends Mt.EventEmitter{constructor(t,e,n){super(),y(this,"channel"),y(this,"queue"),y(this,"serverProtocolVersion"),S(this,dr,new Map),y(this,"respond",(i,s,r=!1)=>{let a;r?a=Yo.createErrorResponse(i,s):a=Yo.createResponse(i,s),this.channel.send(JSON.stringify(a))}),y(this,"notify",i=>{const s=Yo.createNotification(i);this.channel.send(JSON.stringify(s))}),y(this,"request",i=>p(this,null,function*(){const s=Yo.createRequest(i),r=new Promise((a,c)=>{const{id:d}=s.payload._bolt,h={id:d,method:s.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(h.timer),a(u))},timer:setTimeout(()=>{this.queue.delete(d)&&c(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(h.timer),c(u))}};this.queue.set(d,h)});return this.channel.send(JSON.stringify(s)),r})),y(this,"send",i=>{const s=JSON.stringify(i),r=16384;if(s.length>r){const a=r-200,c=Math.ceil(s.length/a),d=[];for(let u=0;u<c;u+=1){const g=u*a,E=(u+1)*a;d.push(s.slice(g,E))}const h=Ar();for(let u=0;u<c;u+=1){const g=d[u],E=JSON.stringify({id:h,count:c,chunkIndex:u,chunk:g});m.debug(`Sending message chunk over dc: ${E}`),this.channel.send(E)}}else m.debug(`Sending message over dc: ${s}`),this.channel.send(s)}),y(this,"processMessage",i=>{var s;o(this,dr).has(i.id)||o(this,dr).set(i.id,[]);const r=o(this,dr).get(i.id);if(r[i.chunkIndex]=i,(r==null?void 0:r.length)===i.count&&!r.some(a=>a===void 0)){const a=o(this,dr).get(i.id),c=a==null?void 0:a.reduce((h,u)=>h+u.chunk,"");o(this,dr).delete(i.id);const d=JSON.parse(c);if(!d.payload||!T0(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=(s=d.payload._bolt)==null?void 0:s.version,!this.processResponseMsg(d))return d}}),y(this,"processResponseMsg",i=>{const{id:s}=i.payload._bolt,r=this.queue.get(s);return r?(m.debug(`resolving pending request with id: ${s}, complete response: ${JSON.stringify(i)}`),i.type==="error"?r.cancel(b0(i)):r.resolve(b0(i)),!0):!1}),y(this,"processBoltHandshake",i=>{var s,r;return i.type==="_bolt"||i.type==="handshake"?(this.respond((r=(s=i.payload._bolt)==null?void 0:s.id)!=null?r:Tp(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=n,this.channel=t,this.queue=new Map}};let Qo=Yo;dr=new WeakMap,y(Qo,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ee(H({},t.payload),{_bolt:{id:Tp(8),type:"REQUEST",version:fl}})}}),y(Qo,"createResponse",(t,e)=>{var n;if((n=e.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:ee(H({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:fl}})}}),y(Qo,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ee(H({},t.payload),{bolt:{id:Tp(8),type:"NOTIFY",version:fl}})}}),y(Qo,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:fl}}}));function C2(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(n=>n.then(i=>({status:"fulfilled",value:i})).catch(i=>({status:"rejected",reason:i})));return Promise.all(e)}const gl="transport closed";var Xo;const bp=class extends Jo{constructor(t,{id:e,direction:n,handlerFactory:i,iceServers:s,iceTransportPolicy:r,proprietaryConstraints:a,additionalSettings:c,appData:d,config:h}){var u,g,E;super(),y(this,"awaitQueue"),y(this,"observer"),S(this,Xo,void 0),y(this,"id"),y(this,"serverId"),y(this,"direction"),y(this,"maxSctpMessageSize"),y(this,"handler"),y(this,"connectionState","new"),y(this,"producers"),y(this,"consumers"),y(this,"datachannels"),y(this,"connected",!1),y(this,"eventsDCReadyPromise"),y(this,"eventsDCReadyPromiseResolver"),y(this,"eventsDCFailureTimer"),y(this,"transportConnectionPromise"),y(this,"consumerTrackEvents"),y(this,"unknownTracksMap"),y(this,"appData"),m.debug(`constructor() [id: ${e}, direction: ${n}]`),T(this,Xo,t),this.id=e,this.direction=n;const b=k2(c,{});delete b.iceServers,delete b.iceTransportPolicy,delete b.bundlePolicy,delete b.rtcpMuxPolicy,delete b.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new dl,this.observer=new Jo,this.handler=i(),this.handler.enableHighBitrate=(u=h==null?void 0:h.enableHighBitrate)!=null?u:!1,this.handler.enableStereo=(g=h==null?void 0:h.enableStereo)!=null?g:!1,this.handler.enableDtx=(E=h==null?void 0:h.enableDtx)!=null?E:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:n,iceServers:s,iceTransportPolicy:r,additionalSettings:c,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(w=>{this.observer.once("connected",()=>{w(!0)}),this.observer.once("disconnect",()=>{w(!1)}),this.observer.once("close",()=>{w(!1)})}),this.eventsDCReadyPromise=new Promise(w=>{this.eventsDCReadyPromiseResolver=w}),this.handler.on("@connectionstatechange",w=>{w!==this.connectionState&&(m.debug(`connection state changed to ${w}`),this.connectionState=w,w==="connected"&&(this.connected=!0,this.observer.emit("connected")),w==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(w==="failed"||w==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",w))}),this.handler.on("@icecandidate",({candidate:w})=>{this.closed||this.safeEmit("icecandidate",w)}),this.handler.on("dc_open",w=>{let M=this.datachannels.get(w.label);M||(M||(M=new Qo(w,w.label,this.serverId),this.datachannels.set(w.label,M)),this.eventsDCFailureTimer=setTimeout(()=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",w.label))},5e3))}),this.handler.on("datachannel",(w,M)=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const D=this.datachannels.get(w.label);if(!D){m.error("unregistered datachannel for message",{rtcChannel:{label:w.label,message:M}});return}try{const F=JSON.parse(M);m.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const Y=D.processMessage(F);if(!Y)return;m.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(Y)}`),this.emit(`datachannel:${w.label}`,D.label,Y)}catch(F){m.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(t){this.serverId=t}getDatachannel(t){return this.datachannels.get(t)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(m.debug("Transport close called"),this.connectionState="closed",this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(gl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(gl)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return p(this,null,function*(){if(this.closed)throw new rn("closed");return this.handler.getTransportStats()})}connect(t){return p(this,null,function*(){try{if(yield this.awaitQueue.push(()=>p(this,null,function*(){const{offerSdp:e,callback:n}=yield this.handler.connect(),{transportId:i,answer:s}=yield t(e);this.setServerId(i),yield n(s)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(o(this,Xo)===St.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw m.error("transport failed to connect:",{error:e}),e}})}restartIce(){return p(this,null,function*(){if(m.debug("restartIce()"),this.closed)throw new rn("closed");return this.handler.restartIce()})}canProduce(t){return p(this,null,function*(){const{track:e,appData:n}=t;if(e){if(this.direction!=="send")throw new Go("not a sending Transport");if(e.readyState==="ended")throw new rn("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(n&&typeof n!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new or("transport not connected");return!0})}produce(t,e){return p(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:n,encodings:i,codecOptions:s,stopTracks:r=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;m.debug(`produce() [track:${n.id}]`);const{producerId:h,localId:u,rtpSender:g}=yield this.awaitQueue.push(()=>p(this,null,function*(){const{offerSdp:E,callback:b,sender:w,mid:M}=yield this.handler.send({track:n,encodings:i,codecOptions:s,screenShare:d==null?void 0:d.screenShare}),{answer:D,producerId:F}=yield e({offer:E,kind:n.kind,paused:a?!n.enabled:!1,appData:ee(H({},d||{}),{mid:M}),codecOptions:s,producingTransportId:this.serverId}),Y=yield b(D);return{producerId:F,localId:Y,rtpSender:w}}),"producer");return this.createProducerObject({id:h,localId:u,track:n,stopTracks:r,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:g})})}createProducerObject(t){return p(this,null,function*(){const e=new _2(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return p(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return p(this,null,function*(){if(this.closed)throw new rn("closed");if(this.direction!=="recv")throw new Go("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.transportConnectionPromise))throw new or("transport not connected");return!0})}consume(t,e,n){return p(this,null,function*(){return this.awaitQueue.push(()=>p(this,null,function*(){const i={},{consumerStates:s,sessionDescription:r,failedProducers:a}=yield e(t);s.forEach((h,u)=>{i[u]=this.createConsumerObjectAndWaitForTrack(ee(H({},h),{producerId:u}))});const c=a;r&&(m.info("Session description found, sending negotiation request"),yield n(r));const d=[];return yield Promise.all(Object.entries(i).map(([h,u])=>u.then(g=>d.push(g)).catch(()=>{m.error(`Failed to create consumer object, producer: ${h}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseCodecAndFmtpMappings(t,e){const n=Na(t.sdp),i={};return n.media.forEach(s=>{e.includes(s.mid.toString())&&(i[s.mid.toString()]={rtp:s.rtp,fmtp:s.fmtp,payloads:s.payloads,rtcpFb:s.rtcpFb})}),i}static setCodecAndFmtpMappings(t,e,n){const i=Na(t.sdp);return i.media=i.media.map(s=>{if(e.includes(s.mid.toString())){const r=H({},s);return r.rtp=n[s.mid.toString()].rtp,r.fmtp=n[s.mid.toString()].fmtp,r.payloads=n[s.mid.toString()].payloads,r.rtcpFb=n[s.mid.toString()].rtcpFb,r}return s}),ee(H({},t),{sdp:pu(i)})}closeConsumers(t,e){return p(this,null,function*(){try{const n=t.map(a=>a.transceiver.mid),i=bp.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,n);m.info("Stopping transceivers",{consumerIds:t.map(({id:a})=>a)}),t.forEach(a=>a.close(void 0,!0));let s=yield this.handler.pc.createOffer();m.info("Created offer for closing consumers",{sdp:s.sdp}),s=bp.setCodecAndFmtpMappings(s,n,i),m.info("Updated codec and fmtp mappings in close consumer offer",{sdp:s.sdp}),yield this.setLocalDescription(s),m.info("Successfully set local description in close consumers");const r=yield e(t,s);m.info("Received answer in close consumers",{sdp:r.sdp}),yield this.setRemoteDescription(r),m.info("Remote description was set successfully in close consumers",{sdp:r.sdp})}catch(n){m.error("Failed to close consumers",{error:n})}})}setRemoteOffer(t){return p(this,null,function*(){try{m.info("Received offer from SFU",{sdp:t.sdp}),yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer();m.info("Created answer corresponding to received offer",{sdp:e.sdp});const n=Na(e.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=H({},i),r=s.fmtp.find(a=>a.payload===111);return r&&(r.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}),e.sdp=pu(n),m.info("Setting munged SDP",{sdp:e.sdp}),yield this.setLocalDescription(e),m.info("Successfully set local description",{sdp:e.sdp}),e}catch(e){throw m.error("Set remote offer failed",{error:e}),e}})}_ontrack(t){const{track:e,transceiver:n,streams:i}=t;m.info(`track event received [trackId: ${e.id}]`);let s;o(this,Xo)===St.HIVE?s=`${i[0].id}:${e.kind}`:s=`${n.mid}:${e.kind}`,e.addEventListener("ended",()=>{m.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(s)});const r=this.consumerTrackEvents.get(s);r?(r(e,n),this.consumerTrackEvents.delete(s)):(m.warn(`track event handler not found ${s}`),this.unknownTracksMap.set(s,t))}sendErrorOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n,!0)}sendResponseOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n)}createConsumerObjectAndWaitForTrack(t){return p(this,null,function*(){const{consumerId:e,producerId:n,producingPeerId:i,producingTransportId:s,streamId:r,paused:a,screenShare:c,appData:d,kind:h,mimeType:u}=t,g=`${r}:${h}`,E=ee(H({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((b,w)=>p(this,null,function*(){const M=setTimeout(()=>{this.consumerTrackEvents.delete(g),E.isTimedout=!0,w(E)},5e3),D=(Y,X)=>{try{if(Y.readyState==="ended")clearTimeout(M),w(E);else{const A=Y;A.enabled=!0,this.handler.midTransceiverMap.set(X.mid,X);const J=new w2({id:e,localId:X.mid,transceiver:X,track:A,paused:a,producerId:n,producingPeerId:i,producingTransportId:s,handler:this.handler,appData:ee(H({},d),{screenShare:c,peerId:i}),rtpReceiver:X.receiver,mimeType:u});this.consumers.set(e,J),J.once("close",()=>{this.consumers.delete(J.id),this.handler.midTransceiverMap.delete(X.mid)}),m.info("consumer created for ",{consumer:{id:e,kind:h,appData:{screenShare:c},peerId:i,producerId:n}}),this.observer.emit("newconsumer",J),clearTimeout(M),b(J)}}catch(A){m.warn("error while creating consumer:",A),clearTimeout(M),w(E)}},F=this.unknownTracksMap.get(g);F?(this.unknownTracksMap.delete(g),D(F.track,F.transceiver)):this.consumerTrackEvents.set(g,D)}))})}setRemoteDescription(t){return p(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return p(this,null,function*(){m.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return p(this,null,function*(){return C2(t.map(e=>p(this,null,function*(){return mp(n=>p(this,null,function*(){return n>0&&m.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(H({},e))}))})))})}sendDataChannelMessage(t,e){return p(this,null,function*(){const n=this.getDatachannel(t);if(!n)throw y2("DC_NOT_READY",`${t} datachannel not ready`);const i=(yield n.request(e)).payload;return m.info(`sendDataChannelMessage::response ${JSON.stringify(i)}`),i})}};let R2=bp;Xo=new WeakMap;function P2(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){m.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return m.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Tm.getParser(t),n=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;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"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(n.name&&n.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(n.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;m.warn("Device::this._detectDevice() | browser not supported");return}m.warn("Device::this._detectDevice() | unknown device")}var vl;class A2{constructor(e,{handlerName:n,handlerFactory:i}={}){if(y(this,"handlerFactory"),S(this,vl,void 0),m.debug("constructor()"),T(this,vl,e),n&&i)throw new TypeError("just one of handlerName or handlerInterface can be given");if(i)this.handlerFactory=i;else{if(n)m.debug(`Device::constructor() | handler given: ${n}`);else if(n=P2(),n)m.debug(`Device::constructor() | detected handler: ${n}`);else throw new Error("device not supported");switch(n){case"Chrome74":this.handlerFactory=gp.createFactory();break;case"Safari12":this.handlerFactory=vp.createFactory();break;case"Firefox60":this.handlerFactory=hl.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=hl.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${n}"`)}}}createTransport(e){const n=Ar();return new R2(o(this,vl),ee(H({id:n},e),{handlerFactory:this.handlerFactory}))}}vl=new WeakMap;const M2=2e3;var rs,Zo,Kt,zt,va,ec,tc,nc,ya,lr,ic,sc,yl,El,kp,wp,w0,_p,_0,Ip,I0,Cp,C0,Rp,R0,Sl,Pp,Tl,Ap;class O2 extends Mt.EventEmitter{constructor(e,n,i){switch(super(),S(this,sc),S(this,El),S(this,wp),S(this,_p),S(this,Ip),S(this,Cp),S(this,Rp),S(this,Sl),S(this,Tl),S(this,rs,void 0),S(this,Zo,void 0),S(this,Kt,void 0),S(this,zt,void 0),S(this,va,void 0),S(this,ec,void 0),S(this,tc,void 0),S(this,nc,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),S(this,ya,void 0),S(this,lr,"all"),S(this,ic,void 0),T(this,rs,e),T(this,va,n),T(this,ic,i),T(this,Zo,new A2(i)),T(this,ec,new b2(n,i)),i){case St.CF:{T(this,tc,Nn);break}case St.HIVE:default:{T(this,tc,Tn);break}}o(this,sc,yl).mediaState={send:{state:ts.NEW,reconnected:!1},recv:{state:ts.NEW,reconnected:!1}},re.hasFeature(ue.FORCE_RELAY)&&T(this,lr,"relay"),Q(this,El,kp).call(this)}get socket(){return o(this,va)}get socketHandler(){return o(this,ec)}get sendTransport(){return o(this,Kt)}get recvTransport(){return o(this,zt)}get events(){return o(this,tc)}get nodeType(){return o(this,ic)}createTransports(e){return p(this,null,function*(){var n,i,s,r,a,c,d,h;re.hasFeature(ue.FORCE_RELAY)&&(m.info("ICE Transport Policy set to relay"),T(this,lr,"relay"));const u=yield It().getICEServers().catch(E=>(m.warn(`failed to get iceservers from server: ${E.message}`),[])),g=[];if(e.send){const E=re.hasFeature(ue.DISABLE_OPUS_DTX_CF),b=Q(this,_p,_0).call(this,{iceServers:u,additionalSettings:{encodedInsertableStreams:(n=o(this,rs).getValue("modules").e2ee)==null?void 0:n.enabled},config:{enableHighBitrate:(r=(s=(i=o(this,rs).getValue("defaults").mediaConfiguration)==null?void 0:i.audio)==null?void 0:s.enableHighBitrate)!=null?r:!1,enableStereo:(d=(c=(a=o(this,rs).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:o(this,ic)===St.HIVE?!0:!!E},iceTransportPolicy:o(this,lr)});g.push(b)}if(e.recv){const E=Q(this,Ip,I0).call(this,{iceServers:u,additionalSettings:{encodedInsertableStreams:(h=o(this,rs).getValue("modules").e2ee)==null?void 0:h.enabled},iceTransportPolicy:o(this,lr)});g.push(E)}yield Promise.all(g)})}stopTransports(e){var n,i;if(e.send&&this.sendTransport!==void 0){const{id:s,serverId:r,direction:a}=o(this,Kt);m.info("Closing send transport",{transport:{id:s,serverId:r,type:a}}),o(this,Kt).close(),o(this,Kt).removeAllListeners(),T(this,Kt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:s,serverId:r,direction:a}=o(this,zt);m.info("Closing recv transport",{transport:{id:s,serverId:r,type:a}}),(n=o(this,zt))==null||n.close(),(i=o(this,zt))==null||i.removeAllListeners(),T(this,zt,void 0)}Q(this,El,kp).call(this)}stopAllTransports(){m.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return p(this,null,function*(){const{id:n,serverId:i,direction:s}=e;Q(this,Cp,C0).call(this,e);try{const r=re.hasFeature(ue.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield mp((a,c)=>p(this,null,function*(){a>0&&m.debug(`Retrying transport connect, count: ${a}`,{transport:{id:n,serverId:i,type:s}});try{if(e.closed)throw new or("Cannot reconnect closed transport");yield Q(this,wp,w0).call(this,e)}catch(d){if(d instanceof or){c(d);return}throw m.error("Failed to connect transport, retrying",{transport:e,error:d}),d}}),{delayTime:100,strategy:"exponential",maxRetryCount:r}),e}catch(r){throw m.error(`Failed to connect send transport after retry: ${e.id}`,{error:r,transport:{id:n,serverId:i,type:s}}),e.close(),e.removeAllListeners(),r}})}handleErrors(e){throw new Error("Method not implemented.")}}rs=new WeakMap,Zo=new WeakMap,Kt=new WeakMap,zt=new WeakMap,va=new WeakMap,ec=new WeakMap,tc=new WeakMap,nc=new WeakMap,ya=new WeakMap,lr=new WeakMap,ic=new WeakMap,sc=new WeakSet,yl=function(){return o(this,rs).getValue("connectionHandler")},El=new WeakSet,kp=function(){T(this,ya,{send:void 0,recv:void 0})},wp=new WeakSet,w0=function(t){return p(this,null,function*(){const{id:e,direction:n}=t;if(m.info(`Connecting ${n} transport`,{transport:{id:e,type:n}}),!o(this,va).isConnected)throw new or("Socket is not connected");if(t.connectionState==="closed")throw new or("Transport is closed");try{yield t.connect(i=>Q(this,Rp,R0).call(this,n,i)),m.info(`Connected ${n} transport`,{transport:{id:e,serverId:t.serverId,type:n}})}catch(i){throw o(this,nc).transportFailureCount[n]+=1,i.message==="ice connection failed"?new or(i.message):i}})},_p=new WeakSet,_0=function(t){return p(this,null,function*(){var e,n;if(o(this,Kt)&&o(this,Kt).connected){m.info("Transport send is already connected",{transport:{id:(e=o(this,Kt))==null?void 0:e.id,serverId:(n=o(this,Kt))==null?void 0:n.serverId,type:"send"}});return}T(this,Kt,o(this,Zo).createTransport(ee(H({},t),{direction:"send"}))),te.configureSendTransport(o(this,Kt))})},Ip=new WeakSet,I0=function(t){return p(this,null,function*(){var e,n;if(o(this,zt)&&o(this,zt).connected){m.info("Transport recv is already connected",{transport:{id:(e=o(this,zt))==null?void 0:e.id,serverId:(n=o(this,zt))==null?void 0:n.serverId,type:"recv"}});return}T(this,zt,o(this,Zo).createTransport(ee(H({},t),{direction:"recv"}))),te.configureRecvTransport(o(this,zt))})},Cp=new WeakSet,C0=function(t){const{direction:e,id:n}=t;t.on("connectionstatechange",i=>p(this,null,function*(){Q(this,Tl,Ap).call(this,{state:i,direction:e}),m.info(`Transport connection state changed for ${e} transport`,{transport:{id:n,serverId:t.serverId,type:e,status:i}});const s=()=>{const r=o(this,ya)[e];r!==void 0&&(clearTimeout(r),o(this,ya)[e]=void 0)};switch(i){case"connected":s(),o(this,nc).lastConnectionTime=performance.now();break;case"disconnected":o(this,ya)[e]=setTimeout(()=>p(this,null,function*(){yield Q(this,Sl,Pp).call(this,t)}),M2);break;case"failed":if(t.closed)return;s(),yield Q(this,Sl,Pp).call(this,t);break}})),t.on("icecandidate",i=>p(this,null,function*(){m.debug("Sending iceCandidate:",{iceCandidate:i})})),t.on("datachannel:events",(i,s)=>p(this,null,function*(){var r,a;m.debug("Got data channel message on event:",{rtcChannel:{label:i,message:s}});try{switch(s.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(i,k0(s),c);break}case"hub-disconnect":{m.debug(`media hub disconnected, full_reconnect: ${(r=s.payload)==null?void 0:r.full_reconnect}`),((a=s.payload)==null?void 0:a.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(c){m.error(`Unable to handle the incoming datachannel message on channel ${i}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(m.warn("Events datachannel did not open in 5s",{country:k.location.country}),this.handleErrors("reconnectRecvTransport"))})},Rp=new WeakSet,R0=function(t,e){return p(this,null,function*(){const n=t==="recv";try{const{sdp:i,type:s}=e,r={consuming:n,description:{sdp:i,type:s,target:n?yi.SUBSCRIBER:yi.PUBLISHER},producers:[]};return o(this,ec).connectTransport(r)}catch(i){throw m.error(`Error in ${t} transport connection:`,{error:i,country:k.location.country}),i}})},Sl=new WeakSet,Pp=function(t){return p(this,null,function*(){m.info("Called reconnect transport",{transport:t}),t.close(),t.removeAllListeners();const{direction:e}=t;switch(re.hasFeature(ue.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&o(this,va).isConnected&&o(this,nc).transportFailureCount[e]>2&&(m.warn(`Multiple disconnections in ${e} transport, forcing relay`),T(this,lr,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(o(this,Kt)),m.info("Transport reconnected",{transport:o(this,Kt)}),L.emit(x.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(o(this,zt)),m.info("Transport reconnected",{transport:o(this,zt)}),L.emit(x.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:m.warn("Unknown transport direction",{transport:t})}Q(this,Tl,Ap).call(this,{state:ts.CONNECTED,direction:e})})},Tl=new WeakSet,Ap=function(t){const{state:e,direction:n}=t;o(this,sc,yl).mediaState[n]={state:e,reconnected:!0},L.emit(x.TRANSPORT_STATE_UPDATE,H({transport:n},o(this,sc,yl).mediaState[n]))};var Mp,P0;class D2{constructor(e){S(this,Mp),this.recvTransport=e,Q(this,Mp,P0).call(this)}create(e){return p(this,null,function*(){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:c,kind:d,mimeType:h})=>({producerId:a,producingTransportId:c,preferredCodec:H(H({},d==="video"&&h?{video:h}:{}),d==="audio"&&h?{audio:h}:{})}))}},i=yield this.recvTransport.sendDataChannelMessage("events",n),s=new Map;e.forEach(a=>s.set(a.producerId,a));const r=new Map;return Object.entries(i).forEach(([a,c])=>{const d=s.get(c.producerId);d&&r.set(c.producerId,{consumerId:a,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:r}})}negotiate(e,n,i){return p(this,null,function*(){try{m.debug(`Received offer over dc: ${e.sdp} for transport`);const s=yield this.recvTransport.setRemoteOffer(e),r={type:"answer",payload:{type:s.type,sdp:s.sdp}};return m.debug(`datachannel answer: ${JSON.stringify(r)}`),this.recvTransport.sendResponseOverDC(i,n,r),s}catch(s){throw m.error("datachannel:events::Error:",s),s.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(i,n,s),s}})}close(e){return p(this,null,function*(){if(!e.length)return{};const n=e.map(a=>a.id);m.info(`Closing consumers: ${JSON.stringify(n)}`);const i={type:"close_consumers",payload:{consumers:n}},s=yield this.recvTransport.sendDataChannelMessage("events",i),{failedConsumers:r}=s;return{failedConsumers:r}})}}Mp=new WeakSet,P0=function(){this.recvTransport.on("datachannel:events",(t,e)=>p(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:n}=e.payload,i={sdp:n,type:"offer"};this.negotiate(i,k0(e),t);break}default:break}}catch(n){m.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class N2{constructor(e,n,i,s){this.events=e,this.recvTransport=n,this.socket=i,this.socketHandler=s}create(e){return p(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n=new Map,i=[];e.forEach(d=>{const{producingPeerId:h,producerId:u,producingTransportId:g}=d;n.set(u,h),i.push({producingPeerId:h,producerId:u,producingTransportId:g})});const s=yield this.socketHandler.consume({requests:i,consumingTransportId:this.recvTransport.serverId}),r=new Map;e.forEach(d=>r.set(d.producerId,d));const a=new Map,c=[];return Object.entries(s.consumerStateMap).forEach(([d,h])=>{const u=r.get(d);if(!u)return;if(h.errorCode){if(m.warn(`Consumer request failed for producer ${d}`,{error:{message:h.errorCode}}),h.errorCode==="not_found_track_error"){m.error(`Track not found for producer: ${u.producerId}. This will not be retried.`);return}c.push(u);return}let g={};try{g=JSON.parse(h.producerState.appData)}catch(E){}a.set(d,{consumerId:h.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:h.producerTrack.streamId,trackId:h.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:g})}),{consumerStates:a,sessionDescription:s.sessionDescription,failedProducers:c}})}negotiate(e){return p(this,null,function*(){try{m.info("Negotiating socket consumer",{transport:this.recvTransport}),m.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const n=yield this.recvTransport.setRemoteOffer(e),i={transportId:this.recvTransport.serverId,description:{sdp:n.sdp,type:n.type,target:yi.SUBSCRIBER}};return m.debug(`sending renegotiate request: ${JSON.stringify(i)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,uP.toBinary(i)),m.info("Renegotiation done",{transport:this.recvTransport}),n}catch(n){m.error("Failed to renegotiate",{error:n});return}})}close(e){return p(this,null,function*(){if(!e.length)return{};const n=(i,s)=>p(this,null,function*(){const r=i.map(h=>h.localId);m.info(`Closing consumers: ${JSON.stringify(r)}`);const a={description:{sdp:s.sdp,type:s.type,target:yi.SUBSCRIBER},consumerIds:r,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(a),d=D1.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,n),"close_consumer"),{}})}}class Op{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,n){return Na(e).media.filter(i=>n==="video"?i.type==="video":i.type==="audio").at(-1).msid}create(e){return p(this,arguments,function*({offer:n,kind:i,paused:s,appData:r,codecOptions:a,producingTransportId:c}){var d,h;const u=Op.getMSIDFromSDP(n.sdp,i),g={description:{sdp:n.sdp,type:n.type,target:yi.PUBLISHER},paused:s,kind:i,msid:u,appData:JSON.stringify(r),screenShare:(d=r.screenShare)!=null?d:!1,mimeType:`${i}/${(h=a[0])==null?void 0:h.name}`,producingTransportId:c},{answer:E,producerId:b}=yield this.socketHandler.produce(g);return{answer:E,producerId:b}})}}var rc,Ea,ur,ac,bl,Ai,Dp,as,oc,Np,A0,kl,Lp,xp,M0,Vp,O0,Up,D0,Bp,N0,Fp,L0,jp,x0;class L2 extends O2{constructor(e,n,i){super(e,n,i),S(this,Np),S(this,kl),S(this,xp),S(this,Vp),S(this,Up),S(this,Bp),S(this,Fp),S(this,jp),S(this,rc,void 0),S(this,Ea,void 0),S(this,ur,void 0),S(this,ac,void 0),S(this,bl,void 0),S(this,Ai,void 0),S(this,Dp,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),S(this,as,[]),S(this,oc,void 0),T(this,rc,e),o(this,Np,A0).mediaState={send:{state:ts.NEW,reconnected:!1},recv:{state:ts.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return o(this,Ea)}get consumers(){return o(this,ur)}get producerIdToConsumerIdMap(){return o(this,ac)}reset(){T(this,Ea,new Map),T(this,ur,new Map),T(this,ac,new Map)}setupTransports(e){return p(this,null,function*(){yield this.createTransports(e);let n,i;e.send&&(n=Q(this,xp,M0).call(this)),e.recv&&(i=Q(this,Vp,O0).call(this)),yield Promise.all([n,i])})}createProducer(e,n){return p(this,null,function*(){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const s=yield this.sendTransport.produce(e,Q(this,Up,D0).bind(this));return(i=e.appData)!=null&&i.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,s),Q(this,Bp,N0).call(this,s,n),s}catch(s){throw m.error("Failed to create producer",{error:s}),o(this,Dp).producerCreationFailureCount+=1,s}})}closeProducer(e,n){return p(this,null,function*(){var i;const s=this.producers.get(e);if(!s){m.warn(`Producer with ID ${e} was not found`);return}n!=null&&n.stopTrack&&s.track.stop();try{yield this.sendTransport.closeProducer(s),(i=o(this,rc).getValue("modules").e2ee)!=null&&i.enabled&&L.emit(x.E2EE_INACTIVE_PRODUCER,s)}catch(r){m.error("Failed to close producer on server",{error:r,producer:s})}})}closeAllProducers(){return Promise.all(Array.from(o(this,Ea).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return p(this,null,function*(){o(this,oc)||clearTimeout(o(this,oc)),T(this,as,o(this,as).concat(e)),yield Q(this,kl,Lp).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return p(this,null,function*(){if(!o(this,Ai))return;const n=e.map(s=>this.consumers.get(s)).filter(s=>s!==void 0);if(n.length===0)return;const{failedConsumers:i}=yield o(this,Ai).close(n);i!=null&&i.length&&m.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(o(this,ur).keys()))}switchConsumersToLayer(e,n){return p(this,null,function*(){const i=this.recvTransport.getDatachannel("events");if(!i){m.warn("events datachannel not found");return}const s={type:"switch_consumer_layer",payload:{consumerIds:e,layer:n}};yield i.request(s),m.info(`Consumers switched layers to ${n}`,{consumerIds:e})})}}rc=new WeakMap,Ea=new WeakMap,ur=new WeakMap,ac=new WeakMap,bl=new WeakMap,Ai=new WeakMap,Dp=new WeakMap,as=new WeakMap,oc=new WeakMap,Np=new WeakSet,A0=function(){return o(this,rc).getValue("connectionHandler")},kl=new WeakSet,Lp=function(){return p(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=o(this,as).splice(0,o(this,as).length);try{const n=e.filter(({producerId:r})=>!this.producers.get(r));if(n.length===0)return;const{consumers:i,failedProducers:s}=yield this.recvTransport.consume(n,Q(this,Fp,L0).bind(this),o(this,Ai).negotiate.bind(o(this,Ai)));i.forEach(Q(this,jp,x0).bind(this)),s!=null&&s.length&&(m.error("Failed to create consumers for producers",{producers:s}),T(this,as,o(this,as).concat(s)),T(this,oc,setTimeout(Q(this,kl,Lp).bind(this),t)))}catch(n){m.error("failed to consume on transport",{error:n})}})},xp=new WeakSet,M0=function(){return p(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),T(this,bl,new Op(this.socketHandler))})},Vp=new WeakSet,O0=function(){return p(this,null,function*(){switch(this.recvTransport.on("connect",()=>{o(this,ac).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case St.CF:{T(this,Ai,new N2(this.events,this.recvTransport,this.socket,this.socketHandler));break}case St.HIVE:default:T(this,Ai,new D2(this.recvTransport))}})},Up=new WeakSet,D0=function(t){return o(this,bl).create(t)},Bp=new WeakSet,N0=function(t,e){t.on("close",(n,i)=>p(this,null,function*(){const{offer:s,reason:r}=n;if(m.info("producer::closing",{debuggingHint:r,producer:ee(H({},t),{status:"closing"})}),r!==gl){const a={producerId:t.id,description:{sdp:s.sdp,type:s.type,target:yi.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(a),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};m.info("producer::closed",{producer:ee(H({},t),{status:"closed"})}),i({answer:d})}catch(c){m.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{m.info("producer::trackended",{producer:ee(H({},t),{status:"UNKNOWN"})})}),o(this,Ea).set(t.id,t)},Fp=new WeakSet,L0=function(t){return p(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield o(this,Ai).create(t)}catch(e){throw m.error("Error in consume request",{error:e}),e}})},jp=new WeakSet,x0=function(t){t.on("close",e=>p(this,null,function*(){m.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),o(this,ur).delete(t.id),L.emit(x.CONSUMER_CLOSED,{id:t.id})})),o(this,ur).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),L.emit(x.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var wl,_l,Il,cc,dc,lc,Cl,Rl,uc,gn,ai,oi,hr,pr,os,Pl,Wp,V0,Hp,U0,qp,B0,Gp,F0;const Jp=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:n=3,hangoverFrames:i=5,noiseAdaptationRate:s=.95,voiceAdaptationRate:r=.99,minEnergyThreshold:a=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:h=50}={}){S(this,Wp),S(this,Hp),S(this,wl,void 0),S(this,_l,void 0),S(this,Il,void 0),S(this,cc,void 0),S(this,dc,void 0),S(this,lc,void 0),S(this,Cl,void 0),S(this,Rl,void 0),S(this,uc,void 0),S(this,gn,void 0),S(this,ai,void 0),S(this,oi,!1),S(this,hr,0),S(this,pr,0),S(this,os,[]),S(this,Pl,void 0),T(this,cc,t),T(this,gn,t),T(this,wl,e),T(this,_l,n),T(this,Il,i),T(this,dc,s),T(this,lc,r),T(this,Cl,a),T(this,Rl,c),T(this,uc,d),T(this,Pl,h),T(this,ai,t/2)}get voiceDetected(){return o(this,oi)}processAudioChunk(t){var e,n;const i=Q(e=Jp,qp,B0).call(e,t),s=Q(n=Jp,Gp,F0).call(n,t);return Q(this,Wp,V0).call(this,i),i/o(this,ai)>o(this,uc)&&i>o(this,gn)&&s>o(this,wl)?(T(this,hr,o(this,hr)+1),T(this,pr,o(this,Il)),o(this,hr)>=o(this,_l)&&T(this,oi,!0)):(T(this,hr,0),o(this,pr)>0?T(this,pr,o(this,pr)-1):o(this,oi)&&T(this,oi,!1),o(this,oi)||Q(this,Hp,U0).call(this,i)),{energy:i,isVoice:o(this,oi)}}reset(){T(this,oi,!1),T(this,hr,0),T(this,pr,0),T(this,gn,o(this,cc)),T(this,ai,o(this,cc)/2),T(this,os,[])}getThresholdInfo(){return{currentEnergyThreshold:o(this,gn),backgroundNoiseEnergy:o(this,ai),energyRatioThreshold:o(this,uc)}}};let $p=Jp;wl=new WeakMap,_l=new WeakMap,Il=new WeakMap,cc=new WeakMap,dc=new WeakMap,lc=new WeakMap,Cl=new WeakMap,Rl=new WeakMap,uc=new WeakMap,gn=new WeakMap,ai=new WeakMap,oi=new WeakMap,hr=new WeakMap,pr=new WeakMap,os=new WeakMap,Pl=new WeakMap,Wp=new WeakSet,V0=function(t){o(this,oi)?T(this,gn,o(this,lc)*o(this,gn)+(1-o(this,lc))*t):T(this,gn,o(this,dc)*o(this,gn)+(1-o(this,dc))*o(this,ai)),T(this,gn,Math.max(o(this,Cl),Math.min(o(this,Rl),o(this,gn))))},Hp=new WeakSet,U0=function(t){if(t<o(this,gn)*1.2)if(o(this,os).push(t),o(this,os).length>o(this,Pl)&&o(this,os).shift(),o(this,os).length>=10){const e=[...o(this,os)].sort((i,s)=>i-s),n=Math.floor(e.length/2);T(this,ai,e[n])}else T(this,ai,.95*o(this,ai)+.05*t)},qp=new WeakSet,B0=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,n)=>e+n)/t.length)},Gp=new WeakSet,F0=function(t){let e=0;for(let n=1;n<t.length;n+=1)(t[n]>=0&&t[n-1]<0||t[n]<0&&t[n-1]>=0)&&(e+=1);return e},S($p,qp),S($p,Gp);const x2=60,V2=400;var cs,ds,ci,mr,fr,hc,Sa,pc,ls,gr,mc,Kp,j0,Al,zp,Yp,W0,Qp,H0;const Ml=class{constructor(t){S(this,Kp),S(this,Yp),S(this,cs,void 0),S(this,ds,void 0),S(this,ci,void 0),S(this,mr,void 0),S(this,fr,void 0),S(this,hc,void 0),S(this,Sa,void 0),S(this,pc,void 0),S(this,ls,void 0),S(this,gr,void 0),S(this,mc,void 0),this.reportRequest=t,T(this,mr,new AudioContext),T(this,fr,o(this,mr).createAnalyser()),o(this,fr).fftSize=2048,T(this,pc,new $p)}set producerId(t){T(this,ci,t)}set audioTrack(t){T(this,hc,t);const e=new MediaStream;e.addTrack(o(this,hc)),o(this,mr).createMediaStreamSource(e).connect(o(this,fr))}start(){m.debug(`AudioActivityReporter: Starting audio activity reporter: ${o(this,ci)}`),o(this,cs)&&Mr(o(this,cs)),T(this,cs,Uc(()=>p(this,null,function*(){var t;if(!o(this,hc)||!o(this,ci))return;const{energy:e}=Q(this,Kp,j0).call(this),n=Q(t=Ml,Al,zp).call(t,e);let i=.9;o(this,mc)!==n&&o(this,mc)?i=.9:n?i=.3:i=.5,T(this,Sa,(o(this,Sa)||0)*(1-i)+e*i)}),x2)),o(this,ds)&&Mr(o(this,ds)),T(this,ds,Uc(Q(this,Yp,W0).bind(this),V2))}stop(){try{m.debug(`AudioActivityReporter: Stopping audio activity reporter: ${o(this,ci)}`),o(this,cs)&&(Mr(o(this,cs)),T(this,cs,void 0)),o(this,ds)&&(Mr(o(this,ds)),T(this,ds,void 0))}catch(t){}o(this,pc).reset()}};let Xp=Ml;cs=new WeakMap,ds=new WeakMap,ci=new WeakMap,mr=new WeakMap,fr=new WeakMap,hc=new WeakMap,Sa=new WeakMap,pc=new WeakMap,ls=new WeakMap,gr=new WeakMap,mc=new WeakMap,Kp=new WeakSet,j0=function(){var t;o(this,mr).state==="suspended"&&o(this,mr).resume().then(()=>{m.debug("AudioActivityReporter: AudioContext forced resumed")}).catch(r=>{m.error("AudioActivityReporter: Error resuming AudioContext",r)});const e=new Float32Array(o(this,fr).frequencyBinCount);o(this,fr).getFloatTimeDomainData(e);const{energy:n,isVoice:i}=o(this,pc).processAudioChunk(e),s=Q(t=Ml,Qp,H0).call(t,n);return re.hasFeature(ue.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&m.debug(`AudioActivityReporter: producer: ${o(this,ci)}, energy: ${o(this,Sa)},
24
- slogScale: ${s}, isVoice: ${i}, minEnergy: ${o(this,ls)},
25
- maxEnergy: ${o(this,gr)}`),s===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,ls)||s<o(this,ls))&&T(this,ls,s),(!o(this,gr)||s>o(this,gr))&&T(this,gr,s),{energy:(s-o(this,ls))/(o(this,gr)-o(this,ls))*10||0,isVoice:i})},Al=new WeakSet,zp=function(t){return t<5},Yp=new WeakSet,W0=function(t=o(this,Sa)){var e;if(!o(this,ci)||!t){re.hasFeature(ue.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&m.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,ci)}`);return}const n={producerId:o(this,ci),energy:Math.round(t),silent:Q(e=Ml,Al,zp).call(e,t)};T(this,mc,n.silent),this.reportRequest(n)},Qp=new WeakSet,H0=function(t){const e=Math.log10(t);return Math.round(e)},S(Xp,Al),S(Xp,Qp);const U2=(t=!1)=>{const e=new window.AudioContext,n=e.createOscillator();n.type="triangle",n.frequency.setValueAtTime(20,e.currentTime);const i=e.createGain();i.gain.setValueAtTime(0,e.currentTime),n.connect(i);const s=e.createMediaStreamDestination();i.connect(s),n.start();const r=s.stream.getAudioTracks()[0];return r.enabled=t,r},B2=(t=!1)=>{var e,n;const i=new MediaStream().getVideoTracks()[0],s=document.createElement("canvas");s.height=(e=i==null?void 0:i.getSettings().height)!=null?e:720,s.width=(n=i==null?void 0:i.getSettings().width)!=null?n:1280;const r=s.getContext("2d");r.fillStyle="black",r.fillRect(0,0,s.width,s.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,s.width,s.height)},1e3);const a=s.captureStream().getVideoTracks()[0];return a.enabled=t,a};var F2=Object.defineProperty,j2=Object.getOwnPropertyDescriptor,Te=(t,e,n,i)=>{for(var s=i>1?void 0:i?j2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&F2(e,n,s),s};const di=["video/VP9","video/VP8"];var Ol,Dl,Yt,ne,fc,vr,an,Ta,ba,yr,Nl,us,gc,ka,wa,on,vn,Er,_a,xt,Qt,Ia,vc,Zp,q0,em,G0,tm,J0;class Ee{constructor(e,n,i){S(this,Er),S(this,xt),S(this,Ia),S(this,Zp),S(this,em),S(this,tm),y(this,"context"),y(this,"authToken"),y(this,"e2ee"),S(this,Ol,void 0),S(this,Dl,void 0),S(this,Yt,void 0),S(this,ne,void 0),S(this,fc,void 0),S(this,vr,void 0),S(this,an,void 0),S(this,Ta,void 0),S(this,ba,void 0),S(this,yr,void 0),S(this,Nl,void 0),S(this,us,void 0),S(this,gc,void 0),S(this,ka,void 0),S(this,wa,void 0),S(this,on,void 0),S(this,vn,void 0),y(this,"partialJoinRoomPromise");var s,r;this.context=e;const{socket:a}=i;this.mediaJoined=!1,T(this,ka,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,wa,new Map([["video/VP9",new Set],["video/VP8",new Set]])),T(this,vr,n),T(this,Yt,a),T(this,Ta,!1),T(this,ne,new L2(e,a,n)),T(this,an,o(this,ne).events),T(this,us,new Set),T(this,on,new Map),T(this,ba,!1),T(this,yr,new dl),n===St.CF&&!navigator.isReactNative&&T(this,vn,new Xp(o(this,ne).socketHandler.audioActivity.bind(o(this,ne).socketHandler))),this.e2ee=(r=(s=e.getValue("modules").e2ee)==null?void 0:s.enabled)!=null?r:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),T(this,Nl,gd(()=>p(this,null,function*(){if(!o(this,Er,_a).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,Dl),o(this,Ol),{},!0,!0);c&&(L.emit(x.RESET_PRODUCER_STATE),L.emit(x.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,Er,_a).mediaJoined}set mediaJoined(e){o(this,Er,_a).mediaJoined=e}reset(e=!0){o(this,ne).closeAllProducers(),o(this,ne).closeAllConsumers(),o(this,on).clear(),o(this,us).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,yr).stop(),o(this,ne).stopAllTransports(),o(this,ne).reset(),T(this,yr,new dl))}joinRoom(e,n){return p(this,arguments,function*(i,s,r={},a=!1,c=!1){o(this,Er,_a).mediaJoinAttempted=!0,T(this,Ta,!0),this.reset(a);const d=It().ipInfo;if(d!=null&&d.loc&&!o(this,gc)){const u=d.loc.split(",");T(this,gc,{latitude:parseFloat(u[0]),longitude:parseFloat(u[1])})}let h;try{return h=yield o(this,yr).push(()=>this._joinRoom(i,s,r,c,o(this,gc)),"joinRoom"),h}catch(u){h={roomJoined:!1}}return h.roomJoined||L.emit(x.ROOM_NODE_FAILED),h})}_partialJoinRoom(e,n,i=!1,s=void 0){return p(this,null,function*(){var r;const{ipInfo:a}=It();let c=s;if(a!=null&&a.loc&&!s){const[u,g]=a.loc.split(",").map(parseFloat);c={latitude:u,longitude:g}}const d=(r=re.getValue(ue.FORCE_VIDEO_CODEC))==null?void 0:r.toString(),h=T2(d);T(this,fc,h),yield mp((u,g)=>p(this,null,function*(){if(!o(this,Yt).isConnected){g(new Error("socket is not connected"));return}u>0&&m.warn(`retrying sending join room request, count: ${u}`);try{yield o(this,ne).socketHandler.joinRoom(n,e,h,i,c)}catch(E){throw m.error("failed to send join room request, error:",{error:E}),E}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:re.hasFeature(ue.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,ne).setupTransports({send:!0,recv:!0}),o(this,vr)!==St.HIVE&&re.hasFeature(ue.PRECREATE_PRODUCERS)&&(this.shareWebcam(B2()),this.shareMic(U2()))})}partialJoinRoom(e,n,i=!1,s=void 0){return p(this,null,function*(){return this.partialJoinRoomPromise=o(this,yr).push(()=>this._partialJoinRoom(e,n,i,s)),this.partialJoinRoomPromise})}_joinRoom(e,n){return p(this,arguments,function*(i,s,r={},a=!1,c=null){T(this,Dl,i);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(i,s,a,c)}catch(d){m.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>p(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:ee(H({},Ue.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};te.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return m.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return p(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,ne).socketHandler.notifySelfJoinComplete();return T(this,Ol,e.roomUuid),T(this,ba,!0),T(this,Ta,!1),!0}catch(e){return m.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return p(this,null,function*(){o(this,ne).stopAllTransports(),T(this,ba,!1),o(this,Er,_a).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,Yt).sendMessagePromise(o(this,an).leaveRoom,LP.toBinary(e)).then(n=>{var i;(i=E1.fromBinary(n.payload))!=null&&i.closed||m.warn("weird state on peer closed and should not happen")}).catch(n=>{m.error("error on sending leave room request",{error:n})}),te.callEnded(),k.destruct()})}getConsumers(){return o(this,ne).consumers}activatePeers(e){return p(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return p(this,null,function*(){const i=new Set;e.forEach(r=>{r.screenShare&&r.kind==="video"&&i.add(r.producingPeerId)});const s=n==="default"?e.filter(r=>!i.has(r.producingPeerId)).filter(r=>r.kind!=="audio"):e;yield Promise.all(s.map(r=>{const a=o(this,ne).producerIdToConsumerIdMap.get(r.producerId);if(!a){m.warn(`consumer not found in deactivate producers: ${r.producerId}`);return}return o(this,ne).closeConsumer(a)}))})}createConsumers(e){return p(this,null,function*(){return e.length===0?Promise.resolve():o(this,ne).createConsumers(e)})}closeConsumers(e){return p(this,null,function*(){if(!e.length)return;const n=e.reduce((i,s)=>{const r=o(this,ne).producerIdToConsumerIdMap.get(s.producerId);return r?(i.push(r),i):(m.warn(`consumer not found in deactivate producers: ${s.producerId}`),i)},[]);yield o(this,ne).closeConsumers(n)})}_shareWebcam(e,n){return p(this,null,function*(){const i=n==="video/VP9"?De.WEBCAM:De.WEBCAM_BACKUP,s=Q(this,xt,Qt).call(this,i);if(s){const u=yield s;if(o(this,ne).producers.has(u)){const g=o(this,ne).producers.get(u);if(!g.closed&&!navigator.isReactNative)return yield g.replaceTrack({track:e}),yield this.resumeWebcam(i),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const r=Q(this,tm,J0).call(this,e,n),a=Ed(this.context,"disableSimulcast"),c=o(this,vr)===St.CF?ue.ENABLE_CF_SIMULCAST:ue.ENABLE_HIVE_SIMULCAST;!a&&re.hasFeature(c)?(m.info(`Simulcast enabled for SFU: ${o(this,vr)}`),r.encodings=gL(e)):m.info(`Simulcast disabled for webcam producer, SFU: ${o(this,vr)}`),re.hasFeature(ue.TRACK_HINT)&&(r.track.contentHint=re.getValue(ue.TRACK_HINT));const d=()=>{m.info("Disabling video due to the producer closure"),o(this,on).delete(i)},h=o(this,ne).createProducer(r,d);return Q(this,Ia,vc).call(this,i,h.then(u=>u.id)),h.then(u=>u.track)})}shareWebcam(e){return p(this,null,function*(){if(e===void 0)return null;if(re.hasFeature(ue.FORCE_VIDEO_CODEC)){const n=re.getValue(ue.FORCE_VIDEO_CODEC).toString();if(n)return m.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(di.map(n=>{var i,s;return((s=(i=o(this,fc).sender)==null?void 0:i.video)==null?void 0:s.codecs.findIndex(r=>r.mimeType===n))>=0&&o(this,wa).get(n).size>0?(m.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return p(this,null,function*(){const{video:n,audio:i}=e;if(n===void 0)return;const s={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ue.isElectron()},stopTracks:!1},r=()=>{m.info("Disabling screenShare due to the producer closure"),o(this,on).delete(De.SCREENSHARE_VIDEO),o(this,on).delete(De.SCREENSHARE_AUDIO)},a=o(this,ne).createProducer(s,r);Q(this,Ia,vc).call(this,De.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(i){const d={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ue.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},h=()=>{};c=o(this,ne).createProducer(d,h),Q(this,Ia,vc).call(this,De.SCREENSHARE_AUDIO,c.then(u=>u.id))}yield Promise.all([a,c||Promise.resolve()]),te.screenShareStart()})}shareMic(e){return p(this,null,function*(){try{if(e===void 0)throw new rn("track undefined");const n=Q(this,xt,Qt).call(this,De.MIC);if(n){const a=yield n;if(o(this,ne).producers.has(a)){const c=o(this,ne).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,vn)&&(o(this,vn).audioTrack=e,o(this,vn).producerId=a,o(this,vn).start());return}yield o(this,ne).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const i=Q(this,em,G0).call(this,e),s=()=>{o(this,on).delete(De.MIC)},r=o(this,ne).createProducer(i,s);Q(this,Ia,vc).call(this,De.MIC,r.then(a=>a.id)),yield r.then(a=>{o(this,vn)&&(o(this,vn).audioTrack=a.track,o(this,vn).producerId=a.id,o(this,vn).start())})}catch(n){throw new O(n)}})}pauseMic(){return p(this,null,function*(){var e;const n=yield Q(this,xt,Qt).call(this,De.MIC),i=o(this,ne).producers.get(n);if(!i){m.error("pauseMic::could_not_find_mic_producer");return}if(i.paused){m.info("pauseMic::mic_producer_already_paused");return}i.pause(),(e=o(this,vn))==null||e.stop();const s={producerId:i.id,pause:!0};o(this,Yt).sendMessage(o(this,an).toggleProducer,kd.toBinary(s))})}pauseWebcam(){return p(this,null,function*(){const e=yield Q(this,xt,Qt).call(this,De.WEBCAM),n=yield Q(this,xt,Qt).call(this,De.WEBCAM_BACKUP),i=o(this,ne).producers.get(e),s=o(this,ne).producers.get(n);if(!i&&!s){m.error("pauseWebcam::could_not_find_webcam_producer");return}const r=a=>{const c={producerId:a.id,pause:!0};o(this,Yt).sendMessage(o(this,an).toggleProducer,kd.toBinary(c))};i&&(i.pause(),r(i)),s&&(s.pause(),r(s))})}resumeMic(){return p(this,null,function*(){const e=yield Q(this,xt,Qt).call(this,De.MIC),n=o(this,ne).producers.get(e);if(!n){m.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){m.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,n);const i={producerId:n.id,pause:!1};o(this,Yt).sendMessage(o(this,an).toggleProducer,kd.toBinary(i))})}resumeWebcam(){return p(this,arguments,function*(e=De.WEBCAM){const n=yield Q(this,xt,Qt).call(this,e),i=o(this,ne).producers.get(n);if(!i){m.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){m.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&L.emit(x.E2EE_ACTIVE_PRODUCER,i);const s={producerId:i.id,pause:!1};o(this,Yt).sendMessage(o(this,an).toggleProducer,kd.toBinary(s))})}disableWebcam(e){return p(this,null,function*(){const n=e==="video/VP9"?De.WEBCAM:De.WEBCAM_BACKUP,i=yield Q(this,xt,Qt).call(this,n);Q(this,Zp,q0).call(this,n),i&&(yield o(this,ne).closeProducer(i))})}disableMic(){return p(this,null,function*(){var e;const n=yield Q(this,xt,Qt).call(this,De.MIC);n&&(yield o(this,ne).closeProducer(n)),(e=o(this,vn))==null||e.stop(),o(this,on).delete(De.MIC)})}disableScreenShare(){return p(this,null,function*(){m.info("screen_sharing_stopped"),te.screenShareStop();const e=yield Q(this,xt,Qt).call(this,De.SCREENSHARE_VIDEO),n=yield Q(this,xt,Qt).call(this,De.SCREENSHARE_AUDIO);e&&(yield o(this,ne).closeProducer(e)),n&&(yield o(this,ne).closeProducer(n)),o(this,us).clear(),o(this,on).delete(De.SCREENSHARE_VIDEO),o(this,on).delete(De.SCREENSHARE_AUDIO)})}muteSelf(){return p(this,null,function*(){this.pauseMic()})}unmuteSelf(){return p(this,null,function*(){})}resetVideoProducers(e,n){return p(this,null,function*(){if(e){const i=yield Q(this,xt,Qt).call(this,De.WEBCAM),s=yield Q(this,xt,Qt).call(this,De.WEBCAM_BACKUP);yield o(this,ne).closeProducer(i,{stopTrack:!1}),yield o(this,ne).closeProducer(s,{stopTrack:!1}),this.shareWebcam(e)}if(n){const i=yield Q(this,xt,Qt).call(this,De.SCREENSHARE_VIDEO);yield o(this,ne).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return p(this,null,function*(){const i={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,ne).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(e){const n={peerIds:[e]};o(this,ne).socketHandler.kickPeer(n)}kickAll(){o(this,ne).socketHandler.kickAll()}muteAll(e){return p(this,null,function*(){if(!(yield o(this,ne).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return p(this,null,function*(){if(!(yield o(this,ne).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return p(this,null,function*(){if(!(yield o(this,ne).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return p(this,null,function*(){if(!(yield o(this,ne).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return p(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,Yt).sendMessagePromise(o(this,an).globalPinPeer,GP.toBinary(n))}catch(i){m.error("Error in pinning peer:",{error:i})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,ne).producers.get(e.producerId)&&o(this,us).add(e.consumerPeerId),o(this,us).size}switchConsumersToLayer(e,n){return p(this,null,function*(){o(this,ne).switchConsumersToLayer(e,n)})}handleSocketEvents(){return p(this,null,function*(){o(this,Yt).on(o(this,an).peerProducerCreateBroadcast,({payload:e})=>{var n,i;if(this.mediaJoined)try{const{participantId:s,producerState:r}=z1.fromBinary(e);if(s===this.peerId)return;if(r!=null&&r.mimeType||(r.mimeType=r.kind===ii.AUDIO?"audio/opus":"video/VP8"),r.kind===ii.VIDEO&&!r.screenShare&&((i=(n=o(this,fc).receiver)==null?void 0:n.video)==null?void 0:i.codecs.findIndex(a=>a.mimeType===di[0]))>=0&&o(this,ka).get(di[0]).has(s)&&r.mimeType!==di[0]){m.warn(`Ignoring producer: ${r.producerId}`);return}m.info(`producer created broadcast: ${s}, producer state: ${r}`),L.emit(x.NEW_PRODUCER,{peerId:s,producer:ee(H({},r),{kind:r.kind===ii.AUDIO?"audio":"video",producingPeerId:s})})}catch(s){m.error("error in peer-producer-create-broadcast",{error:s})}}),o(this,Yt).on(o(this,an).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:i,producerState:{kind:s,pause:r,producerId:a}}=Zv.fromBinary(e),c=s===ii.AUDIO?"audio":"video";if(m.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${r} payload: ${JSON.stringify(Zv.fromBinary(e))}`),n===this.peerId&&i!==this.peerId&&r&&L.emit(c==="audio"?x.MUTE_SELF:x.MUTE_SELF_VIDEO),n===this.peerId)return;L.emit(x.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:r,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==r&&(m.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${r}`),r?(d.pause(),L.emit(x.CONSUMER_PAUSED,{id:d.id})):(d.resume(),L.emit(x.CONSUMER_RESUMED,{id:d.id})))})}catch(n){m.error("error in producer toggle broadcast handler",{error:n})}}),o(this,Yt).on(o(this,an).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=gh.fromBinary(e);if(n===this.peerId)return;m.info(`peer left broadcast:${n}`),o(this,us).delete(n),o(this,ne).consumers.forEach(i=>{i.peerId===n&&i.close()}),L.emit(x.PEER_CLOSED,{id:n})}catch(n){m.error("error in peer left broadcast",{error:n})}}),o(this,Yt).on(o(this,an).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:i}}=X1.fromBinary(e);if(n===this.peerId)return;m.info(`producer closed broadcast:${n}`),L.emit(x.PRODUCER_CLOSED,{peerId:n,producerId:i});const s=o(this,ne).producerIdToConsumerIdMap.get(i);if(!s){m.warn(`no consumer found for producer:${i}`);return}m.info(`closing consumer ${s}, producer id: ${i}`),o(this,ne).closeConsumer(s).then(()=>{m.info(`closed consumer: ${s}`),o(this,ne).producerIdToConsumerIdMap.delete(i),L.emit(x.CONSUMER_CLOSED,{id:s})}).catch(r=>{m.error("error closing consumer",{error:r})})}catch(n){m.error("error on producer close broadcast",{error:n})}}),o(this,Yt).on(o(this,an).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,Ta)&&!o(this,ba)||(m.warn("media hub termination broadcast received, rejoining room"),L.emit(x.ROOM_NODE_DISCONNECTED),o(this,Nl).call(this))})})}handleCallstatsEvents(){te.onConsumerScore(e=>{e.forEach((n,i)=>{const s=o(this,ne).consumers.get(i);s&&L.emit(x.CONSUMER_SCORE_UPDATE,{id:i,kind:s.kind,peerId:s.peerId,score:n.score,scoreStats:n})})}),te.onProducerScore(e=>{e.forEach((n,i)=>{const s=Array.from(o(this,ne).producers.values()).find(r=>r.id===i);s&&L.emit(x.PRODUCER_SCORE_UPDATE,{id:i,kind:s.kind,appData:s.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var i,s,r,a;for(let c=0;c<=di.length;c+=1){const d=di[c];if(((s=(i=n==null?void 0:n.receiver)==null?void 0:i.video)==null?void 0:s.codecs.findIndex(h=>h.mimeType===d))>=0||c===di.length-1){o(this,wa).get(d).add(e);break}}for(let c=0;c<=di.length;c+=1){const d=di[c];if(((a=(r=n==null?void 0:n.sender)==null?void 0:r.video)==null?void 0:a.codecs.findIndex(h=>h.mimeType===d))>=0||c===di.length-1){o(this,ka).get(d).add(e);break}}}handlePeerLeaving(e){re.hasFeature(ue.FORCE_VIDEO_CODEC)||(o(this,ka).forEach(n=>n.delete(e)),o(this,wa).forEach((n,i)=>{n.delete(e),n.size===0&&this.disableWebcam(i)}))}}Ol=new WeakMap,Dl=new WeakMap,Yt=new WeakMap,ne=new WeakMap,fc=new WeakMap,vr=new WeakMap,an=new WeakMap,Ta=new WeakMap,ba=new WeakMap,yr=new WeakMap,Nl=new WeakMap,us=new WeakMap,gc=new WeakMap,ka=new WeakMap,wa=new WeakMap,on=new WeakMap,vn=new WeakMap,Er=new WeakSet,_a=function(){return this.context.getValue("connectionHandler")},xt=new WeakSet,Qt=function(t){return o(this,on).get(t)},Ia=new WeakSet,vc=function(t,e){return o(this,on).set(t,e)},Zp=new WeakSet,q0=function(t){return o(this,on).delete(t)},em=new WeakSet,G0=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},tm=new WeakSet,J0=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},Te([k.trace("MediaNodeClient.reset",{country:k.location.country})],Ee.prototype,"reset",1),Te([k.trace("MediaNodeClient.joinRoom")],Ee.prototype,"joinRoom",1),Te([k.trace("MediaNodeClient.completeJoinRoom")],Ee.prototype,"completeJoinRoom",1),Te([k.trace("MediaNodeClient.leaveRoom")],Ee.prototype,"leaveRoom",1),Te([k.trace("MediaNodeClient.activatePeers")],Ee.prototype,"activatePeers",1),Te([k.trace("MediaNodeClient.deactivatePeers")],Ee.prototype,"deactivatePeers",1),Te([k.trace("MediaNodeClient.createConsumers")],Ee.prototype,"createConsumers",1),Te([k.trace("MediaNodeClient.closeConsumers")],Ee.prototype,"closeConsumers",1),Te([k.trace("MediaNodeClient._shareWebcam")],Ee.prototype,"_shareWebcam",1),Te([k.trace("MediaNodeClient.shareWebcam")],Ee.prototype,"shareWebcam",1),Te([k.trace("MediaNodeClient.shareScreen")],Ee.prototype,"shareScreen",1),Te([k.trace("MediaNodeClient.shareMic")],Ee.prototype,"shareMic",1),Te([k.trace("MediaNodeClient.pauseMic")],Ee.prototype,"pauseMic",1),Te([k.trace("MediaNodeClient.pauseWebcam")],Ee.prototype,"pauseWebcam",1),Te([k.trace("MediaNodeClient.resumeMic")],Ee.prototype,"resumeMic",1),Te([k.trace("MediaNodeClient.resumeWebcam")],Ee.prototype,"resumeWebcam",1),Te([k.trace("MediaNodeClient.disableWebcam")],Ee.prototype,"disableWebcam",1),Te([k.trace("HiveClient.disableMic")],Ee.prototype,"disableMic",1),Te([k.trace("HiveClient.disableScreenShare")],Ee.prototype,"disableScreenShare",1),Te([k.trace("MediaNodeClient.muteSelf")],Ee.prototype,"muteSelf",1),Te([k.trace("MediaNodeClient.resetVideoProducers")],Ee.prototype,"resetVideoProducers",1),Te([k.trace("MediaNodeClient.changeDisplayName")],Ee.prototype,"changeDisplayName",1),Te([k.trace("MediaNodeClient.kickPeer")],Ee.prototype,"kick",1),Te([k.trace("MediaNodeClient.kickAllPeers")],Ee.prototype,"kickAll",1),Te([k.trace("MediaNodeClient.muteAll")],Ee.prototype,"muteAll",1),Te([k.trace("MediaNodeClient.muteAllVideo")],Ee.prototype,"muteAllVideo",1),Te([k.trace("MediaNodeClient.disableAudio")],Ee.prototype,"disableAudio",1),Te([k.trace("MediaNodeClient.disableVideo")],Ee.prototype,"disableVideo",1),Te([k.trace("MediaNodeClient.pinPeer")],Ee.prototype,"pinPeer",1),Te([k.trace("MediaNodeClient.validateScreenShare")],Ee.prototype,"validateScreenShare",1);function $0(t,e,n){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const s=new Ee(t,e,n);return t.setValue("roomNodeClient",s),s}function K0(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(n){m.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var W2=Object.defineProperty,H2=Object.getOwnPropertyDescriptor,Sr=(t,e,n,i)=>{for(var s=i>1?void 0:i?H2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&W2(e,n,s),s},Tr,li,Xt,In,Gn,z0;const Y0=(z0=class{constructor(t,e,n,i){S(this,In),y(this,"self"),y(this,"authToken"),S(this,Tr,void 0),y(this,"viewType"),S(this,li,void 0),S(this,Xt,void 0);const{socket:s}=n,r=t.getValue("authToken");this.self=e,T(this,Xt,t),this.viewType=i,this.authToken=r,T(this,Tr,s),T(this,li,n),e.config.viewType!==Ft.Chat&&this.setupEvents()}get peerId(){return o(this,Xt).getValue("peerId")}get mediaJoined(){return o(this,Xt).getValue("connectionHandler").mediaJoined}static init(t,e,n,i,s){return p(this,null,function*(){const r=It(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield bt.__init__(t,n,i,s,s.name,c);if(navigator.product!=="ReactNative"){const h=!re.hasFeature(ue.PRECALL_BANDWIDTH_TEST);setTimeout(()=>p(this,null,function*(){const u=yield d.getAllDevices();m.info("populated_full_device_list",{devices:JSON.stringify(u)}),te.devices("AUDIO",u==null?void 0:u.filter(g=>g.kind==="audioinput")),te.devices("VIDEO",u==null?void 0:u.filter(g=>g.kind==="videoinput")),te.devices("SPEAKER",u==null?void 0:u.filter(g=>g.kind==="audiooutput")),m.info("Callstats:: initializing");try{yield te.initialize({peerId:a,engineName:Ue.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield r.getICEServers(),apiBase:t.getValue("apiBase"),flags:re.getAllFlags(),logger:m,apiHostnames:xv(t),skipConnectivityChecks:h}),m.info("Callstats:: initialized")}catch(g){m.error("Callstats:: initialization failed",{error:g})}}),0)}else m.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Y0(t,d,e,s.viewType)})}shareMediaTracks(){return p(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:i,audioEnabled:s,videoEnabled:r,screenShareEnabled:a,screenShareTracks:c}=this.self;if(i.canProduceAudio&&s)try{yield o(this,In,Gn).shareMic(e)}catch(d){this.self.disableAudio()}if(i.canProduceVideo&&r)try{const d=yield o(this,In,Gn).shareWebcam(n);d&&d.id!==n.id&&re.hasFeature(ue.EXP_RESHARE)&&(yield o(this,In,Gn).shareWebcam(d))}catch(d){this.self.disableVideo()}if(i.canProduceScreenshare&&a)try{yield(t=o(this,In,Gn))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return p(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){m.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(m.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){m.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(m.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){m.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return p(this,null,function*(){te.callEnded(),o(this,In,Gn).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){L.on(x.RESET_PRODUCER_STATE,()=>p(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),L.on(x.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),L.on(x.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),L.on(x.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),L.on(x.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),L.on(x.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&re.hasFeature(ue.REFRESH_ID_ON_DISCONNECTION)&&(e=Ar()),o(this,Tr).updateURL(e),k.resetPeerId(e),It().setHeader("dyte-tracing-id",e),Bs.remapContext(e,o(this,Xt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),L.on(x.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,li).on(z.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,li).on(Pd.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&L.emit(x.UPDATE_PERMISSIONS,e.patch)})}),o(this,li).on(z.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,li).on(z.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,li).on(z.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),L.onAsync(x.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),L.on(x.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:i})=>{var s;const r=(s=n==null?void 0:n.screenShare)!=null?s:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:r,score:t,participantId:this.self.id,scoreStats:i})}),L.on(x.MUTE_SELF,()=>p(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),te.audioOff())})),L.on(x.MUTE_SELF_VIDEO,()=>p(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),te.videoOff())})),L.onAsync(x.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),L.on(x.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return p(this,null,function*(){try{const{peer:e}=yield o(this,li).joinRoom(this.self);o(this,li).socket.flush();const n=Gh(e.stageType);if(o(this,Xt).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,Xt).notify("stageStatus")}catch(e){throw m.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return p(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Tr))==null||e.disconnect()}catch(i){m.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,Xt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,Xt).notify("stageStatus");try{(n=o(this,Tr))==null||n.disconnect()}catch(i){m.error("SelfController::leaveRoom::socketDisconnect")}K0(o(this,Xt)),ol.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return p(this,null,function*(){var e,n;const{peerId:i,viewType:s,meetingId:r,stageStatus:a,roomNodeOptions:c}=o(this,Xt).getAllValues(),{sfu:d}=c;try{if(s===Ft.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}$0(o(this,Xt),d,{socket:o(this,Tr),peerId:i})}const{roomJoined:h}=(n=yield(e=o(this,In,Gn))==null?void 0:e.joinRoom(this.self.name,r,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!h)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(h){throw m.error("Error:SelfController.mediaRoomJoin",{error:h}),new O("Error: could not join media room","0002")}})}leaveMediaRoom(t){return p(this,null,function*(){const e=o(this,Xt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ft.Webinar)&&o(this,In,Gn)&&(o(this,In,Gn).mediaJoined&&t!=="disconnected"&&(yield o(this,In,Gn).leaveRoom()),!(t==="stageLeft"&&e===Ft.Livestream)&&(o(this,In,Gn).mediaJoined=!1))})}cleanupSelf(){return p(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()})}},Tr=new WeakMap,li=new WeakMap,Xt=new WeakMap,In=new WeakSet,Gn=function(){return o(this,Xt).getValue("roomNodeClient")},z0);let hs=Y0;Sr([k.trace("SelfController.resetSelf")],hs.prototype,"resetSelf",1),Sr([k.trace("SelfController.setupEvents")],hs.prototype,"setupEvents",1),Sr([k.trace("SelfController.joinRoom")],hs.prototype,"joinRoom",1),Sr([k.trace("SelfController.leaveRoom")],hs.prototype,"leaveRoom",1),Sr([k.trace("SelfController.joinMediaRoom")],hs.prototype,"joinMediaRoom",1),Sr([k.trace("SelfController.leaveMediaRoom")],hs.prototype,"leaveMediaRoom",1),Sr([k.trace("SelfController.init")],hs,"init",1);var Ll;class q2{constructor(e){S(this,Ll,void 0),T(this,Ll,e)}on(e,n){let i;e===z.roomPeerCount?i=ny.fromBinary.bind(ny):i=Ey.fromBinary.bind(Ey),o(this,Ll).on(e,({payload:s})=>{const r=i(s);return n(r)})}}Ll=new WeakMap;var xl;class G2{constructor(e){S(this,xl,void 0),T(this,xl,e)}on(e,n){let i,s;switch(e){case z.transcript:{i=vh.fromBinary.bind(vh),s=vh.create();break}default:{m.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,xl).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}xl=new WeakMap;var J2=Object.defineProperty,$2=Object.getOwnPropertyDescriptor,nm=(t,e,n,i)=>{for(var s=i>1?void 0:i?$2(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&J2(e,n,s),s},ps;class Vl{constructor(e){S(this,ps,void 0),T(this,ps,e)}getPolls(){return o(this,ps).sendMessagePromise(Ti.getPolls)}createPoll(e,n,i=!1,s=!1){const r={anonymous:i,hideVotes:s,question:e,options:n};return o(this,ps).sendMessage(Ti.createPoll,FD.toBinary(r))}votePoll(e,n){const i={index:n,pollId:e};return o(this,ps).sendMessage(Ti.votePoll,WD.toBinary(i))}on(e,n){let i,s;switch(e){case Ti.updatePoll:case Ti.createPoll:case Ti.votePoll:{i=Ah.fromBinary.bind(Ah),s=Ah.create();break}}o(this,ps).on(e,({payload:r})=>{let a=s;try{a=i(r)}catch(c){m.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,ps).removeListeners(e)}}ps=new WeakMap,nm([k.trace("PollSocketHandler.getPolls")],Vl.prototype,"getPolls",1),nm([k.trace("PollSocketHandler.createPoll")],Vl.prototype,"createPoll",1),nm([k.trace("PollSocketHandler.votePoll")],Vl.prototype,"votePoll",1);var yn;class K2{constructor(e){S(this,yn,void 0),T(this,yn,e)}getStageRequests(){return p(this,null,function*(){const{payload:e}=yield o(this,yn).sendMessagePromise(z.getStageRequests);return e?Ph.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,yn).sendMessage(z.requestStageAccess)}cancelRequestAccess(){o(this,yn).sendMessage(z.cancelStageRequest)}grantAccess(e){return p(this,null,function*(){const n={userIds:e};o(this,yn).sendMessage(z.grantStageAccess,AD.toBinary(n))})}denyAccess(e){return p(this,null,function*(){const n={userIds:e};o(this,yn).sendMessage(z.denyStageAccess,OD.toBinary(n))})}joinStage(){return o(this,yn).sendMessagePromise(z.joinStage,void 0,void 0,z.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,yn).sendMessagePromise(z.leaveStage,Ty.toBinary(n),void 0,z.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,yn).sendMessagePromise(z.leaveStage,Ty.toBinary(n))}on(e,n){let i;switch(e){case z.grantStageAccess:case z.denyStageAccess:{i=void 0;break}case z.getStagePeers:{i=Sy.fromBinary.bind(Sy);break}case z.getStageRequests:case z.requestStageAccess:case z.cancelStageRequest:{i=Ph.fromBinary.bind(Ph);break}case z.peerStageStatusUpdate:{i=ty.fromBinary.bind(ty);break}}o(this,yn).on(e,({payload:s,id:r})=>{if(!s||!i)return n(void 0,r);const a=i(s);return n(a,r)})}getPeerInfo(e){return p(this,null,function*(){const n=yield o(this,yn).sendMessagePromise(z.getPeerInfo,ry.toBinary({peerId:e}));return Wr.fromBinary(n.payload)})}}yn=new WeakMap;var kt;class z2{constructor(e){S(this,kt,void 0),T(this,kt,e)}addPlugin(e,n){o(this,kt).sendMessage(ie.addPlugin,$O.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,kt).sendMessage(ie.removePlugin,zO.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return p(this,null,function*(){const{payload:e}=yield o(this,kt).sendMessagePromise(ie.getPlugins);return e?yD.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,i){const s={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,kt).sendMessage(ie.customPluginEventToRoom,rD.toBinary(s),i)}customPluginEventToPeers(e,n,i,s){const r={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(i))};o(this,kt).sendMessage(ie.customPluginEventToPeers,oD.toBinary(r),s)}enablePluginForRoom(e,n){o(this,kt).sendMessage(ie.enablePluginForRoom,QO.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,i){o(this,kt).sendMessage(ie.enablePluginForPeers,tD.toBinary({pluginId:e,peerIds:n}),i)}disablePluginForRoom(e,n){o(this,kt).sendMessage(ie.disablePluginForRoom,ZO.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,i){o(this,kt).sendMessage(ie.disablePluginForPeers,iD.toBinary({pluginId:e,peerIds:n}),i)}storeInsertKeys(e,n,i,s){const r={pluginId:e,storeName:n,insertKeys:i.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,kt).sendMessage(ie.storeInsertKeys,fy.toBinary(r),s)}storeGetKeys(e,n,i,s){const r={pluginId:e,storeName:n,getKeys:i.map(a=>({storeKey:a.key}))};o(this,kt).sendMessage(ie.storeGetKeys,uD.toBinary(r),s)}storeDeleteKeys(e,n,i,s){const r={pluginId:e,storeName:n,deleteKeys:i.map(a=>({storeKey:a.key}))};o(this,kt).sendMessage(ie.storeDeleteKeys,pD.toBinary(r),s)}storeDelete(e,n,i){o(this,kt).sendMessage(ie.storeDelete,fD.toBinary({pluginId:e,storeName:n}),i)}getPluginDataOld(e,n){m.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,i){const s={pluginId:e,storeName:n,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};o(this,kt).sendMessage(ie.storeInsertKeys,fy.toBinary(s))}on(e,n){let i;switch(e){case ie.addPlugin:case ie.enablePluginForPeers:case ie.enablePluginForRoom:{i=Rh.fromBinary.bind(Rh);break}case ie.removePlugin:case ie.disablePluginForPeers:case ie.disablePluginForRoom:{i=gy.fromBinary.bind(gy);break}case ie.customPluginEventToPeers:case ie.customPluginEventToRoom:{i=yy.fromBinary.bind(yy);break}case ie.storeInsertKeys:case ie.storeGetKeys:case ie.storeDeleteKeys:case ie.storeDelete:{i=vy.fromBinary.bind(vy);break}}o(this,kt).on(e,({payload:s,id:r})=>{const a=i(s);return n(a,r)})}}kt=new WeakMap;var Y2=Object.defineProperty,Q2=(t,e,n)=>e in t?Y2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,X2=(t,e,n)=>(Q2(t,typeof e!="symbol"?e+"":e,n),n),im=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},W=(t,e,n)=>(im(t,e,"read from private field"),n?n.call(t):e.get(t)),Be=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},ke=(t,e,n,i)=>(im(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),je=(t,e,n)=>(im(t,e,"access private method"),n),Ul={},Z2={get exports(){return Ul},set exports(t){Ul=t}},Ca=typeof Reflect=="object"?Reflect:null,Q0=Ca&&typeof Ca.apply=="function"?Ca.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},Bl;Ca&&typeof Ca.ownKeys=="function"?Bl=Ca.ownKeys:Object.getOwnPropertySymbols?Bl=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Bl=function(t){return Object.getOwnPropertyNames(t)};function ex(t){console&&console.warn&&console.warn(t)}var X0=Number.isNaN||function(t){return t!==t};function _e(){_e.init.call(this)}Z2.exports=_e,Ul.once=sx,_e.EventEmitter=_e,_e.prototype._events=void 0,_e.prototype._eventsCount=0,_e.prototype._maxListeners=void 0;var Z0=10;function Fl(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 Z0},set:function(t){if(typeof t!="number"||t<0||X0(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Z0=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||X0(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 eE(t){return t._maxListeners===void 0?_e.defaultMaxListeners:t._maxListeners}_e.prototype.getMaxListeners=function(){return eE(this)},_e.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")Q0(c,this,e);else for(var d=c.length,h=rE(c,d),n=0;n<d;++n)Q0(h[n],this,e);return!0};function tE(t,e,n,i){var s,r,a;if(Fl(n),r=t._events,r===void 0?(r=t._events=Object.create(null),t._eventsCount=0):(r.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),r=t._events),a=r[e]),a===void 0)a=r[e]=n,++t._eventsCount;else if(typeof a=="function"?a=r[e]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),s=eE(t),s>0&&a.length>s&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,ex(c)}return t}_e.prototype.addListener=function(t,e){return tE(this,t,e,!1)},_e.prototype.on=_e.prototype.addListener,_e.prototype.prependListener=function(t,e){return tE(this,t,e,!0)};function tx(){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 nE(t,e,n){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},s=tx.bind(i);return s.listener=n,i.wrapFn=s,s}_e.prototype.once=function(t,e){return Fl(e),this.on(t,nE(this,t,e)),this},_e.prototype.prependOnceListener=function(t,e){return Fl(e),this.prependListener(t,nE(this,t,e)),this},_e.prototype.removeListener=function(t,e){var n,i,s,r,a;if(Fl(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(s=-1,r=n.length-1;r>=0;r--)if(n[r]===e||n[r].listener===e){a=n[r].listener,s=r;break}if(s<0)return this;s===0?n.shift():nx(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},_e.prototype.off=_e.prototype.removeListener,_e.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),r;for(i=0;i<s.length;++i)r=s[i],r!=="removeListener"&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function iE(t,e,n){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?n?[s.listener||s]:[s]:n?ix(s):rE(s,s.length)}_e.prototype.listeners=function(t){return iE(this,t,!0)},_e.prototype.rawListeners=function(t){return iE(this,t,!1)},_e.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):sE.call(t,e)},_e.prototype.listenerCount=sE;function sE(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}_e.prototype.eventNames=function(){return this._eventsCount>0?Bl(this._events):[]};function rE(t,e){for(var n=new Array(e),i=0;i<e;++i)n[i]=t[i];return n}function nx(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function ix(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function sx(t,e){return new Promise(function(n,i){function s(a){t.removeListener(e,r),i(a)}function r(){typeof t.removeListener=="function"&&t.removeListener("error",s),n([].slice.call(arguments))}aE(t,e,r,{once:!0}),e!=="error"&&rx(t,s,{once:!0})})}function rx(t,e,n){typeof t.on=="function"&&aE(t,"error",e,n)}function aE(t,e,n,i){if(typeof t.on=="function")i.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(r){i.once&&t.removeEventListener(e,s),n(r)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class ax 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 oE=new ax;class cE{static encode(e){return oE.toBinary(e)}static decode(e){return oE.fromBinary(new Uint8Array(e))}}function ox(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var ms;class cx{constructor(e={}){X2(this,"opts"),Be(this,ms,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ke(this,ms,0)}wait(){return p(this,null,function*(){ke(this,ms,W(this,ms)+1);const e=ox(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Ae(2,W(this,ms))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return W(this,ms)}reset(){ke(this,ms,0)}}ms=new WeakMap;const fs={debug:0,info:1,warn:2,error:3};var br,kr;class dx{constructor(e){Be(this,br,void 0),Be(this,kr,void 0),ke(this,br,console),ke(this,kr,e)}debug(...e){fs[W(this,kr)]>fs.debug||W(this,br).debug("[Sockrates]:",...e)}info(...e){fs[W(this,kr)]>fs.info||W(this,br).info("[Sockrates]:",...e)}warn(...e){fs[W(this,kr)]>fs.warn||W(this,br).warn("[Sockrates]:",...e)}error(...e){fs[W(this,kr)]>fs.error||W(this,br).error("[Sockrates]:",...e)}}br=new WeakMap,kr=new WeakMap;var dE=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(dE||{});const lx="2",ux="3";var Ke,Ra,We,nt,gs,wt,Mi,vs,Jn,Pa,Oi,sm,lE,yc,jl,rm,uE,am,hE,Wl,om,cm,pE,Ec,Hl,Sc,ql,Gl,dm,Aa,Tc,bc,Jl;class hx{constructor(e,n){var i;Be(this,sm),Be(this,yc),Be(this,rm),Be(this,am),Be(this,Wl),Be(this,cm),Be(this,Ec),Be(this,Sc),Be(this,Gl),Be(this,Aa),Be(this,bc),Be(this,Ke,void 0),Be(this,Ra,void 0),Be(this,We,void 0),Be(this,nt,void 0),Be(this,gs,void 0),Be(this,wt,void 0),Be(this,Mi,void 0),Be(this,vs,void 0),Be(this,Jn,void 0),Be(this,Pa,void 0),Be(this,Oi,void 0);var s,r,a,c,d,h,u,g,E;ke(this,Ra,e),ke(this,gs,[]),ke(this,wt,new Ul),ke(this,Mi,!0),ke(this,Jn,!1),ke(this,We,n!=null?n:{}),(s=W(this,We)).autoReconnect!=null||(s.autoReconnect=!0),(r=W(this,We)).retryConnectionInterval!=null||(r.retryConnectionInterval=1e3),(a=W(this,We)).pingTimeout!=null||(a.pingTimeout=3e4),(c=W(this,We)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=W(this,We)).debug!=null||(d.debug=!0),(h=W(this,We)).maxReconnectionAttempts!=null||(h.maxReconnectionAttempts=10),(u=W(this,We)).disconnectOnPingTimeout!=null||(u.disconnectOnPingTimeout=!0),(g=W(this,We)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(E=W(this,We)).flushOnReconnect!=null||(E.flushOnReconnect=!1),ke(this,vs,{code:void 0,reason:void 0}),ke(this,nt,(i=W(this,We).logger)!=null?i:new dx(W(this,We).debug?"debug":"info")),ke(this,Oi,new cx)}get readyState(){var e;return(e=W(this,Ke))==null?void 0:e.readyState}get url(){return W(this,Ra)}updateURL(e){ke(this,Ra,e),je(this,cm,pE).call(this)}get config(){return W(this,We)}get sendQueue(){return W(this,gs)}flush(){if(!W(this,We).queueOnDisconnect)return!1;const e=[];return W(this,gs).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),ke(this,gs,e),W(this,gs)}connect(e=!1){return p(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){W(this,nt).debug("Websocket was already connecting or connected.");return}if(W(this,Mi)!==!1)return new Promise((n,i)=>{je(this,Aa,Tc).call(this),je(this,bc,Jl).call(this);try{ke(this,Ke,new WebSocket(je(this,sm,lE).call(this,W(this,Ra)))),W(this,Ke).binaryType="arraybuffer",W(this,nt).debug("Connecting");const s=setTimeout(()=>{W(this,nt).debug("Connection timeout. Closing socket"),ke(this,Mi,!0),je(this,bc,Jl).call(this),W(this,Ke).close(3001,"Connection Timeout"),W(this,We).autoReconnect&&!W(this,Jn)&&(W(this,wt).emit("reconnecting"),je(this,Ec,Hl).call(this)),i(new Error("Connection timed out!"))},W(this,We).connectionTimeout);W(this,Ke).onopen=()=>{W(this,nt).debug(`Ready State: ${dE[W(this,Ke).readyState]}`),s&&clearTimeout(s),je(this,Gl,dm).call(this),ke(this,vs,{code:void 0,reason:void 0}),W(this,wt).emit("connected"),W(this,We).flushOnReconnect&&this.flush(),n()},W(this,Ke).onclose=r=>{try{s&&clearTimeout(s);const{code:a,reason:c}=r;i(c),W(this,nt).debug("Socket closed. Close event:",{event:r}),W(this,nt).debug(`Connection closed code: ${a}`),W(this,nt).debug(`Connection closed reason: ${c}`),W(this,Jn)||je(this,Wl,om).call(this,a,c)}catch(a){je(this,yc,jl).call(this,a)}},W(this,Ke).onerror=r=>{je(this,yc,jl).call(this,r)},W(this,Ke).onmessage=r=>je(this,rm,uE).call(this,r)}catch(s){je(this,yc,jl).call(this,s,i)}})})}send(e,n,i,s){const r={event:e,id:n,payload:i,metadata:s};if(W(this,We).queueOnDisconnect&&(!W(this,Ke)||W(this,Ke).readyState!==1))return W(this,nt).debug("Queuing message since socket is not connected!",r),W(this,gs).push(r),!1;const a=cE.encode(r);return je(this,Sc,ql).call(this,a)}emit(e,n,i,s){return this.send(e,n,i,s)}sendRaw(e){return je(this,Sc,ql).call(this,e)}receive(e,n){return W(this,wt).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){W(this,wt).on(e,n);return}this.receive(e,n)}removeAllListeners(){W(this,wt).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){W(this,wt).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){W(this,wt).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){ke(this,Mi,!1),je(this,Aa,Tc).call(this),this.removeAllListeners(),ke(this,vs,{code:1e3,reason:"Sockrates disconnect method called"}),W(this,Ke).close(1e3,"Sockrates disconnect method called.")}}Ke=new WeakMap,Ra=new WeakMap,We=new WeakMap,nt=new WeakMap,gs=new WeakMap,wt=new WeakMap,Mi=new WeakMap,vs=new WeakMap,Jn=new WeakMap,Pa=new WeakMap,Oi=new WeakMap,sm=new WeakSet,lE=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)://.")},yc=new WeakSet,jl=function(t,e){W(this,nt).error("Error:",{error:t}),W(this,wt).emit("errored",{error:t}),e==null||e(t)},rm=new WeakSet,uE=function(t){if(je(this,Gl,dm).call(this),t.data===lx){W(this,nt).debug("Received ping from server"),je(this,Sc,ql).call(this,ux);return}const e=cE.decode(t.data),{id:n,payload:i}=e;W(this,nt).debug("Received message",{event:e.event,messageID:n}),W(this,wt).emit(e.event.toString(),{id:n,payload:i})},am=new WeakSet,hE=function(){return W(this,Ke).readyState===1},Wl=new WeakSet,om=function(t,e){ke(this,vs,{reason:e,code:t}),W(this,wt).emit("disconnected",{code:t,reason:e})},cm=new WeakSet,pE=function(){const{reason:t,code:e}=W(this,vs);e&&e!==1e3&&W(this,Mi)&&W(this,We).autoReconnect&&!W(this,Jn)&&(W(this,nt).debug(`Triggering reconnection due to ${t}.`),W(this,wt).emit("reconnecting"),je(this,Ec,Hl).call(this))},Ec=new WeakSet,Hl=function(t=!0){return p(this,null,function*(){if(t&&W(this,Jn)){W(this,nt).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(W(this,Jn)||W(this,Oi).reset(),W(this,We).maxReconnectionAttempts!==null&&W(this,Oi).getAttempts()>=W(this,We).maxReconnectionAttempts){W(this,wt).emit("failed"),ke(this,Jn,!1);return}ke(this,Jn,!0),je(this,bc,Jl).call(this),je(this,Aa,Tc).call(this);try{if(yield W(this,Oi).wait(),W(this,Mi)===!1)return;if(W(this,nt).debug(`Reconnection attempt ${W(this,Oi).getAttempts()}`),W(this,wt).emit("reconnectAttempt",{attempt:W(this,Oi).getAttempts()}),yield this.connect(),!je(this,am,hE).call(this))throw Error("Reconnect Failed");ke(this,Jn,!1),ke(this,vs,{code:void 0,reason:void 0}),W(this,wt).emit("reconnected")}catch(e){W(this,nt).debug("Failed to reconnect."),W(this,wt).emit("reconnectFailure",{attempt:W(this,Oi).getAttempts()}),je(this,Ec,Hl).call(this,!1)}})},Sc=new WeakSet,ql=function(t){try{return W(this,Ke).send(t),!0}catch(e){return W(this,nt).error(e.message),!1}},Gl=new WeakSet,dm=function(){this.config.disconnectOnPingTimeout&&(W(this,nt).debug("Resetting ping timeout"),je(this,Aa,Tc).call(this),ke(this,Pa,setTimeout(()=>{var t;W(this,nt).debug("Disconnecting the socket due to ping timeout"),ke(this,Mi,!0);const e=3002,n="Ping timeout";(t=W(this,Ke))==null||t.close(e,n),je(this,Wl,om).call(this,e,n)},W(this,We).pingTimeout)))},Aa=new WeakSet,Tc=function(){W(this,Pa)&&(clearTimeout(W(this,Pa)),ke(this,Pa,void 0))},bc=new WeakSet,Jl=function(){W(this,Ke)&&(W(this,Ke).onopen=void 0,W(this,Ke).onerror=void 0,W(this,Ke).onmessage=void 0,W(this,Ke).onclose=void 0)};var px=Object.defineProperty,mx=Object.getOwnPropertyDescriptor,$l=(t,e,n,i)=>{for(var s=i>1?void 0:i?mx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&px(e,n,s),s};const mE=65535,fx=3e3;var wr,ze,Ye,it,$n,ys,Kl,lm,zl,um,fE;const gE=(fE=class{constructor(t,{peerId:e,meetingId:n,authToken:i,capabilities:s}){S(this,Ye),S(this,Kl),S(this,zl),S(this,wr,void 0),S(this,ze,void 0),y(this,"roomName"),y(this,"authToken"),y(this,"capabilities"),S(this,$n,void 0),S(this,ys,void 0);var r;if(!e||!n||!i)throw new O("peerId, meetingId, or authToken can not be empty","0404");T(this,$n,void 0),T(this,ys,t),this.capabilities=s,this.roomName=n,this.authToken=i,T(this,wr,Q(this,Kl,lm).call(this,e)),T(this,ze,new hx(o(this,wr),{autoReconnect:!0,disconnectOnPingTimeout:(r=s.includes("PING"))!=null?r:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:m})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,Ye,it).socketJoinAttempted}set joinAttempted(t){o(this,Ye,it).socketJoinAttempted=t}get peerId(){return o(this,ys).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,wr,Q(this,Kl,lm).call(this,t)),m.debug("SocketService:: Connection URL updated.")),o(this,ze).updateURL(o(this,wr))}static getSocketEdgeDomain(t){return Fr({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,wr)}connect(){return p(this,null,function*(){o(this,Ye,it).socketJoinAttempted=!0,yield o(this,ze).connect(),o(this,Ye,it).socketJoinAttempted=!0,o(this,Ye,it).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return p(this,null,function*(){o(this,Ye,it).socketJoinAttempted=!1,o(this,ze).disconnect(),o(this,Ye,it).socketJoinAttempted=!0,o(this,Ye,it).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,ze).readyState===1}catch(t){return!1}}sendMessage(t,e,n){const i={};return k.injectContext(i),o(this,ze).send(t,n!=null?n:Q(this,zl,um).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,n,i){const s=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:s,protobuf:e,messageId:n,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:i,resp:s}){const r=s!=null?s:t;return new Promise((a,c)=>{const d=(b,w)=>{o(this,ze).removeListener(r,b),o(this,ze).removeListener(mE,w),o(this,ze).removeListener(Tn.errorResponse,w),o(this,ze).removeListener(Nn.errorResponse,w)},h=i!=null?i:Q(this,zl,um).call(this),u={};k.injectContext(u);const g=({id:b,payload:w})=>{if(h===b){let M;try{const D=d1.fromBinary(w);M=new Error(D.errorMessage)}catch(D){M=new Error("failed to parse error message",{cause:D});try{const F=lA.fromBinary(w);M=new Error(F.message)}catch(F){M=new Error("failed to parse error message",{cause:F})}}c(M),d(E,g)}},E=({id:b,payload:w})=>{h===b&&(a({id:b,payload:w}),d(E,g))};o(this,ze).on(r,E),o(this,ze).on(mE,g),o(this,ze).on(Tn.errorResponse,g),o(this,ze).on(Nn.errorResponse,g),setTimeout(()=>{d(E,g),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,ze).send(t,h,n,new TextEncoder().encode(JSON.stringify(u)))})}on(t,e){o(this,ze).on(t,e)}onStateEvent(t,e){o(this,ze).on(t,e)}removeListener(t,e){o(this,ze).removeListener(t,e)}removeListeners(t){o(this,ze).removeListeners(t)}flush(){return o(this,ze).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>p(this,null,function*(){m.info("SocketService::Connected to socket-edge"),o(this,$n)&&(clearTimeout(o(this,$n)),T(this,$n,void 0)),o(this,Ye,it).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;m.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:i,send:s}=(n=o(this,Ye,it).mediaState)!=null?n:{};i!=null&&i.state&&(i==null?void 0:i.state)!==ts.CONNECTED||s!=null&&s.state&&(s==null?void 0:s.state)!==ts.CONNECTED?L.emit(x.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ye,it).joinAttempted}):T(this,$n,setTimeout(()=>{L.emit(x.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ye,it).joinAttempted}),T(this,$n,void 0)},fx)),o(this,Ye,it).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>p(this,null,function*(){m.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),o(this,Ye,it).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>p(this,[t],function*({attempt:e}){m.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,Ye,it).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{m.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,Ye,it).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>p(this,null,function*(){m.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,Ye,it).mediaJoinAttempted}}),o(this,$n)&&(clearTimeout(o(this,$n)),T(this,$n,void 0)),L.emit(x.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,Ye,it).mediaJoinAttempted}),o(this,Ye,it).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>p(this,null,function*(){m.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),L.emit(x.SOCKET_SERVICE_FAILED),o(this,Ye,it).updateSocketConnectionState("failed")}))}},wr=new WeakMap,ze=new WeakMap,Ye=new WeakSet,it=function(){return o(this,ys).getValue("connectionHandler")},$n=new WeakMap,ys=new WeakMap,Kl=new WeakSet,lm=function(t){let e=gE.getSocketEdgeDomain(o(this,ys).getValue("baseURI"));typeof Ed(o(this,ys),"socket_server_base")=="string"&&(e=Ed(o(this,ys),"socket_server_base"));const n=`wss://${e}`,i=new URL(`${n}/ws`),s=this.peerId,r=ee(H({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},s!==t&&{oldPeerID:s}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>wd[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(r).forEach(([a,c])=>{i.searchParams.append(a,c.toString())}),i.href},zl=new WeakSet,um=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},fE);let kc=gE;$l([k.trace("SocketService.connect")],kc.prototype,"connect",1),$l([k.trace("SocketService.disconnect")],kc.prototype,"disconnect",1),$l([k.trace("SocketService.sendMessagePromise")],kc.prototype,"sendMessagePromise",1),$l([k.trace("SocketService.sendMessagePromiseWithTimeout")],kc.prototype,"sendMessagePromiseWithTimeout",1);const _r=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=VA.fromBinary(t),i=n.meetings.map(s=>{var r;return{id:s.id,title:s.title,participants:(r=s.participants)!=null?r:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:i}}static handleTransferPeerRaw({payload:t}){const e=dM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=cy.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return oy.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return ZA.fromBinary(t).payloads}static getConnectedRoomsDump(){return p(this,null,function*(){const t=yield _r.socketService.sendMessagePromise(z.getConnectedRoomsDump);return _r.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return p(this,null,function*(){const{payload:e}=yield _r.socketService.sendMessagePromise(z.createConnectedRooms,jA.toBinary({payloads:t}));return oy.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return p(this,null,function*(){})}static disableConnectedRooms(t){return p(this,null,function*(){const e=t.map(i=>({id:i})),n=yield _r.socketService.sendMessagePromise(z.deleteConnectedRooms,QA.toBinary({payloads:e}));return _r.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return p(this,null,function*(){try{const e=yield _r.socketService.sendMessagePromise(z.movePeers,rM.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 Je=_r;y(Je,"socketService"),y(Je,"currentMeetingId");var gx=Object.defineProperty,vx=Object.getOwnPropertyDescriptor,Yl=(t,e,n,i)=>{for(var s=i>1?void 0:i?vx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&gx(e,n,s),s};const Ma=class{constructor(t,e){y(this,"apiBase"),y(this,"selfController"),y(this,"pollController"),y(this,"chatController"),y(this,"metaController"),y(this,"storesManager"),y(this,"stageController"),y(this,"pluginController"),y(this,"internalsController"),y(this,"recordingController"),y(this,"livestreamController"),y(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 p(this,null,function*(){var e,n;const{peerId:i,apiBase:s,authToken:r,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(L.reset(),ol.cleanup(),K0(t),Ue.isSupported()===!1)throw new O("Browser not supported","0010",!0);const h=TN(t,{authToken:r,baseURL:s,cachedUserDetails:d});h.setRoomName(a),h.setRoomUUID(a),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",i),t.setValue("apiClient",h);const u=new iL;t.setValue("connectionHandler",u);const g=Ma.createSocketService(t),E=g.connect(),b=h.getUserDetails(),w=h.getPlugins();let M=St.HIVE,D,F="";try{yield Ma.setupFlagsmith(t)}catch(J){m.error("Failed to setup flagsmith",{error:J})}try{yield E}catch(J){m.error("[Controller]: Failed to connect to socket server:",{error:J})}try{({sfu:M,meetingTitle:F}=yield h.getRoomNodeData()),D=yield b,m.info(`SFU ${M} is being used.`),t.setValue("presetName",D.preset.name),t.setValue("roomNodeOptions",{sfu:M})}catch(J){m.error("Failed to get room metadata",{error:J})}const Y=jL.init(D.preset,!t.getValue("modules").theme),X=Ma.setupControllers(g,t,D,w,F,Y);JN(Y)&&((e=Ma.createRoomNodeClient(t,g).partialJoinRoom(D.participant.name,a,void 0))==null||e.catch(J=>{m.error("[Controller]: Failed to queue partial media room promise:",{error:J})})),k.location.country=(n=h.ipInfo)==null?void 0:n.country;const{controllers:A}=yield X;return KR(),new Ma(s,A)})}static setupFlagsmith(t){return p(this,null,function*(){var e;const{peerId:n,baseURI:i,overrides:s,meetingId:r,organizationId:a}=t.getAllValues(),c=JR(r),d=ee(H({entity:hh.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:r},Ue.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=s==null?void 0:s.whitelabelled_flags_endpoint)==null||e?Fr({servicePrefix:"flags",baseURI:i}):"edge.api.flagsmith.com";yield re.identify(`${hh.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,h,m),m.info("flagsmith::allFlags",{flags:JSON.stringify(re.getAllFlags())},!0)}catch(h){m.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,i,s,r){return p(this,null,function*(){var a,c,d;const h=e.getValue("modules"),{preset:u,participant:g}=n,E=e.getValue("defaults"),{sfu:b}=e.getValue("roomNodeOptions"),{viewType:w,mediaConstraints:{audio:M}}=r;e.setValue("viewType",w),e.setValue("defaults",H({mediaConfiguration:{audio:{enableHighBitrate:(a=M.enableHighBitrate)!=null?a:!1,enableStereo:(c=M.enableStereo)!=null?c:!1}}},E));const D=c2.init(e,w,u.permissions);e.setValue("maxPreferredStreams",Ue.isMobile()?r.maxVideoStreams.mobile:r.maxVideoStreams.desktop);let F,Y,X,A,J,me,Re,fe;const Qe=new G2(t);Je.socketService=t;const vt=new Vl(t),V=new bn(t),I=new K2(t),P=ol.create(t,e),K=new z2(t),Se=new q2(t),st=new qs(t),q=yield hs.init(e,P,g,D,r),N=yield Wy.init(e,q.self,P,Qe,s);if(h.participant&&(fe=new Ii(e,q.self,P,b)),(d=h.e2ee)!=null&&d.enabled&&h.e2ee.manager.init(m,L),h.chat&&(Y=yield bi.init(e,V,st,q.self,fe.participants)),h.internals&&(J=yield zh.init()),h.livestream&&r.viewType===Ft.Livestream&&re.hasFeature(ue.LIVESTREAM)&&(Re=new a0(q.self,Se)),r.viewType!==Ft.Chat){if(h.poll&&(F=yield xy.init(e,q.self,vt)),h.recording&&(me=new Yy(e,q.self,P)),h.stage&&(X=new Hy(e,I,P,q.self,fe.participants)),h.plugin){if(!fe)throw new O("The plugin module cannot be initialized without the `participant` module","0102");const zn=yield i;A=yield po.init(e,zn,K,V,Y==null?void 0:Y.chat,q.self,fe.participants,s)}if(h.pip){const zn=yield QR._init(e,q.self);e.setValue("pip",zn)}}const rt={storesManager:new zL(e,K),pollController:F,selfController:q,metaController:N,chatController:Y,stageController:X,pluginController:A,recordingController:me,internalsController:J,livestreamController:Re,participantController:fe};return{theme:r,permissions:D,controllers:rt}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:i}=t.getAllValues(),{sfu:s}=i;return $0(t,s,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:i}=t.getAllValues(),s=["PING"];return new kc(t,{peerId:e,meetingId:n,authToken:i,capabilities:s})}};let wc=Ma;Yl([k.trace("Controller.init")],wc,"init",1),Yl([k.trace("setupFlagsmith")],wc,"setupFlagsmith",1),Yl([k.trace("Controller.createRoomNodeClient")],wc,"createRoomNodeClient",1),Yl([k.trace("Controller.createSocketService")],wc,"createSocketService",1);var yx=Object.defineProperty,Ex=Object.getOwnPropertyDescriptor,Sx=(t,e,n,i)=>{for(var s=i>1?void 0:i?Ex(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&yx(e,n,s),s},Ql,hm;class vE extends cn{constructor(e,n){super(),S(this,Ql,void 0),y(this,"meetings",[]),y(this,"parentMeeting",null),S(this,hm,void 0),T(this,hm,e),T(this,Ql,n.self)}get supportsConnectedMeetings(){return o(this,Ql).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Je.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
26
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return p(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Je.getConnectedRoomsDump()})}createMeetings(e){return p(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Je.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return p(this,null,function*(){this.validateConnectedMeetingsAction(),yield Je.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return p(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(s=>s.id)):Promise.resolve());return yield Promise.all(n),yield Je.disableConnectedRooms(e)})}moveParticipants(e,n,i){return p(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield Je.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i.map(r=>({id:r}))});return s.success&&this.moveSuccessHandler(e,n,i),s})}moveParticipantsWithCustomPreset(e,n,i){return p(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield Je.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i});return s.success&&this.moveSuccessHandler(e,n,i.map(r=>r.id)),s})}moveSuccessHandler(e,n,i){const s=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(r=>r.participants)].forEach(r=>s.set(r.id,r)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(r=>s.get(r)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(r=>!i.includes(r.id))),this.meetings=this.meetings.map(r=>{if(n===r.id){const a=r.participants.concat(i.map(c=>s.get(c)));return ee(H({},r),{participants:a})}if(e===r.id){const a=r.participants.filter(c=>!i.includes(c.id));return ee(H({},r),{participants:a})}return r})}}Ql=new WeakMap,hm=new WeakMap,Sx([en({maxInvocations:60,period:60})],vE.prototype,"getConnectedMeetings",1);var Tx=Object.defineProperty,bx=Object.getOwnPropertyDescriptor,pm=(t,e,n,i)=>{for(var s=i>1?void 0:i?bx(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&Tx(e,n,s),s},_c,Kn,mm,fm;const Es=(mm=class{constructor(t,e,n){y(this,"connectedMeetings"),S(this,_c,void 0),S(this,Kn,void 0),S(this,fm,void 0),T(this,fm,t),T(this,_c,n),this.connectedMeetings=new vE(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return Es.instance||(Es.instance=new Es(t,e,n)),Es.instance.connectedMeetings.supportsConnectedMeetings&&(Es.instance.setupEvents(),e.self.once("roomJoined",()=>Es.instance.getConnectedMeetings())),Es.instance}setCurrentMeeting(t){T(this,Kn,t),Je.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Je.socketService&&(Je.socketService.on(z.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Je.socketService.on(z.transferPeer,this.handleTransferPeer.bind(this)),Je.socketService.on(z.movedPeer,this.handleMovedPeer.bind(this)),Je.socketService.on(z.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Je.socketService.on(z.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Je.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return p(this,arguments,function*({authToken:e,meetingId:n}){var i,s,r,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
27
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);m.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,Kn).self.videoEnabled,audio:o(this,Kn).self.audioEnabled};try{o(this,Kn).self.cleanupEvents(),yield o(this,Kn).leave("connected-meeting")}catch(h){m.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(s=(i=o(this,Kn))==null?void 0:i.meta)==null?void 0:s.meetingId}`,{error:h})}Je.socketService=void 0,m.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield TE.init(ee(H({},o(this,_c)),{cachedUserDetails:null,defaults:ee(H(H({},o(this,_c).defaults),c),{mediaHandler:o(this,Kn).self}),authToken:e}));m.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(r=d==null?void 0:d.meta)==null?void 0:r.meetingId}`);try{const{hidden:h}=o(this,Kn).self;d.self.setName(o(this,Kn).self.name),yield d.join(),h&&d.self.hide()}catch(h){m.error("ConnectedMeetingsController.joinRoom",{error:h})}return m.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Je.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Je.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Je.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(i=>{n.set(i.id,i)}),e.forEach(i=>{n.has(i.id)?n.get(i.id).title=i.title:n.set(i.id,ee(H({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Je.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},_c=new WeakMap,Kn=new WeakMap,fm=new WeakMap,y(mm,"instance"),mm);let Xl=Es;pm([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Xl.prototype,"getConnectedMeetings",1),pm([k.trace("ConnectedMeetingsController.setupEvents")],Xl.prototype,"setupEvents",1),pm([k.trace("ConnectedMeetingsController.switchMeeting")],Xl.prototype,"switchMeeting",1);class kx{constructor(){y(this,"battery"),y(this,"init",()=>p(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){m.error("Error getting battery",e)}})),y(this,"updateChargeInfo",()=>{var e;m.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),y(this,"updateLevelInfo",()=>{if(!this.battery){m.log("Battery level: Not known");return}m.log(`Battery level: ${this.battery.level*100}%`)}),y(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const yE=new kx;function wx(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:n,orgId:i,participantId:s}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let r="dyte.io";e&&(r=e);const a=`https://api.${r}`;return{meetingId:n,orgId:i,participantId:s,baseURI:r,apiBase:a}}catch(n){throw m.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new O("Invalid auth token","0004")}}var _x=Object.defineProperty,Ix=Object.getOwnPropertyDescriptor,Zl=(t,e,n,i)=>{for(var s=i>1?void 0:i?Ix(e,n):e,r=t.length-1,a;r>=0;r--)(a=t[r])&&(s=(i?a(e,n,s):a(s))||s);return i&&s&&_x(e,n,s),s},Rt,eu,tu,gm,EE,SE;let Ss=(SE=class{constructor(t,e){S(this,gm),S(this,Rt,void 0),S(this,eu,void 0),S(this,tu,void 0),T(this,tu,t),T(this,Rt,e)}static init(t){return p(this,null,function*(){var e,n,i,s,r,a,c;HR(),Ue.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Ar();yE.init();const{authToken:h,baseURI:u}=t,g=wx(h,u),{meetingId:E}=g,b=Fc(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const w=Ss.setupContext(d,t,E,b);k.meetingMetadata.roomName=E,k.meetingMetadata.userId=b.participantId,k.meetingMetadata.organizationId=b.orgId,k.init(w,(s=(i=t.modules)==null?void 0:i.tracing)!=null?s:!0),m.info("DyteClient::init::options",{dyteClientInitOptions:ee(H({},t),{authToken:`${(r=t.authToken)==null?void 0:r.slice(0,10)}...
28
- ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const M=yield wc.init(w),D=new Ss(w,M);return Q(c=D,gm,EE).call(c,t),D})}static setupContext(t,e,n,i){var s;const r=Bs.createContext(t,e),a=H(H({},VR),e==null?void 0:e.modules);return r.setValue("peerId",t),r.setValue("modules",a),r.setValue("sdkName","web-core"),r.setValue("meetingId",n),r.setValue("apiBase",i.apiBase),r.setValue("baseURI",i.baseURI),r.setValue("userId",i.participantId),r.setValue("organizationId",i.orgId),r.setValue("authToken",e.authToken),r.setValue("overrides",(s=e.overrides)!=null?s:{}),r.setValue("env",UR({baseURI:i.baseURI})),r.setValue("defaults",e.defaults||{audio:!0,video:!0}),r.setValue("onError",e.onError||(()=>{})),r.setValue("cachedUserDetails",xn(e.cachedUserDetails)),r.setValue("sdkVersion","2.5.0-staging.102"),r}join(){return p(this,null,function*(){const{selfController:t}=o(this,Rt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return p(this,null,function*(){yE.cleanup();const{selfController:e}=o(this,Rt);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,Rt).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,Rt).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,Rt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,Rt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,Rt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,Rt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,Rt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,eu))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,Rt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,Rt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,Rt).stageController)==null?void 0:t.stage}get stores(){return o(this,Rt).storesManager}get __internals__(){var t;return(t=o(this,Rt).internalsController)==null?void 0:t.internals}joinRoom(){return p(this,null,function*(){return this.join()})}leaveRoom(t){return p(this,null,function*(){return this.leave(t)})}},Rt=new WeakMap,eu=new WeakMap,tu=new WeakMap,gm=new WeakSet,EE=function(t){T(this,eu,Xl.init(o(this,tu),this,t))},SE);Zl([Ot("0002"),ns.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Ss.prototype,"join",1),Zl([Ot("0003")],Ss.prototype,"leave",1),Zl([Ot("0001"),ns.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Ss,"init",1),Ss=Zl([Ot("0000")],Ss);const TE=Ss;return TE}();
12
+ `)),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,i]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,r;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),i.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(r=s)}),n&&r)try{if(n.currentRoundTripTime&&r.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:r.currentRoundTripTime};const s=(r.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch(s){return}})}close(){this.pc1.close(),this.pc2.close()}}class Yp extends lt{constructor(e){super(),m(this,"call"),m(this,"timeOut"),this.call=new Wi(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 PS=8,RS=1/1e3;class MS extends Yp{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(Wi.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let i=0;i<262144;i+=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(r){}}const i=e.getTime()-this.startTime.getTime();i>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=i/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const i=new Date,n=i.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const r=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*PS/(n/1e3);this.finalBitrateSum+=r,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=i}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const r=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(r*RS)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:i,backendRTT:n})=>super.testComplete({RTT:i,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Il extends Yp{constructor(e,i=Wi.noFilter){super(e),m(this,"ch1"),m(this,"ch2"),this.call.setIceCandidateFilter(i);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(i){}}dataChannelHandler(e){const i=e.channel;this.ch2=i,i.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class AS extends Il{constructor(e){super(e,Wi.isHost)}}class DS extends Il{constructor(e){super(e,Wi.isRelay)}}class OS extends Il{constructor(e){super(e,Wi.isReflexive)}}class NS{constructor(){m(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:i,apiHostnames:n,logger:r}){var s,o,c;if(!this.ipInformation){try{const d=`https://${n.location}`,l=yield(yield fetch(d)).json();if(((s=l.loc)==null?void 0:s.length)>5)return this.ipInformation=l,(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=dn(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(d){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:d})}try{const d=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${i}`,{method:"POST"});this.ipInformation=yield d.json(),(c=this.ipInformation)!=null&&c.ip&&(this.ipInformation.ip=dn(this.ipInformation.ip))}catch(d){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:d})}}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Cl=new NS,Qp=[{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 Xp(t){const[e,i]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(i)}}}class Zp{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 em extends lt{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 lt}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.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,i,n){var r,s;const o=((s=(r=this==null?void 0:this.callStatsInstance)==null?void 0:r.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};i.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))):(i.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,i,n){var r,s;const o=((s=(r=this==null?void 0:this.callStatsInstance)==null?void 0:r.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};i.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))):(i.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,i,n){var r;const s=((r=this==null?void 0:this.callStatsInstance)==null?void 0:r.currentUserMediaStates)||{};i.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))):(i.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,i,n){var r;const s=((r=this==null?void 0:this.callStatsInstance)==null?void 0:r.currentUserMediaStates)||{};i.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))):(i.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,i,n){var r;const s=((r=this==null?void 0:this.callStatsInstance)==null?void 0:r.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=s,l=o||c||d;i.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(i.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,i,n){var r,s;const o=!!Array.from(((s=(r=this==null?void 0:this.callStatsInstance)==null?void 0:r.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((c,d)=>c||d.audio||d.video||d.screen,!1);i.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))):(i.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.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.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,i=!1){return u(this,null,function*(){const n=yield e.getStats(),r=i?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 r})}generateConsumerStreamMap(e,i=!1){return u(this,null,function*(){const n=yield e.getStats(),r=i?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 r})}deregisterProducer(e){this.outboundProducerMap.forEach((i,n)=>{i===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((i,n)=>{i===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var i;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(i=e.relayProtocol)!=null?i:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(i=>{const n=i.framesEncoded>0,r=i.packetsSent>0,s=i.frameWidth&&i.frameHeight;return n&&r&&!!s})||e[e.length-1]}parseRTCReport(e,i=[],n=!1,r=void 0,s=void 0){var o,c,d,l,p,g,y,T,b,N,M,F,H;const K=e,I=new Zp,re=i.length?new Set(i):void 0,ae=[],De=[],Oe=[],ft=new Map,Yt=new Map;for(const A of K.values()){if(re){if(re.size===0)break;if(re.has(A.type))n&&re.delete(A.type);else continue}switch(A.type){case"local-candidate":{ae.push(this.getIceCandidateStats(A));break}case"remote-candidate":{De.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:k}=A,{selected:_}=A,W=A,Ie={nominated:k!=null?k:_,currentRoundTripTime:W.currentRoundTripTime,totalRoundTripTime:W.totalRoundTripTime,bytesReceived:W.bytesReceived,bytesSent:W.bytesSent,availableOutgoingBitrate:W.availableOutgoingBitrate,availableIncomingBitrate:W.availableIncomingBitrate,lastPacketReceivedTimestamp:W.lastPacketReceivedTimestamp,lastPacketSentTimestamp:W.lastPacketSentTimestamp,localCandidateId:W.localCandidateId,remoteCandidateId:W.remoteCandidateId,bytesDiscardedOnSend:W.bytesDiscardedOnSend,packetsSent:W.packetsSent,packetsReceived:W.packetsReceived,packetsDiscardedOnSend:W.packetsDiscardedOnSend};Oe.push(Ie),(A.nominated===!0||A.selected===!0)&&(I.candidatePair=Ie);break}case"transport":{const k=A;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 _={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(I.transport=_,s){if(s.producing){const W=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,W,_)}if(s.consuming){const W=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,W,_)}}break}case"remote-inbound-rtp":{const k=A,_={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};I.remoteInboundRtp.set(k.localId,_);break}case"outbound-rtp":{const k=A,_=r||this.outboundProducerMap.get(A.id),W=this.pausedProducerMap.get(_);if(W){if(W.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ie=this.overallProducersStatsMap[_];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(A.id)){I.staleProducerStreamMap=!0;break}const Ye=this.callStatsInstance.producers.get(_);if(((o=Ye==null?void 0:Ye.track)==null?void 0:o.readyState)==="ended")break;I.producerStreamMap.has(_)||I.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const U={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 C=k,Qe=x({frameHeight:C.frameHeight,frameWidth:C.frameWidth,framesEncoded:C.framesEncoded,framesDropped:C.framesDropped,framesPerSecond:C.framesPerSecond,framesSent:C.framesSent,keyFramesEncoded:C.keyFramesEncoded,firCount:C.firCount,encoderImplementation:C.encoderImplementation,hugeFramesSent:C.hugeFramesSent,pliCount:C.pliCount,qpSum:C.qpSum,qualityLimitationDurations:C.qualityLimitationDurations,qualityLimitationReason:C.qualityLimitationReason,qualityLimitationResolutionChanges:C.qualityLimitationResolutionChanges,totalEncodeTime:C.targetBitrate,totalPacketSendDelay:C.totalPacketSendDelay,retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,scalabilityMode:C.scalabilityMode,powerEfficientEncoder:C.powerEfficientEncoder},U);I.outboundVideoRtp.set(A.id,Qe),I.producerStreamMap.get(_).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(_,Ie,Qe)}else if(k.mediaType==="audio"||k.kind==="audio"){const C=k,Qe=x({retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent},U);I.outboundAudioRtp.set(A.id,Qe),I.producerStreamMap.get(_).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(_,Ie,Qe)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=A,_=r||this.inboundConsumerMap.get(A.id),W=this.pausedConsumerMap.get(_);if(W){if(W.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ie=this.overallConsumersStatsMap[_];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(A.id)){I.staleConsumerStreamMap=!0;break}I.consumerStreamMap.has(_)||I.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ye={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 U=k,C=x({frameHeight:U.frameHeight,frameWidth:U.frameWidth,framesDecoded:U.framesDecoded,framesDropped:U.framesDropped,framesPerSecond:U.framesPerSecond,framesReceived:U.framesReceived,keyFramesDecoded:U.keyFramesDecoded,firCount:U.firCount,decoderImplementation:U.decoderImplementation,pliCount:U.pliCount,totalProcessingDelay:U.totalProcessingDelay,qpSum:U.qpSum||0,totalAssemblyTime:U.totalAssemblyTime||0,totalDecodeTime:U.totalDecodeTime||0,totalFreezesDuration:U.totalFreezesDuration||0,totalInterFrameDelay:U.totalInterFrameDelay||0,totalPausesDuration:U.totalPausesDuration||0,totalSquaredInterFrameDelay:U.totalSquaredInterFrameDelay||0,freezeCount:U.freezeCount||0,pauseCount:U.pauseCount||0,powerEfficientDecoder:U.powerEfficientDecoder},Ye);C.score=zp({frameWidth:C.frameWidth||0,framesDecoded:(C.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(_))==null?void 0:c.framesDecoded)||0),framesPerSecond:C.framesPerSecond||0,packetsLost:(C.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(_))==null?void 0:d.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((l=this.videoConsumerToStatsMap.get(_))==null?void 0:l.packetsReceived)||0),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),Yt.set(_,{score:+(C.score*10).toFixed(),frameWidth:C.frameWidth||0,frameHeight:C.frameHeight||0,framesPerSecond:C.framesPerSecond||0,packetsLostPercentage:lc({packetsLost:(C.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(_))==null?void 0:p.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(_))==null?void 0:g.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((C.bytesReceived||0)-(((y=this.videoConsumerToStatsMap.get(_))==null?void 0:y.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,C),I.inboundVideoRtp.set(A.id,C),I.consumerStreamMap.get(_).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(_,Ie,C)}else if(k.mediaType==="audio"||k.kind==="audio"){const U=k,C=x({audioLevel:U.audioLevel,concealedSamples:U.concealedSamples,concealmentEvents:U.concealmentEvents,totalAudioEnergy:U.totalAudioEnergy,totalSamplesDuration:U.totalSamplesDuration,totalSamplesReceived:U.totalSamplesReceived,fecPacketsDiscarded:U.fecPacketsDiscarded||0,fecPacketsReceived:U.fecPacketsReceived||0,insertedSamplesForDeceleration:U.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:U.removedSamplesForAcceleration||0,silentConcealedSamples:U.silentConcealedSamples||0,playoutId:U.playoutId},Ye);C.score=Kp({concealmentEvents:(C.concealmentEvents||0)-(((T=this.audioConsumerToStatsMap.get(_))==null?void 0:T.concealmentEvents)||0),packetsLost:(C.packetsLost||0)-(((b=this.audioConsumerToStatsMap.get(_))==null?void 0:b.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((N=this.audioConsumerToStatsMap.get(_))==null?void 0:N.packetsReceived)||0),jitter:C.jitter||0}),Yt.set(_,{score:+(C.score*10).toFixed(),packetsLostPercentage:lc({packetsLost:(C.packetsLost||0)-(((M=this.audioConsumerToStatsMap.get(_))==null?void 0:M.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(_))==null?void 0:F.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((C.bytesReceived||0)-(((H=this.audioConsumerToStatsMap.get(_))==null?void 0:H.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,C),I.inboundAudioRtp.set(A.id,C),I.consumerStreamMap.get(_).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(_,Ie,C)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(I.producerStreamMap.forEach((A,k)=>{var _,W,Ie,Ye,U,C,Qe,on,Do,Oo,No,Lo,xo,Vo,Uo,Fo,Bo,Wo,jo,Ho,Go,qo,Jo;if(A.outboundVideoRtpId.length>0){const ye=[];A.outboundVideoRtpId.forEach(tp=>{ye.push(I.outboundVideoRtp.get(tp))});const oe=this.getWorkingSimulcastVideoStats(ye);oe.score=Jp({frameWidth:oe.frameWidth||0,framesPerSecond:oe.framesPerSecond||0,jitter:((_=oe.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(oe.packetsSent||0)-(((W=this.videoProducerToStatsMap.get(k))==null?void 0:W.packetsSent)||0),packetsLost:(((Ie=oe.remoteData)==null?void 0:Ie.packetsLost)||0)-(((U=(Ye=this.videoProducerToStatsMap.get(k))==null?void 0:Ye.remoteData)==null?void 0:U.packetsLost)||0),framesEncoded:(oe.framesEncoded||0)-(((C=this.videoProducerToStatsMap.get(k))==null?void 0:C.framesEncoded)||0)}),ft.set(k,{score:+(oe.score*10).toFixed(),frameWidth:oe.frameWidth||0,frameHeight:oe.frameHeight||0,framesPerSecond:oe.framesPerSecond||0,jitter:((Qe=oe.remoteData)==null?void 0:Qe.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:dc({packetsSent:(oe.packetsSent||0)-(((on=this.videoProducerToStatsMap.get(k))==null?void 0:on.packetsSent)||0),packetsLost:(((Do=oe.remoteData)==null?void 0:Do.packetsLost)||0)-(((No=(Oo=this.videoProducerToStatsMap.get(k))==null?void 0:Oo.remoteData)==null?void 0:No.packetsLost)||0)}),bitrate:((oe.bytesSent||0)-(((Lo=this.videoProducerToStatsMap.get(k))==null?void 0:Lo.bytesSent)||0))*8/7,cpuLimitations:oe.qualityLimitationReason==="cpu",bandwidthLimitations:oe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,oe)}else if(A.outboundAudioRtpId.length>0){const ye=I.outboundAudioRtp.get(A.outboundAudioRtpId[0]);ye.score=qp({packetsSent:(ye.packetsSent||0)-(((xo=this.audioProducerToStatsMap.get(k))==null?void 0:xo.packetsSent)||0),packetsLost:(((Vo=ye.remoteData)==null?void 0:Vo.packetsLost)||0)-(((Fo=(Uo=this.audioProducerToStatsMap.get(k))==null?void 0:Uo.remoteData)==null?void 0:Fo.packetsLost)||0),jitter:((Bo=ye.remoteData)==null?void 0:Bo.jitter)||0}),ft.set(k,{score:+(ye.score*10).toFixed(),bitrate:((ye.bytesSent||0)-(((Wo=this.audioProducerToStatsMap.get(k))==null?void 0:Wo.bytesSent)||0))*8/7,packetsLostPercentage:dc({packetsSent:(ye.packetsSent||0)-(((jo=this.audioProducerToStatsMap.get(k))==null?void 0:jo.packetsSent)||0),packetsLost:(((Ho=ye.remoteData)==null?void 0:Ho.packetsLost)||0)-(((qo=(Go=this.audioProducerToStatsMap.get(k))==null?void 0:Go.remoteData)==null?void 0:qo.packetsLost)||0)}),jitter:((Jo=ye.remoteData)==null?void 0:Jo.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,ye)}}),Oe.forEach(A=>{const k=ae.find(W=>W.id===A.localCandidateId?(A.localCandidateId=W.id,W):null),_=De.find(W=>W.id===A.remoteCandidateId?(A.remoteCandidateId=W.id,W):null);k&&(A.localCandidateType=k.type,A.localCandidateAddress=dn(k.address),A.localCandidatePort=k.port,A.localCandidateProtocol=k.protocol,A.localCandidateUrl=k.url,A.localCandidateNetworkType=k.networkType,A.localCandidateRelatedAddress=dn(k.relatedAddress),A.localCandidateRelatedPort=k.relatedPort),_&&(A.remoteCandidateType=_.type,A.remoteCandidateAddress=dn(_.address),A.remoteCandidatePort=_.port,A.remoteCandidateProtocol=_.protocol,A.remoteCandidateUrl=_.url)}),I.candidatePair&&(I.transport?(I.transport.totalRoundTripTime=I.candidatePair.totalRoundTripTime,I.transport.availableOutgoingBitrate=I.candidatePair.availableOutgoingBitrate,I.transport.availableIncomingBitrate=I.candidatePair.availableIncomingBitrate,I.transport.roundTripTime=I.candidatePair.currentRoundTripTime):I.transport={bytesReceived:I.candidatePair.bytesReceived,bytesSent:I.candidatePair.bytesSent,totalRoundTripTime:I.candidatePair.totalRoundTripTime,availableOutgoingBitrate:I.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:I.candidatePair.availableIncomingBitrate,roundTripTime:I.candidatePair.currentRoundTripTime}),I.transport&&(I.transport.candidatePairs=Oe),I.transport&&!I.transport.roundTripTime){let A=0,k=0;I.remoteInboundRtp.forEach((_,W)=>{_.roundTripTime&&_.roundTripTime>A&&(A=_.roundTripTime,k=_.totalRoundTripTime)}),I.transport.roundTripTime=A,I.transport.totalRoundTripTime=k}if(Yt.size>0)try{this.observer.emit("consumer_score",Yt)}catch(A){}if(ft.size>0)try{this.observer.emit("producer_score",ft)}catch(A){}return I}getProducersReport(e){return u(this,null,function*(){const i=e.map(n=>this.generateProducerStreamMap(n,!0));return i.length>0?Promise.all(i):void 0})}getConsumersReport(e){return u(this,null,function*(){const i=e.map(n=>this.generateConsumerStreamMap(n,!0));return i.length>0?Promise.all(i):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,i,n){return u(this,null,function*(){const r=yield this.getTransportReport(e),s={producing:n,consuming:i,id:e.id},o=r,c=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!c)return;const d={stats:c.transport,transportId:e.id,consuming:i,producing:n},l=c.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(c),p=c.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(c);return{transportReport:d,producerReport:l,consumerReport:p}})}getProducerStatsFromReport(e){const i=[];try{e.producerStreamMap.forEach((n,r)=>{var s,o;i.push({producerId:r,videoStats:n.outboundVideoRtpId.map(c=>e.outboundVideoRtp.get(c)),audioStats:n.outboundAudioRtpId.map(c=>e.outboundAudioRtp.get(c)),appData:((o=(s=this.callStatsInstance.producers)==null?void 0:s.get(r))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return i}getConsumerStatsFromReport(e){const i=[];try{e.consumerStreamMap.forEach((n,r)=>{const{peerId:s,producerId:o,appData:c}=this.consumerPeerIdMap.get(r);i.push({consumerId:r,peerId:s,producerId:o,appData:c,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 i}getUserLocation(){return u(this,null,function*(){return new Promise((e,i)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):i()}catch(n){i(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const i={iceServers:e||Qp},n=new Promise((l,p)=>{try{const g=new AS(i);g.addListener("done",l),g.addListener("failed",()=>{l({connectivity:!1})}),g.start(2e3)}catch(g){p(g)}}),r=new Promise((l,p)=>{try{const g=new DS(i);g.addListener("done",l),g.addListener("failed",()=>{l({connectivity:!1})}),g.start(2e3)}catch(g){p(g)}}),s=new Promise((l,p)=>{try{const g=new OS(i);g.addListener("done",l),g.addListener("failed",()=>{l({connectivity:!1})}),g.start(2e3)}catch(g){p(g)}}),[o,c,d]=yield Promise.all([n,r,s]);return{host:o==null?void 0:o.connectivity,relay:c==null?void 0:c.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(i){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const i=yield new Promise((n,r)=>{try{const s={iceServers:e||Qp},o=new MS(s);o.addListener("done",n),o.addListener("failed",r),o.start(1e4)}catch(s){r(s)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(i){return}})}getIPDetails(){return u(this,null,function*(){var e,i;try{return this.ipDetails||(this.ipDetails=yield Cl.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(i=this.callStatsInstance)==null?void 0:i.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(n){return}})}getNetworkQuality(e){return u(this,null,function*(){const[i,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:i,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,i=!1){return u(this,null,function*(){var n,r;if(i){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d!=null&&d.loc?Xp(d==null?void 0:d.loc):void 0}}const[s,o,c]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:c,effectiveNetworkType:(r=navigator.connection)==null?void 0:r.effectiveType,location:c!=null&&c.loc?Xp(c==null?void 0:c.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 LS extends em{}class tm extends em{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.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.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.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,i=!1){return u(this,null,function*(){const n=yield e.getStats(),r=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...r.consumerStreamMap.values()][0],o=i?this.getConsumerStatsFromParsedConsumerStats(r,s,e.id):void 0;for(const c of n.values())switch(c.type){case"inbound-rtp":{this.inboundConsumerMap.set(c.id,e.id);break}}return o})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((i,n)=>{i===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((i,n)=>{i===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var i;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(i=e.relayProtocol)!=null?i:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,i=[],n=!1,r=void 0,s=void 0){var o,c,d,l,p,g,y,T,b,N,M,F,H;const K=e,I=new Zp,re=i.length?new Set(i):void 0,ae=[],De=[],Oe=[],ft=new Map,Yt=new Map;for(const A of K.values()){if(re){if(re.size===0)break;if(re.has(A.type))n&&re.delete(A.type);else continue}switch(A.type){case"local-candidate":{ae.push(this.getIceCandidateStats(A));break}case"remote-candidate":{De.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:k}=A,{selected:_}=A,W=A,Ie={nominated:k!=null?k:_,currentRoundTripTime:W.currentRoundTripTime,totalRoundTripTime:W.totalRoundTripTime,bytesReceived:W.bytesReceived,bytesSent:W.bytesSent,availableOutgoingBitrate:W.availableOutgoingBitrate,availableIncomingBitrate:W.availableIncomingBitrate,lastPacketReceivedTimestamp:W.lastPacketReceivedTimestamp,lastPacketSentTimestamp:W.lastPacketSentTimestamp,localCandidateId:W.localCandidateId,remoteCandidateId:W.remoteCandidateId,bytesDiscardedOnSend:W.bytesDiscardedOnSend,packetsSent:W.packetsSent,packetsReceived:W.packetsReceived,packetsDiscardedOnSend:W.packetsDiscardedOnSend};Oe.push(Ie),(A.nominated===!0||A.selected===!0)&&(I.candidatePair=Ie);break}case"transport":{const k=A;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 _={bytesReceived:k.bytesReceived,bytesSent:k.bytesSent,packetsSent:k.packetsSent,packetsReceived:k.packetsReceived,dtlsCipher:k.dtlsCipher,dtlsState:k.dtlsState,iceRole:k.iceRole};if(I.transport=_,s){if(s.producing){const W=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,W,_)}if(s.consuming){const W=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,W,_)}}break}case"remote-inbound-rtp":{const k=A,_={jitter:k.jitter,fractionLost:k.fractionLost,roundTripTime:k.roundTripTime,roundTripTimeMeasurements:k.roundTripTimeMeasurements,totalRoundTripTime:k.totalRoundTripTime,packetsLost:k.packetsLost};I.remoteInboundRtp.set(k.localId,_);break}case"outbound-rtp":{const k=A,_=r||this.outboundProducerMap.get(A.id),W=this.pausedProducerMap.get(_);if(W){if(W.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Ie=this.overallProducersStatsMap[_];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.outboundProducerMap.has(A.id)){I.staleProducerStreamMap=!0;break}const Ye=this.callStatsInstance.producers.get(_);if(((o=Ye==null?void 0:Ye.track)==null?void 0:o.readyState)==="ended")break;I.producerStreamMap.has(_)||I.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const U={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 C=k,Qe=x({frameHeight:C.frameHeight,frameWidth:C.frameWidth,framesEncoded:C.framesEncoded,framesDropped:C.framesDropped?C.framesDropped:C.droppedFrames,framesPerSecond:C.framesPerSecond?C.framesPerSecond:C.framerateMean,framesSent:C.framesSent,keyFramesEncoded:C.keyFramesEncoded,firCount:C.firCount,encoderImplementation:C.encoderImplementation,hugeFramesSent:C.hugeFramesSent,pliCount:C.pliCount,qpSum:C.qpSum,qualityLimitationReason:C.qualityLimitationReason,qualityLimitationDurations:C.qualityLimitationDurations,qualityLimitationResolutionChanges:C.qualityLimitationResolutionChanges,totalEncodeTime:C.totalEncodeTime,totalPacketSendDelay:C.totalEncodeTime,retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent,scalabilityMode:C.scalabilityMode,powerEfficientEncoder:C.powerEfficientEncoder},U);I.outboundVideoRtp.set(A.id,Qe),I.producerStreamMap.get(_).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(_,Ie,Qe)}else if(k.mediaType==="audio"||k.kind==="audio"){const C=k,Qe=x({retransmittedBytesSent:C.retransmittedBytesSent,retransmittedPacketsSent:C.retransmittedPacketsSent},U);I.outboundAudioRtp.set(A.id,Qe),I.producerStreamMap.get(_).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(_,Ie,Qe)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}case"inbound-rtp":{const k=A,_=r||this.inboundConsumerMap.get(A.id),W=this.pausedConsumerMap.get(_);if(W){if(W.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(k.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Ie=this.overallConsumersStatsMap[_];if(["video","audio"].includes(k.mediaType)||["video","audio"].includes(k.kind)){if(!this.inboundConsumerMap.has(A.id)){I.staleConsumerStreamMap=!0;break}I.consumerStreamMap.has(_)||I.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ye={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 U=k,C=x({frameHeight:U.frameHeight,frameWidth:U.frameWidth,framesDecoded:U.framesDecoded,framesDropped:U.framesDropped?U.framesDropped:U.droppedFrames,framesPerSecond:U.framesPerSecond?U.framesPerSecond:U.framerateMean,framesReceived:U.framesReceived,keyFramesDecoded:U.keyFramesDecoded,firCount:U.firCount,decoderImplementation:U.decoderImplementation,pliCount:U.pliCount,totalProcessingDelay:U.totalProcessingDelay,qpSum:U.qpSum||0,totalAssemblyTime:U.totalAssemblyTime||0,totalDecodeTime:U.totalDecodeTime||0,totalFreezesDuration:U.totalFreezesDuration||0,totalInterFrameDelay:U.totalInterFrameDelay||0,totalPausesDuration:U.totalPausesDuration||0,totalSquaredInterFrameDelay:U.totalSquaredInterFrameDelay||0,freezeCount:U.freezeCount||0,pauseCount:U.pauseCount||0,powerEfficientDecoder:U.powerEfficientDecoder},Ye);C.score=zp({frameWidth:C.frameWidth||0,framesDecoded:(C.framesDecoded||0)-(((c=this.videoConsumerToStatsMap.get(_))==null?void 0:c.framesDecoded)||0),framesPerSecond:C.framesPerSecond||0,packetsLost:(C.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(_))==null?void 0:d.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((l=this.videoConsumerToStatsMap.get(_))==null?void 0:l.packetsReceived)||0),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),Yt.set(_,{score:+(C.score*10).toFixed(),frameWidth:C.frameWidth||0,frameHeight:C.frameHeight||0,framesPerSecond:C.framesPerSecond||0,packetsLostPercentage:lc({packetsLost:(C.packetsLost||0)-(((p=this.videoConsumerToStatsMap.get(_))==null?void 0:p.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((g=this.videoConsumerToStatsMap.get(_))==null?void 0:g.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((C.bytesReceived||0)-(((y=this.videoConsumerToStatsMap.get(_))==null?void 0:y.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,C),I.inboundVideoRtp.set(A.id,C),I.consumerStreamMap.get(_).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(_,Ie,C)}else if(k.mediaType==="audio"||k.kind==="audio"){const U=k,C=x({audioLevel:U.audioLevel,concealedSamples:U.concealedSamples,concealmentEvents:U.concealmentEvents,totalAudioEnergy:U.totalAudioEnergy,totalSamplesDuration:U.totalSamplesDuration,totalSamplesReceived:U.totalSamplesReceived,fecPacketsDiscarded:U.fecPacketsDiscarded||0,fecPacketsReceived:U.fecPacketsReceived||0,insertedSamplesForDeceleration:U.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:U.removedSamplesForAcceleration||0,silentConcealedSamples:U.silentConcealedSamples||0,playoutId:U.playoutId},Ye);C.score=Kp({concealmentEvents:(C.concealmentEvents||0)-(((T=this.audioConsumerToStatsMap.get(_))==null?void 0:T.concealmentEvents)||0),packetsLost:(C.packetsLost||0)-(((b=this.audioConsumerToStatsMap.get(_))==null?void 0:b.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((N=this.audioConsumerToStatsMap.get(_))==null?void 0:N.packetsReceived)||0),jitter:C.jitter||0}),Yt.set(_,{score:+(C.score*10).toFixed(),packetsLostPercentage:lc({packetsLost:(C.packetsLost||0)-(((M=this.audioConsumerToStatsMap.get(_))==null?void 0:M.packetsLost)||0),packetsReceived:(C.packetsReceived||0)-(((F=this.audioConsumerToStatsMap.get(_))==null?void 0:F.packetsReceived)||0)}),jitter:C.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((C.bytesReceived||0)-(((H=this.audioConsumerToStatsMap.get(_))==null?void 0:H.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,C),I.inboundAudioRtp.set(A.id,C),I.consumerStreamMap.get(_).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(_,Ie,C)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${k.mediaType} kind: ${k.kind}`);break}}}if(I.producerStreamMap.forEach((A,k)=>{var _,W,Ie,Ye,U,C,Qe,on,Do,Oo,No,Lo,xo,Vo,Uo,Fo,Bo,Wo,jo,Ho,Go,qo,Jo;if(A.outboundVideoRtpId.length>0){const ye=[];A.outboundVideoRtpId.forEach(tp=>{ye.push(I.outboundVideoRtp.get(tp))});const oe=this.getWorkingSimulcastVideoStats(ye);oe.score=Jp({frameWidth:oe.frameWidth||0,framesPerSecond:oe.framesPerSecond||0,jitter:((_=oe.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsSent:(oe.packetsSent||0)-(((W=this.videoProducerToStatsMap.get(k))==null?void 0:W.packetsSent)||0),packetsLost:(((Ie=oe.remoteData)==null?void 0:Ie.packetsLost)||0)-(((U=(Ye=this.videoProducerToStatsMap.get(k))==null?void 0:Ye.remoteData)==null?void 0:U.packetsLost)||0),framesEncoded:(oe.framesEncoded||0)-(((C=this.videoProducerToStatsMap.get(k))==null?void 0:C.framesEncoded)||0)}),ft.set(k,{score:+(oe.score*10).toFixed(),frameWidth:oe.frameWidth||0,frameHeight:oe.frameHeight||0,framesPerSecond:oe.framesPerSecond||0,jitter:((Qe=oe.remoteData)==null?void 0:Qe.jitter)||0,isScreenShare:this.screenShareProducers.has(k),packetsLostPercentage:dc({packetsSent:(oe.packetsSent||0)-(((on=this.videoProducerToStatsMap.get(k))==null?void 0:on.packetsSent)||0),packetsLost:(((Do=oe.remoteData)==null?void 0:Do.packetsLost)||0)-(((No=(Oo=this.videoProducerToStatsMap.get(k))==null?void 0:Oo.remoteData)==null?void 0:No.packetsLost)||0)}),bitrate:((oe.bytesSent||0)-(((Lo=this.videoProducerToStatsMap.get(k))==null?void 0:Lo.bytesSent)||0))*8/7,cpuLimitations:oe.qualityLimitationReason==="cpu",bandwidthLimitations:oe.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(k,oe)}else if(A.outboundAudioRtpId.length>0){const ye=I.outboundAudioRtp.get(A.outboundAudioRtpId[0]);ye.score=qp({packetsSent:(ye.packetsSent||0)-(((xo=this.audioProducerToStatsMap.get(k))==null?void 0:xo.packetsSent)||0),packetsLost:(((Vo=ye.remoteData)==null?void 0:Vo.packetsLost)||0)-(((Fo=(Uo=this.audioProducerToStatsMap.get(k))==null?void 0:Uo.remoteData)==null?void 0:Fo.packetsLost)||0),jitter:((Bo=ye.remoteData)==null?void 0:Bo.jitter)||0}),ft.set(k,{score:+(ye.score*10).toFixed(),bitrate:((ye.bytesSent||0)-(((Wo=this.audioProducerToStatsMap.get(k))==null?void 0:Wo.bytesSent)||0))*8/7,packetsLostPercentage:dc({packetsSent:(ye.packetsSent||0)-(((jo=this.audioProducerToStatsMap.get(k))==null?void 0:jo.packetsSent)||0),packetsLost:(((Ho=ye.remoteData)==null?void 0:Ho.packetsLost)||0)-(((qo=(Go=this.audioProducerToStatsMap.get(k))==null?void 0:Go.remoteData)==null?void 0:qo.packetsLost)||0)}),jitter:((Jo=ye.remoteData)==null?void 0:Jo.jitter)||0,isScreenShare:this.screenShareProducers.has(k)}),this.audioProducerToStatsMap.set(k,ye)}}),Oe.forEach(A=>{const k=ae.find(W=>W.id===A.localCandidateId?(A.localCandidateId=W.id,W):null),_=De.find(W=>W.id===A.remoteCandidateId?(A.remoteCandidateId=W.id,W):null);k&&(A.localCandidateType=k.type,A.localCandidateAddress=dn(k.address),A.localCandidatePort=k.port,A.localCandidateProtocol=k.protocol,A.localCandidateUrl=k.url,A.localCandidateNetworkType=k.networkType,A.localCandidateRelatedAddress=dn(k.relatedAddress),A.localCandidateRelatedPort=k.relatedPort),_&&(A.remoteCandidateType=_.type,A.remoteCandidateAddress=dn(_.address),A.remoteCandidatePort=_.port,A.remoteCandidateProtocol=_.protocol,A.remoteCandidateUrl=_.url)}),I.candidatePair&&(I.transport?(I.transport.bytesReceived=I.candidatePair.bytesReceived,I.transport.bytesSent=I.candidatePair.bytesSent,I.transport.totalRoundTripTime=I.candidatePair.totalRoundTripTime,I.transport.availableOutgoingBitrate=I.candidatePair.availableOutgoingBitrate,I.transport.availableIncomingBitrate=I.candidatePair.availableIncomingBitrate,I.transport.roundTripTime=I.candidatePair.currentRoundTripTime):I.transport={bytesReceived:I.candidatePair.bytesReceived,bytesSent:I.candidatePair.bytesSent,totalRoundTripTime:I.candidatePair.totalRoundTripTime,availableOutgoingBitrate:I.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:I.candidatePair.availableIncomingBitrate,roundTripTime:I.candidatePair.currentRoundTripTime}),I.transport&&(I.transport.candidatePairs=Oe),I.transport&&!I.transport.roundTripTime){let A=0,k=0;I.remoteInboundRtp.forEach((_,W)=>{_.roundTripTime&&_.roundTripTime>A&&(A=_.roundTripTime,k=_.totalRoundTripTime)}),I.transport.roundTripTime=A,I.transport.totalRoundTripTime=k}if(Yt.size>0)try{this.observer.emit("consumer_score",Yt)}catch(A){}if(ft.size>0)try{this.observer.emit("producer_score",ft)}catch(A){}return I}getProducerStatsFromReport(e){const i=[];try{e.producerStreamMap.forEach((n,r)=>{const s=this.producerMap.get(r),o=s.track.getSettings(),c=n.outboundVideoRtpId.map(l=>{const p=e.outboundVideoRtp.get(l);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),d={producerId:r,appData:s.appData,videoStats:c,audioStats:n.outboundAudioRtpId.map(l=>e.outboundAudioRtp.get(l))};i.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return i}getConsumerStatsFromParsedConsumerStats(e,i,n){let r;try{const{peerId:s,producerId:o,appData:c}=this.consumerPeerIdMap.get(n),d=i==null?void 0:i.inboundVideoRtpId.map(l=>{const p=this.consumerMap.get(n).track.getSettings(),g=e.inboundVideoRtp.get(l);return g.frameHeight||(g.frameHeight=p.height,g.frameWidth=p.width,g.framesPerSecond=p.frameRate),g});r={consumerId:n,peerId:s,producerId:o,appData:c,videoStats:d,audioStats:i==null?void 0:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return r}getConsumerStatsFromReport(e){const i=[];try{e.consumerStreamMap.forEach((n,r)=>{i.push(this.getConsumerStatsFromParsedConsumerStats(e,n,r))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return i}}class xS extends tm{}function mc(t,e,i,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof i=="function"&&n instanceof e)i.call(null,n,t);else throw n}function im(t,e,i){const n=t.value;return t.value=function(...r){try{const s=n.apply(this,r);return s&&s instanceof Promise?s.catch(o=>{mc(this,e,i,o)}):s}catch(s){mc(this,e,i,s)}return null},t}const ie=(t,e)=>(i,n,r)=>{const s=r.value;return r.value=function(...o){try{const c=s.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{mc(this,t,e,d)}):c}catch(c){mc(this,t,e,c)}return null},r},VS=(t,e)=>(i,n,r)=>{if(r)return im(r,t,e);for(const s of Reflect.ownKeys(i.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(i.prototype,s);o.value instanceof Function&&Object.defineProperty(i.prototype,s,im(o,t,e))}};var ee=globalThis&&globalThis.__decorate||function(t,e,i,n){var r=arguments.length,s=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,i,n);else for(var c=t.length-1;c>=0;c--)(o=t[c])&&(s=(r<3?o(s):r>3?o(e,i,s):o(e,i))||s);return r>3&&s&&Object.defineProperty(e,i,s),s};const te=console;let X=class extends lt{constructor(t="https://api.testingv3.dyte.in",e="Blink",i=js.PROD,n,r,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=i,this.apiHostnames=o,this.logger=r,this.peerId=s,this.eventHandler=new TS({logger:r,peerId:s,apiHostnames:o}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new LS;break;case"Gecko":this.measurements=new tm;break;case"WebKit":this.measurements=new xS;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 lt,this.measurements.observer.on("consumer_score",c=>{r.debug(`callStats::consumer_score ${[...c.entries()]}`),this.eventHandler.emit("consumer_score",c)}),this.measurements.observer.on("producer_score",c=>{r.debug(`callStats::producer_score ${[...c.entries()]}`),this.eventHandler.emit("producer_score",c)})}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.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.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const i=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(i,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(i=>{this.registerProducer(i)}),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(i=>{this.registerConsumer(i)}),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:V.PRECALL_TEST_BEGIN,timestamp:e}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:V.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:e})})}sendScreenShareToggleEvent(t,e=null,i){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?V.SCREENSHARE_STARTED:V.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:i})}sendScreenShareRequestedEvent(t){this.eventHandler.callEvent({event:V.SCREENSHARE_START_REQUESTED,timestamp:t})}sendActiveSpeakerEvent(t,e){this.eventHandler.callEvent({event:V.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:e})}devices(t,e,i){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_DEVICES_UPDATES||t===Qt.VIDEO&&V.VIDEO_DEVICES_UPDATES||t===Qt.SPEAKER&&V.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:i})}selectedDevice(t,e,i){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.SELECTED_MICROHPONE_UPDATE||t===Qt.VIDEO&&V.SELECTED_CAMERA_UPDATE||t===Qt.SPEAKER&&V.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:i})}mediaPermission(t,e,i){this.eventHandler.callEvent({event:V.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:i})}mediaPlaybackFailed(t,e){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_PLAY_FAILED||t===Qt.VIDEO&&V.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:e})}mediaTrackMuted(t,e){this.eventHandler.callEvent({event:t===Qt.AUDIO&&V.AUDIO_TRACK_MUTED||t===Qt.VIDEO&&V.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:e})}tabChanged(t,e){this.eventHandler.callEvent({event:V.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:e})}browserBackgrounded(t){this.eventHandler.callEvent({event:V.BROWSER_BACKGROUNDED,timestamp:t})}browserForegrounded(t){this.eventHandler.callEvent({event:V.BROWSER_FOREGROUNDED,timestamp:t})}legacySwitch(t,e){this.eventHandler.callEvent({event:V.LEGACY_SWITCH,metadata:{on:t},timestamp:e})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t,e){t=q(x({},t),{meetingEnv:this.env}),t.deviceInfo=q(x({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:V.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:e})}sendNetworkQualityTestBeginEvent(t,e){this.eventHandler.callEvent({event:V.NET_QUALITY_TEST_BEGIN,timestamp:e}),new Promise((i,n)=>u(this,null,function*(){const r=[];try{for(const s of t)try{if(s.iceServers&&s.iceServers.length>0){const o=yield this.measurements.getNetworkQuality(s.iceServers);r.push(q(x({},s),{networkResults:o}))}}catch(o){console.warn("Error handling ",o)}i({regionData:r})}catch(s){console.warn("Error in callstats, ",s),n(s)}})).then(i=>{this.eventHandler.callEvent({event:V.NET_QUALITY_TEST_END,timestamp:e,metaData:i})})}sendWebSocketConnectedEvent(t){this.eventHandler.callEvent({event:V.WEBSOCKET_CONNECTED,timestamp:t})}sendTransportConnectedEvent(t){this.eventHandler.callEvent({event:V.TRANSPORT_CONNECTED,timestamp:t})}sendAudioToggleEvent(t,e){this.currentUserMediaStates.audio=t;let i;t?i=V.AUDIO_ON:i=V.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:e})}sendVideoToggleEvent(t,e){this.currentUserMediaStates.video=t;let i;t?i=V.VIDEO_ON:i=V.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:e})}sendParticipantRoleToggleEvent(t,e){this.eventHandler.callEvent({event:V.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 i,n;if(this.producingTransport&&(i=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!(i!=null&&i.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const s=yield this.measurements.getProducersReport([...this.producers.values()]);i&&s?i.producerReport=s:(i=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.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 r={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(t&&r.producerStats.length===0&&r.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:V.PING_STAT,metaData:r,timestamp:e})})}sendIVSPlayerRebufferEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_REBUFFERING,timestamp:t})}sendIVSPlayerAudioBlockEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_AUDIO_BLOCKED,timestamp:t})}sendIVSPlayerPlaybackBlockedEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:t})}sendIVSPlayerNetworkUnavailableEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:t})}sendIVSPlayerInitializedEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_INITIALIZED,timestamp:t})}sendIVSPlayerWorkerErrorEvent(t){this.eventHandler.callEvent({event:V.IVS_PLAYER_WORKER_ERROR,timestamp:t})}sendIVSPlayerErrorEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_ERROR,timestamp:e,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:e,metaData:t})}sendIVSPlayerAnalyticsEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_ANALYTICS_EVENT,timestamp:e,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:e,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t,e){this.eventHandler.callEvent({event:V.IVS_PLAYER_QUALITY_CHANGED,timestamp:e,metaData:t})}sendPlayerLiveLatency(t,e){this.eventHandler.callEvent({event:V.LIVESTREAM_LATENCY,timestamp:e,metaData:{latency:t}})}sendDisconnectEvent(t){this.eventHandler.callEvent({event:V.DISCONNECT,timestamp:t})}sendReconnectEvent(t){this.eventHandler.callEvent({event:V.RECONNECT_ATTEMPT,timestamp:t})}expectedVideoResolution(t,e,i){this.eventHandler.callEvent({event:V.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:t,frameHeight:e}})}expectedScreenshareResolution(t,e,i){this.eventHandler.callEvent({event:V.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:t,frameHeight:e}})}};ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"registerIceServers",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"registerConsumer",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"registerProducer",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendConsumerSharedMediaStateEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"registerProducingTransport",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"registerConsumingTransport",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"deRegisterConsumer",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"deRegisterProducer",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"disconnectConsumingTransport",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"disconnectProducingTransport",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendPreCallTestBeginEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendScreenShareToggleEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendScreenShareRequestedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendActiveSpeakerEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"devices",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"selectedDevice",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"mediaPermission",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"mediaPlaybackFailed",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"mediaTrackMuted",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"tabChanged",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"browserBackgrounded",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"browserForegrounded",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"legacySwitch",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"getPreCallTestResults",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendCallJoinBeginEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendNetworkQualityTestBeginEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendWebSocketConnectedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendTransportConnectedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendAudioToggleEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendVideoToggleEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendParticipantRoleToggleEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"startPingStats",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"stopPingStats",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendPingStatsEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerRebufferEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerAudioBlockEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerInitializedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerWorkerErrorEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerErrorEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerRecoverableErrorEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerAnalyticsEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendIVSPlayerQualityChanged",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendPlayerLiveLatency",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendDisconnectEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"sendReconnectEvent",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"expectedVideoResolution",null),ee([ie(TypeError,(t,e)=>te.error(e,t))],X.prototype,"expectedScreenshareResolution",null),X=ee([VS(TypeError,(t,e)=>te.error(e,t))],X);const US=X;class FS extends lt{constructor(){super(...arguments),m(this,"stats"),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:i,engineName:n,env:r=js.PROD,iceServers:s,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:p=!1}){var g,y,T;try{this.peerId=i,this.logger=d,this.ipInformation=yield Cl.getIPDetails({peerId:i,apiHostnames:l,logger:d}),this.backend=new US(o,n,r,c,d,i,l),this.iceServers=s,(g=this.backend)==null||g.registerIceServers(this.iceServers),this.initialized=!0,(T=(y=this.backend)==null?void 0:y.eventHandler)==null||T.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(b){this.logger.error("callStats::CallStatsIntegration: ",{error:b}),this.stallCallStats()}})}configureSendTransport(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.registerConsumingTransport(e)})}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){const i=new Date;this.onSafeInitialization(()=>{var n;try{(n=this.backend)==null||n.sendNetworkQualityTestBeginEvent(e,i)}catch(r){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:r.reason}})}})})}roomJoined(e){return u(this,null,function*(){const i=new Date;this.onSafeInitialization(()=>{var n,r;(n=this.backend)==null||n.sendCallJoinBeginEvent(e,i),this.backend,(r=this.backend)==null||r.startPingStats()})})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.stopPingStats(),(n=this.backend)==null||n.sendDisconnectEvent(e)})}screenShareStart(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!0,e,i)})}consumerSharedMediaState(e,i){this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,i)})}screenShareStop(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendScreenShareToggleEvent(!1,e,i)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendActiveSpeakerEvent(e,i)})}devices(e,i){const n=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.devices(e,i,n)})}selectedDevice(e,i){const n=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.selectedDevice(e,i,n)})}mediaPermission(e,i){const n=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.mediaPermission(e,i,n)})}mediaPlaybackFailed(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPlaybackFailed(e,i)})}mediaTrackMuted(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaTrackMuted(e,i)})}tabChanged(e=!1){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.tabChanged(e,i)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.browserForegrounded(e)})}legacySwitch(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.legacySwitch(e,i)})}startPreCallTest(e=!1){return u(this,null,function*(){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPreCallTestBeginEvent(e,i)})})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const i=n=>{e(n,!0)};return this.once("initialized",i),i}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,i){const n=new Date;this.onSafeInitialization(()=>{var r,s,o,c,d,l,p,g,y,T,b;switch(e){case"PlayerRebuffering":(r=this.backend)==null||r.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":(c=this.backend)==null||c.sendIVSPlayerNetworkUnavailableEvent(n);break;case"PlayerInitialized":(d=this.backend)==null||d.sendIVSPlayerInitializedEvent(n);break;case"PlayerWorkerError":(l=this.backend)==null||l.sendIVSPlayerWorkerErrorEvent(n);break;case"PlayerError":(p=this.backend)==null||p.sendIVSPlayerErrorEvent(i,n);break;case"PlayerRecoverableError":(g=this.backend)==null||g.sendIVSPlayerRecoverableErrorEvent(i,n);break;case"PlayerAnalyticsEvent":(y=this.backend)==null||y.sendIVSPlayerAnalyticsEvent(i,n);break;case"PlayerPlaybackRateChanged":(T=this.backend)==null||T.sendIVSPlayerPlaybackRateChangedEvent(i,n);break;case"PlayerQualityChanged":(b=this.backend)==null||b.sendIVSPlayerQualityChanged(i,n);break}})}livestreamLatency(e){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.sendPlayerLiveLatency(e,i)})}expectedVideoResolution(e,i){const n=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.expectedVideoResolution(e,i,n)})}expectedScreenshareResolution(e,i){const n=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.expectedScreenshareResolution(e,i,n)})}}const J=new FS;J.setMaxListeners(30);function BS(t){const{length:e}=this,i=t>=0?t:e+t;return i<0||i>=e?void 0:this[i]}Array.prototype.at||Object.assign(Array.prototype,{at:BS});function WS(t){const{length:e}=this,i=t>=0?t:e+t;return i<0||i>=e?void 0:this[i]}String.prototype.at||Object.assign(String.prototype,{at:WS});function jS(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var nm={exports:{}},Be=nm.exports={},Ii,Ci;function Pl(){throw new Error("setTimeout has not been defined")}function Rl(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Ii=setTimeout:Ii=Pl}catch(t){Ii=Pl}try{typeof clearTimeout=="function"?Ci=clearTimeout:Ci=Rl}catch(t){Ci=Rl}})();function rm(t){if(Ii===setTimeout)return setTimeout(t,0);if((Ii===Pl||!Ii)&&setTimeout)return Ii=setTimeout,setTimeout(t,0);try{return Ii(t,0)}catch(e){try{return Ii.call(null,t,0)}catch(i){return Ii.call(this,t,0)}}}function HS(t){if(Ci===clearTimeout)return clearTimeout(t);if((Ci===Rl||!Ci)&&clearTimeout)return Ci=clearTimeout,clearTimeout(t);try{return Ci(t)}catch(e){try{return Ci.call(null,t)}catch(i){return Ci.call(this,t)}}}var ji=[],Hr=!1,Jn,gc=-1;function GS(){!Hr||!Jn||(Hr=!1,Jn.length?ji=Jn.concat(ji):gc=-1,ji.length&&sm())}function sm(){if(!Hr){var t=rm(GS);Hr=!0;for(var e=ji.length;e;){for(Jn=ji,ji=[];++gc<e;)Jn&&Jn[gc].run();gc=-1,e=ji.length}Jn=null,Hr=!1,HS(t)}}Be.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)e[i-1]=arguments[i];ji.push(new am(t,e)),ji.length===1&&!Hr&&rm(sm)};function am(t,e){this.fun=t,this.array=e}am.prototype.run=function(){this.fun.apply(null,this.array)},Be.title="browser",Be.browser=!0,Be.env={},Be.argv=[],Be.version="",Be.versions={};function Hi(){}Be.on=Hi,Be.addListener=Hi,Be.once=Hi,Be.off=Hi,Be.removeListener=Hi,Be.removeAllListeners=Hi,Be.emit=Hi,Be.prependListener=Hi,Be.prependOnceListener=Hi,Be.listeners=function(t){return[]},Be.binding=function(t){throw new Error("process.binding is not supported")},Be.cwd=function(){return"/"},Be.chdir=function(t){throw new Error("process.chdir is not supported")},Be.umask=function(){return 0};var qS=nm.exports;const Hs=jS(qS);function JS(){this.__data__=[],this.size=0}function Gs(t,e){return t===e||t!==t&&e!==e}function fc(t,e){for(var i=t.length;i--;)if(Gs(t[i][0],e))return i;return-1}var $S=Array.prototype,KS=$S.splice;function zS(t){var e=this.__data__,i=fc(e,t);if(i<0)return!1;var n=e.length-1;return i==n?e.pop():KS.call(e,i,1),--this.size,!0}function YS(t){var e=this.__data__,i=fc(e,t);return i<0?void 0:e[i][1]}function QS(t){return fc(this.__data__,t)>-1}function XS(t,e){var i=this.__data__,n=fc(i,t);return n<0?(++this.size,i.push([t,e])):i[n][1]=e,this}function Gi(t){var e=-1,i=t==null?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}Gi.prototype.clear=JS,Gi.prototype.delete=zS,Gi.prototype.get=YS,Gi.prototype.has=QS,Gi.prototype.set=XS;function ZS(){this.__data__=new Gi,this.size=0}function eE(t){var e=this.__data__,i=e.delete(t);return this.size=e.size,i}function tE(t){return this.__data__.get(t)}function iE(t){return this.__data__.has(t)}const vc=globalThis||void 0||self;var nE=typeof vc=="object"&&vc&&vc.Object===Object&&vc;const om=nE;var rE=typeof self=="object"&&self&&self.Object===Object&&self,sE=om||rE||Function("return this")();const si=sE;var aE=si.Symbol;const ln=aE;var cm=Object.prototype,oE=cm.hasOwnProperty,cE=cm.toString,qs=ln?ln.toStringTag:void 0;function dE(t){var e=oE.call(t,qs),i=t[qs];try{t[qs]=void 0;var n=!0}catch(s){}var r=cE.call(t);return n&&(e?t[qs]=i:delete t[qs]),r}var lE=Object.prototype,uE=lE.toString;function hE(t){return uE.call(t)}var pE="[object Null]",mE="[object Undefined]",dm=ln?ln.toStringTag:void 0;function $n(t){return t==null?t===void 0?mE:pE:dm&&dm in Object(t)?dE(t):hE(t)}function ai(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var gE="[object AsyncFunction]",fE="[object Function]",vE="[object GeneratorFunction]",yE="[object Proxy]";function Ml(t){if(!ai(t))return!1;var e=$n(t);return e==fE||e==vE||e==gE||e==yE}var SE=si["__core-js_shared__"];const Al=SE;var lm=function(){var t=/[^.]+$/.exec(Al&&Al.keys&&Al.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function EE(t){return!!lm&&lm in t}var TE=Function.prototype,kE=TE.toString;function Kn(t){if(t!=null){try{return kE.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var bE=/[\\^$.*+?()[\]{}|]/g,_E=/^\[object .+?Constructor\]$/,wE=Function.prototype,IE=Object.prototype,CE=wE.toString,PE=IE.hasOwnProperty,RE=RegExp("^"+CE.call(PE).replace(bE,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ME(t){if(!ai(t)||EE(t))return!1;var e=Ml(t)?RE:_E;return e.test(Kn(t))}function AE(t,e){return t==null?void 0:t[e]}function zn(t,e){var i=AE(t,e);return ME(i)?i:void 0}var DE=zn(si,"Map");const Js=DE;var OE=zn(Object,"create");const $s=OE;function NE(){this.__data__=$s?$s(null):{},this.size=0}function LE(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var xE="__lodash_hash_undefined__",VE=Object.prototype,UE=VE.hasOwnProperty;function FE(t){var e=this.__data__;if($s){var i=e[t];return i===xE?void 0:i}return UE.call(e,t)?e[t]:void 0}var BE=Object.prototype,WE=BE.hasOwnProperty;function jE(t){var e=this.__data__;return $s?e[t]!==void 0:WE.call(e,t)}var HE="__lodash_hash_undefined__";function GE(t,e){var i=this.__data__;return this.size+=this.has(t)?0:1,i[t]=$s&&e===void 0?HE:e,this}function Yn(t){var e=-1,i=t==null?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}Yn.prototype.clear=NE,Yn.prototype.delete=LE,Yn.prototype.get=FE,Yn.prototype.has=jE,Yn.prototype.set=GE;function qE(){this.size=0,this.__data__={hash:new Yn,map:new(Js||Gi),string:new Yn}}function JE(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function yc(t,e){var i=t.__data__;return JE(e)?i[typeof e=="string"?"string":"hash"]:i.map}function $E(t){var e=yc(this,t).delete(t);return this.size-=e?1:0,e}function KE(t){return yc(this,t).get(t)}function zE(t){return yc(this,t).has(t)}function YE(t,e){var i=yc(this,t),n=i.size;return i.set(t,e),this.size+=i.size==n?0:1,this}function Qn(t){var e=-1,i=t==null?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}Qn.prototype.clear=qE,Qn.prototype.delete=$E,Qn.prototype.get=KE,Qn.prototype.has=zE,Qn.prototype.set=YE;var QE=200;function XE(t,e){var i=this.__data__;if(i instanceof Gi){var n=i.__data__;if(!Js||n.length<QE-1)return n.push([t,e]),this.size=++i.size,this;i=this.__data__=new Qn(n)}return i.set(t,e),this.size=i.size,this}function Pi(t){var e=this.__data__=new Gi(t);this.size=e.size}Pi.prototype.clear=ZS,Pi.prototype.delete=eE,Pi.prototype.get=tE,Pi.prototype.has=iE,Pi.prototype.set=XE;function ZE(t,e){for(var i=-1,n=t==null?0:t.length;++i<n&&e(t[i],i,t)!==!1;);return t}var eT=function(){try{var t=zn(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const Sc=eT;function Dl(t,e,i){e=="__proto__"&&Sc?Sc(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}var tT=Object.prototype,iT=tT.hasOwnProperty;function um(t,e,i){var n=t[e];(!(iT.call(t,e)&&Gs(n,i))||i===void 0&&!(e in t))&&Dl(t,e,i)}function Ks(t,e,i,n){var r=!i;i||(i={});for(var s=-1,o=e.length;++s<o;){var c=e[s],d=n?n(i[c],t[c],c,i,t):void 0;d===void 0&&(d=t[c]),r?Dl(i,c,d):um(i,c,d)}return i}function nT(t,e){for(var i=-1,n=Array(t);++i<t;)n[i]=e(i);return n}function Ri(t){return t!=null&&typeof t=="object"}var rT="[object Arguments]";function hm(t){return Ri(t)&&$n(t)==rT}var pm=Object.prototype,sT=pm.hasOwnProperty,aT=pm.propertyIsEnumerable,oT=hm(function(){return arguments}())?hm:function(t){return Ri(t)&&sT.call(t,"callee")&&!aT.call(t,"callee")};const Ec=oT;var cT=Array.isArray;const un=cT;function dT(){return!1}var mm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gm=mm&&typeof module=="object"&&module&&!module.nodeType&&module,lT=gm&&gm.exports===mm,fm=lT?si.Buffer:void 0,uT=fm?fm.isBuffer:void 0,hT=uT||dT;const Gr=hT;var pT=9007199254740991,mT=/^(?:0|[1-9]\d*)$/;function vm(t,e){var i=typeof t;return e=e==null?pT:e,!!e&&(i=="number"||i!="symbol"&&mT.test(t))&&t>-1&&t%1==0&&t<e}var gT=9007199254740991;function ym(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=gT}var fT="[object Arguments]",vT="[object Array]",yT="[object Boolean]",ST="[object Date]",ET="[object Error]",TT="[object Function]",kT="[object Map]",bT="[object Number]",_T="[object Object]",wT="[object RegExp]",IT="[object Set]",CT="[object String]",PT="[object WeakMap]",RT="[object ArrayBuffer]",MT="[object DataView]",AT="[object Float32Array]",DT="[object Float64Array]",OT="[object Int8Array]",NT="[object Int16Array]",LT="[object Int32Array]",xT="[object Uint8Array]",VT="[object Uint8ClampedArray]",UT="[object Uint16Array]",FT="[object Uint32Array]",be={};be[AT]=be[DT]=be[OT]=be[NT]=be[LT]=be[xT]=be[VT]=be[UT]=be[FT]=!0,be[fT]=be[vT]=be[RT]=be[yT]=be[MT]=be[ST]=be[ET]=be[TT]=be[kT]=be[bT]=be[_T]=be[wT]=be[IT]=be[CT]=be[PT]=!1;function BT(t){return Ri(t)&&ym(t.length)&&!!be[$n(t)]}function Ol(t){return function(e){return t(e)}}var Sm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,zs=Sm&&typeof module=="object"&&module&&!module.nodeType&&module,WT=zs&&zs.exports===Sm,Nl=WT&&om.process,jT=function(){try{var t=zs&&zs.require&&zs.require("util").types;return t||Nl&&Nl.binding&&Nl.binding("util")}catch(e){}}();const qr=jT;var Em=qr&&qr.isTypedArray,HT=Em?Ol(Em):BT;const Tc=HT;var GT=Object.prototype,qT=GT.hasOwnProperty;function Tm(t,e){var i=un(t),n=!i&&Ec(t),r=!i&&!n&&Gr(t),s=!i&&!n&&!r&&Tc(t),o=i||n||r||s,c=o?nT(t.length,String):[],d=c.length;for(var l in t)(e||qT.call(t,l))&&!(o&&(l=="length"||r&&(l=="offset"||l=="parent")||s&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||vm(l,d)))&&c.push(l);return c}var JT=Object.prototype;function kc(t){var e=t&&t.constructor,i=typeof e=="function"&&e.prototype||JT;return t===i}function km(t,e){return function(i){return t(e(i))}}var $T=km(Object.keys,Object);const KT=$T;var zT=Object.prototype,YT=zT.hasOwnProperty;function bm(t){if(!kc(t))return KT(t);var e=[];for(var i in Object(t))YT.call(t,i)&&i!="constructor"&&e.push(i);return e}function Ys(t){return t!=null&&ym(t.length)&&!Ml(t)}function Ll(t){return Ys(t)?Tm(t):bm(t)}function QT(t,e){return t&&Ks(e,Ll(e),t)}function XT(t){var e=[];if(t!=null)for(var i in Object(t))e.push(i);return e}var ZT=Object.prototype,ek=ZT.hasOwnProperty;function tk(t){if(!ai(t))return XT(t);var e=kc(t),i=[];for(var n in t)n=="constructor"&&(e||!ek.call(t,n))||i.push(n);return i}function Qs(t){return Ys(t)?Tm(t,!0):tk(t)}function ik(t,e){return t&&Ks(e,Qs(e),t)}var _m=typeof exports=="object"&&exports&&!exports.nodeType&&exports,wm=_m&&typeof module=="object"&&module&&!module.nodeType&&module,nk=wm&&wm.exports===_m,Im=nk?si.Buffer:void 0,Cm=Im?Im.allocUnsafe:void 0;function Pm(t,e){if(e)return t.slice();var i=t.length,n=Cm?Cm(i):new t.constructor(i);return t.copy(n),n}function Rm(t,e){var i=-1,n=t.length;for(e||(e=Array(n));++i<n;)e[i]=t[i];return e}function rk(t,e){for(var i=-1,n=t==null?0:t.length,r=0,s=[];++i<n;){var o=t[i];e(o,i,t)&&(s[r++]=o)}return s}function Mm(){return[]}var sk=Object.prototype,ak=sk.propertyIsEnumerable,Am=Object.getOwnPropertySymbols,ok=Am?function(t){return t==null?[]:(t=Object(t),rk(Am(t),function(e){return ak.call(t,e)}))}:Mm;const xl=ok;function ck(t,e){return Ks(t,xl(t),e)}function Dm(t,e){for(var i=-1,n=e.length,r=t.length;++i<n;)t[r+i]=e[i];return t}var dk=km(Object.getPrototypeOf,Object);const Vl=dk;var lk=Object.getOwnPropertySymbols,uk=lk?function(t){for(var e=[];t;)Dm(e,xl(t)),t=Vl(t);return e}:Mm;const Om=uk;function hk(t,e){return Ks(t,Om(t),e)}function Nm(t,e,i){var n=e(t);return un(t)?n:Dm(n,i(t))}function Ul(t){return Nm(t,Ll,xl)}function pk(t){return Nm(t,Qs,Om)}var mk=zn(si,"DataView");const Fl=mk;var gk=zn(si,"Promise");const Bl=gk;var fk=zn(si,"Set");const Wl=fk;var vk=zn(si,"WeakMap");const jl=vk;var Lm="[object Map]",yk="[object Object]",xm="[object Promise]",Vm="[object Set]",Um="[object WeakMap]",Fm="[object DataView]",Sk=Kn(Fl),Ek=Kn(Js),Tk=Kn(Bl),kk=Kn(Wl),bk=Kn(jl),Xn=$n;(Fl&&Xn(new Fl(new ArrayBuffer(1)))!=Fm||Js&&Xn(new Js)!=Lm||Bl&&Xn(Bl.resolve())!=xm||Wl&&Xn(new Wl)!=Vm||jl&&Xn(new jl)!=Um)&&(Xn=function(t){var e=$n(t),i=e==yk?t.constructor:void 0,n=i?Kn(i):"";if(n)switch(n){case Sk:return Fm;case Ek:return Lm;case Tk:return xm;case kk:return Vm;case bk:return Um}return e});const Jr=Xn;var _k=Object.prototype,wk=_k.hasOwnProperty;function Ik(t){var e=t.length,i=new t.constructor(e);return e&&typeof t[0]=="string"&&wk.call(t,"index")&&(i.index=t.index,i.input=t.input),i}var Ck=si.Uint8Array;const bc=Ck;function Hl(t){var e=new t.constructor(t.byteLength);return new bc(e).set(new bc(t)),e}function Pk(t,e){var i=e?Hl(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.byteLength)}var Rk=/\w*$/;function Mk(t){var e=new t.constructor(t.source,Rk.exec(t));return e.lastIndex=t.lastIndex,e}var Bm=ln?ln.prototype:void 0,Wm=Bm?Bm.valueOf:void 0;function Ak(t){return Wm?Object(Wm.call(t)):{}}function jm(t,e){var i=e?Hl(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.length)}var Dk="[object Boolean]",Ok="[object Date]",Nk="[object Map]",Lk="[object Number]",xk="[object RegExp]",Vk="[object Set]",Uk="[object String]",Fk="[object Symbol]",Bk="[object ArrayBuffer]",Wk="[object DataView]",jk="[object Float32Array]",Hk="[object Float64Array]",Gk="[object Int8Array]",qk="[object Int16Array]",Jk="[object Int32Array]",$k="[object Uint8Array]",Kk="[object Uint8ClampedArray]",zk="[object Uint16Array]",Yk="[object Uint32Array]";function Qk(t,e,i){var n=t.constructor;switch(e){case Bk:return Hl(t);case Dk:case Ok:return new n(+t);case Wk:return Pk(t,i);case jk:case Hk:case Gk:case qk:case Jk:case $k:case Kk:case zk:case Yk:return jm(t,i);case Nk:return new n;case Lk:case Uk:return new n(t);case xk:return Mk(t);case Vk:return new n;case Fk:return Ak(t)}}var Hm=Object.create,Xk=function(){function t(){}return function(e){if(!ai(e))return{};if(Hm)return Hm(e);t.prototype=e;var i=new t;return t.prototype=void 0,i}}();const Zk=Xk;function Gm(t){return typeof t.constructor=="function"&&!kc(t)?Zk(Vl(t)):{}}var e0="[object Map]";function t0(t){return Ri(t)&&Jr(t)==e0}var qm=qr&&qr.isMap,i0=qm?Ol(qm):t0;const n0=i0;var r0="[object Set]";function s0(t){return Ri(t)&&Jr(t)==r0}var Jm=qr&&qr.isSet,a0=Jm?Ol(Jm):s0;const o0=a0;var c0=1,d0=2,l0=4,$m="[object Arguments]",u0="[object Array]",h0="[object Boolean]",p0="[object Date]",m0="[object Error]",Km="[object Function]",g0="[object GeneratorFunction]",f0="[object Map]",v0="[object Number]",zm="[object Object]",y0="[object RegExp]",S0="[object Set]",E0="[object String]",T0="[object Symbol]",k0="[object WeakMap]",b0="[object ArrayBuffer]",_0="[object DataView]",w0="[object Float32Array]",I0="[object Float64Array]",C0="[object Int8Array]",P0="[object Int16Array]",R0="[object Int32Array]",M0="[object Uint8Array]",A0="[object Uint8ClampedArray]",D0="[object Uint16Array]",O0="[object Uint32Array]",Ee={};Ee[$m]=Ee[u0]=Ee[b0]=Ee[_0]=Ee[h0]=Ee[p0]=Ee[w0]=Ee[I0]=Ee[C0]=Ee[P0]=Ee[R0]=Ee[f0]=Ee[v0]=Ee[zm]=Ee[y0]=Ee[S0]=Ee[E0]=Ee[T0]=Ee[M0]=Ee[A0]=Ee[D0]=Ee[O0]=!0,Ee[m0]=Ee[Km]=Ee[k0]=!1;function _c(t,e,i,n,r,s){var o,c=e&c0,d=e&d0,l=e&l0;if(i&&(o=r?i(t,n,r,s):i(t)),o!==void 0)return o;if(!ai(t))return t;var p=un(t);if(p){if(o=Ik(t),!c)return Rm(t,o)}else{var g=Jr(t),y=g==Km||g==g0;if(Gr(t))return Pm(t,c);if(g==zm||g==$m||y&&!r){if(o=d||y?{}:Gm(t),!c)return d?hk(t,ik(o,t)):ck(t,QT(o,t))}else{if(!Ee[g])return r?t:{};o=Qk(t,g,c)}}s||(s=new Pi);var T=s.get(t);if(T)return T;s.set(t,o),o0(t)?t.forEach(function(M){o.add(_c(M,e,i,M,t,s))}):n0(t)&&t.forEach(function(M,F){o.set(F,_c(M,e,i,F,t,s))});var b=l?d?pk:Ul:d?Qs:Ll,N=p?void 0:b(t);return ZE(N||t,function(M,F){N&&(F=M,M=t[F]),um(o,F,_c(M,e,i,F,t,s))}),o}var N0=1,L0=4;function Gl(t){return _c(t,N0|L0)}var x0="[object Symbol]";function V0(t){return typeof t=="symbol"||Ri(t)&&$n(t)==x0}var U0=Object.defineProperty,F0=(t,e)=>{for(var i in e)U0(t,i,{get:e[i],enumerable:!0})},B0={};F0(B0,{permissions:()=>W0,theme:()=>j0});var yt=(t=>(t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT",t))(yt||{}),Y=(t=>(t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST",t))(Y||{}),W0={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},j0={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}},Ym="hXgU8Wc8pwuGNq9ms5q9Hh",Qm;typeof Hs!="undefined"&&(Qm=Hs==null?void 0:Hs.env)!=null&&Qm.FLAGSMITH_ENVIRONMENT_KEY&&(Ym=Hs.env.FLAGSMITH_ENVIRONMENT_KEY);function H0(t=[]){const e={};return t.forEach(i=>{e[i.feature.name]={enabled:i.enabled,value:i.feature_state_value}}),e}var G0=class{constructor(t=Ym){m(this,"flags",{}),m(this,"environmentKey",null),this.environmentKey=t}identifyAndFetchFlagsWithRetry(t){return u(this,arguments,function*({primaryEndpoint:e,secondaryEndpoint:i,forceEvaluate:n,timeout:r,uniqueIdentifier:s,traitsObj:o,logger:c}){const d=JSON.parse(JSON.stringify(o)),l=Object.entries(d).map(g=>({trait_key:g[0],trait_value:g[1]})),p=[e,i,i];for(const g of p)try{const y=new AbortController,T=setTimeout(()=>y.abort(),r),b="_"+(Math.random()+1).toString(36).substring(2),N=yield fetch(`https://${g}/api/v1/identities/`,{method:"POST",headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},body:JSON.stringify({identifier:s+(n?b:""),traits:l}),signal:y.signal});if(clearTimeout(T),!N.ok)throw new Error(`Request failed with status ${N.status}`);const M=yield N.json();return H0(M.flags||[])}catch(y){c.error("Flagsmith identify failed!!",{error:y,url:g})}return{}})}identify(t){return u(this,arguments,function*(e,i={},n=!1,r=5e3,s="edge.api.flagsmith.com",o=console){return this.flags=yield this.identifyAndFetchFlagsWithRetry({traitsObj:i,uniqueIdentifier:e,forceEvaluate:n,timeout:r,primaryEndpoint:s,secondaryEndpoint:"edge.api.flagsmith.com",logger:o}),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 G0,Xm=[-2,-1,0,1,2],q0=[0,1,2,3,4];function J0(t){t=t.trim();let e="0",i="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],i="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],i="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+i,+n]}var $0=(t,e,i)=>{let n,r,s;if(e==0)n=r=s=i;else{const o=(l,p,g)=>(g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?l+(p-l)*6*g:g<.5?p:g<.6666666666666666?l+(p-l)*(.6666666666666666-g)*6:l),c=i<.5?i*(1+e):i+e-i*e,d=2*i-c;n=o(d,c,t+1/3),r=o(d,c,t),s=o(d,c,t-1/3)}return[Math.round(n*255),Math.round(r*255),Math.round(s*255)]},K0=(t,e,i)=>{t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let s,o;const c=(n+r)/2;if(n==r)s=o=0;else{const d=n-r;switch(o=c>.5?d/(2-n-r):d/(n+r),n){case t:s=(e-i)/d+(e<i?6:0);break;case e:s=(i-t)/d+2;break;case i:s=(t-e)/d+4;break}s/=6}return[s,o,c]},z0=(t,e,i)=>{const n=r=>r.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(i)}`},Zm=(t,e=Xm,i=.4)=>{const n=[],[r,s,o]=J0(t),[c,d,l]=K0(r,s,o),p=Math.round(l*100);p>70?i=.8:p>60?i=.9:p<10?i=.075:p<42&&(i=.3);const g=e.findIndex(M=>M===0);if(g===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const y=5-g,T=g+1,b=(100-p)/y,N=p/T;for(const M of e){let F;M<0?F=p+M*N*i:M>0?F=p+M*b*i:F=p;const[H,K,I]=$0(c,d,F/100);n.push(z0(H,K,I))}return n},eg={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"}},Y0=t=>{const[e,i,n,r,s]=Zm(t,Xm);return{300:e,400:i,500:n,600:r,700:s}},Q0=t=>{if(t==="#FFFFFF")return eg.light.background;if(t==="#000000")return eg.dark.background;const[e,i,n,r,s]=Zm(t,q0);return{1e3:e,900:i,800:n,700:r,600:s}},X0={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:Y0("#2160FD"),background:Q0("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function tg(){return Gl(X0)}var Z0={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:tg(),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,track_recording:{subscriptions:[]}},version:"hybrid"};function eb(){return Gl(Z0)}var tb={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:tg(),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,track_recording:{subscriptions:[]}},version:"2.0.0"};function ql(){return Gl(tb)}var ib=/\s/;function nb(t){for(var e=t.length;e--&&ib.test(t.charAt(e)););return e}var rb=/^\s+/;function sb(t){return t&&t.slice(0,nb(t)+1).replace(rb,"")}var ig=0/0,ab=/^[-+]0x[0-9a-f]+$/i,ob=/^0b[01]+$/i,cb=/^0o[0-7]+$/i,db=parseInt;function ng(t){if(typeof t=="number")return t;if(V0(t))return ig;if(ai(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=ai(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=sb(t);var i=ob.test(t);return i||cb.test(t)?db(t.slice(2),i?2:8):ab.test(t)?ig:+t}function rg(t){return t}function lb(t,e,i){switch(i.length){case 0:return t.call(e);case 1:return t.call(e,i[0]);case 2:return t.call(e,i[0],i[1]);case 3:return t.call(e,i[0],i[1],i[2])}return t.apply(e,i)}var ub=800,hb=16,pb=Date.now;function mb(t){var e=0,i=0;return function(){var n=pb(),r=hb-(n-i);if(i=n,r>0){if(++e>=ub)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function gb(t){return function(){return t}}var fb=Sc?function(t,e){return Sc(t,"toString",{configurable:!0,enumerable:!1,value:gb(e),writable:!0})}:rg,vb=mb(fb);const yb=vb;var sg=Math.max;function Sb(t,e,i){return e=sg(e===void 0?t.length-1:e,0),function(){for(var n=arguments,r=-1,s=sg(n.length-e,0),o=Array(s);++r<s;)o[r]=n[e+r];r=-1;for(var c=Array(e+1);++r<e;)c[r]=n[r];return c[e]=i(o),lb(t,this,c)}}function Eb(t,e){return yb(Sb(t,e,rg),t+"")}function Tb(t,e,i){if(!ai(i))return!1;var n=typeof e;return(n=="number"?Ys(i)&&vm(e,i.length):n=="string"&&e in i)?Gs(i[e],t):!1}function kb(t){return Eb(function(e,i){var n=-1,r=i.length,s=r>1?i[r-1]:void 0,o=r>2?i[2]:void 0;for(s=t.length>3&&typeof s=="function"?(r--,s):void 0,o&&Tb(i[0],i[1],o)&&(s=r<3?void 0:s,r=1),e=Object(e);++n<r;){var c=i[n];c&&t(e,c,n,s)}return e})}var bb="[object Object]",_b=Function.prototype,wb=Object.prototype,ag=_b.toString,Ib=wb.hasOwnProperty,Cb=ag.call(Object);function Pb(t){if(!Ri(t)||$n(t)!=bb)return!1;var e=Vl(t);if(e===null)return!0;var i=Ib.call(e,"constructor")&&e.constructor;return typeof i=="function"&&i instanceof i&&ag.call(i)==Cb}var Rb="__lodash_hash_undefined__";function Mb(t){return this.__data__.set(t,Rb),this}function Ab(t){return this.__data__.has(t)}function wc(t){var e=-1,i=t==null?0:t.length;for(this.__data__=new Qn;++e<i;)this.add(t[e])}wc.prototype.add=wc.prototype.push=Mb,wc.prototype.has=Ab;function Db(t,e){for(var i=-1,n=t==null?0:t.length;++i<n;)if(e(t[i],i,t))return!0;return!1}function Ob(t,e){return t.has(e)}var Nb=1,Lb=2;function og(t,e,i,n,r,s){var o=i&Nb,c=t.length,d=e.length;if(c!=d&&!(o&&d>c))return!1;var l=s.get(t),p=s.get(e);if(l&&p)return l==e&&p==t;var g=-1,y=!0,T=i&Lb?new wc:void 0;for(s.set(t,e),s.set(e,t);++g<c;){var b=t[g],N=e[g];if(n)var M=o?n(N,b,g,e,t,s):n(b,N,g,t,e,s);if(M!==void 0){if(M)continue;y=!1;break}if(T){if(!Db(e,function(F,H){if(!Ob(T,H)&&(b===F||r(b,F,i,n,s)))return T.push(H)})){y=!1;break}}else if(!(b===N||r(b,N,i,n,s))){y=!1;break}}return s.delete(t),s.delete(e),y}function xb(t){var e=-1,i=Array(t.size);return t.forEach(function(n,r){i[++e]=[r,n]}),i}function Vb(t){var e=-1,i=Array(t.size);return t.forEach(function(n){i[++e]=n}),i}var Ub=1,Fb=2,Bb="[object Boolean]",Wb="[object Date]",jb="[object Error]",Hb="[object Map]",Gb="[object Number]",qb="[object RegExp]",Jb="[object Set]",$b="[object String]",Kb="[object Symbol]",zb="[object ArrayBuffer]",Yb="[object DataView]",cg=ln?ln.prototype:void 0,Jl=cg?cg.valueOf:void 0;function Qb(t,e,i,n,r,s,o){switch(i){case Yb:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case zb:return!(t.byteLength!=e.byteLength||!s(new bc(t),new bc(e)));case Bb:case Wb:case Gb:return Gs(+t,+e);case jb:return t.name==e.name&&t.message==e.message;case qb:case $b:return t==e+"";case Hb:var c=xb;case Jb:var d=n&Ub;if(c||(c=Vb),t.size!=e.size&&!d)return!1;var l=o.get(t);if(l)return l==e;n|=Fb,o.set(t,e);var p=og(c(t),c(e),n,r,s,o);return o.delete(t),p;case Kb:if(Jl)return Jl.call(t)==Jl.call(e)}return!1}var Xb=1,Zb=Object.prototype,e_=Zb.hasOwnProperty;function t_(t,e,i,n,r,s){var o=i&Xb,c=Ul(t),d=c.length,l=Ul(e),p=l.length;if(d!=p&&!o)return!1;for(var g=d;g--;){var y=c[g];if(!(o?y in e:e_.call(e,y)))return!1}var T=s.get(t),b=s.get(e);if(T&&b)return T==e&&b==t;var N=!0;s.set(t,e),s.set(e,t);for(var M=o;++g<d;){y=c[g];var F=t[y],H=e[y];if(n)var K=o?n(H,F,y,e,t,s):n(F,H,y,t,e,s);if(!(K===void 0?F===H||r(F,H,i,n,s):K)){N=!1;break}M||(M=y=="constructor")}if(N&&!M){var I=t.constructor,re=e.constructor;I!=re&&"constructor"in t&&"constructor"in e&&!(typeof I=="function"&&I instanceof I&&typeof re=="function"&&re instanceof re)&&(N=!1)}return s.delete(t),s.delete(e),N}var i_=1,dg="[object Arguments]",lg="[object Array]",Ic="[object Object]",n_=Object.prototype,ug=n_.hasOwnProperty;function r_(t,e,i,n,r,s){var o=un(t),c=un(e),d=o?lg:Jr(t),l=c?lg:Jr(e);d=d==dg?Ic:d,l=l==dg?Ic:l;var p=d==Ic,g=l==Ic,y=d==l;if(y&&Gr(t)){if(!Gr(e))return!1;o=!0,p=!1}if(y&&!p)return s||(s=new Pi),o||Tc(t)?og(t,e,i,n,r,s):Qb(t,e,d,i,n,r,s);if(!(i&i_)){var T=p&&ug.call(t,"__wrapped__"),b=g&&ug.call(e,"__wrapped__");if(T||b){var N=T?t.value():t,M=b?e.value():e;return s||(s=new Pi),r(N,M,i,n,s)}}return y?(s||(s=new Pi),t_(t,e,i,n,r,s)):!1}function hg(t,e,i,n,r){return t===e?!0:t==null||e==null||!Ri(t)&&!Ri(e)?t!==t&&e!==e:r_(t,e,i,n,hg,r)}function s_(t){return function(e,i,n){for(var r=-1,s=Object(e),o=n(e),c=o.length;c--;){var d=o[t?c:++r];if(i(s[d],d,s)===!1)break}return e}}var a_=s_();const o_=a_;var c_=function(){return si.Date.now()};const $l=c_;var d_="Expected a function",l_=Math.max,u_=Math.min;function Cc(t,e,i){var n,r,s,o,c,d,l=0,p=!1,g=!1,y=!0;if(typeof t!="function")throw new TypeError(d_);e=ng(e)||0,ai(i)&&(p=!!i.leading,g="maxWait"in i,s=g?l_(ng(i.maxWait)||0,e):s,y="trailing"in i?!!i.trailing:y);function T(ae){var De=n,Oe=r;return n=r=void 0,l=ae,o=t.apply(Oe,De),o}function b(ae){return l=ae,c=setTimeout(F,e),p?T(ae):o}function N(ae){var De=ae-d,Oe=ae-l,ft=e-De;return g?u_(ft,s-Oe):ft}function M(ae){var De=ae-d,Oe=ae-l;return d===void 0||De>=e||De<0||g&&Oe>=s}function F(){var ae=$l();if(M(ae))return H(ae);c=setTimeout(F,N(ae))}function H(ae){return c=void 0,y&&n?T(ae):(n=r=void 0,o)}function K(){c!==void 0&&clearTimeout(c),l=0,n=d=r=c=void 0}function I(){return c===void 0?o:H($l())}function re(){var ae=$l(),De=M(ae);if(n=arguments,r=this,d=ae,De){if(c===void 0)return b(d);if(g)return clearTimeout(c),c=setTimeout(F,e),T(d)}return c===void 0&&(c=setTimeout(F,e)),o}return re.cancel=K,re.flush=I,re}function Kl(t,e,i){(i!==void 0&&!Gs(t[e],i)||i===void 0&&!(e in t))&&Dl(t,e,i)}function h_(t){return Ri(t)&&Ys(t)}function zl(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function p_(t){return Ks(t,Qs(t))}function m_(t,e,i,n,r,s,o){var c=zl(t,i),d=zl(e,i),l=o.get(d);if(l){Kl(t,i,l);return}var p=s?s(c,d,i+"",t,e,o):void 0,g=p===void 0;if(g){var y=un(d),T=!y&&Gr(d),b=!y&&!T&&Tc(d);p=d,y||T||b?un(c)?p=c:h_(c)?p=Rm(c):T?(g=!1,p=Pm(d,!0)):b?(g=!1,p=jm(d,!0)):p=[]:Pb(d)||Ec(d)?(p=c,Ec(c)?p=p_(c):(!ai(c)||Ml(c))&&(p=Gm(d))):g=!1}g&&(o.set(d,p),r(p,d,n,s,o),o.delete(d)),Kl(t,i,p)}function pg(t,e,i,n,r){t!==e&&o_(e,function(s,o){if(r||(r=new Pi),ai(s))m_(t,e,o,i,pg,n,r);else{var c=n?n(zl(t,o),s,o+"",t,e,r):void 0;c===void 0&&(c=s),Kl(t,o,c)}},Qs)}var g_="[object Map]",f_="[object Set]",v_=Object.prototype,y_=v_.hasOwnProperty;function S_(t){if(t==null)return!0;if(Ys(t)&&(un(t)||typeof t=="string"||typeof t.splice=="function"||Gr(t)||Tc(t)||Ec(t)))return!t.length;var e=Jr(t);if(e==g_||e==f_)return!t.size;if(kc(t))return!bm(t).length;for(var i in t)if(y_.call(t,i))return!1;return!0}function E_(t,e){return hg(t,e)}var T_=kb(function(t,e,i){pg(t,e,i)});const hn=T_;var Yl=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Yl||{});const ne={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",USE_EXPERIMENTAL_SFU_HANDLER:"use_experimental_sfu_handler",TRACK_HINT:"track_hint",OVERRIDE_HIVE_SIMULCAST_DYNAMIC:"override_hive_simulcast_dynamic",PRECREATE_PRODUCERS:"precreate_producers",DISABLE_OPUS_DTX_CF:"disable_opus_dtx_cf",ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS:"enable_audio_activity_debug_logs"};function Pc(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 k_(t){var e,i,n,r;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((i=window.location.host)==null?void 0:i.includes("dyte.io")),o=!!((r=(n=t==null?void 0:t.getValue("modules"))==null?void 0:n.devTools)!=null&&r.logs);return s||o}function b_(t){var e;if(Q.hasFeature(ne.LOG_LEVEL)){let i=((e=Q.getValue(ne.LOG_LEVEL))==null?void 0:e.toString())||"all";if(i=i.toLowerCase().trim(),i==="off")return!1;if(i!=="all"){const n=["debug","log","info","warn","error"],r=n.indexOf(t),s=n.indexOf(i);if(r<s)return!1}}return!0}function mg(t,e,i={}){return Object.getOwnPropertyNames(t).forEach(n=>{var r;if([null,void 0,NaN].includes(t[n])||e&&(((r=e.match(/\./g))==null?void 0:r.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?mg(t[n],s,i):["number","string","boolean"].includes(typeof t[n])&&(i[s]=t[n])}),i}function gg(t,e,i={},n=""){const r={};try{const s=JSON.stringify(i),o=JSON.parse(s),c=mg(o,n),d=JSON.stringify(c);return JSON.parse(d)}catch(s){const o=Pc(s);r[`${n}.error.message`]=o.message||"",r[`${n}.error.stack`]=o.stack||"",r[`${n}.error.reason`]=o.reason||"",r[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return r}const Xs="chrome",fg="opera",vg="firefox",yg="iexplorer",Sg="safari",Eg="nwjs",Tg="electron",kg="react-native",Ql="unknown",Rc={Chrome:Xs,Chromium:Xs,Opera:fg,Firefox:vg,"Internet Explorer":yg,Safari:Sg};function __(){const{userAgent:t}=navigator,e={name:Ql,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const i=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(i,10)>72&&(e.name=Xs,e.version=i)}else e.name=Xs,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function w_(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:Tg,version:e}}return null}function I_(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Eg,version:e}}}function C_(){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:kg,version:e}}function P_(t){let e;const i=[C_,w_,I_];for(let r=0;r<i.length;r+=1)if(e=i[r](),e)return e;const n=t.getBrowserName();return n in Rc?{name:Rc[n],version:t.getBrowserVersion()}:(e=__(),e||{name:Ql,version:void 0})}class R_{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 i,n;if(this._bowser=rp.getParser(navigator.userAgent),typeof e=="undefined"){const r=P_(this._bowser);i=r.name,n=r.version}else e.name in Rc?(i=Rc[e.name],n=e.version):(i=Ql,n=void 0);this._name=i,this._version=n}getName(){return this._name}isChrome(){return this._name===Xs}isOpera(){return this._name===fg}isFirefox(){return this._name===vg}isIExplorer(){return this._name===yg}isSafari(){return this._name===Sg}isNWJS(){return this._name===Eg}isElectron(){return this._name===Tg}isReactNative(){return this._name===kg||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 M_ extends R_{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(i){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(Hs.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 _e=new M_,A_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Zs={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"},D_={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 Mc(t,e){const i=t.getValue("overrides");return i&&i[e]?i[e]:!1}function O_({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?js.PREPROD:t!=null&&t.includes("devel.dyte")?js.DEVEL:js.PROD}function $r({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function bg(t){const e=t.getValue("baseURI");return{location:$r({servicePrefix:"location",baseURI:e}),locationLegacy:$r({servicePrefix:"location-legacy",baseURI:e}),daCollector:$r({servicePrefix:"da-collector",baseURI:e})}}const N_='<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>',L_='<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>',Ac=t=>{if(!t)return;if(!t.startsWith("<svg"))return new Promise(r=>{r(t)});const e=new Blob([t],{type:"image/svg+xml"}),i=new Image,n=window.URL.createObjectURL(e);return new Promise((r,s)=>{i.onload=()=>{r(i),window.URL.revokeObjectURL(n)},i.onerror=()=>{s(),window.URL.revokeObjectURL(n)},i.src=n})};function x_(t){const e=x({},t),i=new Map,n=(o,c)=>(i.has(o)||i.set(o,new Set),i.get(o).add(c),()=>{var d;return(d=i.get(o))==null?void 0:d.delete(c)}),r=(o,c)=>{var d;(d=i.get(o))==null||d.delete(c)},s=o=>{var c;(c=i.get(o))==null||c.forEach(d=>{try{d(e[o])}catch(l){h.error(`Error in notifying for "${o.toString()}"`,l)}})};return{subscribe:n,unsubscribe:r,notify:s,setValue:(o,c,d=!0)=>{e[o]=c,d&&s(o)},getValue:o=>e[o],getAllValues:()=>e}}class V_{constructor(){m(this,"contexts",new Map),m(this,"mostRecentPeerId",null)}createContext(e,i){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,x_(i)),this.mostRecentPeerId=e,this.contexts.get(e))}remapContext(e,i){const n=i.getValue("peerId");n!==e&&(i.setValue("peerId",e),this.mostRecentPeerId=e,this.contexts.set(e,i),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}getMostRecentPeerId(){return this.mostRecentPeerId}}const Zn=new V_,ce=class{static get logsEndpoint(){const t=Zn.getContext(ce.meetingMetadata.peerId);return`https://${$r({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){ce.meetingMetadata.peerId=t}static init(t,e){const i=t.getValue("peerId");ce.tracingEnabled=e,ce.meetingMetadata.peerId=i,ce.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),ce.meetingMetadata.deviceInfo=_e.getDeviceInfo(),ce.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",ce.processCachedLogs),ce.logsProcessorTimer=setInterval(ce.processCachedLogs,ce.logsProcessingInterval),e&&(ce.initialized=!0)}static trace(t,e=void 0){return(i,n,r)=>{const s=r.value;return r.value=function(...o){if(!ce.initialized||navigator.isReactNative||!ce.tracingEnabled||Q.hasFeature(ne.SKIP_OTEL_TRACES))return s.apply(this,o);ce.addLogInCurrentSpan("info",t,e);const c=performance.now(),d=s.apply(this,o);return Promise.resolve(d).then(()=>{const l=performance.now();l-c>10&&ce.addLogInCurrentSpan("info",`${t}_timing`,{execTime:l-c,country:ce.location.country})}).catch(()=>{const l=performance.now();ce.addLogInCurrentSpan("info",`${t}_timing`,{execTime:l-c})}),d},r}}static injectContext(t){var e;const i=Br().replace(/-/g,"").substring(0,16),n=(e=ce.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${i}-01`}static addLogInCurrentSpan(t,e,i={},n=!1){i!=null&&i.error&&Object.assign(i,{error:Pc(i.error)});const r=Zn.getContext(ce.meetingMetadata.peerId);if(k_(r)&&(S_(i)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,i)),!!b_(t))try{const s=gg(r,e,i,"metadata"),o=new Date,c=q(x({message:e,level:t},s),{loggedAt:o.toISOString(),loggedAtTzOffset:o.getTimezoneOffset()});n?ce.sendOtelLogsToNewRelic([c]):ce.logsCache.push(c)}catch(s){ce.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Pc(s)})}}static sendOtelLogsToNewRelic(t){const e=Zn.getContext(ce.meetingMetadata.peerId);fetch(ce.logsEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({meetingMetadata:gg(e,"sendOtelLogsToNewRelic",ce.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t})}).catch(i=>{ce.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Pc(i)}),ce.logsCache.push(...t)})}static processCachedLogs(){const t=ce.logsCache.splice(0,25);t!=null&&t.length&&ce.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(ce.logsProcessorTimer),ce.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",ce.processCachedLogs)}};let S=ce;m(S,"logsCache",[]),m(S,"logsProcessorTimer"),m(S,"location",{country:void 0}),m(S,"tracingEnabled",!0),m(S,"initialized",!1),m(S,"logsProcessingInterval",7e3),m(S,"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(S,"meetingMetadata",{});class h{static info(e,i,n){S.addLogInCurrentSpan("info",e,i,n)}static error(e,i,n){S.addLogInCurrentSpan("error",e,i,n)}static debug(e,i,n){S.addLogInCurrentSpan("debug",e,i,n)}static log(e,i,n){S.addLogInCurrentSpan("log",e,i,n)}static warn(e,i,n){S.addLogInCurrentSpan("warn",e,i,n)}}const U_=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&h.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,i,n,r,s,o,c,d;h.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(i=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:i.url,baseURL:(r=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:r.baseURL,method:(o=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:o.method,status:(c=t==null?void 0:t.reason)==null?void 0:c.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{h.info("window::offline")}),window.addEventListener("online",()=>{h.info("window::online")}))},F_={"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"},Dc={"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(Dc).forEach(t=>{Dc[t]=`{${F_[t.slice(0,2)]}} ${Dc[t]}`});class w extends Error{constructor(e,i,n=!1){super(e),m(this,"code"),this.code=i,this.name="DyteError",this.message=`[ERR${this.code}]: ${Dc[this.code]}
13
+ ${this.message}`;try{let r=n;i&&i.endsWith("00")&&(r=!0),r&&h.error("DyteError",{error:{message:this.message,name:this.name,code:i}});const s=Zn.getContext(Zn.getMostRecentPeerId());if(s){const o=s.getValue("onError");try{o(this)}catch(c){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("dyteError",{detail:this}))}catch(r){}}}function Oc(t,e,i,n){if(n instanceof w)throw n;if(n instanceof e){const r=new w(n.message,i);throw r.stack=n.stack,r}else throw n}function _g(t,e,i){if(!t.value){const r=t.get,s=t.set;return r&&(t.get=function(){try{return r.apply(this)}catch(o){Oc(this,e,i,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(c){Oc(this,e,i,c)}}),t}const n=t.value;return t.value=function(...r){try{const s=n.apply(this,r);return s&&s instanceof Promise?s.catch(o=>{Oc(this,e,i,o)}):s}catch(s){Oc(this,e,i,s)}},t}function B_(t,e){return(i,n,r)=>{if(r)return _g(r,t,e);for(const s of Reflect.ownKeys(i.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(i.prototype,s);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(i.prototype,s,_g(o,t,e))}}}const ut=t=>B_(Error,t);function W_(t){let e=0,i,n;if(!t)return e;for(i=0;i<t.length;i+=1)n=t.charCodeAt(i),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var pn,mn;const wg=class extends lt.EventEmitter{constructor(){super(),f(this,pn,void 0),f(this,mn,void 0),m(this,"asyncPromiseTimeout"),v(this,pn,new Map),v(this,mn,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){a(this,pn).set(t,[]);const i=a(this,mn).get(t).map(()=>new Promise(n=>{a(this,pn).get(t).push(n)}));uS(wg.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(i),new Promise((n,r)=>setTimeout(()=>r(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),a(this,pn).delete(t)})}onAsync(t,e){const i=a(this,pn),n=(...r)=>u(this,null,function*(){var s;try{yield e(...r)}catch(c){h.error("[onAsync]",{error:c})}const o=(s=i.get(t))==null?void 0:s.shift();o==null||o()});return a(this,mn).get(t)||a(this,mn).set(t,[]),a(this,mn).get(t).push(n),super.on(t,n)}reset(){v(this,pn,new Map),v(this,mn,new Map),super.removeAllListeners()}};let j_=wg;pn=new WeakMap,mn=new WeakMap;const P=new j_;function H_(){_e.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 i=e.find(r=>{var s;return(s=r.id)==null?void 0:s.includes("screen")});i=i!=null?i:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:i.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var R=(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))(R||{});class Kr extends lt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...i){return super.emit("*",e,...i),super.emit(e,...i)}on(e,i){try{const n=this.listenerCount(e);n>25&&n%25===0&&h.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,i)}addListener(e,i){try{const n=this.listenerCount(e);n>25&&n%25===0&&h.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,i)}off(e,i){return super.off(e,i)}once(e,i){return super.once(e,i)}prependListener(e,i){return super.prependListener(e,i)}prependOnceListener(e,i){return super.prependOnceListener(e,i)}removeListener(e,i){return super.removeListener(e,i)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Ft extends lt.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...i){return super.emit("*",e,...i),super.emit(e,...i)}on(e,i){try{const n=this.listenerCount(e);n>25&&n%25===0&&h.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,i)}addListener(e,i){try{const n=this.listenerCount(e);n>25&&n%25===0&&h.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,i)}off(e,i){return super.off(e,i)}once(e,i){return super.once(e,i)}prependListener(e,i){return super.prependListener(e,i)}prependOnceListener(e,i){return super.prependOnceListener(e,i)}removeListener(e,i){return super.removeListener(e,i)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}function G_(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(i=>i.charAt(0)).join("").toUpperCase()}const Ig=1080,Cg=1920,q_=(t,e,i,n,r,s)=>{let o=.5,c=.5;const d=r,l=s,p=Math.min(i/d,n/l);let g=d*p,y=l*p,T,b,N,M,F=1;return g<i&&(F=i/g),Math.abs(F-1)<1e-14&&y<n&&(F=n/y),g*=F,y*=F,N=d/(g/i),M=l/(y/n),T=(d-N)*o,b=(l-M)*c,T<0&&(T=0),b<0&&(b=0),N>d&&(N=d),M>l&&(M=l),[T,b,N,M,t,e,i,n]};var oi,ea,St,ci,We,Mi,gn,At,Ge,ta,ia,fn,na;const Pg=class extends Ft{constructor(t,e,i,n){super(),f(this,oi,void 0),f(this,ea,void 0),f(this,St,void 0),f(this,ci,void 0),f(this,We,{height:Ig,width:Cg}),f(this,Mi,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),f(this,gn,void 0),f(this,At,{}),f(this,Ge,void 0),f(this,ta,void 0),f(this,ia,void 0),f(this,fn,void 0),f(this,na,!1),m(this,"cleanupEventListeners",()=>{a(this,ea).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Ge).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ge).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ge).removeListener("roomLeft",()=>this.disable())}),m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),m(this,"onSelfVideoUpdateListener",({videoEnabled:r})=>{this.updateMediaSession("CAMERA",r)}),m(this,"onSelfAudioUpdateListener",({audioEnabled:r})=>{this.updateMediaSession("MIC",r)}),m(this,"handlePipMediaControls",r=>{r==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),m(this,"eventCallback",r=>{r==="CAMERA"&&(a(this,Ge).videoEnabled?a(this,Ge).disableVideo():a(this,Ge).enableVideo(),this.emit("cameraToggled")),r==="MIC"&&(a(this,Ge).audioEnabled?a(this,Ge).disableAudio():a(this,Ge).enableAudio(),this.emit("micToggled")),r==="END"&&(P.emit(R.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",()=>{if(!this.isActive&&a(this,fn)==="active"){this.disable(!0);return}a(this,At)!==void 0&&this.paintCanvas(),a(this,gn)!==void 0&&v(this,gn,requestAnimationFrame(()=>this.animate()))}),m(this,"disable",(r=!1)=>{v(this,fn,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,gn)),r!==!0&&document.body.removeChild(a(this,St)),v(this,gn,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()}),v(this,ea,t),v(this,fn,"idle"),v(this,Ge,e),v(this,Mi,{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}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static _init(t,e){return u(this,null,function*(){let i,n;try{i=yield Ac(N_),n=yield Ac(L_)}catch(r){}return new Pg(t,e,i,n)})}setupIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":v(this,ia,e);break;case"pin":v(this,ta,e);break}})}overrideIcon(t,e){return u(this,null,function*(){switch(t){case"handRaise":v(this,ia,yield Ac(e));break;case"pin":v(this,ta,yield Ac(e));break}})}constructImage(t){const e=new Image,i=new Blob([t],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(r=>{e.onload=()=>{r(e),window.URL.revokeObjectURL(n)},e.src=n})}createVideoContainer(){v(this,St,document.createElement("div")),a(this,St).style.width="0.1px",a(this,St).style.height="0.1px",a(this,St).style.overflow="hidden",a(this,St).style.position="absolute",a(this,St).style.bottom="0",a(this,St).style.right="0",a(this,St).style.opacity="0",a(this,St).appendChild(a(this,ci))}setupEventListeners(){a(this,ea).subscribe("stageStatus",this.handlePipMediaControls),a(this,Ge).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ge).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ge).addListener("roomLeft",()=>this.disable())}createCanvas(){const t=document.createElement("canvas");t.height=a(this,We).height,t.width=a(this,We).width,v(this,oi,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||a(this,Ge).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Ge).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const t=Object.values(a(this,At)).reduce((e,i)=>(e[i.pinned?"pinned":"regular"].push(i),e),{pinned:[],regular:[]});return[...t.pinned,...t.regular]}drawEmptyTile(t,e,i,n){if(a(this,oi)===void 0)return;const r=a(this,oi).getContext("2d"),s=a(this,oi).width,o=0,c=0,d=e-o*2,l=i-o*2,p=Math.floor(s/d),g=Math.floor(t/p),y=t%p*(d+o)+o,T=g*(l+o)+o,{displayText:b,image:N}=n!=null?n:{};r.fillStyle=b||N?a(this,Mi).videoBackground:a(this,Mi).background,r.strokeStyle=a(this,Mi).brand,r.beginPath(),r.moveTo(y+c,T),r.arcTo(y+d,T,y+d,T+c,c),r.arcTo(y+d,T+l,y+d-c,T+l,c),r.arcTo(y,T+l,y,T+l-c,c),r.arcTo(y,T,y+c,T,c),r.closePath(),r.fill(),r.stroke();const M=d/6,F=d/2+y,H=l/2+T;r.save(),(b||N)&&(r.beginPath(),r.arc(F,H,M,0,Math.PI*2),r.fillStyle=a(this,Mi).brand,r.fill(),N?(r.clip(),r.drawImage(N,F-M,H-M,M*2,M*2),r.restore()):b&&(r.fillStyle=a(this,Mi).textOnBrand,r.font=`${M/2}px sans-serif`,r.textAlign="center",r.textBaseline="middle",r.fillText(b,F,H)),this.drawIcons(n,y,T,Math.max(d,l)))}drawIcons(t,e,i,n){const r=Math.min(Math.max(n*.15,100),200),s=r*.2,o=r*.2;let c=e+s;const d=i+s,l=p=>{const g=a(this,oi).getContext("2d");g.save(),g.fillStyle=a(this,Mi).background,g.beginPath(),g.moveTo(c+o,d),g.arcTo(c+r,d,c+r,d+o,o),g.arcTo(c+r,d+r,c+r-o,d+r,o),g.arcTo(c,d+r,c,d+r-o,o),g.arcTo(c,d,c+o,d,o),g.closePath(),g.fill(),typeof p=="string"?(g.font=`${r/1.5}px sans-serif`,g.fillStyle=a(this,Mi).text,g.textAlign="center",g.textBaseline="top",g.fillText(p,r/2+c,d+s)):g.drawImage(p,c+s,d+s,r-s*2,r-s*2),c+=r+s,g.restore()};t.pinned&&l(a(this,ta)),t.handRaised&&l(a(this,ia))}drawTile(t,e,i){var n,r;if(a(this,oi)===void 0)return;const s=a(this,oi).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,We).height-5;){let l=0;for(;l<a(this,We).width-5&&d<i;){if((n=o[d])!=null&&n.enabled){const p=o[d].element,[g,y,T,b,N,M,F,H]=q_(l,c,t,e,p.videoWidth,p.videoHeight);(r=p==null?void 0:p.classList)!=null&&r.contains("mirror")?(s.save(),s.scale(-1,1),s.drawImage(p,g,y,T,b,-1*N,M,-1*F,H),s.restore()):s.drawImage(p,g,y,T,b,N,M,F,H),this.drawIcons(o[d],N,M,Math.max(F,H))}else this.drawEmptyTile(d,t,e,o[d]);d+=1,l+=t}c+=e}}calcGridElemSize(t){switch(t){case 0:case 1:return[a(this,We).width,a(this,We).height];case 2:return[Math.floor(a(this,We).width/2),a(this,We).height];case 3:case 4:return[Math.floor(a(this,We).width/2),Math.floor(a(this,We).height/2)];case 5:case 6:return[Math.floor(a(this,We).width/3),Math.floor(a(this,We).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,We).width/3),Math.floor(a(this,We).height/3)];default:return[Math.floor(a(this,We).width/3),Math.floor(a(this,We).height/2)]}}paintCanvas(){let t=this.getSources().length;t!==1&&(t=t%2>0?t+1:t);const[e,i]=this.calcGridElemSize(t);this.drawTile(e,i,t)}isSupported(){var t;return!!window.chrome&&document.pictureInPictureEnabled&&((t=a(this,Ge).config)==null?void 0:t.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(v(this,na,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,St))try{document.body.removeChild(a(this,St))}catch(t){}this.removeAllSources(),v(this,oi,void 0),v(this,ci,void 0),v(this,gn,void 0)}init({height:t,width:e}={}){if(!this.isSupported())throw h.error("DytePip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,na))return;v(this,na,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");v(this,We,{height:t!=null?t:Ig,width:e!=null?e:Cg}),i.height=a(this,We).height,i.width=a(this,We).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,oi).captureStream(24),v(this,ci,i),a(this,ci).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,ci).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,At)[t]!==void 0&&(a(this,At)[t].enabled=!0)}disableSource(t){a(this,At)[t]!==void 0&&(a(this,At)[t].enabled=!1)}generateAvatar(t,e){return u(this,null,function*(){if(!e)return;const i=new Image;try{const n=yield(yield fetch(e)).blob(),r=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(t,{image:i}),window.URL.revokeObjectURL(r)},i.src=r}catch(n){h.error("DytePip::GenerateAvatar",{error:n})}})}addSource(t,e,i,n=!1,r=void 0,s=void 0,o=!1){h.debug("DytePIP::AddSource",{pip:{id:t,handRaised:o}}),a(this,At)[t]={id:t,element:e,enabled:i,pinned:n,displayText:r?G_(r):void 0,imageUrl:s,handRaised:o},s&&this.generateAvatar(t,s)}updateSource(t,e){h.info("DytePIP::UpdateSource",{pip:{id:t,handRaised:e.handRaised}});const i=a(this,At)[t];i&&(a(this,At)[t]=x(x({},i),e))}removeSource(t){delete a(this,At)[t]}removePinnedSource(){Object.values(a(this,At)).forEach(t=>{t.pinned&&this.removeSource(t.id)})}removeAllSources(){v(this,At,{})}enable(){v(this,fn,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Ge).videoEnabled),this.updateMediaSession("MIC",a(this,Ge).audioEnabled),document.body.appendChild(a(this,St)),v(this,gn,requestAnimationFrame(()=>this.animate())),a(this,ci).onloadedmetadata=()=>{a(this,ci).requestPictureInPicture().then(()=>{v(this,fn,"active")})},a(this,ci).readyState===4&&a(this,ci).requestPictureInPicture().then(()=>{v(this,fn,"active")})}};let J_=Pg;oi=new WeakMap,ea=new WeakMap,St=new WeakMap,ci=new WeakMap,We=new WeakMap,Mi=new WeakMap,gn=new WeakMap,At=new WeakMap,Ge=new WeakMap,ta=new WeakMap,ia=new WeakMap,fn=new WeakMap,na=new WeakMap;var qi;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(qi||(qi={}));var Ai;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(Ai||(Ai={}));class $_ 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},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Rg=new $_;class K_ 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 z_=new K_;class Y_ extends E{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Y_;class Q_ extends E{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",qi]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const di=new Q_;class X_ extends E{constructor(){super("media.ProducerPayload",[{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:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const Z_=new X_;class ew 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:()=>di},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>Z_}])}}const tw=new ew;class iw extends E{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const nw=new iw;class rw extends E{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>di},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Mg=new rw;class sw extends E{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>di}])}}const aw=new sw;class ow extends E{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>di}])}}new ow;class cw 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 dw=new cw;class lw 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 uw=new lw;class hw 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 hw;class pw 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 pw;class mw extends E{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ai]},{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},{no:8,name:"codec",kind:"message",T:()=>Rg}])}}const ra=new mw;class gw extends E{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ra},{no:3,name:"producer_track",kind:"message",T:()=>uw},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const fw=new gw;class vw extends E{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>fw}}])}}const Ag=new vw;class yw extends E{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Ng},{no:2,name:"receiver",kind:"message",T:()=>Ng}])}}const Dg=new yw;class Sw extends E{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Rg},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>z_}])}}const Og=new Sw;class Ew extends E{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Og},{no:2,name:"video",kind:"message",T:()=>Og}])}}const Ng=new Ew;class Tw 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 kw=new Tw;class bw 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 _w=new bw;class ww 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:()=>_w},{no:9,name:"capabilities",kind:"message",T:()=>Dg}])}}const Iw=new ww;class Cw extends E{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Pw=new Cw;class Rw extends E{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const Mw=new Rw;class Aw 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 Aw;class Dw 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:()=>kw},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const Ow=new Dw;class Nw extends E{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>Ow},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Lw=new Nw;class xw 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:()=>di},{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},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const Vw=new xw;class Uw extends E{constructor(){super("media.edge.SelectedPeersRequest",[])}}new Uw;class Fw extends E{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Bw=new Fw;class Ww 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 Nc=new Ww;class jw extends E{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new jw;class Hw extends E{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>di},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const Gw=new Hw;class qw 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:()=>di},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const Jw=new qw;class $w extends E{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new $w;class Kw extends E{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Lg=new Kw;class zw 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 Yw=new zw;class Qw 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 Xw=new Qw;class Zw 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 eI=new Zw;class tI 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 iI=new tI;class nI 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 rI=new nI;class sI extends E{constructor(){super("media.edge.EmptyResponse",[])}}new sI;class aI 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:()=>ra},{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:()=>Dg}])}}const xg=new aI;class oI 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 Xl=new oI;class cI 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 dI=new cI;class lI extends E{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>dI}])}}const Vg=new lI;class uI extends E{constructor(){super("media.edge.PeerJoinResponse",[])}}new uI;class hI extends E{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>iI},{no:2,name:"participants",kind:"message",repeat:1,T:()=>xg},{no:3,name:"selected_peers",kind:"message",T:()=>Xl},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Zl=new hI;class pI extends E{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const mI=new pI;class gI extends E{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Ag}])}}new gI;class fI extends E{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Ag},{no:3,name:"description",kind:"message",T:()=>di}])}}const vI=new fI;class yI 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:()=>di}])}}const SI=new yI;class EI extends E{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>dw}])}}new EI;class TI 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 TI;class kI extends E{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new kI;class bI extends E{constructor(){super("media.edge.ProducerToggleResponse",[])}}new bI;class _I extends E{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new _I;class wI extends E{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>di}])}}const II=new wI;class CI extends E{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>di}])}}const PI=new CI;class RI extends E{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new RI;class MI extends E{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new MI;class AI extends E{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new AI;class DI extends E{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const OI=new DI;class NI extends E{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const LI=new NI;class xI extends E{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const VI=new xI;class UI extends E{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>xg}])}}const Ug=new UI;class FI extends E{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Fg=new FI;class BI extends E{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Fg},{no:3,name:"screenshare",kind:"message",T:()=>Fg}])}}const WI=new BI;class jI extends E{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Mg},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>WI}])}}new jI;class HI extends E{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ra}])}}const GI=new HI;class qI extends E{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ra},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Bg=new qI;class JI extends E{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ra}])}}const $I=new JI;class KI extends E{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const eu=new KI;class zI extends E{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Wg=new zI;class YI extends E{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new YI;class QI extends E{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new QI;class XI extends E{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new XI;class ZI 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 ZI;class eC extends E{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new eC;class tC extends E{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new tC;class iC 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 tu=new iC;class nC 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 nC;class rC 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 sC=new rC;var er;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(er||(er={}));var Ji;(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"})(Ji||(Ji={}));var iu;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(iu||(iu={}));var nu;(function(t){t[t.PEERS=0]="PEERS",t[t.ROOMS=1]="ROOMS"})(nu||(nu={}));var Lc;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(Lc||(Lc={}));class aC 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 oC=new aC;class cC 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",Ji,"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:()=>oC}])}}const xc=new cC;class dC extends E{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>xc}])}}const zr=new dC;class lC 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",Ji,"STAGE_TYPE_"]}])}}const jg=new lC;class uC 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 hC=new uC;class pC extends E{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>xc}])}}const ru=new pC;class mC extends E{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Hg=new mC;class gC 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:()=>vC},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Gg=new gC;class fC 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",er]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const vC=new fC;class yC extends E{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Gg}])}}const qg=new yC;class SC extends E{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Jg=new SC;class EC 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 EC;class TC extends E{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>xc},{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",Lc,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const kC=new TC;class bC extends E{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>xc},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const _C=new bC;class wC extends E{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Gg}])}}new wC;class IC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new IC;class CC 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 su=new CC;class PC 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 RC=new PC;class MC 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:()=>RC}])}}const $g=new MC;class AC extends E{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>$g},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>$g}])}}const DC=new AC;class OC extends E{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const NC=new OC;class LC extends E{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>NC}])}}const xC=new LC;class VC 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:()=>su}])}}const UC=new VC;class FC extends E{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>UC}])}}const Kg=new FC;class BC 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 WC=new BC;class jC extends E{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>WC}])}}new jC;class HC extends E{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const GC=new HC;class qC extends E{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>GC}])}}const JC=new qC;class $C extends E{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>YC}])}}const KC=new $C;class zC 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:()=>su}])}}const YC=new zC;class QC 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 XC=new QC;class ZC 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:()=>XC}])}}const eP=new ZC;class tP 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:()=>su}])}}const zg=new tP;class iP extends E{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>zg}])}}new iP;class nP 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 rP=new nP;class sP extends E{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>cP}])}}const aP=new sP;class oP 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 cP=new oP;class dP extends E{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Yg=new dP;class lP 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",nu,"BROADCAST_TYPE_"]}])}}const sa=new lP;class uP extends E{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const hP=new uP;class pP extends E{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mP=new pP;class gP 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 fP=new gP;class vP extends E{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>fP}])}}const Qg=new vP;class yP 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 Xg=new yP;var au;(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"})(au||(au={}));var vn;(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"})(vn||(vn={}));class SP 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 EP=new SP;class TP 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 kP=new TP;class bP 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 _P=new bP;class wP 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 IP=new wP;class CP extends E{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>_P},{no:2,name:"private",kind:"message",T:()=>IP}])}}const PP=new CP;class RP 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 MP=new RP;class AP extends E{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",vn,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",vn,"STREAM_PERMISSION_TYPE_"]}])}}const ou=new AP;class DP extends E{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>ou},{no:2,name:"audio",kind:"message",T:()=>ou},{no:3,name:"screenshare",kind:"message",T:()=>ou}])}}const OP=new DP;class NP extends E{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>EP},{no:2,name:"plugins",kind:"message",T:()=>kP},{no:3,name:"chat",kind:"message",T:()=>PP},{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",au,"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",iu,"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:()=>MP},{no:23,name:"media",kind:"message",T:()=>OP}])}}const cu=new NP;class LP extends E{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const xP=new LP;class VP 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 UP=new VP;class FP extends E{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>UP}])}}const BP=new FP;class WP extends E{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>cu}])}}const Zg=new WP;class jP extends E{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Zg}])}}const HP=new jP;class GP extends E{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>Zg}])}}const ef=new GP;class qP 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 JP=new qP;class $P extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>JP},{no:2,name:"patch",kind:"message",T:()=>cu}])}}new $P;class KP extends E{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>cu}])}}new KP;class zP 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 tr=new zP;class YP 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 QP=new YP;class XP extends E{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>tr},{no:2,name:"next",kind:"scalar",T:8}])}}const ZP=new XP;class eR extends E{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>tr}])}}const tf=new eR;class tR 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 iR=new tR;class nR extends E{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>tr}])}}const du=new nR;class rR 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 sR=new rR;class aR extends E{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>tr}])}}const lu=new aR;class oR 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 cR=new oR;class dR extends E{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>tr}])}}new dR;class lR 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 uR=new lR;class hR 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 pR=new hR;class mR 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 Vc=new mR;class gR extends E{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>tr}])}}const Uc=new gR;class fR 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 vR=new fR;class yR 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 Fc=new yR;class SR 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 ER=new SR;class TR 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 kR=new TR;class bR extends E{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const _R=new bR;class wR 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 IR=new wR;class CR 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 PR=new CR;class RR extends E{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new RR;class MR extends E{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const AR=new MR;class DR extends E{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>tr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const OR=new DR;class NR 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:()=>OR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const LR=new NR;class xR extends E{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>LR}])}}const $i=new xR;class VR 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 UR=new VR;class FR extends E{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>UR}])}}const BR=new FR;class WR 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 jR=new WR;class HR 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 GR=new HR;class qR extends E{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const JR=new qR;class $R extends E{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const KR=new $R;class zR 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 YR=new zR;class QR 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 XR=new QR;class ZR 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 eM=new ZR;class tM 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 iM=new tM;class nM 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 uu=new nM;class rM 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:()=>uu}])}}const nf=new rM;class sM 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:()=>uu}])}}const aM=new sM;class oM 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:()=>uu}])}}const cM=new oM;class dM 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 lM=new dM;class uM 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 hu=new uM;class hM extends E{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>hu}])}}const pM=new hM;class mM 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 rf=new mM;class gM 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 fM=new gM;class vM 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:()=>fM}])}}const sf=new vM;class yM 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 af=new yM;class SM 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 of=new SM;class EM extends E{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const cf=new EM;class TM 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 kM=new TM;class bM extends E{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>kM}])}}const pu=new bM;class _M extends E{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const wM=new _M;class IM extends E{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const CM=new IM;class PM extends E{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const df=new PM;class RM 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:()=>AM},{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 lf=new RM;class MM 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:()=>OM}])}}const AM=new MM;class DM 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 OM=new DM;class NM 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 LM=new NM;class xM 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 VM=new xM;class UM extends E{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>lf}])}}const mu=new UM;class FM extends E{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>lf}])}}const BM=new FM;class WM 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",er]}])}}const uf=new WM;class jM 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(),i=Date.now();return e.seconds=Se.from(Math.floor(i/1e3)).toBigInt(),e.nanos=i%1e3*1e6,e}toDate(e){return new Date(Se.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const i=this.create(),n=e.getTime();return i.seconds=Se.from(Math.floor(n/1e3)).toBigInt(),i.nanos=n%1e3*1e6,i}internalJsonWrite(e,i){let n=Se.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 r="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?r="."+s.substring(0,3)+"Z":s.substring(6)==="000"?r="."+s.substring(0,6)+"Z":r="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",r)}internalJsonRead(e,i,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+gl(e)+".");let r=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(!r)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(r[1]+"-"+r[2]+"-"+r[3]+"T"+r[4]+":"+r[5]+":"+r[6]+(r[8]?r[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=Se.from(s/1e3).toBigInt(),n.nanos=0,r[7]&&(n.nanos=parseInt("1"+r[7]+"0".repeat(9-r[7].length))-1e9),n}}new jM;class HM extends E{constructor(){super("common.BaseHubMessage",[{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},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9}])}}const gu=new HM;class GM extends E{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>gu}])}}new GM;class qM extends E{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>gu},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>gu}])}}new qM;const JM=0,$M=1,KM=2,zM=3,YM=4,QM=5,XM={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},ZM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},eA={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},tA={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},hf={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,audioActivity:100},iA={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},nA={getUserPresets:0,updateUserPreset:1};function Yr(t,e){return Object.keys(e).reduce((i,n)=>(i[n]=(t<<16)+e[n],i),{})}function pf(t,e){return Object.keys(t).reduce((i,n)=>(i[n]=e|t[n],i),{})}const B=Yr(JM,XM),Me=Yr($M,ZM),z=Yr(KM,eA),Ki=Yr(zM,tA),ir=Yr(YM,iA),Xt=pf(hf,16777216),li=pf(hf,50331648),Bc=Yr(QM,nA);var rA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,fu=(t,e,i,n)=>{for(var r=n>1?void 0:n?sA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&rA(e,i,r),r},nr,mf;const vu=(mf=class{constructor(t){f(this,nr,void 0),v(this,nr,t)}createChannel(t,e,i,n="public",r=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:i,visibility:n,isDirectMessage:r};r&&(s.visibility="private");const o=yield a(this,nr).sendMessagePromise(ir.createChatChannel,IR.toBinary(s)),c=$i.fromBinary(o.payload).chatChannels;return vu.formatChannel(c[0])})}updateChannel(t,e){return u(this,null,function*(){const i=yield a(this,nr).sendMessagePromise(ir.updateChatChannel,PR.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=$i.fromBinary(i.payload).chatChannels;return vu.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:i}=t,n=q(x({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=i==null?void 0:i.unreadCount)!=null?e:0});return i!=null&&i.message&&(n.latestMessage=zi.formatSocketServiceMessage(i.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield a(this,nr).sendMessagePromise(ir.getChannelMembers,AR.toBinary({chatChannelId:t}));return BR.fromBinary(e.payload).channelMembers.map(i=>{var n=i,{id:r}=n,s=ac(n,["id"]);return q(x({},s),{userId:r})})}catch(e){return[]}})}on(t,e){let i,n;switch(t){case ir.createChatChannel:{i=$i.fromBinary.bind($i),n=$i.create();break}case ir.updateChatChannel:{i=$i.fromBinary.bind($i),n=$i.create();break}}if(!i){h.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}a(this,nr).on(t,({payload:r})=>{let s=n;try{s=i(r)}catch(o){h.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}},nr=new WeakMap,mf);let rr=vu;fu([S.trace("ChatChannelHandler.createChannel")],rr.prototype,"createChannel",1),fu([S.trace("ChatChannelHandler.updateChannel")],rr.prototype,"updateChannel",1),fu([S.trace("ChatChannelHandler.getChannelMembers")],rr.prototype,"getChannelMembers",1);var aA=Object.defineProperty,oA=Object.getOwnPropertyDescriptor,ui=(t,e,i,n)=>{for(var r=n>1?void 0:n?oA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&aA(e,i,r),r},Et=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(Et||{}),Tt;class Zt{constructor(e){f(this,Tt,void 0),v(this,Tt,e)}getChatMessages(){return a(this,Tt).sendMessagePromise(Me.getMessages)}getChatMessagesPaginated(e,i,n,r=0,s=""){return u(this,null,function*(){const o={timeStamp:e,size:i,from:r,reversed:n,channelId:s},c=yield a(this,Tt).sendMessagePromise(Me.getPaginatedMessages,QP.toBinary(o));return c.payload?ZP.fromBinary(c.payload):{messages:[],next:!1}})}sendMessageToRoom(e,i){const n={payloadType:i,payload:e};a(this,Tt).sendMessage(Me.sendMessageToRoom,iR.toBinary(n))}sendMessageToPeers(e,i,n){const r={payloadType:i,peerIds:n,payload:e};a(this,Tt).sendMessage(Me.sendMessageToPeers,sR.toBinary(r))}sendMessageToChannel(e,i,n){const r={payloadType:i,channelId:n,payload:e};a(this,Tt).sendMessage(Me.sendMessageToChannel,cR.toBinary(r))}sendMessage(e,i,n,r){if(r&&this.sendMessageToChannel(e,i,r),n&&n.length>0){this.sendMessageToPeers(e,i,n);return}this.sendMessageToRoom(e,i)}editMessage(e,i,n,r,s){return u(this,null,function*(){const o={chatId:e,payloadType:n,payload:i};r&&(o.channelId=r),s!==void 0&&(o.pinned=s);const c=yield a(this,Tt).sendMessagePromise(Me.editMessage,uR.toBinary(o));return Uc.fromBinary(c.payload).message})}deleteMessage(e,i){return u(this,null,function*(){const n={chatId:e};i&&(n.channelId=i);const r=yield a(this,Tt).sendMessagePromise(Me.deleteMessage,vR.toBinary(n)),s=Fc.fromBinary(r.payload);return x({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,i){return u(this,null,function*(){var n,r,s;const o={searchTerm:e,timeStamp:(n=i.timestamp)!=null?n:Date.now(),size:(r=i.size)!=null?r:75,from:0,reversed:(s=i.reversed)!=null?s:!0};i.channelId&&(o.channelId=i.channelId);try{const c=yield a(this,Tt).sendMessagePromise(Me.searchChannelMessages,ER.toBinary(o));return tf.fromBinary(c.payload).messages}catch(c){return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield a(this,Tt).sendMessagePromise(Me.getAllChatChannels);return $i.fromBinary(e.payload).chatChannels.map(rr.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,i){return u(this,null,function*(){const n=yield a(this,Tt).sendMessagePromise(Me.markChannelIndexAsRead,kR.toBinary({channelId:e,userId:i.userId,channelIndex:i.channelIndex}));return _R.fromBinary(n.payload).channelIndex})}setPinState(e,i){return u(this,null,function*(){const n={chatId:e.id,pinned:i,channelId:e.channelId},r=yield a(this,Tt).sendMessagePromise(Me.pinMessage,pR.toBinary(n));return Vc.fromBinary(r.payload)})}on(e,i){let n,r;switch(e){case Me.sendMessageToRoom:{n=du.fromBinary.bind(du),r=du.create();break}case Me.sendMessageToPeers:{n=lu.fromBinary.bind(lu),r=lu.create();break}case Me.editMessage:{n=Uc.fromBinary.bind(Uc),r=Uc.create();break}case Me.pinMessage:{n=Vc.fromBinary.bind(Vc),r=Vc.create();break}case Me.deleteMessage:{n=Fc.fromBinary.bind(Fc),r=Fc.create();break}}if(!n){h.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}a(this,Tt).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){h.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}Tt=new WeakMap,ui([S.trace("SocketService.getChatMessages")],Zt.prototype,"getChatMessages",1),ui([S.trace("SocketService.getChatMessagesPaginated")],Zt.prototype,"getChatMessagesPaginated",1),ui([S.trace("SocketService.sendMessageToRoom")],Zt.prototype,"sendMessageToRoom",1),ui([S.trace("SocketService.sendMessageToPeers")],Zt.prototype,"sendMessageToPeers",1),ui([S.trace("SocketService.sendMessageToChannel")],Zt.prototype,"sendMessageToChannel",1),ui([S.trace("SocketService.sendMessage")],Zt.prototype,"sendMessage",1),ui([S.trace("SocketService.editMessage")],Zt.prototype,"editMessage",1),ui([S.trace("SocketService.deleteMessage")],Zt.prototype,"deleteMessage",1),ui([S.trace("SocketService.searchMessages")],Zt.prototype,"searchMessages",1),ui([S.trace("SocketService.getAllChannels")],Zt.prototype,"getAllChannels",1),ui([S.trace("SocketService.markLastReadMessage")],Zt.prototype,"markLastReadMessage",1);function cA(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function hi(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(i=>hi(i));const e={};return Object.keys(t).forEach(i=>{const n=pl(i)?i:cA(i);e[n]=hi(t[i])}),e}function dA(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function gf(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(i=>gf(i));const e={};return Object.keys(t).forEach(i=>{const n=pl(i)?i:dA(i);e[n]=t[i]}),e}function Wc(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(i=>{if(typeof t[i]!="function"){if(typeof t[i]=="object"){Wc(t[i],e[i]={});return}e[i]=t[i]}}),e)}class ff{constructor(e){m(this,"defaults"),this.defaults={baseURL:e.baseURL,headers:{common:{}},timeout:e.timeout,retry:e.retry,retryDelay:e.retryDelay}}buildURL(e,i){const{baseURL:n}=this.defaults,r=e.startsWith("http")?e:`${n}${e.startsWith("/")?e:`/${e}`}`;if(i){const s=new URLSearchParams;return Object.entries(i).forEach(([o,c])=>{s.append(o,c)}),`${r}${r.includes("?")?"&":"?"}${s.toString()}`}return r}request(e){return u(this,null,function*(){var i;const n=((i=e.method)==null?void 0:i.toUpperCase())||"GET",r=this.buildURL(e.url||"",e.params),s=x(x({},this.defaults.headers.common),e.headers);n!=="GET"&&n!=="HEAD"&&e.data&&!s["Content-Type"]&&(s["Content-Type"]="application/json");const o=s["Content-Type"]==="application/json"?JSON.stringify(e.data):e.data,c={method:n,headers:s,body:n!=="GET"&&n!=="HEAD"&&e.data?o:void 0},d=e.timeout||this.defaults.timeout,l=e.retry!==void 0?e.retry:this.defaults.retry,p=e.retryDelay||this.defaults.retryDelay;try{const g=new AbortController,y=setTimeout(()=>g.abort(),d);c.signal=g.signal;const T=yield fetch(r,c);clearTimeout(y);let b=null;const N=T.headers.get("content-type");N&&N.includes("application/json")?b=yield T.json():b=yield T.text();const M={};T.headers.forEach((H,K)=>{M[K]=H});const F={data:b,status:T.status,statusText:T.statusText,headers:M,config:e};if(!T.ok)throw F;return F}catch(g){if(g instanceof Error&&l>0)return yield new Promise(y=>setTimeout(y,p)),this.defaults.baseURL==="https://api.dyte.io"?this.defaults.baseURL="https://api.cluster.dyte.in":this.defaults.baseURL==="https://api.cluster.dyte.in"&&(this.defaults.baseURL="https://api.dyte.io"),this.request(q(x({},e),{retry:l-1}));throw g}})}get(e){return u(this,arguments,function*(i,n={}){return this.request(q(x({},n),{method:"GET",url:i}))})}post(e,i){return u(this,arguments,function*(n,r,s={}){return this.request(q(x({},s),{method:"POST",url:n,data:r}))})}put(e,i){return u(this,arguments,function*(n,r,s={}){return this.request(q(x({},s),{method:"PUT",url:n,data:r}))})}}const lA=3,uA=30,hA=8e3;class pA{constructor(e,i){m(this,"ipInfo"),m(this,"fetchClient"),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=hA,retry:r=lA,retryDelay:s=uA,baseURL:o="https://api.dyte.io",authToken:c,cachedUserDetails:d}=i||{};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=new ff({baseURL:o,timeout:n,retry:r,retryDelay:s,responseType:"json"}),this.fetchClient=new ff({baseURL:"",timeout:n,retry:r,retryDelay:s,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=p=>u(this,null,function*(){var g,y,T,b,N;try{S.injectContext(this.requests.defaults.headers.common);const M=yield l(p);return p.url!==S.logsEndpoint&&h.debug("xhr::fetch",{networkCall:{status:M.status,statusText:M.statusText,baseURL:p.baseURL||this.requests.defaults.baseURL,url:p.url,method:p.method}}),M}catch(M){throw M?(((g=M.config)==null?void 0:g.url)!==S.logsEndpoint&&h.error("xhr::fetch",{error:M,networkCall:{status:M.status,statusText:M.statusText,baseURL:((y=M.config)==null?void 0:y.baseURL)||this.requests.defaults.baseURL,url:(T=M.config)==null?void 0:T.url,retries:(b=M.config)==null?void 0:b.retry,method:(N=M.config)==null?void 0:N.method,isOnline:navigator.onLine?"online":"offline"}}),new w(M.message||"Network request failed","0011")):new w("Unknown network error occurred","0011")}})}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,i){const{bearer:n}=i||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,i){this.requests.defaults.headers.common[e]=i}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var mA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,ei=(t,e,i,n)=>{for(var r=n>1?void 0:n?gA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&mA(e,i,r),r};class Bt extends pA{constructor(e,i){super(e,i),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:i}=this;try{const n=yield Cl.getIPDetails({peerId:i,apiHostnames:bg(this.context),logger:h});if(h.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){h.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:i}=(yield this.requests.get("/iceservers")).data;if(e)return(i==null?void 0:i.length)>0&&(this.iceServers=i),i})}getPlugins(){return u(this,null,function*(){var e,i,n,r,s,o,c;if(this.pluginInformation)return this.pluginInformation;const{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data,l=((i=(e=Q.getValue(ne.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:i.split(","))||[],p=d.reduce((g,y)=>(g[l.includes(y.id)?"v1":"v2"].push(q(x({},y),{name:y.name.replace("v2","")})),g),{v1:[],v2:[]});return(s=(r=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:r.plugins)!=null&&s.length&&((c=(o=this.context.getValue("modules"))==null?void 0:o.devTools)==null||c.plugins.forEach(g=>{var y,T,b;const N=q(x({},Zs),{tags:[...Zs.tags],baseUrl:`http://localhost:${g.port}`,name:g.name,picture:(y=g.picture)!=null?y:Zs.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:g.id,organizationId:this.organizationId,description:(T=g.description)!=null?T:Zs.description,staggered:(b=g.staggered)!=null?b:Zs.staggered});p.v2.push(N)})),p.v2})}getPluginDetails(e){return u(this,null,function*(){const{plugin:i}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return i})}getPluginConfig(e){return u(this,null,function*(){return(yield this.fetchClient.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const i={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,i)).data.data;return n})}getPresignedUrls(e,i){return u(this,null,function*(){const n=Mc(this.context,"chat_upload_expiry"),r={roomUUID:this.roomUUID,filename:e,expiry:typeof n=="number"?n:void 0};Q.hasFeature(ne.FEAT_CHAT_SDK)&&(r.viewType=i);const{getLocation:s,putLocation:o}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",r)).data.data;return{getLocation:s,putLocation:o}})}uploadFile(e,i){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){h.error(`sendFileMessage::${n}`)}else yield this.fetchClient.put(i,e,{headers:{"Content-Type":e.type}})})}startLivestreaming(e){return u(this,arguments,function*({manualIngestion:i}){const n=hi(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!i})).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=hi((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 hi(e)})}startRecording(e,i){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",q(x({},gf(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!i}))).data.data.id})}updateRecording(e,i){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:i})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:i}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:i}})}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.fetchClient.get(e)).data}}catch(i){throw new w("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:i,title:n,useHiveMedia:r,sfu:s}=hi((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:i,meetingTitle:n,useHiveMedia:r!=null?r:!1,sfu:s}})}}ei([S.trace("APIClient.getIPDetails")],Bt.prototype,"getIPDetails",1),ei([S.trace("APIClient.getICEServers")],Bt.prototype,"getICEServers",1),ei([S.trace("APIClient.getPlugins")],Bt.prototype,"getPlugins",1),ei([S.trace("APIClient.startLivestreaming")],Bt.prototype,"startLivestreaming",1),ei([S.trace("APIClient.stopLivestreaming")],Bt.prototype,"stopLivestreaming",1),ei([S.trace("APIClient.getActiveLivestream")],Bt.prototype,"getActiveLivestream",1),ei([S.trace("APIClient.getUserDetails")],Bt.prototype,"getUserDetails",1),ei([S.trace("APIClient.startRecording")],Bt.prototype,"startRecording",1),ei([S.trace("APIClient.stopRecording")],Bt.prototype,"updateRecording",1),ei([S.trace("APIClient.getActiveRecording")],Bt.prototype,"getActiveRecording",1),ei([S.trace("APIClient.getActiveTranscript")],Bt.prototype,"getActiveTranscript",1),ei([S.trace("APIClient.getRoomNodeData")],Bt.prototype,"getRoomNodeData",1);let yu;function fA(t,e){return yu=new Bt(t,e),yu}function at(){return yu}function vA(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
14
+ ${t}`}const Qr={maxInvocations:5,period:1};function Dt(t,e){return function(i,n,r){const s=r.value;let o=0,c=Date.now();return r.value=function(...d){const l=Date.now(),p=e?this[e]:t;if(l-c>p.period*1e3&&(c=l,o=0),o>=p.maxInvocations)throw new w(`Method rate limit ${p.maxInvocations} invocations/${p.period}sec exceeded`,"0013");return o+=1,s.apply(this,d)},r}}var yA=Object.defineProperty,SA=Object.getOwnPropertyDescriptor,ht=(t,e,i,n)=>{for(var r=n>1?void 0:n?SA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&yA(e,i,r),r};const EA=["text","image","file","custom","poll"],jc={maxInvocations:180,period:60};var se,Xr,Ke,Zr,Hc,Su,vf,Gc,Eu,yf;let Xe=(yf=class extends Ft{constructor(t,e,i,n,r){super(),f(this,Su),f(this,Gc),m(this,"messages"),m(this,"channels",[]),f(this,se,void 0),f(this,Xr,void 0),f(this,Ke,void 0),f(this,Zr,void 0),f(this,Hc,void 0),m(this,"maxTextLimit",2e3),v(this,Hc,t),v(this,Ke,e),v(this,Zr,i),v(this,se,n),v(this,Xr,r),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,i){return u(this,arguments,function*(n,r,s,o={}){switch(n.type){case"text":{const c=o.replyTo&&o.replyTo.type==="text"?vA(n.message,o.replyTo.message):n.message;yield this.sendTextMessageInternal(c,r,s);break}case"image":yield this.sendImageMessageInternal(n.image,r,s);break;case"file":yield this.sendFileMessageInternal(n.file,r,s);break;default:h.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,i){return u(this,null,function*(){var n,r,s,o,c,d;if(t.length>this.maxTextLimit)throw new w("Max character limit breached","0503");if(e&&e.length>0){if(!((n=a(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((r=a(this,se).permissions)!=null&&r.chatPrivate.text))throw h.error("sendTextMessage::private_chat_permission_denied"),new w("Could not send message to private chat.","0501")}else if(!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.text))throw h.error("sendTextMessage::public_chat_permission_denied"),new w("Could not send message to public chat.","0501");if(!t)throw h.error("sendTextMessage::message_can_not_be_empty"),new w("Message can not be empty.","0502");if(i){a(this,Ke).sendMessageToChannel(t,Et.TEXT,i);return}let l=[];e&&e.length>0&&(e.push(a(this,se).id),l=a(this,Xr).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),l.push(a(this,se).userId)),a(this,Ke).sendMessage(t,Et.TEXT,e)})}sendImageMessageInternal(t,e,i){return u(this,null,function*(){var n,r,s,o,c,d;if(e&&e.length>0){if(!((n=a(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((r=a(this,se).permissions)!=null&&r.chatPrivate.files)){h.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){h.error("sendImageMessage::permission_denied");return}if(!t){h.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){h.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const l=at(),{getLocation:p,putLocation:g}=yield l.getPresignedUrls(t.name,a(this,se).config.viewType);if(yield l.uploadFile(t,g),i){a(this,Ke).sendMessageToChannel(p,Et.IMAGE,i);return}let y=[];e&&e.length>0&&(e.push(a(this,se).id),y=a(this,Xr).joined.toArray().filter(T=>e.includes(T.id)).map(T=>T.userId),y.push(a(this,se).userId)),a(this,Ke).sendMessage(p,Et.IMAGE,e)}catch(l){throw new w("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,i){return u(this,null,function*(){var n,r,s,o,c,d;if(e&&e.length>0){if(!((n=a(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((r=a(this,se).permissions)!=null&&r.chatPrivate.files)){h.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){h.error("sendFileMessage::permission_denied");return}if(!t){h.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=at(),{getLocation:p,putLocation:g}=yield l.getPresignedUrls(t.name,a(this,se).config.viewType);if(yield l.uploadFile(t,g),i){a(this,Ke).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),Et.FILE,i);return}let y=[];e&&e.length>0&&(e.push(a(this,se).id),y=a(this,Xr).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),y.push(a(this,se).userId));const T=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});a(this,Ke).sendMessage(T,Et.FILE,e)}catch(l){throw new w("Error sending file message.","0500")}})}get rateLimits(){return jc}updateRateLimits(t,e){jc.maxInvocations=t,jc.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var i,n,r,s,o,c,d,l,p,g,y,T,b,N,M;if(e&&e.length>0){if(!((i=a(this,se).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,se).permissions)!=null&&n.chatPrivate.files)||!((r=a(this,se).permissions)!=null&&r.chatPrivate.text)){h.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((p=(l=a(this,se).permissions)==null?void 0:l.chatPublic)!=null&&p.text)){h.error("sendCustomMessage::permission_denied");return}const F=K=>u(this,null,function*(){try{if(typeof K=="string")return{link:K};const I=at(),{getLocation:re,putLocation:ae}=yield I.getPresignedUrls(K.name,a(this,se).config.viewType);return yield I.uploadFile(K,ae),{link:re,type:K.type,name:K.name,size:K.size}}catch(I){throw new w("Error sending image message.","0500")}}),H=q(x({},t),{files:yield Promise.all((y=(g=t.files)!=null?g:[])==null?void 0:y.map(K=>u(this,null,function*(){return F(K)}))),images:yield Promise.all((b=(T=t.images)!=null?T:[])==null?void 0:b.map(K=>u(this,null,function*(){return F(K)}))),videos:yield Promise.all((M=(N=t.videos)!=null?N:[])==null?void 0:M.map(K=>u(this,null,function*(){return F(K)})))});a(this,Ke).sendMessage(JSON.stringify(H),Et.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,i){return u(this,null,function*(){var n,r,s,o,c,d;if(((r=(n=a(this,se).permissions)==null?void 0:n.chatMessage)==null?void 0:r.canEdit)==="NONE")throw new w("Not permitted to edit messages","0501");if(!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.text)){h.error("editTextMessage::permission_denied");return}if(!e){h.error("editTextMessage::message_can_not_be_empty");return}a(this,Ke).editMessage(t,e,Et.TEXT,i)})}editImageMessage(t,e,i){return u(this,null,function*(){var n,r,s,o;if(!((r=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&r.canSend)||!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){h.error("editImageMessage::permission_denied");return}if(!e){h.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){h.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const c=at(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,se).config.viewType);yield c.uploadFile(e,l),a(this,Ke).editMessage(t,d,Et.IMAGE,i)}catch(c){throw new w("Error editing image message.","0500")}})}editFileMessage(t,e,i){return u(this,null,function*(){var n,r,s,o;if(!((r=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&r.canSend)||!((o=(s=a(this,se).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){h.error("sendFileMessage::permission_denied");return}if(!e){h.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=at(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,se).config.viewType);yield c.uploadFile(e,l),a(this,Ke).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Et.FILE,i)}catch(c){throw new w("Error editing file message.","0500")}})}editMessage(t,e,i){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,i);break}case"image":{this.editImageMessage(t,e.image,i);break}case"file":{this.editFileMessage(t,e.file,i);break}default:{h.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var i,n;if(((n=(i=a(this,se).permissions)==null?void 0:i.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new w("Not permitted to delete messages","0501");a(this,Ke).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(!a(this,Gc,Eu))throw new w("Can`t pin message without joining room","0505");if(!a(this,se).permissions.pinParticipant)throw new w("You do not have permission to pin messages.","0501");const e=this.messages.find(i=>i.id===t);if(e){a(this,Ke).setPinState(e,!0);return}throw new w(`No message found with id: ${t}`,"0504")})}unpin(t){return u(this,null,function*(){if(!a(this,Gc,Eu))throw new w("Can`t unpin message without joining room","0505");if(!a(this,se).permissions.pinParticipant)throw new w("You do not have permission to unpin messages.","0501");const e=this.messages.find(i=>i.id===t);if(e){a(this,Ke).setPinState(e,!1);return}throw new w(`No message found with id: ${t}`,"0504")})}getMessages(t,e,i,n=0,r=void 0){return u(this,null,function*(){const s=yield a(this,Ke).getChatMessagesPaginated(t,e,i,n,r);return{messages:s.messages.map(o=>zi.formatSocketServiceMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(i,n,r={}){var s;const o=(s=a(this,se).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new w("Not permitted to create channels","0501");if(r.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new w("Not permitted to create public channels","0501");if(r.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new w("Not permitted to create private channels","0501")}if(!i||i.trim().length===0)throw new w("channel name cannot be empty.","0510");const c=[...new Set([...n,a(this,se).userId])];return yield a(this,Zr).createChannel(i.trim(),c,r.displayPictureUrl,r.visibility,r.isDirectMessage)})}updateChannel(t,e){var i,n,r,s,o;const c=this.channels.find(p=>p.id===t),d=(i=a(this,se).permissions)==null?void 0:i.chatChannel;if(d){if(d.canUpdate==="NONE")throw new w("Not permitted to update channels","0501");if(c.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new w("Not permitted to update public channels","0501");if(c.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new w("Not permitted to update private channels","0501")}const l={memberIds:(n=e.memberIds)!=null?n:c.memberIds,displayName:(r=e.displayName)!=null?r:c.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:c.displayPictureUrl,visibility:(o=e.visibility)!=null?o:c.visibility};return a(this,Zr).updateChannel(t,l)}sendMessageToChannel(t,e){return u(this,arguments,function*(i,n,r={}){return this.sendMessageInternal(i,null,n,r)})}getChannelMembers(t){return u(this,null,function*(){return a(this,Zr).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,i={}){if(!Q.hasFeature(ne.FEAT_CHAT_SDK_SEARCH))throw new w("searchMessages is temporarily disabled!","0506");return(yield a(this,Ke).searchMessages(e,i)).map(zi.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield a(this,Ke).markLastReadMessage(t,e);const i=this.channels.find(n=>n.id===t);if(i){const n=q(x({},i),{unreadCount:0});this.channels=this.channels.map(r=>r.id===t?n:r),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},se=new WeakMap,Xr=new WeakMap,Ke=new WeakMap,Zr=new WeakMap,Hc=new WeakMap,Su=new WeakSet,vf=function(){return a(this,Hc).getValue("connectionHandler")},Gc=new WeakSet,Eu=function(){return a(this,Su,vf).socketJoined===!0},yf);ht([S.trace("DyteChat.sendTextMessage"),Dt(jc)],Xe.prototype,"sendTextMessage",1),ht([S.trace("DyteChat.sendImageMessage"),Dt({maxInvocations:20,period:60})],Xe.prototype,"sendImageMessage",1),ht([S.trace("DyteChat.sendFileMessage"),Dt({maxInvocations:20,period:60})],Xe.prototype,"sendFileMessage",1),ht([S.trace("DyteChat.sendMessage"),Dt({maxInvocations:180,period:60})],Xe.prototype,"sendMessage",1),ht([S.trace("DyteChat.editTextMessage")],Xe.prototype,"editTextMessage",1),ht([S.trace("DyteChat.editImageMessage")],Xe.prototype,"editImageMessage",1),ht([S.trace("DyteChat.editFileMessage")],Xe.prototype,"editFileMessage",1),ht([S.trace("DyteChat.editMessage")],Xe.prototype,"editMessage",1),ht([S.trace("DyteChat.deleteMessage")],Xe.prototype,"deleteMessage",1),ht([S.trace("DyteChat.createChannel")],Xe.prototype,"createChannel",1),ht([S.trace("DyteChat.updateChannel")],Xe.prototype,"updateChannel",1),ht([S.trace("DyteChat.sendMessageToChannel")],Xe.prototype,"sendMessageToChannel",1),ht([S.trace("DyteChat.getChannelMembers")],Xe.prototype,"getChannelMembers",1),ht([S.trace("DyteChat.searchMessages")],Xe.prototype,"searchMessages",1),ht([S.trace("DyteChat.markLastReadMessage")],Xe.prototype,"markLastReadMessage",1),Xe=ht([ut("0500")],Xe);var TA=Object.defineProperty,kA=Object.getOwnPropertyDescriptor,bA=(t,e,i,n)=>{for(var r=n>1?void 0:n?kA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&TA(e,i,r),r},Tu,Sf;const sr=(Sf=class{constructor(t,e,i,n,r){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),f(this,Tu,void 0),v(this,Tu,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=i,this.chat=new Xe(t,e,i,n,r),this.self=n,this.setupEvents()}static init(t,e,i,n,r){return u(this,null,function*(){return new sr(t,e,i,n,r)})}static formatMessage(t){return q(x({},t),{time:new Date(t.time),type:EA[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,i={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(i.type){case Et.TEXT:{i.message=t.payload;break}case Et.IMAGE:{i.link=t.payload;break}case Et.FILE:{const{link:n,name:r,size:s}=JSON.parse(t.payload);i.link=n,i.name=r,i.size=s;break}case Et.CUSTOM:{const{html:n,images:r,message:s,videos:o,files:c}=JSON.parse(t.payload);i.message=s,i.html=n,i.images=r,i.videos=o,i.files=c;break}}return sr.formatMessage(i)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||Q.hasFeature(ne.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=tf.fromBinary(t.payload).messages;this.chat.messages=e.map(i=>sr.formatSocketServiceMessage(i))})}setupEvents(){P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Me.sendMessageToRoom,t=>{const e=sr.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const i=this.chat.channels.find(n=>n.id===e.channelId);i&&(i.latestMessage=e,i.unreadCount+=1,this.chat.emit("channelMessageUpdate",i))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Me.sendMessageToPeers,t=>{const e=sr.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(Me.editMessage,t=>{const e=sr.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const i=this.chat.messages.findIndex(n=>n.id===e.id);i!==-1&&(this.chat.messages[i]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Me.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[i]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:i,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ir.createChatChannel,t=>{const[e]=t.chatChannels,i=rr.formatChannel(e);this.chat.channels.push(i),this.chat.emit("channelCreate",i)}),this.chatSocketHandler.on(Me.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const i=this.chat.messages[e];i.pinned=t.pinned,this.chat.messages[e]=i,this.chat.emit("chatUpdate",{action:"edit",message:i,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ir.updateChatChannel,t=>{const[e]=t.chatChannels,i=rr.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===i.id?i:n),this.chat.emit("channelUpdate",i)})}},Tu=new WeakMap,Sf);let zi=sr;bA([S.trace("ChatController.setupEvents")],zi.prototype,"setupEvents",1);var _A=Object.defineProperty,wA=Object.getOwnPropertyDescriptor,IA=(t,e,i,n)=>{for(var r=n>1?void 0:n?wA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&_A(e,i,r),r},ku,Ef,bu,Tf,aa,oa,qc,kf;let _u=(kf=class extends Ft{constructor(t,e,i){super(),f(this,ku),f(this,bu),m(this,"items"),f(this,aa,void 0),f(this,oa,void 0),f(this,qc,void 0),v(this,qc,t),v(this,aa,e),v(this,oa,i),this.items=[]}create(t,e,i=!1,n=!1){return u(this,null,function*(){if(!a(this,bu,Tf))throw new w("Can't create polls without joining room","0705");if(!a(this,aa).permissions.polls.canCreate){h.error("DytePolls::create::permission_denied");return}if(!t||!e){h.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){h.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield a(this,oa).createPoll(t,e,i,n)})}vote(t,e){return u(this,null,function*(){if(!a(this,aa).permissions.polls.canVote){h.error("DytePolls::vote::permission_denied");return}yield a(this,oa).votePoll(t,e)})}},ku=new WeakSet,Ef=function(){return a(this,qc).getValue("connectionHandler")},bu=new WeakSet,Tf=function(){var t;return((t=a(this,ku,Ef))==null?void 0:t.socketJoined)===!0},aa=new WeakMap,oa=new WeakMap,qc=new WeakMap,kf);_u=IA([ut("0700")],_u);var CA=Object.defineProperty,PA=Object.getOwnPropertyDescriptor,RA=(t,e,i,n)=>{for(var r=n>1?void 0:n?PA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&CA(e,i,r),r},ca,es,bf;const ts=(bf=class{constructor(t,e,i){m(this,"polls"),f(this,ca,void 0),f(this,es,void 0),this.polls=new _u(t,e,i),v(this,ca,e),v(this,es,i),this.setupEvents()}static init(t,e,i){return u(this,null,function*(){return new ts(t,e,i)})}canViewPolls(){return a(this,ca).permissions.polls.canView}setupEvents(){const t={[Ki.createPoll]:n=>{n.poll&&this.updatePoll(ts.formatSocketServicePoll(n.poll))},[Ki.updatePoll]:n=>{n.poll&&this.updatePoll(ts.formatSocketServicePoll(n.poll))},[Ki.votePoll]:n=>{n.poll&&this.updatePoll(ts.formatSocketServicePoll(n.poll))}},e=()=>{P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{a(this,es).on(n,t[n])})},i=()=>{P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(n=>{a(this,es).removeListeners(n)})};a(this,ca).permissions.on("permissionsUpdate",n=>u(this,null,function*(){var r;(r=n==null?void 0:n.polls)!=null&&r.canView?(yield this.getPolls(),e()):(this.polls.items=[],i())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(i=>i.id===t.id);if(e>-1){const i=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,i!==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 a(this,es).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=BM.fromBinary(t.payload);this.polls.items=e.map(i=>ts.formatSocketServicePoll(i))})}static formatSocketServicePoll(t){const e=t.options.map(i=>({count:i.count,text:i.text,votes:i.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}}},ca=new WeakMap,es=new WeakMap,bf);let _f=ts;RA([S.trace("PollController.setupEvents")],_f.prototype,"setupEvents",1);var MA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,DA=(t,e,i,n)=>{for(var r=n>1?void 0:n?AA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&MA(e,i,r),r},wf=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(wf||{}),da,Jc,wu,is,$c,If;let Iu=(If=class extends Ft{constructor(t,e,i,n,r){super(),f(this,Jc),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),f(this,da,void 0),f(this,is,void 0),f(this,$c,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),v(this,da,t),v(this,is,e),this.viewType=i,v(this,$c,n),this.meetingTitle=r,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Jc,wu).socketState}get mediaState(){return a(this,Jc,wu).mediaState}get meetingId(){return a(this,da).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,is).permissions.canSpotlight)throw h.error("DyteSpotlight::setSpotlighted::permission_denied"),new w("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 i;h.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(i=a(this,is).permissions)!=null&&i.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,$c).broadcastMessage("spotlight",{userId:a(this,is).userId,currentTab:this.selfActiveTab})}},da=new WeakMap,Jc=new WeakSet,wu=function(){return a(this,da).getValue("connectionHandler")},is=new WeakMap,$c=new WeakMap,If);Iu=DA([ut("0800")],Iu);function OA(t){let e="",i=[""];const n=[i];let r=0,s=0,o=!0,c;for(c of t)c==='"'?(o&&c===e&&(i[r]+=c),o=!o):c===","&&o?c=i[++r]="":c===`
15
+ `&&o?(e==="\r"&&(i[r]=i[r].slice(0,-1)),i=n[++s]=[c=""],r=0):i[r]+=c,e=c;return n}var NA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Cf=(t,e,i,n)=>{for(var r=n>1?void 0:n?LA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&NA(e,i,r),r};let yn=class extends Ft{constructor(){super(),m(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new yn;try{t&&e.getActiveTranscript()}catch(i){h.error("Error fetching active transcriptions ",i)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[i,n,r,s,o,c]]=OA(t);return{id:Br(),name:o,peerId:n,userId:r,customParticipantId:s,transcript:c,isPartialTranscript:e,date:new Date(parseInt(i,10)*1e3)}}catch(i){h.error(`Failed to parse transcript: ${t}`,i);return}}static parseTranscripts(t){return t?t.split(`
16
+ `).map(e=>yn.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=at(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=yn.parseTranscripts(e)}catch(t){}})}onTranscript(t){return u(this,null,function*(){var e;const i=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=i==null?void 0:i.at(-1))!=null&&e.isPartialTranscript){const n=i.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};Cf([S.trace("DyteAi.getActiveTranscript")],yn.prototype,"getActiveTranscript",1),yn=Cf([ut("0000")],yn);var xA=Object.defineProperty,VA=Object.getOwnPropertyDescriptor,UA=(t,e,i,n)=>{for(var r=n>1?void 0:n?VA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&xA(e,i,r),r},ar,la,Cu,Pf;const Rf=(Pf=class{constructor(t,e,i,n,r,s){m(this,"meta"),m(this,"ai"),f(this,ar,void 0),f(this,la,void 0),m(this,"aiSocketHandler"),f(this,Cu,void 0),v(this,Cu,t),this.meta=new Iu(t,e,e.config.viewType,i,s),this.ai=n,v(this,ar,e),v(this,la,i),this.aiSocketHandler=r,e.config.viewType!==yt.Chat&&this.setupEvents()}static init(t,e,i,n,r){return u(this,null,function*(){const s=yield yn.init(e.permissions.transcriptionEnabled);return new Rf(t,e,i,s,n,r)})}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,wf.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){P.on(R.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),P.on(R.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),P.on(R.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const i=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!i){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),P.on(R.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),a(this,ar).permissions.canSpotlight&&(h.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,la).broadcastMessage("spotlight",{userId:a(this,ar).userId,currentTab:this.meta.selfActiveTab})),P.on(R.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){a(this,ar).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,la).broadcastToPeers("spotlight",[t.id],{userId:a(this,ar).userId,currentTab:this.meta.selfActiveTab})})),P.on(R.ROOM_MESSAGE,t=>{var e,i;let n;if("type"in t){if(t.type!=="spotlight")return;n=x(x({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;h.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(i=n.currentTab)==null?void 0:i.type}}}),this.conditionallySetActiveTab(n)}),P.on(R.MESSAGE,t=>{var e,i;let n;if("type"in t){if(t.type!=="spotlight")return;n=x(x({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;h.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(i=n.currentTab)==null?void 0:i.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(B.transcript,t=>{const{meetingId:e,transcript:i,isPartial:n}=t,r=yn.parseTranscript(i,n);if(!r){h.warn("Received empty transcript data");return}this.ai.onTranscript(r),this.meta.emit("transcript",r);const{peerId:s,name:o,transcript:c}=r;h.debug(`${e} Received transcript for peer ${s} - ${o}: ${c}`)})}},ar=new WeakMap,la=new WeakMap,Cu=new WeakMap,Pf);let Mf=Rf;UA([S.trace("MetaController.setupEvents")],Mf.prototype,"setupEvents",1);var FA=Object.defineProperty,BA=Object.getOwnPropertyDescriptor,or=(t,e,i,n)=>{for(var r=n>1?void 0:n?BA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&FA(e,i,r),r},pi,ua,he,Kc,Yi,Di,zc,Pu,ha,Yc;class Sn extends Ft{constructor(e,i,n,r,s){super(),f(this,zc),f(this,ha),f(this,pi,void 0),f(this,ua,void 0),f(this,he,void 0),f(this,Kc,void 0),f(this,Yi,void 0),f(this,Di,void 0),v(this,Di,e),v(this,pi,r),v(this,ua,s),v(this,he,i),v(this,Kc,n),v(this,Yi,[]),this.setupEvents()}get status(){return a(this,Di).getValue("stageStatus")}setupEvents(){const e={[R.GET_STAGE_REQUESTS]:r=>u(this,null,function*(){v(this,Yi,r)}),[R.UPDATE_STAGE_REQUESTS]:r=>u(this,[r],function*({add:s}){const o=a(this,Yi).length,{stageRequests:c}=this.getAccessRequests();(s||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},i=()=>{Object.entries(e).forEach(([r,s])=>{P.onAsync(r,s)})},n=()=>{Object.entries(e).forEach(([r,s])=>{P.removeListener(r,s)})};a(this,he).permissions.on("permissionsUpdate",r=>{const{canAcceptProductionRequests:s}=r;s!==void 0&&(a(this,he).permissions.acceptStageRequests?(i(),a(this,pi).getStageRequests()):(n(),v(this,Yi,[]),this.emit("stageAccessRequestUpdate",a(this,Yi))))}),a(this,he).permissions.acceptStageRequests&&i()}getAccessRequests(){if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,he).permissions.acceptStageRequests)throw h.error("DyteStage::get_access_request::permission_denied"),new w("You do not have permission to perform this action","2001");const e=a(this,Kc).joined.toArray().filter(i=>i.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(i=>({displayName:i.name,userId:i.userId,peerId:i.id}));return v(this,Yi,e),{stageRequests:a(this,Yi)}}requestAccess(){return u(this,null,function*(){if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new w(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,he).permissions.stageAccess===Y.Allowed){j(this,ha,Yc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,pi).requestAccess(),j(this,ha,Yc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");a(this,pi).cancelRequestAccess(),j(this,ha,Yc).call(this,"OFF_STAGE")})}grantAccess(e){if(!a(this,he).roomJoined)throw new w("Can`t grant for participant without joining room");if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,he).permissions.acceptStageRequests)throw h.error("DyteStage::grant_access::permission_denied"),new w("You do not have permission to perform this action","2001");return a(this,pi).grantAccess(e)}denyAccess(e){if(!a(this,he).roomJoined)throw new w("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,he).permissions.acceptStageRequests)throw h.error("DyteStage::deny_access::permission_denied"),new w("You do not have permission to perform this action","2001");return a(this,pi).denyAccess(e)}join(){return u(this,null,function*(){const e=a(this,Di).getValue("viewType");if(this.status==="ON_STAGE")throw new w("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,he).permissions.stageAccess===Y.NotAllowed)throw new w(`Unable to join stage you are currently ${this.status}`,"2006");if(yield a(this,pi).joinStage(),e===yt.Livestream){yield a(this,ua).joinRoom(a(this,he));const{peers:i}=yield a(this,ua).getStagePeers();P.emit(R.SOCKET_PEERS,i)}a(this,Di).setValue("stageStatus","ON_STAGE"),a(this,he).audioEnabled&&a(this,zc,Pu).shareMic(a(this,he).audioTrack),a(this,he).videoEnabled&&a(this,zc,Pu).shareWebcam(a(this,he).videoTrack)})}leave(){return u(this,null,function*(){if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new w(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,he).setIsPinned(!1),yield a(this,pi).leaveStage(a(this,he).userId),a(this,Di).setValue("stageStatus","OFF_STAGE",!1),yield P.emitAsync(R.LEAVE_MEDIA_ROOM,"stageLeft"),a(this,Di).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!a(this,he).roomJoined)throw new w("Can`t kick participant without joining room","2005");if(!a(this,he).permissions.stageEnabled)throw h.error("DyteStage::stage_disabled"),new w("Stage is disabled","2003");if(!a(this,he).permissions.acceptStageRequests)throw h.error("DyteStage::kick::permission_denied"),new w("You do not have permissions for kick","2001");return a(this,pi).kick(e)})}}pi=new WeakMap,ua=new WeakMap,he=new WeakMap,Kc=new WeakMap,Yi=new WeakMap,Di=new WeakMap,zc=new WeakSet,Pu=function(){return a(this,Di).getValue("roomNodeClient")},ha=new WeakSet,Yc=function(t){return u(this,null,function*(){this.status!==t&&a(this,Di).setValue("stageStatus",t)})},or([S.trace("DyteStage.getStageRequests")],Sn.prototype,"getAccessRequests",1),or([S.trace("DyteStage.requestAccess")],Sn.prototype,"requestAccess",1),or([S.trace("DyteStage.cancelRequestAccess")],Sn.prototype,"cancelRequestAccess",1),or([S.trace("DyteStage.grantAccess")],Sn.prototype,"grantAccess",1),or([S.trace("DyteStage.denyAccess")],Sn.prototype,"denyAccess",1),or([S.trace("DyteStage.joinStage")],Sn.prototype,"join",1),or([S.trace("DyteStage.leaveStage")],Sn.prototype,"leave",1);function WA(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Ru(t){switch(t){case Ji.UNSPECIFIED:return"OFF_STAGE";case Ji.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Ji.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Ji.OFF_STAGE:return"OFF_STAGE";case Ji.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var jA=Object.defineProperty,HA=Object.getOwnPropertyDescriptor,GA=(t,e,i,n)=>{for(var r=n>1?void 0:n?HA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&jA(e,i,r),r},cr,ns,dr,Qc,En;class Af{constructor(e,i,n,r,s){m(this,"stage"),f(this,cr,void 0),f(this,ns,void 0),f(this,dr,void 0),f(this,Qc,0),f(this,En,void 0),v(this,En,e),this.stage=new Sn(e,r,s,i,n),v(this,dr,i),v(this,cr,r),v(this,ns,s),this.setupEvents()}setupEvents(){a(this,En).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),a(this,dr).on(B.grantStageAccess,()=>{a(this,cr).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,dr).on(B.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===a(this,cr).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),a(this,dr).on(B.denyStageAccess,()=>{a(this,cr).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,dr).on(B.getStageRequests,e=>u(this,null,function*(){var i;if(a(this,cr).permissions.stageAccess!==Y.Allowed)return;const n=(i=e==null?void 0:e.stageRequests)!=null?i:[];yield P.emitAsync(R.GET_STAGE_REQUESTS,n),a(this,Qc)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),v(this,Qc,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return a(this,ns).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&&a(this,En).setValue("stageStatus",e)})}selfStageStatusHandler(e){const i=Ru(e.stageType),n=a(this,En).getValue("stageStatus");if(n!==i)switch(e.stageType){case 1:a(this,En).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:a(this,En).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const i=a(this,ns).joined.get(e.peerId),n=a(this,ns).viewMode==="ACTIVE_GRID";if(!i){h.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:i.setStageStatus("ON_STAGE"),n&&P.emit(R.UPDATE_ACTIVE);break;case 2:i.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:i.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:i.setStageStatus("OFF_STAGE"),n&&P.emit(R.UPDATE_ACTIVE);break}P.emit(R.UPDATE_PEER_STAGE_STATUS,{id:i.id,status:i.stageStatus})})}}cr=new WeakMap,ns=new WeakMap,dr=new WeakMap,Qc=new WeakMap,En=new WeakMap,GA([S.trace("DyteStage.setupEvents")],Af.prototype,"setupEvents",1);var qA=Object.defineProperty,JA=Object.getOwnPropertyDescriptor,Xc=(t,e,i,n)=>{for(var r=n>1?void 0:n?JA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&qA(e,i,r),r};const Ne={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,ti,pa,ma,Tn,ga,rs,fa,Df;let ss=(Df=class extends Kr{constructor(t,{baseURL:e,createdAt:i,description:n,id:r,name:s,organizationId:o,picture:c,private:d,published:l,staggered:p,tags:g,type:y,updatedAt:T},b,N,M,F,H){super(),f(this,kt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),f(this,ti,void 0),f(this,pa,void 0),f(this,ma,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"),f(this,Tn,void 0),m(this,"config"),f(this,ga,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),f(this,rs,void 0),f(this,fa,void 0),v(this,rs,t),this.baseURL=e,this.createdAt=new Date(i),this.description=n,this.id=r,this.name=s,v(this,ti,N),this.organizationId=o,this.picture=c,this.private=d,this.published=l,this.staggered=p,this.tags=g,this.type=y,this.updatedAt=new Date(T),this.active=!1,this.iframes=new Map,v(this,kt,b),v(this,pa,M),v(this,ma,F),this.enabledBy="",v(this,fa,H)}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:i}=e;i&&(navigator.isReactNative?i.postMessage(JSON.stringify(t)):i.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const i=t,{payload:n,uuid:r,type:s}=i;switch(s){case z.customPluginEventToRoom:{a(this,kt).customPluginEventToRoom(this.id,n,r);break}case z.customPluginEventToPeers:{a(this,kt).customPluginEventToPeers(this.id,n.peerIds,n,r);break}case z.enablePluginForRoom:{a(this,kt).enablePluginForRoom(this.id,r);break}case z.enablePluginForPeers:{a(this,kt).enablePluginForPeers(this.id,n.peerIds,r);break}case z.disablePluginForRoom:{a(this,kt).disablePluginForRoom(this.id,r);break}case z.disablePluginForPeers:{a(this,kt).disablePluginForPeers(this.id,n.peerIds,r);break}case z.storeInsertKeys:{a(this,kt).storeInsertKeys(this.id,n.store,n.insertKeys,r);break}case z.storeGetKeys:{a(this,kt).storeGetKeys(this.id,n.store,n.getKeys,r);break}case z.storeDeleteKeys:{a(this,kt).storeDeleteKeys(this.id,n.store,n.deleteKeys,r);break}case z.storeDelete:{a(this,kt).storeDelete(this.id,n.store,r);break}case Ne.chatMessage:{const{messagePayload:o,peerIds:c}=n;if(!a(this,ma)){this.sendIframeEvent({type:Ne.chatMessage,uuid:i.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield a(this,ma).sendMessage(o,c),this.sendIframeEvent({type:Ne.chatMessage,uuid:i.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ne.chatMessage,uuid:i.uuid,payload:{error:d}})}break}case Ne.getPeer:{let o;const{peerId:c}=n,d=q(x({},a(this,ti)),{id:a(this,ti).id,isRecorder:(e=a(this,ti).permissions)==null?void 0:e.isRecorder,isHidden:a(this,ti).permissions.hiddenParticipant,stageStatus:a(this,ti).stageStatus});c?(o=a(this,pa).joined.get(n.peerId),a(this,ti).id===c&&(o=d)):o=d,this.sendIframeEvent({type:Ne.getPeer,payload:{peer:o&&Wc(o)},uuid:i.uuid});break}case Ne.getPeers:{const o=a(this,pa).joined.toArray().map(c=>Wc(c));this.sendIframeEvent({type:Ne.getPeers,payload:{peers:o},uuid:i.uuid});break}case Ne.getPluginInitiator:{this.sendIframeEvent({type:Ne.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:i.uuid});break}case Ne.getDisplayTitle:{this.sendIframeEvent({type:Ne.getDisplayTitle,payload:{displayTitle:a(this,fa)},uuid:i.uuid});break}case Ne.getRoomName:{this.sendIframeEvent({type:Ne.getRoomName,payload:{roomName:a(this,rs).getValue("meetingId")},uuid:i.uuid});break}case Ne.customPluginEventToParent:{this.emit(i.payload.eventName,i.payload.data);break}}})}sendData(t){this.active&&(h.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ne.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:i,listener:n}=(e=this.iframes.get(t))!=null?e:{};(i||n)&&(navigator.isReactNative?i.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var i;if(!a(this,ga))throw h.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new w("No auth token set for plugin.","0602");if(!t)throw h.error("DytePlugin::addPluginView::iframe_was_not_provided"),new w("Iframe was not provided.","0603");this.removePluginView(e);const n=t,r=new URL(this.baseURL),s={auth:a(this,ga),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,rs).getValue("apiBase"),pluginId:this.id,roomName:(i=a(this,rs).getValue("meetingId"))!=null?i:"",displayTitle:a(this,fa)};if(Object.keys(s).forEach(o=>{r.searchParams.set(o,s[o])}),n.src=r.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=c=>u(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:n,listener:o})}}setActive(t){var e,i;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:(i=this.config)==null?void 0:i.views})}activateForSelf(){return u(this,null,function*(){const t=at(),e=yield t.authorizePlugin(this.id);v(this,ga,e),v(this,Tn,new Date);try{const i=yield t.getPluginConfig(this.baseURL);this.config=i}catch(i){h.error("DytePlugin::activateForSelf",{error:i})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),v(this,Tn,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=a(this,ti).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,kt).addPlugin(this.id,this.staggered),v(this,Tn,new Date),h.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=a(this,ti).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,ti).id||(a(this,kt).removePlugin(this.id),h.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,Tn)?new Date().getTime()-a(this,Tn).getTime():0}}),v(this,Tn,void 0)))})}},kt=new WeakMap,ti=new WeakMap,pa=new WeakMap,ma=new WeakMap,Tn=new WeakMap,ga=new WeakMap,rs=new WeakMap,fa=new WeakMap,Df);Xc([Dt({maxInvocations:5,period:1})],ss.prototype,"sendData",1),Xc([S.trace("DytePlugin.activatePlugin")],ss.prototype,"activate",1),Xc([S.trace("DytePlugin.deactivatePlugin")],ss.prototype,"deactivate",1),ss=Xc([ut("0600")],ss);var qe,as;class Of extends Map{constructor(e){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:r}=e;super(),f(this,qe,void 0),f(this,as,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),v(this,qe,new Kr),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=r,v(this,as,new Map)}emit(e,...i){return a(this,qe).emit(e,...i)}on(e,i){return a(this,qe).on(e,i)}addListener(e,i){return a(this,qe).addListener(e,i)}off(e,i){return a(this,qe).off(e,i)}once(e,i){return a(this,qe).once(e,i)}prependListener(e,i){return a(this,qe).prependListener(e,i)}prependOnceListener(e,i){return a(this,qe).prependOnceListener(e,i)}removeListener(e,i){return a(this,qe).removeListener(e,i)}removeAllListeners(e){return a(this,qe).removeAllListeners(e)}listeners(e){return a(this,qe).listeners(e)}listenerCount(e){return a(this,qe).listenerCount(e)}getMaxListeners(){return a(this,qe).getMaxListeners()}setMaxListeners(e){return a(this,qe).setMaxListeners(e)}eventNames(){return a(this,qe).eventNames()}add(e,i=!0){return this.set(e.id,e,i)}set(e,i,n=!0){const r=super.set(e,i),s=(o,...c)=>{this.emit(o,i,...c)};return a(this,as).set(e,s),i.on("*",s),n&&a(this,qe).emit(this.onAddEvent,i),r}delete(e,i=!0,n=!1){const r=this.get(e);if(!r)return!1;r.removeListener("*",a(this,as).get(e));const s=super.delete(e);return n&&r.removeAllListeners(),i&&a(this,qe).emit(this.onDeleteEvent,r),s}clear(e=!0,i=!1){this.forEach(r=>{r.removeListener("*",a(this,as).get(r.id)),i&&r.removeAllListeners()});const n=super.clear();return e&&a(this,qe).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}qe=new WeakMap,as=new WeakMap;class Nf extends Of{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,i=!0){return super.add(e,i)}delete(e,i=!0,n=!1){return super.delete(e,i,n)}}var $A=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,zA=(t,e,i,n)=>{for(var r=n>1?void 0:n?KA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&$A(e,i,r),r};let Mu=class{constructor(){m(this,"all"),m(this,"active"),this.all=new Nf,this.active=new Nf}};Mu=zA([ut("0600")],Mu);var YA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,Zc=(t,e,i,n)=>{for(var r=n>1?void 0:n?QA(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&YA(e,i,r),r},mi,va,ed,Lf;const xf=(Lf=class{constructor(t,e,i,n){m(this,"plugins"),f(this,mi,void 0),f(this,va,void 0),f(this,ed,void 0),v(this,mi,e),v(this,va,i),v(this,ed,t),this.plugins=n,this.setupEvents()}static init(t,e,i,n,r,s,o,c){return u(this,null,function*(){const d=new Mu;return e.forEach(l=>{const p=new ss(t,l,i,s,o,r,c);d.all.add(p)}),new xf(t,i,n,d)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield a(this,mi).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(i=>{this.disablePlugin({id:i.id})}),yield Promise.all(e.map(i=>this.enablePlugin({id:i.pluginId,enabledBy:i.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:i}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=i)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const i=this.plugins.all.get(e);i&&i.deactivateForSelf()})}sendIframeEvent(t,e,i,n){const r=this.plugins.all.get(e);r&&r.sendIframeEvent({type:t,uuid:i,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(i=>{this.sendIframeEvent(t,i.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)}),P.onAsync(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),h.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),a(this,mi).on(z.addPlugin,t=>u(this,null,function*(){var e;const i=t.pluginId;(e=this.plugins.all.get(i))!=null&&e.active||(yield this.enablePlugin({id:i,enabledBy:t.enabledBy}))})),a(this,mi).on(z.removePlugin,t=>u(this,null,function*(){var e;const i=t.pluginId;(e=this.plugins.all.get(i))!=null&&e.active&&(yield this.disablePlugin({id:i}))})),[z.enablePluginForPeers,z.enablePluginForRoom].forEach(t=>{a(this,mi).on(t,(e,i)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,i,{enabledBy:e.enabledBy})}))}),[z.disablePluginForPeers,z.disablePluginForRoom].forEach(t=>{a(this,mi).on(t,(e,i)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,i,{disabledBy:e.disabledBy})}))}),[z.customPluginEventToPeers,z.customPluginEventToRoom].forEach(t=>{a(this,mi).on(t,(e,i)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,i,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{a(this,mi).on(t,(e,i)=>u(this,null,function*(){var n;const r=(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,i,{storeName:e.storeName,storeItems:r})}))}),a(this,mi).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),a(this,va).on(Me.sendMessageToPeers,t=>{const e=zi==null?void 0:zi.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ne.chatMessage,{message:e})}),a(this,va).on(Me.sendMessageToRoom,t=>{const e=zi==null?void 0:zi.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ne.chatMessage,{message:e})}),P.on(R.PEER_JOINED_INTERNAL,t=>{const e=Wc(t);this.broadcastIframeEvent(Ne.peerJoined,e)}),P.on(R.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ne.peerLeft,t)}),P.on(R.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ne.peerStageStatusUpdate,t)}),a(this,ed).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ne.stageStatusUpdate,t)})}},mi=new WeakMap,va=new WeakMap,ed=new WeakMap,Lf);let ya=xf;Zc([S.trace("PluginController.getRoomPlugins")],ya.prototype,"getRoomPlugins",1),Zc([S.trace("PluginController.enableForSelf")],ya.prototype,"enablePlugin",1),Zc([S.trace("PluginController.disableForSelf")],ya.prototype,"disablePlugin",1),Zc([S.trace("PluginController.setupEvents")],ya.prototype,"setupEvents",1);class XA{constructor(){m(this,"mediaJoined"),m(this,"socketJoined"),m(this,"socketJoinAttempted"),m(this,"mediaJoinAttempted"),m(this,"socketState"),m(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,i){let n;const{reconnected:r}=this.socketState;switch(e){case"connected":n={state:"connected",reconnected:r,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:r,reconnectionAttempt:0};break;case"reconnectAttempt":n={state:"reconnecting",reconnected:r,reconnectionAttempt:i};break;case"failed":n={state:"failed",reconnected:r,reconnectionAttempt:void 0},this.socketJoined=!1;break}n&&(P.emit(R.SOCKET_STATE_UPDATE,n),this.socketState=n)}}var ZA=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,Sa=(t,e,i,n)=>{for(var r=n>1?void 0:n?e1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&ZA(e,i,r),r},Ea,td,Ta,id,Vf;let lr=(Vf=class extends Ft{constructor(t,e){super(),f(this,Ta),f(this,Ea,void 0),f(this,td,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),v(this,td,t),v(this,Ea,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(!a(this,Ea).permissions.canRecord)throw h.error("DyteRecording::start::permission_denied"),new w("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 h.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new w(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=at(),{recording:i={}}=a(this,td).getValue("defaults"),n=yield e.startRecording(i,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING",type:"BROWSER"}])}catch(e){throw h.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new w("Error while starting recording","1000")}})}stop(t){return u(this,null,function*(){yield j(this,Ta,id).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield j(this,Ta,id).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield j(this,Ta,id).call(this,"resume",["PAUSED"],t)})}},Ea=new WeakMap,td=new WeakMap,Ta=new WeakSet,id=function(t,e,i){return u(this,null,function*(){if(!a(this,Ea).permissions.canRecord)throw h.error("DyteRecording::stop::permission_denied"),new w("User does not have permission to stop recording","1001");let n=[];if(i!==void 0){const r=this.recordings.find(s=>s.id===i);if(r===void 0)throw new w("Could not find the specified recording","1004");if(e.includes(r.state)){h.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:r.state}});return}n.push(r)}else n=this.recordings.filter(r=>e.includes(r.state));n.forEach(r=>u(this,null,function*(){const s=r.state;t==="stop"&&(r.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield at().updateRecording(r.id,t)}catch(o){throw h.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),r.state!==s&&(r.state=s,this.emit("recordingUpdate",s)),new w("Error while stopping recording","1000")}}))})},Vf);Sa([S.trace("DyteRecording.start")],lr.prototype,"start",1),Sa([S.trace("DyteRecording.stop")],lr.prototype,"stop",1),Sa([S.trace("DyteRecording.stop")],lr.prototype,"pause",1),Sa([S.trace("DyteRecording.stop")],lr.prototype,"resume",1),lr=Sa([ut("1000")],lr);var t1=Object.defineProperty,i1=Object.getOwnPropertyDescriptor,n1=(t,e,i,n)=>{for(var r=n>1?void 0:n?i1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&t1(e,i,r),r},Au;class Uf{constructor(e,i,n){m(this,"recording"),m(this,"room"),f(this,Au,void 0),v(this,Au,e),this.recording=new lr(e,i),this.room=n,this.setupEvents()}getRecordingTypeFromProtoType(e){let i;switch(e){case er.BROWSER:i="BROWSER";break;case er.COMPOSITE:i="COMPOSITE";break;case er.TRACK:i="TRACK";break;default:i="BROWSER"}return i}setupEvents(){P.on(R.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(i=>{const n=this.getRecordingTypeFromProtoType(i.recordingType);return{id:i.recordingId,state:i.recordingStatus,type:n}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(B.recordingStarted,e=>{let i=!1;const n=[...this.recording.recordings];if(n.forEach(r=>{r.id===e.recordingId&&(i=!0,r.state="RECORDING")}),i===!1){const r=this.getRecordingTypeFromProtoType(e.recordingType);n.push({id:e.recordingId,state:"RECORDING",type:r})}this.recording.updateRecordings(n)}),this.room.on(B.recordingPaused,e=>{const i=[...this.recording.recordings];i.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(i)}),this.room.on(B.recordingStopped,e=>{const i=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(i)})}}Au=new WeakMap,n1([S.trace("RecordingController.setupEvents")],Uf.prototype,"setupEvents",1);class r1{static hasFeature(e){var i;return(i=Q.hasFeature(e))!=null?i:!1}static getFeatureValue(e){return Q.getValue(e)}static getAllFeatures(){return Q.getAllFlags()}}class Du{constructor(e,i,n){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=i,this.browserSpecs=_e,this.callStats=n}static init(e){return new Du(h,r1,e)}}class Ou{constructor(e){m(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=Du.init(J);return new Ou(e)})}}var s1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,Wt=(t,e,i,n)=>{for(var r=n>1?void 0:n?a1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&s1(e,i,r),r},Ze,Je,Ce,Qi,gi,nd,Nu;class Ot extends Kr{constructor(e,i,n=Lu,r=!0){super(),f(this,Ze,void 0),f(this,Je,void 0),f(this,Ce,void 0),f(this,Qi,void 0),f(this,gi,void 0),f(this,nd,void 0),f(this,Nu,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),v(this,Nu,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,v(this,Ze,new Wf(e,i)),v(this,Je,new P1(a(this,Ze),void 0,n)),v(this,Ce,new L1(a(this,Ze),void 0,n)),v(this,gi,new D1(a(this,Ze))),v(this,Qi,new M1(a(this,Ze))),v(this,nd,r),a(this,Je).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Je).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,Ce).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,Ce).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,gi).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return u(this,null,function*(){J.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?J.browserBackgrounded():(J.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:i,video:n}){var r;i?J.audioOn():J.audioOff(),n?J.videoOn():J.videoOff();let s,o;if(i&&n)try{const c=yield a(this,Ze).getAudioAndVideoTrack(a(this,Je).userSelectedDevice,a(this,Ce).userSelectedDevice);s=c.audioTrack,o=c.videoTrack}catch(c){h.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!s&&i)try{s=yield a(this,Ze).getAudioTrack(!1,a(this,Je).userSelectedDevice)}catch(c){h.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!o&&n)try{o=yield a(this,Ze).getVideoTrack(a(this,Ce).userSelectedDevice)}catch(c){h.error("LocalMediaHandler::init::Failed to get video track",{error:c})}i&&!s&&J.audioOff(),n&&!o&&J.videoOff(),yield a(this,Je).setMediaTrack(s),yield a(this,Ce).setMediaTrack(o);try{yield a(this,Qi).setupSpeaker()}catch(c){}if(o){const c=yield this.getDeviceById(o.getSettings().deviceId);J.selectedDevice("VIDEO",c)}if(s){const c=yield this.getDeviceById(s.getSettings().deviceId);J.selectedDevice("AUDIO",c)}(r=a(this,Qi).currentDevice)!=null&&r.deviceId&&J.selectedDevice("SPEAKER",a(this,Qi).currentDevice),a(this,Ze).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:a(this,Je).currentDevice,video:a(this,Ce).currentDevice,speaker:a(this,Qi).currentDevice}}get permissions(){return a(this,Ze).permissions}getAllDevices(){return a(this,Ze).getAvailableDevices()}getDeviceById(e,i){return a(this,Ze).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Je).mediaTrack}get audioTrack(){return a(this,Je).transformedMediaTrack}get audioEnabled(){return a(this,Je).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield a(this,Je).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){a(this,Je).muteTrack()}getAudioDevices(e){return a(this,Ze).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield a(this,Je).setDevice(e),e!=null&&e.deviceId&&J.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return a(this,Qi).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield a(this,Qi).setupSpeaker(e),e!=null&&e.deviceId&&J.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,Ce).mediaTrack}get videoTrack(){return a(this,Ce).transformedMediaTrack}get videoEnabled(){return a(this,Ce).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield a(this,Ce).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){a(this,Ce).disableTrack()}getVideoDevices(e){return a(this,Ze).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield a(this,Ce).setDevice(e),e!=null&&e.deviceId&&J.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield a(this,Ce).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,gi).audioMediaTrack,video:a(this,gi).videoMediaTrack}}get screenShareEnabled(){return a(this,gi).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield a(this,gi).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){a(this,gi).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield a(this,gi).updateConstraints(e)})}getSpeakerDevices(e){return a(this,Ze).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Je).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Je).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Je).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,Ce).addMiddleware(e)}removeVideoMiddleware(e){return a(this,Ce).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,Ce).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,Ce).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Je).disableTrack(),a(this,Ce).disableTrack(),a(this,Ce).terminateMiddlewareWebWorker(),a(this,gi).disableScreenShare(),a(this,Ze).destruct()}onDeviceChange(e,i){return u(this,null,function*(){var n,r;this.emit("DEVICE_LIST_UPDATED",e),!(i||!a(this,nd))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!Lu(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(r=e==null?void 0:e.removed)==null||r.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Je).disableTrack()}removeVideoTrack(){a(this,Ce).disableTrack(),a(this,Ce).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}Ze=new WeakMap,Je=new WeakMap,Ce=new WeakMap,Qi=new WeakMap,gi=new WeakMap,nd=new WeakMap,Nu=new WeakMap,Wt([S.trace("MediaHandler.setupStreams")],Ot.prototype,"setupStreams",1),Wt([S.trace("MediaHandler.enableAudio")],Ot.prototype,"enableAudio",1),Wt([S.trace("MediaHandler.disableAudio")],Ot.prototype,"disableAudio",1),Wt([S.trace("MediaHandler.setAudioDevice")],Ot.prototype,"setAudioDevice",1),Wt([S.trace("MediaHandler.enableVideo")],Ot.prototype,"enableVideo",1),Wt([S.trace("MediaHandler.disableVideo")],Ot.prototype,"disableVideo",1),Wt([S.trace("MediaHandler.setVideoDevice")],Ot.prototype,"setVideoDevice",1),Wt([S.trace("MediaHandler.updateVideoConstraints")],Ot.prototype,"updateVideoConstraints",1),Wt([S.trace("MediaHandler.enableScreenShare")],Ot.prototype,"enableScreenShare",1),Wt([S.trace("MediaHandler.disableScreenShare")],Ot.prototype,"disableScreenShare",1),Wt([S.trace("MediaHandler.updateScreenshareConstraints")],Ot.prototype,"updateScreenshareConstraints",1),Wt([S.trace("MediaHandler.destruct")],Ot.prototype,"destruct",1),Wt([S.trace("MediaHandler.onDeviceChange")],Ot.prototype,"onDeviceChange",1);function rd(t,e,i){switch(!0){case _e.isChromiumBased():switch(e){case"NotAllowedError":return i.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case _e.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case _e.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 o1=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Lu(t){var e,i;const n=(e=t.label)==null?void 0:e.toLowerCase();return((i=_e._bowser)==null?void 0:i.getOSName())==="macOS"&&n.includes("iphone")?(h.log("isVirtualDevice::ignore_macos_continuity"),!0):o1.some(r=>n==null?void 0:n.includes(r))}function c1(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const i=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(o=>o(i))),r=i.createMediaStreamSource(new MediaStream([e])),s=i.createMediaStreamDestination();try{let o=r;for(let c=0;c<n.length;c+=1)o.connect(n[c]),o=n[c];o.connect(s)}catch(o){return h.error("getTransformedAudioTrack::middleware_execution_failed",{error:o}),e}return s.stream.getAudioTracks()[0]})}var os;class d1{constructor(){f(this,os,void 0)}terminateMiddlewareWebWorker(){if(a(this,os))try{Wr(a(this,os)),v(this,os,void 0)}catch(e){h.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,i,n){return u(this,null,function*(){if(!(e!=null&&e.length))return i;const r=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(g=>g({canvas:r,WorkerTimers:Xy})));if(n.disablePerFrameCanvasRendering){const g=r.captureStream().getVideoTracks()[0];return Object.defineProperty(g,"originalSettings",{value:i.getSettings()}),g}const o=document.createElement("video"),c=new MediaStream;c.addTrack(i);const d=r.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=()=>u(this,null,function*(){if(i.enabled===!1||i.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),r.remove();return}try{d.drawImage(o,0,0);for(let g=0;g<s.length;g+=1)typeof s[g]=="function"&&(yield s[g](r,d))}catch(g){h.error("getTransformedVideoTrack::middleware_execution_failed",{error:g})}});try{o.play()}catch(g){}o.addEventListener("play",()=>{r.width=o.width||i.getSettings().width,r.height=o.width||i.getSettings().height,v(this,os,rc(l,50))},!1);const p=r.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:i.getSettings()}),p})}}os=new WeakMap;const Ff={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}}},l1=[[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"}]],[1920,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:9e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:15e5,maxFramerate:30,scalabilityMode:"L1T1"}]]],u1=t=>{var e;const i="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((e=t.originalSettings)==null?void 0:e.width);let n=l1;Q.hasFeature(ne.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(n=JSON.parse(Q.getValue(ne.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const r=n.map(([c])=>c).sort((c,d)=>c-d);let s=Number.MAX_VALUE,o=0;return r.forEach((c,d)=>{Math.abs(c-i)<s&&(s=Math.abs(c-i),o=d)}),n[o][1]};var Te=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Te||{});const h1=eb(),cs=hi(h1.config.media);function p1(t){var e,i;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(i=t.audio.enableHighBitrate)!=null?i:!1}),n.video=t.video.quality,n}var ds,xu;class m1{constructor(e,i){f(this,ds,void 0),f(this,xu,void 0),m(this,"getScreenShareConstraints",()=>{var n,r,s,o,c,d,l,p,g,y,T;const b=(n=a(this,ds))==null?void 0:n.screenshare,N=(s=(r=b==null?void 0:b.width)==null?void 0:r.max)!=null?s:1920,M=(c=(o=b==null?void 0:b.height)==null?void 0:o.max)!=null?c:1080,F=(l=(d=b==null?void 0:b.frameRate)==null?void 0:d.max)!=null?l:5;let H=(g=(p=b==null?void 0:b.frameRate)==null?void 0:p.ideal)!=null?g:5;const K=b==null?void 0:b.displaySurface,I=b==null?void 0:b.selfBrowserSurface;Q.getValue(ne.VAL_MIN_FRAMERATE)&&(H=parseInt((y=Q.getValue(ne.VAL_MIN_FRAMERATE))==null?void 0:y.toString(),10));let re={width:{max:N},height:{max:M},frameRate:{ideal:H,max:F}};if(Q.hasFeature(ne.SCREENSHARE_CONSTRAINTS)){const ae=(T=Q.getValue(ne.SCREENSHARE_CONSTRAINTS))==null?void 0:T.toString();re=JSON.parse(ae)}return K!==void 0&&["monitor","browser","window"].includes(K)&&(re=q(x({},re),{displaySurface:K})),I!==void 0&&(re=q(x({},re),{selfBrowserSurface:I})),{audio:!0,video:re}}),m(this,"getAudioConstraints",n=>{var r,s,o,c,d,l,p,g;const y={},T=(r=a(this,ds))==null?void 0:r.audio,b=T!=null&&T.enableStereo?2:1;return _e.isFirefox()||_e.isWebKitBased()?(y.audio={deviceId:n,autoGainControl:(s=T==null?void 0:T.autoGainControl)!=null?s:!0,echoCancellation:(o=T==null?void 0:T.echoCancellation)!=null?o:!0,noiseSuppression:(c=T==null?void 0:T.noiseSupression)!=null?c:!0,channelCount:b},y):(y.audio={},y.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:b},{echoCancellation:(d=T==null?void 0:T.echoCancellation)!=null?d:!0},{googEchoCancellation:(l=T==null?void 0:T.echoCancellation)!=null?l:!0},{googAutoGainControl:(p=T==null?void 0:T.autoGainControl)!=null?p:!0},{googNoiseSuppression:(g=T==null?void 0:T.noiseSupression)!=null?g:!0},{googHighpassFilter:!0}],y)}),m(this,"getVideoConstraints",n=>{var r,s,o,c;const d={},l=(r=a(this,ds))==null?void 0:r.video;let p=Ff.vga;if(typeof l=="string"?p=Ff[l]:l!==void 0&&(p.height.ideal=l.height.ideal,p.width.ideal=l.width.ideal),p.frameRate={ideal:(o=(s=p.frameRate)==null?void 0:s.ideal)!=null?o:24},_e.isChromiumBased()&&(p.frameRate.max=30),Q.hasFeature(ne.VIDEO_CONSTRAINTS)){const g=(c=Q.getValue(ne.VIDEO_CONSTRAINTS))==null?void 0:c.toString();p=JSON.parse(g)}return d.video=p,typeof d.video=="boolean"||(n?d.video.deviceId={exact:n}:d.video.facingMode="user"),d}),v(this,xu,e),v(this,ds,i)}getUpdatedVideoConstraints(e){return e}}ds=new WeakMap,xu=new WeakMap;class Vu extends Error{constructor(e,i,n){super(i),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=n}}class g1{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let i=e;return e||(i=yield this.getAvailableDevices()),i.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let i=e;return e||(i=yield this.getAvailableDevices()),i.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let i=e;return e||(i=yield this.getAvailableDevices()),i.filter(n=>n.kind==="audiooutput")})}}var f1=Object.defineProperty,v1=Object.getOwnPropertyDescriptor,fi=(t,e,i,n)=>{for(var r=n>1?void 0:n?v1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&f1(e,i,r),r},ka,vi,Uu,Bf;let jt=(Bf=class extends g1{constructor(t,e){super(),m(this,"availableDevices"),f(this,ka,void 0),f(this,vi,void 0),f(this,Uu,void 0),v(this,Uu,t),v(this,vi,new m1(t,e)),v(this,ka,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return a(this,vi)}destruct(){return u(this,null,function*(){var t;(t=a(this,ka))==null||t.abort()})}handlePermissionErrors(t,e){const i=rd(t,e.name,e.message);return this.permissions[t]=i,P.emit(R.MEDIA_PERMISSION_ERROR,{message:i,constraints:e.constraints,kind:t}),i}getAudioAndVideoTrack(t,e){return u(this,null,function*(){const i={audio:a(this,vi).getAudioConstraints(t).audio,video:a(this,vi).getVideoConstraints(e).video};try{h.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(i)});const n=yield navigator.mediaDevices.getUserMedia(i);h.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(i)});const r=n.getAudioTracks()[0];let s=n.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",Q.hasFeature(ne.OBS_QUALITY)&&s.label.includes("OBS Virtual")){const o=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));s=yield this.getVideoTrack(o.deviceId)}return P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:s}}catch(n){throw h.error("WebMediaInterface.getAudioAndVideoTrack",{error:n}),new w("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let i=yield this.getAudioInputDevices();if(i.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new w("No audio devices available","1606");const n=r=>u(this,null,function*(){let s;try{i=i.filter(c=>c.deviceId!==r),s=a(this,vi).getAudioConstraints(r),h.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[o]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return h.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const c=rd("audio",o.name,o.message),d=new Vu(o.name,o.message,s);if(c==="COULD_NOT_START"){const l=i.shift();if(!l)throw d;h.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:o});const p=a(this,vi).getAudioConstraints(l.deviceId);return h.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(p)}),n(l.deviceId)}throw d}});try{const r=yield n(e);return r.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),r}catch(r){throw r.constraints&&this.handlePermissionErrors("audio",r),new w(r.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const i=Q.hasFeature(ne.OBS_QUALITY),n=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),r=i&&n,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new w("No video devices available","1607");const o=c=>u(this,null,function*(){try{let d=c;const{video:l}=d;r&&typeof l!="boolean"&&(d={video:{deviceId:l.deviceId}}),h.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[p]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(r&&typeof l!="boolean"&&typeof l.width=="object"){const{width:g,height:y}=p.getSettings(),{ideal:T}=l.width;p.applyConstraints({width:{ideal:T},height:{ideal:Math.floor(y*T/g)},frameRate:l.frameRate})}return h.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),p}catch(d){const l=rd("video",d.name,d.message),p=new Vu(d.name,d.message,c);if(l==="COULD_NOT_START"){const g=s.shift();if(!g)throw p;h.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const y=a(this,vi).getVideoConstraints(g.deviceId);return h.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(y)}),o({video:y.video})}throw p}});try{const c=a(this,vi).getVideoConstraints(t),d=yield o(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(c){throw c.constraints&&this.handlePermissionErrors("video",c),new w(c.message,"1602")}})}getScreenShareTracks(){return u(this,null,function*(){const t=e=>u(this,null,function*(){try{h.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),J.screenShareRequested();const i=yield navigator.mediaDevices.getDisplayMedia(e);return h.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),i}catch(i){const n=rd("video",i.name,i.message),r=new Vu(i.name,i.message,e),s={video:!0};if(E_(e,s)||!Q.hasFeature(ne.SCREEENSHARE_CONSTRAINTS_RETRY))throw r;if(n==="COULD_NOT_START")return t(s);throw r}});try{const e=a(this,vi).getScreenShareConstraints(),i=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:i.getAudioTracks()[0],videoTrack:i.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new w(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 h.error("enumerate_devices_failed",{error:t}),new w("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 h.error("enumerate_devices_failed",{error:e}),new w("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 h.error("enumerate_devices_failed",{error:e}),new w("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){_e.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var i,n;const r=p=>`${p.kind}-${p.deviceId}-${p.groupId}`,s=this.availableDevices,o=new Set(s.map(p=>r(p))),c=yield this.getAvailableDevices(),d=new Set(c.map(p=>r(p))),l={added:c.filter(p=>!o.has(r(p))),removed:s.filter(p=>!d.has(r(p))),devices:c};if((i=l.added)!=null&&i.length||(n=l.removed)!=null&&n.length){h.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const p=[...l.added,...l.removed];p.some(g=>g.kind==="audioinput")&&J.devices("AUDIO",c==null?void 0:c.filter(g=>g.kind==="audioinput")),p.some(g=>g.kind==="videoinput")&&J.devices("VIDEO",c==null?void 0:c.filter(g=>g.kind==="videoinput")),p.some(g=>g.kind==="audiooutput")&&J.devices("SPEAKER",c==null?void 0:c.filter(g=>g.kind==="audiooutput")),t(e,l,!1)}}),{signal:a(this,ka).signal})})}},ka=new WeakMap,vi=new WeakMap,Uu=new WeakMap,Bf);fi([S.trace("WebMediaInterface.destruct")],jt.prototype,"destruct",1),fi([S.trace("WebMediaInterface.handlePermissionErrors")],jt.prototype,"handlePermissionErrors",1),fi([S.trace("WebMediaInterface.getAudioAndVideoTrack")],jt.prototype,"getAudioAndVideoTrack",1),fi([S.trace("WebMediaInterface.getAudioTrack")],jt.prototype,"getAudioTrack",1),fi([S.trace("WebMediaInterface.getVideoTrack")],jt.prototype,"getVideoTrack",1),fi([S.trace("WebMediaInterface.getScreenShareTracks")],jt.prototype,"getScreenShareTracks",1),fi([S.trace("WebMediaInterface.getAvailableDevices")],jt.prototype,"getAvailableDevices",1),fi([S.trace("WebMediaInterface.getAvailableDevicesByKind")],jt.prototype,"getAvailableDevicesByKind",1),fi([S.trace("WebMediaInterface.getDevice")],jt.prototype,"getDevice",1),fi([S.trace("WebMediaInterface.onDeviceChange")],jt.prototype,"onDeviceChange",1),jt=fi([ut("1600")],jt);const Wf=jt,ba={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(i){h.error("LocalStorage::setItem::crashed",{error:i,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){h.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},y1=(t=0)=>new Promise(e=>setTimeout(e,t)),S1=(t,e,i)=>{const n=typeof i=="number"?i:250,r=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,r.connect(s);const o=new Uint8Array(s.fftSize);let c=!1;setTimeout(()=>{c=!0},n);function d(){return c?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):y1().then(d))}return d().then(l=>(r.disconnect(),l),l=>{throw r.disconnect(),l})},E1=typeof AudioContext!="undefined"?AudioContext:null;class Fu{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const i=x({AudioContext:E1},e);Object.defineProperties(this,{_AudioContext:{value:i.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Fu}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(i){}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 jf=new Fu,T1=3,k1=250;function b1(t){const e={},i=jf.getOrCreate(e);let n=T1;function r(){return n-=1,S1(i,t.srcObject,k1).then(s=>s?n>0?r():!0:!1).catch(()=>!0)}return r().finally(()=>{jf.release(e)})}function Hf(t){return u(this,null,function*(){const e=new Audio,i=new MediaStream;i.addTrack(t),e.srcObject=i;let n=!1;try{const r=e.play();r&&(yield r),n=yield b1(e),n&&h.info("checkIfAudioTrackIsSilent::silence_detected")}catch(r){h.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:r})}finally{e.pause(),e.remove()}return n})}var _1=Object.defineProperty,w1=Object.getOwnPropertyDescriptor,Gf=(t,e,i,n)=>{for(var r=n>1?void 0:n?w1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&_1(e,i,r),r};let sd=class extends Kr{constructor(t,e,i){var n;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"),m(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),m(this,"setUserPreferredDevice",r=>ba.setItem(this.userPreferredDeviceKey,r)),m(this,"getUserPreferredDevice",()=>ba.getItem(this.userPreferredDeviceKey)),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=(n=this.getUserPreferredDevice())!=null?n:void 0,this.isNonPreferredDevice=i,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=i=>{h.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){e(i)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){e(i)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){h.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 h.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new w("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:i}=this.mediaTrack;switch(i){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))})}setDevice(t){return u(this,null,function*(){if(!t)throw h.warn(`${this.constructorName}.setDevice No device received`),new w("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),yield this.onSetDevice(t)})}addMiddleware(t){return u(this,null,function*(){if(_e.isWebKitBased()&&!Q.hasFeature(ne.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 h.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(i){return h.error("While removing middleware",{error:i}),{success:!1,message:i==null?void 0:i.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 h.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,i;this.mediaTrack&&(h.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(i=this.mediaTrack)==null?void 0:i.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,i;this.mediaTrack&&(h.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(i=this.mediaTrack)==null?void 0:i.kind}`),h.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Gf([S.trace("BaseMediaHandler.unmuteTrack")],sd.prototype,"unmuteTrack",1),sd=Gf([ut("1600")],sd);const qf=sd;var I1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,Bu=(t,e,i,n)=>{for(var r=n>1?void 0:n?C1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&I1(e,i,r),r};const Wu="[Dyte]nonSilentDeviceLabels";class ad extends qf{onSetDevice(e){return u(this,null,function*(){if(!e)throw h.warn("AudioMediaHandler.setDevice No device received"),new w("No device received!","1603");if(e.kind!=="audioinput")throw h.warn("AudioMediaHandler.setDevice Received non audio device"),new w("Non audio device received while setting device!","1603");try{const i=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!i,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(i){throw h.error("AudioMediaHandler.setDevice.error",{error:i}),this.disableTrack(),new w(i.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){h.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const i=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(i)})}setTransformedTrack(e){return u(this,null,function*(){var i;if(!e&&!((i=this.middlewares)!=null&&i.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c1(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){h.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){h.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){h.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var i;if(!e||this.userSelectedDevice)return e;let n=e;const r=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?r.filter(d=>d&&!this.isNonPreferredDevice(d)):r;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),h.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const o=JSON.parse(ba.getItem(Wu));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Hf(n))){const d=(i=o==null?void 0:o.devices.concat({label:n.label}))!=null?i:[{label:n.label}];return ba.setItem(Wu,JSON.stringify({devices:d})),n}h.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==c).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Hf(n))){const l=o.devices.concat({label:n.label});return ba.setItem(Wu,JSON.stringify({devices:l})),h.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return h.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}Bu([S.trace("AudioMediaHandler.setTransformedTrack")],ad.prototype,"setTransformedTrack",1),Bu([S.trace("AudioMediaHandler.onTrackEnded")],ad.prototype,"onTrackEnded",1),Bu([S.trace("AudioMediaHandler.conditionallyChangeTrack")],ad.prototype,"conditionallyChangeTrack",1);const P1=ad;var _a;class R1{constructor(e){f(this,_a,void 0),m(this,"currentDevice"),v(this,_a,e)}setupSpeaker(e){return u(this,null,function*(){var i,n;if(!(a(this,_a)instanceof Wf))return;let r=e;if(e||([r]=(yield a(this,_a).getAvailableDevicesByKind("audiooutput")).filter(o=>!Lu(o))),!r)throw new w("No speaker found","1608");if(((i=this.currentDevice)==null?void 0:i.deviceId)===r.deviceId)return;this.currentDevice=r;const s=document.querySelectorAll("audio");(n=s[0])!=null&&n.setSinkId&&s.forEach(o=>u(this,null,function*(){if(typeof o.sinkId!="undefined"&&this.currentDevice.deviceId&&o.sinkId!==this.currentDevice.deviceId)try{yield o.setSinkId(this.currentDevice.deviceId)}catch(c){}}))})}}_a=new WeakMap;const M1=R1;class A1 extends Kr{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,i;try{const{audioTrack:n,videoTrack:r}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=r,this.addMediaTrackListeners(),((i=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:i.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}})}disableScreenShare(){var e,i;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(i=this.videoMediaTrack)==null||i.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new w("No media track enabled!","1610");const i=this.mediaInterface;if(!i.constraintsBuilder)throw new w("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(i.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){h.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e,i;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),_e.isWebKitBased()&&((i=this.videoMediaTrack)==null||i.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,i;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(i=this.videoMediaTrack)==null||i.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const D1=A1;var O1=Object.defineProperty,N1=Object.getOwnPropertyDescriptor,od=(t,e,i,n)=>{for(var r=n>1?void 0:n?N1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&O1(e,i,r),r},wa,cd;class Ia extends qf{constructor(e,i,n){super(e,i,n),f(this,wa,void 0),f(this,cd,{disablePerFrameCanvasRendering:!1}),v(this,wa,new d1)}onSetDevice(e){return u(this,null,function*(){if(!e)throw h.warn("VideoMediaHandler.setDevice No device received"),new w("No device received!","1603");if(e.kind!=="videoinput")throw h.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new w("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){h.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(i){throw h.error("VideoMediaHandler.setDevice.error",{error:i}),this.disableTrack(),new w("Failed to change device","1600")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){h.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var i;if(!e&&!((i=this.middlewares)!=null&&i.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield a(this,wa).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,cd)),this.emit("trackChanged")}catch(n){h.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){v(this,cd,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new w("No media track enabled!","1610");const i=this.mediaInterface;if(!i.constraintsBuilder)throw new w("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(i.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){h.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){a(this,wa).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){h.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){h.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let i=e;const n=yield this.mediaInterface.getVideoInputDevices(),r=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(r!=null&&r.length)||window.FAST_DYTE||r.find(s=>s.deviceId===e.getSettings().deviceId)||(i.stop(),h.info("localmediahandler::setupstreams::found_video_non_preferred"),i=yield this.mediaInterface.getVideoTrack(r[0].deviceId)),i})}}wa=new WeakMap,cd=new WeakMap,od([S.trace("VideoMediaHandler.setTransformedTrack")],Ia.prototype,"setTransformedTrack",1),od([S.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Ia.prototype,"setVideoMiddlewareGlobalConfig",1),od([S.trace("VideoMediaHandler.onTrackEnded")],Ia.prototype,"onTrackEnded",1),od([S.trace("VideoMediaHandler.conditionallyChangeTrack")],Ia.prototype,"conditionallyChangeTrack",1);const L1=Ia,Jf=hi(ql());var Ht,ls,dd,Ca;const Pa=class{constructor(t){if(f(this,Ht,void 0),f(this,ls,void 0),f(this,dd,void 0),f(this,Ca,void 0),!t)throw new w("Could not load preset.","0904");v(this,Ht,t.config),v(this,dd,t.name),v(this,ls,t.ui||hi(ql().ui)),v(this,Ca,t.permissions.plugins.config)}static fromResponse(t){return new Pa(t)}static default(){return new Pa(Jf)}static init(t,e=!0){return!t||e?new Pa(Jf):new Pa(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:a(this,ls).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Ht).viewType}get livestreamViewerQualities(){return a(this,Ht).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Ht).maxVideoStreams}get maxScreenShareCount(){return a(this,Ht).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Ca)).filter(t=>a(this,Ca)[t].disabled)}get designTokens(){return a(this,ls).designTokens}get configDiff(){return a(this,ls).configDiff}get mediaConstraints(){var t,e,i,n,r,s,o,c,d,l,p,g,y,T,b,N,M,F,H,K,I,re,ae,De;return{audio:{enableStereo:(n=(i=(e=(t=a(this,Ht))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:i.enableStereo)!=null?n:cs.audio.enableStereo,enableHighBitrate:(c=(o=(s=(r=a(this,Ht))==null?void 0:r.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?c:cs.audio.enableHighBitrate},video:{quality:(g=(p=(l=(d=a(this,Ht))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:p.quality)!=null?g:cs.video.quality,frameRate:(N=(b=(T=(y=a(this,Ht))==null?void 0:y.media)==null?void 0:T.video)==null?void 0:b.frameRate)!=null?N:cs.video.frameRate},screenshare:{quality:(K=(H=(F=(M=a(this,Ht))==null?void 0:M.media)==null?void 0:F.screenshare)==null?void 0:H.quality)!=null?K:cs.screenshare.quality,frameRate:(De=(ae=(re=(I=a(this,Ht))==null?void 0:I.media)==null?void 0:re.screenshare)==null?void 0:ae.frameRate)!=null?De:cs.screenshare.frameRate}}}get name(){return a(this,dd)}};let x1=Pa;Ht=new WeakMap,ls=new WeakMap,dd=new WeakMap,Ca=new WeakMap;var V1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,$f=(t,e,i,n)=>{for(var r=n>1?void 0:n?U1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&V1(e,i,r),r},Ra;class ju extends Ft{constructor(e){super(),f(this,Ra,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"ingestionCredentials"),m(this,"viewerCount"),v(this,Ra,e),this.viewerCount=0}setLivestreamState(e){const i=this.state;this.state=e,i!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!a(this,Ra).permissions.canLivestream)throw h.error("DyteLivestream::start::permission_denied"),new w("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const i=at(),{playbackUrl:n,ingestionCredentials:r}=yield i.startLivestreaming(e);this.playbackUrl=n,this.ingestionCredentials=r,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(i){throw h.error("DyteRecording::stop::livestream_failed_to_start",{error:i}),this.setLivestreamState("IDLE"),new w("Error while starting livestream","1900")}})}stop(){return u(this,null,function*(){if(!a(this,Ra).permissions.canLivestream)throw h.error("DyteLivestream::stop::permission_denied"),new w("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw h.error("DyteLivestream::stop::inconsistent_state"),new w("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield at().stopLivestreaming()}catch(e){throw h.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new w("Error while stopping livestream","1900")}})}}Ra=new WeakMap,$f([S.trace("livestream.start")],ju.prototype,"start",1),$f([S.trace("livestream.stop")],ju.prototype,"stop",1);var F1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,W1=(t,e,i,n)=>{for(var r=n>1?void 0:n?B1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&F1(e,i,r),r},Ma,Aa,kn;class Kf{constructor(e,i){m(this,"livestream"),f(this,Ma,void 0),f(this,Aa,void 0),f(this,kn,void 0),v(this,Aa,e),this.livestream=new ju(e),v(this,kn,i),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=at(),{status:i,playbackUrl:n,manualIngest:r,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,this.livestream.ingestionCredentials=s,i==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),i==="INVOKED"&&r&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){a(this,kn).on(B.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,Aa).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(i){h.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),a(this,kn).on(B.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,Aa).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(i){h.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),a(this,kn).on(B.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,kn).on(B.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,kn).on(B.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),P.on(R.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var i;((i=e.flags)==null?void 0:i.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(v(this,Ma,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),P.on(R.PEER_CLOSED,e=>{e.id===a(this,Ma)&&(v(this,Ma,void 0),this.livestream.setLivestreamState("IDLE"))}),P.onAsync(R.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(h.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){h.error("Error: LivestreamController.fetchLivestream")}}))}}Ma=new WeakMap,Aa=new WeakMap,kn=new WeakMap,W1([S.trace("LivestreamController.setupEvents")],Kf.prototype,"setupEvents",1);var j1=Object.defineProperty,H1=Object.getOwnPropertyDescriptor,Da=(t,e,i,n)=>{for(var r=n>1?void 0:n?H1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&j1(e,i,r),r},bt,ur,hr,Hu,zf;class us{constructor({name:e,socketHandler:i,meetingId:n}){f(this,Hu),m(this,"name",""),f(this,bt,{}),f(this,ur,""),f(this,hr,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),m(this,"listeners",{}),this.name=e,v(this,hr,i),v(this,ur,n)}set(e,i,n=!0,r=!1){return u(this,null,function*(){a(this,bt)[e]=i,n&&this.remoteSet(e,i),r&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:a(this,bt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:a(this,bt)[e]})))})}remoteSet(e,i){a(this,hr).storeInsertKeys(a(this,ur),this.name,[{key:e,payload:i}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:i,payload:n})=>{a(this,bt)[i]=n}),a(this,hr).storeInsertKeys(a(this,ur),this.name,e)})}update(e,i,n=!0){return u(this,null,function*(){j(this,Hu,zf).call(this,e,i,n)})}delete(e,i=!0,n=!1){return u(this,null,function*(){if(a(this,bt)[e]&&delete a(this,bt)[e],i)return a(this,hr).storeDeleteKeys(a(this,ur),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(r=>r({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(r=>r({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:i})=>{a(this,bt)[i]&&delete a(this,bt)[i]}),a(this,hr).storeDeleteKeys(a(this,ur),this.name,e)})}get(e){if(a(this,bt)[e])return a(this,bt)[e]}getAll(){return a(this,bt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,i){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=i}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,i){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=i}subscribe(e,i){if(this.listeners[e]){this.listeners[e].push(i);return}this.listeners[e]=[i]}unsubscribe(e,i){var n;if(i){this.listeners[e]=((n=this.listeners[e])==null?void 0:n.filter(r=>r!==i))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){v(this,bt,e)}}bt=new WeakMap,ur=new WeakMap,hr=new WeakMap,Hu=new WeakSet,zf=function(t,e,i=!0){let n;const r=a(this,bt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(r);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...r,...e];break;case"[object Object]":n=x(x({},r),e);break;case"[object Map]":n=new Map([...r,...e]);break;case"[object Set]":n=new Set([...r,...e]);break;default:n=e;break}this.set(t,n,i)},Da([Dt(Qr,"rateLimitConfig")],us.prototype,"remoteSet",1),Da([Dt(Qr,"bulkRateLimitConfig")],us.prototype,"bulkSet",1),Da([Dt(Qr,"rateLimitConfig")],us.prototype,"update",1),Da([Dt(Qr,"rateLimitConfig")],us.prototype,"delete",1),Da([Dt(Qr,"bulkRateLimitConfig")],us.prototype,"bulkDelete",1);var hs,ps,ld,Gu,ud,pr,qu,Yf;class G1{constructor(e,i){f(this,ld),f(this,qu),m(this,"stores",new Map),f(this,hs,void 0),f(this,ps,""),f(this,ud,void 0),f(this,pr,new Map),v(this,hs,i),v(this,ps,e.getValue("meetingId")),v(this,ud,e),j(this,qu,Yf).call(this)}create(e){const i=new us({name:e,socketHandler:a(this,hs),meetingId:a(this,ps)});return a(this,hs).storeGetKeys(a(this,ps),e,[]),new Promise((n,r)=>{const s=setTimeout(()=>r(Error("Failed")),3e3);a(this,pr).set(e,{rejectTimeout:s,resolve:n,store:i})})}}hs=new WeakMap,ps=new WeakMap,ld=new WeakSet,Gu=function(){return a(this,ud).getValue("peerId")},ud=new WeakMap,pr=new WeakMap,qu=new WeakSet,Yf=function(){[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{a(this,hs).on(t,e=>u(this,null,function*(){var i,n;if(e.pluginId!==a(this,ps))return;const r=(i=e.storeItems)==null?void 0:i.map(o=>{var c;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((c=o.payload)!=null&&c.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===z.storeGetKeys){const o=a(this,pr).get(e.storeName),c=this.stores.get(e.storeName)||(o==null?void 0:o.store);a(this,pr).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(c),clearTimeout(o.rejectTimeout),a(this,pr).delete(e.storeName)),r.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=a(this,pr).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===z.storeInsertKeys&&r.forEach(({key:o,peerId:c,payload:d})=>{c!==a(this,ld,Gu)&&s.set(o,d,!1,!0)}),t===z.storeDeleteKeys&&r.forEach(({key:o,peerId:c})=>{c!==a(this,ld,Gu)&&s.delete(o,!1,!0)}))}))})};function mr(t){var e,i,n,r,s,o,c,d,l,p,g,y,T;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(c=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(g=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:g.enabled,trackId:(T=(y=t.screenShareTracks)==null?void 0:y.video)==null?void 0:T.id}}}}:{}}var q1=Object.defineProperty,J1=Object.getOwnPropertyDescriptor,ms=(t,e,i,n)=>{for(var r=n>1?void 0:n?J1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&q1(e,i,r),r};const $1=.8,K1=1.2;var Oa,Na,gr,gs,La,fs,xa,Ju,Qf,bn,hd,fr,Va,pd,_n,$u,md,Ku,Xf;let Xi=(Xf=class extends Ft{constructor(t,e,i,n){super(),f(this,gs),f(this,fs),f(this,Ju),f(this,Va),f(this,md),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"),f(this,Oa,void 0),m(this,"supportsRemoteControl",!1),f(this,Na,void 0),m(this,"presetName"),f(this,gr,void 0),f(this,bn,void 0),f(this,hd,void 0),f(this,fr,new Map),f(this,_n,1),f(this,$u,Cc(I=>{if(!this.videoTrack)return;const{clientWidth:re,clientHeight:ae}=I,{width:De,height:Oe}=this.videoTrack.getSettings();if(!De||!Oe)return;const ft=Oe/ae,Yt=De/re,A=Math.max(ft,Yt);A>K1&&a(this,_n)===1?(v(this,_n,0),P.emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,_n)})):A<$1&&a(this,_n)===0&&(v(this,_n,1),P.emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,_n)}))},2e3)),v(this,gr,t);const{id:r,userId:s,displayName:o,device:c,picture:d,isHost:l,flags:p,clientSpecificId:g,stageStatus:y,customParticipantId:T,audioMuted:b,audioTrack:N,videoEnabled:M=!1,videoTrack:F,producers:H,metadata:K}=e;this.id=r,this.userId=s,this.name=o,this.device=c,this.picture=d,this.isHost=l,this.flags=p,this.manualProducerConfig=A_,v(this,Na,y!=null?y:"ON_STAGE"),this.customParticipantId=T!=null?T:g,this.audioEnabled=!b,this.audioTrack=N,this.videoEnabled=M,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=H!=null?H:[],this.presetName=K==null?void 0:K.preset_name,v(this,Oa,!1),v(this,bn,i),v(this,hd,n),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),j(this,md,Ku).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,Na)}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(h.info("DyteParticipant::setVideoEnabled::videoUpdate",x({},mr(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(h.info("DyteParticipant::setAudioEnabled::audioUpdate",x({},mr(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",j(this,md,Ku))}pin(){return u(this,null,function*(){if(!a(this,fs,xa))throw new w("Can`t pin participant without joining room","1205");if(!a(this,bn).permissions.pinParticipant)throw new w("You do not have permission to pin participants.","1201");return a(this,gs,La).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,fs,xa))throw new w("Can`t unpin participant without joining room","1205");if(!a(this,bn).permissions.pinParticipant)throw new w("You do not have permission to unpin participants.","1201");return a(this,gs,La).pinPeer(null)})}setIsPinned(t,e=!0){var i;v(this,Oa,t);const n=t?"pinned":"unpinned";(i=a(this,Va,pd))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(h.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!a(this,fs,xa))throw new w("Can`t disable participant audio without joining room","1205");if(a(this,bn).permissions.canDisableParticipantAudio)return a(this,gs,La).disableAudio(t);throw h.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new w("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return u(this,null,function*(){const t=this.id;if(h.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!a(this,Ju,Qf))throw new w("Can`t kick participant without joining room","1205");if(a(this,bn).permissions.kickParticipant){yield P.emitAsync(R.KICK_PEER,{peerId:t});return}throw h.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new w("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(h.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!a(this,fs,xa))throw new w("Can`t disable participant video without joining room","1205");if(a(this,bn).permissions.canDisableParticipantVideo)return a(this,gs,La).disableVideo(t);throw h.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new w("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return u(this,null,function*(){return a(this,hd).getUserPermissions(this.userId)})}setStageStatus(t){v(this,Na,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Oa)}registerVideoElement(t){var e,i,n,r;let s;(i=(e=a(this,fr).get(t))==null?void 0:e.observer)==null||i.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>a(this,$u).call(this,t)),s.observe(t)),a(this,fr).set(t,{observer:s}),this.updateVideo(t),(r=a(this,Va,pd))==null||r.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,i,n;t.srcObject=void 0,(i=(e=a(this,fr).get(t))==null?void 0:e.observer)==null||i.disconnect(),a(this,fr).delete(t),(n=a(this,Va,pd))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const i=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((i==null?void 0:i.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"}},Oa=new WeakMap,Na=new WeakMap,gr=new WeakMap,gs=new WeakSet,La=function(){return a(this,gr).getValue("roomNodeClient")},fs=new WeakSet,xa=function(){return a(this,gr).getValue("connectionHandler").mediaJoined},Ju=new WeakSet,Qf=function(){return a(this,gr).getValue("connectionHandler").socketJoined},bn=new WeakMap,hd=new WeakMap,fr=new WeakMap,Va=new WeakSet,pd=function(){return a(this,gr).getValue("pip")},_n=new WeakMap,$u=new WeakMap,md=new WeakSet,Ku=function(){Array.from(a(this,fr).keys()).forEach(this.updateVideo)},Xf);ms([S.trace("DyteParticipant.disableAudio")],Xi.prototype,"disableAudio",1),ms([S.trace("DyteParticipant.kick")],Xi.prototype,"kick",1),ms([S.trace("DyteParticipant.disableVideo")],Xi.prototype,"disableVideo",1),ms([S.trace("DyteParticipant.getPermissions")],Xi.prototype,"getPermissions",1),ms([S.trace("DyteParticipant.setStageStatus")],Xi.prototype,"setStageStatus",1),Xi=ms([ut("1200")],Xi);class Ua extends Of{constructor(e){const{onAddEvent:i="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:r="participantsCleared"}=e!=null?e:{};super({onAddEvent:i,onDeleteEvent:n,onClearEvent:r})}add(e,i=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,i)}clear(e=!0,i=!1){return super.clear(e,i)}delete(e,i=!0,n=!1){return super.delete(e,i,n)}}var vr;class z1 extends Kr{constructor(){super(),f(this,vr,void 0),v(this,vr,new Map)}__set(e,i){return a(this,vr).set(e,i)}__clear(){return a(this,vr).clear()}get(e){return a(this,vr).get(e)}toArray(){return Array.from(a(this,vr).values())}}vr=new WeakMap;class Y1{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,i){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:i}),this._orderedArray.splice(Math.max(i-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const r=this.add(e,i);return n!==r?r:-1}delete(e){if(this._map.has(e)){const i=this.index(e);this._map.delete(e),this._orderedArray.splice(i,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class Q1{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new Y1,this._compulsoryPeers=new Set}add(e,i){if(!e)return-1;if(i<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(i>0||i===246267631)){if(h.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),i===246267631)return-1}else if(i===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,i)}delete(e){h.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 Zf=new Q1;var X1=Object.defineProperty,Z1=Object.getOwnPropertyDescriptor,Gt=(t,e,i,n)=>{for(var r=n>1?void 0:n?Z1(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&X1(e,i,r),r};const eD=["ACTIVE_GRID","PAGINATED","MANUAL"];var yi,vs,Fa,ys,Ba,Wa,gd,Ss,qt,ev;let _t=(ev=class extends Ft{constructor(t,e,i){super(),f(this,vs),f(this,ys),f(this,Wa),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"videoSubscribed"),m(this,"audioSubscribed"),m(this,"pinned"),m(this,"all"),f(this,yi,void 0),f(this,Ss,void 0),f(this,qt,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",Zf),v(this,yi,t),v(this,Ss,e),v(this,qt,i),this.waitlisted=new Ua,this.joined=new Ua,this.videoSubscribed=new Ua,this.audioSubscribed=new Ua,this.active=this.videoSubscribed,this.pinned=new Ua,this.all=new z1,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,yi).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){P.on(R.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=a(this,yi).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(){var t;return(t=a(this,yi))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new w("0 <= Max active participants count limit <= 24","1203");a(this,yi).setValue("maxPreferredStreams",t),a(this,Wa,gd)&&P.emit(R.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(i=>i.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,i;if(!a(this,ys,Ba))throw new w("Can`t accept waiting room request without joining room","1205");const n=(i=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?i:t;return a(this,qt).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(i=>{var n,r;return(r=(n=this.waitlisted.get(i))==null?void 0:n.userId)!=null?r:i});return a(this,qt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,i;if(!a(this,ys,Ba))throw new w("Can`t reject waiting room request without joining room","1205");const n=(i=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?i:t;a(this,qt).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(h.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>eD.includes(e))(t))throw h.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new w(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){h.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL")throw new w("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,P.emit(R.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,P.emit(R.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,i=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new w("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(r=>{const s=this.joined.get(r);if(s){if(i.includes("audio")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(s);const o=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&n.push(o)}if(i.includes("video")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{video:!0}),this.audioSubscribed.add(s);const o=s.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&n.push(o)}if(i.includes("screenshareAudio")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{screenshareAudio:!0});const o=s.producers.find(c=>c.kind==="audio"&&c.screenShare);n.push(o)}if(i.includes("screenshareVideo")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{screenshareVideo:!0});const o=s.producers.find(c=>c.kind==="video"&&c.screenShare);n.push(o)}}}),yield a(this,vs,Fa).createConsumers(n)})}unsubscribe(t){return u(this,arguments,function*(e,i=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new w("MANUAL subscription mode was not activated.","1206");const n=[];e.forEach(r=>{const s=this.joined.get(r);if(s){if(i.includes("audio")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{audio:!1});const o=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&n.push(o)}if(i.includes("video")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{video:!1});const o=s.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&n.push(o)}if(i.includes("screenshareAudio")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{screenshareAudio:!1});const o=s.producers.find(c=>c.kind==="audio"&&c.screenShare);n.push(o)}if(i.includes("screenshareVideo")){s.manualProducerConfig=q(x({},s.manualProducerConfig),{screenshareVideo:!1});const o=s.producers.find(c=>c.kind==="video"&&c.screenShare);n.push(o)}}}),yield a(this,vs,Fa).closeConsumers(n)})}getPeerIdsForCurrentPage(){h.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)),i=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)),r=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-i.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-i.length);return e.concat(i,n.slice(r,s))}setPage(t){return u(this,null,function*(){if(h.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 h.error("DyteParticipants::invalid_page_number"),new w(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,P.emit(R.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(h.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Wa,gd))throw new w("Can`t disable all audio without joining room","1205");if(a(this,Ss).permissions.canAllowParticipantAudio)return a(this,vs,Fa).muteAll(t);throw h.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new w("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return u(this,null,function*(){if(h.info("DyteParticipants::disable_all_video"),!a(this,Wa,gd))throw new w("Can`t disable all video without joining room","1205");if(a(this,Ss).permissions.canAllowParticipantVideo)return a(this,vs,Fa).muteAllVideo();throw h.error("DyteParticipants::unauthorized_disable_all_video"),new w("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 P.emitAsync(R.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(h.info("DyteParticipants::kick_all"),a(this,yi).getValue("viewType")!=="LIVESTREAM"&&!a(this,ys,Ba))throw new w("Can`t kick all without joining room","1205");if(!a(this,Ss).permissions.kickParticipant)throw h.error("DyteParticipants::unauthorized_kick_all"),new w("Unauthorized: User does not have permission to kick peers.","1201");const t=Q.hasFeature(ne.PROPAGATE_KICK_ALL);a(this,qt).kickAll(t)})}broadcastMessage(t,e,i){return u(this,null,function*(){if(h.info("DyteParticipants::broadcastMessage"),!a(this,ys,Ba))throw new w("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new w("`type` must be a non-empty string.","1209");if(i)if("meetingIds"in i)yield a(this,qt).broadcastToMeetings(t,i.meetingIds,e);else{let n=[];"participantIds"in i?n=i.participantIds:n=this.joined.toArray().filter(r=>{var s;return(s=i.presetNames)==null?void 0:s.includes(r.presetName)}).map(r=>r.id),yield a(this,qt).broadcastToPeers(t,n,e)}else yield a(this,qt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,i){return u(this,null,function*(){return(yield a(this,qt).getRoomPeers(t,e,i)).peers.map(Zi.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const i=this.joined.toArray().filter(r=>t.includes(r.id)).map(r=>r.userId),n=[...new Set(i)];if(!n.length)throw new w("Cannot update permissions, no valid userIDs found","1204");a(this,qt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return a(this,qt).getRoomPeersNonPaginated()})}},yi=new WeakMap,vs=new WeakSet,Fa=function(){return a(this,yi).getValue("roomNodeClient")},ys=new WeakSet,Ba=function(){var t;return((t=a(this,yi).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Wa=new WeakSet,gd=function(){var t;return((t=a(this,yi).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ss=new WeakMap,qt=new WeakMap,ev);Gt([S.trace("DyteParticipants.setViewMode")],_t.prototype,"setViewMode",1),Gt([S.trace("DyteParticipants.setPage")],_t.prototype,"setPage",1),Gt([S.trace("DyteParticipants.disableAllAudio")],_t.prototype,"disableAllAudio",1),Gt([S.trace("DyteParticipants.disableAllVideo")],_t.prototype,"disableAllVideo",1),Gt([S.trace("DyteParticipants.disablePeerAudio")],_t.prototype,"disableAudio",1),Gt([S.trace("DyteParticipants.disablePeerVideo")],_t.prototype,"disableVideo",1),Gt([S.trace("DyteParticipants.kickPeer")],_t.prototype,"kick",1),Gt([S.trace("DyteParticipants.kickAll")],_t.prototype,"kickAll",1),Gt([S.trace("DyteParticipants.broadcastMessage"),Dt(Qr,"rateLimitConfig")],_t.prototype,"broadcastMessage",1),Gt([S.trace("DyteParticipants.getAllJoinedPeers"),Dt({maxInvocations:10,period:60})],_t.prototype,"getAllJoinedPeers",1),Gt([S.trace("DyteParticipant.updatePermissions"),Dt({maxInvocations:1e3,period:60})],_t.prototype,"updatePermissions",1),Gt([S.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],_t.prototype,"getParticipantsInMeetingPreJoin",1),_t=Gt([ut("1200")],_t);var wn=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(wn||{}),et=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(et||{}),tD=Object.defineProperty,iD=Object.getOwnPropertyDescriptor,yr=(t,e,i,n)=>{for(var r=n>1?void 0:n?iD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&tD(e,i,r),r};const tv=class{constructor(t,e,i,n){switch(m(this,"participants"),m(this,"self"),m(this,"selectedPeers",Zf),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"events"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),m(this,"updateConsumerSpatialLayers",Cc(()=>{const r={},s=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(s.entries()).forEach(([o,c])=>{r[c]===void 0&&(r[c]={layer:c,consumerIds:[]}),r[c].consumerIds.push(o)}),Object.keys(r).forEach(o=>{const c=r[o];h.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),m(this,"updateConsumers",(r,s)=>{let o=Promise.resolve();s.length>0&&(h.info("Closing consumers for producers",{producers:s}),o=this.roomNodeClient.closeConsumers(s)),o.then(()=>{r.length!==0&&(h.info("Consuming producers",{producers:r}),this.roomNodeClient.createConsumers(r).catch(c=>h.error("Error activating peers",{error:c})))}).catch(c=>h.error("Error deactivating peers",{error:c}))}),m(this,"updateConsumersDebounced",Cc(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=i,this.participants=new _t(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,n){case et.HIVE:{this.events=Xt;break}case et.CF:{this.events=li;break}default:this.events=Xt}e.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}setupEvents(){this.roomSocketHandler.on(B.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),P.on(R.SOCKET_PEERS,t=>u(this,null,function*(){const e=Q.hasFeature(ne.DEBUG_SOCKET_JOIN);if(e){const i=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(n=>n.peerId))}:void 0;h.info("Processing socket peers",i)}t==null||t.forEach(i=>{i.waitlisted||this.onParticipantJoined(this.fromSocketService(i))}),e&&h.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{Q.hasFeature(ne.DEBUG_SOCKET_JOIN)&&h.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:i})=>{if(Q.hasFeature(ne.DEBUG_SOCKET_JOIN)){const s=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;h.info("events.selfJoinComplete",s)}t.forEach(({peerId:s,producerStates:o,capabilities:c})=>this.onMediaJoined(s,o,c));const{audioPeers:n,compulsoryPeers:r}=e!=null?e:{};i.pinnedPeerIds.length!==0&&this.onParticipantPinned(i.pinnedPeerIds[0]),this.computeActivateParticipants(n!=null?n:[],r),P.emit(R.UPDATE_ACTIVE,{createAllConsumers:!0})}),P.on(R.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const i=this.videoPeerConsumerMap.get(t);i&&(this.maxSpatialLayerUpdates.set(i,e),this.updateConsumerSpatialLayers())}),P.on(R.NEW_PRODUCER,({peerId:t,producer:e})=>{const i=this.participants.joined.get(t);if(!i){h.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(i.producers.push(e),h.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let n=!1;const r=e.kind==="audio",s=e.kind==="video",o=i.manualProducerConfig;(r&&(o.audio&&!e.screenShare||o.screenshareAudio&&e.screenShare)||s&&(o.video&&!e.screenShare||o.screenshareVideo&&e.screenShare))&&(n=!0),n?this.roomNodeClient.createConsumers([e]):h.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(n=>{h.error("ParticipantController::createConsumer failed",{error:n})}):h.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),P.on(R.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const i=this.participants.joined.get(t);if(!i){h.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}i.producers=i.producers.filter(n=>n.producerId!==e)}),P.on(R.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:i,kind:n})=>{const r=this.participants.joined.get(t);if(r){n==="audio"&&r.setAudioEnabled(!i);const s=r.producers.find(o=>o.producerId===e);s&&(s.pause=i)}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const i=e;this.onParticipantPinned(i);const n=this.participants.joined.get(i);n&&this.roomNodeClient.activatePeers(n.producers).catch(r=>{h.error("unable to create consumers",{error:r})})}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.mediaJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:t})=>{if(!this.mediaJoined)return;const e=t.map(i=>({peerId:i.peerId,priority:i.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(n=>!this.participants.waitlisted.toArray().find(r=>r.userId===n.userId)),i=this.participants.waitlisted.toArray().filter(n=>!t.requests.find(r=>r.userId===n.userId));e.forEach(n=>this.participants.waitlisted.add(new Xi(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))),i.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,i=e.filter(c=>this.participants.joined.has(c)),n=Array.from(this.participants.pinned.keys()).filter(c=>!i.includes(c)),r=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),s=Math.max((t-1)*(this.maxPreferredStreams-i.length-n.length)),o=t*(this.maxPreferredStreams-i.length-n.length);return i.concat(n,r.slice(s,o))})}selectActivePeers(){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(l=>l.stageStatus==="ON_STAGE").map(l=>(t.set(l.id,!0),l.id))),i=this.selectedPeers.peers,n=this.participants.pinned.toArray().reduce((l,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):l.push(p.id),l),[]),r=this.self.stageStatus==="ON_STAGE"?1:0,s=this.participants.maxActiveParticipantsCount-r,o=new Set(i.concat(n).filter(l=>l!==this.self.id&&t.has(l)));let c=Array.from(o);const d=s-o.size;if(d>=0){const l=e.filter(p=>!o.has(p)&&p!==this.self.id).slice(0,d);c=Array.from(o).concat(l)}else c=c.slice(0,s);return c}updateActive(t,e){return u(this,null,function*(){const{page:i,createAllConsumers:n}=e!=null?e:{};let{strategies:r}=e!=null?e:{},s,o;switch(t){case"PAGINATED":{if(!i)return;s=yield this.selectPagePeers(i),h.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s}),r!=null||(r={video:this.updateParticipantsMap.bind(this)}),o=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{s=this.selectActivePeers(),h.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:s}),r!=null||(r={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),o=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let c,d;const l=this.updateGrid(s,r);n?(c=this.mapPeerIdsToProducers(s,["audio","video","screenshare"]),d=[]):(c=[...this.mapPeerIdsToProducers([...l.video.add],["video"]),...this.mapPeerIdsToProducers([...l.audio.add],["audio"])],d=[...this.mapPeerIdsToProducers([...l.video.remove],["video"]),...this.mapPeerIdsToProducers([...l.audio.remove],["audio"])]),!(c.length===0&&d.length===0)&&o(c,d)})}computeActivateParticipants(t,e){const i=t.map((r,s)=>({peerId:r,priority:s+1})),n=e==null?void 0:e.map((r,s)=>({peerId:r,priority:-(s+1)}));i.push(...n!=null?n:[]),i.length>0&&this.updateActiveParticipantsWithPriorities(i)}fromSocketService(t){const e=tv.formatSocketServiceMessage(t);return new Xi(this.context,q(x({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var i,n;e?(i=this.pip)==null||i.enableSource(t):(n=this.pip)==null||n.disableSource(t)}onMediaJoined(t,e,i){if(!this.mediaJoined||t===this.self.id)return;const n=this.participants.joined.get(t);if(!n){h.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(r=>{r.kind===Ai.AUDIO&&!r.screenShare?n.setAudioEnabled(!r.pause):r.kind===Ai.VIDEO&&!r.screenShare&&(n.setVideoEnabled(!r.pause),this.updatePipSource(n.id,!r.pause)),n.producers.push(q(x({},r),{producingTransportId:r.producingTransportId,kind:r.kind===Ai.AUDIO?"audio":"video",producingPeerId:t,mimeType:r.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,i),Q.hasFeature(ne.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack)}updateParticipantsMapMinReplacement(t,e){const i=Array.from(t.keys()),n=new Map(t),r=[],s=[],o=new Set(e),c=[];return i.forEach((d,l)=>{(!o.has(d)||!this.participants.joined.get(d))&&c.push(l)}),e.forEach(d=>{if(t.get(d))return;if(i.length<e.length){i.push(d),r.push(d);return}const l=c.shift();s.push(i[l]),i[l]=d,r.push(i[l])}),i.forEach((d,l)=>{o.has(d)||s.concat(i.splice(l,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!o.has(d))}),i.forEach(d=>{if(!this.participants.joined.get(d)){h.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!n.get(d))}),t.emit("participantsUpdate"),[r,s]}updateParticipantsMap(t,e){const i=Array.from(t.keys()),n=[],r=[];return i.forEach(s=>{e.includes(s)||(t.delete(s,!0),r.push(s))}),e.forEach(s=>{t.get(s)||(t.add(this.participants.joined.get(s)),n.push(s))}),t.emit("participantsUpdate"),[n,r]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(B.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=Q.hasFeature(ne.DEBUG_SOCKET_JOIN);e&&h.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&h.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(B.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e),this.onParticipantLeave(e)}),P.on(R.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())}),P.on(R.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})}),P.on(R.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),P.on(R.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),P.on(R.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),P.on(R.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),P.on(R.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:i,timestamp:n}){this.participants.emit("broadcastedMessage",{type:i,payload:e,timestamp:n})})),P.on(R.MESSAGE,t=>u(this,[t],function*({payload:e,type:i,timestamp:n}){i!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:i,payload:e,timestamp:n})})),P.on(R.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:i})=>{const n=this.participants.joined.get(t);n&&(n.emit("poorConnection",{score:e,kind:i}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:i}))}),P.on(R.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:i,peerId:n,scoreStats:r})=>{var s;const o=e==="video"&&((s=i==null?void 0:i.screenShare)!=null?s:!1),c=this.participants.joined.get(n);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:n,scoreStats:r}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:n,scoreStats:r}))}),P.onAsync(R.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const i=this.participants.joined.get(e);this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),i?i.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),P.on(R.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({page:e,createAllConsumers:i}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:i})}))}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,i,n;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((i=t.flags)!=null&&i.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"&&P.emit(R.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),P.emit(R.PEER_JOINED_INTERNAL,t),this.self.config.viewType===yt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.maxPreferredStreams)return;const r=this.participants.currentPage;this.updateActive(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}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),this.roomNodeClient&&(this.roomNodeClient.handlePeerLeaving(t),this.roomNodeClient.closeConsumers(e==null?void 0:e.producers)),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&P.emit(R.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:i}=this.participants,n=this.maxPreferredStreams*(i-1),r=this.participants.videoSubscribed.get(t);n===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=n?i===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(i-1):r&&this.updateActive(i?"PAGINATED":"ACTIVE_GRID",{page:i})})}processMedia(t){var e;const i=this.roomNodeClient.getConsumers(),{peerId:n,kind:r,appData:s,track:o,producerId:c,rtpReceiver:d,paused:l}=(e=i.get(t))!=null?e:{};if(!n)return h.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:r,peerId:n,appData:{supportsRemoteControl:!!(s!=null&&s.supportsRemoteControl),screenShare:!!(s!=null&&s.screenShare)},remotelyPaused:l,producerId:c}}),{};const p=s;return r==="video"&&p.screenShare!==!0&&this.videoPeerConsumerMap.set(n,t),h.info("ParticipantController::processMedia",{consumer:{id:t,peerId:n,kind:r,appData:p,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:r,peerId:n,appData:p,remotelyPaused:l,producerId:c}),{peerId:n,kind:r,appData:p,remotelyPaused:l,track:o,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:i,appData:n,remotelyPaused:r,producerId:s}=this.consumerPeerMap.get(t)||{},o=this.participants.joined.get(e);if(h.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:n,kind:i,remotelyPaused:r,producerId:s}}),this.consumerPeerMap.delete(t),i==="video"&&n.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const c=[];n&&n.screenShare?(o.setScreenShareEnabled(!1),J.consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&c.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&c.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):i==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&c.push(o.audioTrack.id),J.consumerSharedMediaState(t,{audio:!1}),o.audioTrack=void 0):i==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&c.push(o.videoTrack.id),J.consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),n.e2ee&&c.forEach(d=>{P.emit(R.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:i,appData:n,track:r,remotelyPaused:s,producerId:o,rtpReceiver:c}=this.processMedia(t);if(!e)return;h.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:i,appData:n,remotelyPaused:s,producerId:o}});const d=this.participants.joined.get(e);if(d){if(n.e2ee&&P.emit(R.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:r}),n.screenShare){i==="video"?d.screenShareTracks.video=r:i==="audio"&&(d.screenShareTracks.audio=r),d.setScreenShareEnabled(!0),J.consumerSharedMediaState(t,{screen:!0});return}i==="video"?(d.videoTrack=r,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),J.consumerSharedMediaState(t,{video:!0})):i==="audio"&&(d.audioTrack=r,d.setAudioEnabled(d.audioEnabled),J.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){h.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:i,track:n,appData:r,remotelyPaused:s,producerId:o}=this.processMedia(t);if(!e)return;h.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:i,appData:r,remotelyPaused:s,producerId:o}});const c=this.participants.joined.get(e);c&&(n&&r.e2ee&&P.emit(R.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:n.id}),i==="video"?(c.videoTrack=n,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),J.consumerSharedMediaState(t,{video:!1})):i==="audio"&&(c.audioTrack=n,c.setAudioEnabled(c.audioEnabled),J.consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:i,remotelyPaused:n,track:r,appData:s,producerId:o,rtpReceiver:c}=this.processMedia(t);if(!e)return;h.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:i,remotelyPaused:n,appData:s,producerId:o}});const d=this.participants.joined.get(e);if(d){if(s.screenShare){i==="video"?d.screenShareTracks.video=r:i==="audio"&&(d.screenShareTracks.audio=r),(!n||this.self.permissions.isRecorder||Q.hasFeature(ne.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}),h.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:i,remotelyPaused:n,appData:s,producerId:o}});return}i==="video"?(d.videoTrack=r,n||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),J.consumerSharedMediaState(t,{video:!n})):i==="audio"&&(d.audioTrack=r,n||d.setAudioEnabled(!0),J.consumerSharedMediaState(t,{audio:!n})),!n&&s.e2ee&&P.emit(R.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:r})}}static formatSocketServiceMessage(t){var e,i,n,r,s,o;if(!t)return;const c=Ru(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:c,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:c,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(i=t.flags)==null?void 0:i.recorderType,flags:{hiddenParticipant:(n=t.flags)==null?void 0:n.hiddenParticipant,hidden_participant:(r=t.flags)==null?void 0:r.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 i=(n,r)=>n.filter(({kind:s,screenShare:o})=>r.includes(s)||o&&r.includes("screenshare"));return t.flatMap(n=>{const r=this.participants.joined.get(n);if(r)return i(r.producers,e)}).filter(n=>!!n)}updateGrid(t,e){let i=[],n=[],r=[],s=[];return e.video&&([i,r]=e.video(this.participants.videoSubscribed,t)),e.audio&&([n,s]=e.audio(this.participants.audioSubscribed,t)),{video:{add:i,remove:r},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){h.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(n=>{this.selectedPeers.add(n.peerId,n.priority)});const i=this.selectedPeers.activeSpeakerPeers.at(0);i!==void 0&&i!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=i,this.participants.emit("activeSpeaker",{peerId:i,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 Zi=tv;yr([S.trace("ParticipantController.setupEvents")],Zi.prototype,"setupEvents",1),yr([S.trace("ParticipantController.setupEvents")],Zi.prototype,"setupEventsGlobal",1),yr([S.trace("ParticipantController.processMedia")],Zi.prototype,"processMedia",1),yr([S.trace("ParticipantController.processConsumerClosed")],Zi.prototype,"processConsumerClosed",1),yr([S.trace("ParticipantController.processConsumerResumed")],Zi.prototype,"processConsumerResumed",1),yr([S.trace("ParticipantController.processConsumerPaused")],Zi.prototype,"processConsumerPaused",1),yr([S.trace("ParticipantController.processNewConsumer")],Zi.prototype,"processNewConsumer",1);const ke=hi(ql().permissions);var G,ja,Ha,zu,Nt,Jt;const Ga=class extends Ft{constructor(t,e,i,n=!1){if(super(),f(this,Nt),f(this,G,void 0),f(this,ja,void 0),f(this,Ha,void 0),f(this,zu,r=>{var s,o,c;const d=r,{chat:l,connectedMeetings:p,plugins:g,polls:y,media:T}=d,b=ac(d,["chat","connectedMeetings","plugins","polls","media"]);if(l&&(l.private&&hn(a(this,G).chat.private,l.private),l.public&&hn(a(this,G).chat.public,l.public),this.emit("chatUpdate")),p&&hn(a(this,G).connectedMeetings,p),T){const N=F=>{switch(F){case vn.NONE:return Y.Allowed;case vn.ALLOWED:return Y.Allowed;case vn.NOT_ALLOWED:return Y.NotAllowed;case vn.CAN_REQUEST:return Y.CanRequest;default:return}},M={audio:void 0,video:void 0,screenshare:void 0};(s=T.audio)!=null&&s.canProduce&&(M.audio={canProduce:N(T.audio.canProduce)}),(o=T.video)!=null&&o.canProduce&&(M.video={canProduce:N(T.video.canProduce)}),(c=T.screenshare)!=null&&c.canProduce&&(M.screenshare={canProduce:N(T.screenshare.canProduce)}),hn(a(this,G).media,M)}g&&(hn(a(this,G).plugins,g),this.emit("pluginsUpdate")),y&&(hn(a(this,G).polls,y),this.emit("pollsUpdate")),Object.keys(b).length!==0&&hn(a(this,G),b),this.emit("permissionsUpdate",r)}),!e)throw h.error("DytePermissionsPreset::load_preset_permissions_failed"),new w("Could not load preset permissions.","0904");v(this,Ha,t),v(this,ja,i),v(this,G,e),n&&this.setupEvents()}setupEvents(){P.on(R.UPDATE_PERMISSIONS,a(this,zu))}static fromResponse(t,e,i){return new Ga(i,t,e,!0)}static default(t,e){return new Ga(t,ke,e)}static init(t,e,i){let n;return i?n=new Ga(t,i,e,!0):n=new Ga(t,ke,e),n}get mediaRoomType(){const{sfu:t}=a(this,Ha).getValue("roomNodeOptions");return t===et.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=a(this,G))==null?void 0:t.stageEnabled)||a(this,ja)===yt.Webinar||a(this,ja)===yt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=a(this,G))==null?void 0:t.acceptStageRequests)||((e=a(this,G))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,i;return((t=a(this,G))==null?void 0:t.stageAccess)===Y.NotAllowed?Y.NotAllowed:((e=a(this,G))==null?void 0:e.stageAccess)===Y.CanRequest?Y.CanRequest:((i=a(this,G))==null?void 0:i.stageAccess)===Y.Allowed||a(this,G).media.audio.canProduce===Y.Allowed||a(this,G).media.video.canProduce===Y.Allowed||a(this,G).media.screenshare.canProduce===Y.Allowed?Y.Allowed:a(this,G).media.audio.canProduce===Y.CanRequest||a(this,G).media.video.canProduce===Y.CanRequest||a(this,G).media.screenshare.canProduce===Y.CanRequest?Y.CanRequest:Y.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=a(this,G))==null?void 0:t.acceptWaitingRequests)!=null?e:ke.acceptWaitingRequests}get requestProduceVideo(){var t,e,i;return((i=(e=(t=a(this,G))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:i.canProduce)===Y.CanRequest}get requestProduceAudio(){var t,e,i;return((i=(e=(t=a(this,G))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:i.canProduce)===Y.CanRequest}get requestProduceScreenshare(){var t,e,i;return((i=(e=(t=a(this,G))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:i.canProduce)===Y.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=a(this,G))==null?void 0:t.disableParticipantAudio)!=null?e:ke.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=a(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:ke.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=a(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:ke.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=a(this,G))==null?void 0:t.kickParticipant)!=null?e:ke.kickParticipant}get pinParticipant(){var t,e;return(e=(t=a(this,G))==null?void 0:t.pinParticipant)!=null?e:ke.pinParticipant}get canRecord(){var t,e;return(e=(t=a(this,G))==null?void 0:t.canRecord)!=null?e:ke.canRecord}get waitingRoomType(){var t,e;return(e=(t=a(this,G))==null?void 0:t.waitingRoomType)!=null?e:ke.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=a(this,G))==null?void 0:t.waitingRoomType)!=null?e:ke.waitingRoomType}get plugins(){var t,e;return(e=(t=a(this,G))==null?void 0:t.plugins)!=null?e:ke.plugins}get polls(){var t,e;return(e=(t=a(this,G))==null?void 0:t.polls)!=null?e:ke.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,G).media.audio.canProduce===Y.CanRequest||a(this,G).media.video.canProduce===Y.CanRequest||a(this,G).media.screenshare.canProduce===Y.CanRequest}get canProduceVideo(){var t;const e=(t=a(this,G).media.video.canProduce)!=null?t:ke.media.video.canProduce;return this.stageEnabled&&(a(this,Nt,Jt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Nt,Jt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(a(this,Nt,Jt)==="OFF_STAGE"||a(this,Nt,Jt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=a(this,G).media.screenshare.canProduce)!=null?t:ke.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Nt,Jt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Nt,Jt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(a(this,Nt,Jt)==="OFF_STAGE"||a(this,Nt,Jt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=a(this,G).media.audio.canProduce)!=null?t:ke.media.audio.canProduce;return this.stageEnabled&&(a(this,Nt,Jt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Nt,Jt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(a(this,Nt,Jt)==="OFF_STAGE"||a(this,Nt,Jt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get chatPublic(){var t,e,i;return(i=(e=(t=a(this,G))==null?void 0:t.chat)==null?void 0:e.public)!=null?i:ke.chat.public}get chatPrivate(){var t,e,i;return(i=(e=(t=a(this,G))==null?void 0:t.chat)==null?void 0:e.private)!=null?i:ke.chat.private}get chatChannel(){var t,e,i;return(i=(e=(t=a(this,G))==null?void 0:t.chat)==null?void 0:e.channel)!=null?i:ke.chat.channel}get chatMessage(){var t,e,i;return(i=(e=(t=a(this,G))==null?void 0:t.chat)==null?void 0:e.message)!=null?i:ke.chat.message}get connectedMeetings(){var t,e;return(e=(t=a(this,G))==null?void 0:t.connectedMeetings)!=null?e:ke==null?void 0:ke.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=a(this,G))==null?void 0:t.hiddenParticipant)!=null?e:ke.hiddenParticipant}get showParticipantList(){var t;return(t=a(this,G).showParticipantList)!=null?t:ke.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=a(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ke.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=a(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ke.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,G).media.audio.canProduce===Y.Allowed||a(this,G).media.video.canProduce===Y.Allowed||a(this,G).media.screenshare.canProduce===Y.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=a(this,G).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,G).isRecorder}get canSpotlight(){return a(this,G).canSpotlight}get canLivestream(){return a(this,G).canLivestream}get transcriptionEnabled(){return a(this,G).transcriptionEnabled}};let nD=Ga;G=new WeakMap,ja=new WeakMap,Ha=new WeakMap,zu=new WeakMap,Nt=new WeakSet,Jt=function(){return a(this,Ha).getValue("stageStatus")};var iv;class rD extends Ft{constructor(){super(...arguments),m(this,"localMediaHandler"),f(this,iv,void 0)}updatePermission(){return u(this,null,function*(){var e,i;const n=(l,p)=>{this.mediaPermissions[l]=p;const g={message:this.mediaPermissions[l],kind:l};p==="DENIED"?P.emit(R.MEDIA_PERMISSION_ERROR,g):P.emit(R.MEDIA_PERMISSION_UPDATE,g)};if(_e.getName()==="firefox")return;const r="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:r}),c=yield(i=navigator==null?void 0:navigator.permissions)==null?void 0:i.query({name:s}),d=(l,p)=>{switch(p){case"granted":n(l,"ACCEPTED");break;case"denied":n(l,"DENIED");break;case"prompt":n(l,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};o&&(o.onchange=()=>d("audio",o.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:i,kind:n}){switch(n){case"audio":{J.mediaPermission("AUDIO",i),J.mediaPermission("SPEAKER",i);break}case"video":{J.mediaPermission("VIDEO",i);break}case"screenshare":{J.mediaPermission("SCREENSHARE",i);break}}})}init(){return u(this,arguments,function*(e={},i=!1,n=null){var r,s,o,c,d,l;if(_e.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:g}=navigator;this.localMediaHandler=yield g.init()}else this.localMediaHandler=new Ot(n,e.constraints,(r=n==null?void 0:n.getValue("defaults"))==null?void 0:r.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(P.on(R.MEDIA_PERMISSION_UPDATE,g=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:g.message,kind:g.kind}),g.message==="NOT_REQUESTED")switch(g==null?void 0:g.kind){case"audio":this.rawAudioTrack&&(h.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(h.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",g)})),P.on(R.MEDIA_PERMISSION_ERROR,g=>u(this,null,function*(){const{kind:y,message:T,constraints:b}=g;this.populateMediaPermissionsInCallstats({message:T,kind:y}),y==="audio"?(h.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(h.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),h.error("SelfController::mediaPermissionError",{error:{message:T},constraints:b,mediaPermissionsErrors:{kind:y,message:T}}),this.emit("mediaPermissionError",g),this.emit("mediaPermissionUpdate",{message:T,kind:y})})),p){h.info(`Setting up DyteSelfMedia streams using media handler. audio:${(o=e==null?void 0:e.audio)!=null?o:!0} video:${(c=e==null?void 0:e.video)!=null?c:!0}`);const g=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(l=e==null?void 0:e.audio)!=null?l:!0});i||(yield g)}}catch(p){h.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,i){let n;return i==="audio"?n="audioinput":i==="video"?n="videoinput":i==="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(i){}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(i){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}iv=new WeakMap;const qa={},In={executeWithLock({methodName:t,lockName:e,timeout:i}){return(n,r,s)=>{const o=s.value;return s.value=function(...c){if(qa[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",h.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}qa[e]=!0;const d=setTimeout(()=>delete qa[e],i),l=o.apply(this,c);return Promise.resolve(l).then(()=>{delete qa[e],clearTimeout(d)}).catch(()=>{delete qa[e],clearTimeout(d)}),l},s}}};var sD=Object.defineProperty,aD=Object.getOwnPropertyDescriptor,wt=(t,e,i,n)=>{for(var r=n>1?void 0:n?aD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&sD(e,i,r),r},Ja,Lt,$a,en,Sr,Es,tt,ot,$e,ze,Ka,za,fd,Yu,nv;let it=(nv=class extends rD{constructor(t,e,i,n,r){var s;super(),f(this,Sr),f(this,tt),f(this,$e),f(this,fd),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),f(this,Ja,void 0),f(this,Lt,void 0),f(this,$a,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),f(this,en,void 0),m(this,"hidden",!1),m(this,"presetName"),m(this,"roomState","init"),f(this,Ka,new Set),f(this,za,new Set),v(this,en,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",v(this,Lt,i),v(this,Ja,n),this.hidden=!1,v(this,$a,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=_e.isElectron(),this.device=_e.getDeviceInfo(),this.presetName=r,n.viewType!==yt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),j(this,fd,Yu).call(this)}get stageStatus(){return a(this,en).getValue("stageStatus")}get id(){return a(this,en).getValue("peerId")}static __init__(t,e,i,n,r,s=!1){return u(this,null,function*(){var o,c,d,l,p;let g=(c=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?c:!0,y=(l=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?l:!0;i.canProduceAudio!=="ALLOWED"&&(g=!1),i.canProduceVideo!=="ALLOWED"&&(y=!1);const T=new it(t,e,i,n,r);if(n.viewType===yt.Chat)return T;const b=p1(n.mediaConstraints);return hn(b,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield T.init({audio:g,video:y,constraints:b},s,t),T.setupEvents(),T})}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"),a(this,Lt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",j(this,fd,Yu)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(h.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",x({},mr(this))),a(this,$e,ze)&&this.audioEnabled)try{yield a(this,tt,ot).shareMic(this.audioTrack)}catch(t){h.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(h.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",x({},mr(this))),a(this,$e,ze)&&this.rawVideoTrack===void 0)h.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,ze))try{const t=yield a(this,tt,ot).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&Q.hasFeature(ne.EXP_RESHARE)&&(yield a(this,tt,ot).shareWebcam(this.videoTrack))}catch(t){h.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(!a(this,$e,ze)){h.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield a(this,tt,ot).shareScreen(this.screenShareTracks)}catch(t){h.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}h.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",x({},mr(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){h.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),h.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",x({},mr(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{J.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){a(this,$e,ze)&&(yield a(this,tt,ot).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),J.videoOff()})),a(this,Lt).on("permissionsUpdate",t=>{var e,i,n;(e=t==null?void 0:t.media)!=null&&e.audio&&a(this,Lt).canProduceAudio!==Y.Allowed&&(this.disableAudio(),h.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=t==null?void 0:t.media)!=null&&i.video&&a(this,Lt).canProduceVideo!==Y.Allowed&&(this.disableVideo(),h.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=t==null?void 0:t.media)!=null&&n.screenshare&&a(this,Lt).canProduceScreenshare!==Y.Allowed&&(this.disableScreenShare(),h.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,Lt)}get config(){return a(this,Ja)}get roomJoined(){var t;return a(this,Ja).viewType===yt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,en).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,ze)}setName(t){if(!t)throw new w("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!==Y.NotAllowed&&!(a(this,Lt).canProduceAudio===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(J.audioOn(),yield this.localMediaHandler.enableAudio(),a(this,$e,ze)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield a(this,tt,ot).shareMic(this.audioTrack)}catch(t){h.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;a(this,tt,ot).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(a(this,Lt).canProduceVideo!==Y.NotAllowed&&!(a(this,Lt).canProduceVideo===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(J.videoOn(),yield this.localMediaHandler.enableVideo(),a(this,$e,ze)&&this.stageStatus==="ON_STAGE")try{yield a(this,tt,ot).shareWebcam(this.videoTrack)}catch(t){h.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),h.info("DyteSelf.enableVideo",x({},mr(this)))}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new w("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!a(this,$e,ze))throw new w("Can`t enable screenshare without joining room","1105");if(a(this,Lt).canProduceScreenshare!==Y.NotAllowed&&!(a(this,Lt).canProduceScreenshare===Y.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 a(this,tt,ot).shareScreen(this.screenShareTracks)}catch(t){h.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 w("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,ze)&&a(this,tt,ot).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),J.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),a(this,$e,ze)&&(yield a(this,tt,ot).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),J.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),a(this,$e,ze)&&(yield a(this,tt,ot).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;v(this,$a,t);const n=t?"pinned":"unpinned";(i=a(this,Sr,Es))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(n,this)}get isPinned(){return a(this,$a)}pin(){return u(this,null,function*(){if(!a(this,$e,ze))throw new w("Can`t pin participants without joining room","1105");return this.show(),a(this,tt,ot).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,$e,ze))throw new w("Can`t unpin participants without joining room","1105");return a(this,tt,ot).pinPeer(null)})}hide(){return u(this,null,function*(){if(!a(this,$e,ze))throw new w("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!a(this,$e,ze))throw new w("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,i,n;if(!t)throw new w("No device selected","1104");const r=this.getCurrentDevices();if(t.deviceId&&(((e=r==null?void 0:r.audio)==null?void 0:e.deviceId)===t.deviceId||((i=r==null?void 0:r.video)==null?void 0:i.deviceId)===t.deviceId||((n=r==null?void 0:r.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(h.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),Q.hasFeature(ne.SKIP_SETTING_IN_USE_DEVICE)))throw new w("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(s){a(this,$e,ze)&&(yield a(this,tt,ot).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(s){a(this,$e,ze)&&(yield a(this,tt,ot).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,i,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(i=this.videoTrack)==null||i.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t,e=!1){var i,n;e?a(this,Ka).add(t):a(this,za).add(t),this.updateVideo(t),e||(n=a(this,Sr,Es))==null||n.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?a(this,Ka).delete(t):(a(this,za).delete(t),a(this,Sr,Es).removeSource(this.id))}updateVideo(t,e=!1){var i,n,r;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(i=t.srcObject)==null?void 0:i.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=a(this,Sr,Es))==null||n.enableSource(this.id)}else t.srcObject=void 0,e||(r=a(this,Sr,Es))==null||r.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ja=new WeakMap,Lt=new WeakMap,$a=new WeakMap,en=new WeakMap,Sr=new WeakSet,Es=function(){return a(this,en).getValue("pip")},tt=new WeakSet,ot=function(){return a(this,en).getValue("roomNodeClient")},$e=new WeakSet,ze=function(){var t;return((t=a(this,en).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ka=new WeakMap,za=new WeakMap,fd=new WeakSet,Yu=function(){Array.from(a(this,za)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Ka)).forEach(t=>this.updateVideo(t,!0))},nv);wt([S.trace("DyteSelf.cleanupEvents")],it.prototype,"cleanupEvents",1),wt([S.trace("DyteSelf.setupEvents")],it.prototype,"setupEvents",1),wt([S.trace("DyteSelf.setupTracks")],it.prototype,"setupTracks",1),wt([S.trace("DyteSelf.destructMediaHandler")],it.prototype,"destructMediaHandler",1),wt([S.trace("DyteSelf.removeDocumentEventListeners")],it.prototype,"removeDocumentEventListeners",1),wt([In.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),S.trace("DyteSelf.enableAudio")],it.prototype,"enableAudio",1),wt([In.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),S.trace("DyteSelf.enableVideo")],it.prototype,"enableVideo",1),wt([S.trace("DyteSelf.updateVideoConstraints")],it.prototype,"updateVideoConstraints",1),wt([S.trace("DyteSelf.enableScreenShare"),In.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],it.prototype,"enableScreenShare",1),wt([S.trace("DyteSelf.updateScreenshareConstraints")],it.prototype,"updateScreenshareConstraints",1),wt([In.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),S.trace("DyteSelf.disableAudio")],it.prototype,"disableAudio",1),wt([In.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),S.trace("DyteSelf.disableVideo")],it.prototype,"disableVideo",1),wt([In.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),S.trace("DyteSelf.disableScreenShare")],it.prototype,"disableScreenShare",1),wt([S.trace("DyteSelf.setDevice")],it.prototype,"setDevice",1),it=wt([ut("1100")],it);var oD=Object.defineProperty,cD=Object.getOwnPropertyDescriptor,dD=(t,e,i,n)=>{for(var r=n>1?void 0:n?cD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&oD(e,i,r),r};let Ts;var vd,rv;const sv=(rv=class{constructor(t,e){m(this,"socket"),f(this,vd,void 0),v(this,vd,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return Ts||(Ts=new sv(t,e)),Ts}static cleanup(){var t;try{(t=Ts==null?void 0:Ts.socket)==null||t.disconnect()}catch(e){h.error("roomSocketHandler::cleanup")}Ts=void 0}joinRoom(t){return u(this,null,function*(){var e;this.socket.joinAttempted=!0;const i={capabilities:[],peer:{displayName:(e=t.name)!=null?e:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(B.joinRoom,kC.toBinary(i));try{const{peer:r}=zr.fromBinary((yield n).payload);a(this,vd).getValue("connectionHandler").socketJoined=!0,P.emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:r});const s=this.getRoomState(),o=this.getRoomPeersNonPaginated(),[{room:c},{peers:d}]=yield Promise.all([s,o]);return P.emit(R.ROOM_STATE,c),P.emit(R.SOCKET_PEERS,d),{peer:r}}catch(r){throw h.error("RoomSocketHandler.joinRoom.failed",{error:r}),new w("Error: RoomSocketHandler.joinRoom failed.","0002",r)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return aP.fromBinary((yield this.socket.sendMessagePromise(B.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:i}=e,n=ac(e,["id"]);return q(x({},n),{userId:i})})}catch(t){return[]}})}getRoomPeers(t,e,i){return u(this,null,function*(){let n;try{const r={seachQuery:t,limit:e,offset:i},s=yield this.socket.sendMessagePromise(B.getRoomPeersInfo,hC.toBinary(r));n=ru.fromBinary(s.payload)}catch(r){h.error("getRoomPeers::binary_decode_error",{error:r})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);t=ru.fromBinary(e.payload)}catch(e){h.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(B.getRoomPeersInfo);t=ru.fromBinary(e.payload)}catch(e){h.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const i=yield this.socket.sendMessagePromise(B.getPeerInfo,Jg.toBinary({peerId:t}));e=zr.fromBinary(i.payload)}catch(i){h.error("getPeerInfo::binary_decode_error",{error:i})}return e})}getRoomState(){return u(this,null,function*(){let t=qg.create();try{const e=yield this.socket.sendMessagePromise(B.getRoomInfo);t=qg.fromBinary(e.payload)}catch(e){h.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Xg.create();try{const e=yield this.socket.sendMessagePromise(B.getRoomStageState);t=Xg.fromBinary(e.payload)}catch(e){h.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(B.broadcastMessage,sa.toBinary(i))})}broadcastToMeetings(t,e,i){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(B.broadcastToEntity,sa.toBinary(n))})}broadcastToPeers(t,e,i){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(B.broadcastToEntity,sa.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(B.leaveRoom,_C.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(B.kick,Yg.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(B.kickAll,Lg.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(B.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(B.acceptWaitingRoomRequests,hP.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(B.denyWaitingRoomRequests,mP.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const i={updatePeersPresets:[]};return t.forEach(n=>{i.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(Bc.updateUserPreset,HP.toBinary(i))})}handleSocketEvents(){this.socket.on(B.broadcastMessage,({payload:t})=>{try{const e=sa.fromBinary(t);P.emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){h.error("failed to decode broadcast message:",e)}}),this.socket.on(B.broadcastToEntity,({payload:t})=>{try{const e=sa.fromBinary(t);P.emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){h.error("failed to decode peer broadcast message:",e)}})}on(t,e){let i,n;switch(t){case B.joinRoom:case B.leaveRoom:case B.kick:case B.kickAll:{i=zr.fromBinary.bind(zr),n=zr.create();break}case B.getWaitingRoomRequests:{i=(r,s)=>r?Qg.fromBinary(r,s):{requests:[]},n=Qg.create();break}case B.recordingPaused:case B.recordingStarted:case B.recordingStopped:{i=uf.fromBinary.bind(uf);break}case Bc.updateUserPreset:{i=ef.fromBinary.bind(ef);break}case li.peerJoinedBroadcast:case Xt.peerJoinedBroadcast:{i=Ug.fromBinary.bind(Ug);break}case li.selfJoinComplete:case Xt.selfJoinComplete:{i=Zl.fromBinary.bind(Zl);break}case li.globalPeerPinBroadcast:case Xt.globalPeerPinBroadcast:{i=Wg.fromBinary.bind(Wg);break}case li.selectedPeer:case Xt.selectedPeer:{i=Xl.fromBinary.bind(Xl);break}case li.selectedPeerDiff:case Xt.selectedPeerDiff:{i=Vg.fromBinary.bind(Vg);break}case li.leaveRoom:case Xt.leaveRoom:{i=eu.fromBinary.bind(eu);break}}this.socket.on(t,({payload:r})=>{let s=n;if(!i)return e(void 0);try{s=i(r)}catch(o){h.error("roomSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const i=yield this.socket.sendMessagePromise(Bc.getUserPresets,xP.toBinary(e)),n=BP.fromBinary(i.payload).peerPresets[0],r=new TextDecoder().decode(n.preset),s=JSON.parse(r).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(i){throw h.error("Error in getting user preset",{error:i}),i}})}},vd=new WeakMap,rv);let yd=sv;dD([S.trace("RoomSocketHandler.joinRoom")],yd.prototype,"joinRoom",1);var Er={},Sd={};Object.defineProperty(Sd,"__esModule",{value:!0}),Sd.Logger=void 0;class lD{constructor(e){}debug(){}warn(){}error(){}}Sd.Logger=lD,Object.defineProperty(Er,"__esModule",{value:!0});var Ed=Er.AwaitQueue=Er.AwaitQueueRemovedTaskError=Er.AwaitQueueStoppedError=void 0;const uD=Sd,Cn=new uD.Logger;class Qu extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Qu)}}Er.AwaitQueueStoppedError=Qu;class Td extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Td)}}Er.AwaitQueueRemovedTaskError=Td;class hD{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,i){return u(this,null,function*(){if(i=i!=null?i:e.name,Cn.debug(`push() [name:${i}]`),typeof e!="function")throw new TypeError("given task is not a function");if(i)try{Object.defineProperty(e,"name",{value:i})}catch(n){}return new Promise((n,r)=>{const s={id:this.nextTaskId++,task:e,name:i,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:o=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),Cn.debug(`resolving task [name:${s.name}]`),n(o);const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:o=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),Cn.debug(`rejecting task [name:${s.name}]: %s`,String(o)),r(o),!this.stopping)){const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){Cn.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Cn.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){Cn.debug(`remove() [taskIdx:${e}]`);const i=Array.from(this.pendingTasks.values())[e];if(!i){Cn.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}i.reject(new Td)}dump(){const e=Date.now();let i=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:i++,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(Cn.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const i=yield e.task();e.resolve(i)}catch(i){e.reject(i)}})}}Ed=Er.AwaitQueue=hD;function pD(t,e){const i=new Error(e);return i.name=t,i}class Ya extends w{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ya):this.stack=new Error(e).stack}}class xt extends w{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,xt):this.stack=new Error(e).stack}}class Tr extends w{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,xt):this.stack=new Error(e).stack}}const av=t=>new Promise(e=>setTimeout(e,t));function Xu(t,e){return u(this,null,function*(){return new Promise((i,n)=>u(this,null,function*(){const{strategy:r,maxRetryCount:s,delayTime:o}=x({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const p=g=>{l=!0,n(g)};for(;c<s;){try{const g=yield t(c,p);return i(g)}catch(g){if(d=g,l)break;if(c<s)r==="linear"?yield av(o*(c+1)):r==="exponential"&&(yield av(o*(c+Math.max(0,c-1))));else break}c+=1}return n(d)}))})}function mD(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function gD(t){return t.map(e=>({uri:e.uri}))}function kd(t){return{codecs:mD(t.codecs),headerExtensions:gD(t.headerExtensions?t.headerExtensions:[])}}function fD(t){const e=RTCRtpReceiver.getCapabilities("audio"),i=RTCRtpReceiver.getCapabilities("video"),n=RTCRtpSender.getCapabilities("audio"),r=RTCRtpSender.getCapabilities("video");t&&(i.codecs=i.codecs.filter(({mimeType:o})=>t===o),r.codecs=r.codecs.filter(({mimeType:o})=>t===o));const s={audio:kd(e),video:kd(i)};return{sender:{audio:kd(n),video:kd(r)},receiver:s}}var pt;class vD{constructor(e,i){f(this,pt,void 0),m(this,"events"),m(this,"sfuType"),v(this,pt,e),this.sfuType=i,this.events=i===et.CF?li:Xt}joinRoom(e,i,n,r=!1,s=null){return u(this,null,function*(){const o={roomUuid:e,displayName:i,prejoined:r,capabilities:n};return s&&(o.location=s),(yield a(this,pt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:Iw.toBinary(o),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const i=(yield a(this,pt).sendMessagePromise(this.events.createWebRTCTransport,tw.toBinary(e))).payload,{transportId:n,description:r,producerIds:s}=Mg.fromBinary(i),o={sdp:r==null?void 0:r.sdp,type:r.type};return{transportId:n,answer:o,producerIds:s}})}produce(e){return u(this,null,function*(){var i,n;const r=(yield a(this,pt).sendMessagePromise(this.events.produce,Vw.toBinary(e))).payload,s=SI.fromBinary(r);return{answer:{sdp:(i=s==null?void 0:s.description)==null?void 0:i.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){if(this.sfuType===et.HIVE)throw new Error("Hive does not support socket consumer operations");const i=(yield a(this,pt).sendMessagePromise(this.events.consume,Lw.toBinary(e))).payload,{consumerIdsMap:{map:n},description:r}=vI.fromBinary(i);return{consumerStateMap:n,sessionDescription:r}})}closeProducer(e){return u(this,null,function*(){const i=(yield a(this,pt).sendMessagePromise(this.events.closeProducer,Gw.toBinary(e))).payload,{description:n}=II.fromBinary(i);return n})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===et.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield a(this,pt).sendMessagePromise(this.events.closeConsumer,Jw.toBinary(e))).payload})}hostControlForPeer(e,i){return u(this,null,function*(){const n={audio:i==="audio",screeShare:!1,video:i==="video",participantId:e},r=(yield a(this,pt).sendMessagePromise(this.events.hostControlPeer,Xw.toBinary(n))).payload;if(!r)return!1;const{status:s}=OI.fromBinary(r);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const i={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield a(this,pt).sendMessagePromise(this.events.hostControlAllPeers,eI.toBinary(i))).payload;if(!n)return!1;const{status:r}=LI.fromBinary(n);return r==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1};a(this,pt).sendMessagePromise(B.kickAll,Lg.toBinary(e))})}kickPeer(e){return u(this,null,function*(){a(this,pt).sendMessagePromise(B.kick,Yg.toBinary(e))})}changeDisplayName(e){return u(this,null,function*(){const i=(yield a(this,pt).sendMessagePromise(this.events.changeDisplayName,Yw.toBinary(e))).payload;if(!i)return!1;const{status:n}=VI.fromBinary(i);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},i=(yield a(this,pt).sendMessagePromise(this.events.selfJoinComplete,Pw.toBinary(e))).payload;return Zl.fromBinary(i)})}audioActivity(e){return u(this,null,function*(){a(this,pt).sendMessage(this.events.audioActivity,nw.toBinary(e))})}}pt=new WeakMap;class Qa extends lt.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...i){const n=this.listenerCount(e);try{return this.emit(e,...i)}catch(r){return h.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:r}),Boolean(n)}}safeEmitAsPromise(e,...i){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...i)})}safeEmitAsPromiseWithTimeout(e,i,...n){return u(this,null,function*(){return new Promise((r,s)=>{setTimeout(s,i,"event request timeout");try{this.emit(e.toString(),...n,r,s)}catch(o){h.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}class Zu extends Qa{constructor(){super(...arguments),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_direction"),m(this,"pc"),m(this,"_transportReady",!1),m(this,"_mapMidTransceiver",new Map),m(this,"enableHighBitrate",!1),m(this,"enableStereo",!1),m(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(h.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){h.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return u(this,null,function*(){h.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return h.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:i=>u(this,null,function*(){h.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i)})}})}init({direction:e,iceServers:i,iceTransportPolicy:n,additionalSettings:r,proprietaryConstraints:s,onTrackHandler:o}){h.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(x({iceServers:i||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},r),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this.pc.createDataChannel("dyte"),i=yield this.pc.createOffer();return yield this.pc.setLocalDescription(i),h.info(`connect offer: ${JSON.stringify(i)}`),{offerSdp:i,callback:n=>u(this,null,function*(){h.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n),e.close()})}})}getTransportStats(){return u(this,null,function*(){return this.pc.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')}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");return i.receiver.getStats()})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),h.debug(`stopSending() [localId:${e}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.sender.replaceTrack(null),this.pc.removeTrack(i.sender),i.direction="inactive";const n=yield this.pc.createOffer();return h.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this.pc.setLocalDescription(n),{offerSdp:n,callback:r=>u(this,null,function*(){h.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this.pc.setRemoteDescription(r),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,i){return u(this,null,function*(){this._assertSendDirection(),i?h.debug(`replaceTrack() [localId:${e}, track.id:${i.id}]`):h.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(i)})}setMaxSpatialLayer(e,i){return u(this,null,function*(){this._assertSendDirection(),h.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${i}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach((s,o)=>{o<=i?s.active=!0:s.active=!1}),yield n.sender.setParameters(r)})}setRtpEncodingParameters(e,i){return u(this,null,function*(){this._assertSendDirection(),h.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(i)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters();r.encodings.forEach((s,o)=>{r.encodings[o]=x(x({},s),i)}),yield n.sender.setParameters(r)})}getSenderStats(e){this._assertSendDirection();const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");return i.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),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:h.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),h.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":h.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":h.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:h.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{h.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{h.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:i}=e;i.onopen=()=>{h.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},i.onclose=()=>{h.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},i.onerror=()=>{h.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class eh extends Zu{static createFactory(){return()=>new eh}get name(){return"Chrome74"}init({direction:e,iceServers:i,iceTransportPolicy:n,additionalSettings:r,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this.pc=new RTCPeerConnection(x({iceServers:i||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},r),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:i,encodings:n,codecOptions:r,screenShare:s}){this._assertSendDirection();const o=this.pc.addTransceiver(i,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){h.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(typeof i=="string"?i:i.kind);h.info(`senders available params: ${JSON.stringify(l)}`);const p=[];r&&r.length&&r.forEach(g=>{var y;const T=l.codecs.find(b=>b.mimeType.includes(g.name));if(g.parameters){h.debug(`codecOption.parameters:${JSON.stringify(g.parameters)}`);const b=((y=T.sdpFmtpLine)==null?void 0:y.split(";"))||[];b.push(...g.parameters);const N=Array.from(new Set(b).values());T.sdpFmtpLine=N.join(";")}p.push(T)}),h.info(`selected codecs: ${JSON.stringify(p)}`),o.setCodecPreferences(p)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),r&&r.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:p}=this,g=this.enableHighBitrate?p?128e3:64e3:p?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${p?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${g}`),c.sdp+=`a=rtcp-fb:111 nack\r
17
+ `}this.midTransceiverMap.set(o.mid,o);const d=l=>u(this,null,function*(){return h.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),o.mid});return h.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:i}=e;i.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class bd extends Zu{constructor(e){super(),m(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new bd(e)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:i,encodings:n,codecOptions:r,screenShare:s}){this._assertSendDirection();const o=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},c=this.pc.addTransceiver(i,x({direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream]},o));if(!this.supportsSendEncodings&&n){n.reverse();const p=c.sender.getParameters();p.encodings=n,yield c.sender.setParameters(p)}const d=(p,g)=>{var y;const T=Ws(p),b=T.media[T.media.length-1],N=b.rtp.filter(K=>g.some(I=>I.name===K.codec)),M=b.fmtp.filter(K=>N.some(I=>I.payload===K.payload)),F=(y=b.rtcpFb)==null?void 0:y.filter(K=>N.some(I=>I.payload===K.payload)),H=N.map(K=>K.payload);return T.media[T.media.length-1].rtp=N,T.media[T.media.length-1].fmtp=M,T.media[T.media.length-1].rtcpFb=F,T.media[T.media.length-1].payloads=H.join(" "),bl(T)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,r),h.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),yield this.pc.setLocalDescription(l),i==="audio"||i.kind==="audio"){const{enableDtx:p,enableStereo:g}=this,y=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:p=>u(this,null,function*(){return h.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),yield this.pc.setRemoteDescription(p),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,i){return u(this,null,function*(){this._assertSendDirection(),h.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${i}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const r=n.sender.getParameters(),s=r.encodings.length-1-i;r.encodings.forEach((o,c)=>{c>=s?o.active=!0:o.active=!1}),yield n.sender.setParameters(r)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:i}=e;i.onmessage=n=>u(this,null,function*(){const r=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(r)))})})}}class th extends Zu{static createFactory(){return()=>new th}get name(){return"Safari12"}send(e){return u(this,arguments,function*({track:i,encodings:n,codecOptions:r,screenShare:s}){this._assertSendDirection(),h.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(i,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),c=RTCRtpSender.getCapabilities(typeof i=="string"?i:i.kind);h.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(p=>{var g;const y=c.codecs.find(T=>T.mimeType.includes(p.name));if(p.parameters){h.info(`Safari12::codecOption.parameters:, ${JSON.stringify(p.parameters)}`);const T=((g=y.sdpFmtpLine)==null?void 0:g.split(";"))||[];T.push(...p.parameters);const b=[...new Set(T).values()];y.sdpFmtpLine=b.join(";")}d.push(y)}),h.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),i==="audio"||i.kind==="audio"){const{enableStereo:p,enableDtx:g}=this,y=this.enableHighBitrate?p?128e3:64e3:p?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${g?"usedtx=1;":""}${p?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:p=>u(this,null,function*(){return h.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),yield this.pc.setRemoteDescription(p),o.mid}),sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:i}=e;i.onmessage=n=>u(this,null,function*(){const r=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,r)})}}}function yD(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var _d,ks,tn,nn,Pn,wd,ih,nh,ov,rh,cv;class SD extends Qa{constructor(e){var i;super(),f(this,nn),f(this,wd),f(this,nh),f(this,rh),m(this,"rtpReceiver"),m(this,"id"),m(this,"localId"),m(this,"producerId"),m(this,"producingTransportId"),m(this,"mimeType"),m(this,"track"),m(this,"peerId"),m(this,"appData"),m(this,"transceiver"),f(this,_d,void 0),f(this,ks,void 0),f(this,tn,void 0),this.id=e.id,this.localId=e.localId,v(this,_d,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,v(this,tn,!1),this.producerId=e.producerId,this.track=e.track,v(this,ks,(i=e.paused)!=null?i:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,j(this,nh,ov).call(this)}get closed(){return a(this,tn)}get kind(){return this.track.kind}get paused(){return a(this,ks)}close(e,i){a(this,tn)||(h.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,nn,Pn)),v(this,tn,!0),i&&(j(this,rh,cv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(a(this,tn))throw new xt("closed");return a(this,_d).getReceiverStats(this.localId)})}pause(){if(h.debug("consumer::pause()",a(this,nn,Pn)),a(this,tn)){h.error("consumer::pause() | Consumer closed",a(this,nn,Pn));return}v(this,ks,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(h.debug("consumer::resume()",a(this,nn,Pn)),a(this,tn)){h.error("Consumer::resume() | Consumer closed",a(this,nn,Pn));return}v(this,ks,!1),this.track.enabled=!0,this.safeEmit("resume")}}_d=new WeakMap,ks=new WeakMap,tn=new WeakMap,nn=new WeakSet,Pn=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},wd=new WeakSet,ih=function(){h.debug('Consumer::track "ended" event',a(this,nn,Pn)),this.safeEmit("trackended")},nh=new WeakSet,ov=function(){this.track.addEventListener("ended",j(this,wd,ih).bind(this))},rh=new WeakSet,cv=function(){try{this.track.removeEventListener("ended",j(this,wd,ih)),this.track.stop()}catch(t){h.error("Consumer::destroyTrack()",q(x({},a(this,nn,Pn)),{error:t}))}};var Oi,Xa,Za,bs,Si,mt,kr,eo,ii,Ei;class ED extends Qa{constructor(e){var i,n;super(),f(this,ii),m(this,"id"),m(this,"localId"),f(this,Oi,void 0),m(this,"kind"),m(this,"appData"),m(this,"rtpSender"),f(this,Xa,void 0),f(this,Za,void 0),f(this,bs,void 0),f(this,Si,!1),f(this,mt,void 0),f(this,kr,void 0),f(this,eo,void 0),this.id=e.id,this.localId=e.localId,v(this,mt,e.track),this.kind=(i=e.track)==null?void 0:i.kind,v(this,kr,e.disableTrackOnPause?!((n=e.track)!=null&&n.enabled):!1),v(this,eo,void 0),v(this,Xa,e.stopTracks),v(this,Za,e.disableTrackOnPause),v(this,bs,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),v(this,Oi,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return a(this,Si)}get track(){return a(this,mt)}get paused(){return a(this,kr)}get maxSpatialLayer(){return a(this,eo)}close(e){return u(this,null,function*(){if(a(this,Si))return;if(h.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,ii,Ei)),v(this,Si,!0),this._destroyTrack(),e===Cd){this.safeEmit("close",{reason:e});return}const{offerSdp:i,callback:n}=yield a(this,Oi).stopSending(this.localId),{answer:r}=yield this.safeEmitAsPromise("close",{offer:i,reason:e});n(r)})}getStats(){return u(this,null,function*(){if(a(this,Si))throw new xt("closed");return a(this,Oi).getSenderStats(this.localId)})}pause(){h.debug("Producer::pause()",a(this,ii,Ei)),a(this,Si)&&h.error("Producer::pause() | Producer closed",a(this,ii,Ei)),v(this,kr,!0),a(this,mt)&&a(this,Za)&&(a(this,mt).enabled=!1),a(this,bs)&&a(this,Oi).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(h.debug("Producer::resume()",a(this,ii,Ei)),a(this,Si)){h.error("Producer::resume() | Producer closed",a(this,ii,Ei));return}v(this,kr,!1),a(this,mt)&&a(this,Za)&&(a(this,mt).enabled=!0),a(this,bs)&&a(this,Oi).replaceTrack(this.localId,a(this,mt)),this.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:i}){if(h.debug(`Producer::replaceTrack() trackId: ${i==null?void 0:i.id}`,a(this,ii,Ei)),a(this,Si)){if(i&&a(this,Xa))try{i.stop()}catch(n){h.error("Producer::replaceTrack",q(x({},a(this,ii,Ei)),{error:n}))}throw new xt("closed")}else if(i&&i.readyState==="ended")throw new xt("track ended");if(i===a(this,mt)){h.debug(`replaceTrack() | same track, ignored trackId: ${i.id}`,a(this,ii,Ei));return}(!a(this,bs)||!a(this,kr))&&(yield a(this,Oi).replaceTrack(this.localId,i)),this._destroyTrack(),v(this,mt,i),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(a(this,Si))throw new xt("closed");if(this.kind!=="video")throw new Ya("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield a(this,Oi).setMaxSpatialLayer(this.localId,e),v(this,eo,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(a(this,Si))throw new xt("closed");if(typeof e!="object")throw new TypeError("invalid params");yield a(this,Oi).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){h.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,ii,Ei)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,mt)&&a(this,mt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,mt))try{a(this,mt).removeEventListener("ended",this._onTrackEnded),a(this,Xa)&&a(this,mt).stop()}catch(i){h.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,q(x({},a(this,ii,Ei)),{error:i}))}}}Oi=new WeakMap,Xa=new WeakMap,Za=new WeakMap,bs=new WeakMap,Si=new WeakMap,mt=new WeakMap,kr=new WeakMap,eo=new WeakMap,ii=new WeakSet,Ei=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function dv(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function sh(t){return Math.random().toString(36).substring(2,2+t)}const Id=1;function lv(t){const e=t;return delete e.payload._bolt,e}function TD(t){return t.payload&&dv(t.payload)}function uv(t){var e,i;return TD(t)&&(i=(e=t.payload._bolt)==null?void 0:e.id)!=null?i:""}var br;const to=class extends lt.EventEmitter{constructor(t,e,i){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),f(this,br,new Map),m(this,"respond",(n,r,s=!1)=>{let o;s?o=to.createErrorResponse(n,r):o=to.createResponse(n,r),this.channel.send(JSON.stringify(o))}),m(this,"notify",n=>{const r=to.createNotification(n);this.channel.send(JSON.stringify(r))}),m(this,"request",n=>u(this,null,function*(){const r=to.createRequest(n),s=new Promise((o,c)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:p=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(p))},timer:setTimeout(()=>{this.queue.delete(d)&&c(new Error(`request timeout for message id: ${d}`))},2e4),cancel:p=>{this.queue.delete(d)&&(clearTimeout(l.timer),c(p))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),s})),m(this,"send",n=>{const r=JSON.stringify(n),s=16384;if(r.length>s){const o=s-200,c=Math.ceil(r.length/o),d=[];for(let p=0;p<c;p+=1){const g=p*o,y=(p+1)*o;d.push(r.slice(g,y))}const l=Br();for(let p=0;p<c;p+=1){const g=d[p],y=JSON.stringify({id:l,count:c,chunkIndex:p,chunk:g});h.debug(`Sending message chunk over dc: ${y}`),this.channel.send(y)}}else h.debug(`Sending message over dc: ${r}`),this.channel.send(r)}),m(this,"processMessage",n=>{var r;a(this,br).has(n.id)||a(this,br).set(n.id,[]);const s=a(this,br).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(o=>o===void 0)){const o=a(this,br).get(n.id),c=o==null?void 0:o.reduce((l,p)=>l+p.chunk,"");a(this,br).delete(n.id);const d=JSON.parse(c);if(!d.payload||!dv(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=(r=d.payload._bolt)==null?void 0:r.version,!this.processResponseMsg(d))return d}}),m(this,"processResponseMsg",n=>{const{id:r}=n.payload._bolt,s=this.queue.get(r);return s?(h.debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(lv(n)):s.resolve(lv(n)),!0):!1}),m(this,"processBoltHandshake",n=>{var r,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(r=n.payload._bolt)==null?void 0:r.id)!=null?s:sh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=i,this.channel=t,this.queue=new Map}};let io=to;br=new WeakMap,m(io,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:q(x({},t.payload),{_bolt:{id:sh(8),type:"REQUEST",version:Id}})}}),m(io,"createResponse",(t,e)=>{var i;if((i=e.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:q(x({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Id}})}}),m(io,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:q(x({},t.payload),{bolt:{id:sh(8),type:"NOTIFY",version:Id}})}}),m(io,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Id}}}));function kD(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(i=>i.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}const Cd="transport closed";var no;const ah=class extends Qa{constructor(t,{id:e,direction:i,handlerFactory:n,iceServers:r,iceTransportPolicy:s,proprietaryConstraints:o,additionalSettings:c,appData:d,config:l}){var p,g,y;super(),m(this,"awaitQueue"),m(this,"observer"),f(this,no,void 0),m(this,"id"),m(this,"serverId"),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,"appData"),h.debug(`constructor() [id: ${e}, direction: ${i}]`),v(this,no,t),this.id=e,this.direction=i;const T=yD(c,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ed,this.observer=new Qa,this.handler=n(),this.handler.enableHighBitrate=(p=l==null?void 0:l.enableHighBitrate)!=null?p:!1,this.handler.enableStereo=(g=l==null?void 0:l.enableStereo)!=null?g:!1,this.handler.enableDtx=(y=l==null?void 0:l.enableDtx)!=null?y:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:r,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:o}),this.appData=d||{},this.transportConnectionPromise=new Promise(b=>{this.observer.once("connected",()=>{b(!0)}),this.observer.once("disconnect",()=>{b(!1)}),this.observer.once("close",()=>{b(!1)})}),this.eventsDCReadyPromise=new Promise(b=>{this.eventsDCReadyPromiseResolver=b}),this.handler.on("@connectionstatechange",b=>{b!==this.connectionState&&(h.debug(`connection state changed to ${b}`),this.connectionState=b,b==="connected"&&(this.connected=!0,this.observer.emit("connected")),b==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(b==="failed"||b==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",b))}),this.handler.on("@icecandidate",({candidate:b})=>{this.closed||this.safeEmit("icecandidate",b)}),this.handler.on("dc_open",b=>{let N=this.datachannels.get(b.label);N||(N||(N=new io(b,b.label,this.serverId),this.datachannels.set(b.label,N)),this.eventsDCFailureTimer=setTimeout(()=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",b.label))},5e3))}),this.handler.on("datachannel",(b,N)=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const M=this.datachannels.get(b.label);if(!M){h.error("unregistered datachannel for message",{rtcChannel:{label:b.label,message:N}});return}try{const F=JSON.parse(N);h.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const H=M.processMessage(F);if(!H)return;h.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(H)}`),this.emit(`datachannel:${b.label}`,M.label,H)}catch(F){h.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(t){this.serverId=t}getDatachannel(t){return this.datachannels.get(t)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(h.debug("Transport close called"),this.connectionState="closed",this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(Cd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(Cd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new xt("closed");return this.handler.getTransportStats()})}connect(t){return u(this,null,function*(){try{if(yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:e,callback:i}=yield this.handler.connect(),{transportId:n,answer:r}=yield t(e);this.setServerId(n),yield i(r)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(a(this,no)===et.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw h.error("transport failed to connect:",{error:e}),e}})}restartIce(){return u(this,null,function*(){if(h.debug("restartIce()"),this.closed)throw new xt("closed");return this.handler.restartIce()})}canProduce(t){return u(this,null,function*(){const{track:e,appData:i}=t;if(e){if(this.direction!=="send")throw new Ya("not a sending Transport");if(e.readyState==="ended")throw new xt("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new Tr("transport not connected");return!0})}produce(t,e){return u(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:i,encodings:n,codecOptions:r,stopTracks:s=!0,disableTrackOnPause:o=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;h.debug(`produce() [track:${i.id}]`);const{producerId:l,localId:p,rtpSender:g}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:y,callback:T,sender:b,mid:N}=yield this.handler.send({track:i,encodings:n,codecOptions:r,screenShare:d==null?void 0:d.screenShare}),{answer:M,producerId:F}=yield e({offer:y,kind:i.kind,paused:o?!i.enabled:!1,appData:q(x({},d||{}),{mid:N}),codecOptions:r,producingTransportId:this.serverId}),H=yield T(M);return{producerId:F,localId:H,rtpSender:b}}),"producer");return this.createProducerObject({id:l,localId:p,track:i,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:g})})}createProducerObject(t){return u(this,null,function*(){const e=new ED(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return u(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new xt("closed");if(this.direction!=="recv")throw new Ya("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.transportConnectionPromise))throw new Tr("transport not connected");return!0})}consume(t,e,i){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const n={},{consumerStates:r,sessionDescription:s,failedProducers:o}=yield e(t);r.forEach((l,p)=>{n[p]=this.createConsumerObjectAndWaitForTrack(q(x({},l),{producerId:p}))});const c=o;s&&(h.info("Session description found, sending negotiation request"),yield i(s));const d=[];return yield Promise.all(Object.entries(n).map(([l,p])=>p.then(g=>d.push(g)).catch(()=>{h.error(`Failed to create consumer object, producer: ${l}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseCodecAndFmtpMappings(t,e){const i=Ws(t.sdp),n={};return i.media.forEach(r=>{e.includes(r.mid.toString())&&(n[r.mid.toString()]={rtp:r.rtp,fmtp:r.fmtp,payloads:r.payloads,rtcpFb:r.rtcpFb})}),n}static setCodecAndFmtpMappings(t,e,i){const n=Ws(t.sdp);return n.media=n.media.map(r=>{if(e.includes(r.mid.toString())){const s=x({},r);return s.rtp=i[r.mid.toString()].rtp,s.fmtp=i[r.mid.toString()].fmtp,s.payloads=i[r.mid.toString()].payloads,s.rtcpFb=i[r.mid.toString()].rtcpFb,s}return r}),q(x({},t),{sdp:bl(n)})}closeConsumers(t,e){return u(this,null,function*(){try{const i=t.map(o=>o.transceiver.mid),n=ah.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i);h.info("Stopping transceivers",{consumerIds:t.map(({id:o})=>o)}),t.forEach(o=>o.close(void 0,!0));let r=yield this.handler.pc.createOffer();h.info("Created offer for closing consumers",{sdp:r.sdp}),r=ah.setCodecAndFmtpMappings(r,i,n),h.info("Updated codec and fmtp mappings in close consumer offer",{sdp:r.sdp}),yield this.setLocalDescription(r),h.info("Successfully set local description in close consumers");const s=yield e(t,r);h.info("Received answer in close consumers",{sdp:s.sdp}),yield this.setRemoteDescription(s),h.info("Remote description was set successfully in close consumers",{sdp:s.sdp})}catch(i){h.error("Failed to close consumers",{error:i})}})}setRemoteOffer(t){return u(this,null,function*(){try{h.info("Received offer from SFU",{sdp:t.sdp}),yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer();h.info("Created answer corresponding to received offer",{sdp:e.sdp});const i=Ws(e.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const r=x({},n),s=r.fmtp.find(o=>o.payload===111);return s&&(s.config+=";stereo=1;sprop-stereo=1"),r.rtcpFb||(r.rtcpFb=[]),r.rtcpFb.some(o=>o.type==="nack")||r.rtcpFb.push({payload:parseInt(r.payloads,10),type:"nack"}),r}return n}),e.sdp=bl(i),h.info("Setting munged SDP",{sdp:e.sdp}),yield this.setLocalDescription(e),h.info("Successfully set local description",{sdp:e.sdp}),e}catch(e){throw h.error("Set remote offer failed",{error:e}),e}})}_ontrack(t){const{track:e,transceiver:i,streams:n}=t;h.info(`track event received [trackId: ${e.id}]`);let r;a(this,no)===et.HIVE?r=`${n[0].id}:${e.kind}`:r=`${i.mid}:${e.kind}`,e.addEventListener("ended",()=>{h.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(r)});const s=this.consumerTrackEvents.get(r);s?(s(e,i),this.consumerTrackEvents.delete(r)):(h.warn(`track event handler not found ${r}`),this.unknownTracksMap.set(r,t))}sendErrorOverDC(t,e,i){const n=this.getDatachannel(t);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});n.respond(e,i,!0)}sendResponseOverDC(t,e,i){const n=this.getDatachannel(t);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});n.respond(e,i)}createConsumerObjectAndWaitForTrack(t){return u(this,null,function*(){const{consumerId:e,producerId:i,producingPeerId:n,producingTransportId:r,streamId:s,paused:o,screenShare:c,appData:d,kind:l,mimeType:p}=t,g=`${s}:${l}`,y=q(x({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((T,b)=>u(this,null,function*(){const N=setTimeout(()=>{this.consumerTrackEvents.delete(g),y.isTimedout=!0,b(y)},5e3),M=(H,K)=>{try{if(H.readyState==="ended")clearTimeout(N),b(y);else{const I=H;I.enabled=!0,this.handler.midTransceiverMap.set(K.mid,K);const re=new SD({id:e,localId:K.mid,transceiver:K,track:I,paused:o,producerId:i,producingPeerId:n,producingTransportId:r,handler:this.handler,appData:q(x({},d),{screenShare:c,peerId:n}),rtpReceiver:K.receiver,mimeType:p});this.consumers.set(e,re),re.once("close",()=>{this.consumers.delete(re.id),this.handler.midTransceiverMap.delete(K.mid)}),h.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:n,producerId:i}}),this.observer.emit("newconsumer",re),clearTimeout(N),T(re)}}catch(I){h.warn("error while creating consumer:",I),clearTimeout(N),b(y)}},F=this.unknownTracksMap.get(g);F?(this.unknownTracksMap.delete(g),M(F.track,F.transceiver)):this.consumerTrackEvents.set(g,M)}))})}setRemoteDescription(t){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return u(this,null,function*(){h.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return kD(t.map(e=>u(this,null,function*(){return Xu(i=>u(this,null,function*(){return i>0&&h.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(x({},e))}))})))})}sendDataChannelMessage(t,e){return u(this,null,function*(){const i=this.getDatachannel(t);if(!i)throw pD("DC_NOT_READY",`${t} datachannel not ready`);const n=(yield i.request(e)).payload;return h.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n})}};let bD=ah;no=new WeakMap;function _D(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){h.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return h.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=rp.getParser(t),i=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;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"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(i.name&&i.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return n?Number(n[1])>=74?"Chrome74":void 0:"Chrome74"}if(i.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;h.warn("Device::this._detectDevice() | browser not supported");return}h.warn("Device::this._detectDevice() | unknown device")}var Pd;class wD{constructor(e,{handlerName:i,handlerFactory:n}={}){if(m(this,"handlerFactory"),f(this,Pd,void 0),h.debug("constructor()"),v(this,Pd,e),i&&n)throw new TypeError("just one of handlerName or handlerInterface can be given");if(n)this.handlerFactory=n;else{if(i)h.debug(`Device::constructor() | handler given: ${i}`);else if(i=_D(),i)h.debug(`Device::constructor() | detected handler: ${i}`);else throw new Error("device not supported");switch(i){case"Chrome74":this.handlerFactory=eh.createFactory();break;case"Safari12":this.handlerFactory=th.createFactory();break;case"Firefox60":this.handlerFactory=bd.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=bd.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${i}"`)}}}createTransport(e){const i=Br();return new bD(a(this,Pd),q(x({id:i},e),{handlerFactory:this.handlerFactory}))}}Pd=new WeakMap;const ID=2e3;var Rn,ro,It,Ct,_s,so,ao,oo,ws,_r,co,lo,Rd,Md,oh,ch,hv,dh,pv,lh,mv,uh,gv,hh,fv,Ad,ph,Dd,mh;class CD extends lt.EventEmitter{constructor(e,i,n){switch(super(),f(this,lo),f(this,Md),f(this,ch),f(this,dh),f(this,lh),f(this,uh),f(this,hh),f(this,Ad),f(this,Dd),f(this,Rn,void 0),f(this,ro,void 0),f(this,It,void 0),f(this,Ct,void 0),f(this,_s,void 0),f(this,so,void 0),f(this,ao,void 0),f(this,oo,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),f(this,ws,void 0),f(this,_r,"all"),f(this,co,void 0),v(this,Rn,e),v(this,_s,i),v(this,co,n),v(this,ro,new wD(n)),v(this,so,new vD(i,n)),n){case et.CF:{v(this,ao,li);break}case et.HIVE:default:{v(this,ao,Xt);break}}a(this,lo,Rd).mediaState={send:{state:wn.NEW,reconnected:!1},recv:{state:wn.NEW,reconnected:!1}},Q.hasFeature(ne.FORCE_RELAY)&&v(this,_r,"relay"),j(this,Md,oh).call(this)}get socket(){return a(this,_s)}get socketHandler(){return a(this,so)}get sendTransport(){return a(this,It)}get recvTransport(){return a(this,Ct)}get events(){return a(this,ao)}get nodeType(){return a(this,co)}createTransports(e){return u(this,null,function*(){var i,n,r,s,o,c,d,l;Q.hasFeature(ne.FORCE_RELAY)&&(h.info("ICE Transport Policy set to relay"),v(this,_r,"relay"));const p=yield at().getICEServers().catch(y=>(h.warn(`failed to get iceservers from server: ${y.message}`),[])),g=[];if(e.send){const y=Q.hasFeature(ne.DISABLE_OPUS_DTX_CF),T=j(this,dh,pv).call(this,{iceServers:p,additionalSettings:{encodedInsertableStreams:(i=a(this,Rn).getValue("modules").e2ee)==null?void 0:i.enabled},config:{enableHighBitrate:(s=(r=(n=a(this,Rn).getValue("defaults").mediaConfiguration)==null?void 0:n.audio)==null?void 0:r.enableHighBitrate)!=null?s:!1,enableStereo:(d=(c=(o=a(this,Rn).getValue("defaults").mediaConfiguration)==null?void 0:o.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:a(this,co)===et.HIVE?!0:!!y},iceTransportPolicy:a(this,_r)});g.push(T)}if(e.recv){const y=j(this,lh,mv).call(this,{iceServers:p,additionalSettings:{encodedInsertableStreams:(l=a(this,Rn).getValue("modules").e2ee)==null?void 0:l.enabled},iceTransportPolicy:a(this,_r)});g.push(y)}yield Promise.all(g)})}stopTransports(e){var i,n;if(e.send&&this.sendTransport!==void 0){const{id:r,serverId:s,direction:o}=a(this,It);h.info("Closing send transport",{transport:{id:r,serverId:s,type:o}}),a(this,It).close(),a(this,It).removeAllListeners(),v(this,It,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:r,serverId:s,direction:o}=a(this,Ct);h.info("Closing recv transport",{transport:{id:r,serverId:s,type:o}}),(i=a(this,Ct))==null||i.close(),(n=a(this,Ct))==null||n.removeAllListeners(),v(this,Ct,void 0)}j(this,Md,oh).call(this)}stopAllTransports(){h.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return u(this,null,function*(){const{id:i,serverId:n,direction:r}=e;j(this,uh,gv).call(this,e);try{const s=Q.hasFeature(ne.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield Xu((o,c)=>u(this,null,function*(){o>0&&h.debug(`Retrying transport connect, count: ${o}`,{transport:{id:i,serverId:n,type:r}});try{if(e.closed)throw new Tr("Cannot reconnect closed transport");yield j(this,ch,hv).call(this,e)}catch(d){if(d instanceof Tr){c(d);return}throw h.error("Failed to connect transport, retrying",{transport:e,error:d}),d}}),{delayTime:100,strategy:"exponential",maxRetryCount:s}),e}catch(s){throw h.error(`Failed to connect send transport after retry: ${e.id}`,{error:s,transport:{id:i,serverId:n,type:r}}),e.close(),e.removeAllListeners(),s}})}handleErrors(e){throw new Error("Method not implemented.")}}Rn=new WeakMap,ro=new WeakMap,It=new WeakMap,Ct=new WeakMap,_s=new WeakMap,so=new WeakMap,ao=new WeakMap,oo=new WeakMap,ws=new WeakMap,_r=new WeakMap,co=new WeakMap,lo=new WeakSet,Rd=function(){return a(this,Rn).getValue("connectionHandler")},Md=new WeakSet,oh=function(){v(this,ws,{send:void 0,recv:void 0})},ch=new WeakSet,hv=function(t){return u(this,null,function*(){const{id:e,direction:i}=t;if(h.info(`Connecting ${i} transport`,{transport:{id:e,type:i}}),!a(this,_s).isConnected)throw new Tr("Socket is not connected");if(t.connectionState==="closed")throw new Tr("Transport is closed");try{yield t.connect(n=>j(this,hh,fv).call(this,i,n)),h.info(`Connected ${i} transport`,{transport:{id:e,serverId:t.serverId,type:i}})}catch(n){throw a(this,oo).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Tr(n.message):n}})},dh=new WeakSet,pv=function(t){return u(this,null,function*(){var e,i;if(a(this,It)&&a(this,It).connected){h.info("Transport send is already connected",{transport:{id:(e=a(this,It))==null?void 0:e.id,serverId:(i=a(this,It))==null?void 0:i.serverId,type:"send"}});return}v(this,It,a(this,ro).createTransport(q(x({},t),{direction:"send"}))),J.configureSendTransport(a(this,It))})},lh=new WeakSet,mv=function(t){return u(this,null,function*(){var e,i;if(a(this,Ct)&&a(this,Ct).connected){h.info("Transport recv is already connected",{transport:{id:(e=a(this,Ct))==null?void 0:e.id,serverId:(i=a(this,Ct))==null?void 0:i.serverId,type:"recv"}});return}v(this,Ct,a(this,ro).createTransport(q(x({},t),{direction:"recv"}))),J.configureRecvTransport(a(this,Ct))})},uh=new WeakSet,gv=function(t){const{direction:e,id:i}=t;t.on("connectionstatechange",n=>u(this,null,function*(){j(this,Dd,mh).call(this,{state:n,direction:e}),h.info(`Transport connection state changed for ${e} transport`,{transport:{id:i,serverId:t.serverId,type:e,status:n}});const r=()=>{const s=a(this,ws)[e];s!==void 0&&(clearTimeout(s),a(this,ws)[e]=void 0)};switch(n){case"connected":r(),a(this,oo).lastConnectionTime=performance.now();break;case"disconnected":a(this,ws)[e]=setTimeout(()=>u(this,null,function*(){yield j(this,Ad,ph).call(this,t)}),ID);break;case"failed":if(t.closed)return;r(),yield j(this,Ad,ph).call(this,t);break}})),t.on("icecandidate",n=>u(this,null,function*(){h.debug("Sending iceCandidate:",{iceCandidate:n})})),t.on("datachannel:events",(n,r)=>u(this,null,function*(){var s,o;h.debug("Got data channel message on event:",{rtcChannel:{label:n,message:r}});try{switch(r.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(n,uv(r),c);break}case"hub-disconnect":{h.debug(`media hub disconnected, full_reconnect: ${(s=r.payload)==null?void 0:s.full_reconnect}`),((o=r.payload)==null?void 0:o.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(c){h.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(h.warn("Events datachannel did not open in 5s",{country:S.location.country}),this.handleErrors("reconnectRecvTransport"))})},hh=new WeakSet,fv=function(t,e){return u(this,null,function*(){const i=t==="recv";try{const{sdp:n,type:r}=e,s={consuming:i,description:{sdp:n,type:r,target:i?qi.SUBSCRIBER:qi.PUBLISHER},producers:[]};return a(this,so).connectTransport(s)}catch(n){throw h.error(`Error in ${t} transport connection:`,{error:n,country:S.location.country}),n}})},Ad=new WeakSet,ph=function(t){return u(this,null,function*(){h.info("Called reconnect transport",{transport:t}),t.close(),t.removeAllListeners();const{direction:e}=t;switch(Q.hasFeature(ne.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,_s).isConnected&&a(this,oo).transportFailureCount[e]>2&&(h.warn(`Multiple disconnections in ${e} transport, forcing relay`),v(this,_r,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(a(this,It)),h.info("Transport reconnected",{transport:a(this,It)}),P.emit(R.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(a(this,Ct)),h.info("Transport reconnected",{transport:a(this,Ct)}),P.emit(R.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:h.warn("Unknown transport direction",{transport:t})}j(this,Dd,mh).call(this,{state:wn.CONNECTED,direction:e})})},Dd=new WeakSet,mh=function(t){const{state:e,direction:i}=t;a(this,lo,Rd).mediaState[i]={state:e,reconnected:!0},P.emit(R.TRANSPORT_STATE_UPDATE,x({transport:i},a(this,lo,Rd).mediaState[i]))};var gh,vv;class PD{constructor(e){f(this,gh),this.recvTransport=e,j(this,gh,vv).call(this)}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const i={type:"create_consumer",payload:{producers:e.map(({producerId:o,producingTransportId:c,kind:d,mimeType:l})=>({producerId:o,producingTransportId:c,preferredCodec:x(x({},d==="video"&&l?{video:l}:{}),d==="audio"&&l?{audio:l}:{})}))}},n=yield this.recvTransport.sendDataChannelMessage("events",i),r=new Map;e.forEach(o=>r.set(o.producerId,o));const s=new Map;return Object.entries(n).forEach(([o,c])=>{const d=r.get(c.producerId);d&&s.set(c.producerId,{consumerId:o,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:s}})}negotiate(e,i,n){return u(this,null,function*(){try{h.debug(`Received offer over dc: ${e.sdp} for transport`);const r=yield this.recvTransport.setRemoteOffer(e),s={type:"answer",payload:{type:r.type,sdp:r.sdp}};return h.debug(`datachannel answer: ${JSON.stringify(s)}`),this.recvTransport.sendResponseOverDC(n,i,s),r}catch(r){throw h.error("datachannel:events::Error:",r),r.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(n,i,r),r}})}close(e){return u(this,null,function*(){if(!e.length)return{};const i=e.map(o=>o.id);h.info(`Closing consumers: ${JSON.stringify(i)}`);const n={type:"close_consumers",payload:{consumers:i}},r=yield this.recvTransport.sendDataChannelMessage("events",n),{failedConsumers:s}=r;return{failedConsumers:s}})}}gh=new WeakSet,vv=function(){this.recvTransport.on("datachannel:events",(t,e)=>u(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:i}=e.payload,n={sdp:i,type:"offer"};this.negotiate(n,uv(e),t);break}default:break}}catch(i){h.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class RD{constructor(e,i,n,r){this.events=e,this.recvTransport=i,this.socket=n,this.socketHandler=r}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const i=new Map,n=[];e.forEach(d=>{const{producingPeerId:l,producerId:p,producingTransportId:g}=d;i.set(p,l),n.push({producingPeerId:l,producerId:p,producingTransportId:g})});const r=yield this.socketHandler.consume({requests:n,consumingTransportId:this.recvTransport.serverId}),s=new Map;e.forEach(d=>s.set(d.producerId,d));const o=new Map,c=[];return Object.entries(r.consumerStateMap).forEach(([d,l])=>{const p=s.get(d);if(!p)return;if(l.errorCode){if(h.warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),l.errorCode==="not_found_track_error"){h.error(`Track not found for producer: ${p.producerId}. This will not be retried.`);return}c.push(p);return}let g={};try{g=JSON.parse(l.producerState.appData)}catch(y){}o.set(d,{consumerId:l.consumerId,producingTransportId:p.producingTransportId,producingPeerId:p.producingPeerId,kind:p.kind,paused:p.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:p.screenShare,mimeType:p.mimeType,appData:g})}),{consumerStates:o,sessionDescription:r.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){try{h.info("Negotiating socket consumer",{transport:this.recvTransport}),h.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const i=yield this.recvTransport.setRemoteOffer(e),n={transportId:this.recvTransport.serverId,description:{sdp:i.sdp,type:i.type,target:qi.SUBSCRIBER}};return h.debug(`sending renegotiate request: ${JSON.stringify(n)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,aw.toBinary(n)),h.info("Renegotiation done",{transport:this.recvTransport}),i}catch(i){h.error("Failed to renegotiate",{error:i});return}})}close(e){return u(this,null,function*(){if(!e.length)return{};const i=(n,r)=>u(this,null,function*(){const s=n.map(l=>l.localId);h.info(`Closing consumers: ${JSON.stringify(s)}`);const o={description:{sdp:r.sdp,type:r.type,target:qi.SUBSCRIBER},consumerIds:s,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(o),d=PI.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,i),"close_consumer"),{}})}}class fh{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,i){return Ws(e).media.filter(n=>i==="video"?n.type==="video":n.type==="audio").at(-1).msid}create(e){return u(this,arguments,function*({offer:i,kind:n,paused:r,appData:s,codecOptions:o,producingTransportId:c}){var d,l;const p=fh.getMSIDFromSDP(i.sdp,n),g={description:{sdp:i.sdp,type:i.type,target:qi.PUBLISHER},paused:r,kind:n,msid:p,appData:JSON.stringify(s),screenShare:(d=s.screenShare)!=null?d:!1,mimeType:`${n}/${(l=o[0])==null?void 0:l.name}`,producingTransportId:c},{answer:y,producerId:T}=yield this.socketHandler.produce(g);return{answer:y,producerId:T}})}}var uo,Is,wr,ho,Od,rn,vh,Mn,po,yh,yv,Nd,Sh,Eh,Sv,Th,Ev,kh,Tv,bh,kv,_h,bv,wh,_v;class MD extends CD{constructor(e,i,n){super(e,i,n),f(this,yh),f(this,Nd),f(this,Eh),f(this,Th),f(this,kh),f(this,bh),f(this,_h),f(this,wh),f(this,uo,void 0),f(this,Is,void 0),f(this,wr,void 0),f(this,ho,void 0),f(this,Od,void 0),f(this,rn,void 0),f(this,vh,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),f(this,Mn,[]),f(this,po,void 0),v(this,uo,e),a(this,yh,yv).mediaState={send:{state:wn.NEW,reconnected:!1},recv:{state:wn.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Is)}get consumers(){return a(this,wr)}get producerIdToConsumerIdMap(){return a(this,ho)}reset(){v(this,Is,new Map),v(this,wr,new Map),v(this,ho,new Map)}setupTransports(e){return u(this,null,function*(){yield this.createTransports(e);let i,n;e.send&&(i=j(this,Eh,Sv).call(this)),e.recv&&(n=j(this,Th,Ev).call(this)),yield Promise.all([i,n])})}createProducer(e,i){return u(this,null,function*(){var n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const r=yield this.sendTransport.produce(e,j(this,kh,Tv).bind(this));return(n=e.appData)!=null&&n.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,r),j(this,bh,kv).call(this,r,i),r}catch(r){throw h.error("Failed to create producer",{error:r}),a(this,vh).producerCreationFailureCount+=1,r}})}closeProducer(e,i){return u(this,null,function*(){var n;const r=this.producers.get(e);if(!r){h.warn(`Producer with ID ${e} was not found`);return}i!=null&&i.stopTrack&&r.track.stop();try{yield this.sendTransport.closeProducer(r),(n=a(this,uo).getValue("modules").e2ee)!=null&&n.enabled&&P.emit(R.E2EE_INACTIVE_PRODUCER,r)}catch(s){h.error("Failed to close producer on server",{error:s,producer:r})}})}closeAllProducers(){return Promise.all(Array.from(a(this,Is).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){a(this,po)||clearTimeout(a(this,po)),v(this,Mn,a(this,Mn).concat(e)),yield j(this,Nd,Sh).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!a(this,rn))return;const i=e.map(r=>this.consumers.get(r)).filter(r=>r!==void 0);if(i.length===0)return;const{failedConsumers:n}=yield a(this,rn).close(i);n!=null&&n.length&&h.warn("Failed to close some consumers",{consumerIds:n})})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,wr).keys()))}switchConsumersToLayer(e,i){return u(this,null,function*(){const n=this.recvTransport.getDatachannel("events");if(!n){h.warn("events datachannel not found");return}const r={type:"switch_consumer_layer",payload:{consumerIds:e,layer:i}};yield n.request(r),h.info(`Consumers switched layers to ${i}`,{consumerIds:e})})}}uo=new WeakMap,Is=new WeakMap,wr=new WeakMap,ho=new WeakMap,Od=new WeakMap,rn=new WeakMap,vh=new WeakMap,Mn=new WeakMap,po=new WeakMap,yh=new WeakSet,yv=function(){return a(this,uo).getValue("connectionHandler")},Nd=new WeakSet,Sh=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=a(this,Mn).splice(0,a(this,Mn).length);try{const i=e.filter(({producerId:s})=>!this.producers.get(s));if(i.length===0)return;const{consumers:n,failedProducers:r}=yield this.recvTransport.consume(i,j(this,_h,bv).bind(this),a(this,rn).negotiate.bind(a(this,rn)));n.forEach(j(this,wh,_v).bind(this)),r!=null&&r.length&&(h.error("Failed to create consumers for producers",{producers:r}),v(this,Mn,a(this,Mn).concat(r)),v(this,po,setTimeout(j(this,Nd,Sh).bind(this),t)))}catch(i){h.error("failed to consume on transport",{error:i})}})},Eh=new WeakSet,Sv=function(){return u(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),v(this,Od,new fh(this.socketHandler))})},Th=new WeakSet,Ev=function(){return u(this,null,function*(){switch(this.recvTransport.on("connect",()=>{a(this,ho).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case et.CF:{v(this,rn,new RD(this.events,this.recvTransport,this.socket,this.socketHandler));break}case et.HIVE:default:v(this,rn,new PD(this.recvTransport))}})},kh=new WeakSet,Tv=function(t){return a(this,Od).create(t)},bh=new WeakSet,kv=function(t,e){t.on("close",(i,n)=>u(this,null,function*(){const{offer:r,reason:s}=i;if(h.info("producer::closing",{debuggingHint:s,producer:q(x({},t),{status:"closing"})}),s!==Cd){const o={producerId:t.id,description:{sdp:r.sdp,type:r.type,target:qi.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(o),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};h.info("producer::closed",{producer:q(x({},t),{status:"closed"})}),n({answer:d})}catch(c){h.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{h.info("producer::trackended",{producer:q(x({},t),{status:"UNKNOWN"})})}),a(this,Is).set(t.id,t)},_h=new WeakSet,bv=function(t){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield a(this,rn).create(t)}catch(e){throw h.error("Error in consume request",{error:e}),e}})},wh=new WeakSet,_v=function(t){t.on("close",e=>u(this,null,function*(){h.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),a(this,wr).delete(t.id),P.emit(R.CONSUMER_CLOSED,{id:t.id})})),a(this,wr).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),P.emit(R.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var Ld,xd,Vd,mo,go,fo,Ud,Fd,vo,$t,Ni,Li,Ir,Cr,An,Bd,Ih,wv,Ch,Iv,Ph,Cv,Rh,Pv;const Mh=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:i=3,hangoverFrames:n=5,noiseAdaptationRate:r=.95,voiceAdaptationRate:s=.99,minEnergyThreshold:o=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){f(this,Ih),f(this,Ch),f(this,Ld,void 0),f(this,xd,void 0),f(this,Vd,void 0),f(this,mo,void 0),f(this,go,void 0),f(this,fo,void 0),f(this,Ud,void 0),f(this,Fd,void 0),f(this,vo,void 0),f(this,$t,void 0),f(this,Ni,void 0),f(this,Li,!1),f(this,Ir,0),f(this,Cr,0),f(this,An,[]),f(this,Bd,void 0),v(this,mo,t),v(this,$t,t),v(this,Ld,e),v(this,xd,i),v(this,Vd,n),v(this,go,r),v(this,fo,s),v(this,Ud,o),v(this,Fd,c),v(this,vo,d),v(this,Bd,l),v(this,Ni,t/2)}get voiceDetected(){return a(this,Li)}processAudioChunk(t){var e,i;const n=j(e=Mh,Ph,Cv).call(e,t),r=j(i=Mh,Rh,Pv).call(i,t);return j(this,Ih,wv).call(this,n),n/a(this,Ni)>a(this,vo)&&n>a(this,$t)&&r>a(this,Ld)?(v(this,Ir,a(this,Ir)+1),v(this,Cr,a(this,Vd)),a(this,Ir)>=a(this,xd)&&v(this,Li,!0)):(v(this,Ir,0),a(this,Cr)>0?v(this,Cr,a(this,Cr)-1):a(this,Li)&&v(this,Li,!1),a(this,Li)||j(this,Ch,Iv).call(this,n)),{energy:n,isVoice:a(this,Li)}}reset(){v(this,Li,!1),v(this,Ir,0),v(this,Cr,0),v(this,$t,a(this,mo)),v(this,Ni,a(this,mo)/2),v(this,An,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,$t),backgroundNoiseEnergy:a(this,Ni),energyRatioThreshold:a(this,vo)}}};let Ah=Mh;Ld=new WeakMap,xd=new WeakMap,Vd=new WeakMap,mo=new WeakMap,go=new WeakMap,fo=new WeakMap,Ud=new WeakMap,Fd=new WeakMap,vo=new WeakMap,$t=new WeakMap,Ni=new WeakMap,Li=new WeakMap,Ir=new WeakMap,Cr=new WeakMap,An=new WeakMap,Bd=new WeakMap,Ih=new WeakSet,wv=function(t){a(this,Li)?v(this,$t,a(this,fo)*a(this,$t)+(1-a(this,fo))*t):v(this,$t,a(this,go)*a(this,$t)+(1-a(this,go))*a(this,Ni)),v(this,$t,Math.max(a(this,Ud),Math.min(a(this,Fd),a(this,$t))))},Ch=new WeakSet,Iv=function(t){if(t<a(this,$t)*1.2)if(a(this,An).push(t),a(this,An).length>a(this,Bd)&&a(this,An).shift(),a(this,An).length>=10){const e=[...a(this,An)].sort((n,r)=>n-r),i=Math.floor(e.length/2);v(this,Ni,e[i])}else v(this,Ni,.95*a(this,Ni)+.05*t)},Ph=new WeakSet,Cv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,i)=>e+i)/t.length)},Rh=new WeakSet,Pv=function(t){let e=0;for(let i=1;i<t.length;i+=1)(t[i]>=0&&t[i-1]<0||t[i]<0&&t[i-1]>=0)&&(e+=1);return e},f(Ah,Ph),f(Ah,Rh);const AD=60,DD=400;var Dn,On,xi,Pr,Rr,yo,Cs,So,Nn,Mr,Eo,Dh,Rv,Wd,Oh,Nh,Mv,Lh,Av;const jd=class{constructor(t){f(this,Dh),f(this,Nh),f(this,Dn,void 0),f(this,On,void 0),f(this,xi,void 0),f(this,Pr,void 0),f(this,Rr,void 0),f(this,yo,void 0),f(this,Cs,void 0),f(this,So,void 0),f(this,Nn,void 0),f(this,Mr,void 0),f(this,Eo,void 0),this.reportRequest=t,v(this,Pr,new AudioContext),v(this,Rr,a(this,Pr).createAnalyser()),a(this,Rr).fftSize=2048,v(this,So,new Ah)}set producerId(t){v(this,xi,t)}set audioTrack(t){v(this,yo,t);const e=new MediaStream;e.addTrack(a(this,yo)),a(this,Pr).createMediaStreamSource(e).connect(a(this,Rr))}start(){h.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,xi)}`),a(this,Dn)&&Wr(a(this,Dn)),v(this,Dn,rc(()=>u(this,null,function*(){var t;if(!a(this,yo)||!a(this,xi))return;const{energy:e}=j(this,Dh,Rv).call(this),i=j(t=jd,Wd,Oh).call(t,e);let n=.9;a(this,Eo)!==i&&a(this,Eo)?n=.9:i?n=.3:n=.5,v(this,Cs,(a(this,Cs)||0)*(1-n)+e*n)}),AD)),a(this,On)&&Wr(a(this,On)),v(this,On,rc(j(this,Nh,Mv).bind(this),DD))}stop(){try{h.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,xi)}`),a(this,Dn)&&(Wr(a(this,Dn)),v(this,Dn,void 0)),a(this,On)&&(Wr(a(this,On)),v(this,On,void 0))}catch(t){}a(this,So).reset()}};let xh=jd;Dn=new WeakMap,On=new WeakMap,xi=new WeakMap,Pr=new WeakMap,Rr=new WeakMap,yo=new WeakMap,Cs=new WeakMap,So=new WeakMap,Nn=new WeakMap,Mr=new WeakMap,Eo=new WeakMap,Dh=new WeakSet,Rv=function(){var t;a(this,Pr).state==="suspended"&&a(this,Pr).resume().then(()=>{h.debug("AudioActivityReporter: AudioContext forced resumed")}).catch(s=>{h.error("AudioActivityReporter: Error resuming AudioContext",s)});const e=new Float32Array(a(this,Rr).frequencyBinCount);a(this,Rr).getFloatTimeDomainData(e);const{energy:i,isVoice:n}=a(this,So).processAudioChunk(e),r=j(t=jd,Lh,Av).call(t,i);return Q.hasFeature(ne.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&h.debug(`AudioActivityReporter: producer: ${a(this,xi)}, energy: ${a(this,Cs)},
18
+ slogScale: ${r}, isVoice: ${n}, minEnergy: ${a(this,Nn)},
19
+ maxEnergy: ${a(this,Mr)}`),r===-1/0||i<1e-6?{energy:0,isVoice:!1}:((!a(this,Nn)||r<a(this,Nn))&&v(this,Nn,r),(!a(this,Mr)||r>a(this,Mr))&&v(this,Mr,r),{energy:(r-a(this,Nn))/(a(this,Mr)-a(this,Nn))*10||0,isVoice:n})},Wd=new WeakSet,Oh=function(t){return t<5},Nh=new WeakSet,Mv=function(t=a(this,Cs)){var e;if(!a(this,xi)||!t){Q.hasFeature(ne.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&h.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xi)}`);return}const i={producerId:a(this,xi),energy:Math.round(t),silent:j(e=jd,Wd,Oh).call(e,t)};v(this,Eo,i.silent),this.reportRequest(i)},Lh=new WeakSet,Av=function(t){const e=Math.log10(t);return Math.round(e)},f(xh,Wd),f(xh,Lh);const OD=(t=!1)=>{const e=new window.AudioContext,i=e.createOscillator();i.type="triangle",i.frequency.setValueAtTime(20,e.currentTime);const n=e.createGain();n.gain.setValueAtTime(0,e.currentTime),i.connect(n);const r=e.createMediaStreamDestination();n.connect(r),i.start();const s=r.stream.getAudioTracks()[0];return s.enabled=t,s},ND=(t=!1)=>{var e,i;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(e=n==null?void 0:n.getSettings().height)!=null?e:720,r.width=(i=n==null?void 0:n.getSettings().width)!=null?i:1280;const s=r.getContext("2d");s.fillStyle="black",s.fillRect(0,0,r.width,r.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,r.width,r.height)},1e3);const o=r.captureStream().getVideoTracks()[0];return o.enabled=t,o};var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,ue=(t,e,i,n)=>{for(var r=n>1?void 0:n?xD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&LD(e,i,r),r};const Vi=["video/VP9","video/VP8"];var Hd,Gd,Pt,$,To,Ar,Vt,Ps,Rs,Dr,qd,Ln,ko,Ms,As,Ut,Kt,Or,Ds,gt,Rt,Os,bo,Vh,Dv,Uh,Ov,Fh,Nv;class le{constructor(e,i,n){f(this,Or),f(this,gt),f(this,Os),f(this,Vh),f(this,Uh),f(this,Fh),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),f(this,Hd,void 0),f(this,Gd,void 0),f(this,Pt,void 0),f(this,$,void 0),f(this,To,void 0),f(this,Ar,void 0),f(this,Vt,void 0),f(this,Ps,void 0),f(this,Rs,void 0),f(this,Dr,void 0),f(this,qd,void 0),f(this,Ln,void 0),f(this,ko,void 0),f(this,Ms,void 0),f(this,As,void 0),f(this,Ut,void 0),f(this,Kt,void 0),m(this,"partialJoinRoomPromise");var r,s;this.context=e;const{socket:o}=n;this.mediaJoined=!1,v(this,Ms,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,As,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Ar,i),v(this,Pt,o),v(this,Ps,!1),v(this,$,new MD(e,o,i)),v(this,Vt,a(this,$).events),v(this,Ln,new Set),v(this,Ut,new Map),v(this,Rs,!1),v(this,Dr,new Ed),i===et.CF&&!navigator.isReactNative&&v(this,Kt,new xh(a(this,$).socketHandler.audioActivity.bind(a(this,$).socketHandler))),this.e2ee=(s=(r=e.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,qd,Cc(()=>u(this,null,function*(){if(!a(this,Or,Ds).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(a(this,Gd),a(this,Hd),{},!0,!0);c&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return a(this,Or,Ds).mediaJoined}set mediaJoined(e){a(this,Or,Ds).mediaJoined=e}reset(e=!0){a(this,$).closeAllProducers(),a(this,$).closeAllConsumers(),a(this,Ut).clear(),a(this,Ln).clear(),e&&(this.partialJoinRoomPromise=void 0,a(this,Dr).stop(),a(this,$).stopAllTransports(),a(this,$).reset(),v(this,Dr,new Ed))}joinRoom(e,i){return u(this,arguments,function*(n,r,s={},o=!1,c=!1){a(this,Or,Ds).mediaJoinAttempted=!0,v(this,Ps,!0),this.reset(o);const d=at().ipInfo;if(d!=null&&d.loc&&!a(this,ko)){const p=d.loc.split(",");v(this,ko,{latitude:parseFloat(p[0]),longitude:parseFloat(p[1])})}let l;try{return l=yield a(this,Dr).push(()=>this._joinRoom(n,r,s,c,a(this,ko)),"joinRoom"),l}catch(p){l={roomJoined:!1}}return l.roomJoined||P.emit(R.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,i,n=!1,r=void 0){return u(this,null,function*(){var s;const{ipInfo:o}=at();let c=r;if(o!=null&&o.loc&&!r){const[p,g]=o.loc.split(",").map(parseFloat);c={latitude:p,longitude:g}}const d=(s=Q.getValue(ne.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=fD(d);v(this,To,l),yield Xu((p,g)=>u(this,null,function*(){if(!a(this,Pt).isConnected){g(new Error("socket is not connected"));return}p>0&&h.warn(`retrying sending join room request, count: ${p}`);try{yield a(this,$).socketHandler.joinRoom(i,e,l,n,c)}catch(y){throw h.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Q.hasFeature(ne.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield a(this,$).setupTransports({send:!0,recv:!0}),a(this,Ar)!==et.HIVE&&Q.hasFeature(ne.PRECREATE_PRODUCERS)&&(this.shareWebcam(ND()),this.shareMic(OD()))})}partialJoinRoom(e,i,n=!1,r=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=a(this,Dr).push(()=>this._partialJoinRoom(e,i,n,r)),this.partialJoinRoomPromise})}_joinRoom(e,i){return u(this,arguments,function*(n,r,s={},o=!1,c=null){v(this,Gd,n);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(n,r,o,c)}catch(d){h.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:r,roomViewType:"groupCall",deviceInfo:q(x({},_e.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return h.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield a(this,$).socketHandler.notifySelfJoinComplete();return v(this,Hd,e.roomUuid),v(this,Rs,!0),v(this,Ps,!1),!0}catch(e){return h.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){a(this,$).stopAllTransports(),v(this,Rs,!1),a(this,Or,Ds).mediaJoinAttempted=!1;const e={closeRoom:!1};a(this,Pt).sendMessagePromise(a(this,Vt).leaveRoom,Mw.toBinary(e)).then(i=>{var n;(n=mI.fromBinary(i.payload))!=null&&n.closed||h.warn("weird state on peer closed and should not happen")}).catch(i=>{h.error("error on sending leave room request",{error:i})}),J.callEnded(),S.destruct()})}getConsumers(){return a(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,i="default"){return u(this,null,function*(){const n=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&n.add(s.producingPeerId)});const r=i==="default"?e.filter(s=>!n.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(r.map(s=>{const o=a(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!o){h.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return a(this,$).closeConsumer(o)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():a(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const i=e.reduce((n,r)=>{const s=a(this,$).producerIdToConsumerIdMap.get(r.producerId);return s?(n.push(s),n):(h.warn(`consumer not found in deactivate producers: ${r.producerId}`),n)},[]);yield a(this,$).closeConsumers(i)})}_shareWebcam(e,i){return u(this,null,function*(){const n=i==="video/VP9"?Te.WEBCAM:Te.WEBCAM_BACKUP,r=j(this,gt,Rt).call(this,n);if(r){const p=yield r;if(a(this,$).producers.has(p)){const g=a(this,$).producers.get(p);if(!g.closed&&!navigator.isReactNative)return yield g.replaceTrack({track:e}),yield this.resumeWebcam(n),e;yield this.disableWebcam(i)}return this._shareWebcam(e,i)}const s=j(this,Fh,Nv).call(this,e,i),o=Mc(this.context,"disableSimulcast"),c=a(this,Ar)===et.CF?ne.ENABLE_CF_SIMULCAST:ne.ENABLE_HIVE_SIMULCAST;!o&&Q.hasFeature(c)?(h.info(`Simulcast enabled for SFU: ${a(this,Ar)}`),s.encodings=u1(e)):h.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Ar)}`),Q.hasFeature(ne.TRACK_HINT)&&(s.track.contentHint=Q.getValue(ne.TRACK_HINT));const d=()=>{h.info("Disabling video due to the producer closure"),a(this,Ut).delete(n)},l=a(this,$).createProducer(s,d);return j(this,Os,bo).call(this,n,l.then(p=>p.id)),l.then(p=>p.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(Q.hasFeature(ne.FORCE_VIDEO_CODEC)){const i=Q.getValue(ne.FORCE_VIDEO_CODEC).toString();if(i)return h.debug(`Calling _shareWebcam with forced video codec: ${i}`),this._shareWebcam(e,i)}return yield Promise.all(Vi.map(i=>{var n,r;return((r=(n=a(this,To).sender)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(s=>s.mimeType===i))>=0&&a(this,As).get(i).size>0?(h.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(e,i)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:i,audio:n}=e;if(i===void 0)return;const r={track:i,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:_e.isElectron()},stopTracks:!1},s=()=>{h.info("Disabling screenShare due to the producer closure"),a(this,Ut).delete(Te.SCREENSHARE_VIDEO),a(this,Ut).delete(Te.SCREENSHARE_AUDIO)},o=a(this,$).createProducer(r,s);j(this,Os,bo).call(this,Te.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(n){const d={track:n,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:_e.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=a(this,$).createProducer(d,l),j(this,Os,bo).call(this,Te.SCREENSHARE_AUDIO,c.then(p=>p.id))}yield Promise.all([o,c||Promise.resolve()]),J.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new xt("track undefined");const i=j(this,gt,Rt).call(this,Te.MIC);if(i){const o=yield i;if(a(this,$).producers.has(o)){const c=a(this,$).producers.get(o);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),a(this,Kt)&&(a(this,Kt).audioTrack=e,a(this,Kt).producerId=o,a(this,Kt).start());return}yield a(this,$).closeProducer(o,{stopTrack:!1})}yield this.shareMic(e);return}const n=j(this,Uh,Ov).call(this,e),r=()=>{a(this,Ut).delete(Te.MIC)},s=a(this,$).createProducer(n,r);j(this,Os,bo).call(this,Te.MIC,s.then(o=>o.id)),yield s.then(o=>{a(this,Kt)&&(a(this,Kt).audioTrack=o.track,a(this,Kt).producerId=o.id,a(this,Kt).start())})}catch(i){throw new w(i)}})}pauseMic(){return u(this,null,function*(){var e;const i=yield j(this,gt,Rt).call(this,Te.MIC),n=a(this,$).producers.get(i);if(!n){h.error("pauseMic::could_not_find_mic_producer");return}if(n.paused){h.info("pauseMic::mic_producer_already_paused");return}n.pause(),(e=a(this,Kt))==null||e.stop();const r={producerId:n.id,pause:!0};a(this,Pt).sendMessage(a(this,Vt).toggleProducer,Nc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const e=yield j(this,gt,Rt).call(this,Te.WEBCAM),i=yield j(this,gt,Rt).call(this,Te.WEBCAM_BACKUP),n=a(this,$).producers.get(e),r=a(this,$).producers.get(i);if(!n&&!r){h.error("pauseWebcam::could_not_find_webcam_producer");return}const s=o=>{const c={producerId:o.id,pause:!0};a(this,Pt).sendMessage(a(this,Vt).toggleProducer,Nc.toBinary(c))};n&&(n.pause(),s(n)),r&&(r.pause(),s(r))})}resumeMic(){return u(this,null,function*(){const e=yield j(this,gt,Rt).call(this,Te.MIC),i=a(this,$).producers.get(e);if(!i){h.error("resumeMic::could_not_find_mic_producer");return}if(!i.pause){h.info("resumeMic::mic_producer_already_resumed");return}i.resume(),i.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,i);const n={producerId:i.id,pause:!1};a(this,Pt).sendMessage(a(this,Vt).toggleProducer,Nc.toBinary(n))})}resumeWebcam(){return u(this,arguments,function*(e=Te.WEBCAM){const i=yield j(this,gt,Rt).call(this,e),n=a(this,$).producers.get(i);if(!n){h.error("resumeWebcam::could_not_find_webcam_producer");return}if(!n.paused){h.info("resumeWebcam::webcam_producer_already_resumed");return}n.resume(),n.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,n);const r={producerId:n.id,pause:!1};a(this,Pt).sendMessage(a(this,Vt).toggleProducer,Nc.toBinary(r))})}disableWebcam(e){return u(this,null,function*(){const i=e==="video/VP9"?Te.WEBCAM:Te.WEBCAM_BACKUP,n=yield j(this,gt,Rt).call(this,i);j(this,Vh,Dv).call(this,i),n&&(yield a(this,$).closeProducer(n))})}disableMic(){return u(this,null,function*(){var e;const i=yield j(this,gt,Rt).call(this,Te.MIC);i&&(yield a(this,$).closeProducer(i)),(e=a(this,Kt))==null||e.stop(),a(this,Ut).delete(Te.MIC)})}disableScreenShare(){return u(this,null,function*(){h.info("screen_sharing_stopped"),J.screenShareStop();const e=yield j(this,gt,Rt).call(this,Te.SCREENSHARE_VIDEO),i=yield j(this,gt,Rt).call(this,Te.SCREENSHARE_AUDIO);e&&(yield a(this,$).closeProducer(e)),i&&(yield a(this,$).closeProducer(i)),a(this,Ln).clear(),a(this,Ut).delete(Te.SCREENSHARE_VIDEO),a(this,Ut).delete(Te.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,i){return u(this,null,function*(){if(e){const n=yield j(this,gt,Rt).call(this,Te.WEBCAM),r=yield j(this,gt,Rt).call(this,Te.WEBCAM_BACKUP);yield a(this,$).closeProducer(n,{stopTrack:!1}),yield a(this,$).closeProducer(r,{stopTrack:!1}),this.shareWebcam(e)}if(i){const n=yield j(this,gt,Rt).call(this,Te.SCREENSHARE_VIDEO);yield a(this,$).closeProducer(n,{stopTrack:!1}),this.shareScreen({video:i})}})}changeDisplayName(e,i){return u(this,null,function*(){const n={displayName:e,participantId:i!=null?i:this.peerId};if(!(yield a(this,$).socketHandler.changeDisplayName(n)))throw new Error("failed to change display name!")})}kick(e){const i={peerIds:[e]};a(this,$).socketHandler.kickPeer(i)}kickAll(){a(this,$).socketHandler.kickAll()}muteAll(e){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const i={participantId:e!=null?e:""};try{yield a(this,Pt).sendMessagePromise(a(this,Vt).globalPinPeer,Bw.toBinary(i))}catch(n){h.error("Error in pinning peer:",{error:n})}})}validateScreenShare(e){return this.peerId===e.peerId&&a(this,$).producers.get(e.producerId)&&a(this,Ln).add(e.consumerPeerId),a(this,Ln).size}switchConsumersToLayer(e,i){return u(this,null,function*(){a(this,$).switchConsumersToLayer(e,i)})}handleSocketEvents(){return u(this,null,function*(){a(this,Pt).on(a(this,Vt).peerProducerCreateBroadcast,({payload:e})=>{var i,n;if(this.mediaJoined)try{const{participantId:r,producerState:s}=GI.fromBinary(e);if(r===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Ai.AUDIO?"audio/opus":"video/VP8"),s.kind===Ai.VIDEO&&!s.screenShare&&((n=(i=a(this,To).receiver)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(o=>o.mimeType===Vi[0]))>=0&&a(this,Ms).get(Vi[0]).has(r)&&s.mimeType!==Vi[0]){h.warn(`Ignoring producer: ${s.producerId}`);return}h.info(`producer created broadcast: ${r}, producer state: ${s}`),P.emit(R.NEW_PRODUCER,{peerId:r,producer:q(x({},s),{kind:s.kind===Ai.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){h.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Pt).on(a(this,Vt).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:i,initiatorParticipantId:n,producerState:{kind:r,pause:s,producerId:o}}=Bg.fromBinary(e),c=r===Ai.AUDIO?"audio":"video";if(h.info(`producer toggle broadcast: ${i}, producerId: ${o}, kind:${c}, paused:${s} payload: ${JSON.stringify(Bg.fromBinary(e))}`),i===this.peerId&&n!==this.peerId&&s&&P.emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),i===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:i,producerId:o,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===o).forEach(d=>{d.paused!==s&&(h.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),P.emit(R.CONSUMER_PAUSED,{id:d.id})):(d.resume(),P.emit(R.CONSUMER_RESUMED,{id:d.id})))})}catch(i){h.error("error in producer toggle broadcast handler",{error:i})}}),a(this,Pt).on(a(this,Vt).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:i}=eu.fromBinary(e);if(i===this.peerId)return;h.info(`peer left broadcast:${i}`),a(this,Ln).delete(i),a(this,$).consumers.forEach(n=>{n.peerId===i&&n.close()}),P.emit(R.PEER_CLOSED,{id:i})}catch(i){h.error("error in peer left broadcast",{error:i})}}),a(this,Pt).on(a(this,Vt).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:i,producerState:{producerId:n}}=$I.fromBinary(e);if(i===this.peerId)return;h.info(`producer closed broadcast:${i}`),P.emit(R.PRODUCER_CLOSED,{peerId:i,producerId:n});const r=a(this,$).producerIdToConsumerIdMap.get(n);if(!r){h.warn(`no consumer found for producer:${n}`);return}h.info(`closing consumer ${r}, producer id: ${n}`),a(this,$).closeConsumer(r).then(()=>{h.info(`closed consumer: ${r}`),a(this,$).producerIdToConsumerIdMap.delete(n),P.emit(R.CONSUMER_CLOSED,{id:r})}).catch(s=>{h.error("error closing consumer",{error:s})})}catch(i){h.error("error on producer close broadcast",{error:i})}}),a(this,Pt).on(a(this,Vt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Ps)&&!a(this,Rs)||(h.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),a(this,qd).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(e=>{e.forEach((i,n)=>{const r=a(this,$).consumers.get(n);r&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:n,kind:r.kind,peerId:r.peerId,score:i.score,scoreStats:i})})}),J.onProducerScore(e=>{e.forEach((i,n)=>{const r=Array.from(a(this,$).producers.values()).find(s=>s.id===n);r&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:n,kind:r.kind,appData:r.appData,score:i.score,scoreStats:i})})})}handlePeerCapabilities(e,i){var n,r,s,o;for(let c=0;c<=Vi.length;c+=1){const d=Vi[c];if(((r=(n=i==null?void 0:i.receiver)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(l=>l.mimeType===d))>=0||c===Vi.length-1){a(this,As).get(d).add(e);break}}for(let c=0;c<=Vi.length;c+=1){const d=Vi[c];if(((o=(s=i==null?void 0:i.sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(l=>l.mimeType===d))>=0||c===Vi.length-1){a(this,Ms).get(d).add(e);break}}}handlePeerLeaving(e){Q.hasFeature(ne.FORCE_VIDEO_CODEC)||(a(this,Ms).forEach(i=>i.delete(e)),a(this,As).forEach((i,n)=>{i.delete(e),i.size===0&&this.disableWebcam(n)}))}}Hd=new WeakMap,Gd=new WeakMap,Pt=new WeakMap,$=new WeakMap,To=new WeakMap,Ar=new WeakMap,Vt=new WeakMap,Ps=new WeakMap,Rs=new WeakMap,Dr=new WeakMap,qd=new WeakMap,Ln=new WeakMap,ko=new WeakMap,Ms=new WeakMap,As=new WeakMap,Ut=new WeakMap,Kt=new WeakMap,Or=new WeakSet,Ds=function(){return this.context.getValue("connectionHandler")},gt=new WeakSet,Rt=function(t){return a(this,Ut).get(t)},Os=new WeakSet,bo=function(t,e){return a(this,Ut).set(t,e)},Vh=new WeakSet,Dv=function(t){return a(this,Ut).delete(t)},Uh=new WeakSet,Ov=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},Fh=new WeakSet,Nv=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ue([S.trace("MediaNodeClient.reset",{country:S.location.country})],le.prototype,"reset",1),ue([S.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1),ue([S.trace("MediaNodeClient.completeJoinRoom")],le.prototype,"completeJoinRoom",1),ue([S.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1),ue([S.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1),ue([S.trace("MediaNodeClient.deactivatePeers")],le.prototype,"deactivatePeers",1),ue([S.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1),ue([S.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1),ue([S.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1),ue([S.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1),ue([S.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1),ue([S.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1),ue([S.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1),ue([S.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1),ue([S.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1),ue([S.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1),ue([S.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1),ue([S.trace("HiveClient.disableMic")],le.prototype,"disableMic",1),ue([S.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1),ue([S.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1),ue([S.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1),ue([S.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1),ue([S.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1),ue([S.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1),ue([S.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1),ue([S.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1),ue([S.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1),ue([S.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1),ue([S.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1),ue([S.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function Lv(t,e,i){const n=t.getValue("roomNodeClient");if(n){if(n)return n;throw new Error("Room node client already set up.")}const r=new le(t,e,i);return t.setValue("roomNodeClient",r),r}function xv(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(i){h.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var VD=Object.defineProperty,UD=Object.getOwnPropertyDescriptor,Nr=(t,e,i,n)=>{for(var r=n>1?void 0:n?UD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&VD(e,i,r),r},Lr,Ui,Mt,ni,Ti,Vv;const Uv=(Vv=class{constructor(t,e,i,n){f(this,ni),m(this,"self"),m(this,"authToken"),f(this,Lr,void 0),m(this,"viewType"),f(this,Ui,void 0),f(this,Mt,void 0);const{socket:r}=i,s=t.getValue("authToken");this.self=e,v(this,Mt,t),this.viewType=n,this.authToken=s,v(this,Lr,r),v(this,Ui,i),e.config.viewType!==yt.Chat&&this.setupEvents()}get peerId(){return a(this,Mt).getValue("peerId")}get mediaJoined(){return a(this,Mt).getValue("connectionHandler").mediaJoined}static init(t,e,i,n,r){return u(this,null,function*(){const s=at(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield it.__init__(t,i,n,r,r.name,c);if(navigator.product!=="ReactNative"){const l=!Q.hasFeature(ne.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();h.info("populated_full_device_list",{devices:JSON.stringify(p)}),J.devices("AUDIO",p==null?void 0:p.filter(g=>g.kind==="audioinput")),J.devices("VIDEO",p==null?void 0:p.filter(g=>g.kind==="videoinput")),J.devices("SPEAKER",p==null?void 0:p.filter(g=>g.kind==="audiooutput")),h.info("Callstats:: initializing");try{yield J.initialize({peerId:o,engineName:_e.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Q.getAllFlags(),logger:h,apiHostnames:bg(t),skipConnectivityChecks:l}),h.info("Callstats:: initialized")}catch(g){h.error("Callstats:: initialization failed",{error:g})}}),0)}else h.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Uv(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:i,permissions:n,audioEnabled:r,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(n.canProduceAudio&&r)try{yield a(this,ni,Ti).shareMic(e)}catch(d){this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield a(this,ni,Ti).shareWebcam(i);d&&d.id!==i.id&&Q.hasFeature(ne.EXP_RESHARE)&&(yield a(this,ni,Ti).shareWebcam(d))}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=a(this,ni,Ti))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){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(){h.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(h.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){h.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(h.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){h.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),a(this,ni,Ti).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Q.hasFeature(ne.REFRESH_ID_ON_DISCONNECTION)&&(e=Br()),a(this,Lr).updateURL(e),S.resetPeerId(e),at().setHeader("dyte-tracing-id",e),Zn.remapContext(e,a(this,Mt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Ui).on(B.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Ui).on(Bc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),a(this,Ui).on(B.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Ui).on(B.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Ui).on(B.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:i,scoreStats:n})=>{var r;const s=(r=i==null?void 0:i.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:n})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Ui).joinRoom(this.self);a(this,Ui).socket.flush();const i=Ru(e.stageType);if(a(this,Mt).setValue("stageStatus",i,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,Mt).notify("stageStatus")}catch(e){throw h.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,i;if(t==="rejected"){try{(e=a(this,Lr))==null||e.disconnect()}catch(n){h.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,Mt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,Mt).notify("stageStatus");try{(i=a(this,Lr))==null||i.disconnect()}catch(n){h.error("SelfController::leaveRoom::socketDisconnect")}xv(a(this,Mt)),yd.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,i;const{peerId:n,viewType:r,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,Mt).getAllValues(),{sfu:d}=c;try{if(r===yt.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}Lv(a(this,Mt),d,{socket:a(this,Lr),peerId:n})}const{roomJoined:l}=(i=yield(e=a(this,ni,Ti))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?i:{};if(!l)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw h.error("Error:SelfController.mediaRoomJoin",{error:l}),new w("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,Mt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===yt.Webinar)&&a(this,ni,Ti)&&(a(this,ni,Ti).mediaJoined&&t!=="disconnected"&&(yield a(this,ni,Ti).leaveRoom()),!(t==="stageLeft"&&e===yt.Livestream)&&(a(this,ni,Ti).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()})}},Lr=new WeakMap,Ui=new WeakMap,Mt=new WeakMap,ni=new WeakSet,Ti=function(){return a(this,Mt).getValue("roomNodeClient")},Vv);let xn=Uv;Nr([S.trace("SelfController.resetSelf")],xn.prototype,"resetSelf",1),Nr([S.trace("SelfController.setupEvents")],xn.prototype,"setupEvents",1),Nr([S.trace("SelfController.joinRoom")],xn.prototype,"joinRoom",1),Nr([S.trace("SelfController.leaveRoom")],xn.prototype,"leaveRoom",1),Nr([S.trace("SelfController.joinMediaRoom")],xn.prototype,"joinMediaRoom",1),Nr([S.trace("SelfController.leaveMediaRoom")],xn.prototype,"leaveMediaRoom",1),Nr([S.trace("SelfController.init")],xn,"init",1);var Jd;class FD{constructor(e){f(this,Jd,void 0),v(this,Jd,e)}on(e,i){let n;e===B.roomPeerCount?n=Hg.fromBinary.bind(Hg):n=of.fromBinary.bind(of),a(this,Jd).on(e,({payload:r})=>{const s=n(r);return i(s)})}}Jd=new WeakMap;var $d;class BD{constructor(e){f(this,$d,void 0),v(this,$d,e)}on(e,i){let n,r;switch(e){case B.transcript:{n=tu.fromBinary.bind(tu),r=tu.create();break}default:{h.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,$d).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){h.error("chatSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}}$d=new WeakMap;var WD=Object.defineProperty,jD=Object.getOwnPropertyDescriptor,Bh=(t,e,i,n)=>{for(var r=n>1?void 0:n?jD(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&WD(e,i,r),r},Vn;class Kd{constructor(e){f(this,Vn,void 0),v(this,Vn,e)}getPolls(){return a(this,Vn).sendMessagePromise(Ki.getPolls)}createPoll(e,i,n=!1,r=!1){const s={anonymous:n,hideVotes:r,question:e,options:i};return a(this,Vn).sendMessage(Ki.createPoll,LM.toBinary(s))}votePoll(e,i){const n={index:i,pollId:e};return a(this,Vn).sendMessage(Ki.votePoll,VM.toBinary(n))}on(e,i){let n,r;switch(e){case Ki.updatePoll:case Ki.createPoll:case Ki.votePoll:{n=mu.fromBinary.bind(mu),r=mu.create();break}}a(this,Vn).on(e,({payload:s})=>{let o=r;try{o=n(s)}catch(c){h.error("pollSocketHandler::on::binary_decode_error",{error:c})}return i(o)})}removeListeners(e){a(this,Vn).removeListeners(e)}}Vn=new WeakMap,Bh([S.trace("PollSocketHandler.getPolls")],Kd.prototype,"getPolls",1),Bh([S.trace("PollSocketHandler.createPoll")],Kd.prototype,"createPoll",1),Bh([S.trace("PollSocketHandler.votePoll")],Kd.prototype,"votePoll",1);var zt;class HD{constructor(e){f(this,zt,void 0),v(this,zt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,zt).sendMessagePromise(B.getStageRequests);return e?pu.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,zt).sendMessage(B.requestStageAccess)}cancelRequestAccess(){a(this,zt).sendMessage(B.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,zt).sendMessage(B.grantStageAccess,wM.toBinary(i))})}denyAccess(e){return u(this,null,function*(){const i={userIds:e};a(this,zt).sendMessage(B.denyStageAccess,CM.toBinary(i))})}joinStage(){return a(this,zt).sendMessagePromise(B.joinStage,void 0,void 0,B.peerStageStatusUpdate)}leaveStage(e){const i={userIds:[e]};return a(this,zt).sendMessagePromise(B.leaveStage,df.toBinary(i),void 0,B.peerStageStatusUpdate)}kick(e){const i={userIds:e};return a(this,zt).sendMessagePromise(B.leaveStage,df.toBinary(i))}on(e,i){let n;switch(e){case B.grantStageAccess:case B.denyStageAccess:{n=void 0;break}case B.getStagePeers:{n=cf.fromBinary.bind(cf);break}case B.getStageRequests:case B.requestStageAccess:case B.cancelStageRequest:{n=pu.fromBinary.bind(pu);break}case B.peerStageStatusUpdate:{n=jg.fromBinary.bind(jg);break}}a(this,zt).on(e,({payload:r,id:s})=>{if(!r||!n)return i(void 0,s);const o=n(r);return i(o,s)})}getPeerInfo(e){return u(this,null,function*(){const i=yield a(this,zt).sendMessagePromise(B.getPeerInfo,Jg.toBinary({peerId:e}));return zr.fromBinary(i.payload)})}}zt=new WeakMap;var nt;class GD{constructor(e){f(this,nt,void 0),v(this,nt,e)}addPlugin(e,i){a(this,nt).sendMessage(z.addPlugin,jR.toBinary({pluginId:e,staggered:i}))}removePlugin(e){a(this,nt).sendMessage(z.removePlugin,GR.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,nt).sendMessagePromise(z.getPlugins);return e?pM.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,i,n){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,nt).sendMessage(z.customPluginEventToRoom,eM.toBinary(r),n)}customPluginEventToPeers(e,i,n,r){const s={pluginId:e,peerIds:i,pluginData:new TextEncoder().encode(JSON.stringify(n))};a(this,nt).sendMessage(z.customPluginEventToPeers,iM.toBinary(s),r)}enablePluginForRoom(e,i){a(this,nt).sendMessage(z.enablePluginForRoom,JR.toBinary({pluginId:e}),i)}enablePluginForPeers(e,i,n){a(this,nt).sendMessage(z.enablePluginForPeers,YR.toBinary({pluginId:e,peerIds:i}),n)}disablePluginForRoom(e,i){a(this,nt).sendMessage(z.disablePluginForRoom,KR.toBinary({pluginId:e}),i)}disablePluginForPeers(e,i,n){a(this,nt).sendMessage(z.disablePluginForPeers,XR.toBinary({pluginId:e,peerIds:i}),n)}storeInsertKeys(e,i,n,r){const s={pluginId:e,storeName:i,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,nt).sendMessage(z.storeInsertKeys,nf.toBinary(s),r)}storeGetKeys(e,i,n,r){const s={pluginId:e,storeName:i,getKeys:n.map(o=>({storeKey:o.key}))};a(this,nt).sendMessage(z.storeGetKeys,aM.toBinary(s),r)}storeDeleteKeys(e,i,n,r){const s={pluginId:e,storeName:i,deleteKeys:n.map(o=>({storeKey:o.key}))};a(this,nt).sendMessage(z.storeDeleteKeys,cM.toBinary(s),r)}storeDelete(e,i,n){a(this,nt).sendMessage(z.storeDelete,lM.toBinary({pluginId:e,storeName:i}),n)}getPluginDataOld(e,i){h.info("getPluginDataOld",{plugin:{id:e,storeName:i}})}storePluginDataOld(e,i,n){const r={pluginId:e,storeName:i,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};a(this,nt).sendMessage(z.storeInsertKeys,nf.toBinary(r))}on(e,i){let n;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{n=hu.fromBinary.bind(hu);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{n=rf.fromBinary.bind(rf);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{n=af.fromBinary.bind(af);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{n=sf.fromBinary.bind(sf);break}}a(this,nt).on(e,({payload:r,id:s})=>{const o=n(r);return i(o,s)})}}nt=new WeakMap;var qD=Object.defineProperty,JD=(t,e,i)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,$D=(t,e,i)=>(JD(t,typeof e!="symbol"?e+"":e,i),i),Wh=(t,e,i)=>{if(!e.has(t))throw TypeError("Cannot "+i)},L=(t,e,i)=>(Wh(t,e,"read from private field"),i?i.call(t):e.get(t)),we=(t,e,i)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,i)},pe=(t,e,i,n)=>(Wh(t,e,"write to private field"),n?n.call(t,i):e.set(t,i),i),Pe=(t,e,i)=>(Wh(t,e,"access private method"),i),zd={},KD={get exports(){return zd},set exports(t){zd=t}},Ns=typeof Reflect=="object"?Reflect:null,Fv=Ns&&typeof Ns.apply=="function"?Ns.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)},Yd;Ns&&typeof Ns.ownKeys=="function"?Yd=Ns.ownKeys:Object.getOwnPropertySymbols?Yd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Yd=function(t){return Object.getOwnPropertyNames(t)};function zD(t){console&&console.warn&&console.warn(t)}var Bv=Number.isNaN||function(t){return t!==t};function ge(){ge.init.call(this)}KD.exports=ge,zd.once=ZD,ge.EventEmitter=ge,ge.prototype._events=void 0,ge.prototype._eventsCount=0,ge.prototype._maxListeners=void 0;var Wv=10;function Qd(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ge,"defaultMaxListeners",{enumerable:!0,get:function(){return Wv},set:function(t){if(typeof t!="number"||t<0||Bv(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wv=t}}),ge.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},ge.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Bv(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 jv(t){return t._maxListeners===void 0?ge.defaultMaxListeners:t._maxListeners}ge.prototype.getMaxListeners=function(){return jv(this)},ge.prototype.emit=function(t){for(var e=[],i=1;i<arguments.length;i++)e.push(arguments[i]);var n=t==="error",r=this._events;if(r!==void 0)n=n&&r.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 c=r[t];if(c===void 0)return!1;if(typeof c=="function")Fv(c,this,e);else for(var d=c.length,l=$v(c,d),i=0;i<d;++i)Fv(l[i],this,e);return!0};function Hv(t,e,i,n){var r,s,o;if(Qd(i),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),s=t._events),o=s[e]),o===void 0)o=s[e]=i,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[i,o]:[o,i]:n?o.unshift(i):o.push(i),r=jv(t),r>0&&o.length>r&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,zD(c)}return t}ge.prototype.addListener=function(t,e){return Hv(this,t,e,!1)},ge.prototype.on=ge.prototype.addListener,ge.prototype.prependListener=function(t,e){return Hv(this,t,e,!0)};function YD(){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 Gv(t,e,i){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},r=YD.bind(n);return r.listener=i,n.wrapFn=r,r}ge.prototype.once=function(t,e){return Qd(e),this.on(t,Gv(this,t,e)),this},ge.prototype.prependOnceListener=function(t,e){return Qd(e),this.prependListener(t,Gv(this,t,e)),this},ge.prototype.removeListener=function(t,e){var i,n,r,s,o;if(Qd(e),n=this._events,n===void 0)return this;if(i=n[t],i===void 0)return this;if(i===e||i.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,i.listener||e));else if(typeof i!="function"){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===e||i[s].listener===e){o=i[s].listener,r=s;break}if(r<0)return this;r===0?i.shift():QD(i,r),i.length===1&&(n[t]=i[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ge.prototype.off=ge.prototype.removeListener,ge.prototype.removeAllListeners=function(t){var e,i,n;if(i=this._events,i===void 0)return this;if(i.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):i[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete i[t]),this;if(arguments.length===0){var r=Object.keys(i),s;for(n=0;n<r.length;++n)s=r[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=i[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 qv(t,e,i){var n=t._events;if(n===void 0)return[];var r=n[e];return r===void 0?[]:typeof r=="function"?i?[r.listener||r]:[r]:i?XD(r):$v(r,r.length)}ge.prototype.listeners=function(t){return qv(this,t,!0)},ge.prototype.rawListeners=function(t){return qv(this,t,!1)},ge.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Jv.call(t,e)},ge.prototype.listenerCount=Jv;function Jv(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}ge.prototype.eventNames=function(){return this._eventsCount>0?Yd(this._events):[]};function $v(t,e){for(var i=new Array(e),n=0;n<e;++n)i[n]=t[n];return i}function QD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function XD(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function ZD(t,e){return new Promise(function(i,n){function r(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),i([].slice.call(arguments))}Kv(t,e,s,{once:!0}),e!=="error"&&eO(t,r,{once:!0})})}function eO(t,e,i){typeof t.on=="function"&&Kv(t,"error",e,i)}function Kv(t,e,i,n){if(typeof t.on=="function")n.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){n.once&&t.removeEventListener(e,r),i(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class tO 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 zv=new tO;class Yv{static encode(e){return zv.toBinary(e)}static decode(e){return zv.fromBinary(new Uint8Array(e))}}function iO(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Un;class nO{constructor(e={}){$D(this,"opts"),we(this,Un,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},pe(this,Un,0)}wait(){return u(this,null,function*(){pe(this,Un,L(this,Un)+1);const e=iO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*lS(2,L(this,Un))));yield new Promise(i=>{setTimeout(i,e)})})}getAttempts(){return L(this,Un)}reset(){pe(this,Un,0)}}Un=new WeakMap;const Fn={debug:0,info:1,warn:2,error:3};var xr,Vr;class rO{constructor(e){we(this,xr,void 0),we(this,Vr,void 0),pe(this,xr,console),pe(this,Vr,e)}debug(...e){Fn[L(this,Vr)]>Fn.debug||L(this,xr).debug("[Sockrates]:",...e)}info(...e){Fn[L(this,Vr)]>Fn.info||L(this,xr).info("[Sockrates]:",...e)}warn(...e){Fn[L(this,Vr)]>Fn.warn||L(this,xr).warn("[Sockrates]:",...e)}error(...e){Fn[L(this,Vr)]>Fn.error||L(this,xr).error("[Sockrates]:",...e)}}xr=new WeakMap,Vr=new WeakMap;var Qv=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Qv||{});const sO="2",aO="3";var Le,Ls,Re,je,Bn,rt,sn,Wn,ki,xs,an,jh,Xv,_o,Xd,Hh,Zv,Gh,ey,Zd,qh,Jh,ty,wo,el,Io,tl,il,$h,Vs,Co,Po,nl;class oO{constructor(e,i){var n;we(this,jh),we(this,_o),we(this,Hh),we(this,Gh),we(this,Zd),we(this,Jh),we(this,wo),we(this,Io),we(this,il),we(this,Vs),we(this,Po),we(this,Le,void 0),we(this,Ls,void 0),we(this,Re,void 0),we(this,je,void 0),we(this,Bn,void 0),we(this,rt,void 0),we(this,sn,void 0),we(this,Wn,void 0),we(this,ki,void 0),we(this,xs,void 0),we(this,an,void 0);var r,s,o,c,d,l,p,g,y;pe(this,Ls,e),pe(this,Bn,[]),pe(this,rt,new zd),pe(this,sn,!0),pe(this,ki,!1),pe(this,Re,i!=null?i:{}),(r=L(this,Re)).autoReconnect!=null||(r.autoReconnect=!0),(s=L(this,Re)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=L(this,Re)).pingTimeout!=null||(o.pingTimeout=3e4),(c=L(this,Re)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Re)).debug!=null||(d.debug=!0),(l=L(this,Re)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(p=L(this,Re)).disconnectOnPingTimeout!=null||(p.disconnectOnPingTimeout=!0),(g=L(this,Re)).queueOnDisconnect!=null||(g.queueOnDisconnect=!1),(y=L(this,Re)).flushOnReconnect!=null||(y.flushOnReconnect=!1),pe(this,Wn,{code:void 0,reason:void 0}),pe(this,je,(n=L(this,Re).logger)!=null?n:new rO(L(this,Re).debug?"debug":"info")),pe(this,an,new nO)}get readyState(){var e;return(e=L(this,Le))==null?void 0:e.readyState}get url(){return L(this,Ls)}updateURL(e){pe(this,Ls,e),Pe(this,Jh,ty).call(this)}get config(){return L(this,Re)}get sendQueue(){return L(this,Bn)}flush(){if(!L(this,Re).queueOnDisconnect)return!1;const e=[];return L(this,Bn).forEach(i=>{this.send(i.event,i.id,i.payload,i.metadata)||e.push(i)}),pe(this,Bn,e),L(this,Bn)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,je).debug("Websocket was already connecting or connected.");return}if(L(this,sn)!==!1)return new Promise((i,n)=>{Pe(this,Vs,Co).call(this),Pe(this,Po,nl).call(this);try{pe(this,Le,new WebSocket(Pe(this,jh,Xv).call(this,L(this,Ls)))),L(this,Le).binaryType="arraybuffer",L(this,je).debug("Connecting");const r=setTimeout(()=>{L(this,je).debug("Connection timeout. Closing socket"),pe(this,sn,!0),Pe(this,Po,nl).call(this),L(this,Le).close(3001,"Connection Timeout"),L(this,Re).autoReconnect&&!L(this,ki)&&(L(this,rt).emit("reconnecting"),Pe(this,wo,el).call(this)),n(new Error("Connection timed out!"))},L(this,Re).connectionTimeout);L(this,Le).onopen=()=>{L(this,je).debug(`Ready State: ${Qv[L(this,Le).readyState]}`),r&&clearTimeout(r),Pe(this,il,$h).call(this),pe(this,Wn,{code:void 0,reason:void 0}),L(this,rt).emit("connected"),L(this,Re).flushOnReconnect&&this.flush(),i()},L(this,Le).onclose=s=>{try{r&&clearTimeout(r);const{code:o,reason:c}=s;n(c),L(this,je).debug("Socket closed. Close event:",{event:s}),L(this,je).debug(`Connection closed code: ${o}`),L(this,je).debug(`Connection closed reason: ${c}`),L(this,ki)||Pe(this,Zd,qh).call(this,o,c)}catch(o){Pe(this,_o,Xd).call(this,o)}},L(this,Le).onerror=s=>{Pe(this,_o,Xd).call(this,s)},L(this,Le).onmessage=s=>Pe(this,Hh,Zv).call(this,s)}catch(r){Pe(this,_o,Xd).call(this,r,n)}})})}send(e,i,n,r){const s={event:e,id:i,payload:n,metadata:r};if(L(this,Re).queueOnDisconnect&&(!L(this,Le)||L(this,Le).readyState!==1))return L(this,je).debug("Queuing message since socket is not connected!",s),L(this,Bn).push(s),!1;const o=Yv.encode(s);return Pe(this,Io,tl).call(this,o)}emit(e,i,n,r){return this.send(e,i,n,r)}sendRaw(e){return Pe(this,Io,tl).call(this,e)}receive(e,i){return L(this,rt).on(e.toString(),i)}on(e,i){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,i);return}this.receive(e,i)}removeAllListeners(){L(this,rt).removeAllListeners()}removeReceiver(e,i){this.removeListener(e,i)}removeListener(e,i){L(this,rt).removeListener(e.toString(),i)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,rt).listeners(e.toString()).map(i=>this.removeListener(e,i))}disconnect(){pe(this,sn,!1),Pe(this,Vs,Co).call(this),this.removeAllListeners(),pe(this,Wn,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Ls=new WeakMap,Re=new WeakMap,je=new WeakMap,Bn=new WeakMap,rt=new WeakMap,sn=new WeakMap,Wn=new WeakMap,ki=new WeakMap,xs=new WeakMap,an=new WeakMap,jh=new WeakSet,Xv=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)://.")},_o=new WeakSet,Xd=function(t,e){L(this,je).error("Error:",{error:t}),L(this,rt).emit("errored",{error:t}),e==null||e(t)},Hh=new WeakSet,Zv=function(t){if(Pe(this,il,$h).call(this),t.data===sO){L(this,je).debug("Received ping from server"),Pe(this,Io,tl).call(this,aO);return}const e=Yv.decode(t.data),{id:i,payload:n}=e;L(this,je).debug("Received message",{event:e.event,messageID:i}),L(this,rt).emit(e.event.toString(),{id:i,payload:n})},Gh=new WeakSet,ey=function(){return L(this,Le).readyState===1},Zd=new WeakSet,qh=function(t,e){pe(this,Wn,{reason:e,code:t}),L(this,rt).emit("disconnected",{code:t,reason:e})},Jh=new WeakSet,ty=function(){const{reason:t,code:e}=L(this,Wn);e&&e!==1e3&&L(this,sn)&&L(this,Re).autoReconnect&&!L(this,ki)&&(L(this,je).debug(`Triggering reconnection due to ${t}.`),L(this,rt).emit("reconnecting"),Pe(this,wo,el).call(this))},wo=new WeakSet,el=function(t=!0){return u(this,null,function*(){if(t&&L(this,ki)){L(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,ki)||L(this,an).reset(),L(this,Re).maxReconnectionAttempts!==null&&L(this,an).getAttempts()>=L(this,Re).maxReconnectionAttempts){L(this,rt).emit("failed"),pe(this,ki,!1);return}pe(this,ki,!0),Pe(this,Po,nl).call(this),Pe(this,Vs,Co).call(this);try{if(yield L(this,an).wait(),L(this,sn)===!1)return;if(L(this,je).debug(`Reconnection attempt ${L(this,an).getAttempts()}`),L(this,rt).emit("reconnectAttempt",{attempt:L(this,an).getAttempts()}),yield this.connect(),!Pe(this,Gh,ey).call(this))throw Error("Reconnect Failed");pe(this,ki,!1),pe(this,Wn,{code:void 0,reason:void 0}),L(this,rt).emit("reconnected")}catch(e){L(this,je).debug("Failed to reconnect."),L(this,rt).emit("reconnectFailure",{attempt:L(this,an).getAttempts()}),Pe(this,wo,el).call(this,!1)}})},Io=new WeakSet,tl=function(t){try{return L(this,Le).send(t),!0}catch(e){return L(this,je).error(e.message),!1}},il=new WeakSet,$h=function(){this.config.disconnectOnPingTimeout&&(L(this,je).debug("Resetting ping timeout"),Pe(this,Vs,Co).call(this),pe(this,xs,setTimeout(()=>{var t;L(this,je).debug("Disconnecting the socket due to ping timeout"),pe(this,sn,!0);const e=3002,i="Ping timeout";(t=L(this,Le))==null||t.close(e,i),Pe(this,Zd,qh).call(this,e,i)},L(this,Re).pingTimeout)))},Vs=new WeakSet,Co=function(){L(this,xs)&&(clearTimeout(L(this,xs)),pe(this,xs,void 0))},Po=new WeakSet,nl=function(){L(this,Le)&&(L(this,Le).onopen=void 0,L(this,Le).onerror=void 0,L(this,Le).onmessage=void 0,L(this,Le).onclose=void 0)};var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,rl=(t,e,i,n)=>{for(var r=n>1?void 0:n?dO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&cO(e,i,r),r};const iy=65535,lO=3e3;var Ur,xe,Ve,He,bi,jn,sl,Kh,al,zh,ny;const ry=(ny=class{constructor(t,{peerId:e,meetingId:i,authToken:n,capabilities:r}){f(this,Ve),f(this,sl),f(this,al),f(this,Ur,void 0),f(this,xe,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),f(this,bi,void 0),f(this,jn,void 0);var s;if(!e||!i||!n)throw new w("peerId, meetingId, or authToken can not be empty","0404");v(this,bi,void 0),v(this,jn,t),this.capabilities=r,this.roomName=i,this.authToken=n,v(this,Ur,j(this,sl,Kh).call(this,e)),v(this,xe,new oO(a(this,Ur),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:h})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ve,He).socketJoinAttempted}set joinAttempted(t){a(this,Ve,He).socketJoinAttempted=t}get peerId(){return a(this,jn).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Ur,j(this,sl,Kh).call(this,t)),h.debug("SocketService:: Connection URL updated.")),a(this,xe).updateURL(a(this,Ur))}static getSocketEdgeDomain(t){return $r({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,Ur)}connect(){return u(this,null,function*(){a(this,Ve,He).socketJoinAttempted=!0,yield a(this,xe).connect(),a(this,Ve,He).socketJoinAttempted=!0,a(this,Ve,He).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ve,He).socketJoinAttempted=!1,a(this,xe).disconnect(),a(this,Ve,He).socketJoinAttempted=!0,a(this,Ve,He).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,xe).readyState===1}catch(t){return!1}}sendMessage(t,e,i){const n={};return S.injectContext(n),a(this,xe).send(t,i!=null?i:j(this,al,zh).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,i,n){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:i,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:i,messageId:n,resp:r}){const s=r!=null?r:t;return new Promise((o,c)=>{const d=(T,b)=>{a(this,xe).removeListener(s,T),a(this,xe).removeListener(iy,b),a(this,xe).removeListener(Xt.errorResponse,b),a(this,xe).removeListener(li.errorResponse,b)},l=n!=null?n:j(this,al,zh).call(this),p={};S.injectContext(p);const g=({id:T,payload:b})=>{if(l===T){let N;try{const M=rI.fromBinary(b);N=new Error(M.errorMessage)}catch(M){N=new Error("failed to parse error message",{cause:M});try{const F=sC.fromBinary(b);N=new Error(F.message)}catch(F){N=new Error("failed to parse error message",{cause:F})}}c(N),d(y,g)}},y=({id:T,payload:b})=>{l===T&&(o({id:T,payload:b}),d(y,g))};a(this,xe).on(s,y),a(this,xe).on(iy,g),a(this,xe).on(Xt.errorResponse,g),a(this,xe).on(li.errorResponse,g),setTimeout(()=>{d(y,g),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,xe).send(t,l,i,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){a(this,xe).on(t,e)}onStateEvent(t,e){a(this,xe).on(t,e)}removeListener(t,e){a(this,xe).removeListener(t,e)}removeListeners(t){a(this,xe).removeListeners(t)}flush(){return a(this,xe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){h.info("SocketService::Connected to socket-edge"),a(this,bi)&&(clearTimeout(a(this,bi)),v(this,bi,void 0)),a(this,Ve,He).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var i;h.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:n,send:r}=(i=a(this,Ve,He).mediaState)!=null?i:{};n!=null&&n.state&&(n==null?void 0:n.state)!==wn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==wn.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,He).joinAttempted}):v(this,bi,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,He).joinAttempted}),v(this,bi,void 0)},lO)),a(this,Ve,He).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){h.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),a(this,Ve,He).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){h.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ve,He).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{h.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ve,He).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){h.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ve,He).mediaJoinAttempted}}),a(this,bi)&&(clearTimeout(a(this,bi)),v(this,bi,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ve,He).mediaJoinAttempted}),a(this,Ve,He).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){h.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),a(this,Ve,He).updateSocketConnectionState("failed")}))}},Ur=new WeakMap,xe=new WeakMap,Ve=new WeakSet,He=function(){return a(this,jn).getValue("connectionHandler")},bi=new WeakMap,jn=new WeakMap,sl=new WeakSet,Kh=function(t){let e=ry.getSocketEdgeDomain(a(this,jn).getValue("baseURI"));typeof Mc(a(this,jn),"socket_server_base")=="string"&&(e=Mc(a(this,jn),"socket_server_base"));const i=`wss://${e}`,n=new URL(`${i}/ws`),r=this.peerId,s=q(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Lc[o]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([o,c])=>{n.searchParams.append(o,c.toString())}),n.href},al=new WeakSet,zh=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},ny);let Ro=ry;rl([S.trace("SocketService.connect")],Ro.prototype,"connect",1),rl([S.trace("SocketService.disconnect")],Ro.prototype,"disconnect",1),rl([S.trace("SocketService.sendMessagePromise")],Ro.prototype,"sendMessagePromise",1),rl([S.trace("SocketService.sendMessagePromiseWithTimeout")],Ro.prototype,"sendMessagePromiseWithTimeout",1);const Fr=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const i=DC.fromBinary(t),n=i.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(e=i.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=rP.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=zg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return Kg.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return KC.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Fr.socketService.sendMessagePromise(B.getConnectedRoomsDump);return Fr.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Fr.socketService.sendMessagePromise(B.createConnectedRooms,xC.toBinary({payloads:t}));return Kg.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),i=yield Fr.socketService.sendMessagePromise(B.deleteConnectedRooms,JC.toBinary({payloads:e}));return Fr.handleConnectedRoomsDeletedRaw(i)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Fr.socketService.sendMessagePromise(B.movePeers,eP.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 Ae=Fr;m(Ae,"socketService"),m(Ae,"currentMeetingId");var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,ol=(t,e,i,n)=>{for(var r=n>1?void 0:n?hO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&uO(e,i,r),r};const Us=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*(){var e,i;const{peerId:n,apiBase:r,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),yd.cleanup(),xv(t),_e.isSupported()===!1)throw new w("Browser not supported","0010",!0);const l=fA(t,{authToken:s,baseURL:r,cachedUserDetails:d});l.setRoomName(o),l.setRoomUUID(o),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",n),t.setValue("apiClient",l);const p=new XA;t.setValue("connectionHandler",p);const g=Us.createSocketService(t),y=g.connect(),T=l.getUserDetails(),b=l.getPlugins();let N=et.HIVE,M,F="";try{yield Us.setupFlagsmith(t)}catch(re){h.error("Failed to setup flagsmith",{error:re})}try{yield y}catch(re){h.error("[Controller]: Failed to connect to socket server:",{error:re})}try{({sfu:N,meetingTitle:F}=yield l.getRoomNodeData()),M=yield T,h.info(`SFU ${N} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:N})}catch(re){h.error("Failed to get room metadata",{error:re})}const H=x1.init(M.preset,!t.getValue("modules").theme),K=Us.setupControllers(g,t,M,b,F,H);WA(H)&&((e=Us.createRoomNodeClient(t,g).partialJoinRoom(M.participant.name,o,void 0))==null||e.catch(re=>{h.error("[Controller]: Failed to queue partial media room promise:",{error:re})})),S.location.country=(i=l.ipInfo)==null?void 0:i.country;const{controllers:I}=yield K;return H_(),new Us(r,I)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:i,baseURI:n,overrides:r,meetingId:s,organizationId:o}=t.getAllValues(),c=W_(s),d=q(x({entity:Yl.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},_e.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?$r({servicePrefix:"flags",baseURI:n}):"edge.api.flagsmith.com";yield Q.identify(`${Yl.PEER}_${i}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,h),h.info("flagsmith::allFlags",{flags:JSON.stringify(Q.getAllFlags())},!0)}catch(l){h.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,i,n,r,s){return u(this,null,function*(){var o,c,d;const l=e.getValue("modules"),{preset:p,participant:g}=i,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:N}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(o=N.enableHighBitrate)!=null?o:!1,enableStereo:(c=N.enableStereo)!=null?c:!1}}},y));const M=nD.init(e,b,p.permissions);e.setValue("maxPreferredStreams",_e.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let F,H,K,I,re,ae,De,Oe;const ft=new BD(t);Ae.socketService=t;const Yt=new Kd(t),A=new Zt(t),k=new HD(t),_=yd.create(t,e),W=new GD(t),Ie=new FD(t),Ye=new rr(t),U=yield xn.init(e,_,g,M,s),C=yield Mf.init(e,U.self,_,ft,r);if(l.participant&&(Oe=new Zi(e,U.self,_,T)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(h,P),l.chat&&(H=yield zi.init(e,A,Ye,U.self,Oe.participants)),l.internals&&(re=yield Ou.init()),l.livestream&&s.viewType===yt.Livestream&&Q.hasFeature(ne.LIVESTREAM)&&(De=new Kf(U.self,Ie)),s.viewType!==yt.Chat){if(l.poll&&(F=yield _f.init(e,U.self,Yt)),l.recording&&(ae=new Uf(e,U.self,_)),l.stage&&(K=new Af(e,k,_,U.self,Oe.participants)),l.plugin){if(!Oe)throw new w("The plugin module cannot be initialized without the `participant` module","0102");const on=yield n;I=yield ya.init(e,on,W,A,H==null?void 0:H.chat,U.self,Oe.participants,r)}if(l.pip){const on=yield J_._init(e,U.self);e.setValue("pip",on)}}const Qe={storesManager:new G1(e,W),pollController:F,selfController:U,metaController:C,chatController:H,stageController:K,pluginController:I,recordingController:ae,internalsController:re,livestreamController:De,participantController:Oe};return{theme:s,permissions:M,controllers:Qe}})}static createRoomNodeClient(t,e){const{peerId:i,roomNodeOptions:n}=t.getAllValues(),{sfu:r}=n;return Lv(t,r,{socket:e,peerId:i})}static createSocketService(t){const{peerId:e,meetingId:i,authToken:n}=t.getAllValues(),r=["PING"];return new Ro(t,{peerId:e,meetingId:i,authToken:n,capabilities:r})}};let Mo=Us;ol([S.trace("Controller.init")],Mo,"init",1),ol([S.trace("setupFlagsmith")],Mo,"setupFlagsmith",1),ol([S.trace("Controller.createRoomNodeClient")],Mo,"createRoomNodeClient",1),ol([S.trace("Controller.createSocketService")],Mo,"createSocketService",1);var pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,gO=(t,e,i,n)=>{for(var r=n>1?void 0:n?mO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&pO(e,i,r),r},cl,Yh;class sy extends Ft{constructor(e,i){super(),f(this,cl,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),f(this,Yh,void 0),v(this,Yh,e),v(this,cl,i.self)}get supportsConnectedMeetings(){return a(this,cl).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ae.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
20
+ 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 Ae.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ae.createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ae.updateConnectedRooms(e.map(i=>({meetingId:i.id,title:i.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(i),yield Ae.disableConnectedRooms(e)})}moveParticipants(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ae.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,i,n),r})}moveParticipantsWithCustomPreset(e,i,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ae.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:i,participants:n});return r.success&&this.moveSuccessHandler(e,i,n.map(s=>s.id)),r})}moveSuccessHandler(e,i,n){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),i===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>r.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(i===s.id){const o=s.participants.concat(n.map(c=>r.get(c)));return q(x({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!n.includes(c.id));return q(x({},s),{participants:o})}return s})}}cl=new WeakMap,Yh=new WeakMap,gO([Dt({maxInvocations:60,period:60})],sy.prototype,"getConnectedMeetings",1);var fO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,Qh=(t,e,i,n)=>{for(var r=n>1?void 0:n?vO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&fO(e,i,r),r},Ao,_i,Xh,Zh;const Hn=(Xh=class{constructor(t,e,i){m(this,"connectedMeetings"),f(this,Ao,void 0),f(this,_i,void 0),f(this,Zh,void 0),v(this,Zh,t),v(this,Ao,i),this.connectedMeetings=new sy(t,e),this.setCurrentMeeting(e)}static init(t,e,i){return Hn.instance||(Hn.instance=new Hn(t,e,i)),Hn.instance.connectedMeetings.supportsConnectedMeetings&&(Hn.instance.setupEvents(),e.self.once("roomJoined",()=>Hn.instance.getConnectedMeetings())),Hn.instance}setCurrentMeeting(t){v(this,_i,t),Ae.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ae.socketService&&(Ae.socketService.on(B.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ae.socketService.on(B.transferPeer,this.handleTransferPeer.bind(this)),Ae.socketService.on(B.movedPeer,this.handleMovedPeer.bind(this)),Ae.socketService.on(B.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ae.socketService.on(B.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ae.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:i}){var n,r,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);h.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",i);const c={video:a(this,_i).self.videoEnabled,audio:a(this,_i).self.audioEnabled};try{a(this,_i).self.cleanupEvents(),yield a(this,_i).leave("connected-meeting")}catch(l){h.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(n=a(this,_i))==null?void 0:n.meta)==null?void 0:r.meetingId}`,{error:l})}Ae.socketService=void 0,h.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${i}`);const d=yield dy.init(q(x({},a(this,Ao)),{cachedUserDetails:null,defaults:q(x(x({},a(this,Ao).defaults),c),{mediaHandler:a(this,_i).self}),authToken:e}));h.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,_i).self;d.self.setName(a(this,_i).self.name),yield d.join(),l&&d.self.hide()}catch(l){h.error("ConnectedMeetingsController.joinRoom",{error:l})}return h.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=Ae.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(i=>({id:i.id,title:i.title,participants:i.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ae.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ae.handleConnectedRoomsUpdatedRaw(t),i=new Map;this.connectedMeetings.meetings.forEach(n=>{i.set(n.id,n)}),e.forEach(n=>{i.has(n.id)?i.get(n.id).title=n.title:i.set(n.id,q(x({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(i.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ae.handleConnectedRoomsDeletedRaw(t).map(i=>i.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(i=>!e.includes(i.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Ao=new WeakMap,_i=new WeakMap,Zh=new WeakMap,m(Xh,"instance"),Xh);let dl=Hn;Qh([S.trace("ConnectedMeetingsController.getConnectedMeetings")],dl.prototype,"getConnectedMeetings",1),Qh([S.trace("ConnectedMeetingsController.setupEvents")],dl.prototype,"setupEvents",1),Qh([S.trace("ConnectedMeetingsController.switchMeeting")],dl.prototype,"switchMeeting",1);class yO{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){h.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;h.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){h.log("Battery level: Not known");return}h.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,i;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(i=this.battery)==null||i.removeEventListener("levelchange",this.updateLevelInfo))})}}const ay=new yO;function SO(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:i,orgId:n,participantId:r}=JSON.parse(atob(t.split(".")[1]));if(!i)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://api.${s}`;return{meetingId:i,orgId:n,participantId:r,baseURI:s,apiBase:o}}catch(i){throw h.error("constants::decodeAuthToken",{error:i,debuggingHint:`Unable to decode auth token: ${t}`},!0),new w("Invalid auth token","0004")}}var EO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,ll=(t,e,i,n)=>{for(var r=n>1?void 0:n?TO(e,i):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(r=(n?o(e,i,r):o(r))||r);return n&&r&&EO(e,i,r),r},ct,ul,hl,ep,oy,cy;let Gn=(cy=class{constructor(t,e){f(this,ep),f(this,ct,void 0),f(this,ul,void 0),f(this,hl,void 0),v(this,hl,t),v(this,ct,e)}static init(t){return u(this,null,function*(){var e,i,n,r,s,o,c;U_(),_e.init();const d=(i=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?i:Br();ay.init();const{authToken:l,baseURI:p}=t,g=SO(l,p),{meetingId:y}=g,T=ac(g,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Gn.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(r=(n=t.modules)==null?void 0:n.tracing)!=null?r:!0),h.info("DyteClient::init::options",{dyteClientInitOptions:q(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
22
+ ${(o=t.authToken)==null?void 0:o.slice(-10)}`})});const N=yield Mo.init(b),M=new Gn(b,N);return j(c=M,ep,oy).call(c,t),M})}static setupContext(t,e,i,n){var r;const s=Zn.createContext(t,e),o=x(x({},D_),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",i),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",(r=e.overrides)!=null?r:{}),s.setValue("env",O_({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",hi(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.103"),s}join(){return u(this,null,function*(){const{selfController:t}=a(this,ct);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){ay.cleanup();const{selfController:e}=a(this,ct);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,ct).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,ct).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,ct).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,ct).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,ct).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,ct).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,ct).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,ul))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,ct).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,ct).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,ct).stageController)==null?void 0:t.stage}get stores(){return a(this,ct).storesManager}get __internals__(){var t;return(t=a(this,ct).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)})}},ct=new WeakMap,ul=new WeakMap,hl=new WeakMap,ep=new WeakSet,oy=function(t){v(this,ul,dl.init(a(this,hl),this,t))},cy);ll([ut("0002"),In.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gn.prototype,"join",1),ll([ut("0003")],Gn.prototype,"leave",1),ll([ut("0001"),In.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gn,"init",1),Gn=ll([ut("0000")],Gn);const dy=Gn;return dy}();