@cloudflare/realtimekit 0.0.2 → 0.5.0-staging.42

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.
@@ -0,0 +1,23 @@
1
+ var RealtimeKitClient=function(){"use strict";var go,cv=new Uint8Array(16);function dv(){if(!go&&(go=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!go))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return go(cv)}var lv=/^(?:[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 Uc(t){return typeof t=="string"&&lv.test(t)}for(var nt=[],Vc=0;Vc<256;++Vc)nt.push((Vc+256).toString(16).substr(1));function uv(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=(nt[t[e+0]]+nt[t[e+1]]+nt[t[e+2]]+nt[t[e+3]]+"-"+nt[t[e+4]]+nt[t[e+5]]+"-"+nt[t[e+6]]+nt[t[e+7]]+"-"+nt[t[e+8]]+nt[t[e+9]]+"-"+nt[t[e+10]]+nt[t[e+11]]+nt[t[e+12]]+nt[t[e+13]]+nt[t[e+14]]+nt[t[e+15]]).toLowerCase();if(!Uc(r))throw TypeError("Stringified UUID is invalid");return r}function gn(t,e,r){t=t||{};var n=t.random||(t.rng||dv)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(var i=0;i<16;++i)e[r+i]=n[i];return e}return uv(n)}const hv={"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"},cu={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"},Ve={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},pt={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"},Ur={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class D{static getFirstMatch(e,r){const n=r.match(e);return n&&n.length>0&&n[1]||""}static getSecondMatch(e,r){const n=r.match(e);return n&&n.length>1&&n[2]||""}static matchAndReturnConst(e,r,n){if(e.test(r))return n}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),r[0]===10)switch(r[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const r=e.split(".").splice(0,2).map(n=>parseInt(n,10)||0);if(r.push(0),!(r[0]===1&&r[1]<5)){if(r[0]===1&&r[1]<6)return"Cupcake";if(r[0]===1&&r[1]>=6)return"Donut";if(r[0]===2&&r[1]<2)return"Eclair";if(r[0]===2&&r[1]===2)return"Froyo";if(r[0]===2&&r[1]>2)return"Gingerbread";if(r[0]===3)return"Honeycomb";if(r[0]===4&&r[1]<1)return"Ice Cream Sandwich";if(r[0]===4&&r[1]<4)return"Jelly Bean";if(r[0]===4&&r[1]>=4)return"KitKat";if(r[0]===5)return"Lollipop";if(r[0]===6)return"Marshmallow";if(r[0]===7)return"Nougat";if(r[0]===8)return"Oreo";if(r[0]===9)return"Pie"}}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,r,n=!1){const i=D.getVersionPrecision(e),s=D.getVersionPrecision(r);let o=Math.max(i,s),a=0;const d=D.map([e,r],h=>{const p=o-D.getVersionPrecision(h),f=h+new Array(p+1).join(".0");return D.map(f.split("."),g=>new Array(20-g.length).join("0")+g).reverse()});for(n&&(a=o-Math.min(i,s)),o-=1;o>=a;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===a)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(e,r){const n=[];let i;if(Array.prototype.map)return Array.prototype.map.call(e,r);for(i=0;i<e.length;i+=1)n.push(r(e[i]));return n}static find(e,r){let n,i;if(Array.prototype.find)return Array.prototype.find.call(e,r);for(n=0,i=e.length;n<i;n+=1){const s=e[n];if(r(s,n))return s}}static assign(e,...r){const n=e;let i,s;if(Object.assign)return Object.assign(e,...r);for(i=0,s=r.length;i<s;i+=1){const o=r[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{n[d]=o[d]})}return e}static getBrowserAlias(e){return hv[e]}static getBrowserTypeByAlias(e){return cu[e]||""}}const Te=/version\/(\d+(\.?_?\d+)+)/i,pv=[{test:[/googlebot/i],describe(t){const e={name:"Googlebot"},r=D.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/opera/i],describe(t){const e={name:"Opera"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opr\/|opios/i],describe(t){const e={name:"Opera"},r=D.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/SamsungBrowser/i],describe(t){const e={name:"Samsung Internet for Android"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Whale/i],describe(t){const e={name:"NAVER Whale Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MZBrowser/i],describe(t){const e={name:"MZ Browser"},r=D.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/focus/i],describe(t){const e={name:"Focus"},r=D.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/swing/i],describe(t){const e={name:"Swing"},r=D.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/coast/i],describe(t){const e={name:"Opera Coast"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(t){const e={name:"Opera Touch"},r=D.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/yabrowser/i],describe(t){const e={name:"Yandex Browser"},r=D.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/ucbrowser/i],describe(t){const e={name:"UC Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/Maxthon|mxios/i],describe(t){const e={name:"Maxthon"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/epiphany/i],describe(t){const e={name:"Epiphany"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/puffin/i],describe(t){const e={name:"Puffin"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sleipnir/i],describe(t){const e={name:"Sleipnir"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/k-meleon/i],describe(t){const e={name:"K-Meleon"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/micromessenger/i],describe(t){const e={name:"WeChat"},r=D.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/qqbrowser/i],describe(t){const e={name:/qqbrowserlite/i.test(t)?"QQ Browser Lite":"QQ Browser"},r=D.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/msie|trident/i],describe(t){const e={name:"Internet Explorer"},r=D.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/\sedg\//i],describe(t){const e={name:"Microsoft Edge"},r=D.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/edg([ea]|ios)/i],describe(t){const e={name:"Microsoft Edge"},r=D.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/vivaldi/i],describe(t){const e={name:"Vivaldi"},r=D.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/seamonkey/i],describe(t){const e={name:"SeaMonkey"},r=D.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/sailfish/i],describe(t){const e={name:"Sailfish"},r=D.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,t);return r&&(e.version=r),e}},{test:[/silk/i],describe(t){const e={name:"Amazon Silk"},r=D.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/phantom/i],describe(t){const e={name:"PhantomJS"},r=D.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/slimerjs/i],describe(t){const e={name:"SlimerJS"},r=D.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e={name:"BlackBerry"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(web|hpw)[o0]s/i],describe(t){const e={name:"WebOS Browser"},r=D.getFirstMatch(Te,t)||D.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/bada/i],describe(t){const e={name:"Bada"},r=D.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/tizen/i],describe(t){const e={name:"Tizen"},r=D.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/qupzilla/i],describe(t){const e={name:"QupZilla"},r=D.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/firefox|iceweasel|fxios/i],describe(t){const e={name:"Firefox"},r=D.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/electron/i],describe(t){const e={name:"Electron"},r=D.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/MiuiBrowser/i],describe(t){const e={name:"Miui"},r=D.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/chromium/i],describe(t){const e={name:"Chromium"},r=D.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,t)||D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/chrome|crios|crmo/i],describe(t){const e={name:"Chrome"},r=D.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/GSA/i],describe(t){const e={name:"Google Search"},r=D.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e={name:"Android Browser"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/playstation 4/i],describe(t){const e={name:"PlayStation 4"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/safari|applewebkit/i],describe(t){const e={name:"Safari"},r=D.getFirstMatch(Te,t);return r&&(e.version=r),e}},{test:[/.*/i],describe(t){const e=/^(.*)\/(.*) /,r=/^(.*)\/(.*)[ \t]\((.*)/,i=t.search("\\(")!==-1?r:e;return{name:D.getFirstMatch(i,t),version:D.getSecondMatch(i,t)}}}];var mv=[{test:[/Roku\/DVP/],describe(t){const e=D.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,t);return{name:pt.Roku,version:e}}},{test:[/windows phone/i],describe(t){const e=D.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,t);return{name:pt.WindowsPhone,version:e}}},{test:[/windows /i],describe(t){const e=D.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,t),r=D.getWindowsVersionName(e);return{name:pt.Windows,version:e,versionName:r}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(t){const e={name:pt.iOS},r=D.getSecondMatch(/(Version\/)(\d[\d.]+)/,t);return r&&(e.version=r),e}},{test:[/macintosh/i],describe(t){const e=D.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,t).replace(/[_\s]/g,"."),r=D.getMacOSVersionName(e),n={name:pt.MacOS,version:e};return r&&(n.versionName=r),n}},{test:[/(ipod|iphone|ipad)/i],describe(t){const e=D.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,t).replace(/[_\s]/g,".");return{name:pt.iOS,version:e}}},{test(t){const e=!t.test(/like android/i),r=t.test(/android/i);return e&&r},describe(t){const e=D.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,t),r=D.getAndroidVersionName(e),n={name:pt.Android,version:e};return r&&(n.versionName=r),n}},{test:[/(web|hpw)[o0]s/i],describe(t){const e=D.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,t),r={name:pt.WebOS};return e&&e.length&&(r.version=e),r}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(t){const e=D.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,t)||D.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,t)||D.getFirstMatch(/\bbb(\d+)/i,t);return{name:pt.BlackBerry,version:e}}},{test:[/bada/i],describe(t){const e=D.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,t);return{name:pt.Bada,version:e}}},{test:[/tizen/i],describe(t){const e=D.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,t);return{name:pt.Tizen,version:e}}},{test:[/linux/i],describe(){return{name:pt.Linux}}},{test:[/CrOS/],describe(){return{name:pt.ChromeOS}}},{test:[/PlayStation 4/],describe(t){const e=D.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,t);return{name:pt.PlayStation4,version:e}}}],fv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(t){const e=D.getFirstMatch(/(can-l01)/i,t)&&"Nova",r={type:Ve.mobile,vendor:"Huawei"};return e&&(r.model=e),r}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ve.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ve.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ve.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ve.tablet}}},{test(t){const e=t.test(/ipod|iphone/i),r=t.test(/like (ipod|iphone)/i);return e&&!r},describe(t){const e=D.getFirstMatch(/(ipod|iphone)/i,t);return{type:Ve.mobile,vendor:"Apple",model:e}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ve.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ve.mobile}}},{test(t){return t.getBrowserName(!0)==="blackberry"},describe(){return{type:Ve.mobile,vendor:"BlackBerry"}}},{test(t){return t.getBrowserName(!0)==="bada"},describe(){return{type:Ve.mobile}}},{test(t){return t.getBrowserName()==="windows phone"},describe(){return{type:Ve.mobile,vendor:"Microsoft"}}},{test(t){const e=Number(String(t.getOSVersion()).split(".")[0]);return t.getOSName(!0)==="android"&&e>=3},describe(){return{type:Ve.tablet}}},{test(t){return t.getOSName(!0)==="android"},describe(){return{type:Ve.mobile}}},{test(t){return t.getOSName(!0)==="macos"},describe(){return{type:Ve.desktop,vendor:"Apple"}}},{test(t){return t.getOSName(!0)==="windows"},describe(){return{type:Ve.desktop}}},{test(t){return t.getOSName(!0)==="linux"},describe(){return{type:Ve.desktop}}},{test(t){return t.getOSName(!0)==="playstation 4"},describe(){return{type:Ve.tv}}},{test(t){return t.getOSName(!0)==="roku"},describe(){return{type:Ve.tv}}}],gv=[{test(t){return t.getBrowserName(!0)==="microsoft edge"},describe(t){if(/\sedg\//i.test(t))return{name:Ur.Blink};const r=D.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,t);return{name:Ur.EdgeHTML,version:r}}},{test:[/trident/i],describe(t){const e={name:Ur.Trident},r=D.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){return t.test(/presto/i)},describe(t){const e={name:Ur.Presto},r=D.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test(t){const e=t.test(/gecko/i),r=t.test(/like gecko/i);return e&&!r},describe(t){const e={name:Ur.Gecko},r=D.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ur.Blink}}},{test:[/(apple)?webkit/i],describe(t){const e={name:Ur.WebKit},r=D.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,t);return r&&(e.version=r),e}}];class du{constructor(e,r=!1){if(e==null||e==="")throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},r!==!0&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=D.find(pv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=D.find(mv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:r}=this.getOS();return e?String(r).toLowerCase()||"":r||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:r}=this.getPlatform();return e?String(r).toLowerCase()||"":r||""}parsePlatform(){this.parsedResult.platform={};const e=D.find(fv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=D.find(gv,r=>{if(typeof r.test=="function")return r.test(this);if(r.test instanceof Array)return r.test.some(n=>this.test(n));throw new Error("Browser's test function is not valid")});return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return D.assign({},this.parsedResult)}satisfies(e){const r={};let n=0;const i={};let s=0;if(Object.keys(e).forEach(a=>{const d=e[a];typeof d=="string"?(i[a]=d,s+=1):typeof d=="object"&&(r[a]=d,n+=1)}),n>0){const a=Object.keys(r),d=D.find(a,p=>this.isOS(p));if(d){const p=this.satisfies(r[d]);if(p!==void 0)return p}const h=D.find(a,p=>this.isPlatform(p));if(h){const p=this.satisfies(r[h]);if(p!==void 0)return p}}if(s>0){const a=Object.keys(i),d=D.find(a,h=>this.isBrowser(h,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(e,r=!1){const n=this.getBrowserName().toLowerCase();let i=e.toLowerCase();const s=D.getBrowserTypeByAlias(i);return r&&s&&(i=s.toLowerCase()),i===n}compareVersion(e){let r=[0],n=e,i=!1;const s=this.getBrowserVersion();if(typeof s=="string")return e[0]===">"||e[0]==="<"?(n=e.substr(1),e[1]==="="?(i=!0,n=e.substr(2)):r=[],e[0]===">"?r.push(1):r.push(-1)):e[0]==="="?n=e.substr(1):e[0]==="~"&&(i=!0,n=e.substr(1)),r.indexOf(D.compareVersions(s,n,i))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,r=!1){return this.isBrowser(e,r)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some(r=>this.is(r))}}/*!
2
+ * Bowser - a browser detector
3
+ * https://github.com/lancedikson/bowser
4
+ * MIT License | (c) Dustin Diaz 2012-2015
5
+ * MIT License | (c) Denis Demchenko 2015-2019
6
+ */class lu{static getParser(e,r=!1){if(typeof e!="string")throw new Error("UserAgent should be a string");return new du(e,r)}static parse(e){return new du(e).getResult()}static get BROWSER_MAP(){return cu}static get ENGINE_MAP(){return Ur}static get OS_MAP(){return pt}static get PLATFORMS_MAP(){return Ve}}function Bc(t){let e=typeof t;if(e=="object"){if(Array.isArray(t))return"array";if(t===null)return"null"}return e}function vv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}let vr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),vo=[];for(let t=0;t<vr.length;t++)vo[vr[t].charCodeAt(0)]=t;vo["-".charCodeAt(0)]=vr.indexOf("+"),vo["_".charCodeAt(0)]=vr.indexOf("/");function yv(t){let e=t.length*3/4;t[t.length-2]=="="?e-=2:t[t.length-1]=="="&&(e-=1);let r=new Uint8Array(e),n=0,i=0,s,o=0;for(let a=0;a<t.length;a++){if(s=vo[t.charCodeAt(a)],s===void 0)switch(t[a]){case"=":i=0;case`
7
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=s,i=1;break;case 1:r[n++]=o<<2|(s&48)>>4,o=s,i=2;break;case 2:r[n++]=(o&15)<<4|(s&60)>>2,o=s,i=3;break;case 3:r[n++]=(o&3)<<6|s,i=0;break}}if(i==1)throw Error("invalid base64 string.");return r.subarray(0,n)}function Ev(t){let e="",r=0,n,i=0;for(let s=0;s<t.length;s++)switch(n=t[s],r){case 0:e+=vr[n>>2],i=(n&3)<<4,r=1;break;case 1:e+=vr[i|n>>4],i=(n&15)<<2,r=2;break;case 2:e+=vr[i|n>>6],e+=vr[n&63],r=0;break}return r&&(e+=vr[i],e+="=",r==1&&(e+="=")),e}var yo;(function(t){t.symbol=Symbol.for("protobuf-ts/unknown"),t.onRead=(r,n,i,s,o)=>{(e(n)?n[t.symbol]:n[t.symbol]=[]).push({no:i,wireType:s,data:o})},t.onWrite=(r,n,i)=>{for(let{no:s,wireType:o,data:a}of t.list(n))i.tag(s,o).raw(a)},t.list=(r,n)=>{if(e(r)){let i=r[t.symbol];return n?i.filter(s=>s.no==n):i}return[]},t.last=(r,n)=>t.list(r,n).slice(-1)[0];const e=r=>r&&Array.isArray(r[t.symbol])})(yo||(yo={}));var Be;(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"})(Be||(Be={}));function Sv(){let t=0,e=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}let r=this.buf[this.pos++];if(t|=(r&15)<<28,e=(r&112)>>4,(r&128)==0)return this.assertBounds(),[t,e];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<n,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function jc(t,e,r){for(let s=0;s<28;s=s+7){const o=t>>>s,a=!(o>>>7==0&&e==0),d=(a?o|128:o)&255;if(r.push(d),!a)return}const n=t>>>28&15|(e&7)<<4,i=e>>3!=0;if(r.push((i?n|128:n)&255),!!i){for(let s=3;s<31;s=s+7){const o=e>>>s,a=o>>>7!=0,d=(a?o|128:o)&255;if(r.push(d),!a)return}r.push(e>>>31&1)}}const Eo=(1<<16)*(1<<16);function uu(t){let e=t[0]=="-";e&&(t=t.slice(1));const r=1e6;let n=0,i=0;function s(o,a){const d=Number(t.slice(o,a));i*=r,n=n*r+d,n>=Eo&&(i=i+(n/Eo|0),n=n%Eo)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),[e,n,i]}function Hc(t,e){if(e>>>0<=2097151)return""+(Eo*e+(t>>>0));let r=t&16777215,n=(t>>>24|e<<8)>>>0&16777215,i=e>>16&65535,s=r+n*6777216+i*6710656,o=n+i*8147497,a=i*2,d=1e7;s>=d&&(o+=Math.floor(s/d),s%=d),o>=d&&(a+=Math.floor(o/d),o%=d);function h(p,f){let g=p?String(p):"";return f?"0000000".slice(g.length)+g:g}return h(a,0)+h(o,a)+h(s,1)}function hu(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let r=0;r<9;r++)e.push(t&127|128),t=t>>7;e.push(1)}}function Tv(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let r=5;(t&128)!==0&&r<10;r++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}let ke;function kv(){const t=new DataView(new ArrayBuffer(8));ke=globalThis.BigInt!==void 0&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:t}:void 0}kv();function pu(t){if(!t)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const mu=/^-?[0-9]+$/,So=4294967296,To=2147483648;class fu{constructor(e,r){this.lo=e|0,this.hi=r|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let e=this.hi*So+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class ct extends fu{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.UMIN)throw new Error("signed value for ulong");if(e>ke.UMAX)throw new Error("ulong too large");return ke.V.setBigUint64(0,e,!0),new ct(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mu.test(e))throw new Error("string is no integer");let[r,n,i]=uu(e);if(r)throw new Error("signed value for ulong");return new ct(n,i);case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new ct(e,e/So)}throw new Error("unknown value "+typeof e)}toString(){return ke?this.toBigInt().toString():Hc(this.lo,this.hi)}toBigInt(){return pu(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigUint64(0,!0)}}ct.ZERO=new ct(0,0);class _e extends fu{static from(e){if(ke)switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=="")throw new Error("string is no integer");e=ke.C(e);case"number":if(e===0)return this.ZERO;e=ke.C(e);case"bigint":if(!e)return this.ZERO;if(e<ke.MIN)throw new Error("signed long too small");if(e>ke.MAX)throw new Error("signed long too large");return ke.V.setBigInt64(0,e,!0),new _e(ke.V.getInt32(0,!0),ke.V.getInt32(4,!0))}else switch(typeof e){case"string":if(e=="0")return this.ZERO;if(e=e.trim(),!mu.test(e))throw new Error("string is no integer");let[r,n,i]=uu(e);if(r){if(i>To||i==To&&n!=0)throw new Error("signed long too small")}else if(i>=To)throw new Error("signed long too large");let s=new _e(n,i);return r?s.negate():s;case"number":if(e==0)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new _e(e,e/So):new _e(-e,-e/So).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return(this.hi&To)!==0}negate(){let e=~this.hi,r=this.lo;return r?r=~r+1:e+=1,new _e(r,e)}toString(){if(ke)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+Hc(e.lo,e.hi)}return Hc(this.lo,this.hi)}toBigInt(){return pu(ke),ke.V.setInt32(0,this.lo,!0),ke.V.setInt32(4,this.hi,!0),ke.V.getBigInt64(0,!0)}}_e.ZERO=new _e(0,0);const gu={readUnknownField:!0,readerFactory:t=>new bv(t)};function _v(t){return t?Object.assign(Object.assign({},gu),t):gu}class bv{constructor(e,r){this.varint64=Sv,this.uint32=Tv,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=r!=null?r:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),r=e>>>3,n=e&7;if(r<=0||n<0||n>5)throw new Error("illegal tag: field no "+r+" wire type "+n);return[r,n]}skip(e){let r=this.pos;switch(e){case Be.Varint:for(;this.buf[this.pos++]&128;);break;case Be.Bit64:this.pos+=4;case Be.Bit32:this.pos+=4;break;case Be.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Be.StartGroup:let i;for(;(i=this.tag()[1])!==Be.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return new _e(...this.varint64())}uint64(){return new ct(...this.varint64())}sint64(){let[e,r]=this.varint64(),n=-(e&1);return e=(e>>>1|(r&1)<<31)^n,r=r>>>1^n,new _e(e,r)}bool(){let[e,r]=this.varint64();return e!==0||r!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ct(this.sfixed32(),this.sfixed32())}sfixed64(){return new _e(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),r=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(r,r+e)}string(){return this.textDecoder.decode(this.bytes())}}function fe(t,e){if(!t)throw new Error(e)}const wv=34028234663852886e22,Cv=-34028234663852886e22,Iv=4294967295,Rv=2147483647,Pv=-2147483648;function cs(t){if(typeof t!="number")throw new Error("invalid int 32: "+typeof t);if(!Number.isInteger(t)||t>Rv||t<Pv)throw new Error("invalid int 32: "+t)}function ko(t){if(typeof t!="number")throw new Error("invalid uint 32: "+typeof t);if(!Number.isInteger(t)||t>Iv||t<0)throw new Error("invalid uint 32: "+t)}function Wc(t){if(typeof t!="number")throw new Error("invalid float 32: "+typeof t);if(!!Number.isFinite(t)&&(t>wv||t<Cv))throw new Error("invalid float 32: "+t)}const vu={writeUnknownFields:!0,writerFactory:()=>new Mv};function Av(t){return t?Object.assign(Object.assign({},vu),t):vu}class Mv{constructor(e){this.stack=[],this.textEncoder=e!=null?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let r=new Uint8Array(e),n=0;for(let i=0;i<this.chunks.length;i++)r.set(this.chunks[i],n),n+=this.chunks[i].length;return this.chunks=[],r}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),r=this.stack.pop();if(!r)throw new Error("invalid state, fork stack empty");return this.chunks=r.chunks,this.buf=r.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,r){return this.uint32((e<<3|r)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ko(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return cs(e),hu(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let r=this.textEncoder.encode(e);return this.uint32(r.byteLength),this.raw(r)}float(e){Wc(e);let r=new Uint8Array(4);return new DataView(r.buffer).setFloat32(0,e,!0),this.raw(r)}double(e){let r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),this.raw(r)}fixed32(e){ko(e);let r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,e,!0),this.raw(r)}sfixed32(e){cs(e);let r=new Uint8Array(4);return new DataView(r.buffer).setInt32(0,e,!0),this.raw(r)}sint32(e){return cs(e),e=(e<<1^e>>31)>>>0,hu(e,this.buf),this}sfixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=_e.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}fixed64(e){let r=new Uint8Array(8),n=new DataView(r.buffer),i=ct.from(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(r)}int64(e){let r=_e.from(e);return jc(r.lo,r.hi,this.buf),this}sint64(e){let r=_e.from(e),n=r.hi>>31,i=r.lo<<1^n,s=(r.hi<<1|r.lo>>>31)^n;return jc(i,s,this.buf),this}uint64(e){let r=ct.from(e);return jc(r.lo,r.hi,this.buf),this}}const yu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Eu={ignoreUnknownFields:!1};function Dv(t){return t?Object.assign(Object.assign({},Eu),t):Eu}function Ov(t){return t?Object.assign(Object.assign({},yu),t):yu}const Su=Symbol.for("protobuf-ts/message-type");function Tu(t){let e=!1;const r=[];for(let n=0;n<t.length;n++){let i=t.charAt(n);i=="_"?e=!0:/\d/.test(i)?(r.push(i),e=!0):e?(r.push(i.toUpperCase()),e=!1):n==0?r.push(i.toLowerCase()):r.push(i)}return r.join("")}var M;(function(t){t[t.DOUBLE=1]="DOUBLE",t[t.FLOAT=2]="FLOAT",t[t.INT64=3]="INT64",t[t.UINT64=4]="UINT64",t[t.INT32=5]="INT32",t[t.FIXED64=6]="FIXED64",t[t.FIXED32=7]="FIXED32",t[t.BOOL=8]="BOOL",t[t.STRING=9]="STRING",t[t.BYTES=12]="BYTES",t[t.UINT32=13]="UINT32",t[t.SFIXED32=15]="SFIXED32",t[t.SFIXED64=16]="SFIXED64",t[t.SINT32=17]="SINT32",t[t.SINT64=18]="SINT64"})(M||(M={}));var sr;(function(t){t[t.BIGINT=0]="BIGINT",t[t.STRING=1]="STRING",t[t.NUMBER=2]="NUMBER"})(sr||(sr={}));var _o;(function(t){t[t.NO=0]="NO",t[t.PACKED=1]="PACKED",t[t.UNPACKED=2]="UNPACKED"})(_o||(_o={}));function Nv(t){var e,r,n,i;return t.localName=(e=t.localName)!==null&&e!==void 0?e:Tu(t.name),t.jsonName=(r=t.jsonName)!==null&&r!==void 0?r:Tu(t.name),t.repeat=(n=t.repeat)!==null&&n!==void 0?n:_o.NO,t.opt=(i=t.opt)!==null&&i!==void 0?i:t.repeat||t.oneof?!1:t.kind=="message",t}function Lv(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 xv{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}prepare(){if(this.data)return;const e=[],r=[],n=[];for(let i of this.fields)if(i.oneof)n.includes(i.oneof)||(n.push(i.oneof),e.push(i.oneof),r.push(i.oneof));else switch(r.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&e.push(i.localName);break;case"message":i.repeat&&e.push(i.localName);break;case"map":e.push(i.localName);break}this.data={req:e,known:r,oneofs:Object.values(n)}}is(e,r,n=!1){if(r<0)return!0;if(e==null||typeof e!="object")return!1;this.prepare();let i=Object.keys(e),s=this.data;if(i.length<s.req.length||s.req.some(o=>!i.includes(o))||!n&&i.some(o=>!s.known.includes(o)))return!1;if(r<1)return!0;for(const o of s.oneofs){const a=e[o];if(!Lv(a))return!1;if(a.oneofKind===void 0)continue;const d=this.fields.find(h=>h.localName===a.oneofKind);if(!d||!this.field(a[a.oneofKind],d,n,r))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(e[o.localName],o,n,r))return!1;return!0}field(e,r,n,i){let s=r.repeat;switch(r.kind){case"scalar":return e===void 0?r.opt:s?this.scalars(e,r.T,i,r.L):this.scalar(e,r.T,r.L);case"enum":return e===void 0?r.opt:s?this.scalars(e,M.INT32,i):this.scalar(e,M.INT32);case"message":return e===void 0?!0:s?this.messages(e,r.T(),n,i):this.message(e,r.T(),n,i);case"map":if(typeof e!="object"||e===null)return!1;if(i<2)return!0;if(!this.mapKeys(e,r.K,i))return!1;switch(r.V.kind){case"scalar":return this.scalars(Object.values(e),r.V.T,i,r.V.L);case"enum":return this.scalars(Object.values(e),M.INT32,i);case"message":return this.messages(Object.values(e),r.V.T(),n,i)}break}return!0}message(e,r,n,i){return n?r.isAssignable(e,i):r.is(e,i)}messages(e,r,n,i){if(!Array.isArray(e))return!1;if(i<2)return!0;if(n){for(let s=0;s<e.length&&s<i;s++)if(!r.isAssignable(e[s],i-1))return!1}else for(let s=0;s<e.length&&s<i;s++)if(!r.is(e[s],i-1))return!1;return!0}scalar(e,r,n){let i=typeof e;switch(r){case M.UINT64:case M.FIXED64:case M.INT64:case M.SFIXED64:case M.SINT64:switch(n){case sr.BIGINT:return i=="bigint";case sr.NUMBER:return i=="number"&&!isNaN(e);default:return i=="string"}case M.BOOL:return i=="boolean";case M.STRING:return i=="string";case M.BYTES:return e instanceof Uint8Array;case M.DOUBLE:case M.FLOAT:return i=="number"&&!isNaN(e);default:return i=="number"&&Number.isInteger(e)}}scalars(e,r,n,i){if(!Array.isArray(e))return!1;if(n<2)return!0;if(Array.isArray(e)){for(let s=0;s<e.length&&s<n;s++)if(!this.scalar(e[s],r,i))return!1}return!0}mapKeys(e,r,n){let i=Object.keys(e);switch(r){case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:return this.scalars(i.slice(0,n).map(s=>parseInt(s)),r,n);case M.BOOL:return this.scalars(i.slice(0,n).map(s=>s=="true"?!0:s=="false"?!1:s),r,n);default:return this.scalars(i,r,n,sr.STRING)}}}function Gt(t,e){switch(e){case sr.BIGINT:return t.toBigInt();case sr.NUMBER:return t.toNumber();default:return t.toString()}}class Fv{constructor(e){this.info=e}prepare(){var e;if(this.fMap===void 0){this.fMap={};const r=(e=this.info.fields)!==null&&e!==void 0?e:[];for(const n of r)this.fMap[n.name]=n,this.fMap[n.jsonName]=n,this.fMap[n.localName]=n}}assert(e,r,n){if(!e){let i=Bc(n);throw(i=="number"||i=="boolean")&&(i=n.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${r}`)}}read(e,r,n){this.prepare();const i=[];for(const[s,o]of Object.entries(e)){const a=this.fMap[s];if(!a){if(!n.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${s}`);continue}const d=a.localName;let h;if(a.oneof){if(o===null&&(a.kind!=="enum"||a.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(a.oneof))throw new Error(`Multiple members of the oneof group "${a.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(a.oneof),h=r[a.oneof]={oneofKind:d}}else h=r;if(a.kind=="map"){if(o===null)continue;this.assert(vv(o),a.name,o);const p=h[d];for(const[f,g]of Object.entries(o)){this.assert(g!==null,a.name+" map value",null);let E;switch(a.V.kind){case"message":E=a.V.T().internalJsonRead(g,n);break;case"enum":if(E=this.enum(a.V.T(),g,a.name,n.ignoreUnknownFields),E===!1)continue;break;case"scalar":E=this.scalar(g,a.V.T,a.V.L,a.name);break}this.assert(E!==void 0,a.name+" map value",g);let v=f;a.K==M.BOOL&&(v=v=="true"?!0:v=="false"?!1:v),v=this.scalar(v,a.K,sr.STRING,a.name).toString(),p[v]=E}}else if(a.repeat){if(o===null)continue;this.assert(Array.isArray(o),a.name,o);const p=h[d];for(const f of o){this.assert(f!==null,a.name,null);let g;switch(a.kind){case"message":g=a.T().internalJsonRead(f,n);break;case"enum":if(g=this.enum(a.T(),f,a.name,n.ignoreUnknownFields),g===!1)continue;break;case"scalar":g=this.scalar(f,a.T,a.L,a.name);break}this.assert(g!==void 0,a.name,o),p.push(g)}}else switch(a.kind){case"message":if(o===null&&a.T().typeName!="google.protobuf.Value"){this.assert(a.oneof===void 0,a.name+" (oneof member)",null);continue}h[d]=a.T().internalJsonRead(o,n,h[d]);break;case"enum":let p=this.enum(a.T(),o,a.name,n.ignoreUnknownFields);if(p===!1)continue;h[d]=p;break;case"scalar":h[d]=this.scalar(o,a.T,a.L,a.name);break}}}enum(e,r,n,i){if(e[0]=="google.protobuf.NullValue"&&fe(r===null||r==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} only accepts null.`),r===null)return 0;switch(typeof r){case"number":return fe(Number.isInteger(r),`Unable to parse field ${this.info.typeName}#${n}, enum can only be integral number, got ${r}.`),r;case"string":let s=r;e[2]&&r.substring(0,e[2].length)===e[2]&&(s=r.substring(e[2].length));let o=e[1][s];return typeof o=="undefined"&&i?!1:(fe(typeof o=="number",`Unable to parse field ${this.info.typeName}#${n}, enum ${e[0]} has no value for "${r}".`),o)}fe(!1,`Unable to parse field ${this.info.typeName}#${n}, cannot parse enum value from ${typeof r}".`)}scalar(e,r,n,i){let s;try{switch(r){case M.DOUBLE:case M.FLOAT:if(e===null)return 0;if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""){s="empty string";break}if(typeof e=="string"&&e.trim().length!==e.length){s="extra whitespace";break}if(typeof e!="string"&&typeof e!="number")break;let o=Number(e);if(Number.isNaN(o)){s="not a number";break}if(!Number.isFinite(o)){s="too large or small";break}return r==M.FLOAT&&Wc(o),o;case M.INT32:case M.FIXED32:case M.SFIXED32:case M.SINT32:case M.UINT32:if(e===null)return 0;let a;if(typeof e=="number"?a=e:e===""?s="empty string":typeof e=="string"&&(e.trim().length!==e.length?s="extra whitespace":a=Number(e)),a===void 0)break;return r==M.UINT32?ko(a):cs(a),a;case M.INT64:case M.SFIXED64:case M.SINT64:if(e===null)return Gt(_e.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Gt(_e.from(e),n);case M.FIXED64:case M.UINT64:if(e===null)return Gt(ct.ZERO,n);if(typeof e!="number"&&typeof e!="string")break;return Gt(ct.from(e),n);case M.BOOL:if(e===null)return!1;if(typeof e!="boolean")break;return e;case M.STRING:if(e===null)return"";if(typeof e!="string"){s="extra whitespace";break}try{encodeURIComponent(e)}catch(d){d="invalid UTF8";break}return e;case M.BYTES:if(e===null||e==="")return new Uint8Array(0);if(typeof e!="string")break;return yv(e)}}catch(o){s=o.message}this.assert(!1,i+(s?" - "+s:""),e)}}class Uv{constructor(e){var r;this.fields=(r=e.fields)!==null&&r!==void 0?r:[]}write(e,r){const n={},i=e;for(const s of this.fields){if(!s.oneof){let h=this.field(s,i[s.localName],r);h!==void 0&&(n[r.useProtoFieldName?s.name:s.jsonName]=h);continue}const o=i[s.oneof];if(o.oneofKind!==s.localName)continue;const a=s.kind=="scalar"||s.kind=="enum"?Object.assign(Object.assign({},r),{emitDefaultValues:!0}):r;let d=this.field(s,o[s.localName],a);fe(d!==void 0),n[r.useProtoFieldName?s.name:s.jsonName]=d}return n}field(e,r,n){let i;if(e.kind=="map"){fe(typeof r=="object"&&r!==null);const s={};switch(e.V.kind){case"scalar":for(const[d,h]of Object.entries(r)){const p=this.scalar(e.V.T,h,e.name,!1,!0);fe(p!==void 0),s[d.toString()]=p}break;case"message":const o=e.V.T();for(const[d,h]of Object.entries(r)){const p=this.message(o,h,e.name,n);fe(p!==void 0),s[d.toString()]=p}break;case"enum":const a=e.V.T();for(const[d,h]of Object.entries(r)){fe(h===void 0||typeof h=="number");const p=this.enum(a,h,e.name,!1,!0,n.enumAsInteger);fe(p!==void 0),s[d.toString()]=p}break}(n.emitDefaultValues||Object.keys(s).length>0)&&(i=s)}else if(e.repeat){fe(Array.isArray(r));const s=[];switch(e.kind){case"scalar":for(let d=0;d<r.length;d++){const h=this.scalar(e.T,r[d],e.name,e.opt,!0);fe(h!==void 0),s.push(h)}break;case"enum":const o=e.T();for(let d=0;d<r.length;d++){fe(r[d]===void 0||typeof r[d]=="number");const h=this.enum(o,r[d],e.name,e.opt,!0,n.enumAsInteger);fe(h!==void 0),s.push(h)}break;case"message":const a=e.T();for(let d=0;d<r.length;d++){const h=this.message(a,r[d],e.name,n);fe(h!==void 0),s.push(h)}break}(n.emitDefaultValues||s.length>0||n.emitDefaultValues)&&(i=s)}else switch(e.kind){case"scalar":i=this.scalar(e.T,r,e.name,e.opt,n.emitDefaultValues);break;case"enum":i=this.enum(e.T(),r,e.name,e.opt,n.emitDefaultValues,n.enumAsInteger);break;case"message":i=this.message(e.T(),r,e.name,n);break}return i}enum(e,r,n,i,s,o){if(e[0]=="google.protobuf.NullValue")return!s&&!i?void 0:null;if(r===void 0){fe(i);return}if(!(r===0&&!s&&!i))return fe(typeof r=="number"),fe(Number.isInteger(r)),o||!e[1].hasOwnProperty(r)?r:e[2]?e[2]+e[1][r]:e[1][r]}message(e,r,n,i){return r===void 0?i.emitDefaultValues?null:void 0:e.internalJsonWrite(r,i)}scalar(e,r,n,i,s){if(r===void 0){fe(i);return}const o=s||i;switch(e){case M.INT32:case M.SFIXED32:case M.SINT32:return r===0?o?0:void 0:(cs(r),r);case M.FIXED32:case M.UINT32:return r===0?o?0:void 0:(ko(r),r);case M.FLOAT:Wc(r);case M.DOUBLE:return r===0?o?0:void 0:(fe(typeof r=="number"),Number.isNaN(r)?"NaN":r===Number.POSITIVE_INFINITY?"Infinity":r===Number.NEGATIVE_INFINITY?"-Infinity":r);case M.STRING:return r===""?o?"":void 0:(fe(typeof r=="string"),r);case M.BOOL:return r===!1?o?!1:void 0:(fe(typeof r=="boolean"),r);case M.UINT64:case M.FIXED64:fe(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let a=ct.from(r);return a.isZero()&&!o?void 0:a.toString();case M.INT64:case M.SFIXED64:case M.SINT64:fe(typeof r=="number"||typeof r=="string"||typeof r=="bigint");let d=_e.from(r);return d.isZero()&&!o?void 0:d.toString();case M.BYTES:return fe(r instanceof Uint8Array),r.byteLength?Ev(r):o?"":void 0}}}function $c(t,e=sr.STRING){switch(t){case M.BOOL:return!1;case M.UINT64:case M.FIXED64:return Gt(ct.ZERO,e);case M.INT64:case M.SFIXED64:case M.SINT64:return Gt(_e.ZERO,e);case M.DOUBLE:case M.FLOAT:return 0;case M.BYTES:return new Uint8Array(0);case M.STRING:return"";default:return 0}}class Vv{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const r=(e=this.info.fields)!==null&&e!==void 0?e:[];this.fieldNoToField=new Map(r.map(n=>[n.no,n]))}}read(e,r,n,i){this.prepare();const s=i===void 0?e.len:e.pos+i;for(;e.pos<s;){const[o,a]=e.tag(),d=this.fieldNoToField.get(o);if(!d){let g=n.readUnknownField;if(g=="throw")throw new Error(`Unknown field ${o} (wire type ${a}) for ${this.info.typeName}`);let E=e.skip(a);g!==!1&&(g===!0?yo.onRead:g)(this.info.typeName,r,o,a,E);continue}let h=r,p=d.repeat,f=d.localName;switch(d.oneof&&(h=h[d.oneof],h.oneofKind!==f&&(h=r[d.oneof]={oneofKind:f})),d.kind){case"scalar":case"enum":let g=d.kind=="enum"?M.INT32:d.T,E=d.kind=="scalar"?d.L:void 0;if(p){let A=h[f];if(a==Be.LengthDelimited&&g!=M.STRING&&g!=M.BYTES){let L=e.uint32()+e.pos;for(;e.pos<L;)A.push(this.scalar(e,g,E))}else A.push(this.scalar(e,g,E))}else h[f]=this.scalar(e,g,E);break;case"message":if(p){let A=h[f],L=d.T().internalBinaryRead(e,e.uint32(),n);A.push(L)}else h[f]=d.T().internalBinaryRead(e,e.uint32(),n,h[f]);break;case"map":let[v,R]=this.mapEntry(d,e,n);h[f][v]=R;break}}}mapEntry(e,r,n){let i=r.uint32(),s=r.pos+i,o,a;for(;r.pos<s;){let[d,h]=r.tag();switch(d){case 1:e.K==M.BOOL?o=r.bool().toString():o=this.scalar(r,e.K,sr.STRING);break;case 2:switch(e.V.kind){case"scalar":a=this.scalar(r,e.V.T,e.V.L);break;case"enum":a=r.int32();break;case"message":a=e.V.T().internalBinaryRead(r,r.uint32(),n);break}break;default:throw new Error(`Unknown field ${d} (wire type ${h}) in map entry for ${this.info.typeName}#${e.name}`)}}if(o===void 0){let d=$c(e.K);o=e.K==M.BOOL?d.toString():d}if(a===void 0)switch(e.V.kind){case"scalar":a=$c(e.V.T,e.V.L);break;case"enum":a=0;break;case"message":a=e.V.T().create();break}return[o,a]}scalar(e,r,n){switch(r){case M.INT32:return e.int32();case M.STRING:return e.string();case M.BOOL:return e.bool();case M.DOUBLE:return e.double();case M.FLOAT:return e.float();case M.INT64:return Gt(e.int64(),n);case M.UINT64:return Gt(e.uint64(),n);case M.FIXED64:return Gt(e.fixed64(),n);case M.FIXED32:return e.fixed32();case M.BYTES:return e.bytes();case M.UINT32:return e.uint32();case M.SFIXED32:return e.sfixed32();case M.SFIXED64:return Gt(e.sfixed64(),n);case M.SINT32:return e.sint32();case M.SINT64:return Gt(e.sint64(),n)}}}class Bv{constructor(e){this.info=e}prepare(){if(!this.fields){const e=this.info.fields?this.info.fields.concat():[];this.fields=e.sort((r,n)=>r.no-n.no)}}write(e,r,n){this.prepare();for(const s of this.fields){let o,a,d=s.repeat,h=s.localName;if(s.oneof){const p=e[s.oneof];if(p.oneofKind!==h)continue;o=p[h],a=!0}else o=e[h],a=!1;switch(s.kind){case"scalar":case"enum":let p=s.kind=="enum"?M.INT32:s.T;if(d)if(fe(Array.isArray(o)),d==_o.PACKED)this.packed(r,p,s.no,o);else for(const f of o)this.scalar(r,p,s.no,f,!0);else o===void 0?fe(s.opt):this.scalar(r,p,s.no,o,a||s.opt);break;case"message":if(d){fe(Array.isArray(o));for(const f of o)this.message(r,n,s.T(),s.no,f)}else this.message(r,n,s.T(),s.no,o);break;case"map":fe(typeof o=="object"&&o!==null);for(const[f,g]of Object.entries(o))this.mapEntry(r,n,s,f,g);break}}let i=n.writeUnknownFields;i!==!1&&(i===!0?yo.onWrite:i)(this.info.typeName,e,r)}mapEntry(e,r,n,i,s){e.tag(n.no,Be.LengthDelimited),e.fork();let o=i;switch(n.K){case M.INT32:case M.FIXED32:case M.UINT32:case M.SFIXED32:case M.SINT32:o=Number.parseInt(i);break;case M.BOOL:fe(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(e,n.K,1,o,!0),n.V.kind){case"scalar":this.scalar(e,n.V.T,2,s,!0);break;case"enum":this.scalar(e,M.INT32,2,s,!0);break;case"message":this.message(e,r,n.V.T(),2,s);break}e.join()}message(e,r,n,i,s){s!==void 0&&(n.internalBinaryWrite(s,e.tag(i,Be.LengthDelimited).fork(),r),e.join())}scalar(e,r,n,i,s){let[o,a,d]=this.scalarInfo(r,i);(!d||s)&&(e.tag(n,o),e[a](i))}packed(e,r,n,i){if(!i.length)return;fe(r!==M.BYTES&&r!==M.STRING),e.tag(n,Be.LengthDelimited),e.fork();let[,s]=this.scalarInfo(r);for(let o=0;o<i.length;o++)e[s](i[o]);e.join()}scalarInfo(e,r){let n=Be.Varint,i,s=r===void 0,o=r===0;switch(e){case M.INT32:i="int32";break;case M.STRING:o=s||!r.length,n=Be.LengthDelimited,i="string";break;case M.BOOL:o=r===!1,i="bool";break;case M.UINT32:i="uint32";break;case M.DOUBLE:n=Be.Bit64,i="double";break;case M.FLOAT:n=Be.Bit32,i="float";break;case M.INT64:o=s||_e.from(r).isZero(),i="int64";break;case M.UINT64:o=s||ct.from(r).isZero(),i="uint64";break;case M.FIXED64:o=s||ct.from(r).isZero(),n=Be.Bit64,i="fixed64";break;case M.BYTES:o=s||!r.byteLength,n=Be.LengthDelimited,i="bytes";break;case M.FIXED32:n=Be.Bit32,i="fixed32";break;case M.SFIXED32:n=Be.Bit32,i="sfixed32";break;case M.SFIXED64:o=s||_e.from(r).isZero(),n=Be.Bit64,i="sfixed64";break;case M.SINT32:i="sint32";break;case M.SINT64:o=s||_e.from(r).isZero(),i="sint64";break}return[n,i,s||o]}}function jv(t){const e=t.messagePrototype?Object.create(t.messagePrototype):Object.defineProperty({},Su,{value:t});for(let r of t.fields){let n=r.localName;if(!r.opt)if(r.oneof)e[r.oneof]={oneofKind:void 0};else if(r.repeat)e[n]=[];else switch(r.kind){case"scalar":e[n]=$c(r.T,r.L);break;case"enum":e[n]=0;break;case"map":e[n]={};break}}return e}function Gc(t,e,r){let n,i=r,s;for(let o of t.fields){let a=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(n=d[a],s=e[o.oneof],s.oneofKind=d.oneofKind,n==null){delete s[a];continue}}else if(n=i[a],s=e,n==null)continue;switch(o.repeat&&(s[a].length=n.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=n[h];else s[a]=n;break;case"message":let d=o.T();if(o.repeat)for(let h=0;h<n.length;h++)s[a][h]=d.create(n[h]);else s[a]===void 0?s[a]=d.create(n):d.mergePartial(s[a],n);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(s[a],n);break;case"message":let h=o.V.T();for(let p of Object.keys(n))s[a][p]=h.create(n[p]);break}break}}}function Hv(t,e,r){if(e===r)return!0;if(!e||!r)return!1;for(let n of t.fields){let i=n.localName,s=n.oneof?e[n.oneof][i]:e[i],o=n.oneof?r[n.oneof][i]:r[i];switch(n.kind){case"enum":case"scalar":let a=n.kind=="enum"?M.INT32:n.T;if(!(n.repeat?_u(a,s,o):ku(a,s,o)))return!1;break;case"map":if(!(n.V.kind=="message"?bu(n.V.T(),bo(s),bo(o)):_u(n.V.kind=="enum"?M.INT32:n.V.T,bo(s),bo(o))))return!1;break;case"message":let d=n.T();if(!(n.repeat?bu(d,s,o):d.equals(s,o)))return!1;break}}return!0}const bo=Object.values;function ku(t,e,r){if(e===r)return!0;if(t!==M.BYTES)return!1;let n=e,i=r;if(n.length!==i.length)return!1;for(let s=0;s<n.length;s++)if(n[s]!=i[s])return!1;return!0}function _u(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!ku(t,e[n],r[n]))return!1;return!0}function bu(t,e,r){if(e.length!==r.length)return!1;for(let n=0;n<e.length;n++)if(!t.equals(e[n],r[n]))return!1;return!0}const Wv=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class k{constructor(e,r,n){this.defaultCheckDepth=16,this.typeName=e,this.fields=r.map(Nv),this.options=n!=null?n:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Wv),{[Su]:{value:this}})),this.refTypeCheck=new xv(this),this.refJsonReader=new Fv(this),this.refJsonWriter=new Uv(this),this.refBinReader=new Vv(this),this.refBinWriter=new Bv(this)}create(e){let r=jv(this);return e!==void 0&&Gc(this,r,e),r}clone(e){let r=this.create();return Gc(this,r,e),r}equals(e,r){return Hv(this,e,r)}is(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!1)}isAssignable(e,r=this.defaultCheckDepth){return this.refTypeCheck.is(e,r,!0)}mergePartial(e,r){Gc(this,e,r)}fromBinary(e,r){let n=_v(r);return this.internalBinaryRead(n.readerFactory(e),e.byteLength,n)}fromJson(e,r){return this.internalJsonRead(e,Dv(r))}fromJsonString(e,r){let n=JSON.parse(e);return this.fromJson(n,r)}toJson(e,r){return this.internalJsonWrite(e,Ov(r))}toJsonString(e,r){var n;let i=this.toJson(e,r);return JSON.stringify(i,null,(n=r==null?void 0:r.prettySpaces)!==null&&n!==void 0?n:0)}toBinary(e,r){let n=Av(r);return this.internalBinaryWrite(e,n.writerFactory(),n).finish()}internalJsonRead(e,r,n){if(e!==null&&typeof e=="object"&&!Array.isArray(e)){let i=n!=null?n:this.create();return this.refJsonReader.read(e,i,r),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${Bc(e)}.`)}internalJsonWrite(e,r){return this.refJsonWriter.write(e,r)}internalBinaryWrite(e,r,n){return this.refBinWriter.write(e,r,n),r}internalBinaryRead(e,r,n,i){let s=i!=null?i:this.create();return this.refBinReader.read(e,s,n,r),s}}const $v=t=>(e,r)=>(t.set(e,r),r),wu=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Cu=536870912,Iu=Cu*2,Gv=(t,e)=>r=>{const n=e.get(r);let i=n===void 0?r.size:n<Iu?n+1:0;if(!r.has(i))return t(r,i);if(r.size<Cu){for(;r.has(i);)i=Math.floor(Math.random()*Iu);return t(r,i)}if(r.size>wu)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*wu);return t(r,i)},Ru=new WeakMap,Jv=$v(Ru),wo=Gv(Jv,Ru),qv=t=>t.method!==void 0&&t.method==="call",Kv=t=>t.error===null&&typeof t.id=="number",Co=((t,e)=>{let r=null;return()=>{if(r!==null)return r;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=t(i),setTimeout(()=>URL.revokeObjectURL(i)),r}})(t=>{const e=new Map([[0,()=>{}]]),r=new Map([[0,()=>{}]]),n=new Map,i=new Worker(t);return i.addEventListener("message",({data:h})=>{if(qv(h)){const{params:{timerId:p,timerType:f}}=h;if(f==="interval"){const g=e.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g();else throw new Error("The timer is in an undefined state.")}else if(f==="timeout"){const g=r.get(p);if(typeof g=="number"){const E=n.get(g);if(E===void 0||E.timerId!==p||E.timerType!==f)throw new Error("The timer is in an undefined state.")}else if(typeof g!="undefined")g(),r.delete(p);else throw new Error("The timer is in an undefined state.")}}else if(Kv(h)){const{id:p}=h,f=n.get(p);if(f===void 0)throw new Error("The timer is in an undefined state.");const{timerId:g,timerType:E}=f;n.delete(p),E==="interval"?e.delete(g):r.delete(g)}else{const{error:{message:p}}=h;throw new Error(p)}}),{clearInterval:h=>{const p=wo(n);n.set(p,{timerId:h,timerType:"interval"}),e.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"interval"}})},clearTimeout:h=>{const p=wo(n);n.set(p,{timerId:h,timerType:"timeout"}),r.set(h,p),i.postMessage({id:p,method:"clear",params:{timerId:h,timerType:"timeout"}})},setInterval:(h,p=0)=>{const f=wo(e);return e.set(f,()=>{h(),typeof e.get(f)=="function"&&i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"interval"}}),f},setTimeout:(h,p=0)=>{const f=wo(r);return r.set(f,h),i.postMessage({id:null,method:"set",params:{delay:p,now:performance.now(),timerId:f,timerType:"timeout"}}),f}}},`(()=>{"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})}}))})();`),Pu=t=>Co().clearInterval(t),zv=t=>Co().clearTimeout(t),Au=(t,e)=>Co().setInterval(t,e);var Yv=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Pu,clearTimeout:zv,setInterval:Au,setTimeout:(t,e)=>Co().setTimeout(t,e)},Symbol.toStringTag,{value:"Module"})),Mu={},Jc={exports:{}},Du=Jc.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(Du).forEach(function(t){var e=Du[t];e.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),function(t){var e=function(a){return String(Number(a))===a?Number(a):a},r=function(a,d,h,p){if(p&&!h)d[p]=e(a[1]);else for(var f=0;f<h.length;f+=1)a[f+1]!=null&&(d[h[f]]=e(a[f+1]))},n=function(a,d,h){var p=a.name&&a.names;a.push&&!d[a.push]?d[a.push]=[]:p&&!d[a.name]&&(d[a.name]={});var f=a.push?{}:p?d[a.name]:d;r(h.match(a.reg),f,a.names,a.name),a.push&&d[a.push].push(f)},i=Jc.exports,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);t.parse=function(a){var d={},h=[],p=d;return a.split(/(\r\n|\r|\n)/).filter(s).forEach(function(f){var g=f[0],E=f.slice(2);g==="m"&&(h.push({rtp:[],fmtp:[]}),p=h[h.length-1]);for(var v=0;v<(i[g]||[]).length;v+=1){var R=i[g][v];if(R.reg.test(E))return n(R,p,E)}}),d.media=h,d};var o=function(a,d){var h=d.split(/=(.+)/,2);return h.length===2?a[h[0]]=e(h[1]):h.length===1&&d.length>1&&(a[h[0]]=void 0),a};t.parseParams=function(a){return a.split(/;\s?/).reduce(o,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(a){return a.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(a){for(var d=[],h=a.split(" ").map(e),p=0;p<h.length;p+=3)d.push({component:h[p],ip:h[p+1],port:h[p+2]});return d},t.parseImageAttributes=function(a){return a.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},t.parseSimulcastStreamList=function(a){return a.split(";").map(function(d){return d.split(",").map(function(h){var p,f=!1;return h[0]!=="~"?p=e(h):(p=e(h.substring(1,h.length)),f=!0),{scid:p,paused:f}})})}}(Mu);var qc=Jc.exports,Qv=/%[sdv%]/g,Xv=function(t){var e=1,r=arguments,n=r.length;return t.replace(Qv,function(i){if(e>=n)return i;var s=r[e];switch(e+=1,i){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ds=function(t,e,r){var n=e.format instanceof Function?e.format(e.push?r:r[e.name]):e.format,i=[t+"="+n];if(e.names)for(var s=0;s<e.names.length;s+=1){var o=e.names[s];e.name?i.push(r[e.name][o]):i.push(r[e.names[s]])}else i.push(r[e.name]);return Xv.apply(null,i)},Zv=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ey=["i","c","b","a"],ty=function(t,e){e=e||{},t.version==null&&(t.version=0),t.name==null&&(t.name=" "),t.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=e.outerOrder||Zv,n=e.innerOrder||ey,i=[];return r.forEach(function(s){qc[s].forEach(function(o){o.name in t&&t[o.name]!=null?i.push(ds(s,o,t)):o.push in t&&t[o.push]!=null&&t[o.push].forEach(function(a){i.push(ds(s,o,a))})})}),t.media.forEach(function(s){i.push(ds("m",qc.m[0],s)),n.forEach(function(o){qc[o].forEach(function(a){a.name in s&&s[a.name]!=null?i.push(ds(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(d){i.push(ds(o,a,d))})})})}),i.join(`\r
8
+ `)+`\r
9
+ `},vn=Mu,ry=ty,ny=ry,Kc=vn.parse;vn.parseParams,vn.parseFmtpConfig,vn.parsePayloads,vn.parseRemoteCandidates,vn.parseImageAttributes,vn.parseSimulcastStreamList;var iy=Object.defineProperty,sy=Object.defineProperties,oy=Object.getOwnPropertyDescriptors,Io=Object.getOwnPropertySymbols,ay=Object.getPrototypeOf,Ou=Object.prototype.hasOwnProperty,Nu=Object.prototype.propertyIsEnumerable,cy=Reflect.get,dy=Math.pow,zc=(t,e,r)=>e in t?iy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,V=(t,e)=>{for(var r in e||(e={}))Ou.call(e,r)&&zc(t,r,e[r]);if(Io)for(var r of Io(e))Nu.call(e,r)&&zc(t,r,e[r]);return t},ne=(t,e)=>sy(t,oy(e)),Ro=(t,e)=>{var r={};for(var n in t)Ou.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&Io)for(var n of Io(t))e.indexOf(n)<0&&Nu.call(t,n)&&(r[n]=t[n]);return r},m=(t,e,r)=>(zc(t,typeof e!="symbol"?e+"":e,r),r),Yc=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},c=(t,e,r)=>(Yc(t,e,"read from private field"),r?r.call(t):e.get(t)),_=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},T=(t,e,r,n)=>(Yc(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),ue=(t,e,r)=>(Yc(t,e,"access private method"),r),ly=(t,e,r)=>cy(ay(t),r,e),u=(t,e,r)=>new Promise((n,i)=>{var s=d=>{try{a(r.next(d))}catch(h){i(h)}},o=d=>{try{a(r.throw(d))}catch(h){i(h)}},a=d=>d.done?n(d.value):Promise.resolve(d.value).then(s,o);a((r=r.apply(t,e)).next())}),Lu=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function uy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var _t={},hy={get exports(){return _t},set exports(t){_t=t}},fi=typeof Reflect=="object"?Reflect:null,xu=fi&&typeof fi.apply=="function"?fi.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Po;fi&&typeof fi.ownKeys=="function"?Po=fi.ownKeys:Object.getOwnPropertySymbols?Po=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Po=function(t){return Object.getOwnPropertyNames(t)};function py(t){console&&console.warn&&console.warn(t)}var Fu=Number.isNaN||function(t){return t!==t};function ve(){ve.init.call(this)}hy.exports=ve,_t.once=vy,ve.EventEmitter=ve,ve.prototype._events=void 0,ve.prototype._eventsCount=0,ve.prototype._maxListeners=void 0;var Uu=10;function Ao(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(ve,"defaultMaxListeners",{enumerable:!0,get:function(){return Uu},set:function(t){if(typeof t!="number"||t<0||Fu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Uu=t}}),ve.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},ve.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Fu(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 Vu(t){return t._maxListeners===void 0?ve.defaultMaxListeners:t._maxListeners}ve.prototype.getMaxListeners=function(){return Vu(this)},ve.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")xu(a,this,e);else for(var d=a.length,h=$u(a,d),r=0;r<d;++r)xu(h[r],this,e);return!0};function Bu(t,e,r,n){var i,s,o;if(Ao(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Vu(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,py(a)}return t}ve.prototype.addListener=function(t,e){return Bu(this,t,e,!1)},ve.prototype.on=ve.prototype.addListener,ve.prototype.prependListener=function(t,e){return Bu(this,t,e,!0)};function my(){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 ju(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=my.bind(n);return i.listener=r,n.wrapFn=i,i}ve.prototype.once=function(t,e){return Ao(e),this.on(t,ju(this,t,e)),this},ve.prototype.prependOnceListener=function(t,e){return Ao(e),this.prependListener(t,ju(this,t,e)),this},ve.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Ao(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():fy(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},ve.prototype.off=ve.prototype.removeListener,ve.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function Hu(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?gy(i):$u(i,i.length)}ve.prototype.listeners=function(t){return Hu(this,t,!0)},ve.prototype.rawListeners=function(t){return Hu(this,t,!1)},ve.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Wu.call(t,e)},ve.prototype.listenerCount=Wu;function Wu(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}ve.prototype.eventNames=function(){return this._eventsCount>0?Po(this._events):[]};function $u(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function fy(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gy(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function vy(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Gu(t,e,s,{once:!0}),e!=="error"&&yy(t,i,{once:!0})})}function yy(t,e,r){typeof t.on=="function"&&Gu(t,"error",e,r)}function Gu(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var or={},Ey={get exports(){return or},set exports(t){or=t}},Qc,Ju;function Sy(){if(Ju)return Qc;Ju=1;var t=1e3,e=t*60,r=e*60,n=r*24,i=n*7,s=n*365.25;Qc=function(p,f){f=f||{};var g=typeof p;if(g==="string"&&p.length>0)return o(p);if(g==="number"&&isFinite(p))return f.long?d(p):a(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))};function o(p){if(p=String(p),!(p.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(f){var g=parseFloat(f[1]),E=(f[2]||"ms").toLowerCase();switch(E){case"years":case"year":case"yrs":case"yr":case"y":return g*s;case"weeks":case"week":case"w":return g*i;case"days":case"day":case"d":return g*n;case"hours":case"hour":case"hrs":case"hr":case"h":return g*r;case"minutes":case"minute":case"mins":case"min":case"m":return g*e;case"seconds":case"second":case"secs":case"sec":case"s":return g*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return g;default:return}}}}function a(p){var f=Math.abs(p);return f>=n?Math.round(p/n)+"d":f>=r?Math.round(p/r)+"h":f>=e?Math.round(p/e)+"m":f>=t?Math.round(p/t)+"s":p+"ms"}function d(p){var f=Math.abs(p);return f>=n?h(p,f,n,"day"):f>=r?h(p,f,r,"hour"):f>=e?h(p,f,e,"minute"):f>=t?h(p,f,t,"second"):p+" ms"}function h(p,f,g,E){var v=f>=g*1.5;return Math.round(p/g)+" "+E+(v?"s":"")}return Qc}function Ty(t){r.debug=r,r.default=r,r.coerce=d,r.disable=s,r.enable=i,r.enabled=o,r.humanize=Sy(),r.destroy=h,Object.keys(t).forEach(p=>{r[p]=t[p]}),r.names=[],r.skips=[],r.formatters={};function e(p){let f=0;for(let g=0;g<p.length;g++)f=(f<<5)-f+p.charCodeAt(g),f|=0;return r.colors[Math.abs(f)%r.colors.length]}r.selectColor=e;function r(p){let f,g=null,E,v;function R(...A){if(!R.enabled)return;const L=R,F=Number(new Date),W=F-(f||F);L.diff=W,L.prev=f,L.curr=F,f=F,A[0]=r.coerce(A[0]),typeof A[0]!="string"&&A.unshift("%O");let H=0;A[0]=A[0].replace(/%([a-zA-Z%])/g,(I,S)=>{if(I==="%%")return"%";H++;const P=r.formatters[S];if(typeof P=="function"){const N=A[H];I=P.call(L,N),A.splice(H,1),H--}return I}),r.formatArgs.call(L,A),(L.log||r.log).apply(L,A)}return R.namespace=p,R.useColors=r.useColors(),R.color=r.selectColor(p),R.extend=n,R.destroy=r.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>g!==null?g:(E!==r.namespaces&&(E=r.namespaces,v=r.enabled(p)),v),set:A=>{g=A}}),typeof r.init=="function"&&r.init(R),R}function n(p,f){const g=r(this.namespace+(typeof f=="undefined"?":":f)+p);return g.log=this.log,g}function i(p){r.save(p),r.namespaces=p,r.names=[],r.skips=[];let f;const g=(typeof p=="string"?p:"").split(/[\s,]+/),E=g.length;for(f=0;f<E;f++)g[f]&&(p=g[f].replace(/\*/g,".*?"),p[0]==="-"?r.skips.push(new RegExp("^"+p.slice(1)+"$")):r.names.push(new RegExp("^"+p+"$")))}function s(){const p=[...r.names.map(a),...r.skips.map(a).map(f=>"-"+f)].join(",");return r.enable(""),p}function o(p){if(p[p.length-1]==="*")return!0;let f,g;for(f=0,g=r.skips.length;f<g;f++)if(r.skips[f].test(p))return!1;for(f=0,g=r.names.length;f<g;f++)if(r.names[f].test(p))return!0;return!1}function a(p){return p.toString().substring(2,p.toString().length-2).replace(/\.\*\?$/,"*")}function d(p){return p instanceof Error?p.stack||p.message:p}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}var ky=Ty;(function(t,e){e.formatArgs=n,e.save=i,e.load=s,e.useColors=r,e.storage=o(),e.destroy=(()=>{let d=!1;return()=>{d||(d=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function r(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let d;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(d=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(d[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function n(d){if(d[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+d[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),!this.useColors)return;const h="color: "+this.color;d.splice(1,0,h,"color: inherit");let p=0,f=0;d[0].replace(/%[a-zA-Z%]/g,g=>{g!=="%%"&&(p++,g==="%c"&&(f=p))}),d.splice(f,0,h)}e.log=console.debug||console.log||(()=>{});function i(d){try{d?e.storage.setItem("debug",d):e.storage.removeItem("debug")}catch(h){}}function s(){let d;try{d=e.storage.getItem("debug")}catch(h){}return!d&&typeof process!="undefined"&&"env"in process&&(d={}.DEBUG),d}function o(){try{return localStorage}catch(d){}}t.exports=ky(e);const{formatters:a}=t.exports;a.j=function(d){try{return JSON.stringify(d)}catch(h){return"[UnexpectedJSONParseError]: "+h.message}}})(Ey,or);const gi="mediasoup-client";let _y=class{constructor(t){t?(this._debug=or(`${gi}:${t}`),this._warn=or(`${gi}:WARN:${t}`),this._error=or(`${gi}:ERROR:${t}`)):(this._debug=or(gi),this._warn=or(`${gi}:WARN`),this._error=or(`${gi}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};const by=new _y("EnhancedEventEmitter");let Mo=class extends _t.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}emit(t,...e){return super.emit(t,...e)}safeEmit(t,...e){const r=super.listenerCount(t);try{return super.emit(t,...e)}catch(n){return by.error("safeEmit() | event listener threw an error [eventName:%s]:%o",t,n),Boolean(r)}}on(t,e){return super.on(t,e),this}off(t,e){return super.off(t,e),this}addListener(t,e){return super.on(t,e),this}prependListener(t,e){return super.prependListener(t,e),this}once(t,e){return super.once(t,e),this}prependOnceListener(t,e){return super.prependOnceListener(t,e),this}removeListener(t,e){return super.off(t,e),this}removeAllListeners(t){return super.removeAllListeners(t),this}listenerCount(t){return super.listenerCount(t)}listeners(t){return super.listeners(t)}rawListeners(t){return super.rawListeners(t)}};var z;(function(t){t[t.MAJOR_EVENT=0]="MAJOR_EVENT",t[t.MINOR_EVENT=1]="MINOR_EVENT"})(z||(z={}));var U;(function(t){t.PRECALL_TEST_BEGIN="precall_begin",t.PRECALL_TEST_COMPLETE="precall_end",t.CALL_JOIN_BEGIN="call_join",t.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",t.NET_QUALITY_TEST_END="net_quality_test_end",t.WEBSOCKET_CONNECTED="websocket_connected",t.TRANSPORT_CONNECTED="transport_connected",t.AUDIO_ON="audio_on",t.AUDIO_OFF="audio_off",t.VIDEO_ON="video_on",t.VIDEO_OFF="video_off",t.PARTICIPANT_ROLE="participant_role",t.PING_STAT="ping_stat",t.DISCONNECT="disconnect",t.RECONNECT_ATTEMPT="reconnect_attempt",t.SCREENSHARE_START_REQUESTED="screenshare_start_requested",t.SCREENSHARE_STARTED="screenshare_started",t.SCREENSHARE_STOPPED="screenshare_stopped",t.TAB_CHANGE="tab_change",t.BROWSER_BACKGROUNDED="browser_backgrounded",t.BROWSER_FOREGROUNDED="browser_foregrounded",t.DOMINANT_SPEAKER="dominant_speaker",t.AUDIO_DEVICES_UPDATES="audio_devices_updates",t.VIDEO_DEVICES_UPDATES="video_devices_updates",t.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",t.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",t.SELECTED_CAMERA_UPDATE="selected_camera_update",t.SELECTED_SPEAKER_UPDATE="selected_speaker_update",t.MEDIA_PERMISSION="media_permission",t.LEGACY_SWITCH="legacy_switch",t.AUDIO_PLAY_FAILED="audio_play_failed",t.VIDEO_PLAY_FAILED="video_play_failed",t.AUDIO_TRACK_MUTED="audio_track_muted",t.VIDEO_TRACK_MUTED="video_track_muted",t.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",t.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",t.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",t.IVS_PLAYER_ERROR="ivs_player_error",t.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",t.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",t.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",t.LIVESTREAM_LATENCY="livestream_latency",t.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",t.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",t.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",t.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(U||(U={}));const wy=new Map([[U.PRECALL_TEST_BEGIN,z.MINOR_EVENT],[U.PRECALL_TEST_COMPLETE,z.MINOR_EVENT],[U.CALL_JOIN_BEGIN,z.MAJOR_EVENT],[U.NET_QUALITY_TEST_BEGIN,z.MINOR_EVENT],[U.NET_QUALITY_TEST_END,z.MINOR_EVENT],[U.WEBSOCKET_CONNECTED,z.MINOR_EVENT],[U.TRANSPORT_CONNECTED,z.MAJOR_EVENT],[U.AUDIO_ON,z.MINOR_EVENT],[U.AUDIO_OFF,z.MINOR_EVENT],[U.VIDEO_ON,z.MINOR_EVENT],[U.VIDEO_OFF,z.MINOR_EVENT],[U.PARTICIPANT_ROLE,z.MINOR_EVENT],[U.PING_STAT,z.MAJOR_EVENT],[U.DISCONNECT,z.MAJOR_EVENT],[U.RECONNECT_ATTEMPT,z.MAJOR_EVENT],[U.SCREENSHARE_START_REQUESTED,z.MINOR_EVENT],[U.SCREENSHARE_STARTED,z.MINOR_EVENT],[U.SCREENSHARE_STOPPED,z.MINOR_EVENT],[U.TAB_CHANGE,z.MINOR_EVENT],[U.BROWSER_BACKGROUNDED,z.MINOR_EVENT],[U.BROWSER_FOREGROUNDED,z.MINOR_EVENT],[U.DOMINANT_SPEAKER,z.MINOR_EVENT],[U.AUDIO_DEVICES_UPDATES,z.MINOR_EVENT],[U.VIDEO_DEVICES_UPDATES,z.MINOR_EVENT],[U.SPEAKER_DEVICES_UPDATES,z.MINOR_EVENT],[U.SELECTED_MICROHPONE_UPDATE,z.MINOR_EVENT],[U.SELECTED_CAMERA_UPDATE,z.MINOR_EVENT],[U.SELECTED_SPEAKER_UPDATE,z.MINOR_EVENT],[U.MEDIA_PERMISSION,z.MINOR_EVENT],[U.LEGACY_SWITCH,z.MINOR_EVENT],[U.AUDIO_PLAY_FAILED,z.MINOR_EVENT],[U.VIDEO_PLAY_FAILED,z.MINOR_EVENT],[U.AUDIO_TRACK_MUTED,z.MINOR_EVENT],[U.VIDEO_TRACK_MUTED,z.MINOR_EVENT],[U.IVS_PLAYER_REBUFFERING,z.MAJOR_EVENT],[U.IVS_PLAYER_AUDIO_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_PLAYBACK_BLOCKED,z.MAJOR_EVENT],[U.IVS_PLAYER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_RECOVERABLE_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_WORKER_ERROR,z.MAJOR_EVENT],[U.IVS_PLAYER_NETWORK_UNAVAILABLE,z.MAJOR_EVENT],[U.LIVESTREAM_LATENCY,z.MAJOR_EVENT],[U.IVS_PLAYER_ANALYTICS_EVENT,z.MINOR_EVENT],[U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_QUALITY_CHANGED,z.MINOR_EVENT],[U.IVS_PLAYER_INITIALIZED,z.MINOR_EVENT]]);class Cy{constructor(){m(this,"events"),this.events=[]}add(e){this.events.push(e)}flush(){return{entries:this.events.splice(0,25)}}}class Iy extends _t{constructor({logger:e,peerId:r,apiHostnames:n}){super(),m(this,"logger"),m(this,"peerId"),m(this,"eventStore"),m(this,"apiEndpoint"),this.logger=e,this.peerId=r,this.apiEndpoint=`https://${n.daCollector}/api/v1/message`,this.eventStore=new Cy}sendEventsChunkToServer(e){return u(this,null,function*(){var r;const n={payload:e,peerId:this.peerId};try{return yield fetch(this.apiEndpoint,{method:"POST",body:JSON.stringify(n)}),!0}catch(i){return this.logger.error("callStats::sendEventsChunkToServer::catch",{error:i}),(r=e.entries)==null||r.forEach(s=>{this.eventStore.add(s)}),!1}})}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),wy.get(e.event)===z.MAJOR_EVENT&&this.flush()}flush(){return u(this,null,function*(){var e;const r=this.eventStore.flush();return(e=r==null?void 0:r.entries)!=null&&e.length?(yield this.sendEventsChunkToServer(r),!0):!1})}}var qu;(function(t){t.CHROMIUM="chromum",t.FIREFOX="firefox",t.SAFARI="safari"})(qu||(qu={}));const ls={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Vt;(function(t){t.AUDIO="AUDIO",t.VIDEO="VIDEO",t.SPEAKER="SPEAKER",t.SCREENSHARE="SCREENSHARE"})(Vt||(Vt={}));var Ku;(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"})(Ku||(Ku={}));const zu=240,Yu=720,Qu=8,Xu=3,Do=10,Oo=.02,No=.03;function yr({stat:t,weight:e,rangeMin:r,rangeMax:n,rangeRankingDirection:i}){return t==null?e:r===n?i==="UP"?t<=r?e:0:t>=n?e:0:i==="UP"?(1-Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r))*e:i==="DOWN"?Math.max(Math.min(n,Math.abs(t))-r,0)/(n-r)*e:e}function Zu({isLowQualityVideo:t,isVideoStuck:e,isVideoLagging:r,jitterQuality:n,packetsLostQuality:i}){const s=.8*((t?.85:1)*(r?.7:1)*(e?.5:1))+.2*(n*i);return Math.round((s+Number.EPSILON)*100)/100}function eh({packetsLost:t,packetsSent:e}){return e>0?t*100/e:0}function th({packetsLost:t,packetsSent:e,jitter:r}){const n=yr({stat:eh({packetsLost:t,packetsSent:e}),weight:.7,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),i=yr({stat:r,weight:.3,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"});return n+i}function Ry({frameWidth:t,isScreenShare:e}){return t<(e?Yu:zu)}function Py({framesPerSecond:t,isScreenShare:e}){return t<(e?Xu:Qu)}function Ay({framesEncoded:t}){return t===0}function rh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsSent:n,jitter:i,isScreenShare:s,framesEncoded:o}){const a=yr({stat:eh({packetsLost:r,packetsSent:n}),weight:1,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),d=yr({stat:i,weight:1,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"}),h=Ry({frameWidth:t,isScreenShare:s}),p=Py({framesPerSecond:e,isScreenShare:s}),f=Ay({framesEncoded:o,isScreenShare:s});return Zu({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}function nh({packetsLost:t,packetsReceived:e}){return e+t>0?t*100/(e+t):0}function ih({concealmentEvents:t,packetsLost:e,packetsReceived:r,jitter:n}){const i=yr({stat:t,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),s=.5,o=yr({stat:nh({packetsLost:e,packetsReceived:r}),weight:s,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),a=yr({stat:n,weight:.3,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"});return i+o+a}function My({framesDecoded:t}){return t===0}function Dy({framesPerSecond:t,isScreenShare:e}){return t<(e?Xu:Qu)}function Oy({frameWidth:t,isScreenShare:e}){return t<(e?Yu:zu)}function sh({frameWidth:t,framesPerSecond:e,packetsLost:r,packetsReceived:n,jitter:i,isScreenShare:s,framesDecoded:o}){const a=yr({stat:nh({packetsLost:r,packetsReceived:n}),weight:1,rangeMin:0,rangeMax:Do,rangeRankingDirection:"UP"}),d=yr({stat:i,weight:1,rangeMin:Oo,rangeMax:No,rangeRankingDirection:"UP"}),h=Oy({frameWidth:t,isScreenShare:s}),p=Dy({framesPerSecond:e,isScreenShare:s}),f=My({framesDecoded:o,isScreenShare:s});return Zu({isLowQualityVideo:h,isVideoLagging:p,isVideoStuck:f,jitterQuality:d,packetsLostQuality:a})}class Er{constructor(e){m(this,"pc1"),m(this,"pc2"),m(this,"constrainVideoBitrateKbps"),m(this,"constrainOfferToRemoveVideoFec",!1),m(this,"iceCandidateFilter");const r=new RTCPeerConnection(e),n=new RTCPeerConnection(e);this.pc1=r,this.pc2=n,this.iceCandidateFilter=Er.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(e){const r="candidate:",n=e.indexOf(r)+r.length,i=e.substr(n).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(e){return e.type!=="host"}static isHost(e){return e.type==="host"}static isRelay(e){return e.type==="relay"}static isReflexive(e){return e.type==="srflx"}static noFilter(e){return!0}onIceCandidate(e,r){if(r.candidate){const n=Er.parseCandidate(r.candidate.candidate);this.iceCandidateFilter(n)&&e.addIceCandidate(r.candidate)}}setIceCandidateFilter(e){this.iceCandidateFilter=e}constrainVideoBitrate(e){this.constrainVideoBitrateKbps=e}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(e){this.constrainOfferToRemoveVideoFec&&(e.sdp=e.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
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
+ 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 u(this,null,function*(){const[e,r]=yield Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let n,i;if(e.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesSent>0&&(n=s)}),r.forEach(s=>{s.type==="candidate-pair"&&s.nominated===!0&&s.bytesReceived>0&&(i=s)}),n&&i)try{if(n.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:n.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const s=(i.lastPacketReceivedTimestamp-n.lastPacketSentTimestamp)/1e3;return{rtt:s,backendRTT:s}}catch(s){return}})}close(){this.pc1.close(),this.pc2.close()}}class oh extends _t{constructor(e){super(),m(this,"call"),m(this,"timeOut"),this.call=new Er(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 Ny=8,Ly=1/1e3;class xy extends oh{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(Er.isNotHostCandidate),this.senderChannel=this.call.pc1.createDataChannel(null);for(let r=0;r<262144;r+=1)this.samplePacket+="h";this.maxNumberOfPacketsToSend=1,this.bytesToKeepBuffered=1024*this.maxNumberOfPacketsToSend,this.testDurationSeconds=4,this.senderChannel.addEventListener("open",this.sendingStep.bind(this)),this.call.pc2.addEventListener("datachannel",this.onRecieverChannel.bind(this))}sendingStep(){const e=new Date;this.startTime||(this.startTime=e,this.lastBitrateMeasureTime=e);for(let n=0;n!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);n+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(i){}}const r=e.getTime()-this.startTime.getTime();r>=1e3*this.testDurationSeconds?(this.stopSending=!0,this.testProgress=100):(this.testProgress=r/(10*this.testDurationSeconds),setTimeout(this.sendingStep.bind(this),1))}onMessageRecieved(e){this.recievedPayloadBytes+=e.data.length;const r=new Date,n=r.getTime()-this.lastBitrateMeasureTime.getTime();if(n>=1e3){const i=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*Ny/(n/1e3);this.finalBitrateSum+=i,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const i=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(i*Ly)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:n})=>super.testComplete({RTT:r,backendRTT:n,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class Xc extends oh{constructor(e,r=Er.noFilter){super(e),m(this,"ch1"),m(this,"ch2"),this.call.setIceCandidateFilter(r);const n=this.call.pc1.createDataChannel(null);this.ch1=n,n.addEventListener("open",()=>{n.send("hello")}),n.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class Fy extends Xc{constructor(e){super(e,Er.isHost)}}class Uy extends Xc{constructor(e){super(e,Er.isRelay)}}class Vy extends Xc{constructor(e){super(e,Er.isReflexive)}}class By{constructor(){m(this,"ipInformation",null)}getIPDetails(e){return u(this,arguments,function*({peerId:r,apiHostnames:n}){var i;if(!this.ipInformation){try{const o=`https://${n.location}`,a=yield(yield fetch(o)).json();if(((i=a.loc)==null?void 0:i.length)>5)return this.ipInformation=a,a;throw Error("Insufficient data")}catch(o){}const s=yield fetch(`https://${n.locationLegacy}/?token=3c493932b0624c&peerId=${r}`,{method:"POST"});this.ipInformation=yield s.json()}return this.ipInformation})}resetCache(){this.ipInformation=null}}const Zc=new By,ah=[{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 ch(t){const[e,r]=t.split(",");return{coords:{latitude:Number(e),longitude:Number(r)}}}class dh{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 lh extends Mo{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 Mo}registerProducer(e){return u(this,null,function*(){yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalVideoPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&o.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,n){var i,s;const o=((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.get(e))||{};r.totalAudioPacketsReceived===n.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=n.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&o.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalVideoPacketsSent===n.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=n.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&s.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{};r.totalAudioPacketsSent===n.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=n.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&s.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,n){var i;const s=((i=this==null?void 0:this.callStatsInstance)==null?void 0:i.currentUserMediaStates)||{},{audio:o,video:a,screen:d}=s,h=o||a||d;r.totalPacketsSent===n.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=n.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&h&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,n){var i,s;const o=!!Array.from(((s=(i=this==null?void 0:this.callStatsInstance)==null?void 0:i.consumerSharedMediaStatesMap)==null?void 0:s.values())||[]).reduce((a,d)=>a||d.audio||d.video||d.screen,!1);r.totalPacketsReceived===n.packetsSent?(this.freezedConsumingTransportIds.add(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","pause",e))):(r.totalPacketsReceived=n.packetsSent,this.freezedConsumingTransportIds.has(e)&&(this.freezedConsumingTransportIds.delete(e),this.callStatsInstance&&o&&(this.callStatsInstance.logger.debug("callStats::measurements::consumingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("consuming_transport_status","resume",e))))}registerConsumer(e){return u(this,null,function*(){yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}generateProducerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getProducerStatsFromReport(this.parseRTCReport(n,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"outbound-rtp":{this.outboundProducerMap.set(s.id,e.id);break}}return i})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=r?this.getConsumerStatsFromReport(this.parseRTCReport(n,["inbound-rtp"],!1,e.id))[0]:void 0;for(const s of n.values())switch(s.type){case"inbound-rtp":{this.inboundConsumerMap.set(s.id,e.id);break}}return i})}deregisterProducer(e){this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}getWorkingSimulcastVideoStats(e){return e.find(r=>{const n=r.framesEncoded>0,i=r.packetsSent>0,s=r.frameWidth&&r.frameHeight;return n&&i&&!!s})||e[e.length-1]}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new dh,R=r.length?new Set(r):void 0,A=[],L=[],F=[],W=new Map,H=new Map;for(const I of E.values()){if(R){if(R.size===0)break;if(R.has(I.type))n&&R.delete(I.type);else continue}switch(I.type){case"local-candidate":{A.push(this.getIceCandidateStats(I));break}case"remote-candidate":{L.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:S}=I,{selected:P}=I,N=I,ce={nominated:S!=null?S:P,currentRoundTripTime:N.currentRoundTripTime,totalRoundTripTime:N.totalRoundTripTime,bytesReceived:N.bytesReceived,bytesSent:N.bytesSent,availableOutgoingBitrate:N.availableOutgoingBitrate,lastPacketReceivedTimestamp:N.lastPacketReceivedTimestamp,lastPacketSentTimestamp:N.lastPacketSentTimestamp,localCandidateId:N.localCandidateId,remoteCandidateId:N.remoteCandidateId,bytesDiscardedOnSend:N.bytesDiscardedOnSend,packetsSent:N.packetsSent,packetsReceived:N.packetsReceived,packetsDiscardedOnSend:N.packetsDiscardedOnSend};F.push(ce),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ce);break}case"transport":{const S=I;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const N=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,N,P)}if(s.consuming){const N=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,N,P)}}break}case"remote-inbound-rtp":{const S=I,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=I,P=i||this.outboundProducerMap.get(I.id),N=this.pausedProducerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(I.id)){v.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((o=Le==null?void 0:Le.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const x=S,Se=V({frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesEncoded:x.framesEncoded,framesDropped:x.framesDropped,framesPerSecond:x.framesPerSecond,framesSent:x.framesSent,keyFramesEncoded:x.keyFramesEncoded,firCount:x.firCount,encoderImplementation:x.encoderImplementation,hugeFramesSent:x.hugeFramesSent,pliCount:x.pliCount,qpSum:x.qpSum,qualityLimitationDurations:x.qualityLimitationDurations,qualityLimitationReason:x.qualityLimitationReason,qualityLimitationResolutionChanges:x.qualityLimitationResolutionChanges,totalEncodeTime:x.targetBitrate,totalPacketSendDelay:x.totalPacketSendDelay,retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(P,Se),v.outboundVideoRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ce,Se)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,Se=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(P,Se),v.outboundAudioRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ce,Se)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=I,P=i||this.inboundConsumerMap.get(I.id),N=this.pausedConsumerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(I.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,x=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped,framesPerSecond:$.framesPerSecond,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Le);x.score=sh({frameWidth:x.frameWidth||0,framesDecoded:(x.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:x.framesPerSecond||0,packetsLost:(x.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:x.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,x.score),this.videoConsumerToStatsMap.set(P,x),v.inboundVideoRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,ce,x)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,x=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Le);x.score=ih({concealmentEvents:(x.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(x.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:x.jitter||0}),H.set(P,x.score),this.audioConsumerToStatsMap.set(P,x),v.inboundAudioRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,ce,x)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((I,S)=>{var P,N,ce,Le,$,x,Se,fn,pi,mi,ht;if(I.outboundVideoRtpId.length>0){const Qe=[];I.outboundVideoRtpId.forEach(fo=>{Qe.push(v.outboundVideoRtp.get(fo))});const Xe=this.getWorkingSimulcastVideoStats(Qe);Xe.score=rh({frameWidth:Xe.frameWidth||0,framesPerSecond:Xe.framesPerSecond||0,jitter:((P=Xe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Xe.packetsSent||0)-(((N=this.videoProducerToStatsMap.get(S))==null?void 0:N.packetsSent)||0),packetsLost:(((ce=Xe.remoteData)==null?void 0:ce.packetsLost)||0)-((($=(Le=this.videoProducerToStatsMap.get(S))==null?void 0:Le.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Xe.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Xe.score)}else if(I.outboundAudioRtpId.length>0){const Qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);Qe.score=th({packetsSent:(Qe.packetsSent||0)-(((Se=this.audioProducerToStatsMap.get(S))==null?void 0:Se.packetsSent)||0),packetsLost:(((fn=Qe.remoteData)==null?void 0:fn.packetsLost)||0)-(((mi=(pi=this.audioProducerToStatsMap.get(S))==null?void 0:pi.remoteData)==null?void 0:mi.packetsLost)||0),jitter:((ht=Qe.remoteData)==null?void 0:ht.jitter)||0}),W.set(S,Qe.score)}}),F.forEach(I=>{const S=A.find(N=>N.id===I.localCandidateId?(I.localCandidateId=N.id,N):null),P=L.find(N=>N.id===I.remoteCandidateId?(I.remoteCandidateId=N.id,N):null);S&&(I.localCandidateType=S.type,I.localCandidateAddress=S.address,I.localCandidatePort=S.port,I.localCandidateProtocol=S.protocol,I.localCandidateUrl=S.url,I.localCandidateNetworkType=S.networkType,I.localCandidateRelatedAddress=S.relatedAddress,I.localCandidateRelatedPort=S.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=P.address,I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=F),v.transport&&!v.transport.roundTripTime){let I=0,S=0;v.remoteInboundRtp.forEach((P,N)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=I,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateProducerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getConsumersReport(e){return u(this,null,function*(){const r=e.map(n=>this.generateConsumerStreamMap(n,!0));return r.length>0?Promise.all(r):void 0})}getTransportReport(e){return u(this,null,function*(){return e.getStats()})}getProcessedStats(e,r,n){return u(this,null,function*(){const i=yield this.getTransportReport(e),s={producing:n,consuming:r,id:e.id},o=i,a=this.parseRTCReport(o,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,s);if(!a)return;const d={stats:a.transport,transportId:e.id,consuming:r,producing:n},h=a.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(a),p=a.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(a);return{transportReport:d,producerReport:h,consumerReport:p}})}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{var s,o;r.push({producerId:i,videoStats:n.outboundVideoRtpId.map(a=>e.outboundVideoRtp.get(a)),audioStats:n.outboundAudioRtpId.map(a=>e.outboundAudioRtp.get(a)),appData:((o=(s=this.callStatsInstance.producers)==null?void 0:s.get(i))==null?void 0:o.appData)||null})})}catch(n){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:n.reason,message:n.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(i);r.push({consumerId:i,peerId:s,producerId:o,appData:a,videoStats:n.inboundVideoRtpId.map(d=>e.inboundVideoRtp.get(d)),audioStats:n.inboundAudioRtpId.map(d=>e.inboundAudioRtp.get(d))})})}catch(n){console.error("getConsumersReport: ",n,e)}return r}getUserLocation(){return u(this,null,function*(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(n=>{e(n)}):r()}catch(n){r(n)}})})}getConnectivity(e){return u(this,null,function*(){try{const r={iceServers:e||ah},n=new Promise((h,p)=>{try{const f=new Fy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),i=new Promise((h,p)=>{try{const f=new Uy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),s=new Promise((h,p)=>{try{const f=new Vy(r);f.addListener("done",h),f.addListener("failed",()=>{h({connectivity:!1})}),f.start(2e3)}catch(f){p(f)}}),[o,a,d]=yield Promise.all([n,i,s]);return{host:o==null?void 0:o.connectivity,relay:a==null?void 0:a.connectivity,reflexive:d==null?void 0:d.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}})}getThroughput(e){return u(this,null,function*(){try{const r=yield new Promise((n,i)=>{try{const s={iceServers:e||ah},o=new xy(s);o.addListener("done",n),o.addListener("failed",i),o.start(1e4)}catch(s){i(s)}});return{throughput:r.throughput,fractionalLoss:0,RTT:r.RTT,jitter:0,backendRTT:r.backendRTT}}catch(r){return}})}getIPDetails(){return u(this,null,function*(){var e,r;try{return this.ipDetails||(this.ipDetails=yield Zc.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames})),this.ipDetails}catch(n){return}})}getNetworkQuality(e){return u(this,null,function*(){const[r,n]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}})}getNetworkInfo(e,r=!1){return u(this,null,function*(){var n,i;if(r){const d=yield this.getIPDetails();return{ipDetails:d,effectiveNetworkType:(n=navigator.connection)==null?void 0:n.effectiveType,location:d.loc?ch(d.loc):void 0}}const[s,o,a]=yield Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:a,effectiveNetworkType:(i=navigator.connection)==null?void 0:i.effectiveType,location:a.loc?ch(a.loc):void 0,turnConnectivity:s?s.host||s.relay||s.reflexive:!1,connectivity:s,throughput:o==null?void 0:o.throughput,fractionalLoss:o==null?void 0:o.fractionalLoss,RTT:o==null?void 0:o.RTT,jitter:o==null?void 0:o.jitter,backendRTT:o==null?void 0:o.backendRTT}})}}class jy extends lh{}class uh extends lh{constructor(){super(...arguments),m(this,"producerMap",new Map),m(this,"consumerMap",new Map)}registerProducer(e){return u(this,null,function*(){this.producerMap.set(e.id,e),yield this.generateProducerStreamMap(e),e.observer.on("close",this.deregisterProducer.bind(this,e)),e.observer.on("pause",this.pauseProducer.bind(this,e.id)),e.observer.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)})}registerConsumer(e){return u(this,null,function*(){this.consumerMap.set(e.id,e),yield this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.observer.on("close",this.deregisterConsumer.bind(this,e)),e.observer.on("pause",this.pauseConsumer.bind(this,e.id)),e.observer.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)})}generateConsumerStreamMap(e,r=!1){return u(this,null,function*(){const n=yield e.getStats(),i=this.parseRTCReport(n,["inbound-rtp"],!1,e.id),s=[...i.consumerStreamMap.values()][0],o=r?this.getConsumerStatsFromParsedConsumerStats(i,s,e.id):void 0;for(const a of n.values())switch(a.type){case"inbound-rtp":{this.inboundConsumerMap.set(a.id,e.id);break}}return o})}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,n)=>{r===e.id&&this.outboundProducerMap.delete(n)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,n)=>{r===e.id&&this.inboundConsumerMap.delete(n)}),this.consumerPeerIdMap.delete(e.id),this.pausedConsumerMap.delete(e.id),this.screenShareConsumers.delete(e.id)}getIceCandidateStats(e){var r;return{id:e.id,type:e.candidateType||e.type,address:e.address,port:e.port,url:e.url,protocol:(r=e.relayProtocol)!=null?r:e.protocol,networkType:e.networkType,relatedAddress:e.relatedAddress,relatedPort:e.relatedPort}}parseRTCReport(e,r=[],n=!1,i=void 0,s=void 0){var o,a,d,h,p,f,g;const E=e,v=new dh,R=r.length?new Set(r):void 0,A=[],L=[],F=[],W=new Map,H=new Map;for(const I of E.values()){if(R){if(R.size===0)break;if(R.has(I.type))n&&R.delete(I.type);else continue}switch(I.type){case"local-candidate":{A.push(this.getIceCandidateStats(I));break}case"remote-candidate":{L.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:S}=I,{selected:P}=I,N=I,ce={nominated:S!=null?S:P,currentRoundTripTime:N.currentRoundTripTime,totalRoundTripTime:N.totalRoundTripTime,bytesReceived:N.bytesReceived,bytesSent:N.bytesSent,availableOutgoingBitrate:N.availableOutgoingBitrate,lastPacketReceivedTimestamp:N.lastPacketReceivedTimestamp,lastPacketSentTimestamp:N.lastPacketSentTimestamp,localCandidateId:N.localCandidateId,remoteCandidateId:N.remoteCandidateId,bytesDiscardedOnSend:N.bytesDiscardedOnSend,packetsSent:N.packetsSent,packetsReceived:N.packetsReceived,packetsDiscardedOnSend:N.packetsDiscardedOnSend};F.push(ce),(I.nominated===!0||I.selected===!0)&&(v.candidatePair=ce);break}case"transport":{const S=I;s&&(s.producing&&(this.overallProducingTransportsStatsMap[s.id]||(this.overallProducingTransportsStatsMap[s.id]={totalPacketsSent:0})),s.consuming&&(this.overallConsumingTransportsStatsMap[s.id]||(this.overallConsumingTransportsStatsMap[s.id]={totalPacketsReceived:0})));const P={bytesReceived:S.bytesReceived,bytesSent:S.bytesSent,packetsSent:S.packetsSent,packetsReceived:S.packetsReceived,dtlsCipher:S.dtlsCipher,dtlsState:S.dtlsState,iceRole:S.iceRole};if(v.transport=P,s){if(s.producing){const N=this.overallProducingTransportsStatsMap[s.id];this.processProducingTransportStats(s.id,N,P)}if(s.consuming){const N=this.overallConsumingTransportsStatsMap[s.id];this.processConsumingTransportStats(s.id,N,P)}}break}case"remote-inbound-rtp":{const S=I,P={jitter:S.jitter,fractionLost:S.fractionLost,roundTripTime:S.roundTripTime,roundTripTimeMeasurements:S.roundTripTimeMeasurements,totalRoundTripTime:S.totalRoundTripTime,packetsLost:S.packetsLost};v.remoteInboundRtp.set(S.localId,P);break}case"outbound-rtp":{const S=I,P=i||this.outboundProducerMap.get(I.id),N=this.pausedProducerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const ce=this.overallProducersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.outboundProducerMap.has(I.id)){v.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((o=Le==null?void 0:Le.track)==null?void 0:o.readyState)==="ended")break;v.producerStreamMap.has(P)||v.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const $={bytesSent:S.bytesSent,packetsSent:S.packetsSent,nackCount:S.nackCount,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const x=S,Se=V({frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesEncoded:x.framesEncoded,framesDropped:x.framesDropped?x.framesDropped:x.droppedFrames,framesPerSecond:x.framesPerSecond?x.framesPerSecond:x.framerateMean,framesSent:x.framesSent,keyFramesEncoded:x.keyFramesEncoded,firCount:x.firCount,encoderImplementation:x.encoderImplementation,hugeFramesSent:x.hugeFramesSent,pliCount:x.pliCount,qpSum:x.qpSum,qualityLimitationReason:x.qualityLimitationReason,qualityLimitationDurations:x.qualityLimitationDurations,qualityLimitationResolutionChanges:x.qualityLimitationResolutionChanges,totalEncodeTime:x.totalEncodeTime,totalPacketSendDelay:x.totalEncodeTime,retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.videoProducerToStatsMap.set(I.id,Se),v.outboundVideoRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,ce,Se)}else if(S.mediaType==="audio"||S.kind==="audio"){const x=S,Se=V({retransmittedBytesSent:x.retransmittedBytesSent,retransmittedPacketsSent:x.retransmittedPacketsSent},$);this.audioProducerToStatsMap.set(I.id,Se),v.outboundAudioRtp.set(I.id,Se),v.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,ce,Se)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}case"inbound-rtp":{const S=I,P=i||this.inboundConsumerMap.get(I.id),N=this.pausedConsumerMap.get(P);if(N){if(N.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(S.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const ce=this.overallConsumersStatsMap[P];if(["video","audio"].includes(S.mediaType)||["video","audio"].includes(S.kind)){if(!this.inboundConsumerMap.has(I.id)){v.staleConsumerStreamMap=!0;break}v.consumerStreamMap.has(P)||v.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:S.bytesReceived,packetsReceived:S.packetsReceived,packetsLost:S.packetsLost,jitter:S.jitter,nackCount:S.nackCount,jitterBufferDelay:S.jitterBufferDelay,jitterBufferEmittedCount:S.jitterBufferEmittedCount,lastPacketReceivedTimestamp:S.lastPacketReceivedTimestamp,ssrc:S.ssrc,mid:S.mid};if(S.mediaType==="video"||S.kind==="video"){if(S.decoderImplementation==="unknown")break;const $=S,x=V({frameHeight:$.frameHeight,frameWidth:$.frameWidth,framesDecoded:$.framesDecoded,framesDropped:$.framesDropped?$.framesDropped:$.droppedFrames,framesPerSecond:$.framesPerSecond?$.framesPerSecond:$.framerateMean,framesReceived:$.framesReceived,keyFramesDecoded:$.keyFramesDecoded,firCount:$.firCount,decoderImplementation:$.decoderImplementation,pliCount:$.pliCount,totalProcessingDelay:$.totalProcessingDelay},Le);x.score=sh({frameWidth:x.frameWidth||0,framesDecoded:(x.framesDecoded||0)-(((a=this.videoConsumerToStatsMap.get(P))==null?void 0:a.framesDecoded)||0),framesPerSecond:x.framesPerSecond||0,packetsLost:(x.packetsLost||0)-(((d=this.videoConsumerToStatsMap.get(P))==null?void 0:d.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((h=this.videoConsumerToStatsMap.get(P))==null?void 0:h.packetsReceived)||0),jitter:x.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),H.set(P,x.score),this.videoConsumerToStatsMap.set(P,x),v.inboundVideoRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,ce,x)}else if(S.mediaType==="audio"||S.kind==="audio"){const $=S,x=V({audioLevel:$.audioLevel,concealedSampels:$.concealedSampels,concealmentEvents:$.concealmentEvents,totalAudioEnergy:$.totalAudioEnergy,totalSamplesDuration:$.totalSamplesDuration,totalSamplesReceived:$.totalSamplesReceived},Le);x.score=ih({concealmentEvents:(x.concealmentEvents||0)-(((p=this.audioConsumerToStatsMap.get(P))==null?void 0:p.concealmentEvents)||0),packetsLost:(x.packetsLost||0)-(((f=this.audioConsumerToStatsMap.get(P))==null?void 0:f.packetsLost)||0),packetsReceived:(x.packetsReceived||0)-(((g=this.audioConsumerToStatsMap.get(P))==null?void 0:g.packetsReceived)||0),jitter:x.jitter||0}),H.set(P,x.score),this.audioConsumerToStatsMap.set(P,x),v.inboundAudioRtp.set(I.id,x),v.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,ce,x)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${S.mediaType} kind: ${S.kind}`);break}}}if(v.producerStreamMap.forEach((I,S)=>{var P,N,ce,Le,$,x,Se,fn,pi,mi,ht;if(I.outboundVideoRtpId.length>0){const Qe=[];I.outboundVideoRtpId.forEach(fo=>{Qe.push(v.outboundVideoRtp.get(fo))});const Xe=this.getWorkingSimulcastVideoStats(Qe);Xe.score=rh({frameWidth:Xe.frameWidth||0,framesPerSecond:Xe.framesPerSecond||0,jitter:((P=Xe.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(S),packetsSent:(Xe.packetsSent||0)-(((N=this.videoProducerToStatsMap.get(S))==null?void 0:N.packetsSent)||0),packetsLost:(((ce=Xe.remoteData)==null?void 0:ce.packetsLost)||0)-((($=(Le=this.videoProducerToStatsMap.get(S))==null?void 0:Le.remoteData)==null?void 0:$.packetsLost)||0),framesEncoded:(Xe.framesEncoded||0)-(((x=this.videoProducerToStatsMap.get(S))==null?void 0:x.framesEncoded)||0)}),W.set(S,Xe.score)}else if(I.outboundAudioRtpId.length>0){const Qe=v.outboundAudioRtp.get(I.outboundAudioRtpId[0]);Qe.score=th({packetsSent:(Qe.packetsSent||0)-(((Se=this.audioProducerToStatsMap.get(S))==null?void 0:Se.packetsSent)||0),packetsLost:(((fn=Qe.remoteData)==null?void 0:fn.packetsLost)||0)-(((mi=(pi=this.audioProducerToStatsMap.get(S))==null?void 0:pi.remoteData)==null?void 0:mi.packetsLost)||0),jitter:((ht=Qe.remoteData)==null?void 0:ht.jitter)||0}),W.set(S,Qe.score)}}),F.forEach(I=>{const S=A.find(N=>N.id===I.localCandidateId?(I.localCandidateId=N.id,N):null),P=L.find(N=>N.id===I.remoteCandidateId?(I.remoteCandidateId=N.id,N):null);S&&(I.localCandidateType=S.type,I.localCandidateAddress=S.address,I.localCandidatePort=S.port,I.localCandidateProtocol=S.protocol,I.localCandidateUrl=S.url,I.localCandidateNetworkType=S.networkType,I.localCandidateRelatedAddress=S.relatedAddress,I.localCandidateRelatedPort=S.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=P.address,I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.remoteCandidateUrl=P.url)}),v.candidatePair&&(v.transport?(v.transport.bytesReceived=v.candidatePair.bytesReceived,v.transport.bytesSent=v.candidatePair.bytesSent,v.transport.totalRoundTripTime=v.candidatePair.totalRoundTripTime,v.transport.availableOutgoingBitrate=v.candidatePair.availableOutgoingBitrate,v.transport.roundTripTime=v.candidatePair.currentRoundTripTime):v.transport={bytesReceived:v.candidatePair.bytesReceived,bytesSent:v.candidatePair.bytesSent,totalRoundTripTime:v.candidatePair.totalRoundTripTime,availableOutgoingBitrate:v.candidatePair.availableOutgoingBitrate,roundTripTime:v.candidatePair.currentRoundTripTime}),v.transport&&(v.transport.candidatePairs=F),v.transport&&!v.transport.roundTripTime){let I=0,S=0;v.remoteInboundRtp.forEach((P,N)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,S=P.totalRoundTripTime)}),v.transport.roundTripTime=I,v.transport.totalRoundTripTime=S}return H.size>0&&this.observer.safeEmit("consumer_score",H),W.size>0&&this.observer.safeEmit("producer_score",W),v}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((n,i)=>{const s=this.producerMap.get(i),o=s.track.getSettings(),a=n.outboundVideoRtpId.map(h=>{const p=e.outboundVideoRtp.get(h);return p.frameHeight||(p.frameHeight=o.height,p.frameWidth=o.width,p.framesPerSecond=o.frameRate),p}),d={producerId:i,appData:s.appData,videoStats:a,audioStats:n.outboundAudioRtpId.map(h=>e.outboundAudioRtp.get(h))};r.push(d)})}catch(n){console.error("getProducersReport: ",n,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,n){let i;try{const{peerId:s,producerId:o,appData:a}=this.consumerPeerIdMap.get(n),d=r==null?void 0:r.inboundVideoRtpId.map(h=>{const p=this.consumerMap.get(n).track.getSettings(),f=e.inboundVideoRtp.get(h);return f.frameHeight||(f.frameHeight=p.height,f.frameWidth=p.width,f.framesPerSecond=p.frameRate),f});i={consumerId:n,peerId:s,producerId:o,appData:a,videoStats:d,audioStats:r==null?void 0:r.inboundAudioRtpId.map(h=>e.inboundAudioRtp.get(h))}}catch(s){console.error("getConsumerStatsFromParsedConsumerStats: ",s,e)}return i}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((n,i)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,n,i))})}catch(n){console.error("getConsumerStatsFromReport: ",n,e)}return r}}class Hy extends uh{}function Lo(t,e,r,n){if(t!=null&&t.logger&&t.logger.error("Callstats::handleError",{error:n}),typeof r=="function"&&n instanceof e)r.call(null,n,t);else throw n}function hh(t,e,r){const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{Lo(this,e,r,o)}):s}catch(s){Lo(this,e,r,s)}return null},t}const te=(t,e)=>(r,n,i)=>{const s=i.value;return i.value=function(...o){try{const a=s.apply(this,o);return a&&a instanceof Promise?a.catch(d=>{Lo(this,t,e,d)}):a}catch(a){Lo(this,t,e,a)}return null},i},Wy=(t,e)=>(r,n,i)=>{if(i)return hh(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);o.value instanceof Function&&Object.defineProperty(r.prototype,s,hh(o,t,e))}};var Z=globalThis&&globalThis.__decorate||function(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s};const ee=console;let Y=class extends Mo{constructor(t="https://api.testingv3.dyte.in",e="Blink",r=ls.PROD,n,i,s,o){switch(super(),m(this,"observer"),m(this,"eventHandler"),m(this,"measurements"),m(this,"producingTransport"),m(this,"consumingTransport"),m(this,"producers",new Map),m(this,"consumers",new Map),m(this,"iceServers"),m(this,"connectionInfoPromise"),m(this,"pingStatsTimeout"),m(this,"logger"),m(this,"env"),m(this,"apiHostnames"),m(this,"peerId"),m(this,"consumerSharedMediaStatesMap",new Map),m(this,"currentUserMediaStates",{}),this.env=r,this.apiHostnames=o,this.logger=i,this.peerId=s,this.eventHandler=new Iy({logger:i,peerId:s,apiHostnames:o}),this.logger.debug("callStats::engineName: ",{engineName:e}),e){case"Blink":this.measurements=new jy;break;case"Gecko":this.measurements=new uh;break;case"WebKit":this.measurements=new Hy;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 Mo,this.measurements.observer.on("consumer_score",a=>{i.debug(`callStats::consumer_score ${[...a.entries()]}`),this.eventHandler.emit("consumer_score",a)}),this.measurements.observer.on("producer_score",a=>{i.debug(`callStats::producer_score ${[...a.entries()]}`),this.eventHandler.emit("producer_score",a)})}registerIceServers(t){this.iceServers=t}registerConsumer(t){var e;this.consumerSharedMediaStatesMap.has(t.id)||this.consumerSharedMediaStatesMap.set(t.id,{}),this.consumers.set(t.id,t),this.measurements.registerConsumer(t),this.logger.debug("callStats::registerConsumer",{consumerId:t.id,consumerkind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterConsumer.bind(this,t))}registerProducer(t){var e;this.producers.set(t.id,t),this.measurements.registerProducer(t),this.logger.debug("callStats::registerProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)}),t.observer.on("close",this.deRegisterProducer.bind(this,t))}sendConsumerSharedMediaStateEvent(t,e){this.consumerSharedMediaStatesMap.has(t)||this.consumerSharedMediaStatesMap.set(t,{});const r=this.consumerSharedMediaStatesMap.get(t);this.consumerSharedMediaStatesMap.set(t,Object.assign(r,e))}registerProducingTransport(t){var e;this.producingTransport=t,t.observer.on("close",this.disconnectProducingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectProducingTransport.bind(this,t)),Array.from(((e=t._producers)==null?void 0:e.values())||[]).forEach(r=>{this.registerProducer(r)}),t.observer.on("newproducer",this.registerProducer)}registerConsumingTransport(t){var e;this.consumingTransport=t,t.observer.on("close",this.disconnectConsumingTransport.bind(this,t)),t.observer.on("disconnect",this.disconnectConsumingTransport.bind(this,t)),Array.from(((e=t._consumers)==null?void 0:e.values())||[]).forEach(r=>{this.registerConsumer(r)}),t.observer.on("newconsumer",this.registerConsumer)}deRegisterConsumer(t){this.consumers.delete(t.id)}deRegisterProducer(t){var e;this.producers.delete(t.id),this.logger.debug("callStats::deRegisterProducer",{producerId:t.id,producerKind:t.kind,isScreenShare:!!((e=t.appData)!=null&&e.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(t){this.eventHandler.callEvent(t)}sendPreCallTestBeginEvent(t=!1){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,t),this.eventHandler.callEvent({event:U.PRECALL_TEST_BEGIN,timestamp:new Date}),this.connectionInfoPromise&&this.connectionInfoPromise.then(e=>{this.eventHandler.callEvent({event:U.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:e},timestamp:new Date})})}sendScreenShareToggleEvent(t,e){this.currentUserMediaStates.screen=t,this.eventHandler.callEvent({event:t?U.SCREENSHARE_STARTED:U.SCREENSHARE_STOPPED,metaData:{ssrc:e},timestamp:new Date})}sendScreenShareRequestedEvent(){this.eventHandler.callEvent({event:U.SCREENSHARE_START_REQUESTED,timestamp:new Date})}sendActiveSpeakerEvent(t){this.eventHandler.callEvent({event:U.DOMINANT_SPEAKER,metaData:{peerId:t},timestamp:new Date})}devices(t,e){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_DEVICES_UPDATES||t===Vt.VIDEO&&U.VIDEO_DEVICES_UPDATES||t===Vt.SPEAKER&&U.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:e},timestamp:new Date})}selectedDevice(t,e){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.SELECTED_MICROHPONE_UPDATE||t===Vt.VIDEO&&U.SELECTED_CAMERA_UPDATE||t===Vt.SPEAKER&&U.SELECTED_SPEAKER_UPDATE,metaData:{device:e},timestamp:new Date})}mediaPermission(t,e){this.eventHandler.callEvent({event:U.MEDIA_PERMISSION,metaData:{deviceType:t,permission:e},timestamp:new Date})}mediaPlaybackFailed(t){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_PLAY_FAILED||t===Vt.VIDEO&&U.VIDEO_PLAY_FAILED,metaData:{deviceType:t},timestamp:new Date})}mediaTrackMuted(t){this.eventHandler.callEvent({event:t===Vt.AUDIO&&U.AUDIO_TRACK_MUTED||t===Vt.VIDEO&&U.VIDEO_TRACK_MUTED,metaData:{deviceType:t},timestamp:new Date})}tabChanged(t){this.eventHandler.callEvent({event:U.TAB_CHANGE,metaData:{isMeetingsTabActive:t},timestamp:new Date})}browserBackgrounded(){this.eventHandler.callEvent({event:U.BROWSER_BACKGROUNDED,timestamp:new Date})}browserForegrounded(){this.eventHandler.callEvent({event:U.BROWSER_FOREGROUNDED,timestamp:new Date})}legacySwitch(t){this.eventHandler.callEvent({event:U.LEGACY_SWITCH,metadata:{on:t},timestamp:new Date})}getPreCallTestResults(){return u(this,null,function*(){return this.connectionInfoPromise})}sendCallJoinBeginEvent(t){t=ne(V({},t),{meetingEnv:this.env}),t.deviceInfo=ne(V({},t.deviceInfo),{userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory}),this.eventHandler.callEvent({event:U.CALL_JOIN_BEGIN,metaData:{peerMetaData:t},timestamp:new Date})}sendNetworkQualityTestBeginEvent(t){this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_BEGIN,timestamp:new Date}),new Promise((e,r)=>u(this,null,function*(){const n=[];try{for(const i of t)try{if(i.iceServers&&i.iceServers.length>0){const s=yield this.measurements.getNetworkQuality(i.iceServers);n.push(ne(V({},i),{networkResults:s}))}}catch(s){console.warn("Error handling ",s)}e({regionData:n})}catch(i){console.warn("Error in callstats, ",i),r(i)}})).then(e=>{this.eventHandler.callEvent({event:U.NET_QUALITY_TEST_END,timestamp:new Date,metaData:e})})}sendWebSocketConnectedEvent(){this.eventHandler.callEvent({event:U.WEBSOCKET_CONNECTED,timestamp:new Date})}sendTransportConnectedEvent(){this.eventHandler.callEvent({event:U.TRANSPORT_CONNECTED,timestamp:new Date})}sendAudioToggleEvent(t){this.currentUserMediaStates.audio=t;let e;t?e=U.AUDIO_ON:e=U.AUDIO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendVideoToggleEvent(t){this.currentUserMediaStates.video=t;let e;t?e=U.VIDEO_ON:e=U.VIDEO_OFF,this.eventHandler.callEvent({event:e,timestamp:new Date})}sendParticipantRoleToggleEvent(t){this.eventHandler.callEvent({event:U.PARTICIPANT_ROLE,timestamp:new Date,metaData:t})}startPingStats(t=7e3){this.sendPingStatsEvent(!1),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),t)}stopPingStats(){clearInterval(this.pingStatsTimeout)}sendPingStatsEvent(t=!0){return u(this,null,function*(){let e,r;if(this.producingTransport&&(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),!e||!(e!=null&&e.producerReport))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const i=yield this.measurements.getProducersReport([...this.producers.values()]);e&&i?e.producerReport=i:(e=yield this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!e||!(e!=null&&e.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!r||!r.consumerReport)){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const i=yield this.measurements.getConsumersReport([...this.consumers.values()]);r&&i?r.consumerReport=i:(r=yield this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!r||!r.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const n={producingTransportStats:e?e==null?void 0:e.transportReport:void 0,consumingTransportStats:r?r==null?void 0:r.transportReport:void 0,producerStats:[].concat((e==null?void 0:e.producerReport)||[]).concat((r==null?void 0:r.producerReport)||[]),consumerStats:[].concat((r==null?void 0:r.consumerReport)||[]).concat((e==null?void 0:e.consumerReport)||[])};if(t&&n.producerStats.length===0&&n.consumerStats.length===0){yield this.eventHandler.flush();return}this.eventHandler.callEvent({event:U.PING_STAT,metaData:n,timestamp:new Date})})}sendIVSPlayerRebufferEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_REBUFFERING,timestamp:new Date})}sendIVSPlayerAudioBlockEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_AUDIO_BLOCKED,timestamp:new Date})}sendIVSPlayerPlaybackBlockedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:new Date})}sendIVSPlayerNetworkUnavailableEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:new Date})}sendIVSPlayerInitializedEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_INITIALIZED,timestamp:new Date})}sendIVSPlayerWorkerErrorEvent(){this.eventHandler.callEvent({event:U.IVS_PLAYER_WORKER_ERROR,timestamp:new Date})}sendIVSPlayerErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerRecoverableErrorEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:new Date,metaData:t})}sendIVSPlayerAnalyticsEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_ANALYTICS_EVENT,timestamp:new Date,metaData:t})}sendIVSPlayerPlaybackRateChangedEvent(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:new Date,metaData:{updatedPlaybackRate:t}})}sendIVSPlayerQualityChanged(t){this.eventHandler.callEvent({event:U.IVS_PLAYER_QUALITY_CHANGED,timestamp:new Date,metaData:t})}sendPlayerLiveLatency(t){this.eventHandler.callEvent({event:U.LIVESTREAM_LATENCY,timestamp:new Date,metaData:{latency:t}})}sendDisconnectEvent(){this.eventHandler.callEvent({event:U.DISCONNECT,timestamp:new Date})}sendReconnectEvent(){this.eventHandler.callEvent({event:U.RECONNECT_ATTEMPT,timestamp:new Date})}};Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerIceServers",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerConsumer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerProducer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendConsumerSharedMediaStateEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerProducingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"registerConsumingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"deRegisterConsumer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"deRegisterProducer",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"disconnectConsumingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"disconnectProducingTransport",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPreCallTestBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendScreenShareToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendScreenShareRequestedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendActiveSpeakerEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"devices",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"selectedDevice",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaPermission",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaPlaybackFailed",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"mediaTrackMuted",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"tabChanged",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"browserBackgrounded",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"browserForegrounded",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"legacySwitch",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"getPreCallTestResults",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendCallJoinBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendNetworkQualityTestBeginEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendWebSocketConnectedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendTransportConnectedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendAudioToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendVideoToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendParticipantRoleToggleEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"startPingStats",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"stopPingStats",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPingStatsEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerRebufferEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerAudioBlockEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerInitializedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerWorkerErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerRecoverableErrorEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerAnalyticsEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendIVSPlayerQualityChanged",null),Z([te(TypeError,(t,e)=>ee.error(e,t))],Y.prototype,"sendPlayerLiveLatency",null),Y=Z([Wy(TypeError,(t,e)=>ee.error(e,t))],Y);const $y=Y;class Gy extends _t{constructor(){super(...arguments),m(this,"stats"),m(this,"roomURL"),m(this,"peerId"),m(this,"backend"),m(this,"iceServers"),m(this,"initialized",!1),m(this,"stalled",!1),m(this,"ipInformation"),m(this,"logger")}initialize(e){return u(this,arguments,function*({peerId:r,engineName:n,env:i=ls.PROD,iceServers:s,apiBase:o="https://api.cluster.dyte.in",flags:a,logger:d=console,apiHostnames:h,skipConnectivityChecks:p=!1}){var f,g,E;try{this.peerId=r,this.logger=d,this.ipInformation=yield Zc.getIPDetails({peerId:r,apiHostnames:h}),this.backend=new $y(o,n,i,a,d,r,h),this.iceServers=s,(f=this.backend)==null||f.registerIceServers(this.iceServers),this.initialized=!0,(E=(g=this.backend)==null?void 0:g.eventHandler)==null||E.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(p)}catch(v){this.logger.error("callStats::CallStatsIntegration: ",{error:v}),this.stallCallStats()}})}setRoomName(e){this.roomURL=e}configureSendTransport(e){var r;(r=this.backend)==null||r.registerProducingTransport(e)}configureRecvTransport(e){var r;(r=this.backend)==null||r.registerConsumingTransport(e)}candidateRegionalNetworkQualityTest(e){return u(this,null,function*(){var r;try{(r=this.backend)==null||r.sendNetworkQualityTestBeginEvent(e)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}roomJoined(e){return u(this,null,function*(){var r,n;(r=this.backend)==null||r.sendCallJoinBeginEvent(e),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!1)}audioOn(){var e;(e=this.backend)==null||e.sendAudioToggleEvent(!0)}videoOff(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!1)}videoOn(){var e;(e=this.backend)==null||e.sendVideoToggleEvent(!0)}callEnded(){var e,r;(e=this.backend)==null||e.stopPingStats(),(r=this.backend)==null||r.sendDisconnectEvent()}screenShareStart(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!0,e)}consumerSharedMediaState(e,r){var n;(n=this.backend)==null||n.sendConsumerSharedMediaStateEvent(e,r)}screenShareStop(e){var r;(r=this.backend)==null||r.sendScreenShareToggleEvent(!1,e)}screenShareRequested(){var e;(e=this.backend)==null||e.sendScreenShareRequestedEvent()}activeSpeaker(e){var r;e===this.peerId&&((r=this.backend)==null||r.sendActiveSpeakerEvent(e))}devices(e,r){var n;(n=this.backend)==null||n.devices(e,r)}selectedDevice(e,r){var n;(n=this.backend)==null||n.selectedDevice(e,r)}mediaPermission(e,r){var n;(n=this.backend)==null||n.mediaPermission(e,r)}mediaPlaybackFailed(e){var r;(r=this.backend)==null||r.mediaPlaybackFailed(e)}mediaTrackMuted(e){var r;(r=this.backend)==null||r.mediaTrackMuted(e)}tabChanged(e=!1){var r;(r=this.backend)==null||r.tabChanged(e)}browserBackgrounded(){var e;(e=this.backend)==null||e.browserBackgrounded()}browserForegrounded(){var e;(e=this.backend)==null||e.browserForegrounded()}legacySwitch(e){var r;(r=this.backend)==null||r.legacySwitch(e)}startPreCallTest(e=!1){return u(this,null,function*(){var r;(r=this.backend)==null||r.sendPreCallTestBeginEvent(e)})}onPreCallTestResults(e){var r;return(r=this.backend)==null||r.eventHandler.once("precall_end",e),e}onReceivingConsumerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)}onReceivingConsumerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)}onReceivingProducerAudioStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)}onReceivingProducerVideoStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)}onReceivingProducingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)}onReceivingConsumingTransportStatus(e){var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)}onProducerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)}onConsumerScore(e){var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=n=>{e(n,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){var n,i,s,o,a,d,h,p,f,g,E;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent();break;case"PlayerAudioBlocked":(i=this.backend)==null||i.sendIVSPlayerAudioBlockEvent();break;case"PlayerPlaybackBlocked":(s=this.backend)==null||s.sendIVSPlayerPlaybackBlockedEvent();break;case"PlayerNetworkUnavailable":(o=this.backend)==null||o.sendIVSPlayerNetworkUnavailableEvent();break;case"PlayerInitialized":(a=this.backend)==null||a.sendIVSPlayerInitializedEvent();break;case"PlayerWorkerError":(d=this.backend)==null||d.sendIVSPlayerWorkerErrorEvent();break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r);break;case"PlayerRecoverableError":(p=this.backend)==null||p.sendIVSPlayerRecoverableErrorEvent(r);break;case"PlayerAnalyticsEvent":(f=this.backend)==null||f.sendIVSPlayerAnalyticsEvent(r);break;case"PlayerPlaybackRateChanged":(g=this.backend)==null||g.sendIVSPlayerPlaybackRateChangedEvent(r);break;case"PlayerQualityChanged":(E=this.backend)==null||E.sendIVSPlayerQualityChanged(r);break}}livestreamLatency(e){var r;(r=this.backend)==null||r.sendPlayerLiveLatency(e)}}const B=new Gy;B.setMaxListeners(30);function Jy(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}Array.prototype.at||Object.assign(Array.prototype,{at:Jy});function qy(t){const{length:e}=this,r=t>=0?t:e+t;return r<0||r>=e?void 0:this[r]}String.prototype.at||Object.assign(String.prototype,{at:qy});var We;(function(t){t.GroupCall="GROUP_CALL",t.Webinar="WEBINAR",t.AudioRoom="AUDIO_ROOM",t.Livestream="LIVESTREAM",t.Chat="CHAT"})(We||(We={}));var xo;(function(t){t.Skip="SKIP",t.OnPrivilegedUserEntry="ON_PRIVILEGED_USER_ENTRY",t.SkipOnAccept="SKIP_ON_ACCEPT"})(xo||(xo={}));var q;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED",t.CanRequest="CAN_REQUEST"})(q||(q={}));var Fo;(function(t){t.Allowed="ALLOWED",t.NotAllowed="NOT_ALLOWED"})(Fo||(Fo={}));var ph;(function(t){t.FULL_ACCESS="FULL_ACCESS",t.VIEW_ONLY="VIEW_ONLY"})(ph||(ph={}));var Uo;(function(t){t.skip="SKIP",t.onAccept="ON_ACCEPT",t.skipOnPrivilegedUserEntry="SKIP_ON_PRIVILEGED_USER_ENTRY",t.skipOnAccept="SKIP_ON_ACCEPT"})(Uo||(Uo={}));var vi;(function(t){t.none="NONE",t.recorder="RECORDER",t.livestreamer="LIVESTREAMER"})(vi||(vi={}));var ed;(function(t){t.groupCall="GROUP_CALL",t.webinar="WEBINAR",t.audioRoom="AUDIO_ROOM",t.livestream="LIVESTREAM",t.chat="CHAT"})(ed||(ed={}));var mh;(function(t){t.SKIP="skip",t.SKIP_ON_PRIVILEGED_USER_ENTRY="skipOnPrivilegedUserEntry",t.ON_ACCEPT="skipOnAccept",t.SKIP_ON_ACCEPT="skipOnAccept"})(mh||(mh={})),ed.groupCall,Uo.skipOnAccept,vi.none;var td={},Ky={get exports(){return td},set exports(t){td=t}},Vo={},zy={get exports(){return Vo},set exports(t){Vo=t}},fh=function(t,e){return function(){for(var r=new Array(arguments.length),n=0;n<r.length;n++)r[n]=arguments[n];return t.apply(e,r)}},Yy=fh,Vr=Object.prototype.toString;function rd(t){return Array.isArray(t)}function nd(t){return typeof t=="undefined"}function Qy(t){return t!==null&&!nd(t)&&t.constructor!==null&&!nd(t.constructor)&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t)}function gh(t){return Vr.call(t)==="[object ArrayBuffer]"}function Xy(t){return Vr.call(t)==="[object FormData]"}function Zy(t){var e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&gh(t.buffer),e}function eE(t){return typeof t=="string"}function tE(t){return typeof t=="number"}function vh(t){return t!==null&&typeof t=="object"}function Bo(t){if(Vr.call(t)!=="[object Object]")return!1;var e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}function rE(t){return Vr.call(t)==="[object Date]"}function nE(t){return Vr.call(t)==="[object File]"}function iE(t){return Vr.call(t)==="[object Blob]"}function yh(t){return Vr.call(t)==="[object Function]"}function sE(t){return vh(t)&&yh(t.pipe)}function oE(t){return Vr.call(t)==="[object URLSearchParams]"}function aE(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function cE(){return typeof navigator!="undefined"&&(navigator.product==="ReactNative"||navigator.product==="NativeScript"||navigator.product==="NS")?!1:typeof window!="undefined"&&typeof document!="undefined"}function id(t,e){if(!(t===null||typeof t=="undefined"))if(typeof t!="object"&&(t=[t]),rd(t))for(var r=0,n=t.length;r<n;r++)e.call(null,t[r],r,t);else for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.call(null,t[i],i,t)}function sd(){var t={};function e(i,s){Bo(t[s])&&Bo(i)?t[s]=sd(t[s],i):Bo(i)?t[s]=sd({},i):rd(i)?t[s]=i.slice():t[s]=i}for(var r=0,n=arguments.length;r<n;r++)id(arguments[r],e);return t}function dE(t,e,r){return id(e,function(n,i){r&&typeof n=="function"?t[i]=Yy(n,r):t[i]=n}),t}function lE(t){return t.charCodeAt(0)===65279&&(t=t.slice(1)),t}var bt={isArray:rd,isArrayBuffer:gh,isBuffer:Qy,isFormData:Xy,isArrayBufferView:Zy,isString:eE,isNumber:tE,isObject:vh,isPlainObject:Bo,isUndefined:nd,isDate:rE,isFile:nE,isBlob:iE,isFunction:yh,isStream:sE,isURLSearchParams:oE,isStandardBrowserEnv:cE,forEach:id,merge:sd,extend:dE,trim:aE,stripBOM:lE},yi=bt;function Eh(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var Sh=function(t,e,r){if(!e)return t;var n;if(r)n=r(e);else if(yi.isURLSearchParams(e))n=e.toString();else{var i=[];yi.forEach(e,function(o,a){o===null||typeof o=="undefined"||(yi.isArray(o)?a=a+"[]":o=[o],yi.forEach(o,function(d){yi.isDate(d)?d=d.toISOString():yi.isObject(d)&&(d=JSON.stringify(d)),i.push(Eh(a)+"="+Eh(d))}))}),n=i.join("&")}if(n){var s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t},uE=bt;function jo(){this.handlers=[]}jo.prototype.use=function(t,e,r){return this.handlers.push({fulfilled:t,rejected:e,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1},jo.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},jo.prototype.forEach=function(t){uE.forEach(this.handlers,function(e){e!==null&&t(e)})};var hE=jo,pE=bt,mE=function(t,e){pE.forEach(t,function(r,n){n!==e&&n.toUpperCase()===e.toUpperCase()&&(t[e]=r,delete t[n])})},Th=function(t,e,r,n,i){return t.config=e,r&&(t.code=r),t.request=n,t.response=i,t.isAxiosError=!0,t.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},t},od,kh;function _h(){if(kh)return od;kh=1;var t=Th;return od=function(e,r,n,i,s){var o=new Error(e);return t(o,r,n,i,s)},od}var ad,bh;function fE(){if(bh)return ad;bh=1;var t=_h();return ad=function(e,r,n){var i=n.config.validateStatus;!n.status||!i||i(n.status)?e(n):r(t("Request failed with status code "+n.status,n.config,null,n.request,n))},ad}var cd,wh;function gE(){if(wh)return cd;wh=1;var t=bt;return cd=t.isStandardBrowserEnv()?function(){return{write:function(e,r,n,i,s,o){var a=[];a.push(e+"="+encodeURIComponent(r)),t.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),t.isString(i)&&a.push("path="+i),t.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read:function(e){var r=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return r?decodeURIComponent(r[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}(),cd}var Ch,Ih;function vE(){return Ih||(Ih=1,Ch=function(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}),Ch}var Rh,Ph;function yE(){return Ph||(Ph=1,Rh=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}),Rh}var dd,Ah;function EE(){if(Ah)return dd;Ah=1;var t=vE(),e=yE();return dd=function(r,n){return r&&!t(n)?e(r,n):n},dd}var ld,Mh;function SE(){if(Mh)return ld;Mh=1;var t=bt,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 ld=function(r){var n={},i,s,o;return r&&t.forEach(r.split(`
13
+ `),function(a){if(o=a.indexOf(":"),i=t.trim(a.substr(0,o)).toLowerCase(),s=t.trim(a.substr(o+1)),i){if(n[i]&&e.indexOf(i)>=0)return;i==="set-cookie"?n[i]=(n[i]?n[i]:[]).concat([s]):n[i]=n[i]?n[i]+", "+s:s}}),n},ld}var ud,Dh;function TE(){if(Dh)return ud;Dh=1;var t=bt;return ud=t.isStandardBrowserEnv()?function(){var e=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a"),n;function i(s){var o=s;return e&&(r.setAttribute("href",o),o=r.href),r.setAttribute("href",o),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:r.pathname.charAt(0)==="/"?r.pathname:"/"+r.pathname}}return n=i(window.location.href),function(s){var o=t.isString(s)?i(s):s;return o.protocol===n.protocol&&o.host===n.host}}():function(){return function(){return!0}}(),ud}var hd,Oh;function Ho(){if(Oh)return hd;Oh=1;function t(e){this.message=e}return t.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},t.prototype.__CANCEL__=!0,hd=t,hd}var pd,Nh;function kE(){if(Nh)return pd;Nh=1;var t=bt,e=fE(),r=gE(),n=Sh,i=EE(),s=SE(),o=TE(),a=_h(),d=Wo(),h=Ho();return pd=function(p){return new Promise(function(f,g){var E=p.data,v=p.headers,R=p.responseType,A;function L(){p.cancelToken&&p.cancelToken.unsubscribe(A),p.signal&&p.signal.removeEventListener("abort",A)}t.isFormData(E)&&delete v["Content-Type"];var F=new XMLHttpRequest;if(p.auth){var W=p.auth.username||"",H=p.auth.password?unescape(encodeURIComponent(p.auth.password)):"";v.Authorization="Basic "+btoa(W+":"+H)}var I=i(p.baseURL,p.url);F.open(p.method.toUpperCase(),n(I,p.params,p.paramsSerializer),!0),F.timeout=p.timeout;function S(){if(F){var N="getAllResponseHeaders"in F?s(F.getAllResponseHeaders()):null,ce=!R||R==="text"||R==="json"?F.responseText:F.response,Le={data:ce,status:F.status,statusText:F.statusText,headers:N,config:p,request:F};e(function($){f($),L()},function($){g($),L()},Le),F=null}}if("onloadend"in F?F.onloadend=S:F.onreadystatechange=function(){!F||F.readyState!==4||F.status===0&&!(F.responseURL&&F.responseURL.indexOf("file:")===0)||setTimeout(S)},F.onabort=function(){F&&(g(a("Request aborted",p,"ECONNABORTED",F)),F=null)},F.onerror=function(){g(a("Network Error",p,null,F)),F=null},F.ontimeout=function(){var N=p.timeout?"timeout of "+p.timeout+"ms exceeded":"timeout exceeded",ce=p.transitional||d.transitional;p.timeoutErrorMessage&&(N=p.timeoutErrorMessage),g(a(N,p,ce.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",F)),F=null},t.isStandardBrowserEnv()){var P=(p.withCredentials||o(I))&&p.xsrfCookieName?r.read(p.xsrfCookieName):void 0;P&&(v[p.xsrfHeaderName]=P)}"setRequestHeader"in F&&t.forEach(v,function(N,ce){typeof E=="undefined"&&ce.toLowerCase()==="content-type"?delete v[ce]:F.setRequestHeader(ce,N)}),t.isUndefined(p.withCredentials)||(F.withCredentials=!!p.withCredentials),R&&R!=="json"&&(F.responseType=p.responseType),typeof p.onDownloadProgress=="function"&&F.addEventListener("progress",p.onDownloadProgress),typeof p.onUploadProgress=="function"&&F.upload&&F.upload.addEventListener("progress",p.onUploadProgress),(p.cancelToken||p.signal)&&(A=function(N){F&&(g(!N||N&&N.type?new h("canceled"):N),F.abort(),F=null)},p.cancelToken&&p.cancelToken.subscribe(A),p.signal&&(p.signal.aborted?A():p.signal.addEventListener("abort",A))),E||(E=null),F.send(E)})},pd}var md,Lh;function Wo(){if(Lh)return md;Lh=1;var t=bt,e=mE,r=Th,n={"Content-Type":"application/x-www-form-urlencoded"};function i(d,h){!t.isUndefined(d)&&t.isUndefined(d["Content-Type"])&&(d["Content-Type"]=h)}function s(){var d;return(typeof XMLHttpRequest!="undefined"||typeof process!="undefined"&&Object.prototype.toString.call(process)==="[object process]")&&(d=kE()),d}function o(d,h,p){if(t.isString(d))try{return(h||JSON.parse)(d),t.trim(d)}catch(f){if(f.name!=="SyntaxError")throw f}return(p||JSON.stringify)(d)}var a={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:s(),transformRequest:[function(d,h){return e(h,"Accept"),e(h,"Content-Type"),t.isFormData(d)||t.isArrayBuffer(d)||t.isBuffer(d)||t.isStream(d)||t.isFile(d)||t.isBlob(d)?d:t.isArrayBufferView(d)?d.buffer:t.isURLSearchParams(d)?(i(h,"application/x-www-form-urlencoded;charset=utf-8"),d.toString()):t.isObject(d)||h&&h["Content-Type"]==="application/json"?(i(h,"application/json"),o(d)):d}],transformResponse:[function(d){var h=this.transitional||a.transitional,p=h&&h.silentJSONParsing,f=h&&h.forcedJSONParsing,g=!p&&this.responseType==="json";if(g||f&&t.isString(d)&&d.length)try{return JSON.parse(d)}catch(E){if(g)throw E.name==="SyntaxError"?r(E,this,"E_JSON_PARSE"):E}return d}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(d){return d>=200&&d<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return t.forEach(["delete","get","head"],function(d){a.headers[d]={}}),t.forEach(["post","put","patch"],function(d){a.headers[d]=t.merge(n)}),md=a,md}var _E=bt,bE=Wo(),wE=function(t,e,r){var n=this||bE;return _E.forEach(r,function(i){t=i.call(n,t,e)}),t},xh,Fh;function Uh(){return Fh||(Fh=1,xh=function(t){return!!(t&&t.__CANCEL__)}),xh}var Vh=bt,fd=wE,CE=Uh(),IE=Wo(),RE=Ho();function gd(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new RE("canceled")}var PE=function(t){gd(t),t.headers=t.headers||{},t.data=fd.call(t,t.data,t.headers,t.transformRequest),t.headers=Vh.merge(t.headers.common||{},t.headers[t.method]||{},t.headers),Vh.forEach(["delete","get","head","post","put","patch","common"],function(r){delete t.headers[r]});var e=t.adapter||IE.adapter;return e(t).then(function(r){return gd(t),r.data=fd.call(t,r.data,r.headers,t.transformResponse),r},function(r){return CE(r)||(gd(t),r&&r.response&&(r.response.data=fd.call(t,r.response.data,r.response.headers,t.transformResponse))),Promise.reject(r)})},At=bt,Bh=function(t,e){e=e||{};var r={};function n(h,p){return At.isPlainObject(h)&&At.isPlainObject(p)?At.merge(h,p):At.isPlainObject(p)?At.merge({},p):At.isArray(p)?p.slice():p}function i(h){if(At.isUndefined(e[h])){if(!At.isUndefined(t[h]))return n(void 0,t[h])}else return n(t[h],e[h])}function s(h){if(!At.isUndefined(e[h]))return n(void 0,e[h])}function o(h){if(At.isUndefined(e[h])){if(!At.isUndefined(t[h]))return n(void 0,t[h])}else return n(void 0,e[h])}function a(h){if(h in e)return n(t[h],e[h]);if(h in t)return n(void 0,t[h])}var d={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a};return At.forEach(Object.keys(t).concat(Object.keys(e)),function(h){var p=d[h]||i,f=p(h);At.isUndefined(f)&&p!==a||(r[h]=f)}),r},jh,Hh;function Wh(){return Hh||(Hh=1,jh={version:"0.25.0"}),jh}var AE=Wh().version,vd={};["object","boolean","number","function","string","symbol"].forEach(function(t,e){vd[t]=function(r){return typeof r===t||"a"+(e<1?"n ":" ")+t}});var $h={};vd.transitional=function(t,e,r){function n(i,s){return"[Axios v"+AE+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return function(i,s,o){if(t===!1)throw new Error(n(s," has been removed"+(e?" in "+e:"")));return e&&!$h[s]&&($h[s]=!0,console.warn(n(s," has been deprecated since v"+e+" and will be removed in the near future"))),t?t(i,s,o):!0}};function ME(t,e,r){if(typeof t!="object")throw new TypeError("options must be an object");for(var n=Object.keys(t),i=n.length;i-- >0;){var s=n[i],o=e[s];if(o){var a=t[s],d=a===void 0||o(a,s,t);if(d!==!0)throw new TypeError("option "+s+" must be "+d);continue}if(r!==!0)throw Error("Unknown option "+s)}}var DE={assertOptions:ME,validators:vd},Gh=bt,OE=Sh,Jh=hE,qh=PE,$o=Bh,Kh=DE,Ei=Kh.validators;function us(t){this.defaults=t,this.interceptors={request:new Jh,response:new Jh}}us.prototype.request=function(t,e){if(typeof t=="string"?(e=e||{},e.url=t):e=t||{},!e.url)throw new Error("Provided config url is not valid");e=$o(this.defaults,e),e.method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var r=e.transitional;r!==void 0&&Kh.assertOptions(r,{silentJSONParsing:Ei.transitional(Ei.boolean),forcedJSONParsing:Ei.transitional(Ei.boolean),clarifyTimeoutError:Ei.transitional(Ei.boolean)},!1);var n=[],i=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(e)===!1||(i=i&&f.synchronous,n.unshift(f.fulfilled,f.rejected))});var s=[];this.interceptors.response.forEach(function(f){s.push(f.fulfilled,f.rejected)});var o;if(!i){var a=[qh,void 0];for(Array.prototype.unshift.apply(a,n),a=a.concat(s),o=Promise.resolve(e);a.length;)o=o.then(a.shift(),a.shift());return o}for(var d=e;n.length;){var h=n.shift(),p=n.shift();try{d=h(d)}catch(f){p(f);break}}try{o=qh(d)}catch(f){return Promise.reject(f)}for(;s.length;)o=o.then(s.shift(),s.shift());return o},us.prototype.getUri=function(t){if(!t.url)throw new Error("Provided config url is not valid");return t=$o(this.defaults,t),OE(t.url,t.params,t.paramsSerializer).replace(/^\?/,"")},Gh.forEach(["delete","get","head","options"],function(t){us.prototype[t]=function(e,r){return this.request($o(r||{},{method:t,url:e,data:(r||{}).data}))}}),Gh.forEach(["post","put","patch"],function(t){us.prototype[t]=function(e,r,n){return this.request($o(n||{},{method:t,url:e,data:r}))}});var NE=us,yd,zh;function LE(){if(zh)return yd;zh=1;var t=Ho();function e(r){if(typeof r!="function")throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(s){n=s});var i=this;this.promise.then(function(s){if(i._listeners){var o,a=i._listeners.length;for(o=0;o<a;o++)i._listeners[o](s);i._listeners=null}}),this.promise.then=function(s){var o,a=new Promise(function(d){i.subscribe(d),o=d}).then(s);return a.cancel=function(){i.unsubscribe(o)},a},r(function(s){i.reason||(i.reason=new t(s),n(i.reason))})}return e.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},e.prototype.subscribe=function(r){if(this.reason){r(this.reason);return}this._listeners?this._listeners.push(r):this._listeners=[r]},e.prototype.unsubscribe=function(r){if(this._listeners){var n=this._listeners.indexOf(r);n!==-1&&this._listeners.splice(n,1)}},e.source=function(){var r,n=new e(function(i){r=i});return{token:n,cancel:r}},yd=e,yd}var Yh,Qh;function xE(){return Qh||(Qh=1,Yh=function(t){return function(e){return t.apply(null,e)}}),Yh}var Ed,Xh;function FE(){if(Xh)return Ed;Xh=1;var t=bt;return Ed=function(e){return t.isObject(e)&&e.isAxiosError===!0},Ed}var Zh=bt,UE=fh,Go=NE,VE=Bh,BE=Wo();function ep(t){var e=new Go(t),r=UE(Go.prototype.request,e);return Zh.extend(r,Go.prototype,e),Zh.extend(r,e),r.create=function(n){return ep(VE(t,n))},r}var ar=ep(BE);ar.Axios=Go,ar.Cancel=Ho(),ar.CancelToken=LE(),ar.isCancel=Uh(),ar.VERSION=Wh().version,ar.all=function(t){return Promise.all(t)},ar.spread=xE(),ar.isAxiosError=FE(),zy.exports=ar,Vo.default=ar,function(t){t.exports=Vo}(Ky);const Jo=uy(td);let tp="hXgU8Wc8pwuGNq9ms5q9Hh";var rp;typeof process!="undefined"&&(rp=process==null?void 0:process.env)!=null&&rp.FLAGSMITH_ENVIRONMENT_KEY&&(tp={}.FLAGSMITH_ENVIRONMENT_KEY);function jE(t=[]){const e={};return t.forEach(r=>{e[r.feature.name]={enabled:r.enabled,value:r.feature_state_value}}),e}class HE{constructor(e=tp){m(this,"flags",{}),m(this,"environmentKey",null),this.environmentKey=e,this.identify=this.identify.bind(this),this.getValue=this.getValue.bind(this),this.hasFeature=this.hasFeature.bind(this),this.getAllFlags=this.getAllFlags.bind(this)}identify(e){return u(this,arguments,function*(r,n={},i=!1,s=5e3,o="edge.api.flagsmith.com"){const a=JSON.parse(JSON.stringify(n)),d=Object.entries(a).map(h=>({trait_key:h[0],trait_value:h[1]}));try{const h="_"+(Math.random()+1).toString(36).substring(2),p=yield Jo.post(`https://${o}/api/v1/identities/`,{identifier:r+(i?h:""),traits:d},{headers:{"Content-Type":"application/json","X-Environment-Key":this.environmentKey},timeout:s});this.flags=jE(p.data.flags||[])}catch(h){}return this.flags})}getValue(e){return this.flags&&this.flags[e]&&this.flags[e].value}hasFeature(e){return this.flags&&this.flags[e]&&this.flags[e].enabled}getAllFlags(){return this.flags}}const K=new HE,np=[-2,-1,0,1,2],WE=[0,1,2,3,4];function $E(t){t=t.trim();let e="0",r="0",n="0";return t.length==4?(e="0x"+t[1]+t[1],r="0x"+t[2]+t[2],n="0x"+t[3]+t[3]):t.length>6&&(e="0x"+t[1]+t[2],r="0x"+t[3]+t[4],n="0x"+t[5]+t[6]),[+e,+r,+n]}const GE=(t,e,r)=>{let n,i,s;if(e==0)n=i=s=r;else{const o=(h,p,f)=>(f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?h+(p-h)*6*f:f<.5?p:f<.6666666666666666?h+(p-h)*(.6666666666666666-f)*6:h),a=r<.5?r*(1+e):r+e-r*e,d=2*r-a;n=o(d,a,t+1/3),i=o(d,a,t),s=o(d,a,t-1/3)}return[Math.round(n*255),Math.round(i*255),Math.round(s*255)]},JE=(t,e,r)=>{t/=255,e/=255,r/=255;const n=Math.max(t,e,r),i=Math.min(t,e,r);let s,o;const a=(n+i)/2;if(n==i)s=o=0;else{const d=n-i;switch(o=a>.5?d/(2-n-i):d/(n+i),n){case t:s=(e-r)/d+(e<r?6:0);break;case e:s=(r-t)/d+2;break;case r:s=(t-e)/d+4;break}s/=6}return[s,o,a]},qE=(t,e,r)=>{const n=i=>i.toString(16).padStart(2,"0");return`#${n(t)}${n(e)}${n(r)}`},ip=(t,e=np,r=.4)=>{const n=[],[i,s,o]=$E(t),[a,d,h]=JE(i,s,o),p=Math.round(h*100);p>70?r=.8:p>60?r=.9:p<10?r=.075:p<42&&(r=.3);const f=e.findIndex(A=>A===0);if(f===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const g=5-f,E=f+1,v=(100-p)/g,R=p/E;for(const A of e){let L;A<0?L=p+A*R*r:A>0?L=p+A*v*r:L=p;const[F,W,H]=GE(a,d,L/100);n.push(qE(F,W,H))}return n},sp={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"}},KE=t=>{const[e,r,n,i,s]=ip(t,np);return{300:e,400:r,500:n,600:i,700:s}},zE=t=>{if(t==="#FFFFFF")return sp.light.background;if(t==="#000000")return sp.dark.background;const[e,r,n,i,s]=ip(t,WE);return{1e3:e,900:r,800:n,700:i,600:s}};function YE(){this.__data__=[],this.size=0}function qo(t,e){return t===e||t!==t&&e!==e}function Ko(t,e){for(var r=t.length;r--;)if(qo(t[r][0],e))return r;return-1}var QE=Array.prototype,XE=QE.splice;function ZE(t){var e=this.__data__,r=Ko(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():XE.call(e,r,1),--this.size,!0}function eS(t){var e=this.__data__,r=Ko(e,t);return r<0?void 0:e[r][1]}function tS(t){return Ko(this.__data__,t)>-1}function rS(t,e){var r=this.__data__,n=Ko(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}function Sr(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Sr.prototype.clear=YE,Sr.prototype.delete=ZE,Sr.prototype.get=eS,Sr.prototype.has=tS,Sr.prototype.set=rS;function nS(){this.__data__=new Sr,this.size=0}function iS(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}function sS(t){return this.__data__.get(t)}function oS(t){return this.__data__.has(t)}var aS=typeof global=="object"&&global&&global.Object===Object&&global;const op=aS;var cS=typeof self=="object"&&self&&self.Object===Object&&self,dS=op||cS||Function("return this")();const Jt=dS;var lS=Jt.Symbol;const Si=lS;var ap=Object.prototype,uS=ap.hasOwnProperty,hS=ap.toString,hs=Si?Si.toStringTag:void 0;function pS(t){var e=uS.call(t,hs),r=t[hs];try{t[hs]=void 0;var n=!0}catch(s){}var i=hS.call(t);return n&&(e?t[hs]=r:delete t[hs]),i}var mS=Object.prototype,fS=mS.toString;function gS(t){return fS.call(t)}var vS="[object Null]",yS="[object Undefined]",cp=Si?Si.toStringTag:void 0;function yn(t){return t==null?t===void 0?yS:vS:cp&&cp in Object(t)?pS(t):gS(t)}function qt(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ES="[object AsyncFunction]",SS="[object Function]",TS="[object GeneratorFunction]",kS="[object Proxy]";function Sd(t){if(!qt(t))return!1;var e=yn(t);return e==SS||e==TS||e==ES||e==kS}var _S=Jt["__core-js_shared__"];const Td=_S;var dp=function(){var t=/[^.]+$/.exec(Td&&Td.keys&&Td.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function bS(t){return!!dp&&dp in t}var wS=Function.prototype,CS=wS.toString;function En(t){if(t!=null){try{return CS.call(t)}catch(e){}try{return t+""}catch(e){}}return""}var IS=/[\\^$.*+?()[\]{}|]/g,RS=/^\[object .+?Constructor\]$/,PS=Function.prototype,AS=Object.prototype,MS=PS.toString,DS=AS.hasOwnProperty,OS=RegExp("^"+MS.call(DS).replace(IS,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function NS(t){if(!qt(t)||bS(t))return!1;var e=Sd(t)?OS:RS;return e.test(En(t))}function LS(t,e){return t==null?void 0:t[e]}function Sn(t,e){var r=LS(t,e);return NS(r)?r:void 0}var xS=Sn(Jt,"Map");const ps=xS;var FS=Sn(Object,"create");const ms=FS;function US(){this.__data__=ms?ms(null):{},this.size=0}function VS(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var BS="__lodash_hash_undefined__",jS=Object.prototype,HS=jS.hasOwnProperty;function WS(t){var e=this.__data__;if(ms){var r=e[t];return r===BS?void 0:r}return HS.call(e,t)?e[t]:void 0}var $S=Object.prototype,GS=$S.hasOwnProperty;function JS(t){var e=this.__data__;return ms?e[t]!==void 0:GS.call(e,t)}var qS="__lodash_hash_undefined__";function KS(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=ms&&e===void 0?qS:e,this}function Tn(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Tn.prototype.clear=US,Tn.prototype.delete=VS,Tn.prototype.get=WS,Tn.prototype.has=JS,Tn.prototype.set=KS;function zS(){this.size=0,this.__data__={hash:new Tn,map:new(ps||Sr),string:new Tn}}function YS(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}function zo(t,e){var r=t.__data__;return YS(e)?r[typeof e=="string"?"string":"hash"]:r.map}function QS(t){var e=zo(this,t).delete(t);return this.size-=e?1:0,e}function XS(t){return zo(this,t).get(t)}function ZS(t){return zo(this,t).has(t)}function eT(t,e){var r=zo(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}function Ti(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}Ti.prototype.clear=zS,Ti.prototype.delete=QS,Ti.prototype.get=XS,Ti.prototype.has=ZS,Ti.prototype.set=eT;var tT=200;function rT(t,e){var r=this.__data__;if(r instanceof Sr){var n=r.__data__;if(!ps||n.length<tT-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new Ti(n)}return r.set(t,e),this.size=r.size,this}function kn(t){var e=this.__data__=new Sr(t);this.size=e.size}kn.prototype.clear=nS,kn.prototype.delete=iS,kn.prototype.get=sS,kn.prototype.has=oS,kn.prototype.set=rT;function nT(t,e){for(var r=-1,n=t==null?0:t.length;++r<n&&e(t[r],r,t)!==!1;);return t}var iT=function(){try{var t=Sn(Object,"defineProperty");return t({},"",{}),t}catch(e){}}();const Yo=iT;function kd(t,e,r){e=="__proto__"&&Yo?Yo(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var sT=Object.prototype,oT=sT.hasOwnProperty;function lp(t,e,r){var n=t[e];(!(oT.call(t,e)&&qo(n,r))||r===void 0&&!(e in t))&&kd(t,e,r)}function fs(t,e,r,n){var i=!r;r||(r={});for(var s=-1,o=e.length;++s<o;){var a=e[s],d=n?n(r[a],t[a],a,r,t):void 0;d===void 0&&(d=t[a]),i?kd(r,a,d):lp(r,a,d)}return r}function aT(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}function Br(t){return t!=null&&typeof t=="object"}var cT="[object Arguments]";function up(t){return Br(t)&&yn(t)==cT}var hp=Object.prototype,dT=hp.hasOwnProperty,lT=hp.propertyIsEnumerable,uT=up(function(){return arguments}())?up:function(t){return Br(t)&&dT.call(t,"callee")&&!lT.call(t,"callee")};const Qo=uT;var hT=Array.isArray;const ki=hT;function pT(){return!1}var pp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,mp=pp&&typeof module=="object"&&module&&!module.nodeType&&module,mT=mp&&mp.exports===pp,fp=mT?Jt.Buffer:void 0,fT=fp?fp.isBuffer:void 0,gT=fT||pT;const Xo=gT;var vT=9007199254740991,yT=/^(?:0|[1-9]\d*)$/;function gp(t,e){var r=typeof t;return e=e==null?vT:e,!!e&&(r=="number"||r!="symbol"&&yT.test(t))&&t>-1&&t%1==0&&t<e}var ET=9007199254740991;function vp(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=ET}var ST="[object Arguments]",TT="[object Array]",kT="[object Boolean]",_T="[object Date]",bT="[object Error]",wT="[object Function]",CT="[object Map]",IT="[object Number]",RT="[object Object]",PT="[object RegExp]",AT="[object Set]",MT="[object String]",DT="[object WeakMap]",OT="[object ArrayBuffer]",NT="[object DataView]",LT="[object Float32Array]",xT="[object Float64Array]",FT="[object Int8Array]",UT="[object Int16Array]",VT="[object Int32Array]",BT="[object Uint8Array]",jT="[object Uint8ClampedArray]",HT="[object Uint16Array]",WT="[object Uint32Array]",Ce={};Ce[LT]=Ce[xT]=Ce[FT]=Ce[UT]=Ce[VT]=Ce[BT]=Ce[jT]=Ce[HT]=Ce[WT]=!0,Ce[ST]=Ce[TT]=Ce[OT]=Ce[kT]=Ce[NT]=Ce[_T]=Ce[bT]=Ce[wT]=Ce[CT]=Ce[IT]=Ce[RT]=Ce[PT]=Ce[AT]=Ce[MT]=Ce[DT]=!1;function $T(t){return Br(t)&&vp(t.length)&&!!Ce[yn(t)]}function _d(t){return function(e){return t(e)}}var yp=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gs=yp&&typeof module=="object"&&module&&!module.nodeType&&module,GT=gs&&gs.exports===yp,bd=GT&&op.process,JT=function(){try{var t=gs&&gs.require&&gs.require("util").types;return t||bd&&bd.binding&&bd.binding("util")}catch(e){}}();const _i=JT;var Ep=_i&&_i.isTypedArray,qT=Ep?_d(Ep):$T;const wd=qT;var KT=Object.prototype,zT=KT.hasOwnProperty;function Sp(t,e){var r=ki(t),n=!r&&Qo(t),i=!r&&!n&&Xo(t),s=!r&&!n&&!i&&wd(t),o=r||n||i||s,a=o?aT(t.length,String):[],d=a.length;for(var h in t)(e||zT.call(t,h))&&!(o&&(h=="length"||i&&(h=="offset"||h=="parent")||s&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||gp(h,d)))&&a.push(h);return a}var YT=Object.prototype;function Zo(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||YT;return t===r}function Tp(t,e){return function(r){return t(e(r))}}var QT=Tp(Object.keys,Object);const XT=QT;var ZT=Object.prototype,ek=ZT.hasOwnProperty;function kp(t){if(!Zo(t))return XT(t);var e=[];for(var r in Object(t))ek.call(t,r)&&r!="constructor"&&e.push(r);return e}function vs(t){return t!=null&&vp(t.length)&&!Sd(t)}function Cd(t){return vs(t)?Sp(t):kp(t)}function tk(t,e){return t&&fs(e,Cd(e),t)}function rk(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var nk=Object.prototype,ik=nk.hasOwnProperty;function sk(t){if(!qt(t))return rk(t);var e=Zo(t),r=[];for(var n in t)n=="constructor"&&(e||!ik.call(t,n))||r.push(n);return r}function ys(t){return vs(t)?Sp(t,!0):sk(t)}function ok(t,e){return t&&fs(e,ys(e),t)}var _p=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bp=_p&&typeof module=="object"&&module&&!module.nodeType&&module,ak=bp&&bp.exports===_p,wp=ak?Jt.Buffer:void 0,Cp=wp?wp.allocUnsafe:void 0;function Ip(t,e){if(e)return t.slice();var r=t.length,n=Cp?Cp(r):new t.constructor(r);return t.copy(n),n}function Rp(t,e){var r=-1,n=t.length;for(e||(e=Array(n));++r<n;)e[r]=t[r];return e}function ck(t,e){for(var r=-1,n=t==null?0:t.length,i=0,s=[];++r<n;){var o=t[r];e(o,r,t)&&(s[i++]=o)}return s}function Pp(){return[]}var dk=Object.prototype,lk=dk.propertyIsEnumerable,Ap=Object.getOwnPropertySymbols,uk=Ap?function(t){return t==null?[]:(t=Object(t),ck(Ap(t),function(e){return lk.call(t,e)}))}:Pp;const Id=uk;function hk(t,e){return fs(t,Id(t),e)}function Mp(t,e){for(var r=-1,n=e.length,i=t.length;++r<n;)t[i+r]=e[r];return t}var pk=Tp(Object.getPrototypeOf,Object);const Rd=pk;var mk=Object.getOwnPropertySymbols,fk=mk?function(t){for(var e=[];t;)Mp(e,Id(t)),t=Rd(t);return e}:Pp;const Dp=fk;function gk(t,e){return fs(t,Dp(t),e)}function Op(t,e,r){var n=e(t);return ki(t)?n:Mp(n,r(t))}function vk(t){return Op(t,Cd,Id)}function yk(t){return Op(t,ys,Dp)}var Ek=Sn(Jt,"DataView");const Pd=Ek;var Sk=Sn(Jt,"Promise");const Ad=Sk;var Tk=Sn(Jt,"Set");const Md=Tk;var kk=Sn(Jt,"WeakMap");const Dd=kk;var Np="[object Map]",_k="[object Object]",Lp="[object Promise]",xp="[object Set]",Fp="[object WeakMap]",Up="[object DataView]",bk=En(Pd),wk=En(ps),Ck=En(Ad),Ik=En(Md),Rk=En(Dd),_n=yn;(Pd&&_n(new Pd(new ArrayBuffer(1)))!=Up||ps&&_n(new ps)!=Np||Ad&&_n(Ad.resolve())!=Lp||Md&&_n(new Md)!=xp||Dd&&_n(new Dd)!=Fp)&&(_n=function(t){var e=yn(t),r=e==_k?t.constructor:void 0,n=r?En(r):"";if(n)switch(n){case bk:return Up;case wk:return Np;case Ck:return Lp;case Ik:return xp;case Rk:return Fp}return e});const ea=_n;var Pk=Object.prototype,Ak=Pk.hasOwnProperty;function Mk(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&Ak.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var Dk=Jt.Uint8Array;const Vp=Dk;function Od(t){var e=new t.constructor(t.byteLength);return new Vp(e).set(new Vp(t)),e}function Ok(t,e){var r=e?Od(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var Nk=/\w*$/;function Lk(t){var e=new t.constructor(t.source,Nk.exec(t));return e.lastIndex=t.lastIndex,e}var Bp=Si?Si.prototype:void 0,jp=Bp?Bp.valueOf:void 0;function xk(t){return jp?Object(jp.call(t)):{}}function Hp(t,e){var r=e?Od(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var Fk="[object Boolean]",Uk="[object Date]",Vk="[object Map]",Bk="[object Number]",jk="[object RegExp]",Hk="[object Set]",Wk="[object String]",$k="[object Symbol]",Gk="[object ArrayBuffer]",Jk="[object DataView]",qk="[object Float32Array]",Kk="[object Float64Array]",zk="[object Int8Array]",Yk="[object Int16Array]",Qk="[object Int32Array]",Xk="[object Uint8Array]",Zk="[object Uint8ClampedArray]",e_="[object Uint16Array]",t_="[object Uint32Array]";function r_(t,e,r){var n=t.constructor;switch(e){case Gk:return Od(t);case Fk:case Uk:return new n(+t);case Jk:return Ok(t,r);case qk:case Kk:case zk:case Yk:case Qk:case Xk:case Zk:case e_:case t_:return Hp(t,r);case Vk:return new n;case Bk:case Wk:return new n(t);case jk:return Lk(t);case Hk:return new n;case $k:return xk(t)}}var Wp=Object.create,n_=function(){function t(){}return function(e){if(!qt(e))return{};if(Wp)return Wp(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();const i_=n_;function $p(t){return typeof t.constructor=="function"&&!Zo(t)?i_(Rd(t)):{}}var s_="[object Map]";function o_(t){return Br(t)&&ea(t)==s_}var Gp=_i&&_i.isMap,a_=Gp?_d(Gp):o_;const c_=a_;var d_="[object Set]";function l_(t){return Br(t)&&ea(t)==d_}var Jp=_i&&_i.isSet,u_=Jp?_d(Jp):l_;const h_=u_;var p_=1,m_=2,f_=4,qp="[object Arguments]",g_="[object Array]",v_="[object Boolean]",y_="[object Date]",E_="[object Error]",Kp="[object Function]",S_="[object GeneratorFunction]",T_="[object Map]",k_="[object Number]",zp="[object Object]",__="[object RegExp]",b_="[object Set]",w_="[object String]",C_="[object Symbol]",I_="[object WeakMap]",R_="[object ArrayBuffer]",P_="[object DataView]",A_="[object Float32Array]",M_="[object Float64Array]",D_="[object Int8Array]",O_="[object Int16Array]",N_="[object Int32Array]",L_="[object Uint8Array]",x_="[object Uint8ClampedArray]",F_="[object Uint16Array]",U_="[object Uint32Array]",be={};be[qp]=be[g_]=be[R_]=be[P_]=be[v_]=be[y_]=be[A_]=be[M_]=be[D_]=be[O_]=be[N_]=be[T_]=be[k_]=be[zp]=be[__]=be[b_]=be[w_]=be[C_]=be[L_]=be[x_]=be[F_]=be[U_]=!0,be[E_]=be[Kp]=be[I_]=!1;function ta(t,e,r,n,i,s){var o,a=e&p_,d=e&m_,h=e&f_;if(r&&(o=i?r(t,n,i,s):r(t)),o!==void 0)return o;if(!qt(t))return t;var p=ki(t);if(p){if(o=Mk(t),!a)return Rp(t,o)}else{var f=ea(t),g=f==Kp||f==S_;if(Xo(t))return Ip(t,a);if(f==zp||f==qp||g&&!i){if(o=d||g?{}:$p(t),!a)return d?gk(t,ok(o,t)):hk(t,tk(o,t))}else{if(!be[f])return i?t:{};o=r_(t,f,a)}}s||(s=new kn);var E=s.get(t);if(E)return E;s.set(t,o),h_(t)?t.forEach(function(A){o.add(ta(A,e,r,A,t,s))}):c_(t)&&t.forEach(function(A,L){o.set(L,ta(A,e,r,L,t,s))});var v=h?d?yk:vk:d?ys:Cd,R=p?void 0:v(t);return nT(R||t,function(A,L){R&&(L=A,A=t[L]),lp(o,L,ta(A,e,r,L,t,s))}),o}var V_=1,B_=4;function Nd(t){return ta(t,V_|B_)}var j_="[object Symbol]";function H_(t){return typeof t=="symbol"||Br(t)&&yn(t)==j_}const W_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:KE("#2160FD"),background:zE("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function Yp(){return Nd(W_)}const $_={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:xo.Skip,plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:q.Allowed,can_consume:Fo.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed,can_consume:Fo.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:vi.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:Yp(),config_diff:{}},config:{view_type:We.GroupCall,media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"hybrid"};function G_(){return Nd($_)}vi.none,Uo.skip;const J_={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:xo.Skip,plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:q.Allowed},audio:{can_produce:q.Allowed},screenshare:{can_produce:q.Allowed}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:vi.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:Yp(),config_diff:{}},config:{view_type:We.GroupCall,media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:24},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1},version:"2.0.0"};function Ld(){return Nd(J_)}var q_=/\s/;function K_(t){for(var e=t.length;e--&&q_.test(t.charAt(e)););return e}var z_=/^\s+/;function Y_(t){return t&&t.slice(0,K_(t)+1).replace(z_,"")}var Qp=0/0,Q_=/^[-+]0x[0-9a-f]+$/i,X_=/^0b[01]+$/i,Z_=/^0o[0-7]+$/i,eb=parseInt;function Xp(t){if(typeof t=="number")return t;if(H_(t))return Qp;if(qt(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=qt(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=Y_(t);var r=X_.test(t);return r||Z_.test(t)?eb(t.slice(2),r?2:8):Q_.test(t)?Qp:+t}function Zp(t){return t}function tb(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var rb=800,nb=16,ib=Date.now;function sb(t){var e=0,r=0;return function(){var n=ib(),i=nb-(n-r);if(r=n,i>0){if(++e>=rb)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}function ob(t){return function(){return t}}var ab=Yo?function(t,e){return Yo(t,"toString",{configurable:!0,enumerable:!1,value:ob(e),writable:!0})}:Zp,cb=sb(ab);const db=cb;var em=Math.max;function lb(t,e,r){return e=em(e===void 0?t.length-1:e,0),function(){for(var n=arguments,i=-1,s=em(n.length-e,0),o=Array(s);++i<s;)o[i]=n[e+i];i=-1;for(var a=Array(e+1);++i<e;)a[i]=n[i];return a[e]=r(o),tb(t,this,a)}}function ub(t,e){return db(lb(t,e,Zp),t+"")}function hb(t,e,r){if(!qt(r))return!1;var n=typeof e;return(n=="number"?vs(r)&&gp(e,r.length):n=="string"&&e in r)?qo(r[e],t):!1}function pb(t){return ub(function(e,r){var n=-1,i=r.length,s=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(s=t.length>3&&typeof s=="function"?(i--,s):void 0,o&&hb(r[0],r[1],o)&&(s=i<3?void 0:s,i=1),e=Object(e);++n<i;){var a=r[n];a&&t(e,a,n,s)}return e})}var mb="[object Object]",fb=Function.prototype,gb=Object.prototype,tm=fb.toString,vb=gb.hasOwnProperty,yb=tm.call(Object);function Eb(t){if(!Br(t)||yn(t)!=mb)return!1;var e=Rd(t);if(e===null)return!0;var r=vb.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&tm.call(r)==yb}function Sb(t){return function(e,r,n){for(var i=-1,s=Object(e),o=n(e),a=o.length;a--;){var d=o[t?a:++i];if(r(s[d],d,s)===!1)break}return e}}var Tb=Sb();const kb=Tb;var _b=function(){return Jt.Date.now()};const xd=_b;var bb="Expected a function",wb=Math.max,Cb=Math.min;function cr(t,e,r){var n,i,s,o,a,d,h=0,p=!1,f=!1,g=!0;if(typeof t!="function")throw new TypeError(bb);e=Xp(e)||0,qt(r)&&(p=!!r.leading,f="maxWait"in r,s=f?wb(Xp(r.maxWait)||0,e):s,g="trailing"in r?!!r.trailing:g);function E(S){var P=n,N=i;return n=i=void 0,h=S,o=t.apply(N,P),o}function v(S){return h=S,a=setTimeout(L,e),p?E(S):o}function R(S){var P=S-d,N=S-h,ce=e-P;return f?Cb(ce,s-N):ce}function A(S){var P=S-d,N=S-h;return d===void 0||P>=e||P<0||f&&N>=s}function L(){var S=xd();if(A(S))return F(S);a=setTimeout(L,R(S))}function F(S){return a=void 0,g&&n?E(S):(n=i=void 0,o)}function W(){a!==void 0&&clearTimeout(a),h=0,n=d=i=a=void 0}function H(){return a===void 0?o:F(xd())}function I(){var S=xd(),P=A(S);if(n=arguments,i=this,d=S,P){if(a===void 0)return v(d);if(f)return clearTimeout(a),a=setTimeout(L,e),E(d)}return a===void 0&&(a=setTimeout(L,e)),o}return I.cancel=W,I.flush=H,I}function Fd(t,e,r){(r!==void 0&&!qo(t[e],r)||r===void 0&&!(e in t))&&kd(t,e,r)}function Ib(t){return Br(t)&&vs(t)}function Ud(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}function Rb(t){return fs(t,ys(t))}function Pb(t,e,r,n,i,s,o){var a=Ud(t,r),d=Ud(e,r),h=o.get(d);if(h){Fd(t,r,h);return}var p=s?s(a,d,r+"",t,e,o):void 0,f=p===void 0;if(f){var g=ki(d),E=!g&&Xo(d),v=!g&&!E&&wd(d);p=d,g||E||v?ki(a)?p=a:Ib(a)?p=Rp(a):E?(f=!1,p=Ip(d,!0)):v?(f=!1,p=Hp(d,!0)):p=[]:Eb(d)||Qo(d)?(p=a,Qo(a)?p=Rb(a):(!qt(a)||Sd(a))&&(p=$p(d))):f=!1}f&&(o.set(d,p),i(p,d,n,s,o),o.delete(d)),Fd(t,r,p)}function rm(t,e,r,n,i){t!==e&&kb(e,function(s,o){if(i||(i=new kn),qt(s))Pb(t,e,o,r,rm,n,i);else{var a=n?n(Ud(t,o),s,o+"",t,e,i):void 0;a===void 0&&(a=s),Fd(t,o,a)}},ys)}var Ab="[object Map]",Mb="[object Set]",Db=Object.prototype,Ob=Db.hasOwnProperty;function Nb(t){if(t==null)return!0;if(vs(t)&&(ki(t)||typeof t=="string"||typeof t.splice=="function"||Xo(t)||wd(t)||Qo(t)))return!t.length;var e=ea(t);if(e==Ab||e==Mb)return!t.size;if(Zo(t))return!kp(t).length;for(var r in t)if(Ob.call(t,r))return!1;return!0}var Lb=pb(function(t,e,r){rm(t,e,r)});const jr=Lb;var Vd=(t=>(t.PARTICIPANT="PARTICIPANT",t.PEER="PEER",t.CLIENT="CLIENT",t))(Vd||{});const X={REFRESH_ID_ON_DISCONNECTION:"refresh_id_on_disconnection",INTERNAL_CALL_STATS:"internal_call_stats",SIMULCAST:"simulcast",CHAT_SOCKET_SERVER:"chat_socket_server",POLL_SOCKET_SERVER:"poll_socket_server",PLUGIN_SOCKET_SERVER:"plugin_socket_server",NR_OTEL_WEB:"nr_otel_web",CONNECTED_MEETINGS:"connected_meetings",ICE_RESTART_ON_FAILED_STATE:"ice_restart_on_failed_state",ICE_RESTART_ON_DISCONNECTED_STATE:"ice_restart_on_disconnected_state",ENABLE_ICE_STATE_LOGGING:"enable_ice_state_logging",SUPPRESS_PEER_MUTE_UNMUTE_EMITS:"web_core_suppress_peer_mute_unmute_emits",SKIP_OTEL_TRACES:"skip_otel_traces",USE_USERIDS_IN_CHAT:"use_userids_in_chat",CUSTOM_PING_PONG:"custom_ping_pong",ENABLE_HIVE_SIMULCAST:"enable_hive_simulcast",ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_hive_transport_reconnection_on_ice_failed",ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY:"enable_hive_fail_recovery",ENABLE_HIVE_INFINITE_RETRIES:"enable_hive_infinite_retries",HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"hive_transport_force_relay_on_ice_failed",ENABLE_HIVE_CONSUME_OVER_DC:"enable_hive_consume_over_dc",ENABLE_CF_SIMULCAST:"enable_cf_simulcast",ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED:"enable_cf_transport_reconnection_on_ice_failed",ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY:"enable_cf_fail_recovery",ENABLE_CF_INFINITE_RETRIES:"enable_cf_infinite_retries",CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED:"cf_transport_force_relay_on_ice_failed",BYPASS_LOG_EXCLUSION_LIST:"bypass_log_exclusion_list",LOG_LEVEL:"log_level",V1_PLUGINS:"v1_plugins",SCREENSHARE_DTX:"screenshare_dtx",SCREENSHARE_PRIORITY:"screenshare_priority",SCREENSHARE_MIN_BITRATE:"screenshare_minbitrate",SCREENSHARE_SIMULCAST:"screenshare_simulcast",DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE:"disable_webcam_layers_on_screenshare",SCREENSHARE_FORCE_GOOG_CONFERENCE:"screenshare_force_goog_conference",LIVESTREAM:"feat_livestream",FETCH_RETRY:"fetch_retry",DISABLE_WEBCAM_SIMULCAST:"webcore_disable_webcam_simulcast",OVERRIDE_WEBCAM_SIMULCAST:"override_webcam_simulcast",SOCKET_POLLING:"socket_polling",FEAT_PAGINATED_CHAT:"feat_paginated_chat",VAL_MIN_FRAMERATE:"val_min_framerate",SCREEENSHARE_ERR_HACK:"screenshare_err_hack",SCREEENSHARE_CONSTRAINTS_RETRY:"screenshare_constraints_retry",TROUBLESHOOTING:"feat_troubleshooting",VIDEO_CONSTRAINTS:"video_constraints",SCREENSHARE_CONSTRAINTS:"screenshare_constraints",FEAT_CHAT_SDK:"feat_chat_sdk",FEAT_CHAT_SDK_SEARCH:"chat_search",OBS_QUALITY:"obs_quality",ALLOW_SAFARI_MEDIA_MIDDLEWARES:"allow_safari_media_middlewares",DYNAMIC_VIDEO_QUALITY:"dynamic_video_quality",EXP_RESHARE:"exp_reshare",LEAVE_STAGE_ON_END:"leave_stage_on_end",SKIP_SETTING_IN_USE_DEVICE:"skip_setting_in_use_device",PRECALL_BANDWIDTH_TEST:"precall_bandwidth_test"};function ra(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 nm(t){var e,r,n,i;const s=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((e=window.location.host)==null?void 0:e.includes("devel"))&&((r=window.location.host)==null?void 0:r.includes("dyte.io")),o=!!((i=(n=t.getValue("modules"))==null?void 0:n.devTools)!=null&&i.logs);return s||o}function xb(t){if(K.hasFeature(X.LOG_LEVEL)){let e=K.getValue(X.LOG_LEVEL)||"all";if(e=e.toLowerCase().trim(),e==="off")return!1;if(e!=="all"){const r=["debug","log","info","warn","error"],n=r.indexOf(t),i=r.indexOf(e);if(n<i)return!1}}return!0}function im(t,e,r={}){return Object.getOwnPropertyNames(t).forEach(n=>{var i;if([null,void 0,NaN].includes(t[n])||e&&(((i=e.match(/\./g))==null?void 0:i.length)||0)>=10)return;const s=e?`${e}.${n}`:n;typeof t[n]=="object"?im(t[n],s,r):["number","string","boolean"].includes(typeof t[n])&&(r[s]=t[n])}),r}function sm(t,e,r={},n=""){const i={};try{const s=JSON.stringify(r),o=JSON.parse(s),a=im(o,n),d=JSON.stringify(a);if(d.length>5e3){const h=`Log named: "${e}" is trying to log an flattened object of size
14
+ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw nm(t)&&console.error(h,{log:r,flattened:d}),new Error(h)}return JSON.parse(d)}catch(s){const o=ra(s);i[`${n}.error.message`]=o.message||"",i[`${n}.error.stack`]=o.stack||"",i[`${n}.error.reason`]=o.reason||"",i[`${n}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}const Es="chrome",om="opera",am="firefox",cm="iexplorer",dm="safari",lm="nwjs",um="electron",hm="react-native",Bd="unknown",na={Chrome:Es,Chromium:Es,Opera:om,Firefox:am,"Internet Explorer":cm,Safari:dm};function Fb(){const{userAgent:t}=navigator,e={name:Bd,version:void 0};if(t.match(/Chrome/)&&!t.match(/Edge/))if(t.match(/Edg(A?)/)){const r=t.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(r,10)>72&&(e.name=Es,e.version=r)}else e.name=Es,e.version=t.match(/Chrome\/([\d.]+)/)[1];return e}function Ub(){const{userAgent:t}=navigator;if(t.match(/Electron/)){const e=t.match(/Electron\/([\d.]+)/)[1];return{name:um,version:e}}return null}function Vb(){const{userAgent:t}=navigator;if(t.match(/JitsiMeetNW/)){const e=t.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:lm,version:e}}}function Bb(){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:hm,version:e}}function jb(t){let e;const r=[Bb,Ub,Vb];for(let i=0;i<r.length;i+=1)if(e=r[i](),e)return e;const n=t.getBrowserName();return n in na?{name:na[n],version:t.getBrowserVersion()}:(e=Fb(),e||{name:Bd,version:void 0})}class Hb{constructor(){m(this,"_bowser"),m(this,"_name"),m(this,"_version"),m(this,"getDeviceInfo",()=>({isMobile:this.isMobile(),browserName:this._bowser.getBrowserName(),osName:this._bowser.getOSName(),browserVersion:this._bowser.getBrowserVersion(),osVersionName:this._bowser.getOSVersion(),engineName:this._bowser.getEngineName()}))}init(e){let r,n;if(this._bowser=lu.getParser(navigator.userAgent),typeof e=="undefined"){const i=jb(this._bowser);r=i.name,n=i.version}else e.name in na?(r=na[e.name],n=e.version):(r=Bd,n=void 0);this._name=r,this._version=n}getName(){return this._name}isChrome(){return this._name===Es}isOpera(){return this._name===om}isFirefox(){return this._name===am}isIExplorer(){return this._name===cm}isSafari(){return this._name===dm}isNWJS(){return this._name===lm}isElectron(){return this._name===um}isReactNative(){return this._name===hm||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 Wb extends Hb{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(r){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(e=>e.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const e=navigator.userAgent;if(e.match(/Chrome/))return Number.parseInt(e.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const ye=new Wb,jd={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Ss={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"},$b={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 pm(t,e){const r=t.getValue("overrides");return r&&r[e]?r[e]:!1}function Gb({baseURI:t}){return t!=null&&t.includes("preprod.dyte")?ls.PREPROD:t!=null&&t.includes("devel.dyte")?ls.DEVEL:ls.PROD}function bi({servicePrefix:t,baseURI:e}){return`${t}.${e}`}function mm(t){const e=t.getValue("baseURI");return{location:bi({servicePrefix:"location",baseURI:e}),locationLegacy:bi({servicePrefix:"location-legacy",baseURI:e}),daCollector:bi({servicePrefix:"da-collector",baseURI:e})}}function Jb(t){const e=V({},t),r=new Map,n=(o,a)=>(r.has(o)||r.set(o,new Set),r.get(o).add(a),()=>{var d;return(d=r.get(o))==null?void 0:d.delete(a)}),i=(o,a)=>{var d;(d=r.get(o))==null||d.delete(a)},s=o=>{var a;(a=r.get(o))==null||a.forEach(d=>{try{d(e[o])}catch(h){l.error(`Error in notifying for "${o.toString()}"`,h)}})};return{subscribe:n,unsubscribe:i,notify:s,setValue:(o,a,d=!0)=>{e[o]=a,d&&s(o)},getValue:o=>e[o],getAllValues:()=>e}}class qb{constructor(){m(this,"contexts",new Map)}createContext(e,r){return this.contexts.has(e)?this.contexts.get(e):(this.contexts.set(e,Jb(r)),this.contexts.get(e))}remapContext(e,r){const n=r.getValue("peerId");n!==e&&(r.setValue("peerId",e),this.contexts.set(e,r),this.contexts.delete(n))}getContext(e){return this.contexts.get(e)}}const Ts=new qb,me=class{static get logsEndpoint(){const t=Ts.getContext(me.meetingMetadata.peerId);return`https://${bi({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}static resetPeerId(t){me.meetingMetadata.peerId=t}static init(t,e){const r=t.getValue("peerId");me.tracingEnabled=e,me.meetingMetadata.peerId=r,me.meetingMetadata.sdkVersion=t.getValue("sdkVersion"),me.meetingMetadata.deviceInfo=ye.getDeviceInfo(),me.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,navigator.isReactNative||document.addEventListener("visibilitychange",me.processCachedLogs),me.logsProcessorTimer=setInterval(me.processCachedLogs,me.logsProcessingInterval),e&&(me.initialized=!0)}static trace(t){return(e,r,n)=>{const i=n.value;return n.value=function(...s){if(!me.initialized||navigator.isReactNative||!me.tracingEnabled||K.hasFeature(X.SKIP_OTEL_TRACES))return i.apply(this,s);me.addLogInCurrentSpan("info",t);const o=performance.now(),a=i.apply(this,s);return Promise.resolve(a).then(()=>{const d=performance.now();d-o>10&&me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}).catch(()=>{const d=performance.now();me.addLogInCurrentSpan("info",`${t}_timing`,{execTime:d-o})}),a},n}}static injectContext(t){var e;const r=gn().replace(/-/g,"").substring(0,16),n=(e=me.meetingMetadata.peerId)==null?void 0:e.replace(/-/g,"");t.TRACEPARENT=`00-${n}-${r}-01`}static addLogInCurrentSpan(t,e,r={},n=!1){r!=null&&r.error&&Object.assign(r,{error:ra(r.error)});const i=Ts.getContext(me.meetingMetadata.peerId);if(nm(i)&&(Nb(r)?console[t]("DyteInternalLogs:: ",t,e):console[t]("DyteInternalLogs:: ",t,e,r)),!!xb(t))try{const s=sm(i,e,r,"metadata"),o=new Date,a=ne(V({message:e,level:t},s),{loggedAt:o.toISOString(),loggedAtTzOffset:o.getTimezoneOffset()});n?me.sendOtelLogsToNewRelic([a]):me.logsCache.push(a)}catch(s){me.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:ra(s)})}}static sendOtelLogsToNewRelic(t){const e=Ts.getContext(me.meetingMetadata.peerId);Jo.post(me.logsEndpoint,{meetingMetadata:sm(e,"sendOtelLogsToNewRelic",me.meetingMetadata,"meetingMetadata"),serviceName:e.getValue("sdkName"),logs:t}).catch(r=>{me.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:ra(r)}),me.logsCache.push(...t)})}static processCachedLogs(){const t=me.logsCache.splice(0,25);t!=null&&t.length&&me.sendOtelLogsToNewRelic(t)}static destruct(){clearInterval(me.logsProcessorTimer),me.processCachedLogs(),navigator.isReactNative||document.removeEventListener("visibilitychange",me.processCachedLogs)}};let y=me;m(y,"logsCache",[]),m(y,"logsProcessorTimer"),m(y,"tracingEnabled",!0),m(y,"initialized",!1),m(y,"logsProcessingInterval",7e3),m(y,"logExclusionList",["message","websocket/message","roomMessage","websocket/room-message","websocket/room-legacy-mode","chatMessage","websocket/new-chat-message","websocket/no-active-speaker","websocket/selected-peers","websocket/active-speaker","ping","websocket/new-consumer","websocket/producer-score","websocket/consumer-score","websocket/plugin-event","websocket/plugin-data","websocket/plugin-internal-data"]),m(y,"meetingMetadata",{});class l{static info(e,r,n){y.addLogInCurrentSpan("info",e,r,n)}static error(e,r,n){y.addLogInCurrentSpan("error",e,r,n)}static debug(e,r,n){y.addLogInCurrentSpan("debug",e,r,n)}static log(e,r,n){y.addLogInCurrentSpan("log",e,r,n)}static warn(e,r,n){y.addLogInCurrentSpan("warn",e,r,n)}}const Kb=()=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&l.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,n,i,s,o,a,d;l.error("window::unhandledrejection",{error:t==null?void 0:t.reason,networkCall:{url:(r=(e=t==null?void 0:t.reason)==null?void 0:e.config)==null?void 0:r.url,baseURL:(i=(n=t==null?void 0:t.reason)==null?void 0:n.config)==null?void 0:i.baseURL,method:(o=(s=t==null?void 0:t.reason)==null?void 0:s.config)==null?void 0:o.method,status:(a=t==null?void 0:t.reason)==null?void 0:a.status,statusText:(d=t==null?void 0:t.reason)==null?void 0:d.statusText}},!0)}),window.addEventListener("offline",()=>{l.info("window::offline")}),window.addEventListener("online",()=>{l.info("window::online")}))},zb={"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"},ia={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0100":"Internal exception","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0510":"Invalid channel name.","0600":"Internal exception","0700":"Internal exception","0800":"Internal exception","0900":"Internal exception",1e3:"Internal exception",1100:"Internal exception",1200:"Internal exception",1300:"Internal exception",1400:"Internal exception",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1701:"Crypto error",9900:"Internal exception"};Object.keys(ia).forEach(t=>{ia[t]=`{${zb[t.slice(0,2)]}} ${ia[t]}`});class C extends Error{constructor(e,r,n=!1){super(e),m(this,"code"),this.code=r,this.name="DyteError",this.message=`[ERR${this.code}]: ${ia[this.code]}
15
+ ${this.message}`;try{let i=n;r&&r.endsWith("00")&&(i=!0),i&&l.error("DyteError",{error:{message:this.message,name:this.name,code:r}})}catch(i){}}}function sa(t,e,r,n){if(n instanceof C){if(navigator.isReactNative||typeof reportError!="function")throw n;reportError(n)}else if(n instanceof e){const i=new C(n.message,r);throw i.stack=n.stack,i}else throw n}function fm(t,e,r){if(!t.value){const i=t.get,s=t.set;return i&&(t.get=function(){try{return i.apply(this)}catch(o){sa(this,e,r,o)}}),s&&(t.set=function(o){try{return s.apply(this,[o])}catch(a){sa(this,e,r,a)}}),t}const n=t.value;return t.value=function(...i){try{const s=n.apply(this,i);return s&&s instanceof Promise?s.catch(o=>{sa(this,e,r,o)}):s}catch(s){sa(this,e,r,s)}},t}function Yb(t,e){return(r,n,i)=>{if(i)return fm(i,t,e);for(const s of Reflect.ownKeys(r.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(r.prototype,s);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(r.prototype,s,fm(o,t,e))}}}const dt=t=>Yb(Error,t);function Qb(t){let e=0,r,n;if(!t)return e;for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),e=(e<<5)-e+n,e|=0;return Math.abs(e)%100+1}var Hr,Wr;const gm=class extends _t.EventEmitter{constructor(){super(),_(this,Hr,void 0),_(this,Wr,void 0),m(this,"asyncPromiseTimeout"),T(this,Hr,new Map),T(this,Wr,new Map),this.asyncPromiseTimeout=8e3}emitAsync(t,...e){return u(this,null,function*(){c(this,Hr).set(t,[]);const r=c(this,Wr).get(t).map(()=>new Promise(n=>{c(this,Hr).get(t).push(n)}));ly(gm.prototype,this,"emit").call(this,t,...e),yield Promise.race([Promise.all(r),new Promise((n,i)=>setTimeout(()=>i(new Error(`emitAsync failed to resolve for event ${t}.`)),this.asyncPromiseTimeout))]),c(this,Hr).delete(t)})}onAsync(t,e){const r=c(this,Hr),n=(...i)=>u(this,null,function*(){var s;try{yield e(...i)}catch(a){l.error("[onAsync]",{error:a})}const o=(s=r.get(t))==null?void 0:s.shift();o==null||o()});return c(this,Wr).get(t)||c(this,Wr).set(t,[]),c(this,Wr).get(t).push(n),super.on(t,n)}reset(){T(this,Hr,new Map),T(this,Wr,new Map),super.removeAllListeners()}};let Xb=gm;Hr=new WeakMap,Wr=new WeakMap;const b=new Xb;function Zb(){ye.isElectron()&&window.dyteElectronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=()=>u(this,null,function*(){const t=yield window.dyteElectronGetDisplayMediaSource({types:["window","screen"]});let e=[];if(t&&(Array.isArray(t)?e=t:e=[t]),!(e!=null&&e.length))throw new Error("Couldn't find any media source for screen share.");let r=e.find(i=>{var s;return(s=i.id)==null?void 0:s.includes("screen")});r=r!=null?r:e[0];const n={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:r.id}}};return yield navigator.mediaDevices.getUserMedia(n)}))}var Mt;(function(t){t[t.PUBLISHER=0]="PUBLISHER",t[t.SUBSCRIBER=1]="SUBSCRIBER"})(Mt||(Mt={}));var wt;(function(t){t[t.AUDIO=0]="AUDIO",t[t.VIDEO=1]="VIDEO"})(wt||(wt={}));class ew extends k{constructor(){super("media.Codec",[])}}new ew;class tw extends k{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new tw;class rw extends k{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Mt]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Kt=new rw;class nw extends k{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:()=>Kt}])}}const vm=new nw;class iw extends k{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8}])}}const Hd=new iw;class sw extends k{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const ym=new sw;class ow extends k{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}new ow;class aw extends k{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 cw=new aw;class dw extends k{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 lw=new dw;class uw extends k{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new uw;class hw extends k{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new hw;class pw extends k{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",wt]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const ks=new pw;class mw extends k{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks},{no:3,name:"producer_track",kind:"message",T:()=>lw}])}}const fw=new mw;class gw extends k{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>fw}}])}}const Em=new gw;class vw extends k{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 yw=new vw;class Ew extends k{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:()=>yw}])}}const Sm=new Ew;class Sw extends k{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const Tm=new Sw;class Tw extends k{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const km=new Tw;class kw extends k{constructor(){super("media.edge.ConsumeMultipleProducerRequest",[{no:1,name:"producer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8}])}}new kw;class _w extends k{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9}])}}const _m=new _w;class bw extends k{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:()=>Kt},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9}])}}const bm=new bw;class ww extends k{constructor(){super("media.edge.SelectedPeersRequest",[])}}new ww;class Cw extends k{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const wm=new Cw;class Iw extends k{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const $r=new Iw;class Rw extends k{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const oa=new Rw;class Pw extends k{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const Cm=new Pw;class Aw extends k{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>Kt}])}}const Im=new Aw;class Mw extends k{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Rm=new Mw;class Dw extends k{constructor(){super("media.edge.KickAllPeersRequest",[])}}const Pm=new Dw;class Ow extends k{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const Am=new Ow;class Nw extends k{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 Mm=new Nw;class Lw extends k{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 Dm=new Lw;class xw extends k{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 Fw=new xw;class Uw extends k{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const Vw=new Uw;class Bw extends k{constructor(){super("media.edge.EmptyResponse",[])}}new Bw;class jw extends k{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>ks},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9}])}}const Om=new jw;class Hw extends k{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 Wd=new Hw;class Ww extends k{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const $w=new Ww;class Gw extends k{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>$w}])}}const Nm=new Gw;class Jw extends k{constructor(){super("media.edge.PeerJoinResponse",[])}}new Jw;class qw extends k{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Fw},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Om},{no:3,name:"selected_peers",kind:"message",T:()=>Wd},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const aa=new qw;class Kw extends k{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Lm=new Kw;class zw extends k{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Em}])}}new zw;class Yw extends k{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Em},{no:3,name:"description",kind:"message",T:()=>Kt}])}}const xm=new Yw;class Qw extends k{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:()=>Kt}])}}const Fm=new Qw;class Xw extends k{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>cw}])}}new Xw;class Zw extends k{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new Zw;class e0 extends k{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new e0;class t0 extends k{constructor(){super("media.edge.ProducerToggleResponse",[])}}new t0;class r0 extends k{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new r0;class n0 extends k{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Kt}])}}const Um=new n0;class i0 extends k{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Kt}])}}new i0;class s0 extends k{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new s0;class o0 extends k{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Vm=new o0;class a0 extends k{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Bm=new a0;class c0 extends k{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const jm=new c0;class d0 extends k{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Hm=new d0;class l0 extends k{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const Wm=new l0;class u0 extends k{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Om}])}}const $m=new u0;class h0 extends k{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Hd}])}}new h0;class p0 extends k{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const Gm=new p0;class m0 extends k{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const Jm=new m0;class f0 extends k{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>ks}])}}const qm=new f0;class g0 extends k{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ca=new g0;class v0 extends k{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Km=new v0;class y0 extends k{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new y0;class E0 extends k{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new E0;class S0 extends k{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new S0;class T0 extends k{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new T0;class k0 extends k{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new k0;class _0 extends k{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new _0;class b0 extends k{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 $d=new b0;class w0 extends k{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 w0;class C0 extends k{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const I0=new C0;var da;(function(t){t[t.BROWSER=0]="BROWSER",t[t.TRACK=1]="TRACK",t[t.COMPOSITE=2]="COMPOSITE"})(da||(da={}));var Tr;(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"})(Tr||(Tr={}));var Gd;(function(t){t[t.NONE=0]="NONE",t[t.RECORDER=1]="RECORDER",t[t.LIVESTREAMER=2]="LIVESTREAMER"})(Gd||(Gd={}));var la;(function(t){t[t.HIVE=0]="HIVE",t[t.CHAT=1]="CHAT",t[t.PING=2]="PING"})(la||(la={}));class R0 extends k{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 P0=new R0;class A0 extends k{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",Tr,"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:()=>P0}])}}const ua=new A0;class M0 extends k{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>ua}])}}const wi=new M0;class D0 extends k{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",Tr,"STAGE_TYPE_"]}])}}const zm=new D0;class O0 extends k{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 N0=new O0;class L0 extends k{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>ua}])}}const Jd=new L0;class x0 extends k{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Ym=new x0;class F0 extends k{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:()=>V0},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Qm=new F0;class U0 extends k{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",da]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const V0=new U0;class B0 extends k{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Qm}])}}const Xm=new B0;class j0 extends k{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Zm=new j0;class H0 extends k{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 H0;class W0 extends k{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ua},{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",la,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const $0=new W0;class G0 extends k{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>ua},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const J0=new G0;class q0 extends k{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Qm}])}}new q0;class K0 extends k{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new K0;class z0 extends k{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 qd=new z0;class Y0 extends k{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 Q0=new Y0;class X0 extends k{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:()=>Q0}])}}const ef=new X0;class Z0 extends k{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>ef},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>ef}])}}const eC=new Z0;class tC extends k{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const rC=new tC;class nC extends k{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rC}])}}const iC=new nC;class sC extends k{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:()=>qd}])}}const oC=new sC;class aC extends k{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>oC}])}}const tf=new aC;class cC extends k{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 dC=new cC;class lC extends k{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>dC}])}}new lC;class uC extends k{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const hC=new uC;class pC extends k{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>hC}])}}const mC=new pC;class fC extends k{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>yC}])}}const gC=new fC;class vC extends k{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:()=>qd}])}}const yC=new vC;class EC extends k{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 SC=new EC;class TC extends k{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:()=>SC}])}}const kC=new TC;class _C extends k{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:()=>qd}])}}const rf=new _C;class bC extends k{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>rf}])}}new bC;class wC extends k{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 CC=new wC;class IC extends k{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>AC}])}}const RC=new IC;class PC extends k{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 AC=new PC;class MC extends k{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const DC=new MC;class OC extends k{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const ha=new OC;class NC extends k{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const LC=new NC;class xC extends k{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const FC=new xC;class UC extends k{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9}])}}const VC=new UC;class BC extends k{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>VC}])}}const nf=new BC;class jC extends k{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 sf=new jC;var Kd;(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"})(Kd||(Kd={}));var pa;(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"})(pa||(pa={}));class HC extends k{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 WC=new HC;class $C extends k{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 GC=new $C;class JC extends k{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 qC=new JC;class KC extends k{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 zC=new KC;class YC extends k{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>qC},{no:2,name:"private",kind:"message",T:()=>zC}])}}const QC=new YC;class XC extends k{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 ZC=new XC;class eI extends k{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",pa,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",pa,"STREAM_PERMISSION_TYPE_"]}])}}const zd=new eI;class tI extends k{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>zd},{no:2,name:"audio",kind:"message",T:()=>zd},{no:3,name:"screenshare",kind:"message",T:()=>zd}])}}const rI=new tI;class nI extends k{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>WC},{no:2,name:"plugins",kind:"message",T:()=>GC},{no:3,name:"chat",kind:"message",T:()=>QC},{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",Kd,"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",Gd,"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:()=>ZC},{no:23,name:"media",kind:"message",T:()=>rI}])}}const Yd=new nI;class iI extends k{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const sI=new iI;class oI extends k{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 aI=new oI;class cI extends k{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>aI}])}}const dI=new cI;class lI extends k{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Yd}])}}const of=new lI;class uI extends k{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>of}])}}const hI=new uI;class pI extends k{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>of}])}}const af=new pI;class mI extends k{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const fI=new mI;class gI extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>fI},{no:2,name:"patch",kind:"message",T:()=>Yd}])}}new gI;class vI extends k{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Yd}])}}new vI;class yI extends k{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 bn=new yI;class EI extends k{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 SI=new EI;class TI extends k{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>bn},{no:2,name:"next",kind:"scalar",T:8}])}}const kI=new TI;class _I extends k{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>bn}])}}const cf=new _I;class bI extends k{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const wI=new bI;class CI extends k{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const Qd=new CI;class II extends k{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 RI=new II;class PI extends k{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const Xd=new PI;class AI extends k{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 MI=new AI;class DI extends k{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}new DI;class OI extends k{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 NI=new OI;class LI extends k{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 xI=new LI;class FI extends k{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 ma=new FI;class UI extends k{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>bn}])}}const fa=new UI;class VI extends k{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 BI=new VI;class jI extends k{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 ga=new jI;class HI extends k{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 WI=new HI;class $I extends k{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 GI=new $I;class JI extends k{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}const qI=new JI;class KI extends k{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 zI=new KI;class YI extends k{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 QI=new YI;class XI extends k{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new XI;class ZI extends k{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}const eR=new ZI;class tR extends k{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>bn},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const rR=new tR;class nR extends k{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:()=>rR},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const iR=new nR;class sR extends k{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>iR}])}}const kr=new sR;class oR extends k{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 aR=new oR;class cR extends k{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>aR}])}}const dR=new cR;class lR extends k{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const uR=new lR;class hR extends k{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const pR=new hR;class mR extends k{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const fR=new mR;class gR extends k{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const vR=new gR;class yR extends k{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 ER=new yR;class SR extends k{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 TR=new SR;class kR extends k{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const _R=new kR;class bR extends k{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 wR=new bR;class CR extends k{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 Zd=new CR;class IR extends k{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:()=>Zd}])}}const df=new IR;class RR extends k{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:()=>Zd}])}}const PR=new RR;class AR extends k{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:()=>Zd}])}}const MR=new AR;class DR extends k{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}const OR=new DR;class NR extends k{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const el=new NR;class LR extends k{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>el}])}}const xR=new LR;class FR extends k{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}const lf=new FR;class UR extends k{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 VR=new UR;class BR extends k{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:()=>VR}])}}const uf=new BR;class jR extends k{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}const hf=new jR;class HR extends k{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9}])}}const pf=new HR;class WR extends k{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const mf=new WR;class $R extends k{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 GR=new $R;class JR extends k{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>GR}])}}const tl=new JR;class qR extends k{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const KR=new qR;class zR extends k{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const YR=new zR;class QR extends k{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ff=new QR;class XR extends k{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:()=>eP},{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 gf=new XR;class ZR extends k{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:()=>rP}])}}const eP=new ZR;class tP extends k{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const rP=new tP;class nP extends k{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 iP=new nP;class sP extends k{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 oP=new sP;class aP extends k{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>gf}])}}const rl=new aP;class cP extends k{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>gf}])}}const dP=new cP;class lP extends k{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",da]}])}}const vf=new lP;class uP extends k{constructor(){super("google.protobuf.Timestamp",[{no:1,name:"seconds",kind:"scalar",T:3,L:0},{no:2,name:"nanos",kind:"scalar",T:5}])}now(){const e=this.create(),r=Date.now();return e.seconds=_e.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}toDate(e){return new Date(_e.from(e.seconds).toNumber()*1e3+Math.ceil(e.nanos/1e6))}fromDate(e){const r=this.create(),n=e.getTime();return r.seconds=_e.from(Math.floor(n/1e3)).toBigInt(),r.nanos=n%1e3*1e6,r}internalJsonWrite(e,r){let n=_e.from(e.seconds).toNumber()*1e3;if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw new Error("Unable to encode Timestamp to JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");if(e.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(e.nanos>0){let s=(e.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(n).toISOString().replace(".000Z",i)}internalJsonRead(e,r,n){if(typeof e!="string")throw new Error("Unable to parse Timestamp from JSON "+Bc(e)+".");let i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("Unable to parse Timestamp from JSON. Invalid format.");let s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new globalThis.Error("Unable to parse Timestamp from JSON. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.");return n||(n=this.create()),n.seconds=_e.from(s/1e3).toBigInt(),n.nanos=0,i[7]&&(n.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),n}}new uP;class Ci extends _t.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}class Dt extends _t.EventEmitter{constructor(){super(),super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.on(e,r)}addListener(e,r){try{const n=this.listenerCount(e);n>25&&n%25===0&&l.warn("DyteEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}})}catch(n){}return super.addListener(e,r)}off(e,r){return super.off(e,r)}once(e,r){return super.once(e,r)}prependListener(e,r){return super.prependListener(e,r)}prependOnceListener(e,r){return super.prependOnceListener(e,r)}removeListener(e,r){return super.removeListener(e,r)}removeAllListeners(e){return super.removeAllListeners(e)}listeners(e){return super.listeners(e)}listenerCount(e){return super.listenerCount(e)}}const hP=0,pP=1,mP=2,fP=3,gP=4,vP=5,yP={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToPeers:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43},EP={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,sendMessageToChannel:6,searchChannelMessages:7,getAllChatChannels:8,markChannelIndexAsRead:9,pinMessage:10},SP={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},TP={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},yf={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},kP={createChatChannel:0,getChatChannel:1,deprecatedGetAllChatChannels:2,getChannelMembers:3,updateChatChannel:4},_P={getUserPresets:0,updateUserPreset:1};function Ii(t,e){return Object.keys(e).reduce((r,n)=>(r[n]=(t<<16)+e[n],r),{})}function Ef(t,e){return Object.keys(t).reduce((r,n)=>(r[n]=e|t[n],r),{})}const j=Ii(hP,yP),De=Ii(pP,EP),J=Ii(mP,SP),_r=Ii(fP,TP),wn=Ii(gP,kP),ie=Ef(yf,16777216),se=Ef(yf,50331648),va=Ii(vP,_P);var bP=Object.defineProperty,wP=Object.getOwnPropertyDescriptor,nl=(t,e,r,n)=>{for(var i=n>1?void 0:n?wP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&bP(e,r,i),i},Cn,Sf;const il=(Sf=class{constructor(t){_(this,Cn,void 0),T(this,Cn,t)}createChannel(t,e,r,n="public",i=!1){return u(this,null,function*(){const s={displayName:t,targetUserIds:e,displayPictureUrl:r,visibility:n,isDirectMessage:i};i&&(s.visibility="private");const o=yield c(this,Cn).sendMessagePromise(wn.createChatChannel,zI.toBinary(s)),a=kr.fromBinary(o.payload).chatChannels;return il.formatChannel(a[0])})}updateChannel(t,e){return u(this,null,function*(){const r=yield c(this,Cn).sendMessagePromise(wn.updateChatChannel,QI.toBinary({chatChannelId:t,targetUserIds:e.memberIds,displayName:e.displayName,displayPictureUrl:e.displayPictureUrl,visibility:e.visibility})),n=kr.fromBinary(r.payload).chatChannels;return il.formatChannel(n[0])})}static formatChannel(t){var e;const{latestMessageAndUnreadCount:r}=t,n=ne(V({},t),{id:t.chatChannelId,memberIds:t.targetUserIds,unreadCount:(e=r==null?void 0:r.unreadCount)!=null?e:0});return r!=null&&r.message&&(n.latestMessage=wr.formatSocketServiceMessage(r.message)),delete n.chatChannelId,delete n.targetUserIds,delete n.latestMessageAndUnreadCount,n}getChannelMembers(t){return u(this,null,function*(){try{const e=yield c(this,Cn).sendMessagePromise(wn.getChannelMembers,eR.toBinary({chatChannelId:t}));return dR.fromBinary(e.payload).channelMembers.map(r=>{var n=r,{id:i}=n,s=Ro(n,["id"]);return ne(V({},s),{userId:i})})}catch(e){return[]}})}on(t,e){let r,n;switch(t){case wn.createChatChannel:{r=kr.fromBinary.bind(kr),n=kr.create();break}case wn.updateChatChannel:{r=kr.fromBinary.bind(kr),n=kr.create();break}}if(!r){l.warn(`ChatChannelSocketHandler::Event ${t} is not recognized`);return}c(this,Cn).on(t,({payload:i})=>{let s=n;try{s=r(i)}catch(o){l.error("ChatChannelSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}},Cn=new WeakMap,Sf);let In=il;nl([y.trace("ChatChannelHandler.createChannel")],In.prototype,"createChannel",1),nl([y.trace("ChatChannelHandler.updateChannel")],In.prototype,"updateChannel",1),nl([y.trace("ChatChannelHandler.getChannelMembers")],In.prototype,"getChannelMembers",1);var CP=Object.defineProperty,IP=Object.getOwnPropertyDescriptor,zt=(t,e,r,n)=>{for(var i=n>1?void 0:n?IP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&CP(e,r,i),i},mt=(t=>(t[t.TEXT=0]="TEXT",t[t.IMAGE=1]="IMAGE",t[t.FILE=2]="FILE",t[t.CUSTOM=3]="CUSTOM",t))(mt||{}),ft;class Bt{constructor(e){_(this,ft,void 0),T(this,ft,e)}getChatMessages(){return c(this,ft).sendMessagePromise(De.getMessages)}getChatMessagesPaginated(e,r,n,i=0,s=""){return u(this,null,function*(){const o={timeStamp:e,size:r,from:i,reversed:n,channelId:s},a=yield c(this,ft).sendMessagePromise(De.getPaginatedMessages,SI.toBinary(o));return a.payload?kI.fromBinary(a.payload):{messages:[],next:!1}})}sendMessageToRoom(e,r){const n={payloadType:r,payload:e};c(this,ft).sendMessage(De.sendMessageToRoom,wI.toBinary(n))}sendMessageToPeers(e,r,n){const i={payloadType:r,peerIds:n,payload:e};c(this,ft).sendMessage(De.sendMessageToPeers,RI.toBinary(i))}sendMessageToChannel(e,r,n){const i={payloadType:r,channelId:n,payload:e};c(this,ft).sendMessage(De.sendMessageToChannel,MI.toBinary(i))}sendMessage(e,r,n,i){if(i&&this.sendMessageToChannel(e,r,i),n&&n.length>0){this.sendMessageToPeers(e,r,n);return}this.sendMessageToRoom(e,r)}editMessage(e,r,n,i,s){return u(this,null,function*(){const o={chatId:e,payloadType:n,payload:r};i&&(o.channelId=i),s!==void 0&&(o.pinned=s);const a=yield c(this,ft).sendMessagePromise(De.editMessage,NI.toBinary(o));return fa.fromBinary(a.payload).message})}deleteMessage(e,r){return u(this,null,function*(){const n={chatId:e};r&&(n.channelId=r);const i=yield c(this,ft).sendMessagePromise(De.deleteMessage,BI.toBinary(n)),s=ga.fromBinary(i.payload);return V({id:s.chatId},s.channelId?{channelId:s.channelId}:{})})}searchMessages(e,r){return u(this,null,function*(){var n,i,s;const o={searchTerm:e,timeStamp:(n=r.timestamp)!=null?n:Date.now(),size:(i=r.size)!=null?i:75,from:0,reversed:(s=r.reversed)!=null?s:!0};r.channelId&&(o.channelId=r.channelId);try{const a=yield c(this,ft).sendMessagePromise(De.searchChannelMessages,WI.toBinary(o));return cf.fromBinary(a.payload).messages}catch(a){return[]}})}getAllChannels(){return u(this,null,function*(){try{const e=yield c(this,ft).sendMessagePromise(De.getAllChatChannels);return kr.fromBinary(e.payload).chatChannels.map(In.formatChannel)}catch(e){return[]}})}markLastReadMessage(e,r){return u(this,null,function*(){const n=yield c(this,ft).sendMessagePromise(De.markChannelIndexAsRead,GI.toBinary({channelId:e,userId:r.userId,channelIndex:r.channelIndex}));return qI.fromBinary(n.payload).channelIndex})}setPinState(e,r){return u(this,null,function*(){const n={chatId:e.id,pinned:r,channelId:e.channelId},i=yield c(this,ft).sendMessagePromise(De.pinMessage,xI.toBinary(n));return ma.fromBinary(i.payload)})}on(e,r){let n,i;switch(e){case De.sendMessageToRoom:{n=Qd.fromBinary.bind(Qd),i=Qd.create();break}case De.sendMessageToPeers:{n=Xd.fromBinary.bind(Xd),i=Xd.create();break}case De.editMessage:{n=fa.fromBinary.bind(fa),i=fa.create();break}case De.pinMessage:{n=ma.fromBinary.bind(ma),i=ma.create();break}case De.deleteMessage:{n=ga.fromBinary.bind(ga),i=ga.create();break}}if(!n){l.warn(`ChatSocketHandler::Event ${e} is not recognized`);return}c(this,ft).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}ft=new WeakMap,zt([y.trace("SocketService.getChatMessages")],Bt.prototype,"getChatMessages",1),zt([y.trace("SocketService.getChatMessagesPaginated")],Bt.prototype,"getChatMessagesPaginated",1),zt([y.trace("SocketService.sendMessageToRoom")],Bt.prototype,"sendMessageToRoom",1),zt([y.trace("SocketService.sendMessageToPeers")],Bt.prototype,"sendMessageToPeers",1),zt([y.trace("SocketService.sendMessageToChannel")],Bt.prototype,"sendMessageToChannel",1),zt([y.trace("SocketService.sendMessage")],Bt.prototype,"sendMessage",1),zt([y.trace("SocketService.editMessage")],Bt.prototype,"editMessage",1),zt([y.trace("SocketService.deleteMessage")],Bt.prototype,"deleteMessage",1),zt([y.trace("SocketService.searchMessages")],Bt.prototype,"searchMessages",1),zt([y.trace("SocketService.getAllChannels")],Bt.prototype,"getAllChannels",1),zt([y.trace("SocketService.markLastReadMessage")],Bt.prototype,"markLastReadMessage",1);function RP(t){return t.replace(/([-_]\w)/g,e=>e[1].toUpperCase())}function dr(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>dr(r));const e={};return Object.keys(t).forEach(r=>{const n=Uc(r)?r:RP(r);e[n]=dr(t[r])}),e}function PP(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Tf(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Tf(r));const e={};return Object.keys(t).forEach(r=>{const n=Uc(r)?r:PP(r);e[n]=t[r]}),e}function ya(t,e={}){return t==null?{}:(Object.getOwnPropertyNames(t).forEach(r=>{if(typeof t[r]!="function"){if(typeof t[r]=="object"){ya(t[r],e[r]={});return}e[r]=t[r]}}),e)}const AP=3,MP=30,DP=8e3;class OP{constructor(e,r){m(this,"ipInfo"),m(this,"axios"),m(this,"requests"),m(this,"roomName"),m(this,"roomUUID"),m(this,"authToken"),m(this,"organizationId"),m(this,"iceServers"),m(this,"pluginInformation"),m(this,"userDetails"),m(this,"roomDetails"),m(this,"context"),this.context=e;const{timeout:n=DP,retry:i=AP,retryDelay:s=MP,baseURL:o="https://api.cluster.dyte.in",authToken:a,cachedUserDetails:d}=r||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=Jo.create({baseURL:o,responseType:"json",timeout:n,retry:i,retryDelay:s}),this.axios=Jo,this.setAuthToken(a,{bearer:!0}),this.requests.interceptors.request.use(h=>(y.injectContext(this.requests.defaults.headers.common),h),h=>u(this,null,function*(){l.error("xhr::axios",{debuggingHint:"otelRequestInterceptor failed.",error:h})})),this.requests.interceptors.response.use(h=>{try{h.config.url!==y.logsEndpoint&&l.debug("xhr::axios",{networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,method:h.config.method}})}catch(p){console.error("xhr::dyte",{error:"responseInterceptorFailed",err:p,response:h})}return h},h=>u(this,null,function*(){var p;try{if(!h)return Promise.reject(new C("Unknown network error occurred","0011"));h&&h.config&&((p=h.config)==null?void 0:p.url)!==y.logsEndpoint&&l.error("xhr::axios",{error:h,networkCall:{status:h.status,statusText:h.statusText,baseURL:h.config.baseURL,url:h.config.url,retries:h.config.retry,method:h.config.method,isOnline:navigator.onLine?"online":"offline"}});const{config:f,message:g}=h;return f&&g&&f.retry!==void 0&&f.retry>0&&(g.includes("timeout")||g.includes("Network Error"))?(f.retry-=1,this.requests(f)):Promise.reject(new C(g,"0011"))}catch(f){return console.error("xhr::dyte",{error:"responseInterceptorFailed",err:f,responseError:h}),Promise.reject(new C(f.message,"0011"))}}))}get peerId(){return this.context.getValue("peerId")}setAuthToken(e,r){const{bearer:n}=r||{};this.authToken=e,this.requests.defaults.headers.common.Authorization=n?`Bearer ${e}`:e}setHeader(e,r){this.requests.defaults.headers.common[e]=r}setRoomName(e){this.roomName=e}setRoomUUID(e){this.roomUUID=e}setOrganizationId(e){this.organizationId=e}}var NP=Object.defineProperty,LP=Object.getOwnPropertyDescriptor,sl=(t,e,r,n)=>{for(var i=n>1?void 0:n?LP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&NP(e,r,i),i};class Ea extends OP{constructor(e,r){super(e,r),this.setHeader("x-dyte-web-core-version",e.getValue("sdkVersion"))}getIPDetails(){return u(this,null,function*(){var e;const{peerId:r}=this;try{const n=yield Zc.getIPDetails({peerId:r,apiHostnames:mm(this.context)});if(l.log("ipInfo",{ipInfo:n}),((e=n.loc)==null?void 0:e.length)>5)return n;throw Error("Insufficient data")}catch(n){l.warn("ApiClient.getRoomNodeLinkAndTitleV1 Failed to get ip details",{error:{name:n.name,message:n.message}});return}})}getICEServers(){return u(this,null,function*(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(yield this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r})}getPlugins(){return u(this,null,function*(){var e,r,n,i,s,o,a;if(this.pluginInformation)return this.pluginInformation;let{plugins:d}=(yield this.requests.get("/v2/plugins/user")).data.data;const h=((r=(e=K.getValue(X.V1_PLUGINS))==null?void 0:e.toString())==null?void 0:r.split(","))||[];return d=d.reduce((p,f)=>(p[h.includes(f.id)?"v1":"v2"].push(f),p),{v1:[],v2:[]}).v2,(s=(i=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:i.plugins)!=null&&s.length&&((a=(o=this.context.getValue("modules"))==null?void 0:o.devTools)==null||a.plugins.forEach(p=>{var f,g,E;const v=ne(V({},Ss),{tags:[...Ss.tags]});v.baseURL=`http://localhost:${p.port}`,v.name=p.name,v.picture=(f=p.picture)!=null?f:Ss.picture,v.description=(g=p.description)!=null?g:Ss.description,v.staggered=(E=p.staggered)!=null?E:Ss.staggered,v.createdAt=new Date().toISOString(),v.updatedAt=new Date().toISOString(),v.id=p.id,v.organizationId=this.organizationId,d.push(v)})),d})}getPluginDetails(e){return u(this,null,function*(){const{plugin:r}=(yield this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r})}getPluginConfig(e){return u(this,null,function*(){return(yield this.axios.get(`${e}/dyte-config.json`)).data})}authorizePlugin(e){return u(this,null,function*(){const r={peerId:this.peerId},{token:n}=(yield this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return n})}getPresignedUrls(e,r){return u(this,null,function*(){const n={roomUUID:this.roomUUID,filename:e};K.hasFeature(X.FEAT_CHAT_SDK)&&(n.viewType=r);const{getLocation:i,putLocation:s}=(yield this.requests.post("/v1/meetings/genPreSignedUploadUrl",n)).data.data;return{getLocation:i,putLocation:s}})}uploadFile(e,r){return u(this,null,function*(){if(navigator.isReactNative&&"uri"in e)try{yield fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(n){l.error(`sendFileMessage::${n}`)}else yield this.axios.put(r,e,{headers:{"Content-Type":e.type}})})}}sl([y.trace("APIClient.getIPDetails")],Ea.prototype,"getIPDetails",1),sl([y.trace("APIClient.getICEServers")],Ea.prototype,"getICEServers",1),sl([y.trace("APIClient.getPlugins")],Ea.prototype,"getPlugins",1);var xP=Object.defineProperty,FP=Object.getOwnPropertyDescriptor,br=(t,e,r,n)=>{for(var i=n>1?void 0:n?FP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&xP(e,r,i),i};class lr extends Ea{startLivestreaming(){return u(this,null,function*(){var e,r;return(r=(e=(yield this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`)).data)==null?void 0:e.data)==null?void 0:r.playback_url})}stopLivestreaming(){return u(this,null,function*(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)})}getActiveLivestream(){return u(this,null,function*(){const{playbackUrl:e,status:r}=dr((yield this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{status:r,playbackUrl:e}})}getUserDetails(){return u(this,null,function*(){if(this.userDetails)return this.userDetails;const e=(yield this.requests.get("v2/internals/participant-details")).data.data;return dr(e)})}startRecording(e,r){return u(this,null,function*(){return(yield this.requests.post("/v2/recordings",ne(V({},Tf(e)),{meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r}))).data.data.id})}updateRecording(e,r){return u(this,null,function*(){return this.requests.put(`v2/recordings/${e}`,{action:r})})}getActiveRecording(){return u(this,null,function*(){const{status:e,id:r}=(yield this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}})}getActiveTranscript(){return u(this,null,function*(){const{transcript_download_url:e}=(yield this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(yield this.axios.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url")}})}getRoomNodeData(){return u(this,null,function*(){if(this.roomDetails)return this.roomDetails;const e=yield this.getIPDetails();this.ipInfo=e;const{roomNodeLink:r,title:n,useHiveMedia:i,sfu:s}=dr((yield this.requests.post("v2/internals/rooms",{ip_information:e})).data.data);return{roomNodeUrl:r,meetingTitle:n,useHiveMedia:i!=null?i:!1,sfu:s}})}}br([y.trace("APIClient.startLivestreaming")],lr.prototype,"startLivestreaming",1),br([y.trace("APIClient.stopLivestreaming")],lr.prototype,"stopLivestreaming",1),br([y.trace("APIClient.getActiveLivestream")],lr.prototype,"getActiveLivestream",1),br([y.trace("APIClient.getUserDetails")],lr.prototype,"getUserDetails",1),br([y.trace("APIClient.startRecording")],lr.prototype,"startRecording",1),br([y.trace("APIClient.stopRecording")],lr.prototype,"updateRecording",1),br([y.trace("APIClient.getActiveRecording")],lr.prototype,"getActiveRecording",1),br([y.trace("APIClient.getActiveTranscript")],lr.prototype,"getActiveTranscript",1),br([y.trace("APIClient.getRoomNodeData")],lr.prototype,"getRoomNodeData",1);let ol;function UP(t,e){return ol=new lr(t,e),ol}function je(){return ol}function VP(t,e){return`<blockquote>${e.replace(/<blockquote>[.\s\S]*<\/blockquote>\n\n/m,"")}</blockquote>
16
+
17
+ ${t}`}function Ct(t){return function(e,r,n){const i=n.value;let s=0,o=Date.now();return n.value=function(...a){const d=Date.now();if(d-o>t.period*1e3&&(o=d,s=0),s>=t.maxInvocations)throw new C(`Method rate limit ${t.maxInvocations} invocations/${t.period}sec exceeded`);return s+=1,i.apply(this,a)},n}}var BP=Object.defineProperty,jP=Object.getOwnPropertyDescriptor,lt=(t,e,r,n)=>{for(var i=n>1?void 0:n?jP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&BP(e,r,i),i};const HP=["text","image","file","custom","poll"],Sa={maxInvocations:180,period:60};var re,Ri,qe,Pi,Ta,al,kf,_f;let Ze=(_f=class extends Dt{constructor(t,e,r,n,i){super(),_(this,al),m(this,"messages"),m(this,"channels",[]),_(this,re,void 0),_(this,Ri,void 0),_(this,qe,void 0),_(this,Pi,void 0),_(this,Ta,void 0),m(this,"maxTextLimit",2e3),T(this,Ta,t),T(this,qe,e),T(this,Pi,r),T(this,re,n),T(this,Ri,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}get roomJoined(){var t;return((t=c(this,al,kf))==null?void 0:t.roomJoined)===!0}sendMessageInternal(t,e,r){return u(this,arguments,function*(n,i,s,o={}){switch(n.type){case"text":{const a=o.replyTo&&o.replyTo.type==="text"?VP(n.message,o.replyTo.message):n.message;yield this.sendTextMessageInternal(a,i,s);break}case"image":yield this.sendImageMessageInternal(n.image,i,s);break;case"file":yield this.sendFileMessageInternal(n.file,i,s);break;default:l.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:n.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(t.length>this.maxTextLimit)throw new C("Max character limit breached");if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text))throw l.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text))throw l.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw l.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");if(r){c(this,qe).sendMessageToChannel(t,mt.TEXT,r);return}let h=[];e&&e.length>0&&(e.push(c(this,re).id),h=c(this,Ri).joined.toArray().filter(p=>e.includes(p.id)).map(p=>p.userId),h.push(c(this,re).userId)),c(this,qe).sendMessage(t,mt.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendImageMessage::permission_denied");return}if(!t){l.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const h=je(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,qe).sendMessageToChannel(p,mt.IMAGE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,Ri).joined.toArray().filter(E=>e.includes(E.id)).map(E=>E.userId),g.push(c(this,re).userId)),c(this,qe).sendMessage(p,mt.IMAGE,e)}catch(h){throw new C("Error sending image message.")}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(e&&e.length>0){if(!((n=c(this,re).permissions)!=null&&n.chatPrivate.canSend)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.files)){l.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)){l.error("sendFileMessage::permission_denied");return}if(!t){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const h=je(),{getLocation:p,putLocation:f}=yield h.getPresignedUrls(t.name,c(this,re).config.viewType);if(yield h.uploadFile(t,f),r){c(this,qe).sendMessageToChannel(JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0}),mt.FILE,r);return}let g=[];e&&e.length>0&&(e.push(c(this,re).id),g=c(this,Ri).joined.toArray().filter(v=>e.includes(v.id)).map(v=>v.userId),g.push(c(this,re).userId));const E=JSON.stringify({link:p,name:t.name,size:"size"in t?t.size:0});c(this,qe).sendMessage(E,mt.FILE,e)}catch(h){throw new C("Error sending file message.")}})}get rateLimits(){return Sa}updateRateLimits(t,e){Sa.maxInvocations=t,Sa.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,n,i,s,o,a,d,h,p,f,g,E,v,R,A;if(e&&e.length>0){if(!((r=c(this,re).permissions)!=null&&r.chatPrivate.canSend)||!((n=c(this,re).permissions)!=null&&n.chatPrivate.files)||!((i=c(this,re).permissions)!=null&&i.chatPrivate.text)){l.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.files)||!((p=(h=c(this,re).permissions)==null?void 0:h.chatPublic)!=null&&p.text)){l.error("sendCustomMessage::permission_denied");return}const L=W=>u(this,null,function*(){try{if(typeof W=="string")return{link:W};const H=je(),{getLocation:I,putLocation:S}=yield H.getPresignedUrls(W.name,c(this,re).config.viewType);return yield H.uploadFile(W,S),{link:I,type:W.type,name:W.name,size:W.size}}catch(H){throw new C("Error sending image message.")}}),F=ne(V({},t),{files:yield Promise.all((g=(f=t.files)!=null?f:[])==null?void 0:g.map(W=>u(this,null,function*(){return L(W)}))),images:yield Promise.all((v=(E=t.images)!=null?E:[])==null?void 0:v.map(W=>u(this,null,function*(){return L(W)}))),videos:yield Promise.all((A=(R=t.videos)!=null?R:[])==null?void 0:A.map(W=>u(this,null,function*(){return L(W)})))});c(this,qe).sendMessage(JSON.stringify(F),mt.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var n,i,s,o,a,d;if(((i=(n=c(this,re).permissions)==null?void 0:n.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new C("Not permitted to edit messages","0501");if(!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(a=c(this,re).permissions)==null?void 0:a.chatPublic)!=null&&d.text)){l.error("editTextMessage::permission_denied");return}if(!e){l.error("editTextMessage::message_can_not_be_empty");return}c(this,qe).editMessage(t,e,mt.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("editImageMessage::permission_denied");return}if(!e){l.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){l.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const a=je(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,qe).editMessage(t,d,mt.IMAGE,r)}catch(a){throw new C("Error editing image message.")}})}editFileMessage(t,e,r){return u(this,null,function*(){var n,i,s,o;if(!((i=(n=c(this,re).permissions)==null?void 0:n.chatPublic)!=null&&i.canSend)||!((o=(s=c(this,re).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){l.error("sendFileMessage::permission_denied");return}if(!e){l.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const a=je(),{getLocation:d,putLocation:h}=yield a.getPresignedUrls(e.name,c(this,re).config.viewType);yield a.uploadFile(e,h),c(this,qe).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),mt.FILE,r)}catch(a){throw new C("Error editing file message.")}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{l.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,n;if(((n=(r=c(this,re).permissions)==null?void 0:r.chatMessage)==null?void 0:n.canDelete)==="NONE")throw new C("Not permitted to delete messages","0501");c(this,qe).deleteMessage(t,e)})}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}pin(t){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to pin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,qe).setPinState(e,!0);return}throw new C(`No message found with id: ${t}`)})}unpin(t){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin message without joining room");if(!c(this,re).permissions.pinParticipant)throw new C("You do not have permission to unpin messages.");const e=this.messages.find(r=>r.id===t);if(e){c(this,qe).setPinState(e,!1);return}throw new C(`No message found with id: ${t}`)})}getMessages(t,e,r,n=0,i=void 0){return u(this,null,function*(){const s=yield c(this,qe).getChatMessagesPaginated(t,e,r,n,i);return{messages:s.messages.map(o=>wr.formatSocketServiceMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,n,i={}){var s;const o=(s=c(this,re).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new C("Not permitted to create channels","0501");if(i.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new C("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new C("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new C("channel name cannot be empty.","0510");const a=[...new Set([...n,c(this,re).userId])];return yield c(this,Pi).createChannel(r.trim(),a,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var r,n,i,s,o;const a=this.channels.find(p=>p.id===t),d=(r=c(this,re).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new C("Not permitted to update channels","0501");if(a.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new C("Not permitted to update public channels","0501");if(a.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new C("Not permitted to update private channels","0501")}const h={memberIds:(n=e.memberIds)!=null?n:a.memberIds,displayName:(i=e.displayName)!=null?i:a.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:a.displayPictureUrl,visibility:(o=e.visibility)!=null?o:a.visibility};return c(this,Pi).updateChannel(t,h)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,n,i={}){return this.sendMessageInternal(r,null,n,i)})}getChannelMembers(t){return u(this,null,function*(){return c(this,Pi).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!K.hasFeature(X.FEAT_CHAT_SDK_SEARCH))throw new C("searchMessages is temporarily disabled!");return(yield c(this,qe).searchMessages(e,r)).map(wr.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield c(this,qe).markLastReadMessage(t,e);const r=this.channels.find(n=>n.id===t);if(r){const n=ne(V({},r),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?n:i),this.emit("channelMessageUpdate",n)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},re=new WeakMap,Ri=new WeakMap,qe=new WeakMap,Pi=new WeakMap,Ta=new WeakMap,al=new WeakSet,kf=function(){return c(this,Ta).getValue("roomNodeClient")},_f);lt([y.trace("DyteChat.sendTextMessage"),Ct(Sa)],Ze.prototype,"sendTextMessage",1),lt([y.trace("DyteChat.sendImageMessage"),Ct({maxInvocations:20,period:60})],Ze.prototype,"sendImageMessage",1),lt([y.trace("DyteChat.sendFileMessage"),Ct({maxInvocations:20,period:60})],Ze.prototype,"sendFileMessage",1),lt([y.trace("DyteChat.sendMessage"),Ct({maxInvocations:180,period:60})],Ze.prototype,"sendMessage",1),lt([y.trace("DyteChat.editTextMessage")],Ze.prototype,"editTextMessage",1),lt([y.trace("DyteChat.editImageMessage")],Ze.prototype,"editImageMessage",1),lt([y.trace("DyteChat.editFileMessage")],Ze.prototype,"editFileMessage",1),lt([y.trace("DyteChat.editMessage")],Ze.prototype,"editMessage",1),lt([y.trace("DyteChat.deleteMessage")],Ze.prototype,"deleteMessage",1),lt([y.trace("DyteChat.createChannel")],Ze.prototype,"createChannel",1),lt([y.trace("DyteChat.updateChannel")],Ze.prototype,"updateChannel",1),lt([y.trace("DyteChat.sendMessageToChannel")],Ze.prototype,"sendMessageToChannel",1),lt([y.trace("DyteChat.getChannelMembers")],Ze.prototype,"getChannelMembers",1),lt([y.trace("DyteChat.searchMessages")],Ze.prototype,"searchMessages",1),lt([y.trace("DyteChat.markLastReadMessage")],Ze.prototype,"markLastReadMessage",1),Ze=lt([dt("0500")],Ze);var w=(t=>(t.NEW_PRODUCER="NEW_PRODUCER",t.PRODUCER_TRACK_ENDED="PRODUCER_TRACK_ENDED",t.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",t.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",t.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",t.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",t.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",t.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",t.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",t.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",t.ROOM_NODE_FAILED="ROOM_NODE_FAILED",t.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",t.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",t.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",t.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",t.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",t.LOW_PRODUCER_SCORE="LOW_PRODUCER_SCORE",t.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",t.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",t.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",t.WAITLISTED="WAIT_LISTED",t.MESSAGE="websocket/message",t.ROOM_MESSAGE="websocket/room-message",t.PEER_JOINED_INTERNAL="peer/joined-internal",t.PEER_CLOSED="websocket/peer-closed",t.CONSUMER_CLOSED="websocket/consumer-closed",t.CONSUMER_PAUSED="websocket/consumer-paused",t.CONSUMER_RESUMED="websocket/consumer-resumed",t.PRODUCER_CLOSED="websocket/producer-closed",t.NEW_CONSUMER="websocket/new-consumer",t.PRODUCER_SCORE="websocket/producer-score",t.CONSUMER_SCORE="websocket/consumer-score",t.PRODUCER_TOGGLE="hive/producer-toggle",t.CONSUMER_TOGGLE="hive/consumer-toggle",t.SELECTED_PEERS_DIFF="hive/selected-peers-diff",t.REFRESH_GRID="hive/refresh-grid",t.UPDATE_ACTIVE="media/update-active",t.RESET_PRODUCER_STATE="hive/reset-producer-state",t.CF_TRANSPORT_STATE_CHANGED="cf/transport-state-changed",t.CF_ROOM_REJOINING="cf/room-rejoining",t.CF_ROOM_REJOIN_FAILED="cf/room-rejoining-failed",t.CF_ROOM_REJOINED="cf/room-rejoined",t.CF_TRANPSORT_RECONNECTING="cf/transport-reconnecting",t.ROOM_STATE="sockethub/room-state",t.PEER_DISPLAY_NAME_CHANGED="hive/display-name-changed",t.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",t.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",t.KICK_PEER="KICK_PEER",t.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",t.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",t.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",t.PIP_HANGUP="PIP_HANGUP",t.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",t.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",t.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",t.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",t.SOCKET_PEERS="SOCKET_PEERS",t.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",t.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",t.MUTE_ALL="MUTE_ALL",t.MUTE_ALL_VIDEO="MUTE_ALL_VIDEO",t))(w||{}),WP=Object.defineProperty,$P=Object.getOwnPropertyDescriptor,GP=(t,e,r,n)=>{for(var i=n>1?void 0:n?$P(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&WP(e,r,i),i},cl,bf;const Rn=(bf=class{constructor(t,e,r,n,i){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),_(this,cl,void 0),T(this,cl,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new Ze(t,e,r,n,i),this.self=n,this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){return new Rn(t,e,r,n,i)})}static formatMessage(t){return ne(V({},t),{time:new Date(t.time),type:HP[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,r={displayName:t.displayName,id:t.chatId,time:e,timeMs:t.createdAtMs,type:t.payloadType,isEdited:t.isEdited,userId:t.userId,targetUserIds:t.targetUserIds,channelId:t.channelId,channelIndex:t.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:t.pinned};switch(r.type){case mt.TEXT:{r.message=t.payload;break}case mt.IMAGE:{r.link=t.payload;break}case mt.FILE:{const{link:n,name:i,size:s}=JSON.parse(t.payload);r.link=n,r.name=i,r.size=s;break}case mt.CUSTOM:{const{html:n,images:i,message:s,videos:o,files:a}=JSON.parse(t.payload);r.message=s,r.html=n,r.images=i,r.videos=o,r.files=a;break}}return Rn.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||K.hasFeature(X.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=cf.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>Rn.formatSocketServiceMessage(r))})}setupEvents(){b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(De.sendMessageToRoom,t=>{const e=Rn.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(n=>n.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(De.sendMessageToPeers,t=>{const e=Rn.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(De.editMessage,t=>{const e=Rn.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(n=>n.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(De.deleteMessage,t=>{if(t.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:t.chatId,channelId:t.channelId},messages:this.chat.messages});return}const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(wn.createChatChannel,t=>{const[e]=t.chatChannels,r=In.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(De.pinMessage,t=>{const e=this.chat.messages.findIndex(n=>n.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(wn.updateChatChannel,t=>{const[e]=t.chatChannels,r=In.formatChannel(e);this.chat.channels=this.chat.channels.map(n=>n.id===r.id?r:n),this.chat.emit("channelUpdate",r)})}},cl=new WeakMap,bf);let wr=Rn;GP([y.trace("ChatController.setupEvents")],wr.prototype,"setupEvents",1);var JP=Object.defineProperty,qP=Object.getOwnPropertyDescriptor,KP=(t,e,r,n)=>{for(var i=n>1?void 0:n?qP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JP(e,r,i),i},dl,wf,Ai,_s,ka,Cf;let ll=(Cf=class extends Dt{constructor(t,e,r){super(),_(this,dl),m(this,"items"),_(this,Ai,void 0),_(this,_s,void 0),_(this,ka,void 0),T(this,ka,t),T(this,Ai,e),T(this,_s,r),this.items=[]}get roomJoined(){var t;return((t=c(this,dl,wf))==null?void 0:t.roomJoined)===!0}create(t,e,r=!1,n=!1){return u(this,null,function*(){if(c(this,Ai).config.viewType!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can't create polls without joining room");if(!c(this,Ai).permissions.polls.canCreate){l.error("DytePolls::create::permission_denied");return}if(!t||!e){l.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){l.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield c(this,_s).createPoll(t,e,r,n)})}vote(t,e){return u(this,null,function*(){if(!c(this,Ai).permissions.polls.canVote){l.error("DytePolls::vote::permission_denied");return}yield c(this,_s).votePoll(t,e)})}},dl=new WeakSet,wf=function(){return c(this,ka).getValue("roomNodeClient")},Ai=new WeakMap,_s=new WeakMap,ka=new WeakMap,Cf);ll=KP([dt("0700")],ll);var zP=Object.defineProperty,YP=Object.getOwnPropertyDescriptor,QP=(t,e,r,n)=>{for(var i=n>1?void 0:n?YP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zP(e,r,i),i},_a,Pn,If;const Mi=(If=class{constructor(t,e,r){m(this,"polls"),_(this,_a,void 0),_(this,Pn,void 0),this.polls=new ll(t,e,r),T(this,_a,e),T(this,Pn,r),this.setupEvents()}static init(t,e,r){return u(this,null,function*(){return new Mi(t,e,r)})}canViewPolls(){return c(this,_a).permissions.polls.canView}setupEvents(){b.on(w.UPDATE_PERMISSIONS,t=>{t.polls&&(t.polls.canView?this.getPolls():this.polls.items=[])}),this.canViewPolls()&&(b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),c(this,Pn).on(_r.createPoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}),c(this,Pn).on(_r.updatePoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}),c(this,Pn).on(_r.votePoll,t=>{t.poll&&this.updatePoll(Mi.formatSocketServicePoll(t.poll))}))}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==JSON.stringify(t)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,t],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}getPolls(){return u(this,null,function*(){const t=yield c(this,Pn).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=dP.fromBinary(t.payload);this.polls.items=e.map(r=>Mi.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(n=>({id:n.userId,name:n.name}))}));return{anonymous:t.anonymous,createdBy:t.createdBy,createdByUserId:t.createdByUserId,hideVotes:t.hideVotes,id:t.pollId,options:e,question:t.question,voted:t.votes}}},_a=new WeakMap,Pn=new WeakMap,If);let Rf=Mi;QP([y.trace("PollController.setupEvents")],Rf.prototype,"setupEvents",1);var XP=Object.defineProperty,ZP=Object.getOwnPropertyDescriptor,eA=(t,e,r,n)=>{for(var i=n>1?void 0:n?ZP(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&XP(e,r,i),i},Pf=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Pf||{}),ba,bs,wa,Di,Ca,Af;let ul=(Af=class extends Dt{constructor(t,e,r,n,i){super(),_(this,bs),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),_(this,ba,void 0),_(this,Di,void 0),_(this,Ca,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),T(this,ba,t),T(this,Di,e),this.viewType=r,T(this,Ca,n),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){var t;return(t=c(this,bs,wa))==null?void 0:t.socketState}get mediaState(){var t;return(t=c(this,bs,wa))==null?void 0:t.mediaState}get meetingId(){var t;return(t=c(this,bs,wa))==null?void 0:t.roomName}setBroadcastTabChanges(t){if(!c(this,Di).permissions.canSpotlight)throw l.error("DyteSpotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;l.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=c(this,Di).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){c(this,Ca).broadcastMessage("spotlight",{userId:c(this,Di).userId,currentTab:this.selfActiveTab})}},ba=new WeakMap,bs=new WeakSet,wa=function(){return c(this,ba).getValue("roomNodeClient")},Di=new WeakMap,Ca=new WeakMap,Af);ul=eA([dt("0800")],ul);function tA(t){let e="",r=[""];const n=[r];let i=0,s=0,o=!0,a;for(a of t)a==='"'?(o&&a===e&&(r[i]+=a),o=!o):a===","&&o?a=r[++i]="":a===`
18
+ `&&o?(e==="\r"&&(r[i]=r[i].slice(0,-1)),r=n[++s]=[a=""],i=0):r[i]+=a,e=a;return n}var rA=Object.defineProperty,nA=Object.getOwnPropertyDescriptor,Mf=(t,e,r,n)=>{for(var i=n>1?void 0:n?nA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&rA(e,r,i),i};let Gr=class extends Dt{constructor(){super(),m(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new Gr;try{t&&e.getActiveTranscript()}catch(r){l.error("Error fetching active transcriptions ",r)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[r,n,i,s,o,a]]=tA(t);return{id:gn(),name:o,peerId:n,userId:i,customParticipantId:s,transcript:a,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}catch(r){l.error(`Failed to parse transcript: ${t}`,r);return}}static parseTranscripts(t){return t?t.split(`
19
+ `).map(e=>Gr.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=je(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Gr.parseTranscripts(e)}catch(t){}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:n})=>n===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const n=r.at(-1);n.transcript=t.transcript,n.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",n);return}this.transcripts.push(t),this.emit("transcript",t)})}};Mf([y.trace("DyteAi.getActiveTranscript")],Gr.prototype,"getActiveTranscript",1),Gr=Mf([dt("0000")],Gr);var iA=Object.defineProperty,sA=Object.getOwnPropertyDescriptor,oA=(t,e,r,n)=>{for(var i=n>1?void 0:n?sA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&iA(e,r,i),i},An,ws,hl,Df;const Of=(Df=class{constructor(t,e,r,n,i,s){m(this,"meta"),m(this,"ai"),_(this,An,void 0),_(this,ws,void 0),m(this,"aiSocketHandler"),_(this,hl,void 0),T(this,hl,t),this.meta=new ul(t,e,e.config.viewType,r,s),this.ai=n,T(this,An,e),T(this,ws,r),this.aiSocketHandler=i,e.config.viewType!==We.Chat&&this.setupEvents()}static init(t,e,r,n,i){return u(this,null,function*(){const s=yield Gr.init(e.permissions.transcriptionEnabled);return new Of(t,e,r,s,n,i)})}conditionallySetActiveTab(t){var e;t!=null&&t.currentTab&&((e=this.meta.selfActiveTab)==null?void 0:e.id)!==t.currentTab.id&&(this.meta.setSelfActiveTab(t.currentTab,Pf.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){b.on(w.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),b.on(w.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),b.on(w.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const n=new Date(t*1e3);this.meta.meetingStartedTimestamp=n,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),b.on(w.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),c(this,An).permissions.canSpotlight&&(l.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&c(this,ws).broadcastMessage("spotlight",{userId:c(this,An).userId,currentTab:this.meta.selfActiveTab})),b.on(w.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){c(this,An).permissions.canSpotlight&&this.meta.selfActiveTab&&c(this,ws).broadcastToPeers("spotlight",[t.id],{userId:c(this,An).userId,currentTab:this.meta.selfActiveTab})})),b.on(w.ROOM_MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),b.on(w.MESSAGE,t=>{var e,r;let n;if("type"in t){if(t.type!=="spotlight")return;n=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;n=t}else return;l.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:n.userId},currentTab:{id:(e=n.currentTab)==null?void 0:e.id,type:(r=n.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(n)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:r,isPartial:n}=t,i=Gr.parseTranscript(r,n);if(!i){l.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:o,transcript:a}=i;l.debug(`${e} Received transcript for peer ${s} - ${o}: ${a}`)})}},An=new WeakMap,ws=new WeakMap,hl=new WeakMap,Df);let Nf=Of;oA([y.trace("MetaController.setupEvents")],Nf.prototype,"setupEvents",1);var aA=Object.defineProperty,cA=Object.getOwnPropertyDescriptor,Mn=(t,e,r,n)=>{for(var i=n>1?void 0:n?cA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&aA(e,r,i),i},ur,Cs,xe,Ia,Dn,hr,Is,Ra;class Jr extends Dt{constructor(e,r,n,i,s){super(),_(this,Is),_(this,ur,void 0),_(this,Cs,void 0),_(this,xe,void 0),_(this,Ia,void 0),_(this,Dn,void 0),_(this,hr,void 0),T(this,hr,e),T(this,ur,i),T(this,Cs,s),T(this,xe,r),T(this,Ia,n),T(this,Dn,[]),this.setupEvents()}get status(){return c(this,hr).getValue("stageStatus")}setupEvents(){b.onAsync(w.GET_STAGE_REQUESTS,e=>u(this,null,function*(){T(this,Dn,e)})),b.onAsync(w.UPDATE_STAGE_REQUESTS,e=>u(this,[e],function*({add:r}){const n=c(this,Ia).joined.toArray().filter(i=>i.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(i=>({displayName:i.name,userId:i.userId,peerId:i.id}));(r||n.length>c(this,Dn).length)&&this.emit("newStageRequest",{count:n.length}),T(this,Dn,n),this.emit("stageAccessRequestUpdate",n)}))}getAccessRequests(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::get_access_request::permission_denied"),new C("You do not have permission to perform this action/");return{stageRequests:c(this,Dn)}}requestAccess(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`);if(c(this,xe).permissions.stageAccess===q.Allowed){ue(this,Is,Ra).call(this,"ACCEPTED_TO_JOIN_STAGE");return}c(this,ur).requestAccess(),ue(this,Is,Ra).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");c(this,ur).cancelRequestAccess(),ue(this,Is,Ra).call(this,"OFF_STAGE")})}grantAccess(e){if(!c(this,xe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::grant_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,ur).grantAccess(e)}denyAccess(e){if(!c(this,xe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::deny_access::permission_denied"),new C("You do not have permission to perform this action/");return c(this,ur).denyAccess(e)}join(){return u(this,null,function*(){const e=c(this,hr).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||c(this,xe).permissions.stageAccess===q.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`);if(yield c(this,ur).joinStage(),e===We.Livestream){const{name:r,id:n,userId:i}=c(this,xe);yield c(this,Cs).joinRoom(r,n,i,e)}if(c(this,hr).setValue("stageStatus","ON_STAGE",!1),yield b.emitAsync(w.JOIN_MEDIA_ROOM),c(this,hr).notify("stageStatus"),e===We.Livestream){const{peers:r}=yield c(this,Cs).getStagePeers();b.emit(w.SOCKET_PEERS,r)}})}leave(){return u(this,null,function*(){if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`);c(this,xe).setIsPinned(!1),yield c(this,ur).leaveStage(c(this,xe).userId),c(this,hr).setValue("stageStatus","OFF_STAGE",!1),yield b.emitAsync(w.LEAVE_MEDIA_ROOM,"stageLeft"),c(this,hr).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!c(this,xe).roomJoined)throw new C("Can`t kick participant without joining room");if(!c(this,xe).permissions.stageEnabled)throw l.error("DyteStage::stage_disabled"),new C("Stage is disabled");if(!c(this,xe).permissions.acceptStageRequests)throw l.error("DyteStage::kick::permission_denied"),new C("You do not have permissions for kick");return c(this,ur).kick(e)})}}ur=new WeakMap,Cs=new WeakMap,xe=new WeakMap,Ia=new WeakMap,Dn=new WeakMap,hr=new WeakMap,Is=new WeakSet,Ra=function(t){return u(this,null,function*(){this.status!==t&&c(this,hr).setValue("stageStatus",t)})},Mn([y.trace("DyteStage.getStageRequests")],Jr.prototype,"getAccessRequests",1),Mn([y.trace("DyteStage.requestAccess")],Jr.prototype,"requestAccess",1),Mn([y.trace("DyteStage.cancelRequestAccess")],Jr.prototype,"cancelRequestAccess",1),Mn([y.trace("DyteStage.grantAccess")],Jr.prototype,"grantAccess",1),Mn([y.trace("DyteStage.denyAccess")],Jr.prototype,"denyAccess",1),Mn([y.trace("DyteStage.joinStage")],Jr.prototype,"join",1),Mn([y.trace("DyteStage.leaveStage")],Jr.prototype,"leave",1);function dA(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function Pa(t){switch(t){case Tr.UNSPECIFIED:return"OFF_STAGE";case Tr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Tr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Tr.OFF_STAGE:return"OFF_STAGE";case Tr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var lA=Object.defineProperty,uA=Object.getOwnPropertyDescriptor,hA=(t,e,r,n)=>{for(var i=n>1?void 0:n?uA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&lA(e,r,i),i},On,Oi,Nn,Aa,qr;class Lf{constructor(e,r,n,i,s){m(this,"stage"),_(this,On,void 0),_(this,Oi,void 0),_(this,Nn,void 0),_(this,Aa,0),_(this,qr,void 0),T(this,qr,e),this.stage=new Jr(e,i,s,r,n),T(this,Nn,r),T(this,On,i),T(this,Oi,s),this.setupEvents()}setupEvents(){c(this,qr).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),c(this,Nn).on(j.grantStageAccess,()=>{c(this,On).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),c(this,Nn).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===c(this,On).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),c(this,Nn).on(j.denyStageAccess,()=>{c(this,On).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),c(this,Nn).on(j.getStageRequests,e=>u(this,null,function*(){var r;if(c(this,On).permissions.stageAccess!==q.Allowed)return;const n=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield b.emitAsync(w.GET_STAGE_REQUESTS,n),c(this,Aa)<n.length&&n.length>0&&this.stage.emit("newStageRequest",{count:n.length}),T(this,Aa,n.length),this.stage.emit("stageAccessRequestUpdate",n)}))}getCurrentStageRequests(){return c(this,Oi).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&c(this,qr).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=Pa(e.stageType),n=c(this,qr).getValue("stageStatus");if(n!==r)switch(e.stageType){case 1:c(this,qr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(n);break;case 0:case 4:default:c(this,qr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=c(this,Oi).joined.get(e.peerId),n=c(this,Oi).viewMode==="ACTIVE_GRID";if(!r){l.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),n&&b.emit(w.REFRESH_GRID);break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),n&&b.emit(w.REFRESH_GRID);break}b.emit(w.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}On=new WeakMap,Oi=new WeakMap,Nn=new WeakMap,Aa=new WeakMap,qr=new WeakMap,hA([y.trace("DyteStage.setupEvents")],Lf.prototype,"setupEvents",1);var pA=Object.defineProperty,mA=Object.getOwnPropertyDescriptor,Ma=(t,e,r,n)=>{for(var i=n>1?void 0:n?mA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&pA(e,r,i),i};const Fe={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 gt,Yt,Rs,Ps,Kr,As,Ms,Ni,Ds,xf;let Li=(xf=class extends Ci{constructor(t,{baseURL:e,createdAt:r,description:n,id:i,name:s,organizationId:o,picture:a,private:d,published:h,staggered:p,tags:f,type:g,updatedAt:E},v,R,A,L){super(),_(this,Ni),_(this,gt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),_(this,Yt,void 0),_(this,Rs,void 0),_(this,Ps,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"),_(this,Kr,void 0),m(this,"config"),_(this,As,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),_(this,Ms,void 0),T(this,Ms,t),this.baseURL=e,this.createdAt=new Date(r),this.description=n,this.id=i,this.name=s,T(this,Yt,R),this.organizationId=o,this.picture=a,this.private=d,this.published=h,this.staggered=p,this.tags=f,this.type=g,this.updatedAt=new Date(E),this.active=!1,this.iframes=new Map,T(this,gt,v),T(this,Rs,A),T(this,Ps,L),this.enabledBy=""}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:n,uuid:i,type:s}=r;switch(s){case J.customPluginEventToRoom:{c(this,gt).customPluginEventToRoom(this.id,n,i);break}case J.customPluginEventToPeers:{c(this,gt).customPluginEventToPeers(this.id,n.peerIds,n,i);break}case J.enablePluginForRoom:{c(this,gt).enablePluginForRoom(this.id,i);break}case J.enablePluginForPeers:{c(this,gt).enablePluginForPeers(this.id,n.peerIds,i);break}case J.disablePluginForRoom:{c(this,gt).disablePluginForRoom(this.id,i);break}case J.disablePluginForPeers:{c(this,gt).disablePluginForPeers(this.id,n.peerIds,i);break}case J.storeInsertKeys:{c(this,gt).storeInsertKeys(this.id,n.store,n.insertKeys,i);break}case J.storeGetKeys:{c(this,gt).storeGetKeys(this.id,n.store,n.getKeys,i);break}case J.storeDeleteKeys:{c(this,gt).storeDeleteKeys(this.id,n.store,n.deleteKeys,i);break}case J.storeDelete:{c(this,gt).storeDelete(this.id,n.store,i);break}case Fe.chatMessage:{const{messagePayload:o,peerIds:a}=n;if(!c(this,Ps)){this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield c(this,Ps).sendMessage(o,a),this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Fe.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Fe.getPeer:{let o;const{peerId:a}=n,d=ne(V({},c(this,Yt)),{isRecorder:(e=c(this,Yt).permissions)==null?void 0:e.isRecorder,isHidden:c(this,Yt).permissions.hiddenParticipant,stageStatus:c(this,Yt).stageStatus});a?(o=c(this,Rs).joined.get(n.peerId),c(this,Yt).id===a&&(o=d)):o=d,this.sendIframeEvent({type:Fe.getPeer,payload:{peer:o&&ya(o)},uuid:r.uuid});break}case Fe.getPeers:{const o=c(this,Rs).joined.toArray().map(a=>ya(a));this.sendIframeEvent({type:Fe.getPeers,payload:{peers:o},uuid:r.uuid});break}case Fe.getPluginInitiator:{this.sendIframeEvent({type:Fe.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Fe.getDisplayTitle:{this.sendIframeEvent({type:Fe.getDisplayTitle,payload:{displayTitle:c(this,Ni,Ds).meetingTitle},uuid:r.uuid});break}case Fe.getRoomName:{this.sendIframeEvent({type:Fe.getRoomName,payload:{roomName:c(this,Ni,Ds).roomName},uuid:r.uuid});break}case Fe.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(l.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Fe.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:n}=(e=this.iframes.get(t))!=null?e:{};(r||n)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",n),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!c(this,As))throw l.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new C("No auth token set for plugin.");if(!t)throw l.error("DytePlugin::addPluginView::iframe_was_not_provided"),new C("Iframe was not provided.");this.removePluginView(e);const n=t,i=new URL(this.baseURL),s={auth:c(this,As),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:c(this,Ms).getValue("apiBase"),pluginId:this.id,roomName:(r=c(this,Ni,Ds).roomName)!=null?r:"",displayTitle:c(this,Ni,Ds).meetingTitle};if(Object.keys(s).forEach(o=>{i.searchParams.set(o,s[o])}),n.src=i.href,n.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",n.title=e,navigator.isReactNative)n.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:n});else{const o=a=>u(this,null,function*(){a.source===t.contentWindow&&(yield this.handleIframeMessage(a.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:n,listener:o})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=je(),e=yield t.authorizePlugin(this.id);T(this,As,e),T(this,Kr,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){l.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),T(this,Kr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=c(this,Yt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(c(this,gt).addPlugin(this.id,this.staggered),T(this,Kr,new Date),l.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=c(this,Yt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==c(this,Yt).id||(c(this,gt).removePlugin(this.id),l.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:c(this,Kr)?new Date().getTime()-c(this,Kr).getTime():0}}),T(this,Kr,void 0)))})}},gt=new WeakMap,Yt=new WeakMap,Rs=new WeakMap,Ps=new WeakMap,Kr=new WeakMap,As=new WeakMap,Ms=new WeakMap,Ni=new WeakSet,Ds=function(){return c(this,Ms).getValue("roomNodeClient")},xf);Ma([Ct({maxInvocations:5,period:1})],Li.prototype,"sendData",1),Ma([y.trace("DytePlugin.activatePlugin")],Li.prototype,"activate",1),Ma([y.trace("DytePlugin.deactivatePlugin")],Li.prototype,"deactivate",1),Li=Ma([dt("0600")],Li);var $e,xi;class Ff extends Map{constructor(e){const{onAddEvent:r,onDeleteEvent:n,onClearEvent:i}=e;super(),_(this,$e,void 0),_(this,xi,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),T(this,$e,new Ci),this.onAddEvent=r,this.onDeleteEvent=n,this.onClearEvent=i,T(this,xi,new Map)}emit(e,...r){return c(this,$e).emit(e,...r)}on(e,r){return c(this,$e).on(e,r)}addListener(e,r){return c(this,$e).addListener(e,r)}off(e,r){return c(this,$e).off(e,r)}once(e,r){return c(this,$e).once(e,r)}prependListener(e,r){return c(this,$e).prependListener(e,r)}prependOnceListener(e,r){return c(this,$e).prependOnceListener(e,r)}removeListener(e,r){return c(this,$e).removeListener(e,r)}removeAllListeners(e){return c(this,$e).removeAllListeners(e)}listeners(e){return c(this,$e).listeners(e)}listenerCount(e){return c(this,$e).listenerCount(e)}getMaxListeners(){return c(this,$e).getMaxListeners()}setMaxListeners(e){return c(this,$e).setMaxListeners(e)}eventNames(){return c(this,$e).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,n=!0){const i=super.set(e,r),s=(o,...a)=>{this.emit(o,r,...a)};return c(this,xi).set(e,s),r.on("*",s),n&&c(this,$e).emit(this.onAddEvent,r),i}delete(e,r=!0,n=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",c(this,xi).get(e));const s=super.delete(e);return n&&i.removeAllListeners(),r&&c(this,$e).emit(this.onDeleteEvent,i),s}clear(e=!0,r=!1){this.forEach(i=>{i.removeListener("*",c(this,xi).get(i.id)),r&&i.removeAllListeners()});const n=super.clear();return e&&c(this,$e).emit(this.onClearEvent),n}toArray(){return Array.from(this.values())}}$e=new WeakMap,xi=new WeakMap;class Uf extends Ff{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var fA=Object.defineProperty,gA=Object.getOwnPropertyDescriptor,vA=(t,e,r,n)=>{for(var i=n>1?void 0:n?gA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&fA(e,r,i),i};let pl=class{constructor(){m(this,"all"),m(this,"active"),this.all=new Uf,this.active=new Uf}};pl=vA([dt("0600")],pl);var yA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,Da=(t,e,r,n)=>{for(var i=n>1?void 0:n?EA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&yA(e,r,i),i},Qt,Os,Oa,Vf;const Bf=(Vf=class{constructor(t,e,r,n){m(this,"plugins"),_(this,Qt,void 0),_(this,Os,void 0),_(this,Oa,void 0),T(this,Qt,e),T(this,Os,r),T(this,Oa,t),this.plugins=n,this.setupEvents()}static init(t,e,r,n,i,s,o){return u(this,null,function*(){const a=new pl;return e.forEach(d=>{const h=new Li(t,d,r,s,o,i);a.all.add(h)}),new Bf(t,r,n,a)})}getRoomPlugins(){return u(this,null,function*(){const{plugins:t}=yield c(this,Qt).getActivePlugins();yield Promise.all(t.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const n=this.plugins.all.get(e);n&&(yield n.activateForSelf(),n.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,n){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:r,payload:n})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),b.onAsync(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),l.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),c(this,Qt).on(J.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),c(this,Qt).on(J.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[J.enablePluginForPeers,J.enablePluginForRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[J.disablePluginForPeers,J.disablePluginForRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[J.customPluginEventToPeers,J.customPluginEventToRoom].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,Qt).on(t,(e,r)=>u(this,null,function*(){var n;const i=(n=e.storeItems)==null?void 0:n.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:i})}))}),c(this,Qt).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),c(this,Os).on(De.sendMessageToPeers,t=>{const e=wr==null?void 0:wr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),c(this,Os).on(De.sendMessageToRoom,t=>{const e=wr==null?void 0:wr.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Fe.chatMessage,{message:e})}),b.on(w.PEER_JOINED_INTERNAL,t=>{const e=ya(t);this.broadcastIframeEvent(Fe.peerJoined,e)}),b.on(w.PEER_CLOSED,t=>{this.broadcastIframeEvent(Fe.peerLeft,t)}),b.on(w.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Fe.peerStageStatusUpdate,t)}),c(this,Oa).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Fe.stageStatusUpdate,t)})}},Qt=new WeakMap,Os=new WeakMap,Oa=new WeakMap,Vf);let Ns=Bf;Da([y.trace("PluginController.getRoomPlugins")],Ns.prototype,"getRoomPlugins",1),Da([y.trace("PluginController.enableForSelf")],Ns.prototype,"enablePlugin",1),Da([y.trace("PluginController.disableForSelf")],Ns.prototype,"disablePlugin",1),Da([y.trace("PluginController.setupEvents")],Ns.prototype,"setupEvents",1);var SA=Object.defineProperty,TA=Object.getOwnPropertyDescriptor,Ls=(t,e,r,n)=>{for(var i=n>1?void 0:n?TA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&SA(e,r,i),i},xs,Na,Fs,La,jf;let Ln=(jf=class extends Dt{constructor(t,e){super(),_(this,Fs),_(this,xs,void 0),_(this,Na,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),T(this,Na,t),T(this,xs,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!c(this,xs).permissions.canRecord)throw l.error("DyteRecording::start::permission_denied"),new C("User does not have permission to start recording");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw l.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(`Cant start recording, recordingState irregular: ${this.recordingState}`);try{const e=je(),{recording:r={}}=c(this,Na).getValue("defaults"),n=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:n,state:"STARTING"}])}catch(e){throw l.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording")}})}stop(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield ue(this,Fs,La).call(this,"resume",["PAUSED"],t)})}},xs=new WeakMap,Na=new WeakMap,Fs=new WeakSet,La=function(t,e,r){return u(this,null,function*(){if(!c(this,xs).permissions.canRecord)throw l.error("DyteRecording::stop::permission_denied"),new C("User does not have permission to stop recording");let n=[];if(r!==void 0){const i=this.recordings.find(s=>s.id===r);if(i===void 0)throw new C("Could not find the specified recording");if(e.includes(i.state)){l.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}n.push(i)}else n=this.recordings.filter(i=>e.includes(i.state));n.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield je().updateRecording(i.id,t)}catch(o){throw l.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new C("Error while stopping recording")}}))})},jf);Ls([y.trace("DyteRecording.start")],Ln.prototype,"start",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"stop",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"pause",1),Ls([y.trace("DyteRecording.stop")],Ln.prototype,"resume",1),Ln=Ls([dt("1000")],Ln);var kA=Object.defineProperty,_A=Object.getOwnPropertyDescriptor,bA=(t,e,r,n)=>{for(var i=n>1?void 0:n?_A(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&kA(e,r,i),i},ml;class Hf{constructor(e,r,n){m(this,"recording"),m(this,"room"),_(this,ml,void 0),T(this,ml,e),this.recording=new Ln(e,r),this.room=n,this.setupEvents()}setupEvents(){b.on(w.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>({id:r.recordingId,state:r.recordingStatus}))):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let r=!1;const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(r=!0,i.state="RECORDING")}),r===!1&&n.push({id:e.recordingId,state:"RECORDING"}),this.recording.updateRecordings(n)}),this.room.on(j.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(n=>{n.id===e.recordingId&&(n.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(j.recordingStopped,e=>{const r=[...this.recording.recordings.filter(n=>n.id!==e.recordingId)];this.recording.updateRecordings(r)})}}ml=new WeakMap,bA([y.trace("RecordingController.setupEvents")],Hf.prototype,"setupEvents",1);class wA{static hasFeature(e){var r;return(r=K.hasFeature(e))!=null?r:!1}static getFeatureValue(e){return K.getValue(e)}static getAllFeatures(){return K.getAllFlags()}}class fl{constructor(e,r,n){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=ye,this.callStats=n}static init(e){return new fl(l,wA,e)}}class gl{constructor(e){m(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=fl.init(B);return new gl(e)})}}var CA=Object.defineProperty,IA=Object.getOwnPropertyDescriptor,Ot=(t,e,r,n)=>{for(var i=n>1?void 0:n?IA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&CA(e,r,i),i},et,ut,Ke,Cr,Xt,xa,vl;class It extends Ci{constructor(e,r,n=$f,i=!0){super(),_(this,et,void 0),_(this,ut,void 0),_(this,Ke,void 0),_(this,Cr,void 0),_(this,Xt,void 0),_(this,xa,void 0),_(this,vl,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),T(this,vl,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,T(this,et,new Yf(e,r)),T(this,ut,new zA(c(this,et),void 0,n)),T(this,Ke,new rM(c(this,et),void 0,n)),T(this,Xt,new ZA(c(this,et))),T(this,Cr,new QA(c(this,et))),T(this,xa,i),c(this,ut).on("trackMuted",this.onAudioTrackMuted.bind(this)),c(this,ut).on("trackChanged",this.onAudioTrackChanged.bind(this)),c(this,Ke).on("trackChanged",this.onVideoTrackChanged.bind(this)),c(this,Ke).on("trackEnded",this.onVideoTrackEnded.bind(this)),c(this,Xt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){B.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?B.browserBackgrounded():B.browserForegrounded()}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:n}){var i;let s,o;if(r&&n)try{const a=yield c(this,et).getAudioAndVideoTrack();s=a.audioTrack,o=a.videoTrack}catch(a){l.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:a})}if(!s&&r)try{s=yield c(this,et).getAudioTrack(!1)}catch(a){l.error("LocalMediaHandler::init::Failed to get audio track",{error:a})}if(!o&&n)try{o=yield c(this,et).getVideoTrack()}catch(a){l.error("LocalMediaHandler::init::Failed to get video track",{error:a})}yield c(this,ut).setMediaTrack(s),yield c(this,Ke).setMediaTrack(o);try{yield c(this,Cr).setupSpeaker()}catch(a){}if(o){const a=yield this.getDeviceById(o.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",a)})}if(s){const a=yield this.getDeviceById(s.getSettings().deviceId);B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",a)})}(i=c(this,Cr).currentDevice)!=null&&i.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",c(this,Cr).currentDevice)}),c(this,et).onDeviceChange((a,d,h)=>{this.onDeviceChange(d,h)})})}getCurrentDevices(){return{audio:c(this,ut).currentDevice,video:c(this,Ke).currentDevice,speaker:c(this,Cr).currentDevice}}get permissions(){return c(this,et).permissions}getAllDevices(){return c(this,et).getAvailableDevices()}getDeviceById(e,r){return c(this,et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return c(this,ut).mediaTrack}get audioTrack(){return c(this,ut).transformedMediaTrack}get audioEnabled(){return c(this,ut).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield c(this,ut).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){c(this,ut).muteTrack()}getAudioDevices(e){return c(this,et).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield c(this,ut).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("AUDIO",e)}),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return c(this,Cr).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield c(this,Cr).setupSpeaker(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("SPEAKER",e)}),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return c(this,Ke).mediaTrack}get videoTrack(){return c(this,Ke).transformedMediaTrack}get videoEnabled(){return c(this,Ke).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield c(this,Ke).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){c(this,Ke).disableTrack()}getVideoDevices(e){return c(this,et).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield c(this,Ke).setDevice(e),e!=null&&e.deviceId&&B.onSafeInitialization(()=>{B.selectedDevice("VIDEO",e)}),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield c(this,Ke).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:c(this,Xt).audioMediaTrack,video:c(this,Xt).videoMediaTrack}}get screenShareEnabled(){return c(this,Xt).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield c(this,Xt).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){c(this,Xt).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield c(this,Xt).updateConstraints(e)})}getSpeakerDevices(e){return c(this,et).getAudioOutputDevices(e)}addAudioMiddleware(e){return c(this,ut).addMiddleware(e)}removeAudioMiddleware(e){return c(this,ut).removeMiddleware(e)}addVideoMiddleware(e){return c(this,Ke).addMiddleware(e)}removeVideoMiddleware(e){return c(this,Ke).removeMiddleware(e)}setVideoMiddlewareGlobalConfig(e){return c(this,Ke).setVideoMiddlewareGlobalConfig(e)}destruct(){c(this,ut).disableTrack(),c(this,Ke).disableTrack(),c(this,Ke).terminateMiddlewareWebWorker(),c(this,Xt).disableScreenShare(),c(this,et).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var n,i;this.emit("DEVICE_LIST_UPDATED",e),!(r||!c(this,xa))&&((n=e==null?void 0:e.added)==null||n.forEach(s=>u(this,null,function*(){var o;s&&!$f(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const a=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);a&&(yield this.setSpeakerDevice(a))}})))})}removeAllTracks(){this.destruct()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}et=new WeakMap,ut=new WeakMap,Ke=new WeakMap,Cr=new WeakMap,Xt=new WeakMap,xa=new WeakMap,vl=new WeakMap,Ot([y.trace("MediaHandler.setupStreams")],It.prototype,"setupStreams",1),Ot([y.trace("MediaHandler.enableAudio")],It.prototype,"enableAudio",1),Ot([y.trace("MediaHandler.disableAudio")],It.prototype,"disableAudio",1),Ot([y.trace("MediaHandler.setAudioDevice")],It.prototype,"setAudioDevice",1),Ot([y.trace("MediaHandler.enableVideo")],It.prototype,"enableVideo",1),Ot([y.trace("MediaHandler.disableVideo")],It.prototype,"disableVideo",1),Ot([y.trace("MediaHandler.setVideoDevice")],It.prototype,"setVideoDevice",1),Ot([y.trace("MediaHandler.updateVideoConstraints")],It.prototype,"updateVideoConstraints",1),Ot([y.trace("MediaHandler.enableScreenShare")],It.prototype,"enableScreenShare",1),Ot([y.trace("MediaHandler.disableScreenShare")],It.prototype,"disableScreenShare",1),Ot([y.trace("MediaHandler.updateScreenshareConstraints")],It.prototype,"updateScreenshareConstraints",1),Ot([y.trace("MediaHandler.destruct")],It.prototype,"destruct",1),Ot([y.trace("MediaHandler.onDeviceChange")],It.prototype,"onDeviceChange",1);var yl=(t=>(t.NotAllowedError="NotAllowedError",t.NotReadableError="NotReadableError",t.NO_DEVICES_AVAILABLEError="NO_DEVICES_AVAILABLEError",t.AbortError="AbortError",t))(yl||{});function Wf(t,e,r){switch(!0){case ye.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ye.isSafari():switch(e){case"NotReadableError":return"DENIED";default:return"COULD_NOT_START"}case ye.isFirefox():switch(e){case"NO_DEVICES_AVAILABLEError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const RA=["virtual","emulator","krisp","solstice conference","teams","manycam","blackHole"];function $f(t){const e=t.label.toLowerCase();return ye._bowser.getOSName()==="macOS"&&e.includes("iphone")?(l.log("isVirtualDevice::ignore_macos_continuity"),!0):RA.some(r=>e.includes(r))}function PA(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const r=new AudioContext,n=yield Promise.all(t==null?void 0:t.map(o=>o(r))),i=r.createMediaStreamSource(new MediaStream([e])),s=r.createMediaStreamDestination();try{let o=i;for(let a=0;a<n.length;a+=1)o.connect(n[a]),o=n[a];o.connect(s)}catch(o){return l.error("getTransformedAudioTrack::middleware_execution_failed",{error:o}),e}return s.stream.getAudioTracks()[0]})}var Fi;class AA{constructor(){_(this,Fi,void 0)}terminateMiddlewareWebWorker(){if(c(this,Fi))try{Pu(c(this,Fi)),T(this,Fi,void 0)}catch(e){l.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,n){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:i,WorkerTimers:Yv})));if(n.disablePerFrameCanvasRendering)return i.captureStream().getVideoTracks()[0];const o=document.createElement("video"),a=new MediaStream;a.addTrack(r);const d=i.getContext("2d");o.srcObject=a,o.autoplay=!0,this.terminateMiddlewareWebWorker();const h=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](i,d))}catch(p){l.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch(p){}return o.addEventListener("play",()=>{i.width=o.width||r.getSettings().width,i.height=o.width||r.getSettings().height,T(this,Fi,Au(h,50))},!1),i.captureStream().getVideoTracks()[0]})}}Fi=new WeakMap;const Gf={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}}},Jf={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"}]},MA={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"h",maxBitrate:14e5,maxFramerate:30,scalabilityMode:"L1T1"}]},qf={320:[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}],640:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}],1280:[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]};var Q=(t=>(t.WEBCAM="webcam",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Q||{});const DA=G_(),Ui=dr(DA.config.media);function OA(t){var e,r;const n={};return t.audio&&(n.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),n.video=t.video.quality,n}var Vi,El;class NA{constructor(e,r){_(this,Vi,void 0),_(this,El,void 0),m(this,"getScreenShareConstraints",()=>{var n,i,s,o,a,d,h,p,f;const g=(n=c(this,Vi))==null?void 0:n.screenshare,E=(s=(i=g==null?void 0:g.width)==null?void 0:i.max)!=null?s:1920,v=(a=(o=g==null?void 0:g.height)==null?void 0:o.max)!=null?a:1080,R=(h=(d=g==null?void 0:g.frameRate)==null?void 0:d.max)!=null?h:5;let A=(f=(p=g==null?void 0:g.frameRate)==null?void 0:p.ideal)!=null?f:5;const L=g==null?void 0:g.displaySurface,F=g==null?void 0:g.selfBrowserSurface;K.getValue(X.VAL_MIN_FRAMERATE)&&(A=parseInt(K.getValue(X.VAL_MIN_FRAMERATE),10));let W={width:{max:E},height:{max:v},frameRate:{ideal:A,max:R}};if(K.hasFeature(X.SCREENSHARE_CONSTRAINTS)){const H=K.getValue(X.SCREENSHARE_CONSTRAINTS);W=JSON.parse(H)}return L!==void 0&&["monitor","browser","window"].includes(L)&&(W=ne(V({},W),{displaySurface:L})),F!==void 0&&(W=ne(V({},W),{selfBrowserSurface:F})),{audio:!0,video:W}}),m(this,"getAudioConstraints",n=>{var i,s,o,a,d,h,p,f;const g={},E=(i=c(this,Vi))==null?void 0:i.audio,v=E!=null&&E.enableStereo?2:1;return ye.isFirefox()||ye.isWebKitBased()?(g.audio={deviceId:n,autoGainControl:(s=E==null?void 0:E.autoGainControl)!=null?s:!0,echoCancellation:(o=E==null?void 0:E.echoCancellation)!=null?o:!0,noiseSuppression:(a=E==null?void 0:E.noiseSupression)!=null?a:!0,channelCount:v},g):(g.audio={},g.audio.optional=[n?{sourceId:n}:{sourceId:"default"},{channelCount:v},{echoCancellation:(d=E==null?void 0:E.echoCancellation)!=null?d:!0},{googEchoCancellation:(h=E==null?void 0:E.echoCancellation)!=null?h:!0},{googAutoGainControl:(p=E==null?void 0:E.autoGainControl)!=null?p:!0},{googNoiseSuppression:(f=E==null?void 0:E.noiseSupression)!=null?f:!0},{googHighpassFilter:!0}],g)}),m(this,"getVideoConstraints",n=>{var i,s,o;const a={},d=(i=c(this,Vi))==null?void 0:i.video;let h=Gf.vga;if(typeof d=="string"?h=Gf[d]:d!==void 0&&(h.height.ideal=d.height.ideal,h.width.ideal=d.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},ye.isChromiumBased()&&(h.frameRate.max=30),K.hasFeature(X.VIDEO_CONSTRAINTS)){const p=K.getValue(X.VIDEO_CONSTRAINTS);h=JSON.parse(p)}return a.video=h,typeof a.video=="boolean"||(n?a.video.deviceId={exact:n}:a.video.facingMode="user"),a}),T(this,El,e),T(this,Vi,r)}getUpdatedVideoConstraints(e){return e}}Vi=new WeakMap,El=new WeakMap;class Kf extends Error{constructor(e,r,n){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=n}}class LA{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(n=>n.kind==="audiooutput")})}}var xA=Object.defineProperty,FA=Object.getOwnPropertyDescriptor,Zt=(t,e,r,n)=>{for(var i=n>1?void 0:n?FA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&xA(e,r,i),i},Us,Ir,Sl,zf;let Nt=(zf=class extends LA{constructor(t,e){super(),m(this,"availableDevices"),_(this,Us,void 0),_(this,Ir,void 0),_(this,Sl,void 0),T(this,Sl,t),T(this,Ir,new NA(t,e)),T(this,Us,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return c(this,Ir)}destruct(){return u(this,null,function*(){var t;(t=c(this,Us))==null||t.abort()})}handlePermissionErrors(t,e){const r=Wf(t,e.name,e.message);return this.permissions[t]=r,b.emit(w.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(){return u(this,null,function*(){const t={audio:c(this,Ir).getAudioConstraints().audio,video:c(this,Ir).getVideoConstraints().video};try{l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(t)});const e=yield navigator.mediaDevices.getUserMedia(t);l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(t)});const r=e.getAudioTracks()[0];let n=e.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",K.hasFeature(X.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const i=(yield this.getVideoInputDevices()).find(s=>s.label.includes("OBS Virtual"));n=yield this.getVideoTrack(i.deviceId)}return b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:n}}catch(e){throw l.error("WebMediaInterface.getAudioAndVideoTrack",{error:e}),new C("Couldnt fetch audio and video track")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available");const n=i=>u(this,null,function*(){let s;try{r=r.filter(a=>a.deviceId!==i),s=c(this,Ir).getAudioConstraints(i),l.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const o=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks()[0];return l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const a=Wf("audio",o.name,o.message),d=new Kf(o.name,o.message,s);if(a==="COULD_NOT_START"){const h=r.shift();if(!h)throw d;return n(h.deviceId)}throw d}});try{const i=yield n(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new C(i.message,"1601")}})}handleGUMError(t,e,r){return u(this,null,function*(){throw this.handlePermissionErrors(t,new Kf(e.name,e.message,r)),l.error(`WebMediaInterface.get${t}Tracks Error while fetching ${t} tracks`,{error:e}),new C(`Couldnt fetch ${t} tracks`)})}getScreenShareTracks(){return u(this,null,function*(){let t=c(this,Ir).getScreenShareConstraints(),e;try{l.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(t)}),B.screenShareRequested(),e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(t)})}catch(r){if(r.name===yl.NotReadableError&&ye.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{t={video:!0},e=yield navigator.mediaDevices.getDisplayMedia(t),l.info("getDisplayMediaWithoutTimeout::received_display_media_retry",{constraints:JSON.stringify(t)})}catch(n){yield this.handleGUMError("screenshare",r,t)}else yield this.handleGUMError("screenshare",r,t)}return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:e.getAudioTracks()[0],videoTrack:e.getVideoTracks()[0]}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getVideoTrack(t){return u(this,null,function*(){const e=K.hasFeature(X.OBS_QUALITY),r=yield this.getCurrentDeviceLabel(t),n=r&&r.includes("OBS Virtual"),{video:i}=c(this,Ir).getVideoConstraints(t);let s={},o;e&&n&&typeof i!="boolean"?s={deviceId:i.deviceId}:s=i;try{if((yield this.getVideoInputDevices()).length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available");[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)})}catch(a){if(a.name===yl.NotReadableError&&ye.isChromiumBased()&&K.hasFeature(X.SCREEENSHARE_CONSTRAINTS_RETRY))try{s=!0,[o]=(yield navigator.mediaDevices.getUserMedia({video:s})).getVideoTracks(),l.info("getUserMediaWithoutTimeout::received_user_media_retry",{constraints:JSON.stringify(s)})}catch(d){yield this.handleGUMError("video",d,s)}else yield this.handleGUMError("video",a,s)}if(e&&n&&typeof i!="boolean"&&typeof i.width=="object"){const{width:a,height:d}=o.getSettings(),{ideal:h}=i.width;o.applyConstraints({width:{ideal:h},height:{ideal:Math.floor(d*h/a)},frameRate:i.frameRate})}return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),o})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw l.error("enumerate_devices_failed",{error:t}),new C("Failed to get available devices")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw l.error("enumerate_devices_failed",{error:e}),new C("Failed to get device")}})}onDeviceChange(t){return u(this,null,function*(){ye.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,n;const i=p=>`${p.kind}-${p.deviceId}`,s=this.availableDevices,o=new Set(s.map(p=>i(p))),a=yield this.getAvailableDevices(),d=new Set(a.map(p=>i(p))),h={added:a.filter(p=>!o.has(i(p))),removed:s.filter(p=>!d.has(i(p))),devices:a};if((r=h.added)!=null&&r.length||(n=h.removed)!=null&&n.length){l.info("repopulated_full_device_list",{devices:JSON.stringify(a)});const p=[...h.added,...h.removed];B.onSafeInitialization(()=>u(this,null,function*(){p.some(f=>f.kind==="audioinput")&&B.devices("AUDIO",a==null?void 0:a.filter(f=>f.kind==="audioinput")),p.some(f=>f.kind==="videoinput")&&B.devices("VIDEO",a==null?void 0:a.filter(f=>f.kind==="videoinput")),p.some(f=>f.kind==="audiooutput")&&B.devices("SPEAKER",a==null?void 0:a.filter(f=>f.kind==="audiooutput"))})),t(e,h,!1)}}),{signal:c(this,Us).signal})})}},Us=new WeakMap,Ir=new WeakMap,Sl=new WeakMap,zf);Zt([y.trace("WebMediaInterface.destruct")],Nt.prototype,"destruct",1),Zt([y.trace("WebMediaInterface.handlePermissionErrors")],Nt.prototype,"handlePermissionErrors",1),Zt([y.trace("WebMediaInterface.getAudioAndVideoTrack")],Nt.prototype,"getAudioAndVideoTrack",1),Zt([y.trace("WebMediaInterface.getAudioTrack")],Nt.prototype,"getAudioTrack",1),Zt([y.trace("WebMediaInterface.getScreenShareTracks")],Nt.prototype,"getScreenShareTracks",1),Zt([y.trace("WebMediaInterface.getVideoTrack")],Nt.prototype,"getVideoTrack",1),Zt([y.trace("WebMediaInterface.getAvailableDevices")],Nt.prototype,"getAvailableDevices",1),Zt([y.trace("WebMediaInterface.getAvailableDevicesByKind")],Nt.prototype,"getAvailableDevicesByKind",1),Zt([y.trace("WebMediaInterface.getDevice")],Nt.prototype,"getDevice",1),Zt([y.trace("WebMediaInterface.onDeviceChange")],Nt.prototype,"onDeviceChange",1),Nt=Zt([dt("1600")],Nt);const Yf=Nt,Tl={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(r){l.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){l.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},UA=(t=0)=>new Promise(e=>setTimeout(e,t)),VA=(t,e,r)=>{const n=typeof r=="number"?r:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const o=new Uint8Array(s.fftSize);let a=!1;setTimeout(()=>{a=!0},n);function d(){return a?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(h=>h!==128&&h!==0)?Promise.resolve(!1):UA().then(d))}return d().then(h=>(i.disconnect(),h),h=>{throw i.disconnect(),h})},BA=typeof AudioContext!="undefined"?AudioContext:null;class kl{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:BA},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:kl}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(r){}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 Qf=new kl,jA=3,HA=250;function WA(t){const e={},r=Qf.getOrCreate(e);let n=jA;function i(){return n-=1,VA(r,t.srcObject,HA).then(s=>s?n>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Qf.release(e)})}function Xf(t){return u(this,null,function*(){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let n=!1;try{const i=e.play();i&&(yield i),n=yield WA(e),n&&l.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){l.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return n})}var $A=Object.defineProperty,GA=Object.getOwnPropertyDescriptor,JA=(t,e,r,n)=>{for(var i=n>1?void 0:n?GA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$A(e,r,i),i};let _l=class extends Ci{constructor(t,e,r){super(),m(this,"constructorName",this.constructor.name),m(this,"userSelectedDevice"),m(this,"mediaInterface"),m(this,"isNonPreferredDevice"),m(this,"_mediaTrack"),m(this,"transformedMediaTrack"),m(this,"middlewares",[]),m(this,"currentDevice"),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=void 0,this.isNonPreferredDevice=r,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return u(this,null,function*(){const e=r=>{l.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){l.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw l.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track")}})}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}((t=this.currentDevice)==null?void 0:t.deviceId)!==this.mediaTrack.getSettings().deviceId&&(this.currentDevice=yield this.mediaInterface.getDevice(this.mediaTrack.getSettings().deviceId))})}addMiddleware(t){return u(this,null,function*(){if(ye.isWebKitBased()&&!K.hasFeature(X.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return l.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return l.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(l.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),l.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};_l=JA([dt("1600")],_l);const Zf=_l;var qA=Object.defineProperty,KA=Object.getOwnPropertyDescriptor,bl=(t,e,r,n)=>{for(var i=n>1?void 0:n?KA(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&qA(e,r,i),i};const wl="[Dyte]nonSilentDeviceLabels";class Fa extends Zf{setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="audioinput")throw l.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;this.userSelectedDevice=e.deviceId,yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,e.deviceId))}catch(r){throw l.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C(r.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){l.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const r=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(r)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield PA(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(n){l.error("AudioMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){l.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){l.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return n;s.find(d=>d.deviceId===e.getSettings().deviceId)||(n.stop(),l.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const o=JSON.parse(Tl.getItem(wl));if(o!=null&&o.devices.some(d=>d.label===n.label))return n;if(!(yield Xf(n))){const d=(r=o==null?void 0:o.devices.concat({label:n.label}))!=null?r:[{label:n.label}];return Tl.setItem(wl,JSON.stringify({devices:d})),n}l.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const a=n.getSettings().deviceId;return s.filter(d=>d.deviceId!==a).some(d=>u(this,null,function*(){if(n=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Xf(n))){const h=o.devices.concat({label:n.label});return Tl.setItem(wl,JSON.stringify({devices:h})),l.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return l.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}bl([y.trace("AudioMediaHandler.setTransformedTrack")],Fa.prototype,"setTransformedTrack",1),bl([y.trace("AudioMediaHandler.onTrackEnded")],Fa.prototype,"onTrackEnded",1),bl([y.trace("AudioMediaHandler.conditionallyChangeTrack")],Fa.prototype,"conditionallyChangeTrack",1);const zA=Fa;var Vs;class YA{constructor(e){_(this,Vs,void 0),m(this,"currentDevice"),T(this,Vs,e)}setupSpeaker(e){return u(this,null,function*(){var r;if(!(c(this,Vs)instanceof Yf))return;let n=e;if(e||([n]=yield c(this,Vs).getAvailableDevicesByKind("audiooutput")),!n)throw new C("No speaker found");((r=this.currentDevice)==null?void 0:r.deviceId)!==n.deviceId&&(this.currentDevice=n,document.querySelectorAll("audio").forEach(i=>u(this,null,function*(){if(typeof i.sinkId!="undefined"&&this.currentDevice.deviceId&&i.sinkId!==this.currentDevice.deviceId)try{yield i.setSinkId(this.currentDevice.deviceId)}catch(s){}})))})}}Vs=new WeakMap;const QA=YA;class XA extends Ci{constructor(e){super(),m(this,"mediaInterface"),m(this,"audioMediaTrack"),m(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:n,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=n,this.videoMediaTrack=i,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",b.emit(w.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(n){}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(n){l.error("ScreenShareHandler.updateConstraints.error",{error:n})}})}addMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this))}removeMediaTrackListeners(){var e;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const ZA=XA;var eM=Object.defineProperty,tM=Object.getOwnPropertyDescriptor,Ua=(t,e,r,n)=>{for(var i=n>1?void 0:n?tM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&eM(e,r,i),i},Bs,Va;class js extends Zf{constructor(e,r,n){super(e,r,n),_(this,Bs,void 0),_(this,Va,{disablePerFrameCanvasRendering:!1}),T(this,Bs,new AA)}setDevice(e){return u(this,null,function*(){if(!e)throw l.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!");if(e.kind!=="videoinput")throw l.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!");if(this.userSelectedDevice=e.deviceId,!(this.mediaTrack&&this.mediaTrack.enabled)){l.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw l.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){l.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield c(this,Bs).getTransformedVideoTrack(this.middlewares,this.mediaTrack,c(this,Va)),this.emit("trackChanged")}catch(n){l.error("VideoMediaHandler.setTransformedTrack",{error:n}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){T(this,Va,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new C("No media track enabled!");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){l.error("VideoMediaHandler.updateConstraints.error",{error:n})}})}terminateMiddlewareWebWorker(){c(this,Bs).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){l.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){l.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const n=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?n.filter(s=>!this.isNonPreferredDevice(s)):n;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(r.stop(),l.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),r})}}Bs=new WeakMap,Va=new WeakMap,Ua([y.trace("VideoMediaHandler.setTransformedTrack")],js.prototype,"setTransformedTrack",1),Ua([y.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],js.prototype,"setVideoMiddlewareGlobalConfig",1),Ua([y.trace("VideoMediaHandler.onTrackEnded")],js.prototype,"onTrackEnded",1),Ua([y.trace("VideoMediaHandler.conditionallyChangeTrack")],js.prototype,"conditionallyChangeTrack",1);const rM=js,eg=dr(Ld());var jt,Bi,Ba,Hs;const Ws=class{constructor(t){if(_(this,jt,void 0),_(this,Bi,void 0),_(this,Ba,void 0),_(this,Hs,void 0),!t)throw new C("Could not load preset.");T(this,jt,t.config),T(this,Ba,t.name),T(this,Bi,t.ui||dr(Ld().ui)),T(this,Hs,t.permissions.plugins.config)}static fromResponse(t){return new Ws(t)}static default(){return new Ws(eg)}static init(t,e=!0){return!t||e?new Ws(eg):new Ws(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:c(this,Bi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return c(this,jt).viewType}get maxVideoStreams(){return c(this,jt).maxVideoStreams}get maxScreenShareCount(){return c(this,jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(c(this,Hs)).filter(t=>c(this,Hs)[t].disabled)}get designTokens(){return c(this,Bi).designTokens}get configDiff(){return c(this,Bi).configDiff}get mediaConstraints(){var t,e,r,n,i,s,o,a,d,h,p,f,g,E,v,R,A,L,F,W,H,I,S,P;return{audio:{enableStereo:(n=(r=(e=(t=c(this,jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?n:Ui.audio.enableStereo,enableHighBitrate:(a=(o=(s=(i=c(this,jt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?a:Ui.audio.enableHighBitrate},video:{quality:(f=(p=(h=(d=c(this,jt))==null?void 0:d.media)==null?void 0:h.video)==null?void 0:p.quality)!=null?f:Ui.video.quality,frameRate:(R=(v=(E=(g=c(this,jt))==null?void 0:g.media)==null?void 0:E.video)==null?void 0:v.frameRate)!=null?R:Ui.video.frameRate},screenshare:{quality:(W=(F=(L=(A=c(this,jt))==null?void 0:A.media)==null?void 0:L.screenshare)==null?void 0:F.quality)!=null?W:Ui.screenshare.quality,frameRate:(P=(S=(I=(H=c(this,jt))==null?void 0:H.media)==null?void 0:I.screenshare)==null?void 0:S.frameRate)!=null?P:Ui.screenshare.frameRate}}}get name(){return c(this,Ba)}};let nM=Ws;jt=new WeakMap,Bi=new WeakMap,Ba=new WeakMap,Hs=new WeakMap;var iM=Object.defineProperty,sM=Object.getOwnPropertyDescriptor,tg=(t,e,r,n)=>{for(var i=n>1?void 0:n?sM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&iM(e,r,i),i},$s;class Cl extends Dt{constructor(e){super(),_(this,$s,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"viewerCount"),T(this,$s,e),this.viewerCount=0}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::start::permission_denied"),new C("User does not have permission to start livestreaming");this.setLivestreamState("STARTING");try{const e=yield je().startLivestreaming();this.playbackUrl=e}catch(e){throw l.error("DyteRecording::stop::livestream_failed_to_start",{error:e}),this.setLivestreamState("IDLE"),new C("Error while starting livestream")}})}stop(){return u(this,null,function*(){if(!c(this,$s).permissions.canLivestream)throw l.error("DyteLivestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming");if(this.state!=="LIVESTREAMING")throw l.error("DyteLivestream::stop::inconsistent_state"),new C("Livestream not started yet");try{this.setLivestreamState("STOPPING"),yield je().stopLivestreaming()}catch(e){throw l.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream")}})}}$s=new WeakMap,tg([y.trace("livestream.start")],Cl.prototype,"start",1),tg([y.trace("livestream.stop")],Cl.prototype,"stop",1);var oM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,cM=(t,e,r,n)=>{for(var i=n>1?void 0:n?aM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&oM(e,r,i),i},Gs,xn;class rg{constructor(e,r){m(this,"livestream"),_(this,Gs,void 0),_(this,xn,void 0),this.livestream=new Cl(e),T(this,xn,r),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=je(),{status:r,playbackUrl:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING")})}setupEvents(){c(this,xn).on(j.startedLivestream,e=>{this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING")}),c(this,xn).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,xn).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),c(this,xn).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),b.on(w.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(T(this,Gs,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),b.on(w.PEER_CLOSED,e=>{e.id===c(this,Gs)&&(T(this,Gs,void 0),this.livestream.setLivestreamState("IDLE"))}),b.onAsync(w.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(l.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){l.error("Error: LivestreamController.fetchLivestream")}}))}}Gs=new WeakMap,xn=new WeakMap,cM([y.trace("LivestreamController.setupEvents")],rg.prototype,"setupEvents",1);var dM=Object.defineProperty,lM=Object.getOwnPropertyDescriptor,Js=(t,e,r,n)=>{for(var i=n>1?void 0:n?lM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&dM(e,r,i),i};const ng={maxInvocations:1,period:200},Il={maxInvocations:5,period:1e3};var vt,Fn,Un,Rl,ig;class ji{constructor({name:e,socketHandler:r,meetingId:n}){_(this,Rl),m(this,"name",""),_(this,vt,{}),_(this,Fn,""),_(this,Un,void 0),m(this,"volatile"),m(this,"listeners",{}),this.name=e,T(this,Un,r),T(this,Fn,n)}set(e,r,n=!0,i=!1){return u(this,null,function*(){c(this,vt)[e]=r,n&&c(this,Un).storeInsertKeys(c(this,Fn),this.name,[{key:e,payload:r}]),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:c(this,vt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:c(this,vt)[e]})))})}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:n})=>{c(this,vt)[r]=n}),c(this,Un).storeInsertKeys(c(this,Fn),this.name,e)})}update(e,r,n=!0){return u(this,null,function*(){ue(this,Rl,ig).call(this,e,r,n)})}delete(e,r=!0,n=!1){return u(this,null,function*(){if(c(this,vt)[e]&&delete c(this,vt)[e],r)return c(this,Un).storeDeleteKeys(c(this,Fn),this.name,[{key:e}]);n&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{c(this,vt)[r]&&delete c(this,vt)[r]}),c(this,Un).storeDeleteKeys(c(this,Fn),this.name,e)})}get(e){if(c(this,vt)[e])return c(this,vt)[e]}getAll(){return c(this,vt)}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e){this.listeners[e]&&delete this.listeners[e]}populate(e){T(this,vt,e)}}vt=new WeakMap,Fn=new WeakMap,Un=new WeakMap,Rl=new WeakSet,ig=function(t,e,r=!0){let n;const i=c(this,vt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(i);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":n=[...i,...e];break;case"[object Object]":n=V(V({},i),e);break;case"[object Map]":n=new Map([...i,...e]);break;case"[object Set]":n=new Set([...i,...e]);break;default:n=e;break}this.set(t,n,r)},Js([Ct(Il)],ji.prototype,"set",1),Js([Ct(ng)],ji.prototype,"bulkSet",1),Js([Ct(Il)],ji.prototype,"update",1),Js([Ct(Il)],ji.prototype,"delete",1),Js([Ct(ng)],ji.prototype,"bulkDelete",1);var Hi,Wi,ja,Pl,Ha,Vn,Al,sg;class uM{constructor(e,r){_(this,ja),_(this,Al),m(this,"stores",new Map),_(this,Hi,void 0),_(this,Wi,""),_(this,Ha,void 0),_(this,Vn,new Map),T(this,Hi,r),T(this,Wi,e.getValue("meetingId")),T(this,Ha,e),ue(this,Al,sg).call(this)}create(e){const r=new ji({name:e,socketHandler:c(this,Hi),meetingId:c(this,Wi)});return c(this,Hi).storeGetKeys(c(this,Wi),e,[]),new Promise((n,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);c(this,Vn).set(e,{rejectTimeout:s,resolve:n,store:r})})}}Hi=new WeakMap,Wi=new WeakMap,ja=new WeakSet,Pl=function(){return c(this,Ha).getValue("peerId")},Ha=new WeakMap,Vn=new WeakMap,Al=new WeakSet,sg=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{c(this,Hi).on(t,e=>u(this,null,function*(){var r,n;if(e.pluginId!==c(this,Wi))return;const i=(r=e.storeItems)==null?void 0:r.map(o=>{var a;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((a=o.payload)!=null&&a.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===J.storeGetKeys){const o=c(this,Vn).get(e.storeName),a=this.stores.get(e.storeName)||(o==null?void 0:o.store);c(this,Vn).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(a),clearTimeout(o.rejectTimeout),c(this,Vn).delete(e.storeName)),i.forEach(d=>{a.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((n=c(this,Vn).get(e.storeName))==null?void 0:n.store);s!==void 0&&(t===J.storeInsertKeys&&i.forEach(({key:o,peerId:a,payload:d})=>{a===c(this,ja,Pl)&&t!==J.storeGetKeys||s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&i.forEach(({key:o,peerId:a})=>{a!==c(this,ja,Pl)&&s.delete(o,!1,!0)}))}))})};function Bn(t){var e,r,n,i,s,o,a,d,h,p,f,g,E;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(n=t.videoTrack)==null?void 0:n.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(a=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:a.enabled,trackId:(h=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:h.id},video:{enabled:(f=(p=t.screenShareTracks)==null?void 0:p.video)==null?void 0:f.enabled,trackId:(E=(g=t.screenShareTracks)==null?void 0:g.video)==null?void 0:E.id}}}}:{}}var hM=Object.defineProperty,pM=Object.getOwnPropertyDescriptor,$i=(t,e,r,n)=>{for(var i=n>1?void 0:n?pM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&hM(e,r,i),i};const mM=.8,fM=1.2;var qs,Ks,Wa,jn,Gi,zr,$a,Hn,Yr,Ml,Ga,Dl,Ol,og,ag;let Rr=(ag=class extends Dt{constructor(t,e,r,n){super(),_(this,jn),_(this,Ga),_(this,Ol),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"),_(this,qs,void 0),m(this,"supportsRemoteControl",!1),_(this,Ks,void 0),m(this,"presetName"),_(this,Wa,void 0),_(this,zr,void 0),_(this,$a,void 0),_(this,Hn,new Map),_(this,Yr,1),_(this,Ml,cr(H=>{if(!this.videoTrack)return;const{clientWidth:I,clientHeight:S}=H,{width:P,height:N}=this.videoTrack.getSettings();if(!P||!N)return;const ce=N/S,Le=P/I,$=Math.max(ce,Le);$>fM&&c(this,Yr)===1?(T(this,Yr,0),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Yr)})):$<mM&&c(this,Yr)===0&&(T(this,Yr,1),b.emit(w.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:c(this,Yr)}))},2e3)),T(this,Wa,t);const{id:i,userId:s,displayName:o,device:a,picture:d,isHost:h,flags:p,clientSpecificId:f,stageStatus:g,customParticipantId:E,audioMuted:v,audioTrack:R,videoEnabled:A=!1,videoTrack:L,producers:F,metadata:W}=e;this.id=i,this.userId=s,this.name=o,this.device=a,this.picture=d,this.isHost=h,this.flags=p,this.manualProducerConfig=jd,T(this,Ks,g!=null?g:"ON_STAGE"),this.customParticipantId=E!=null?E:f,this.audioEnabled=!v,this.audioTrack=R,this.videoEnabled=A,this.videoTrack=L,this.screenShareTracks={audio:void 0,video:void 0},this.producers=F!=null?F:[],this.presetName=W==null?void 0:W.preset_name,T(this,qs,!1),T(this,zr,r),T(this,$a,n),this.setupEvents()}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return c(this,Ks)}get roomJoined(){var t;return((t=c(this,jn,Gi))==null?void 0:t.roomJoined)===!0}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(l.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},Bn(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(l.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},Bn(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",ue(this,Ol,og))}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participant without joining room");if(!c(this,zr).permissions.pinParticipant)throw new C("You do not have permission to pin participants.");return c(this,jn,Gi).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participant without joining room");if(!c(this,zr).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.");return c(this,jn,Gi).pinPeer(null)})}setIsPinned(t,e=!0){T(this,qs,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant audio without joining room");if(c(this,zr).permissions.canDisableParticipantAudio)return c(this,jn,Gi).disableAudio(t);throw l.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.")})}kick(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t kick participant without joining room");if(c(this,zr).permissions.kickParticipant){yield b.emitAsync(w.KICK_PEER,{peerId:t});return}throw l.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(l.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.roomJoined)throw new C("Can`t disable participant video without joining room");if(c(this,zr).permissions.canDisableParticipantVideo)return c(this,jn,Gi).disableVideo(t);throw l.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.")})}getPermissions(){return u(this,null,function*(){return c(this,$a).getUserPermissions(this.userId)})}setStageStatus(t){T(this,Ks,t),this.emit("stageStatusUpdate",this)}get isPinned(){return c(this,qs)}registerVideoElement(t){var e,r;let n;(r=(e=c(this,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>c(this,Ml).call(this,t)),n.observe(t)),c(this,Hn).set(t,{observer:n}),ue(this,Ga,Dl).call(this,t)}deregisterVideoElement(t){var e,r;t.srcObject=void 0,(r=(e=c(this,Hn).get(t))==null?void 0:e.observer)==null||r.disconnect(),c(this,Hn).delete(t)}},qs=new WeakMap,Ks=new WeakMap,Wa=new WeakMap,jn=new WeakSet,Gi=function(){return c(this,Wa).getValue("roomNodeClient")},zr=new WeakMap,$a=new WeakMap,Hn=new WeakMap,Yr=new WeakMap,Ml=new WeakMap,Ga=new WeakSet,Dl=function(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0},Ol=new WeakSet,og=function(){Array.from(c(this,Hn).keys()).forEach(ue(this,Ga,Dl))},ag);$i([y.trace("DyteParticipant.disableAudio")],Rr.prototype,"disableAudio",1),$i([y.trace("DyteParticipant.kick")],Rr.prototype,"kick",1),$i([y.trace("DyteParticipant.disableVideo")],Rr.prototype,"disableVideo",1),$i([y.trace("DyteParticipant.getPermissions")],Rr.prototype,"getPermissions",1),$i([y.trace("DyteParticipant.setStageStatus")],Rr.prototype,"setStageStatus",1),Rr=$i([dt("1200")],Rr);class Ja extends Ff{constructor(e){const{onAddEvent:r="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:n,onClearEvent:i})}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,n=!1){return super.delete(e,r,n)}}var Wn;class gM extends Ci{constructor(){super(),_(this,Wn,void 0),T(this,Wn,new Map)}__set(e,r){return c(this,Wn).set(e,r)}__clear(){return c(this,Wn).clear()}get(e){return c(this,Wn).get(e)}toArray(){return Array.from(c(this,Wn).values())}}Wn=new WeakMap;function vM(t,e=2){return t.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,e).map(r=>r.charAt(0)).join("").toUpperCase()}const cg=1080,dg=1920,yM=(t,e,r,n,i,s)=>{let o=.5,a=.5;const d=i,h=s,p=Math.min(r/d,n/h);let f=d*p,g=h*p,E,v,R,A,L=1;return f<r&&(L=r/f),Math.abs(L-1)<1e-14&&g<n&&(L=n/g),f*=L,g*=L,R=d/(f/r),A=h/(g/n),E=(d-R)*o,v=(h-A)*a,E<0&&(E=0),v<0&&(v=0),R>d&&(R=d),A>h&&(A=h),[E,v,R,A,t,e,r,n]};var pr,zs,yt,Qr,Oe,Xr,Zr,er,ze;class EM extends Dt{constructor(e,r){super(),_(this,pr,void 0),_(this,zs,void 0),_(this,yt,void 0),_(this,Qr,void 0),_(this,Oe,{height:cg,width:dg}),_(this,Xr,{brand:"#2160FD",background:"#141414",videoBackground:"#191919",textOnBrand:"#EEEEEE"}),_(this,Zr,void 0),_(this,er,{}),_(this,ze,void 0),m(this,"cleanupEventListeners",()=>{c(this,zs).unsubscribe("stageStatus",this.handlePipMediaControls),c(this,ze).removeListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,ze).removeListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,ze).removeListener("roomLeft",this.disable)}),m(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()}),m(this,"onSelfVideoUpdateListener",({videoEnabled:n})=>{this.updateMediaSession("CAMERA",n)}),m(this,"onSelfAudioUpdateListener",({audioEnabled:n})=>{this.updateMediaSession("MIC",n)}),m(this,"handlePipMediaControls",n=>{n==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()}),m(this,"eventCallback",n=>{n==="CAMERA"&&(c(this,ze).videoEnabled?c(this,ze).disableVideo():c(this,ze).enableVideo(),this.emit("cameraToggled")),n==="MIC"&&(c(this,ze).audioEnabled?c(this,ze).disableAudio():c(this,ze).enableAudio(),this.emit("micToggled")),n==="END"&&(b.emit(w.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())}),m(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))}),m(this,"animate",()=>{c(this,er)!==void 0&&this.paintCanvas(),c(this,Zr)!==void 0&&T(this,Zr,requestAnimationFrame(()=>this.animate()))}),m(this,"disable",()=>{this.cleanupEventListeners(),cancelAnimationFrame(c(this,Zr)),document.body.removeChild(c(this,yt)),T(this,Zr,void 0),document.exitPictureInPicture()}),T(this,zs,e),T(this,ze,r),T(this,Xr,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand})}createVideoContainer(){T(this,yt,document.createElement("div")),c(this,yt).style.width="0.1px",c(this,yt).style.height="0.1px",c(this,yt).style.overflow="hidden",c(this,yt).style.position="absolute",c(this,yt).style.bottom="0",c(this,yt).style.right="0",c(this,yt).style.opacity="0",c(this,yt).appendChild(c(this,Qr))}setupEventListeners(){c(this,zs).subscribe("stageStatus",this.handlePipMediaControls),c(this,ze).addListener("videoUpdate",this.onSelfVideoUpdateListener),c(this,ze).addListener("audioUpdate",this.onSelfAudioUpdateListener),c(this,ze).addListener("roomLeft",this.disable)}createCanvas(){const e=document.createElement("canvas");e.height=c(this,Oe).height,e.width=c(this,Oe).width,T(this,pr,e)}setupMediaSessionEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("hangup",()=>{this.eventCallback("END")}),this.mountAudioEvents(),this.mountVideoEvents())}mountAudioEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setMicrophoneActive===void 0||c(this,ze).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||c(this,ze).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const e=Object.values(c(this,er)),r=e.filter(n=>n.pinned);return r.length===1?r:e}drawEmptyTile(e,r,n,i,s){if(c(this,pr)===void 0)return;const o=c(this,pr).getContext("2d"),a=c(this,pr).width,d=4,h=4,p=r-d*2,f=n-d*2,g=Math.floor(a/p),E=Math.floor(e/g),v=e%g*(p+d)+d,R=E*(f+d)+d;o.fillStyle=c(this,Xr).videoBackground,o.strokeStyle=c(this,Xr).brand,o.beginPath(),o.moveTo(v+h,R),o.arcTo(v+p,R,v+p,R+h,h),o.arcTo(v+p,R+f,v+p-h,R+f,h),o.arcTo(v,R+f,v,R+f-h,h),o.arcTo(v,R,v+h,R,h),o.closePath(),o.fill(),o.stroke();const A=p/6,L=p/2+v,F=f/2+R;if(o.save(),(i||s)&&(o.beginPath(),o.arc(L,F,A,0,Math.PI*2),o.fillStyle=c(this,Xr).brand,o.fill()),i&&(o.fillStyle=c(this,Xr).textOnBrand,o.font=`${A/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(i,L,F)),s){const W=new Image;W.src=s,W.onload=()=>{o.drawImage(W,L-A,F-A,A*2,A*2),o.restore()}}}drawGrid(e,r,n){if(c(this,pr)===void 0)return;const i=c(this,pr).getContext("2d");i.fillStyle=c(this,Xr).background,i.fillRect(0,0,c(this,Oe).width,c(this,Oe).height);const s=this.getSources();let o=0,a=0;for(;o<c(this,Oe).height-5;){let d=0;for(;d<c(this,Oe).width-5&&a<n;){const h=s[a].element;if(s[a].enabled){const[p,f,g,E,v,R,A,L]=yM(d,o,e,r,h.videoWidth,h.videoHeight);i.drawImage(h,p,f,g,E,v,R,A,L)}else this.drawEmptyTile(a,e,r,s[a].displayText);a+=1,d+=e}o+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[c(this,Oe).width,c(this,Oe).height];case 2:return[Math.floor(c(this,Oe).width/2),c(this,Oe).height];case 3:case 4:return[Math.floor(c(this,Oe).width/2),Math.floor(c(this,Oe).height/2)];case 5:case 6:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/2)];case 7:case 8:case 9:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/3)];default:return[Math.floor(c(this,Oe).width/3),Math.floor(c(this,Oe).height/2)]}}paintCanvas(){const e=this.getSources().length,[r,n]=this.calcGridElemSize(e);this.drawGrid(r,n,e)}isSupported(){return!!window.chrome&&document.pictureInPictureEnabled}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),c(this,yt))try{document.body.removeChild(c(this,yt))}catch(e){}this.removeAllSources(),T(this,pr,void 0),T(this,Qr,void 0),T(this,Zr,void 0)}init({height:e,width:r}={}){this.createCanvas(),this.setupMediaSessionEvents();const n=document.createElement("video");T(this,Oe,{height:e!=null?e:cg,width:r!=null?r:dg}),n.height=c(this,Oe).height,n.width=c(this,Oe).width,n.autoplay=!0,n.muted=!0,n.srcObject=c(this,pr).captureStream(24),T(this,Qr,n),c(this,Qr).onloadedmetadata=()=>{try{this.emit("pipStarted"),c(this,Qr).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(i){this.emit("pipEnded")}},this.createVideoContainer(),this.paintCanvas()}updateMediaSession(e,r){navigator.mediaSession!==void 0&&(e==="CAMERA"&&navigator.mediaSession.setCameraActive!==void 0&&navigator.mediaSession.setCameraActive(r),e==="MIC"&&navigator.mediaSession.setMicrophoneActive!==void 0&&navigator.mediaSession.setMicrophoneActive(r))}enableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!0)}disableSource(e){c(this,er)[e]!==void 0&&(c(this,er)[e].enabled=!1)}addSource(e,r,n,i=!1,s=void 0){i&&this.removePinnedSource(),c(this,er)[e]={id:e,element:r,enabled:n,pinned:i,displayText:s?vM(s):void 0}}removeSource(e){delete c(this,er)[e]}removePinnedSource(){const[e]=this.getSources();e&&this.removeSource(e.id)}removeAllSources(){T(this,er,{})}enable(){this.setupEventListeners(),this.updateMediaSession("CAMERA",c(this,ze).videoEnabled),this.updateMediaSession("MIC",c(this,ze).audioEnabled),document.body.appendChild(c(this,yt)),T(this,Zr,requestAnimationFrame(()=>this.animate())),c(this,Qr).requestPictureInPicture()}}pr=new WeakMap,zs=new WeakMap,yt=new WeakMap,Qr=new WeakMap,Oe=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,er=new WeakMap,ze=new WeakMap;var $n={},qa={},SM=Lu&&Lu.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qa,"__esModule",{value:!0}),qa.Logger=void 0;const Ji=SM(or),qi="awaitqueue";class TM{constructor(e){e?(this._debug=(0,Ji.default)(`${qi}:${e}`),this._warn=(0,Ji.default)(`${qi}:WARN:${e}`),this._error=(0,Ji.default)(`${qi}:ERROR:${e}`)):(this._debug=(0,Ji.default)(qi),this._warn=(0,Ji.default)(`${qi}:WARN`),this._error=(0,Ji.default)(`${qi}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}}qa.Logger=TM,Object.defineProperty($n,"__esModule",{value:!0});var Ki=$n.AwaitQueue=$n.AwaitQueueRemovedTaskError=$n.AwaitQueueStoppedError=void 0;const kM=qa,en=new kM.Logger;class Nl extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Nl)}}$n.AwaitQueueStoppedError=Nl;class Ka extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ka)}}$n.AwaitQueueRemovedTaskError=Ka;class _M{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,r){return u(this,null,function*(){if(r=r!=null?r:e.name,en.debug(`push() [name:${r}]`),typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch(n){}return new Promise((n,i)=>{const s={id:this.nextTaskId++,task:e,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:o=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),en.debug(`resolving task [name:${s.name}]`),n(o);const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)},reject:o=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),en.debug(`rejecting task [name:${s.name}]: %s`,String(o)),i(o),!this.stopping)){const[a]=this.pendingTasks.values();a&&!a.executedAt&&this.execute(a)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){en.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())en.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){en.debug(`remove() [taskIdx:${e}]`);const r=Array.from(this.pendingTasks.values())[e];if(!r){en.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}r.reject(new Ka)}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:r++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}execute(e){return u(this,null,function*(){if(en.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=yield e.task();e.resolve(r)}catch(r){e.reject(r)}})}}Ki=$n.AwaitQueue=_M;var za;class lg{constructor(){m(this,"meetingTitle"),m(this,"roomName"),m(this,"roomUUID"),_(this,za,void 0),m(this,"context"),m(this,"authToken"),m(this,"maxPreferredStreams"),m(this,"roomJoined")}get peerId(){return this.context.getValue("peerId")}get sfuHandler(){return c(this,za)}get socketState(){return{state:void 0,reconnected:!1,reconnectionAttempt:void 0}}get mediaState(){return c(this,za).transportState}reconnect(){throw new C("Method not implemented.")}partialJoinRoom(e,r,n=!1,i=void 0){return u(this,null,function*(){throw new C("Method not implemented.")})}joinRoom(e,r){return u(this,arguments,function*(n,i,s={},o=!1,a=!1){throw new C("Method not implemented.")})}leaveRoom(){return u(this,null,function*(){throw new C("Method not implemented.")})}reset(e=!0){throw new C("Method not implemented")}handleSocketCallbacks(e){return u(this,null,function*(){throw new C("Method not implemented.")})}handleSockets(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}shareMic(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareWebcam(e){return u(this,null,function*(){throw new C("Method not implemented.")})}shareScreen(e){return u(this,null,function*(){throw new C("Method not implemented.")})}unmuteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}muteSelf(){return u(this,null,function*(){throw new C("Method not implemented.")})}pauseWebcam(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableScreenShare(){return u(this,null,function*(){throw new C("Method not implemented.")})}acceptWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}rejectWaitingRequest(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAll(e){return u(this,null,function*(){throw new C("Method not implemented.")})}muteAllVideo(){return u(this,null,function*(){throw new C("Method not implemented.")})}disableAudio(e){return u(this,null,function*(){throw new C("Method not implemented.")})}disableVideo(e){return u(this,null,function*(){throw new C("Method not implemented.")})}kickAll(){return u(this,null,function*(){throw new C("Method not implemented.")})}kick(e){return u(this,null,function*(){throw new C("Method not implemented.")})}pinPeer(e){return u(this,null,function*(){throw new C("Method not implemented.")})}getConsumers(){throw new C("Method not implemented.")}stopAllProducers(){throw new C("Method not implemented.")}activatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}deactivatePeers(e){return u(this,null,function*(){throw new C("Method not implemented.")})}switchConsumersToLayer(e,r){return u(this,null,function*(){throw new C("Method not implemented.")})}}za=new WeakMap;var Pr=(t=>(t.INITIALIZING="INITIALIZING",t.INITIALIZED="INITIALIZED",t.NOT_INITIALIZED="NOT_INITIALIZED",t))(Pr||{});class ug extends _t.EventEmitter{}class Gn extends _t.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...r){const n=this.listenerCount(e);try{return this.emit(e,...r)}catch(i){return l.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(n)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const n={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,n,...r)})}safeEmitAsPromiseWithTimeout(e,r,...n){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...n,i,s)}catch(o){l.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}function bM(t,e){const r=new Error(e);return r.name=t,r}class Jn extends C{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Jn):this.stack=new Error(e).stack}}class it extends C{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,it):this.stack=new Error(e).stack}}var Ya,Qa,Xa,Za,Ar,ec,tc,mr,zi,rc,nc,ic,Ll,xl,hg,Fl,pg;class mg extends Gn{constructor({id:e,localId:r,producerId:n,producingPeerId:i,producingTransportId:s,handler:o,track:a,appData:d,paused:h,reuseTrack:p,rtpReceiver:f}){super(),_(this,ic),_(this,xl),_(this,Fl),m(this,"rtpReceiver"),m(this,"observer"),_(this,Ya,void 0),_(this,Qa,void 0),_(this,Xa,void 0),_(this,Za,void 0),_(this,Ar,void 0),_(this,ec,void 0),_(this,tc,void 0),_(this,mr,void 0),_(this,zi,void 0),_(this,rc,void 0),_(this,nc,void 0),T(this,Ya,e),T(this,Qa,r),T(this,tc,o),T(this,nc,d),T(this,rc,i),T(this,Za,s),T(this,Ar,!1),T(this,Xa,n),T(this,mr,a),T(this,zi,h!=null?h:!1),T(this,ec,p),this.observer=new Gn,this.rtpReceiver=f,ue(this,xl,hg).call(this)}get id(){return c(this,Ya)}get peerId(){return c(this,rc)}get localId(){return c(this,Qa)}get producerId(){return c(this,Xa)}get producingTransportId(){return c(this,Za)}get closed(){return c(this,Ar)}get kind(){return c(this,mr).kind}get track(){return c(this,mr)}get paused(){return c(this,zi)}get remotelyPaused(){return this.paused}get appData(){return c(this,nc)}close(e){c(this,Ar)||(l.debug("Consumer::close() with reason:",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,closureReason:e,kind:this.kind}}),T(this,Ar,!0),c(this,ec)||ue(this,Fl,pg).call(this),this.emit("close",e),this.observer.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(c(this,Ar))throw new it("closed");return c(this,tc).getReceiverStats(this.localId)})}pause(){if(l.debug("consumer::pause()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ar)){l.error("consumer::pause() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,zi,!0),c(this,mr).enabled=!1,this.observer.safeEmit("pause")}resume(){if(l.debug("consumer::resume()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),c(this,Ar)){l.error("Consumer::resume() | Consumer closed",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}});return}T(this,zi,!1),c(this,mr).enabled=!0,this.observer.safeEmit("resume")}}Ya=new WeakMap,Qa=new WeakMap,Xa=new WeakMap,Za=new WeakMap,Ar=new WeakMap,ec=new WeakMap,tc=new WeakMap,mr=new WeakMap,zi=new WeakMap,rc=new WeakMap,nc=new WeakMap,ic=new WeakSet,Ll=function(){l.debug('Consumer::track "ended" event',{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}),this.safeEmit("trackended"),this.observer.safeEmit("trackended")},xl=new WeakSet,hg=function(){c(this,mr).addEventListener("ended",ue(this,ic,Ll).bind(this))},Fl=new WeakSet,pg=function(){try{c(this,mr).removeEventListener("ended",ue(this,ic,Ll)),c(this,mr).stop()}catch(t){l.error("Consumer::destroyTrack()",{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind},error:t})}};let wM=class extends mg{};const fg=t=>new Promise(e=>setTimeout(e,t));function fr(t,e){return u(this,null,function*(){return new Promise((r,n)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let a=0,d,h=!1;const p=f=>{h=!0,n(f)};for(;a<s;){try{const f=yield t(a,p);return r(f)}catch(f){if(d=f,h)break;if(a<s)i==="linear"?yield fg(o*(a+1)):i==="exponential"&&(yield fg(o*(a+Math.max(0,a-1))));else break}a+=1}return n(d)}))})}function sc(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(r=>r.then(n=>({status:"fulfilled",value:n})).catch(n=>({status:"rejected",reason:n})));return Promise.all(e)}function CM(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}function gg(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Ul(t){return Math.random().toString(36).substring(2,2+t)}const oc=1;function vg(t){const e=t;return delete e.payload._bolt,e}function IM(t){return t.payload&&gg(t.payload)}function ac(t){var e,r;return IM(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var qn;const Ys=class extends _t.EventEmitter{constructor(t,e,r){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),_(this,qn,new Map),m(this,"respond",(n,i,s=!1)=>{let o;s?o=Ys.createErrorResponse(n,i):o=Ys.createResponse(n,i),this.channel.send(JSON.stringify(o))}),m(this,"notify",n=>{const i=Ys.createNotification(n);this.channel.send(JSON.stringify(i))}),m(this,"request",n=>u(this,null,function*(){const i=Ys.createRequest(n),s=new Promise((o,a)=>{const d=1e3*(5+.1*this.queue.size),{id:h}=i.payload._bolt,p={id:h,method:i.type,resolve:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),o(f))},timer:setTimeout(()=>{this.queue.delete(h)&&a(new Error(`request timeout for message id: ${h}`))},d),cancel:f=>{this.queue.delete(h)&&(clearTimeout(p.timer),a(f))}};this.queue.set(h,p)});return this.channel.send(JSON.stringify(i)),s})),m(this,"send",n=>{const i=JSON.stringify(n),s=16384;if(i.length>s){const o=s-200,a=Math.ceil(i.length/o),d=[];for(let p=0;p<a;p+=1){const f=p*o,g=(p+1)*o;d.push(i.slice(f,g))}const h=gn();for(let p=0;p<a;p+=1){const f=d[p],g=JSON.stringify({id:h,count:a,chunkIndex:p,chunk:f});l.debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else l.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),m(this,"processMessage",n=>{var i;c(this,qn).has(n.id)||c(this,qn).set(n.id,[]);const s=c(this,qn).get(n.id);if(s[n.chunkIndex]=n,(s==null?void 0:s.length)===n.count&&!s.some(o=>o===void 0)){const o=c(this,qn).get(n.id),a=o==null?void 0:o.reduce((h,p)=>h+p.chunk,"");c(this,qn).delete(n.id);const d=JSON.parse(a);if(!d.payload||!gg(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),m(this,"processResponseMsg",n=>{const{id:i}=n.payload._bolt,s=this.queue.get(i);return s?(l.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(n)}`),n.type==="error"?s.cancel(vg(n)):s.resolve(vg(n)),!0):!1}),m(this,"processBoltHandshake",n=>{var i,s;return n.type==="_bolt"||n.type==="handshake"?(this.respond((s=(i=n.payload._bolt)==null?void 0:i.id)!=null?s:Ul(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=r,this.channel=t,this.queue=new Map}};let Qs=Ys;qn=new WeakMap,m(Qs,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{_bolt:{id:Ul(8),type:"REQUEST",version:oc}})}}),m(Qs,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:ne(V({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:oc}})}}),m(Qs,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:ne(V({},t.payload),{bolt:{id:Ul(8),type:"NOTIFY",version:oc}})}}),m(Qs,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:oc}}}));const Vl="transport closed";class yg extends Gn{constructor({id:e,direction:r,handlerFactory:n,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:o,additionalSettings:a,appData:d,config:h}){var p,f;super(),m(this,"awaitQueue"),m(this,"observer"),m(this,"id"),m(this,"serverId"),m(this,"closed",!1),m(this,"direction"),m(this,"maxSctpMessageSize"),m(this,"handler"),m(this,"connectionState","new"),m(this,"producers"),m(this,"consumers"),m(this,"datachannels"),m(this,"connected",!1),m(this,"eventsDCReadyPromise"),m(this,"eventsDCReadyPromiseResolver"),m(this,"eventsDCFailureTimer"),m(this,"transportConnectionPromise"),m(this,"consumerTrackEvents"),m(this,"unknownTracksMap"),m(this,"consumerTrackPool"),m(this,"appData"),l.debug(`constructor() [id: ${e}, direction: ${r}]`),this.id=e,this.direction=r;const g=CM(a,{});delete g.iceServers,delete g.iceTransportPolicy,delete g.bundlePolicy,delete g.rtcpMuxPolicy,delete g.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.consumerTrackPool=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ki,this.observer=new Gn,this.handler=n(),this.handler._enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler._enableStereo=(f=h==null?void 0:h.enableStereo)!=null?f:!1,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:r,iceServers:i,iceTransportPolicy:s,additionalSettings:a,proprietaryConstraints:o}),this.appData=d||{},this.transportConnectionPromise=new Promise(E=>{this.observer.once("connected",()=>{E(!0)}),this.observer.once("disconnect",()=>{E(!1)}),this.observer.once("close",()=>{E(!1)})}),this.eventsDCReadyPromise=new Promise(E=>{this.eventsDCReadyPromiseResolver=E}),this.handler.on("@connectionstatechange",E=>{E!==this.connectionState&&(l.debug(`connection state changed to ${E}`),this.connectionState=E,E==="connected"&&(this.connected=!0,this.observer.emit("connected")),E==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(E==="failed"||E==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",E))}),this.handler.on("@icecandidate",({candidate:E})=>{this.closed||this.safeEmit("icecandidate",E)}),this.handler.on("dc_open",E=>{let v=this.datachannels.get(E.label);v||(v||(v=new Qs(E,E.label,this.serverId),this.datachannels.set(E.label,v)),this.eventsDCFailureTimer=setTimeout(()=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",E.label))},5e3))}),this.handler.on("datachannel",(E,v)=>{E.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const R=this.datachannels.get(E.label);if(!R){l.error("unregistered datachannel for message",{rtcChannel:{label:E.label,message:v}});return}try{const A=JSON.parse(v);l.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:A.id,count:A.count,chunkIndex:A.chunkIndex,chunk:A.chunk,transprtId:this.serverId}});const L=R.processMessage(A);if(!L)return;l.debug(`datachannel message with id:${A.id} on transport:${this.serverId}complete - ${JSON.stringify(L)}`),this.emit(`datachannel:${E.label}`,R.label,L)}catch(A){l.error("error parsing message",{error:A})}})}get isConnected(){return this.transportConnectionPromise}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(l.debug("close()"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Vl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Vl)}),this.consumers.clear(),this.consumerTrackPool.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new it("closed");return this.handler.getTransportStats()})}restartIce(){return u(this,null,function*(){if(l.debug("restartIce()"),this.closed)throw new it("closed");return this.handler.restartIce()})}updateIceServers(){return u(this,arguments,function*({iceServers:e}={}){if(l.debug("updateIceServers()"),this.closed)throw new it("closed");return this.handler.updateIceServers(e)})}setRemoteOffer(e){return u(this,null,function*(){yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer(),n=Kc(r.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const s=V({},i),o=s.fmtp.find(a=>a.payload===111);return o&&(o.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(a=>a.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),r.sdp=ny(n),yield this.setLocalDescription(r),r})}sendErrorOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n,!0)}sendResponseOverDC(e,r,n){const i=this.getDatachannel(e);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});i.respond(r,n)}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){l.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}createConsumerOverDC(e){return u(this,null,function*(){const r=this.getDatachannel("events");if(!r)throw bM("DC_NOT_READY","events datachannel not ready");if(e.length===0)throw new Error("one of producer id or publisher id is required");const n={type:"create_consumer",payload:{}};e.length===1?n.payload={producerId:e[0].producerId,publisherId:e[0].producingTransportId}:n.payload={publisherId:e[0].producingTransportId};const i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=(yield r.request(n)).payload,o=new Map;return Object.entries(s).forEach(([a,d])=>{const h=i.get(d.producerId);if(!h){l.error(`unknown entry in create consumer response, producerId: ${d.producerId}`,{consumerState:d});return}o.set(d.producerId,{consumerId:a,producingTransportId:h.producingTransportId,kind:h.kind,paused:h.pause,streamId:d.streamId,trackId:d.trackId,screenShare:h.screenShare,appData:{}})}),l.info(`createConsumerOverDC::response ${JSON.stringify(s)}`),o})}}class Eg extends Gn{constructor({id:e,localId:r,track:n,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,handler:a,appData:d,rtpSender:h}){super(),m(this,"_id"),m(this,"_localId"),m(this,"_closed",!1),m(this,"_handler"),m(this,"_track"),m(this,"_kind"),m(this,"_paused"),m(this,"_maxSpatialLayer"),m(this,"_stopTracks"),m(this,"_disableTrackOnPause"),m(this,"_zeroRtpOnPause"),m(this,"_appData"),m(this,"observer"),m(this,"rtpSender"),this._id=e,this._localId=r,this._track=n,this._kind=n.kind,this._paused=s?!n.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=i,this._disableTrackOnPause=s,this._zeroRtpOnPause=o,this._appData=d||{},this._onTrackEnded=this._onTrackEnded.bind(this),this._handler=a,this.rtpSender=h,this.observer=new Gn,this._handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get track(){return this._track}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){throw new Error("cannot override appData object")}close(e){return u(this,null,function*(){if(this._closed)return;if(l.debug("Producer::close() with reason:"),this._closed=!0,this._destroyTrack(),e===Vl){this.observer.emit("close");return}const{offerSdp:r,callback:n}=yield this._handler.stopSending(this.localId);this.observer.emit("close");const{answer:i}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});n(i)})}getStats(){return u(this,null,function*(){if(this._closed)throw new it("closed");return this._handler.getSenderStats(this.localId)})}pause(){l.debug("Producer::pause()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed&&l.error("Producer::pause() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,null),this.observer.emit("pause")}resume(){if(l.debug("Producer::resume()",{producer:{id:this.id,appData:this.appData,kind:this.kind}}),this._closed){l.error("Producer::resume() | Producer closed",{producer:{id:this.id,appData:this.appData,kind:this.kind}});return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&this._handler.replaceTrack(this.localId,this._track),this.observer.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(l.debug("Producer::replaceTrack()",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}}),this._closed){if(r&&this._stopTracks)try{r.stop()}catch(n){l.error("Producer::replaceTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id},error:n})}throw new it("closed")}else if(r&&r.readyState==="ended")throw new it("track ended");if(r===this._track){l.debug("replaceTrack() | same track, ignored",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:r==null?void 0:r.id}});return}(!this._zeroRtpOnPause||!this._paused)&&(yield this._handler.replaceTrack(this.localId,r)),this._destroyTrack(),this._track=r,this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(this._kind!=="video")throw new Jn("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield this._handler.setMaxSpatialLayer(this.localId,e),this._maxSpatialLayer=e})}setRtpEncodingParameters(e){return u(this,null,function*(){if(this._closed)throw new it("closed");if(typeof e!="object")throw new TypeError("invalid params");yield this._handler.setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){l.debug('Producer::track "ended" event',{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:this.track.id}}),this.observer.emit("trackended"),this.safeEmit("trackended",this.track.id)}_handleTrack(){this._track&&this._track.addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(this._track)try{this._track.removeEventListener("ended",this._onTrackEnded),this._stopTracks&&this._track.stop()}catch(r){l.error("Producer::_destroyTrack",{producer:{id:this.id,appData:this.appData,kind:this.kind,trackId:(e=this._track)==null?void 0:e.id},error:r})}}}let RM=class extends Eg{},PM=class extends yg{consume(t){return u(this,null,function*(){const{producers:e,producingPeerId:r,consumeOverDC:n}=t;if(l.debug(`consume() peerId: ${r}, producers: ${JSON.stringify(e)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new Jn("not a receiving Transport");if(typeof t.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[];let s;if(n)s=yield this.createConsumerOverDC(e);else{const o={producingPeerId:r};e.length===1&&(o.producerId=e[0].producerId);const{consumersMap:a}=yield this.safeEmitAsPromise("consume_peer",V({},o));s=a}return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:R}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:r,producingTransportId:R,paused:f,screenShare:p,appData:v}))}),sc(i)})}connect(){return u(this,null,function*(){try{const{offerSdp:t,callback:e}=yield this.handler.connect(),{answer:r}=yield this.safeEmitAsPromise("connect",{offer:t});if(yield e(r),!(yield this.isConnected))throw new Error("ice connection failed");if(!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(t){throw l.error("transport failed to connect:",t),t}})}_ontrack(t){const{track:e,transceiver:r,streams:n}=t;l.info(`track event received [trackId: ${e.id}]`);const i=`${n[0].id}:${e.kind}`;e.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${e.id}]`),this.consumerTrackPool.delete(e.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(e.id,[e,r]);const s=this.consumerTrackEvents.get(i);s?(s(e,r),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}consumerCreationTask(t){return u(this,arguments,function*({consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,paused:a,screenShare:d,appData:h,kind:p}){const f=`${s}:${p}`,g={consumerId:e,producerId:r,producingPeerId:n,producingTransportId:i,streamId:s,trackId:o,appData:h,kind:p,paused:a,screenShare:d,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((E,v)=>{const R=setTimeout(()=>{this.consumerTrackEvents.delete(f),g.isTimedout=!0,v(g)},5e3),A=(W,H)=>{try{if(W.readyState==="ended")clearTimeout(R),v(g);else{const I=W;I.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const S=new wM({id:e,localId:H.mid,track:I,paused:a,producerId:r,producingPeerId:n,producingTransportId:i,handler:this.handler,appData:ne(V({},h),{screenShare:d,peerId:n}),reuseTrack:!0,rtpReceiver:H.receiver});this.consumers.set(e,S),S.once("close",()=>{this.consumers.delete(S.id),this.handler.midTransceiverMap.delete(H.mid)}),l.info("consumer created for ",{consumer:{id:e,kind:p,appData:{screenShare:d},peerId:n,producerId:r}}),this.observer.emit("newconsumer",S),clearTimeout(R),E(S)}}catch(I){l.warn("error while creating consumer:",I),clearTimeout(R),v(g)}},L=this.consumerTrackPool.get(e);if((L==null?void 0:L.length)===2){A(L[0],L[1]);return}const F=this.unknownTracksMap.get(f);F?(this.unknownTracksMap.delete(f),A(F.track,F.transceiver)):this.consumerTrackEvents.set(f,A)})})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return sc(t.map(e=>u(this,null,function*(){return fr(r=>u(this,null,function*(){return r>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.consumerCreationTask(V({},e))}))})))})}produce(){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,stopTracks:n=!0,disableTrackOnPause:i=!0,zeroRtpOnPause:s=!1,appData:o={}}={}){if(l.debug(`produce() [track:${t.id}]`),t){if(this.direction!=="send")throw new Jn("not a sending Transport");if(t.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:a,localId:d,rtpSender:h}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:f,callback:g,sender:E,mid:v}=yield this.handler.send({track:t,encodings:e,codecOption:r,screenShare:o==null?void 0:o.screenShare}),{answer:R,producerId:A}=yield this.safeEmitAsPromise("produce",{offer:f,kind:t.kind,paused:i?!t.enabled:!1,appData:ne(V({},o||{}),{mid:v})}),L=yield g(R);return{producerId:A,localId:L,rtpSender:E}}),"producer"),p=new RM({id:a,localId:d,track:t,stopTracks:n,disableTrackOnPause:i,zeroRtpOnPause:s,appData:o,handler:this.handler,rtpSender:h});return this.producers.set(a,p),p.observer.on("close",()=>{this.producers.delete(p.id)}),this.emit("newproducer",p),this.observer.emit("newproducer",p),p})}};class Bl extends Gn{constructor(){super(),m(this,"_mapMidTransceiver",new Map),m(this,"_enableHighBitrate",!1),m(this,"_enableStereo",!1),this._mapMidTransceiver=new Map,this._enableHighBitrate=!1}get midTransceiverMap(){return this._mapMidTransceiver}}class jl extends Bl{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new jl}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("close()"),this._pc)try{this._pc.close()}catch(e){l.error("pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Chrome74::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`send() [kind:${r.kind}, track.id:${r.id}]`);const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n});if(!navigator.isReactNative){l.debug("creating new transceiver");const h=RTCRtpSender.getCapabilities(r.kind);l.info(`senders available params: ${JSON.stringify(h)}`);const p=[];if(i){const f=h.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`codecOption.parameters:${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=Array.from(new Set(g).values());f.sdpFmtpLine=E.join(";")}p.push(f)}l.info(`selected codecs: ${JSON.stringify(p)}`),a.setCodecPreferences(p)}const d=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(d),i&&i.name==="opus"){const h=this._enableStereo,p=this._enableHighBitrate?h?128e3:64e3:h?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${h?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${p}`),d.sdp+=`a=rtcp-fb:111 nack\r
20
+ `}return{offerSdp:d,callback:h=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this._pc.setRemoteDescription(h),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`stopReceiving() [localId:${e}]`),Error("method not implemented")})}pauseReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`pauseReceiving() [localId:${e}]`),Error("method not implemented")})}resumeReceiving(e){return u(this,null,function*(){throw this._assertRecvDirection(),l.debug(`resumeReceiving() [localId:${e}]`),Error("method not implemented")})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.addEventListener("datachannel",e=>{l.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n.data)))}})}}class cc extends Bl{constructor(e){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1),m(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new cc(e)}get name(){return"Firefox60"}get pc(){return this._pc}close(){if(l.debug("Firefox60::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Firefox60::pc.close()",{error:e})}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Firefox60::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Firefox60::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Firefox60::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){throw l.debug("Firefox60::updateIceServers()"),new Error("not supported")})}restartIce(){return u(this,null,function*(){l.debug("Firefox60::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`Firefox60::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`Firefox60::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,screenShare:i}){this._assertSendDirection(),l.debug(`Firefox60::send() [kind:${r.kind}, track.id:${r.id}]`),l.debug("Firefox60::creating new transceiver");const s=this.supportsSendEncodings&&n!==void 0?{sendEncodings:n}:{},o=this._pc.addTransceiver(r,V({direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream]},s));if(!this.supportsSendEncodings&&n){n.reverse();const d=o.sender.getParameters();d.encodings=n,yield o.sender.setParameters(d)}const a=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(a),r.kind==="audio"){const d=this._enableStereo,h=this._enableHighBitrate?d?128e3:64e3:d?64e3:32e3;a.sdp=a.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${this.supportsSendEncodings?"":`${d?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${h}`}`)}return{offerSdp:a,callback:d=>u(this,null,function*(){return l.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),yield this._pc.setRemoteDescription(d),this.midTransceiverMap.set(o.mid,o),o.mid}),sender:o.sender,mid:o.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Firefox60::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated transceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Firefox60::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters(),s=i.encodings.length-1-r;i.encodings.forEach((o,a)=>{a>=s?o.active=!0:o.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Firefox60::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`Firefox60::stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Firefox60::stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Firefox60::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("datachannel",e=>{l.info("Firefox60::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Firefox60::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Firefox60::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=yield n.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})}),this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Firefox60::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Firefox60::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Firefox60::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})})}}class Hl extends Bl{constructor(){super(),m(this,"_direction"),m(this,"_pc"),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_transportReady",!1)}static createFactory(){return()=>new Hl}get name(){return"Chrome74"}get pc(){return this._pc}close(){if(l.debug("Safari12::close()"),this._pc)try{this._pc.close()}catch(e){l.error("Safari12::pc.close()",e)}}init({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:o}){l.debug("Safari12::init()"),this._direction=e,this._pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:n||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),o&&this._pc.addEventListener("track",a=>{o(a)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this._pc.createDataChannel("dyte"),r=yield this._pc.createOffer();return l.info(`Safari12::connect offer: ${JSON.stringify(r)}`),yield this._pc.setLocalDescription(r),{offerSdp:r,callback:n=>u(this,null,function*(){l.debug(`Safari12::connect() | calling pc.setRemoteDescription() [answer: ${JSON.stringify(n)}]`),yield this._pc.setRemoteDescription(n),e.close()})}})}updateIceServers(e){return u(this,null,function*(){l.debug("Safari12::updateIceServers()");const r=this._pc.getConfiguration();r.iceServers=e,this._pc.setConfiguration(r)})}restartIce(){return u(this,null,function*(){l.debug("Safari12::restartIce()");const e=yield this.pc.createOffer({iceRestart:!0});return l.debug(`restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){l.info(`restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this._pc.setRemoteDescription(r)})}})}getTransportStats(){return u(this,null,function*(){return this._pc.getStats()})}send(e){return u(this,arguments,function*({track:r,encodings:n,codecOption:i,screenShare:s}){var o;this._assertSendDirection(),l.debug(`Safari12::send() [kind: ${r.kind}, track.id: ${r.id}]`),l.debug("Safari12::creating new transceiver");const a=this._pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:n}),d=RTCRtpSender.getCapabilities(r.kind);l.info(`Safari12::senders available params: ${JSON.stringify(d)}`);const h=[];if(i){const f=d.codecs.find(g=>g.mimeType.includes(i.name));if(i.parameters){l.info(`Safari12::codecOption.parameters:, ${JSON.stringify(i.parameters)}`);const g=((o=f.sdpFmtpLine)==null?void 0:o.split(";"))||[];g.push(...i.parameters);const E=[...new Set(g).values()];f.sdpFmtpLine=E.join(";")}h.push(f)}l.info(`Safari12::selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h);const p=yield this._pc.createOffer();if(!this._transportReady)throw new Error("webrtc transport not connected");if(yield this._pc.setLocalDescription(p),r.kind==="audio"){const f=this._enableStereo,g=this._enableHighBitrate?f?128e3:64e3:f?64e3:32e3;p.sdp=p.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;usedtx=1${f?"":";stereo=1;sprop-stereo=1"};maxaveragebitrate=${g}`)}return{offerSdp:p,callback:f=>u(this,null,function*(){return l.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(f)}]`),yield this._pc.setRemoteDescription(f),this.midTransceiverMap.set(a.mid,a),a.mid}),sender:a.sender,mid:a.mid}})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),l.debug(`Safari12::stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this._pc.removeTrack(r.sender),r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`Safari12::stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?l.debug(`Safari12::replaceTrack() [localId:${e}, track.id:${r.id}]`):l.debug(`Safari12::replaceTrack() [localId:${e}, no track]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");yield n.sender.replaceTrack(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield n.sender.setParameters(i)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),l.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");const i=n.sender.getParameters();i.encodings.forEach((s,o)=>{i.encodings[o]=V(V({},s),r)}),yield n.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}receive(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`recieve() | calling pc.setLocalDescription() [answer:${JSON.stringify(e)}]`);const r=this._pc.getTransceivers().at(-1);return l.info("Safari12::Transceiver is now receiving"),this.midTransceiverMap.set(r.mid,r),{track:r.receiver.track,localId:r.mid}})}stopReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::stopReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive",l.info(`Safari12::active transcievers: ${JSON.stringify(this._pc.getTransceivers())}`);const n=yield this._pc.createOffer();return l.debug(`stopRecieving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`stopRecieving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}pauseReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::pauseReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="inactive";const n=yield this._pc.createOffer();return l.debug(`pauseReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),yield this._pc.setLocalDescription(n),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`pauseReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}resumeReceiving(e){return u(this,null,function*(){this._assertRecvDirection(),l.debug(`Safari12::resumeReceiving() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.direction="recvonly";const n=yield this._generateOffer();return l.debug(`Safari12::resumeReceiving() | calling pc.setLocalDescription() [offer:${JSON.stringify(n)}]`),{offerSdp:n,callback:i=>u(this,null,function*(){l.debug(`Safari12::resumeReceiving() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this._pc.setRemoteDescription(i)})}})}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}_generateOffer(){return u(this,null,function*(){const e=yield this._pc.createOffer();return yield this._pc.setLocalDescription(e),e})}_setAnswer(e){return u(this,null,function*(){l.debug(`Safari12::_setAnswer() | calling pc.setRemoteDescription() [answer:${JSON.stringify(e)}]`),yield this._pc.setRemoteDescription(e)})}_addEventListeners(){this._pc.addEventListener("iceconnectionstatechange",()=>{switch(this._pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this._pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),l.debug("Safari12::negotiationneeded")}),this._pc.addEventListener("icegatheringstatechange",()=>{switch(this._pc.iceGatheringState){case"gathering":l.debug("Safari12::icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":l.debug("Safari12::icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:l.warn("Safari12::unknown state");break}}),this._pc.addEventListener("icecandidateerror",e=>{l.error("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this._pc.ondatachannel=e=>{l.info("Safari12::data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{l.info("Safari12::data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{l.warn("Safari12::data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{l.error("Safari12::data channel error: ",{rtcChannel:{label:e.channel.label}})},r.onmessage=n=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(n.data));this.safeEmit("datachannel",e.channel,i)})}}}function AM(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){l.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return l.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=lu.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=70",chromium:">=70"}))return"Chrome70";if(e.satisfies({chrome:">=67",chromium:">=67"}))return"Chrome67";if(e.satisfies({chrome:">=55",chromium:">=55"}))return"Chrome55";if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"}))return"Safari11";if(e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return"Edge11";if(r.name&&r.name.toLowerCase()==="blink"){const n=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);if(n){const i=Number(n[1]);return i>=74?"Chrome74":i>=70?"Chrome70":i>=67?"Chrome67":"Chrome55"}return"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":"Safari11";l.warn("Device::this._detectDevice() | browser not supported");return}l.warn("Device::this._detectDevice() | unknown device")}class Sg{constructor({handlerName:e,handlerFactory:r}={}){if(m(this,"handlerFactory"),m(this,"_handlerName"),m(this,"_observer"),l.debug("constructor()"),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)l.debug(`Device::constructor() | handler given: ${e}`);else if(e=AM(),e)l.debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=jl.createFactory();break;case"Safari12":this.handlerFactory=Hl.createFactory();break;case"Firefox60":this.handlerFactory=cc.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=cc.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}const n=this.handlerFactory();this._handlerName=n.name,n.close(),this._observer=new _t}get handlerName(){return this._handlerName}createSendTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){return l.debug("Device::createSendTransport()"),this.createTransport({direction:"send",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o})}createRecvTransport({iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s}){return l.debug("Device::createRecvTransport()"),this.createTransport({direction:"recv",iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s})}}let MM=class extends Sg{createTransport({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,config:o}){const a=gn(),d=new PM({id:a,direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:n,proprietaryConstraints:i,appData:s,handlerFactory:this.handlerFactory,config:o});return this._observer.emit("newtransport",d),d}};var Et;class DM{constructor(e){_(this,Et,void 0),T(this,Et,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Et).sendMessagePromiseWithTimeout({event:ie.joinRoom,protobuf:Sm.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.createWebRTCTransport,vm.toBinary(e))).payload,{transportId:n,description:i}=Hd.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Et).sendMessagePromise(ie.produce,bm.toBinary(e))).payload,s=Fm.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.consume,_m.toBinary(e))).payload,{consumerIdsMap:{map:n}}=xm.fromBinary(r);return n})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.closeProducer,Cm.toBinary(e))).payload,{description:n}=Um.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Et).sendMessagePromise(ie.closeConsumer,Im.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Et).sendMessagePromise(ie.hostControlPeer,Mm.toBinary(n))).payload;if(!i)return!1;const{status:s}=jm.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Et).sendMessagePromise(ie.hostControlAllPeers,Dm.toBinary(r))).payload;if(!n)return!1;const{status:i}=Hm.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.kickAll,Pm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Bm.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.kickPeer,Rm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vm.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Et).sendMessagePromise(ie.changeDisplayName,Am.toBinary(e))).payload;if(!r)return!1;const{status:n}=Wm.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Et).sendMessagePromise(ie.selfJoinComplete,Tm.toBinary(e))).payload;return aa.fromBinary(r)})}}Et=new WeakMap;const OM=Error("task execution aborted");class NM{constructor(e,r){m(this,"id"),m(this,"executor"),m(this,"cancel"),this.id=e,this.executor=r}execute(){return u(this,null,function*(){return new Promise((e,r)=>{this.cancel=()=>r(OM),this.executor.then(n=>e(n))})})}}let Tg=0;const dc=new Map;class Yi{static execute(e){const r=Tg;Tg+=1;const n=new NM(r,e);return dc.set(r,n),{id:r,value:n.execute().finally(()=>dc.delete(r))}}static stop(e){const r=dc.get(e);r&&(r.cancel(),dc.delete(e))}}var st=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t))(st||{}),Qi=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Qi||{});const LM=2e3;var tn;class xM extends ug{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),_(this,tn,void 0),T(this,tn,e),this._device=new MM({}),this._socket=r,this.transportState={consuming:{state:st.NEW,reconnected:!1},producing:{state:st.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new DM(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get hiveSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield je().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&Yi.stop(v.id),s){case"send":{const R=Yi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,tn).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,tn).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,tn).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}case"recv":{const R=Yi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,tn).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield fr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield fr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?Mt.SUBSCRIBER:Mt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},LM);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,ac(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,ac(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from hive node, event: ${i.type}`);break}}catch(a){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Kc(o.sdp).media.filter(R=>a==="video"?R.type==="video":R.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:Mt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:R,producerId:A}=yield this._socketHandler.produce(v);p({answer:R,producerId:A})}catch(R){l.error("create producer error:",R),f(R)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o,producerId:a},d,h){l.info("consumePeer:",o);const p={producingPeerId:o,producerId:a};try{const f=yield this._socketHandler.consume(p);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:f});const g=new Map;Object.entries(f).forEach(([E,v])=>{var R,A,L;let F={};try{F=JSON.parse(v.producerState.appData)}catch(W){}g.set(E,{consumerId:v.consumerId,trackId:(R=v.producerTrack)==null?void 0:R.trackId,streamId:v.producerTrack.streamId,kind:v.producerState.kind===wt.VIDEO?"video":"audio",appData:F,screenShare:(A=v.producerState)==null?void 0:A.screenShare,paused:(L=v.producerState)==null?void 0:L.pause})}),d({consumersMap:g})}catch(f){l.error("consumePeer error:",{error:f}),h(f)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,R,A,L,F;const W={producingPeerId:a,producerId:o};try{const H=(yield this._socketHandler.consume(W))[o];let I={};try{I=JSON.parse((p=H.producerState)==null?void 0:p.appData)}catch(S){}l.info("consumer create response:",{consumer:{remotelyPaused:(f=H.producerState)==null?void 0:f.pause,producerId:(g=H.producerState)==null?void 0:g.producerId,kind:(v=(E=H.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},I),{screenShare:(R=H.producerState)==null?void 0:R.screenShare}),id:H.consumerId},consumerState:H}),d({consumerId:H.consumerId,screenShare:(A=H.producerState)==null?void 0:A.screenShare,trackId:(L=H.producerTrack)==null?void 0:L.trackId,streamId:H.producerTrack.streamId,kind:H.producerState.kind===wt.VIDEO?"video":"audio",paused:(F=H.producerState)==null?void 0:F.pause,appData:I})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Pr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:Mt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Q.MIC,Q.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Pr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Q.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Q.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(s=>this.getProducer(s.producerId))){l.warn("why are you creating a consumer for local producer?");return}const i=K.hasFeature(X.ENABLE_HIVE_CONSUME_OVER_DC);yield fr(s=>u(this,null,function*(){s>0&&l.debug(`retrying consume call, retryCount: ${s}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r,consumeOverDC:i}).catch(o=>{throw l.error("failed to consume:",{error:o}),o})).forEach(o=>{o.status==="rejected"?(l.error("consumer creation task is failing",o.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(o.value)})})).catch(s=>{l.error("create consumer failed after retries",{error:s}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,tn).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(ie.toggleConsumer,oa.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(ie.toggleConsumer,oa.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Mt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(ie.renegotiateSessionDescription,ym.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch(a){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_HIVE_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_HIVE_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:st.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`HiveSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}tn=new WeakMap;var FM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,de=(t,e,r,n)=>{for(var i=n>1?void 0:n?UM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&FM(e,r,i),i};const Kn={joinAttempted:!1},VM=3e3;var Ie,he,Mr,Xi,zn,Yn,lc,uc,hc,rn,Xs,tr,Dr,nn,kg;const _g=(kg=class extends lg{constructor(t,e){var r,n;super(),_(this,Dr),_(this,Ie,void 0),_(this,he,void 0),_(this,Mr,void 0),_(this,Xi,void 0),_(this,zn,void 0),_(this,Yn,void 0),_(this,lc,void 0),_(this,uc,void 0),_(this,hc,void 0),_(this,rn,void 0),_(this,Xs,void 0),_(this,tr,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Ie,a),T(this,Mr,!1),T(this,tr,void 0),T(this,he,new xM(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,rn,new Set),T(this,Xi,!1),T(this,zn,0),T(this,Yn,new Ki),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSocketConnectionEvents(),this.handleSFUEvents(),this.handleCallstatsEvents(),T(this,lc,cr(()=>u(this,null,function*(){if(!Kn.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,uc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),T(this,hc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,b.emit(w.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Ie).connectionState}get mediaState(){return c(this,he).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new _g(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,he)}get rejoinRoom(){return c(this,lc)}reset(t=!0){var e,r,n,i;(r=(e=c(this,he))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,he))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,rn).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,Yn).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,Yn,new Ki))}reconnectTransport(t){return u(this,null,function*(){l.info(`HiveNodeClient::Room joining state: ${c(this,Mr)}`),!(!t||c(this,Mr))&&(t.direction==="send"?yield c(this,uc).call(this,t):yield c(this,hc).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,he).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,he).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){Kn.joinAttempted=!0,T(this,Mr,!0),this.reset(s);const a=je().ipInfo;if(a!=null&&a.loc&&!c(this,Xs)){const h=a.loc.split(",");T(this,Xs,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,Yn).push(()=>this._joinRoom(r,n,i,o,c(this,Xs)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=je().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield fr((o,a)=>(c(this,Ie).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.hiveSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,Yn).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},ye.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{this.roomJoined=!0;const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.hiveSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,T(this,Xi,!0),T(this,Mr,!1),this.maxPreferredStreams=t!=null?t:6,b.emit(w.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),this.roomJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){c(this,he).stopAllTransports(),T(this,Xi,!1),Kn.joinAttempted=!1;const t={closeRoom:!1};c(this,Ie).sendMessagePromise(ie.leaveRoom,km.toBinary(t)).then(e=>{var r;(r=Lm.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,he).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t,e="default"){return u(this,null,function*(){if(l.info("deactivating producers",{producerInfo:{peerId:t.peerId,producers:t.producers}}),t.producers.some(r=>r.screenShare&&r.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:r,kind:n})=>{if(n==="audio"&&e!=="default"){l.debug("we don't want to deactive audio consumers");return}const i=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!i){l.warn(`consumer not found in deactivate producers: ${r}`);return}this.sfuHandler.closeConsumer(i)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){return t.forEach(e=>{this.activatedProducingPeerIds.delete(e)}),this.sfuHandler.closeConsumers(t)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,he).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in HiveNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,he).producers.has(Q.WEBCAM)){const n=c(this,he).producers.get(Q.WEBCAM);if(!n.closed&&!navigator.isReactNative)return yield n.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,he).removeProducer(Q.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};if(K.hasFeature(X.ENABLE_HIVE_SIMULCAST)){let n=t.getConstraints().width;n in Jf||(n=320),e.encodings=Jf[n]}const r=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,he).createProducer(Q.WEBCAM,e,r)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,he).createProducer(Q.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,he).createProducer(Q.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,he).producers.has(Q.MIC)){const n=c(this,he).producers.get(Q.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,he).removeProducer(Q.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,he).createProducer(Q.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,he).producers.get(Q.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,he).producers.get(Q.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Ie).sendMessage(ie.toggleProducer,$r.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,he).removeProducer(Q.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,he).removeProducer(Q.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,he).removeProducer(Q.SCREENSHARE_VIDEO),yield c(this,he).removeProducer(Q.SCREENSHARE_AUDIO),c(this,rn).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,he).removeProducer(Q.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,he).removeProducer(Q.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.hiveSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.hiveSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.hiveSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Ie).sendMessagePromise(ie.globalPinPeer,wm.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,rn).add(t.consumerPeerId),c(this,rn).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Ie).on(ie.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Gm.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===wt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Jm.fromBinary(t),s=r===wt.AUDIO?"audio":"video";if(l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),e===this.peerId&&n){b.emit(s==="audio"?w.MUTE_ALL:w.MUTE_ALL_VIDEO);return}b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),b.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),b.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Ie).on(ie.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=ca.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,rn).delete(e),this.sfuHandler.cleanupConsumers(e),b.emit(w.PEER_CLOSED,{id:e})}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Ie).on(ie.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=qm.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Ie).on(ie.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Mr)&&!c(this,Xi)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Ie).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),c(this,tr)&&(clearTimeout(c(this,tr)),T(this,tr,void 0)),ue(this,Dr,nn).call(this,"connected")})),c(this,Ie).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==st.CONNECTED||n.state!==st.CONNECTED?b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Kn.joinAttempted}):T(this,tr,setTimeout(()=>{b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:Kn.joinAttempted}),T(this,tr,void 0)},VM)),ue(this,Dr,nn).call(this,"disconnected"),this.roomJoined=!1}),c(this,Ie).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,Dr,nn).call(this,"reconnecting")})),c(this,Ie).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,Dr,nn).call(this,"reconnectAttempt",e)})),c(this,Ie).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,Dr,nn).call(this,"reconnectFailure",t)}),c(this,Ie).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:Kn}),c(this,tr)&&(clearTimeout(c(this,tr)),T(this,tr,void 0)),b.emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:Kn.joinAttempted}),ue(this,Dr,nn).call(this,"reconnected")})),c(this,Ie).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),b.emit(w.SOCKET_SERVICE_FAILED),ue(this,Dr,nn).call(this,"failed"),this.roomJoined=!1}))}handleSFUEvents(){c(this,he).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,he).on("rejoin",t=>{if(c(this,zn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Mr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,zn,c(this,zn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,zn)}]`),this.roomJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Ie=new WeakMap,he=new WeakMap,Mr=new WeakMap,Xi=new WeakMap,zn=new WeakMap,Yn=new WeakMap,lc=new WeakMap,uc=new WeakMap,hc=new WeakMap,rn=new WeakMap,Xs=new WeakMap,tr=new WeakMap,Dr=new WeakSet,nn=function(t,e){let r;const{reconnected:n}=c(this,Ie).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(b.emit(w.SOCKET_STATE_UPDATE,r),c(this,Ie).connectionState=r)},kg);let oe=_g;de([y.trace("HiveNodeClient.reset")],oe.prototype,"reset",1),de([y.trace("HiveNodeClient.reconnect")],oe.prototype,"reconnectTransport",1),de([y.trace("HiveNodeClient.setupTransport")],oe.prototype,"setupTransports",1),de([y.trace("HiveNodeClient.stopAllProducers")],oe.prototype,"stopAllProducers",1),de([y.trace("HiveNodeClient.joinRoom")],oe.prototype,"joinRoom",1),de([y.trace("HiveNodeClient.completeJoinRoom")],oe.prototype,"completeJoinRoom",1),de([y.trace("HiveNodeClient.leaveRoom")],oe.prototype,"leaveRoom",1),de([y.trace("HiveNodeClient.activatePeers")],oe.prototype,"activatePeers",1),de([y.trace("HiveNodeClient.deactivatePeers")],oe.prototype,"deactivatePeers",1),de([y.trace("HiveNodeClient.createConsumer")],oe.prototype,"createConsumer",1),de([y.trace("HiveNodeClient.pauseConsumers")],oe.prototype,"pauseConsumers",1),de([y.trace("HiveNodeClient.resumeConsumers")],oe.prototype,"resumeConsumers",1),de([y.trace("HiveNodeClient.closeConsumers")],oe.prototype,"closeConsumers",1),de([y.trace("HiveNodeClient.consumePeer")],oe.prototype,"consumePeer",1),de([y.trace("HiveNodeClient.shareWebcam")],oe.prototype,"shareWebcam",1),de([y.trace("HiveNodeClient.shareScreen")],oe.prototype,"shareScreen",1),de([y.trace("HiveNodeClient.shareMic")],oe.prototype,"shareMic",1),de([y.trace("HiveNodeClient.pauseMic")],oe.prototype,"pauseMic",1),de([y.trace("HiveNodeClient.pauseWebcam")],oe.prototype,"pauseWebcam",1),de([y.trace("HiveNodeClient.resumeMic")],oe.prototype,"resumeMic",1),de([y.trace("HiveNodeClient.resumeWebcam")],oe.prototype,"resumeWebcam",1),de([y.trace("HiveNodeClient.disableWebcam")],oe.prototype,"disableWebcam",1),de([y.trace("HiveClient.disableMic")],oe.prototype,"disableMic",1),de([y.trace("HiveClient.disableScreenShare")],oe.prototype,"disableScreenShare",1),de([y.trace("HiveNodeClient.muteSelf")],oe.prototype,"muteSelf",1),de([y.trace("HiveNodeClient.resetVideoProducers")],oe.prototype,"resetVideoProducers",1),de([y.trace("HiveNodeClient.changeDisplayName")],oe.prototype,"changeDisplayName",1),de([y.trace("HiveNodeClient.kickPeer")],oe.prototype,"kick",1),de([y.trace("HiveNodeClient.kickAllPeers")],oe.prototype,"kickAll",1),de([y.trace("HiveNodeClient.muteAll")],oe.prototype,"muteAll",1),de([y.trace("HiveNodeClient.muteAllVideo")],oe.prototype,"muteAllVideo",1),de([y.trace("HiveNodeClient.disableAudio")],oe.prototype,"disableAudio",1),de([y.trace("HiveNodeClient.disableVideo")],oe.prototype,"disableVideo",1),de([y.trace("HiveNodeClient.pinPeer")],oe.prototype,"pinPeer",1),de([y.trace("HiveNodeClient.validateScreenShare")],oe.prototype,"validateScreenShare",1),de([y.trace("HiveNodeClient.init")],oe,"init",1);class BM{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const n=this.index(e);this.delete(e);const i=this.add(e,r);return n!==i?i:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class Wl{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new BM,this._compulsoryPeers=new Set}add(e,r){if(r<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(l.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,r)}delete(e){l.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get peerPriorities(){return Array.from(this._activeSpeakerPeers).map((e,r)=>r)}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}var jM=Object.defineProperty,HM=Object.getOwnPropertyDescriptor,Lt=(t,e,r,n)=>{for(var i=n>1?void 0:n?HM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&jM(e,r,i),i};const WM=["ACTIVE_GRID","PAGINATED","MANUAL"];var Zi,Ht,rr,Qn,Wt,bg;let St=(bg=class extends Dt{constructor(t,e,r,n){var i;super(),_(this,Ht),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"pinned"),m(this,"all"),m(this,"pip"),_(this,Zi,void 0),_(this,Qn,void 0),_(this,Wt,void 0),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",new Wl),T(this,Zi,t),T(this,Qn,e),T(this,Wt,r),this.waitlisted=new Ja,this.joined=new Ja,this.active=new Ja,this.pinned=new Ja,this.selectedPeers=new Wl,this.all=new gM,this.viewMode="ACTIVE_GRID",this.currentPage=0,((i=n==null?void 0:n.pip)==null||i)&&(this.pip=new EM(t,e)),this.setupEvents()}get roomJoined(){var t;return((t=c(this,Ht,rr))==null?void 0:t.roomJoined)===!0}setupEvents(){b.on(w.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=c(this,Zi).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){return c(this,Ht,rr).maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24");c(this,Ht,rr).maxPreferredStreams=t,c(this,Qn).roomJoined&&b.emit(w.REFRESH_GRID)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.joined.toArray().filter(e=>e.stageStatus==="ON_STAGE");return Math.ceil(t.length/this.maxActiveParticipantsCount)}return 0}acceptWaitingRoomRequest(t){var e,r;if(!this.roomJoined)throw new C("Can`t accept waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return c(this,Wt).acceptWaitingRoomRequest([n])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var n,i;return(i=(n=this.waitlisted.get(r))==null?void 0:n.userId)!=null?i:r});return c(this,Wt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!this.roomJoined)throw new C("Can`t reject waiting room request without joining room");const n=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;c(this,Wt).rejectWaitingRoomRequest([n])})}setViewMode(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>WM.includes(e))(t))throw l.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new C(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`);if(this.viewMode===t){l.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL"&&!(c(this,Ht,rr)instanceof oe))throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,b.emit(w.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,b.emit(w.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Please activate MANUAL subscription mode first.");const e={},r=[],n=[];t.forEach(a=>{e[a.id]=!0;const d=this.active.get(a.id);if(!d)r.push(a);else{d.manualProducerConfig=a.producers;const h=p=>u(this,[p],function*({producers:f,config:g}){const E=[];f.forEach(v=>{const R=v.kind==="audio",A=v.kind==="video";(R&&(g.audio&&!v.screenShare||g.screenshareAudio&&v.screenShare)||A&&(g.video&&!v.screenShare||g.screenshareVideo&&v.screenShare))&&E.push(v.producerId),c(this,Ht,rr).closeConsumers(E)})});n.push(h({peerId:a.id,config:a.producers,producers:d.producers}))}});const i=[];this.active.forEach(a=>{if(e[a.id])return;const d=h=>u(this,null,function*(){const p={peerId:h.id,producers:h.producers};yield c(this,Ht,rr).deactivatePeers(p,"manual"),this.active.delete(h.id);const f=this.joined.get(h.id);f.manualProducerConfig=jd});i.push(d(a))}),yield Promise.all([...i,...n]);const s=(a,d)=>a.reduce((h,p)=>(!p.screenShare&&d[p.kind]&&h.push(p),p.screenShare&&(p.kind==="audio"&&d.screenshareAudio||p.kind==="video"&&d.screenshareVideo)&&h.push(p),h),[]),o=r.map(a=>{const d=this.joined.get(a.id);return this.active.add(d),d.manualProducerConfig=a.producers,{peerId:d.id,producers:s(d.producers,a.producers)}});yield c(this,Ht,rr).activatePeers(o),this.active.emit("participantsUpdate")})}unsubscribe(t){return u(this,null,function*(){if(this.viewMode!=="MANUAL")throw new C("Manual Subscription is not enabled for your Organization. Please contact support.");t.forEach(e=>u(this,null,function*(){const r=this.joined.get(e);if(!r)return;const n={peerId:r.id,producers:r.producers};r.manualProducerConfig=jd,yield c(this,Ht,rr).deactivatePeers(n,"manual"),this.active.delete(r.id)}))})}getPeerIdsForCurrentPage(){l.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),n=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,n.slice(i,s))}setPage(t){return u(this,null,function*(){if(l.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw l.error("DyteParticipants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`);this.currentPage=t,b.emit(w.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.roomJoined)throw new C("Can`t disable all audio without joining room");if(c(this,Qn).permissions.canAllowParticipantAudio)return c(this,Ht,rr).muteAll(t);throw l.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.")})}disableAllVideo(){return u(this,null,function*(){if(l.info("DyteParticipants::disable_all_video"),!this.roomJoined)throw new C("Can`t disable all video without joining room");if(c(this,Qn).permissions.canAllowParticipantVideo)return c(this,Ht,rr).muteAllVideo();throw l.error("DyteParticipants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield b.emitAsync(w.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(l.info("DyteParticipants::kick_all"),c(this,Zi).getValue("viewType")!=="LIVESTREAM"&&!this.roomJoined)throw new C("Can`t kick all without joining room");if(!c(this,Qn).permissions.kickParticipant)throw l.error("DyteParticipants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.");c(this,Wt).kickAll()})}broadcastMessage(t,e,r){return u(this,null,function*(){if(l.info("DyteParticipants::broadcastMessage"),!this.roomJoined)throw new C("Can`t broadcast message without joining room");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.");if(r){let n=[];"participantIds"in r?n=r.participantIds:n=this.joined.toArray().filter(i=>{var s;return(s=r.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),c(this,Wt).broadcastToPeers(t,n,e)}else c(this,Wt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield c(this,Wt).getRoomPeers(t,e,r)).peers.map(gr.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),n=[...new Set(r)];c(this,Wt).updatePermissions(n,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return c(this,Wt).getRoomPeersNonPaginated()})}},Zi=new WeakMap,Ht=new WeakSet,rr=function(){return c(this,Zi).getValue("roomNodeClient")},Qn=new WeakMap,Wt=new WeakMap,bg);Lt([y.trace("DyteParticipants.setViewMode")],St.prototype,"setViewMode",1),Lt([y.trace("DyteParticipants.setPage")],St.prototype,"setPage",1),Lt([y.trace("DyteParticipants.disableAllAudio")],St.prototype,"disableAllAudio",1),Lt([y.trace("DyteParticipants.disableAllVideo")],St.prototype,"disableAllVideo",1),Lt([y.trace("DyteParticipants.disablePeerAudio")],St.prototype,"disableAudio",1),Lt([y.trace("DyteParticipants.disablePeerVideo")],St.prototype,"disableVideo",1),Lt([y.trace("DyteParticipants.kickPeer")],St.prototype,"kick",1),Lt([y.trace("DyteParticipants.kickAll")],St.prototype,"kickAll",1),Lt([y.trace("DyteParticipants.broadcastMessage"),Ct({maxInvocations:500,period:60})],St.prototype,"broadcastMessage",1),Lt([y.trace("DyteParticipants.getAllJoinedPeers"),Ct({maxInvocations:10,period:60})],St.prototype,"getAllJoinedPeers",1),Lt([y.trace("DyteParticipant.updatePermissions"),Ct({maxInvocations:1e3,period:60})],St.prototype,"updatePermissions",1),Lt([y.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],St.prototype,"getParticipantsInMeetingPreJoin",1),St=Lt([dt("1200")],St);var $M=Object.defineProperty,GM=Object.getOwnPropertyDescriptor,Xn=(t,e,r,n)=>{for(var i=n>1?void 0:n?GM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$M(e,r,i),i};class gr{constructor(e,r,n,i){m(this,"participants"),m(this,"self"),m(this,"selectedPeers",new Wl),m(this,"currentActiveGridParticipants",new Set),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),m(this,"updateConsumerSpatialLayers",cr(()=>{const s={},o=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(o.entries()).forEach(([a,d])=>{s[d]===void 0&&(s[d]={layer:d,consumerIds:[]}),s[d].consumerIds.push(a)}),Object.keys(s).forEach(a=>{const d=s[a];l.log(`Switching max spatial layer to ${d.layer}`,{consumerIds:d.consumerIds}),this.roomNodeClient.switchConsumersToLayer(d.consumerIds,d.layer)})},2e3)),m(this,"refreshGridParticipants",cr((s=!1)=>{const o=new Map,a=Array.from(this.participants.joined.toArray().filter(R=>R.stageStatus==="ON_STAGE").map(R=>(o.set(R.id,!0),R.id))),d=this.selectedPeers.peers,h=this.participants.pinned.toArray().reduce((R,A)=>(A.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(A.id):R.push(A.id),R),[]);if(this.participants.viewMode!=="ACTIVE_GRID"){l.warn("ParticipantController::refreshGridParticipants::not_refreshing_grid_in_not_active_grid_mode");return}const p=this.self.stageStatus==="ON_STAGE"?1:0,f=this.participants.maxActiveParticipantsCount-p,g=new Set(d.concat(h).filter(R=>R!==this.self.id&&o.has(R)));let E=Array.from(g);const v=f-g.size;if(v>=0){const R=a.filter(A=>!g.has(A)&&A!==this.self.id).slice(0,v);E=Array.from(g).concat(R)}else E=E.slice(0,f);this.updateActiveParticipants(E,s)},500,{trailing:!0,leading:!0})),this.context=e,this.roomSocketHandler=n,this.participants=new St(e,r,this.roomSocketHandler,i),this.self=r,this.consumerPeerMap=new Map,r.config.viewType!=="CHAT"&&this.setupEventsGlobal()}get roomJoined(){var e;return((e=this.roomNodeClient)==null?void 0:e.roomJoined)===!0}waitingRoomRequestHandler(e){const r=e.requests.filter(i=>!this.participants.waitlisted.toArray().find(s=>s.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!e.requests.find(s=>s.userId===i.userId));r.forEach(i=>this.participants.waitlisted.add(new Rr(this.context,{id:i.peerId,displayName:i.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:i.userId,flags:{},isHost:!1},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}updateActive(e){return u(this,arguments,function*({page:r}){if(r&&r!==0){const{compulsoryPeers:n}=this.selectedPeers,i=n.filter(p=>this.participants.joined.has(p)),s=Array.from(this.participants.pinned.keys()).filter(p=>!i.includes(p)),o=Array.from(this.participants.joined.toArray().filter(p=>p.stageStatus==="ON_STAGE").map(p=>p.id)),a=Math.max((r-1)*(this.roomNodeClient.maxPreferredStreams-i.length-s.length)),d=r*(this.roomNodeClient.maxPreferredStreams-i.length-s.length),h=i.concat(s,o.slice(a,d));this.updatePageParticipants(h)}else b.emit(w.REFRESH_GRID)})}updatePageParticipants(e){const r=new Set(e),n=new Map(this.participants.active);this.participants.active.forEach((s,o)=>{this.participants.active.delete(o,!r.has(o))}),r.forEach(s=>{if(!this.participants.joined.get(s)){l.warn("updatePageParticipants::participant_not_in_joined_list",{dyteParticipant:{id:s}});return}this.participants.active.add(this.participants.joined.get(s),!n.get(s))}),this.currentActiveGridParticipants=new Set(this.participants.active.keys()),Array.from(n.keys()).forEach(s=>{if(r.has(s))return;const o=this.participants.joined.get(s);if(!o)return;const a={producers:o.producers,peerId:o.id};this.roomNodeClient.deactivatePeers(a)});const i=[];return this.participants.active.forEach(s=>{const o={peerId:s.id,producers:s.producers};i.push(o)}),this.roomNodeClient.activatePeers(i),{activePeers:n,peerIdsSet:r}}computeActivateParticipants(e,r){const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(e){var r,n,i,s;const o={};return(r=e.flags)!=null&&r.hiddenParticipant&&(o.hidden_participant=(n=e.flags)==null?void 0:n.hiddenParticipant),((i=e.flags)==null?void 0:i.recorderType)!==void 0&&((s=e.flags)==null?void 0:s.recorderType)!=="NONE"&&(o.recorder=!0),new Rr(this.context,ne(V({},e),{flags:o,id:e.peerId,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0,picture:e.displayPictureUrl,stageStatus:Pa(e.stageType)}),this.self,this.roomSocketHandler)}onMediaJoined(e,r){return u(this,null,function*(){if(!this.roomJoined||e===this.self.id)return;const n=this.participants.joined.get(e);if(!n){l.warn(`Recieved media.peerJoinedBroadcast for non-existent peer ${e}`);return}r.forEach(i=>{i.kind===wt.AUDIO&&!i.screenShare?n.setAudioEnabled(!i.pause):i.kind===wt.VIDEO&&!i.screenShare&&n.setVideoEnabled(!i.pause),n.producers.push(ne(V({},i),{producingTransportId:i.producingTransportId,kind:i.kind===wt.AUDIO?"audio":"video"}))})})}updateActiveParticipantsMapMinReplacement(e){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipants",{roomJoined:this.roomJoined});return}const r=Array.from(this.participants.active.keys()),n=new Map(this.participants.active),i={};e.forEach(o=>{i[o]=!0});const s=[];r.forEach((o,a)=>{(!i[o]||!this.participants.joined.get(o))&&s.push(a)}),e.forEach(o=>{n.get(o)||(r.length<e.length?r.push(o):r[s.shift()]=o)}),r.forEach((o,a)=>{i[o]||r.splice(a,1)}),Array.from(this.participants.active.keys()).forEach(o=>{this.participants.active.delete(o,!i[o])}),r.forEach(o=>{if(!this.participants.joined.get(o)){l.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:o}});return}this.participants.active.add(this.participants.joined.get(o),!n.get(o))}),this.participants.active.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(e=>{e.setIsPinned(!1),this.participants.pinned.delete(e.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:e})=>{if(!e.waitlisted){if(this.context.getValue("viewType")==="LIVESTREAM"&&e.stageType!==1)return;this.onParticipantJoined(this.fromSocketService(e))}}),this.roomSocketHandler.on(j.leaveRoom,e=>{this.selectedPeers.delete(e.peer.peerId),this.onParticipantLeave(e.peer.peerId)}),b.on(w.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),b.on(w.SOCKET_SERVICE_DISCONNECTED,()=>{Array.from(this.participants.joined.keys()).forEach(e=>{this.participants.joined.delete(e)}),Array.from(this.participants.active.keys()).forEach(e=>{this.participants.active.delete(e)}),Array.from(this.participants.pinned.keys()).forEach(e=>{this.participants.pinned.delete(e)}),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),this.currentActiveGridParticipants=new Set}),b.on(w.CONSUMER_PAUSED,({id:e})=>{this.processConsumerPaused(e)}),b.on(w.CONSUMER_RESUMED,({id:e})=>{this.processConsumerResumed(e)}),b.on(w.NEW_CONSUMER,({id:e})=>{this.processNewConsumer(e)}),b.on(w.CONSUMER_CLOSED,({id:e})=>{this.processConsumerClosed(e)}),b.on(w.ROOM_MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),b.on(w.MESSAGE,e=>u(this,[e],function*({payload:r,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:r,timestamp:i})})),b.on(w.LOW_CONSUMER_SCORE,({peerId:e,score:r,kind:n})=>{const i=this.participants.joined.get(e);i&&(i.emit("poorConnection",{score:r,kind:n}),this.participants.emit("poorConnection",{participantId:e,score:r,kind:n}))}),b.on(w.CONSUMER_SCORE_UPDATE,({score:e,kind:r,appData:n,peerId:i})=>{var s;const o=r==="video"&&((s=n==null?void 0:n.screenShare)!=null?s:!1),a=this.participants.joined.get(i);a&&(a.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}),this.participants.emit("mediaScoreUpdate",{kind:r,isScreenshare:o,score:e,participantId:i}))}),b.onAsync(w.KICK_PEER,e=>u(this,[e],function*({peerId:r}){const n=this.participants.joined.get(r);yield this.roomNodeClient.kick(r),yield this.roomSocketHandler.kick(r),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:r})})),b.on(w.UPDATE_ACTIVE,(...e)=>u(this,[...e],function*({page:r}={}){yield this.updateActive({page:r})}))}onParticipantPinned(e){return u(this,null,function*(){if(!e){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(e===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const r=this.participants.joined.get(e);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),r.setIsPinned(!0),this.participants.pinned.add(r)})}onParticipantJoined(e){return u(this,null,function*(){var r,n,i;this.self.id!==e.id&&!((r=e.flags)!=null&&r.recorder)&&!((n=e.flags)!=null&&n.hidden_participant)&&!((i=e.flags)!=null&&i.hiddenParticipant)&&(this.participants.active.delete(e.id),this.participants.joined.add(e),this.participants.waitlisted.delete(e.id),e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!0})),b.emit(w.PEER_JOINED_INTERNAL,e),!(this.self.config.viewType===We.Webinar&&e.stageStatus!=="ON_STAGE")&&(this.roomNodeClient===void 0||this.participants.active.size>=this.roomNodeClient.maxPreferredStreams||this.updateActive({page:this.participants.currentPage}))})}onParticipantLeave(e){return u(this,null,function*(){const r=this.participants.joined.get(e);this.participants.joined.delete(e,!0,!0),this.participants.pinned.delete(e,!0,!0),this.participants.waitlisted.delete(e,!0,!0),r&&r.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&b.emit(w.UPDATE_STAGE_REQUESTS,{request:{displayName:r.name,userId:r.userId,peerId:r.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),s=this.participants.active.get(e);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?n===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(n-1):s&&this.updateActive({page:n})})}processMedia(e){var r;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:o,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}=(r=n.get(e))!=null?r:{};if(!i)return l.warn("processMedia::Peer ID is undefined",{consumer:{id:e,kind:s,peerId:i,appData:{supportsRemoteControl:o==null?void 0:o.supportsRemoteControl,screenShare:o==null?void 0:o.screenShare},remotelyPaused:a,producerId:h}}),{};const f=o;return s==="video"&&f.screenShare!==!0&&this.videoPeerConsumerMap.set(i,e),l.info("ParticipantController::processMedia",{consumer:{id:e,peerId:i,kind:s,appData:f,remotelyPaused:a,producerId:h}}),this.consumerPeerMap.set(e,{type:s,peerId:i,appData:f,remotelyPaused:a,producerId:h}),{peerId:i,kind:s,appData:f,remotelyPaused:a,track:d,producerId:h,rtpReceiver:p}}processConsumerClosed(e){const{peerId:r,type:n,appData:i,remotelyPaused:s,producerId:o}=this.consumerPeerMap.get(e)||{},a=this.participants.joined.get(r);if(l.info("ParticipantController::processConsumerClosed",{consumer:{id:e,peerId:r,appData:i,kind:n,remotelyPaused:s,producerId:o}}),this.consumerPeerMap.delete(e),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(r),!a)return;const d=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),B.consumerSharedMediaState(e,{screen:!1}),a.screenShareTracks.video&&d.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&d.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&d.push(a.audioTrack.id),B.consumerSharedMediaState(e,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),a.videoTrack&&d.push(a.videoTrack.id),B.consumerSharedMediaState(e,{video:!1}),a.videoTrack=void 0),i.e2ee&&d.forEach(h=>{b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:h})})}processConsumerResumed(e){const{peerId:r,kind:n,appData:i,track:s,remotelyPaused:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerResumed",{consumer:{id:e,peerId:r,kind:n,appData:i,remotelyPaused:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(i.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s}),i.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),h.setScreenShareEnabled(!0),B.consumerSharedMediaState(e,{screen:!0});return}n==="video"?(h.videoTrack=s,h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!0})):n==="audio"&&(h.audioTrack=s,h.setAudioEnabled(h.audioEnabled),B.consumerSharedMediaState(e,{audio:h.audioEnabled}))}}processConsumerPaused(e){l.info(`ParticipantController::processConsumerPaused called for consumerId: ${e}`);const{peerId:r,kind:n,track:i,appData:s,remotelyPaused:o,producerId:a}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processConsumerPaused",{consumer:{id:e,peerId:r,kind:n,appData:s,remotelyPaused:o,producerId:a}});const d=this.participants.joined.get(r);d&&(i&&s.e2ee&&b.emit(w.E2EE_INACTIVE_CONSUMER,{peerId:r,trackId:i.id}),n==="video"?(d.videoTrack=i,d.setVideoEnabled(!1),B.consumerSharedMediaState(e,{video:!1})):n==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),B.consumerSharedMediaState(e,{audio:d.audioEnabled})))}processNewConsumer(e){const{peerId:r,kind:n,remotelyPaused:i,track:s,appData:o,producerId:a,rtpReceiver:d}=this.processMedia(e);if(!r)return;l.info("ParticipantController::processNewConsumer",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});const h=this.participants.joined.get(r);if(h){if(o.screenShare){n==="video"?h.screenShareTracks.video=s:n==="audio"&&(h.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||K.hasFeature(X.SCREEENSHARE_ERR_HACK))&&h.setScreenShareEnabled(!0),o.supportsRemoteControl&&(h.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:r,screenShare:!0,consumerId:e,consumerPeerId:this.self.id}),l.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:e,peerId:r,kind:n,remotelyPaused:i,appData:o,producerId:a}});return}n==="video"?(h.videoTrack=s,i||h.setVideoEnabled(!0),B.consumerSharedMediaState(e,{video:!i})):n==="audio"&&(h.audioTrack=s,i||h.setAudioEnabled(!0),B.consumerSharedMediaState(e,{audio:!i})),!i&&o.e2ee&&b.emit(w.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:s})}}static formatSocketServiceMessage(e){var r,n,i,s;if(!e)return;const o=Pa(e.stageType);return{id:e.peerId,userId:e.userId,name:e.displayName,displayName:e.displayName,stageType:o,customParticipantId:e.customParticipantId,presetId:e.presetId,picture:e.displayPictureUrl,waitlisted:e.waitlisted,stageStatus:o,metadata:{preset_name:(r=e.flags)==null?void 0:r.presetName},recorderType:(n=e.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=e.flags)==null?void 0:i.hiddenParticipant,recorder:!!((s=e.flags)!=null&&s.recorderType)}}}updateActiveParticipants(e,r=!1){if(this.updateActiveParticipantsMapMinReplacement(e),!this.roomJoined)return;l.info("ParticipantController::updateActiveParticipants::updating_current_selected_peers",{debuggingHint:r?"Forcefully updating currentActiveGridParticipants set":null}),r&&(this.currentActiveGridParticipants=new Set);const n=new Set(e),i=[],s=[];if(this.currentActiveGridParticipants.forEach(a=>{n.has(a)||i.push(a)}),n.forEach(a=>{this.currentActiveGridParticipants.has(a)||s.push(a)}),this.currentActiveGridParticipants=n,s.length===0&&i.length===0)return;const o=[];i.forEach(a=>{const d=this.participants.joined.get(a);if(!d)return;const h={producers:d.producers,peerId:d.id};o.push(this.roomNodeClient.deactivatePeers(h))}),Promise.all(o).then(()=>{const a=[];s.forEach(d=>{const h=this.participants.active.get(d);if(!h){l.warn("peer is not in active map which is going to activate, should not happen",{dyteParticipant:{id:d}});return}const p={peerId:h.id,producers:h.producers,force:r};a.push(p)}),this.roomNodeClient.activatePeers(a)}).catch(a=>{l.info("Error on deactivating peers",a)})}onSelectedPeers(e,r){return u(this,null,function*(){if(this.participants.viewMode!=="ACTIVE_GRID")return;const n=e.map((s,o)=>({peerId:s,priority:o+1})),i=r==null?void 0:r.map((s,o)=>({peerId:s,priority:-(o+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)})}updateActiveParticipantsWithPriorities(e,r=!1){if(!this.roomJoined){l.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.roomJoined});return}let n=null;e.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority),(n===null||i.priority<n.priority)&&(n=i)}),n&&n.peerId!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n.peerId,this.participants.emit("activeSpeaker",{peerId:n.peerId,volume:n.priority})),r&&this.refreshGridParticipants()}}Xn([y.trace("updateActiveParticipantsMapMinReplacement")],gr.prototype,"updateActiveParticipantsMapMinReplacement",1),Xn([y.trace("ParticipantController.setupEvents")],gr.prototype,"setupEventsGlobal",1),Xn([y.trace("ParticipantController.processMedia")],gr.prototype,"processMedia",1),Xn([y.trace("ParticipantController.processConsumerClosed")],gr.prototype,"processConsumerClosed",1),Xn([y.trace("ParticipantController.processConsumerResumed")],gr.prototype,"processConsumerResumed",1),Xn([y.trace("ParticipantController.processConsumerPaused")],gr.prototype,"processConsumerPaused",1),Xn([y.trace("ParticipantController.processNewConsumer")],gr.prototype,"processNewConsumer",1);var JM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,KM=(t,e,r,n)=>{for(var i=n>1?void 0:n?qM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JM(e,r,i),i};class wg extends gr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>this.onParticipantJoined(this.fromSocketService(r)))})),this.roomSocketHandler.on(se.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(se.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.REFRESH_GRID,!0)}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&cr(()=>{this.refreshGridParticipants(e)},500,{maxWait:1e3,leading:!0})()}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(se.globalPeerPinBroadcast,({participantId:e})=>{if(!this.roomJoined)return;const r=e;this.onParticipantPinned(r);const n=this.participants.joined.get(r);this.roomNodeClient.activatePeers([{peerId:n.id,producers:n.producers}]).catch(i=>{l.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(se.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(se.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}KM([y.trace("ParticipantController.setupEvents")],wg.prototype,"setupEvents",1);var zM=Object.defineProperty,YM=Object.getOwnPropertyDescriptor,QM=(t,e,r,n)=>{for(var i=n>1?void 0:n?YM(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zM(e,r,i),i};class Cg extends gr{get roomNodeClient(){return this.context.getValue("roomNodeClient")}constructor(e,r,n,i){super(e,r,n,i),this.setupEvents()}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),b.on(w.SOCKET_PEERS,e=>u(this,null,function*(){e==null||e.forEach(r=>{r.waitlisted||this.onParticipantJoined(this.fromSocketService(r))})})),this.roomSocketHandler.on(ie.peerJoinedBroadcast,({participant:e})=>this.onMediaJoined(e.peerId,e.producerStates)),this.roomSocketHandler.on(ie.selfJoinComplete,({participants:e,selectedPeers:r,roomState:n})=>{e.forEach(o=>this.onMediaJoined(o.peerId,o.producerStates));const{audioPeers:i,compulsoryPeers:s}=r!=null?r:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),b.emit(w.REFRESH_GRID,!0)}),b.on(w.MAX_SPATIAL_LAYER_CHANGE,({peerId:e,maxSpatialLayer:r})=>{const n=this.videoPeerConsumerMap.get(e);n&&(this.maxSpatialLayerUpdates.set(n,r),this.updateConsumerSpatialLayers())}),b.on(w.REFRESH_GRID,(e=!1)=>{this.participants.viewMode==="ACTIVE_GRID"&&this.refreshGridParticipants(e)}),b.on(w.NEW_PRODUCER,({peerId:e,producer:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:r==null?void 0:r.producerId,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}},dyteParticipant:{id:e}});return}if(n.producers.push(r),l.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=r.kind==="audio",o=r.kind==="video",a=n.manualProducerConfig;(s&&(a.audio&&!r.screenShare||a.screenshareAudio&&r.screenShare)||o&&(a.video&&!r.screenShare||a.screenshareVideo&&r.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumer(e,r):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}});return}(r==null?void 0:r.kind)==="audio"||r!=null&&r.screenShare||this.currentActiveGridParticipants.has(e)?this.roomNodeClient.createConsumer(e,r).catch(i=>{l.error("ParticipantController::createConsumer failed",{error:i})}):l.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:r==null?void 0:r.producerId,peerId:e,kind:r==null?void 0:r.kind,status:"UNKNOWN",appData:{screenShare:r==null?void 0:r.screenShare}}})}),b.on(w.PRODUCER_CLOSED,({peerId:e,producerId:r})=>{const n=this.participants.joined.get(e);if(!n){l.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:e}});return}n.producers=n.producers.filter(i=>i.producerId!==r)}),b.on(w.PRODUCER_TOGGLE,({peerId:e,producerId:r,paused:n,kind:i})=>{const s=this.participants.joined.get(e);if(s){i==="audio"&&s.setAudioEnabled(!n);const o=s.producers.find(a=>a.producerId===r);o&&(o.pause=n)}}),this.roomSocketHandler.on(ie.globalPeerPinBroadcast,e=>{let r;if(e&&(r=e.participantId),!this.roomJoined)return;const n=r;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers([{peerId:i.id,producers:i.producers}]).catch(s=>{l.error("unable to create consumers",{error:s})})}),this.roomSocketHandler.on(ie.selectedPeer,({audioPeers:e,compulsoryPeers:r})=>{this.roomJoined&&this.onSelectedPeers(r.concat(e))}),this.roomSocketHandler.on(ie.selectedPeerDiff,({entries:e})=>{if(!this.roomJoined||this.participants.viewMode!=="ACTIVE_GRID")return;const r=e.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(r,!0)})}}QM([y.trace("ParticipantController.setupEvents")],Cg.prototype,"setupEvents",1);const we=dr(Ld().permissions);var G,Zs,eo,$l,Rt,xt;const to=class extends Dt{constructor(t,e,r,n=!1){if(super(),_(this,Rt),_(this,G,void 0),_(this,Zs,void 0),_(this,eo,void 0),_(this,$l,i=>{const s=i,{chat:o,connectedMeetings:a,plugins:d,polls:h,media:p}=s,f=Ro(s,["chat","connectedMeetings","plugins","polls","media"]);let g=!1;o&&(i.chat.private&&jr(c(this,G).chat.private,i.chat.private),i.chat.public&&jr(c(this,G).chat.public,i.chat.public),g=!0,this.emit("chatUpdate")),a&&(g=!0,jr(c(this,G).connectedMeetings,i.connectedMeetings)),p&&(g=!0,jr(c(this,G).media,i.media)),d&&(jr(c(this,G).plugins,i.plugins),g=!0,this.emit("pluginsUpdate")),h&&(jr(c(this,G).polls,i.polls),g=!0,this.emit("pollsUpdate")),Object.keys(f).length!==0&&(jr(c(this,G),f),g=!0),g&&this.emit("permissionsUpdate")}),!e)throw l.error("DytePermissionsPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.");T(this,eo,t),T(this,Zs,r),T(this,G,e),n&&this.setupEvents()}setupEvents(){b.on(w.UPDATE_PERMISSIONS,c(this,$l))}static fromResponse(t,e,r){return new to(r,t,e,!0)}static default(t,e){return new to(t,we,e)}static init(t,e,r){let n;return r?n=new to(t,r,e,!0):n=new to(t,we,e),n}get mediaRoomType(){const{sfu:t}=c(this,eo).getValue("roomNodeOptions");return t===Qi.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=c(this,G))==null?void 0:t.stageEnabled)||c(this,Zs)===We.Webinar||c(this,Zs)===We.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=c(this,G))==null?void 0:t.acceptStageRequests)||((e=c(this,G))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=c(this,G))==null?void 0:t.stageAccess)===q.NotAllowed?q.NotAllowed:((e=c(this,G))==null?void 0:e.stageAccess)===q.CanRequest?q.CanRequest:((r=c(this,G))==null?void 0:r.stageAccess)===q.Allowed||c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed?q.Allowed:c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=c(this,G))==null?void 0:t.acceptWaitingRequests)!=null?e:we.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===q.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=c(this,G))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantAudio)!=null?e:we.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:we.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=c(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:we.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.kickParticipant)!=null?e:we.kickParticipant}get pinParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.pinParticipant)!=null?e:we.pinParticipant}get canRecord(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canRecord)!=null?e:we.canRecord}get waitingRoomType(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:we.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=c(this,G))==null?void 0:t.waitingRoomType)!=null?e:we.waitingRoomType}get plugins(){var t,e;return(e=(t=c(this,G))==null?void 0:t.plugins)!=null?e:we.plugins}get polls(){var t,e;return(e=(t=c(this,G))==null?void 0:t.polls)!=null?e:we.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return c(this,G).media.audio.canProduce===q.CanRequest||c(this,G).media.video.canProduce===q.CanRequest||c(this,G).media.screenshare.canProduce===q.CanRequest}get canProduceVideo(){var t;const e=(t=c(this,G).media.video.canProduce)!=null?t:we.media.video.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=c(this,G).media.screenshare.canProduce)!=null?t:we.media.screenshare.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=c(this,G).media.audio.canProduce)!=null?t:we.media.audio.canProduce;return this.stageEnabled&&(c(this,Rt,xt)==="ACCEPTED_TO_JOIN_STAGE"||c(this,Rt,xt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(c(this,Rt,xt)==="OFF_STAGE"||c(this,Rt,xt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:we.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:we.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:we.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=c(this,G))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:we.chat.message}get connectedMeetings(){var t,e;return(e=(t=c(this,G))==null?void 0:t.connectedMeetings)!=null?e:we==null?void 0:we.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=c(this,G))==null?void 0:t.hiddenParticipant)!=null?e:we.hiddenParticipant}get showParticipantList(){var t;return(t=c(this,G).showParticipantList)!=null?t:we.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:we.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=c(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:we.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return c(this,G).media.audio.canProduce===q.Allowed||c(this,G).media.video.canProduce===q.Allowed||c(this,G).media.screenshare.canProduce===q.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=c(this,G).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return c(this,G).isRecorder}get canSpotlight(){return c(this,G).canSpotlight}get canLivestream(){return c(this,G).canLivestream}get transcriptionEnabled(){return c(this,G).transcriptionEnabled}};let XM=to;G=new WeakMap,Zs=new WeakMap,eo=new WeakMap,$l=new WeakMap,Rt=new WeakSet,xt=function(){return c(this,eo).getValue("stageStatus")};var Ig;class ZM extends Dt{constructor(){super(...arguments),m(this,"localMediaHandler"),_(this,Ig,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const n=(h,p)=>{this.mediaPermissions[h]=p;const f={message:this.mediaPermissions[h],kind:h};p==="DENIED"?b.emit(w.MEDIA_PERMISSION_ERROR,f):b.emit(w.MEDIA_PERMISSION_UPDATE,f)};if(ye.getName()==="firefox")return;const i="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),a=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:s}),d=(h,p)=>{switch(p){case"granted":n(h,"ACCEPTED");break;case"denied":n(h,"DENIED");break;case"prompt":n(h,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};o&&(o.onchange=()=>d("audio",o.state)),a&&(a.onchange=()=>d("video",a.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:n}){B.onSafeInitialization(()=>{switch(n){case"audio":{B.mediaPermission("AUDIO",r),B.mediaPermission("SPEAKER",r);break}case"video":{B.mediaPermission("VIDEO",r);break}case"screenshare":{B.mediaPermission("SCREENSHARE",r);break}}})})}init(){return u(this,arguments,function*(e={},r=!1,n=null){var i,s,o,a,d;if(ye.init(),!this.localMediaHandler)try{let h=!0;if(n!=null&&n.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=n.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:p}=navigator;this.localMediaHandler=yield p.init()}else this.localMediaHandler=new It(n,e.constraints,(i=n==null?void 0:n.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=n==null?void 0:n.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(b.on(w.MEDIA_PERMISSION_UPDATE,p=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:p.message,kind:p.kind}),p.message==="NOT_REQUESTED")switch(p==null?void 0:p.kind){case"audio":this.rawAudioTrack&&(l.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(l.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",p)})),b.on(w.MEDIA_PERMISSION_ERROR,p=>u(this,null,function*(){const{kind:f,message:g,constraints:E}=p;this.populateMediaPermissionsInCallstats({message:g,kind:f}),f==="audio"?(l.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):f==="video"&&(l.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),l.error("SelfController::mediaPermissionError",{error:{message:g},constraints:E,mediaPermissionsErrors:{kind:f,message:g}}),this.emit("mediaPermissionError",p),this.emit("mediaPermissionUpdate",{message:g,kind:f})})),h){l.info(`Setting up DyteSelfMedia streams using media handler. audio:${!!(e!=null&&e.audio)} video:${(o=e==null?void 0:e.video)!=null?o:!0}`);const p=this.localMediaHandler.setupStreams({video:(a=e==null?void 0:e.video)!=null?a:!0,audio:(d=e==null?void 0:e.audio)!=null?d:!0});r||(yield p)}}catch(h){l.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,r){let n;return r==="audio"?n="audioinput":r==="video"?n="videoinput":r==="speaker"&&(n="audiooutput"),this.localMediaHandler.getDeviceById(e,n)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(r){}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(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Ig=new WeakMap;const ro={},sn={executeWithLock({methodName:t,lockName:e,timeout:r}){return(n,i,s)=>{const o=s.value;return s.value=function(...a){if(ro[e]){const p=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw p.name="UnsupportedConcurrentMethodExecution",l.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:p.stack},dyteLocker:{methodName:t,lockName:e}}),p}ro[e]=!0;const d=setTimeout(()=>delete ro[e],r),h=o.apply(this,a);return Promise.resolve(h).then(()=>{delete ro[e],clearTimeout(d)}).catch(()=>{delete ro[e],clearTimeout(d)}),h},s}}};var eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,Pt=(t,e,r,n)=>{for(var i=n>1?void 0:n?tD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&eD(e,r,i),i},pc,Or,no,es,Ge,Ye,io,Gl,Rg,Pg;let ot=(Pg=class extends ZM{constructor(t,e,r,n,i){var s;super(),_(this,Ge),_(this,Gl),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),_(this,pc,void 0),_(this,Or,void 0),_(this,no,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),_(this,es,void 0),m(this,"presetName"),m(this,"roomState","init"),_(this,io,new Set),T(this,es,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",T(this,Or,r),T(this,pc,n),T(this,no,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ye.isElectron(),this.device=ye.getDeviceInfo(),this.presetName=i,n.viewType!==We.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this)}get stageStatus(){return c(this,es).getValue("stageStatus")}get id(){return c(this,es).getValue("peerId")}static __init__(t,e,r,n,i,s=!1){return u(this,null,function*(){var o,a,d,h,p;let f=(a=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?a:!0,g=(h=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?h:!0;r.canProduceAudio!=="ALLOWED"&&(f=!1),r.canProduceVideo!=="ALLOWED"&&(g=!1);const E=new ot(t,e,r,n,i);if(n.viewType===We.Chat)return E;const v=OA(n.mediaConstraints);return jr(v,(p=t.getValue("defaults"))==null?void 0:p.mediaConfiguration),yield E.init({audio:f,video:g,constraints:v},s,t),E.setupEvents(),E})}setupEvents(){this.on("videoUpdate",ue(this,Gl,Rg)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},Bn(this))),this.roomJoined&&this.audioEnabled)try{yield c(this,Ge,Ye).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(l.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",V({},Bn(this))),this.roomJoined&&this.rawVideoTrack===void 0)l.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&this.roomJoined)try{const t=yield c(this,Ge,Ye).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Ge,Ye).shareWebcam(this.videoTrack))}catch(t){l.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>u(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!this.roomJoined){l.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield c(this,Ge,Ye).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}l.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",V({},Bn(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){l.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),l.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",V({},Bn(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{B.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff()}))}get permissions(){return c(this,Or)}get config(){return c(this,pc)}get roomJoined(){var t;return((t=c(this,Ge,Ye))==null?void 0:t.roomJoined)===!0}setName(t){if(!t)throw new C("Name cannot be empty.");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){var e,r;return t.forceReset&&(c(this,Ge,Ye).stopAllProducers(),this.localMediaHandler.removeAllTracks()),this.localMediaHandler.setupStreams({video:(e=t.video)!=null?e:!0,audio:(r=t.audio)!=null?r:!0})})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==q.NotAllowed&&!(c(this,Or).canProduceAudio===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(yield this.localMediaHandler.enableAudio(),this.roomJoined&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield c(this,Ge,Ye).shareMic(this.audioTrack)}catch(t){l.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;c(this,Ge,Ye).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOn()}})}enableVideo(){return u(this,null,function*(){if(c(this,Or).canProduceVideo!==q.NotAllowed&&!(c(this,Or).canProduceVideo===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(yield this.localMediaHandler.enableVideo(),this.roomJoined&&this.stageStatus==="ON_STAGE")try{yield c(this,Ge,Ye).shareWebcam(this.videoTrack)}catch(t){l.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),l.info("DyteSelf.enableVideo",V({},Bn(this))),B.videoOn()}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t enable screenshare without joining room");if(c(this,Or).canProduceScreenshare!==q.NotAllowed&&!(c(this,Or).canProduceScreenshare===q.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield c(this,Ge,Ye).shareScreen(this.screenShareTracks)}catch(t){l.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),this.roomJoined&&c(this,Ge,Ye).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),B.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),B.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),this.roomJoined&&(yield c(this,Ge,Ye).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){T(this,no,t);const r=t?"pinned":"unpinned";e&&this.emit(r,this)}get isPinned(){return c(this,no)}pin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t pin participants without joining room");return c(this,Ge,Ye).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.roomJoined)throw new C("Can`t unpin participants without joining room");return c(this,Ge,Ye).pinPeer(null)})}setDevice(t){return u(this,null,function*(){var e,r,n;if(!t)throw new C("No device selected");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((r=i==null?void 0:i.video)==null?void 0:r.deviceId)===t.deviceId||((n=i==null?void 0:i.speaker)==null?void 0:n.deviceId)===t.deviceId)&&(l.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),K.hasFeature(X.SKIP_SETTING_IN_USE_DEVICE)))throw new C("Cannot set device currently in use");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(s){this.roomJoined&&(yield c(this,Ge,Ye).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){this.roomJoined&&(yield c(this,Ge,Ye).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,n;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(n=this.rawVideoTrack)==null||n.stop()}registerVideoElement(t){c(this,io).add(t),this.updateVideo(t)}deregisterVideoElement(t){t.srcObject=void 0,c(this,io).delete(t)}updateVideo(t){if(this.videoEnabled){if(this.videoTrack==null)return;const e=new MediaStream;e.addTrack(this.videoTrack),t.srcObject=e}else t.srcObject=void 0}},pc=new WeakMap,Or=new WeakMap,no=new WeakMap,es=new WeakMap,Ge=new WeakSet,Ye=function(){return c(this,es).getValue("roomNodeClient")},io=new WeakMap,Gl=new WeakSet,Rg=function(){Array.from(c(this,io)).forEach(this.updateVideo)},Pg);Pt([y.trace("DyteSelf.setupEvents")],ot.prototype,"setupEvents",1),Pt([y.trace("DyteSelf.setupTracks")],ot.prototype,"setupTracks",1),Pt([y.trace("DyteSelf.destructMediaHandler")],ot.prototype,"destructMediaHandler",1),Pt([y.trace("DyteSelf.removeDocumentEventListeners")],ot.prototype,"removeDocumentEventListeners",1),Pt([sn.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.enableAudio")],ot.prototype,"enableAudio",1),Pt([sn.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.enableVideo")],ot.prototype,"enableVideo",1),Pt([y.trace("DyteSelf.updateVideoConstraints")],ot.prototype,"updateVideoConstraints",1),Pt([y.trace("DyteSelf.enableScreenShare"),sn.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],ot.prototype,"enableScreenShare",1),Pt([y.trace("DyteSelf.updateScreenshareConstraints")],ot.prototype,"updateScreenshareConstraints",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),y.trace("DyteSelf.disableAudio")],ot.prototype,"disableAudio",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),y.trace("DyteSelf.disableVideo")],ot.prototype,"disableVideo",1),Pt([sn.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),y.trace("DyteSelf.disableScreenShare")],ot.prototype,"disableScreenShare",1),Pt([y.trace("DyteSelf.setDevice")],ot.prototype,"setDevice",1),ot=Pt([dt("1100")],ot);class rD extends mg{constructor(e){super(e),m(this,"sessionDescription"),this.sessionDescription=e.sessionDescription}}class nD extends Eg{}class iD extends yg{retryFailedConsumerCreationTasks(e){return u(this,null,function*(){return sc(e.map(r=>u(this,null,function*(){return fr(n=>u(this,null,function*(){return n>0&&l.warn(`retrying failed consumer creation task: ${JSON.stringify(r)}`),this.consumerCreationTask(V({},r))}))})))})}consumerCreationTask(e){return u(this,arguments,function*({consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,paused:d,screenShare:h,appData:p,kind:f,sessionDescription:g}){const E=`${o}:${f}`,v={consumerId:r,producerId:n,producingPeerId:i,producingTransportId:s,streamId:o,trackId:a,sessionDescription:g,appData:p,kind:f,paused:d,screenShare:h,name:"consumer creation task error",message:"consumer creation failed"};return new Promise((R,A)=>u(this,null,function*(){const L=setTimeout(()=>{this.consumerTrackEvents.delete(E),v.isTimedout=!0,A(v)},5e3),F=(I,S)=>{try{if(I.readyState==="ended")clearTimeout(L),A(v);else{const P=I;P.enabled=!0,this.handler.midTransceiverMap.set(S.mid,S);const N=new rD({id:r,localId:S.mid,track:P,paused:d,producerId:n,producingPeerId:i,handler:this.handler,appData:ne(V({},p),{screenShare:h,peerId:i}),reuseTrack:!0,rtpReceiver:S.receiver,producingTransportId:s,sessionDescription:g});this.consumers.set(r,N),N.once("close",()=>{this.consumers.delete(N.id),this.handler.midTransceiverMap.delete(S.mid)}),l.info("consumer created for ",{consumer:{id:r,kind:f,appData:{screenShare:h},peerId:i,producerId:n}}),this.observer.emit("newconsumer",N),clearTimeout(L),R(N)}}catch(P){l.warn("error while creating consumer:",P),clearTimeout(L),A(v)}},W=this.consumerTrackPool.get(r);if((W==null?void 0:W.length)===2){F(W[0],W[1]);return}const H=this.unknownTracksMap.get(E);H?(this.unknownTracksMap.delete(E),F(H.track,H.transceiver)):this.consumerTrackEvents.set(E,F),g&&(yield this.safeEmitAsPromise("negotiate",{description:g}))}))})}connect(){return u(this,null,function*(){try{const{offerSdp:e,callback:r}=yield this.handler.connect(),{answer:n}=yield this.safeEmitAsPromise("connect",{offer:e});if(yield r(n),!(yield this.isConnected))throw new Error("ice connection failed")}catch(e){throw l.error("transport failed to connect:",e),e}})}_ontrack(e){const{track:r,transceiver:n}=e;l.info(`track event received [trackId: ${r.id}]`);const i=`${n.mid}:${r.kind}`;r.addEventListener("ended",()=>{l.info(`rtc consumer track ended [trackId: ${r.id}]`),this.consumerTrackPool.delete(r.id),this.unknownTracksMap.delete(i)}),this.consumerTrackPool.set(r.id,[r,n]);const s=this.consumerTrackEvents.get(i);s?(s(r,n),this.consumerTrackEvents.delete(i)):(l.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,e))}consume(e){return u(this,null,function*(){const{producers:r,producingPeerId:n}=e;if(l.debug(`consume() peerId: ${n}, producers: ${JSON.stringify(r)}`),this.closed)throw new it("closed");if(this.direction!=="recv")throw new Jn("not a receiving Transport");if(typeof e.producingPeerId!="string")throw new TypeError("missing producingPeerId");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const i=[],{consumersMap:s}=yield this.safeEmitAsPromise("consume_peer",{producingPeerId:n});return s.forEach((o,a)=>{const{consumerId:d,trackId:h,screenShare:p,paused:f,streamId:g,kind:E,appData:v,producingTransportId:R,sessionDescription:A}=o;i.push(this.consumerCreationTask({consumerId:d,trackId:h,streamId:g,kind:E,producerId:a,producingPeerId:n,producingTransportId:R,paused:f,screenShare:p,appData:v,sessionDescription:A}))}),sc(i)})}produce(){return u(this,arguments,function*({track:e,encodings:r,codecOptions:n,stopTracks:i=!0,disableTrackOnPause:s=!0,zeroRtpOnPause:o=!1,appData:a={}}={}){if(l.debug(`produce() [track:${e.id}]`),e){if(this.direction!=="send")throw new Jn("not a sending Transport");if(e.readyState==="ended")throw new it("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.isConnected))return Promise.reject(new Error("Transport not connected"));const{producerId:d,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:g,callback:E,sender:v,mid:R}=yield this.handler.send({track:e,encodings:r,codecOption:n,screenShare:a==null?void 0:a.screenShare}),{answer:A,producerId:L}=yield this.safeEmitAsPromise("produce",{offer:g,kind:e.kind,paused:s?!e.enabled:!1,appData:ne(V({},a||{}),{mid:R})}),F=yield E(A);return{producerId:L,localId:F,rtpSender:v}}),"producer"),f=new nD({id:d,localId:h,track:e,stopTracks:i,disableTrackOnPause:s,zeroRtpOnPause:o,appData:a,handler:this.handler,rtpSender:p});return this.producers.set(d,f),f.observer.on("close",()=>{this.producers.delete(f.id)}),this.emit("newproducer",f),this.observer.emit("newproducer",f),f})}}class sD extends Sg{createTransport({direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,config:a}){const d=gn(),h=new iD({id:d,direction:e,iceServers:r,iceTransportPolicy:n,additionalSettings:i,proprietaryConstraints:s,appData:o,handlerFactory:this.handlerFactory,config:a});return this._observer.emit("newtransport",h),h}}var Tt;class oD{constructor(e){_(this,Tt,void 0),T(this,Tt,e)}joinRoom(e,r,n=!1,i=null){return u(this,null,function*(){const s={roomUuid:e,displayName:r,prejoined:n};return i&&(s.location=i),(yield c(this,Tt).sendMessagePromiseWithTimeout({event:se.joinRoom,protobuf:Sm.toBinary(s),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.createWebRTCTransport,vm.toBinary(e))).payload,{transportId:n,description:i}=Hd.fromBinary(r),s={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:n,answer:s}})}produce(e){return u(this,null,function*(){var r,n;const i=(yield c(this,Tt).sendMessagePromise(se.produce,bm.toBinary(e))).payload,s=Fm.fromBinary(i);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.sdp,type:(n=s==null?void 0:s.description)==null?void 0:n.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.consume,_m.toBinary(e))).payload,{consumerIdsMap:{map:n},description:i}=xm.fromBinary(r);return{consumerStateMap:n,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.closeProducer,Cm.toBinary(e))).payload,{description:n}=Um.fromBinary(r);return n})}closeConsumer(e){return u(this,null,function*(){return(yield c(this,Tt).sendMessagePromise(se.closeConsumer,Im.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const n={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},i=(yield c(this,Tt).sendMessagePromise(se.hostControlPeer,Mm.toBinary(n))).payload;if(!i)return!1;const{status:s}=jm.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},n=(yield c(this,Tt).sendMessagePromise(se.hostControlAllPeers,Dm.toBinary(r))).payload;if(!n)return!1;const{status:i}=Hm.fromBinary(n);return i==="success"})}kickAll(){return u(this,null,function*(){const e={},r=(yield c(this,Tt).sendMessagePromise(se.kickAll,Pm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Bm.fromBinary(r);return n==="success"})}kickPeer(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.kickPeer,Rm.toBinary(e))).payload;if(!r)return!1;const{status:n}=Vm.fromBinary(r);return n==="success"})}changeDisplayName(e){return u(this,null,function*(){const r=(yield c(this,Tt).sendMessagePromise(se.changeDisplayName,Am.toBinary(e))).payload;if(!r)return!1;const{status:n}=Wm.fromBinary(r);return n==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield c(this,Tt).sendMessagePromise(se.selfJoinComplete,Tm.toBinary(e))).payload;return aa.fromBinary(r)})}}Tt=new WeakMap;const aD=2e3;var on;class cD extends ug{constructor(e,r){super(),m(this,"_device"),m(this,"_sendTransport"),m(this,"_recvTransport"),m(this,"_consumers"),m(this,"_producers"),m(this,"_producerStatus"),m(this,"_producerIdToConsumerIdMap"),m(this,"_socket"),m(this,"_socketHandler"),m(this,"_totalTransportReconnectionCount"),m(this,"_transportReconnectFailureCount"),m(this,"_consumerCreationFailureCount"),m(this,"_producerNotReadyFailureCount"),m(this,"_consumerNotBoundFailureCount"),m(this,"_transportDisconnectedTimer"),m(this,"_iceTransportPolicy","all"),m(this,"_transportConnectionFailCount",0),m(this,"lastConnectionTime",0),m(this,"transportConnectionStatus"),m(this,"transportState"),m(this,"transportDisconnected"),_(this,on,void 0),T(this,on,e),this._device=new sD({}),this._socket=r,this.transportState={consuming:{state:st.NEW,reconnected:!1},producing:{state:st.NEW,reconnected:!1}},this.transportDisconnected={consuming:!1,producing:!1},this._socketHandler=new oD(r),this.reset()}get socket(){return this._socket}get producers(){return this._producers}get consumers(){return this._consumers}get producerIdToConsumerIdMap(){return this._producerIdToConsumerIdMap}get cfSocketHandler(){return this._socketHandler}get sendTransport(){return this._sendTransport}get recvTransport(){return this._recvTransport}reset(){this._producers=new Map,this._consumers=new Map,this._producerStatus=new Map,this._producerIdToConsumerIdMap=new Map,this.transportConnectionStatus=new Map,this._transportReconnectFailureCount=0,this._consumerCreationFailureCount=0,this._totalTransportReconnectionCount=0,this._producerNotReadyFailureCount=0,this._consumerNotBoundFailureCount=0,this._transportDisconnectedTimer={consuming:void 0,producing:void 0}}setupTransports(e,r){return u(this,null,function*(){const n=yield je().getICEServers().catch(s=>(l.warn(`failed to get iceservers from server: ${s.message}`),[])),i=e.map(s=>{var o,a,d,h,p,f,g,E;const v=this.transportConnectionStatus.get(s);if(v&&!r)return v;switch(v&&r&&Yi.stop(v.id),s){case"send":{const R=Yi.execute(this.createSendTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(o=c(this,on).getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(h=(d=(a=c(this,on).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:d.enableHighBitrate)!=null?h:!1,enableStereo:(g=(f=(p=c(this,on).getValue("defaults").mediaConfiguration)==null?void 0:p.audio)==null?void 0:f.enableStereo)!=null?g:!1},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}case"recv":{const R=Yi.execute(this.createRecvTransport({iceServers:n,additionalSettings:{encodedInsertableStreams:(E=c(this,on).getValue("modules").e2ee)==null?void 0:E.enabled},iceTransportPolicy:this._iceTransportPolicy}));return this.transportConnectionStatus.set(s,R),R.value}default:return l.warn(`What are you thinking when passing this transportType: ${s}?`,{transport:{type:s}}),Promise.reject(Error("TYPE_OF_TRANSPORT_UNKNOWN"))}});return Promise.all(i).finally(()=>{e.forEach(s=>{this.transportConnectionStatus.delete(s)})})})}stopAllTransports(){var e,r,n,i;l.info(" closing all the transports"),(e=this._sendTransport)==null||e.close(),(r=this._sendTransport)==null||r.removeAllListeners(),(n=this._recvTransport)==null||n.close(),(i=this._recvTransport)==null||i.removeAllListeners(),this._sendTransport=void 0,this._recvTransport=void 0,this.reset()}createSendTransport(e){return u(this,null,function*(){var r,n,i,s;if(this._sendTransport&&this._sendTransport.connected){l.info("sendTransport::already_exists_in_connected_state",{transport:{id:(r=this._sendTransport)==null?void 0:r.id,serverId:(n=this._sendTransport)==null?void 0:n.serverId,type:"send"}});return}l.info("sendTransport::initializing_transport",{transport:{id:(i=this._sendTransport)==null?void 0:i.id,serverId:(s=this._sendTransport)==null?void 0:s.serverId,type:"send"}});const o=this._device.createSendTransport(e);this._transportDisconnectedTimer.producing=void 0,l.info("sendTransport::initialized_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this.handleTransport(o,!1),l.info("sendTransport::connecting_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}});try{yield fr((a,d)=>u(this,null,function*(){this.socket.isConnected||d(new Error("socket is not connected")),o.connectionState==="closed"&&d(new Error("transport is closed")),a>0&&l.debug(`retrying transport connect, count: ${a}`,{transport:{id:o.id,serverId:o.serverId,type:"send"}});try{yield o.connect()}catch(h){throw l.error(`failed to connect send transport: ${o.id}`,{error:h,transport:{id:o.id,serverId:o.serverId,type:"send"}}),h.message==="ice connection failed"&&d(h),h}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("sendTransport::connected_transport",{transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._producerNotReadyFailureCount=0,this._sendTransport=o,B.onSafeInitialization(()=>{B.configureSendTransport(o)})}catch(a){throw l.error(`failed to connect send transport after retry:${o.id}`,{error:a,transport:{id:o==null?void 0:o.id,serverId:o==null?void 0:o.serverId,type:"send"}}),o.close(),o.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),a}})}createRecvTransport(e){return u(this,null,function*(){var r,n,i,s,o;if(this._recvTransport&&this._recvTransport.connected){l.info("recvTransport::already_exists_in_connected_state",{transport:{id:(r=this._recvTransport)==null?void 0:r.id,serverId:(n=this._recvTransport)==null?void 0:n.serverId,type:"recv"}});return}l.info("recvTransport::initializing_transport",{transport:{id:(i=this._recvTransport)==null?void 0:i.id,serverId:(s=this._recvTransport)==null?void 0:s.serverId,type:"recv"}});const a=this._device.createRecvTransport(ne(V({},e),{additionalSettings:ne(V({},(o=e.additionalSettings)!=null?o:{}),{rtcAudioJitterBufferMaxPackets:25,rtcAudioJitterBufferFastAccelerate:!0,rtcAudioJitterBufferMinDelayMs:20})}));this._transportDisconnectedTimer.consuming=void 0,l.info("recvTransport::initialized_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this.handleTransport(a,!0),l.info("recvTransport::connecting_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield fr((d,h)=>u(this,null,function*(){this.socket.isConnected||h(new Error("socket is not connected")),a.connectionState==="closed"&&h(new Error("transport is closed")),d>0&&l.debug(`retrying transport connect, count: ${d}`,{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}});try{yield a.connect()}catch(p){throw l.error(`fail to connect recv transport: ${a.id}`,{error:p,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),p.message==="ice connection failed"&&h(p),p}}),{delayTime:100,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),l.info("recvTransport::connected_transport",{transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),this._transportReconnectFailureCount=Math.max(0,this._transportReconnectFailureCount-1),this._consumerCreationFailureCount=0,this._consumerNotBoundFailureCount=0,this.producerIdToConsumerIdMap.clear(),this._recvTransport=a,B.onSafeInitialization(()=>{B.configureRecvTransport(a)})}catch(d){throw l.error(`failed to connect recv transport after retry:${a.id}`,{error:d,transport:{id:a==null?void 0:a.id,serverId:a==null?void 0:a.serverId,type:"recv"}}),a.close(),a.removeAllListeners(),this._transportReconnectFailureCount+=1,this.handleFailure(),d}})}handleTransport(e,r){if(e.on("connect",(n,i,s)=>u(this,[n,i,s],function*({offer:o},a,d){try{const h={consuming:r,description:{sdp:o.sdp,type:o.type,target:r?Mt.SUBSCRIBER:Mt.PUBLISHER}},{transportId:p,answer:f}=yield this._socketHandler.connectTransport(h);e.setServerId(p),a({answer:f})}catch(h){l.error(`${r?"consumer":"producer"} transport connection error:`,{error:h,transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send"}}),d(h)}})),e.on("connectionstatechange",n=>u(this,null,function*(){this.updateTransportState({state:n,direction:r?"consuming":"producing"}),l.info(`${r?"consumer":"producer"} transport connectionState:`,{transport:{id:e==null?void 0:e.id,serverId:e==null?void 0:e.serverId,type:r?"recv":"send",status:n}});const i=()=>{this._transportDisconnectedTimer[r?"consuming":"producing"]!==void 0&&(clearTimeout(this._transportDisconnectedTimer[r?"consuming":"producing"]),this._transportDisconnectedTimer[r?"consuming":"producing"]=void 0)};switch(n){case"connected":i(),this.lastConnectionTime=performance.now();break;case"disconnected":this._transportDisconnectedTimer[r?"consuming":"producing"]=setTimeout(()=>{this.triggerTransportReconnection(e,r)},aD);break;case"failed":if(e.closed)return;i(),this.triggerTransportReconnection(e,r);break}})),e.on("icecandidate",n=>u(this,null,function*(){l.debug("sending icecandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,i)=>u(this,null,function*(){var s,o;l.debug("got data channel message on event:",{rtcChannel:{label:n,message:i}});try{switch(i.type){case"negotiation":{this.negotiateOverDC(i,ac(i),n,e);break}case"handshake":{const a={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,ac(i),a);break}case"consumer_toggle":{this.handleConsumerToggle(i.payload);break}case"hub-disconnect":{l.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((o=i.payload)==null?void 0:o.full_reconnect)===!0&&this.emit("rejoin");break}case"error":{this.handleErrorOverDC(i.payload,e.id);break}default:l.warn(`unknown event received from cf node, event: ${i.type}`);break}}catch(a){l.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(l.warn("events datachannel did not open in 5s"),this.handleFailure())}),e.on("negotiate",(n,i,s)=>u(this,[n,i,s],function*({description:o},a,d){try{const h={sdp:o==null?void 0:o.sdp,type:o==null?void 0:o.type},p=yield this.negotiate(e,h);a({answer:p})}catch(h){l.error("negotiate error:",{transport:{id:e.id,serverId:e.serverId,type:e.direction},error:h}),d(h)}})),!r){e.on("produce",(n,i,s)=>u(this,[n,i,s],function*({offer:o,kind:a,paused:d,appData:h},p,f){var g;const E=Kc(o.sdp).media.filter(R=>a==="video"?R.type==="video":R.type==="audio").at(-1).msid,v={description:{sdp:o.sdp,type:o.type,target:Mt.PUBLISHER},paused:d,kind:a,msid:E,appData:JSON.stringify(h),screenShare:(g=h.screenShare)!=null?g:!1};try{const{answer:R,producerId:A}=yield this._socketHandler.produce(v);p({answer:R,producerId:A})}catch(R){l.error("create producer error:",{error:R}),f(R)}}));return}e.on("consume_peer",(n,i,s)=>u(this,[n,i,s],function*({producingPeerId:o},a,d){l.info("consumePeer:",o);const h={producingPeerId:o};try{const p=yield this._socketHandler.consume(h);l.debug(`consumePeer response for ${o}:`,{consumerStateMap:p.consumerStateMap});const f=new Map;Object.entries(p.consumerStateMap).forEach(([g,E])=>{var v,R,A;let L={};try{L=JSON.parse(E.producerState.appData)}catch(F){}f.set(g,{consumerId:E.consumerId,trackId:(v=E.producerTrack)==null?void 0:v.trackId,streamId:E.producerTrack.streamId,kind:E.producerState.kind===wt.VIDEO?"video":"audio",appData:L,screenShare:(R=E.producerState)==null?void 0:R.screenShare,paused:(A=E.producerState)==null?void 0:A.pause,sessionDescription:p.sessionDescription})}),a({consumersMap:f})}catch(p){l.error("consumePeer error:",{error:p}),d(p)}})),e.on("consume",(n,i,s)=>u(this,[n,i,s],function*({producerId:o,producingPeerId:a},d,h){var p,f,g,E,v,R,A,L,F;const W={producingPeerId:a,producerId:o};try{const H=yield this._socketHandler.consume(W),I=H.consumerStateMap[o];let S={};try{S=JSON.parse((p=I.producerState)==null?void 0:p.appData)}catch(P){}l.info("consumer create response:",{consumer:{remotelyPaused:(f=I.producerState)==null?void 0:f.pause,producerId:(g=I.producerState)==null?void 0:g.producerId,kind:(v=(E=I.producerState)==null?void 0:E.kind)==null?void 0:v.toString(),appData:ne(V({},S),{screenShare:(R=I.producerState)==null?void 0:R.screenShare}),id:I.consumerId,sessionDescription:H.sessionDescription},consumerState:I}),d({consumerId:I.consumerId,screenShare:(A=I.producerState)==null?void 0:A.screenShare,trackId:(L=I.producerTrack)==null?void 0:L.trackId,streamId:I.producerTrack.streamId,kind:I.producerState.kind===wt.VIDEO?"video":"audio",paused:(F=I.producerState)==null?void 0:F.pause,appData:S,sessionDescription:H.sessionDescription})}catch(H){l.error("error during consuming on server:",H),h(H)}}))}createProducer(e,r,n){return u(this,null,function*(){var i;if(this._sendTransport===void 0||this._sendTransport.closed)return null;l.info("createProducer::initializing_producer",{producer:{id:"TO_BE_CREATED",kind:e,status:"initializing",appData:r==null?void 0:r.appData}});const s=this._producerStatus.get(e);if((s==null?void 0:s.trackId)===r.track.id&&(s==null?void 0:s.status)===Pr.INITIALIZING)return l.info("createProducer::producer getting initializing",{producer:{id:"GETTING_CREATED",status:"initializing",kind:e,appData:r==null?void 0:r.appData}}),null;this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZING});try{const o=yield this._sendTransport.produce(r);return(i=r.appData)!=null&&i.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,o),l.info("createProducer::initialized_producer",{producer:{id:o==null?void 0:o.id,kind:e,status:"producing",appData:r==null?void 0:r.appData}}),o.on("close",(a,d)=>u(this,[a,d],function*({offer:h,reason:p},f){l.info("producer::closing",{debuggingHint:p,producer:{id:o==null?void 0:o.id,kind:e,status:"closing",appData:r==null?void 0:r.appData}});const g={producerId:o.id,description:{sdp:h.sdp,type:h.type,target:Mt.PUBLISHER}};try{const E=yield this._socketHandler.closeProducer(g),v={sdp:E==null?void 0:E.sdp,type:E==null?void 0:E.type};l.info("producer::closed",{producer:{id:o==null?void 0:o.id,kind:e,status:"closed",appData:r==null?void 0:r.appData}}),f({answer:v})}catch(E){l.error("producer close error",E)}this._producerStatus.delete(e),this._producers.delete(e),n(),this.reconfigureWebcamLayers()})),o.on("trackended",()=>{l.info("producer::trackended",{producer:{id:o==null?void 0:o.id,kind:e,status:"UNKNOWN",appData:o==null?void 0:o.appData}}),[Q.MIC,Q.WEBCAM].includes(e)||n()}),this._producers.set(e,o),this._producerStatus.set(e,{trackId:r.track.id,status:Pr.INITIALIZED}),this.reconfigureWebcamLayers(),o.track}catch(o){throw this._producerStatus.set(e,{status:Pr.NOT_INITIALIZED,trackId:r.track.id}),l.error("createProducer::transport_initialization_failed",{producer:{id:"FAILED_TO_CREATE",kind:e,status:"failed",appData:r==null?void 0:r.appData,error:o}}),o}})}reconfigureWebcamLayers(){return u(this,null,function*(){if(!K.hasFeature(X.DISABLE_WEBCAM_LAYERS_ON_SCREENSHARE))return;const e=this.producers.get(Q.WEBCAM);e&&(yield this._switchProducerSpatialLayer(e,this.producers.get(Q.SCREENSHARE_VIDEO)?0:3))})}_switchProducerSpatialLayer(e,r){return u(this,null,function*(){try{l.debug("switching layer of webcam producer to:",{media:{video:{layer:r}},producer:{id:e.id,kind:e.kind,appData:e.appData}}),yield e.setMaxSpatialLayer(r)}catch(n){l.error("failed to switch spatial layer",{error:n})}})}_initConsumer(e){e&&(e.observer.on("close",r=>u(this,null,function*(){l.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),this._consumers.delete(e.id),b.emit(w.CONSUMER_CLOSED,{id:e.id})})),this._consumers.set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),b.emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId}))}createConsumer(e){return u(this,null,function*(){if(this._recvTransport===void 0||this._recvTransport.closed||!this._recvTransport.connected)return;const{producers:r,producingPeerId:n}=e;if(r.every(i=>this.getProducer(i.producerId))){l.warn("why are you creating a consumer for local producer?");return}yield fr(i=>u(this,null,function*(){i>0&&l.debug(`retrying consume call, retryCount: ${i}`),(yield this._recvTransport.consume({producingPeerId:n,producers:r}).catch(s=>{throw l.error("failed to consume:",{error:s}),s})).forEach(s=>{s.status==="rejected"?(l.error("consumer creation task is failing",s.reason),this._consumerCreationFailureCount+=1,setTimeout(this.handleFailure.bind(this),0)):this._initConsumer(s.value)})})).catch(i=>{l.error("create consumer failed after retries",{error:i}),this._consumerCreationFailureCount+=1,this.handleFailure()})})}pauseProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.pause(),r.appData.e2ee&&b.emit(w.E2EE_INACTIVE_PRODUCER,r),l.info(`Paused the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}resumeProducer(e){return u(this,null,function*(){const r=this._producers.get(e);if(!r){l.warn(`producer type: ${e} not found`);return}r.resume(),l.info(`Resumed the producer of type: ${r.kind}`,{producer:{id:r.id,kind:r.kind,appData:r.appData}})})}replaceTrack(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}yield n.replaceTrack({track:r}),l.info(`Replaced track for the producer of type: ${n.kind}`,{producer:{id:n.id,kind:n.kind,appData:n.appData,trackId:r.id}})})}removeProducer(e,r){return u(this,null,function*(){const n=this._producers.get(e);if(!n){l.warn(`producer type: ${e} not found`);return}r&&n.track.stop(),yield this.sendTransport.awaitQueue.push(n.close.bind(n),"producer").then(()=>{c(this,on).getValue("modules").e2ee.enabled&&b.emit(w.E2EE_INACTIVE_PRODUCER,n)}).catch(i=>{l.error("failed to close producer on server",i)})})}pauseConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}this.toggleConsumerOverDC(e,!0),l.info(`Paused the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})})}pauseConsumerOverSocket(e){return u(this,null,function*(){try{const r={consumerId:e.id,pause:!0};yield this.socket.sendMessagePromise(se.toggleConsumer,oa.toBinary(r)),e.pause(),b.emit(w.CONSUMER_PAUSED,{id:e.id}),l.info(`Paused the consumer of type: ${e.kind} over socket`,{consumer:{id:e.id,kind:e.kind,appData:e.appData}})}catch(r){l.error("error on pausing consumer",{error:r,consumer:{id:e.id,kind:e.kind,appData:e.appData}})}})}toggleConsumerOverDC(e,r){return u(this,null,function*(){const n={type:"consumer_toggle",payload:{consumerId:e,mute:r}},i=this._recvTransport.getDatachannel("events");if(!i){l.warn("recvTransport:: events datachannel not found");return}yield i.request(n),l.info(`HiveSFUHandler::consumer toggled, consumerId: ${e}, muted: ${r}`)})}resumeConsumer(e){return u(this,null,function*(){const r=this._consumers.get(e);if(!r){l.warn(`consumer with id: ${e} not found`);return}if(!r.paused){l.warn(`consumer with id:${e} is not paused so not resuming`);return}try{const n={consumerId:e,pause:!1};yield this.socket.sendMessagePromise(se.toggleConsumer,oa.toBinary(n)),r.resume(),b.emit(w.CONSUMER_RESUMED,{id:r.id}),l.info(`Resumed the consumer of type: ${r.kind}`,{consumer:{id:r.id,kind:r.kind,appData:r.appData}})}catch(n){l.error("error on resuming consumer",n)}})}closeConsumer(e,r){return u(this,null,function*(){return this.closeConsumers([e],r)})}closeConsumers(e,r=!1){return u(this,null,function*(){l.info(`Closing consumers: ${JSON.stringify(e)} with force: ${r}`);let n=!0;const i=e.filter(a=>this._consumers.get(a)?!0:(l.warn(`consumer with id: ${a} not found`),!1));if(!i.length)return;const s={consumerIds:i},o=()=>u(this,null,function*(){var a;return(a=this._recvTransport)==null?void 0:a.awaitQueue.push(()=>u(this,null,function*(){yield this._socketHandler.closeConsumer(s)}),"close_consumer").catch(d=>{l.warn("error on closing consumer:",{error:d}),n=r})});r?o():yield o(),n&&i.forEach(a=>{const d=this.consumers.get(a);this.producerIdToConsumerIdMap.delete(d.producerId),d.close(r?"force closed":void 0)})})}cleanupConsumers(e){return u(this,null,function*(){l.debug("cleaning up all consumers");const r=[];this._consumers.forEach(n=>{e?n.peerId===e&&r.push(n.id):r.push(n.id)}),this.closeConsumers(r,!0)})}stopAllProducers(){return u(this,null,function*(){l.info("stopping all available producers"),this._producers.forEach((e,r)=>{l.debug(`closing producer type: ${r}`,{producer:{id:e==null?void 0:e.id,kind:e.kind,appData:e.appData}}),e.close()})})}getProducer(e){return Array.from(this.producers.values()).filter(r=>r.id===e).at(0)}hasProducer(e){return this.getProducer(e)!==void 0}negotiate(e,r){return u(this,null,function*(){l.debug(`setting remote offer : ${JSON.stringify(r)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}});const n=yield e.setRemoteOffer(r),i={transportId:e.serverId,description:{sdp:n.sdp,type:n.type,target:Mt.SUBSCRIBER}};return l.debug(`sending renegotiate request: ${JSON.stringify(i)} on ${e.direction} transport`,{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),yield this.socket.sendMessagePromise(se.renegotiateSessionDescription,ym.toBinary(i)),l.info("renegotiation done",{transport:{id:e.id,serverId:e.serverId,type:e.direction}}),n})}negotiateOverDC(e,r,n,i){return u(this,null,function*(){const{sdp:s}=e.payload,o={sdp:s,type:"offer"};try{l.debug(`got offer over dc: ${s} for transport: ${i.id}`);const a=yield i.setRemoteOffer(o),d={type:"answer",payload:{type:a.type,sdp:a.sdp}};l.debug(`datachannel answer: ${JSON.stringify(d)}`),i.sendResponseOverDC(n,r,d)}catch(a){l.error("datachannel:events::Error:",a),a.code!=="DC_NOT_FOUND"&&i.sendErrorOverDC(n,r,a)}})}handleConsumerToggle(e){const{mute:r,trackId:n}=e;l.info(`consumer toggled for trackId: ${n} muted: ${r}`);const i=this.consumers.get(n);if(!i){l.warn(`consumer with trackId: ${n} not found`);return}i.paused!==r&&(l.debug("consumer state is not same",{consumer:{id:i.id,remotelyPaused:i.paused}}),r?(i.pause(),b.emit(w.CONSUMER_PAUSED,{id:i.id})):(i.resume(),b.emit(w.CONSUMER_RESUMED,{id:i.id})))}handleErrorOverDC(e,r){return u(this,null,function*(){l.error(`got error over dc: ${JSON.stringify(e)} for transport: ${r}`);const{type:n,error:i,id:s}=e;if(n==="consumer"){if(i==="bind-fail"){if(this._consumerNotBoundFailureCount>=2){this.handleFailure();return}this._consumerNotBoundFailureCount+=1;const o=this.consumers.get(s);if(!o)return;try{yield this.closeConsumer(o.id),yield this.createConsumer({producers:[{kind:o.kind,pause:o.paused,producerId:o.producerId,producingTransportId:o.producingTransportId,screenShare:o.appData.screenShare}],producingPeerId:o.peerId})}catch(a){l.error("failed to recreate consumer on downtrack bound failure,",{consumer:{id:o.id,producerId:o.producerId,kind:o.kind,appData:o.appData}})}}}else if(n==="producer")if(i==="ready-fail"){if(this._producerNotReadyFailureCount>=2){this.handleFailure();return}this._producerNotReadyFailureCount+=1;const[o]=Array.from(this.producers.entries()).find(a=>a[1].id===s);if(!o)return;yield this.removeProducer(o).catch(a=>{l.error("failed to remove ready-fail producer:",{error:a,producer:{id:s,kind:o,appData:null}})})}else i==="general-failure"&&(this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}handleFailure(){return u(this,null,function*(){if(this._transportReconnectFailureCount>0||this._totalTransportReconnectionCount>3){l.warn("transport failure detected"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("rejoining room"),this.emit("rejoin"));return}(this._consumerCreationFailureCount>0||this._consumerNotBoundFailureCount>=2)&&(l.warn("consumer creation failure detected or consumer not bound failure increased"),K.hasFeature(X.ENABLE_CF_EXPERIMENTAL_FAIL_RECOVERY)&&(l.debug("reconnecting recv transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"consuming"}),this.emit("reconnect_transport",this._recvTransport))),this._producerNotReadyFailureCount>=2&&(l.warn("producer receiver not getting added needs to reconnect send transport"),this._totalTransportReconnectionCount+=1,this.updateTransportState({state:st.RECONNECTING,direction:"producing"}),this.emit("reconnect_transport",this._sendTransport))})}triggerTransportReconnection(e,r){l.info("triggerTransportReconnection:: reconnecting transport",{transport:{type:e.direction,id:e.id,serverId:e.serverId}});const n=K.hasFeature(X.ENABLE_CF_TRANSPORT_RECONNECTION_ON_ICE_FAILED),i=K.hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED);n&&(i&&this._socket.isConnected&&(performance.now()-this.lastConnectionTime>2e4&&(this._transportConnectionFailCount=0),this._transportConnectionFailCount>2&&(l.warn("Multiple disconnections, forcing relay"),this._iceTransportPolicy="relay"),this._transportConnectionFailCount+=1),this.updateTransportState({state:st.RECONNECTING,direction:r?"consuming":"producing"}),this.emit("reconnect_transport",e))}switchConsumersToLayer(e,r){return u(this,null,function*(){const n=this._recvTransport.getDatachannel("events");if(!n){l.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:r}};yield n.request(i),l.info(`CFSFUHandler::consumer id: ${e} layer switched to ${r}`)})}updateTransportState(e){const{state:r,direction:n}=e;r==="disconnected"&&(this.transportDisconnected[n]=!0),this.transportState[n]={state:r,reconnected:r==="connected"?this.transportDisconnected[n]:this.transportState[n].reconnected},r==="connected"&&(this.transportDisconnected[n]=!1),b.emit(w.TRANSPORT_STATE_UPDATE,V({transport:n},this.transportState[n]))}}on=new WeakMap;var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,le=(t,e,r,n)=>{for(var i=n>1?void 0:n?lD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&dD(e,r,i),i};const ts={joinAttempted:!1},uD=5e3;var Re,pe,Nr,rs,Zn,ei,mc,fc,gc,an,so,ti,Lr,cn,Ag;const Mg=(Ag=class extends lg{constructor(t,e){var r,n;super(),_(this,Lr),_(this,Re,void 0),_(this,pe,void 0),_(this,Nr,void 0),_(this,rs,void 0),_(this,Zn,void 0),_(this,ei,void 0),_(this,mc,void 0),_(this,fc,void 0),_(this,gc,void 0),_(this,an,void 0),_(this,so,void 0),_(this,ti,void 0),m(this,"legacyMode"),m(this,"roomNodeUrl"),m(this,"peerDisplayName"),m(this,"activatedProducingPeerIds"),m(this,"e2ee"),m(this,"partialJoinRoomPromise"),this.context=t;const{roomName:i,authToken:s,legacyMode:o,socketClient:a,meetingTitle:d}=e;this.roomJoined=!1,this.roomName=i,this.authToken=s,this.legacyMode=o,this.meetingTitle=d,T(this,Re,a),T(this,Nr,!1),T(this,ti,void 0),T(this,pe,new cD(t,a)),this.maxPreferredStreams=6,this.activatedProducingPeerIds=new Set,T(this,an,new Set),T(this,rs,!1),T(this,Zn,0),T(this,ei,new Ki),this.e2ee=(n=(r=t.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?n:!1,B.legacySwitch(o),this.handleSocketEvents(),this.handleSFUEvents(),this.handleSocketConnectionEvents(),this.handleCallstatsEvents(),T(this,mc,cr(()=>u(this,null,function*(){if(!ts.joinAttempted)return;const{roomJoined:h}=yield this.joinRoom(this.peerDisplayName,this.roomUUID,{},!0,!0);h&&(b.emit(w.RESET_PRODUCER_STATE),b.emit(w.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3})),T(this,fc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["send"]),l.info("send transport reconected!"),b.emit(w.RESET_PRODUCER_STATE)}),1e3)),T(this,gc,cr(h=>u(this,null,function*(){h.close(),h.removeAllListeners(),yield this.sfuHandler.setupTransports(["recv"]),l.info("recv transport reconnected!"),this.activatedProducingPeerIds=new Set,b.emit(w.REFRESH_GRID,!0)}),1e3))}get socketState(){return c(this,Re).connectionState}get mediaState(){return c(this,pe).transportState}static init(t,e){return u(this,null,function*(){const{legacyMode:r=!0,meetingId:n,authToken:i,meetingTitle:s,socket:o}=e;return new Mg(t,{legacyMode:r,authToken:i,socketClient:o,roomName:n,meetingTitle:s})})}get sfuHandler(){return c(this,pe)}get rejoinRoom(){return c(this,mc)}reset(t=!0){var e,r,n,i;(r=(e=c(this,pe))==null?void 0:e.cleanupConsumers)==null||r.call(e),(i=(n=c(this,pe))==null?void 0:n.stopAllProducers)==null||i.call(n),c(this,an).clear(),this.activatedProducingPeerIds.clear(),t&&(c(this,ei).stop(),this.sfuHandler.stopAllTransports(),this.sfuHandler.reset(),T(this,ei,new Ki))}reconnectTransport(t){return u(this,null,function*(){l.info(`CFNodeClient::Room joining state: ${c(this,Nr)}`),!(!t||c(this,Nr))&&(t.direction==="send"?yield c(this,fc).call(this,t):yield c(this,gc).call(this,t))})}setupTransports(t=!1){return u(this,null,function*(){yield c(this,pe).setupTransports(["recv","send"],t)})}stopAllProducers(){return u(this,null,function*(){yield c(this,pe).stopAllProducers()})}joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=!1){ts.joinAttempted=!0,T(this,Nr,!0),this.reset(s);const a=je().ipInfo;if(a!=null&&a.loc&&!c(this,so)){const h=a.loc.split(",");T(this,so,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let d;try{return d=yield c(this,ei).push(()=>this._joinRoom(r,n,i,o,c(this,so)),"joinRoom"),d}catch(h){d={roomJoined:!1}}return d.roomJoined||b.emit(w.ROOM_NODE_FAILED),d})}_partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){const i=je().ipInfo;let s=n;if(i!=null&&i.loc&&!n){const o=i.loc.split(",");s={latitude:parseFloat(o[0]),longitude:parseFloat(o[1])}}yield fr((o,a)=>(c(this,Re).isConnected||a(new Error("socket is not connected")),o>0&&l.warn(`retrying sending join room request, count: ${o}`),this.sfuHandler.cfSocketHandler.joinRoom(e,t,r,s).catch(d=>{throw l.error("failed to send join room request, error:",{error:d}),d})),{delayTime:1e3,strategy:"exponential",maxRetryCount:K.hasFeature(X.ENABLE_CF_INFINITE_RETRIES)?1/0:3}),yield this.setupTransports(!0)})}partialJoinRoom(t,e,r=!1,n=void 0){return u(this,null,function*(){this.partialJoinRoomPromise=c(this,ei).push(()=>this._partialJoinRoom(t,e,r,n))})}_joinRoom(t,e){return u(this,arguments,function*(r,n,i={},s=!1,o=null){this.peerDisplayName=r;try{return this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,n,s,o),K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const a={userId:this.context.getValue("userId"),peerId:this.peerId,displayName:r,roomUUID:n,roomViewType:"groupCall",roomName:this.roomName,deviceInfo:ne(V({},ye.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};B.roomJoined(a),i!=null&&i.audio?B.audioOn():B.audioOff(),i!=null&&i.video?B.videoOn():B.videoOff()})),{roomJoined:yield this.completeJoinRoom()}}catch(a){return l.error("error on sending join room request",{error:a}),{roomJoined:!1}}finally{this.partialJoinRoomPromise=void 0}})}completeJoinRoom(){return u(this,null,function*(){try{const{maxPreferredStreams:t,roomState:e}=yield this.sfuHandler.cfSocketHandler.notifySelfJoinComplete();return this.roomUUID=e.roomUuid,this.maxPreferredStreams=t!=null?t:6,T(this,Nr,!1),T(this,rs,!0),this.roomJoined=!0,b.emit(w.REFRESH_GRID,!0),!0}catch(t){return l.error("error on completing join room:",{error:t}),!1}})}leaveRoom(){return u(this,null,function*(){c(this,pe).stopAllTransports(),T(this,rs,!1),ts.joinAttempted=!1;const t={closeRoom:!1};c(this,Re).sendMessagePromise(se.leaveRoom,km.toBinary(t)).then(e=>{var r;(r=Lm.fromBinary(e.payload))!=null&&r.closed||l.warn("weird state on peer closed and should not happen")}).catch(e=>{l.error("error on sending leave room request",{error:e})}),B.callEnded(),y.destruct()})}getConsumers(){return c(this,pe).consumers}activatePeers(t){return u(this,null,function*(){const e=t.map(({peerId:r,producers:n,force:i})=>{if(n.length===0)return Promise.resolve();if(i)return this.consumePeer(r,n,i);const s=[];return n.every(o=>{const a=this.sfuHandler.producerIdToConsumerIdMap.get(o.producerId);if(!a)return!1;const d=this.sfuHandler.consumers.get(a);return d&&!o.pause&&d.paused&&s.push(a),!0})?s.length>0?this.resumeConsumers(s):Promise.resolve():this.consumePeer(r,n)});yield Promise.all(e)})}deactivatePeers(t){return u(this,null,function*(){if(l.info("deactivating producers"),t.producers.some(e=>e.screenShare&&e.kind==="video")){l.debug("peer is screensharing can't deactivate");return}t.producers.forEach(({producerId:e,kind:r})=>{if(r==="audio"){l.debug("we don't want to deactive audio consumers");return}const n=this.sfuHandler.producerIdToConsumerIdMap.get(e);if(!n){l.warn(`consumer not found in deactivate producers: ${e}`);return}this.sfuHandler.closeConsumer(n)}),this.activatedProducingPeerIds.delete(t.peerId)})}createConsumer(t,e){return u(this,null,function*(){return this.sfuHandler.createConsumer({producingPeerId:t,producers:[e]})})}pauseConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.pauseConsumer(e)})})}resumeConsumers(t){return u(this,null,function*(){t.forEach(e=>{this.sfuHandler.resumeConsumer(e)})})}closeConsumers(t){return u(this,null,function*(){const e=Array.from(this.getConsumers().values()).filter(r=>t.includes(r.peerId)).map(r=>r.id);return t.forEach(r=>{this.activatedProducingPeerIds.delete(r)}),this.sfuHandler.closeConsumers(e)})}consumePeer(t,e,r){return u(this,null,function*(){if(l.info(`current activated Peer ids: ${JSON.stringify(Array.from(this.activatedProducingPeerIds.values()))}, forced?:${r}`),!this.activatedProducingPeerIds.has(t)||r)try{yield c(this,pe).createConsumer({producingPeerId:t,producers:e}),this.activatedProducingPeerIds.add(t)}catch(n){l.error("consumePeer failed in CFNodeClient.ts",{error:n})}else l.info(`not creating consumer for this peerId: ${t}`)})}shareWebcam(t){return u(this,null,function*(){if(t===void 0)return null;if(c(this,pe).producers.has(Q.WEBCAM)){const i=c(this,pe).producers.get(Q.WEBCAM);if(!i.closed&&!navigator.isReactNative)return yield i.replaceTrack({track:t}),yield this.resumeWebcam(),t;yield c(this,pe).removeProducer(Q.WEBCAM)}const e={track:t,codecOptions:{name:"VP8"},appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1};let r=t.getConstraints().width;r in qf||(r=640),e.encodings=MA[r],K.hasFeature(X.ENABLE_CF_SIMULCAST)&&(e.encodings=qf[r]);const n=()=>{l.info("Disabling video due to the producer closure"),this.disableWebcam()};return c(this,pe).createProducer(Q.WEBCAM,e,n)})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const n={track:e,codecOptions:{name:"VP8"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1};let i=()=>{l.info("Disabling screenShare due to the producer closure"),this.disableScreenShare()};if(yield c(this,pe).createProducer(Q.SCREENSHARE_VIDEO,n,i),r){const s={track:r,codecOptions:{name:"opus"},appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ye.isElectron()},stopTracks:!1,zeroRtpOnPause:!0};i=()=>{},yield c(this,pe).createProducer(Q.SCREENSHARE_AUDIO,s,i)}B.screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new it("track undefined");if(c(this,pe).producers.has(Q.MIC)){const n=c(this,pe).producers.get(Q.MIC);if(!n.closed&&!navigator.isReactNative){yield n.replaceTrack({track:t}),yield this.resumeMic();return}yield c(this,pe).removeProducer(Q.MIC,!1)}const e={track:t,encodings:[{priority:"high"}],codecOptions:{name:"opus"},appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0},r=()=>{l.info("Disabling audio due to the producer closure"),this.disableMic()};yield c(this,pe).createProducer(Q.MIC,e,r)}catch(e){throw new C(e)}})}pauseMic(){const t=c(this,pe).producers.get(Q.MIC);if(!t){l.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){l.info("pauseMic::mic_producer_already_paused");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))}pauseWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.WEBCAM);if(!t){l.error("pauseWebcam::could_not_find_webcam_producer");return}t.pause();const e={producerId:t.id,pause:!0};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}resumeMic(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.MIC);if(!t){l.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){l.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}resumeWebcam(){return u(this,null,function*(){const t=c(this,pe).producers.get(Q.WEBCAM);if(!t){l.error("resumeWebcam::could_not_find_webcam_producer");return}t.resume(),t.appData.e2ee&&b.emit(w.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};c(this,Re).sendMessage(se.toggleProducer,$r.toBinary(e))})}disableWebcam(){return u(this,null,function*(){yield c(this,pe).removeProducer(Q.WEBCAM)})}disableMic(){return u(this,null,function*(){yield c(this,pe).removeProducer(Q.MIC)})}disableScreenShare(){return u(this,null,function*(){l.info("screen_sharing_stopped"),B.screenShareStop(),yield c(this,pe).removeProducer(Q.SCREENSHARE_VIDEO),yield c(this,pe).removeProducer(Q.SCREENSHARE_AUDIO),c(this,an).clear()})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){t&&(yield c(this,pe).removeProducer(Q.WEBCAM,!1),this.shareWebcam(t)),e&&(yield c(this,pe).removeProducer(Q.SCREENSHARE_VIDEO,!1),this.shareScreen({video:e}))})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield this.sfuHandler.cfSocketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){return u(this,null,function*(){const e={participantId:t};if(!(yield this.sfuHandler.cfSocketHandler.kickPeer(e)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield this.sfuHandler.cfSocketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield c(this,Re).sendMessagePromise(se.globalPinPeer,wm.toBinary(e))}catch(r){l.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&this.sfuHandler.hasProducer(t.producerId)&&c(this,an).add(t.consumerPeerId),c(this,an).size}switchConsumersToLayer(t,e){return u(this,null,function*(){this.sfuHandler.switchConsumersToLayer(t,e)})}handleSocketEvents(){return u(this,null,function*(){c(this,Re).on(se.peerProducerCreateBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:r}=Gm.fromBinary(t);if(e===this.peerId)return;l.info(`producer created broadcast: ${e}, producer state: ${r}`),b.emit(w.NEW_PRODUCER,{peerId:e,producer:ne(V({},r),{kind:r.kind===wt.AUDIO?"audio":"video"})})}catch(e){l.error("error in peer-producer-create-broadcast",{error:e})}}),c(this,Re).on(se.peerProducerToggleBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{kind:r,pause:n,producerId:i}}=Jm.fromBinary(t),s=r===wt.AUDIO?"audio":"video";l.info(`producer toggle broadcast: ${e}, producerId: ${i}, kind:${s}, paused:${n}`),b.emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:i,paused:n,kind:s}),Array.from(this.getConsumers().values()).filter(o=>o.producerId===i).forEach(o=>{o.paused!==n&&(l.debug(`consumer state mismatched for ${o.id}. updating consumer pause state ${o.paused} to ${n}`),n?(o.pause(),b.emit(w.CONSUMER_PAUSED,{id:o.id})):(o.resume(),b.emit(w.CONSUMER_RESUMED,{id:o.id})))})}catch(e){l.error("error in producer toggle broadcast handler",{error:e})}}),c(this,Re).on(se.peerLeaveBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e}=ca.fromBinary(t);if(e===this.peerId)return;l.info(`peer left broadcast:${e}`),c(this,an).delete(e),this.sfuHandler.cleanupConsumers(e)}catch(e){l.error("error in peer left broadcast",{error:e})}}),c(this,Re).on(se.peerProducerCloseBroadcast,({payload:t})=>{if(this.roomJoined)try{const{participantId:e,producerState:{producerId:r}}=qm.fromBinary(t);if(e===this.peerId)return;l.info(`producer closed broadcast:${e}`),b.emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const n=this.sfuHandler.producerIdToConsumerIdMap.get(r);if(!n){l.warn(`no consumer found for producer:${r}`);return}l.info(`closing consumer ${n}, producer id: ${r}`),this.sfuHandler.closeConsumer(n).then(()=>{l.info(`closed consumer: ${n}`),this.sfuHandler.producerIdToConsumerIdMap.delete(r),b.emit(w.CONSUMER_CLOSED,{id:n})}).catch(i=>{l.error("error closing consumer",{error:i})})}catch(e){l.error("error on producer close broadcast",{error:e})}}),c(this,Re).on(se.mediaRoomTerminationBroadcastResponse,()=>{!this.roomJoined&&!c(this,Nr)&&!c(this,rs)||(l.warn("media hub termination broadcast received, rejoining room"),b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom())})})}handleSocketConnectionEvents(){c(this,Re).onStateEvent("connected",()=>u(this,null,function*(){l.info("SocketService::Connected to socket-edge"),clearTimeout(c(this,ti)),T(this,ti,void 0),ue(this,Lr,cn).call(this,"connected")})),c(this,Re).onStateEvent("disconnected",({code:t,reason:e})=>{l.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e}});const{consuming:r,producing:n}=this.mediaState;r.state!==st.CONNECTED||n.state!==st.CONNECTED?b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:ts.joinAttempted}):T(this,ti,setTimeout(()=>{b.emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:ts.joinAttempted}),T(this,ti,void 0)},uD)),ue(this,Lr,cn).call(this,"disconnected"),this.roomJoined=!1}),c(this,Re).onStateEvent("reconnecting",()=>u(this,null,function*(){l.info("SocketService::Reconnecting to socket-edge"),ue(this,Lr,cn).call(this,"reconnecting")})),c(this,Re).onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){l.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),ue(this,Lr,cn).call(this,"reconnectAttempt",e)})),c(this,Re).onStateEvent("reconnectFailure",({attempt:t})=>{l.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),ue(this,Lr,cn).call(this,"reconnectFailure",t)}),c(this,Re).onStateEvent("reconnected",()=>u(this,null,function*(){l.info("SocketService::Reconnected to socket-edge",{connectionState:ts}),b.emit(w.SOCKET_SERVICE_RECONNECTED),ue(this,Lr,cn).call(this,"reconnected")})),c(this,Re).onStateEvent("failed",()=>u(this,null,function*(){l.info("SocketService::Failed to connect to socket-edge"),ue(this,Lr,cn).call(this,"failed")}))}handleSFUEvents(){c(this,pe).on("reconnect_transport",t=>u(this,null,function*(){try{yield this.reconnectTransport(t),l.info(`transport reconnected [id:${t.id}]`)}catch(e){l.error("error on reconnection transports",{error:e})}})),c(this,pe).on("rejoin",t=>{if(c(this,Zn)>3&&!t){l.warn("cannot rejoin more already rejoined 3 times");return}if(c(this,Nr)&&!t){l.warn("room joining in progress, cannot start rejoining");return}T(this,Zn,c(this,Zn)+1),l.warn(`rejoining the room because transports are failing. [rejoinCount: ${c(this,Zn)}]`),this.roomJoined=!1,b.emit(w.ROOM_NODE_DISCONNECTED),this.rejoinRoom()})}handleCallstatsEvents(){B.onSafeInitialization(()=>{B.onConsumerScore(t=>{t.forEach((e,r)=>{const n=this.sfuHandler.consumers.get(r);n&&b.emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:n.kind,peerId:n.peerId,score:+(e*10).toFixed()})})}),B.onProducerScore(t=>{t.forEach((e,r)=>{const n=Array.from(this.sfuHandler.producers.values()).find(i=>i.id===r);n&&b.emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:n.kind,appData:n.appData,score:+(e*10).toFixed()})})})})}},Re=new WeakMap,pe=new WeakMap,Nr=new WeakMap,rs=new WeakMap,Zn=new WeakMap,ei=new WeakMap,mc=new WeakMap,fc=new WeakMap,gc=new WeakMap,an=new WeakMap,so=new WeakMap,ti=new WeakMap,Lr=new WeakSet,cn=function(t,e){let r;const{reconnected:n}=c(this,Re).connectionState;switch(t){case"connected":r={state:"connected",reconnected:n,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0};break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:n,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:n,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:n,reconnectionAttempt:void 0};break}r&&(c(this,Re).connectionState=r,b.emit(w.SOCKET_STATE_UPDATE,r))},Ag);let ae=Mg;le([y.trace("CFNodeClient.reset")],ae.prototype,"reset",1),le([y.trace("CFNodeClient.reconnect")],ae.prototype,"reconnectTransport",1),le([y.trace("CFNodeClient.setupTransport")],ae.prototype,"setupTransports",1),le([y.trace("CFNodeClient.stopAllProducers")],ae.prototype,"stopAllProducers",1),le([y.trace("CFNodeClient.joinRoom")],ae.prototype,"joinRoom",1),le([y.trace("CFNodeClient.completeJoinRoom")],ae.prototype,"completeJoinRoom",1),le([y.trace("CFNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),le([y.trace("CFNodeClient.activatePeers")],ae.prototype,"activatePeers",1),le([y.trace("CFNodeClient.deactivatePeers")],ae.prototype,"deactivatePeers",1),le([y.trace("CFNodeClient.createConsumer")],ae.prototype,"createConsumer",1),le([y.trace("CFNodeClient.pauseConsumers")],ae.prototype,"pauseConsumers",1),le([y.trace("CFNodeClient.resumeConsumers")],ae.prototype,"resumeConsumers",1),le([y.trace("CFNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),le([y.trace("CFNodeClient.consumePeer")],ae.prototype,"consumePeer",1),le([y.trace("CFNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),le([y.trace("CFNodeClient.shareScreen")],ae.prototype,"shareScreen",1),le([y.trace("CFNodeClient.shareMic")],ae.prototype,"shareMic",1),le([y.trace("CFNodeClient.pauseMic")],ae.prototype,"pauseMic",1),le([y.trace("CFNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),le([y.trace("CFNodeClient.resumeMic")],ae.prototype,"resumeMic",1),le([y.trace("CFNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),le([y.trace("CFNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),le([y.trace("CFClient.disableMic")],ae.prototype,"disableMic",1),le([y.trace("CFClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),le([y.trace("CFNodeClient.muteSelf")],ae.prototype,"muteSelf",1),le([y.trace("CFNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),le([y.trace("CFNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),le([y.trace("CFNodeClient.kickPeer")],ae.prototype,"kick",1),le([y.trace("CFNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),le([y.trace("CFNodeClient.muteAll")],ae.prototype,"muteAll",1),le([y.trace("CFNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),le([y.trace("CFNodeClient.disableAudio")],ae.prototype,"disableAudio",1),le([y.trace("CFNodeClient.disableVideo")],ae.prototype,"disableVideo",1),le([y.trace("CFNodeClient.pinPeer")],ae.prototype,"pinPeer",1),le([y.trace("CFNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1),le([y.trace("CFNodeClient.init")],ae,"init",1);function hD(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof oe)return r;throw new Error("Room Node Client already setup")}const n=yield oe.init(t,e);return t.setValue("roomNodeClient",n),n})}function pD(t,e){return u(this,null,function*(){const r=t.getValue("roomNodeClient");if(r){if(r instanceof ae)return r;throw new Error("Room Node Client already setup")}const n=yield ae.init(t,e);return t.setValue("roomNodeClient",n),n})}function Dg(t,e){return u(this,arguments,function*(r,n,i=Qi.HIVE){return i===Qi.CF?pD(r,n):hD(r,n)})}function Og(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(r){l.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var mD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,gD=(t,e,r,n)=>{for(var i=n>1?void 0:n?fD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&mD(e,r,i),i};let ns;const Ng=class{constructor(t){m(this,"socket"),this.socket=t,this.handleSocketEvents()}static create(t){return ns||(ns=new Ng(t)),ns}static cleanup(){var t;try{(t=ns==null?void 0:ns.socket)==null||t.disconnect()}catch(e){l.error("roomSocketHandler::cleanup")}ns=void 0}joinRoom(t,e,r,n){return u(this,null,function*(){const i={capabilities:[],peer:{displayName:t!=null?t:"Participant",peerId:e,userId:r,waitlisted:!1},roomUuid:""},s=this.socket.sendMessagePromise(j.joinRoom,$0.toBinary(i));try{const{peer:o}=wi.fromBinary((yield s).payload);b.emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:o});const a=this.getRoomState();let d=()=>new Promise(f=>{f({peers:[]})});n!==We.Livestream&&(d=this.getRoomPeersNonPaginated()),n===We.Livestream&&o.stageType===1&&(d=this.getStagePeers());const[{room:h},{peers:p}]=yield Promise.all([a,d]);return b.emit(w.ROOM_STATE,h),b.emit(w.SOCKET_PEERS,p),{peer:o}}catch(o){throw l.error("RoomSocketHandler.joinRoom.failed",{error:o}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",o)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return RC.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:r}=e,n=Ro(e,["id"]);return ne(V({},n),{userId:r})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let n;try{const i={seachQuery:t,limit:e,offset:r},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,N0.toBinary(i));n=Jd.fromBinary(s.payload)}catch(i){l.error("getRoomPeers::binary_decode_error",{error:i})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jd.fromBinary(e.payload)}catch(e){l.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(j.getPeerInfo,Zm.toBinary({peerId:t}));e=wi.fromBinary(r.payload)}catch(r){l.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Xm.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=Xm.fromBinary(e.payload)}catch(e){l.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=sf.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=sf.fromBinary(e.payload)}catch(e){l.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),peerIds:[]};return this.socket.sendMessagePromise(j.broadcastMessage,ha.toBinary(r))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),peerIds:e};return this.socket.sendMessage(j.broadcastToPeers,ha.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.sendMessagePromise(j.leaveRoom,J0.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,DC.toBinary(e))})}kickAll(){return u(this,null,function*(){this.socket.sendMessage(j.kickAll)})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,LC.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,FC.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(n=>{r.updatePeersPresets.push({userIds:n,patch:e})}),this.socket.sendMessagePromise(va.updateUserPreset,hI.toBinary(r))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=ha.fromBinary(t);b.emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToPeers,({payload:t})=>{try{const e=ha.fromBinary(t);b.emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){l.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,n;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{r=wi.fromBinary.bind(wi),n=wi.create();break}case j.getWaitingRoomRequests:{r=(i,s)=>i?nf.fromBinary(i,s):{requests:[]},n=nf.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{r=vf.fromBinary.bind(vf);break}case va.updateUserPreset:{r=af.fromBinary.bind(af);break}case se.peerJoinedBroadcast:case ie.peerJoinedBroadcast:{r=$m.fromBinary.bind($m);break}case se.selfJoinComplete:case ie.selfJoinComplete:{r=aa.fromBinary.bind(aa);break}case se.globalPeerPinBroadcast:case ie.globalPeerPinBroadcast:{r=Km.fromBinary.bind(Km);break}case se.selectedPeer:case ie.selectedPeer:{r=Wd.fromBinary.bind(Wd);break}case se.selectedPeerDiff:case ie.selectedPeerDiff:{r=Nm.fromBinary.bind(Nm);break}case se.leaveRoom:case ie.leaveRoom:{r=ca.fromBinary.bind(ca);break}}this.socket.on(t,({payload:i})=>{let s=n;if(!r)return e(void 0);try{s=r(i)}catch(o){l.error("roomSocketHandler::on::binary_decode_error",{error:o})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(va.getUserPresets,sI.toBinary(e)),n=dI.fromBinary(r.payload).peerPresets[0],i=new TextDecoder().decode(n.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(r){throw l.error("Error in getting user preset",{error:r}),r}})}};let vc=Ng;gD([y.trace("RoomSocketHandler.joinRoom")],vc.prototype,"joinRoom",1);var vD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,is=(t,e,r,n)=>{for(var i=n>1?void 0:n?yD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&vD(e,r,i),i},ri,nr,kt,Ft,$t,Lg;const xg=(Lg=class{constructor(t,e,r,n){_(this,Ft),m(this,"self"),m(this,"authToken"),_(this,ri,void 0),m(this,"viewType"),_(this,nr,void 0),_(this,kt,void 0);const{socket:i}=r,s=t.getValue("authToken");this.self=e,T(this,kt,t),this.viewType=n,this.authToken=s,T(this,ri,i),T(this,nr,r),e.config.viewType!==We.Chat&&this.setupEvents()}get peerId(){return c(this,kt).getValue("peerId")}static init(t,e,r,n,i){return u(this,null,function*(){const s=je(),o=t.getValue("peerId"),a=!!t.getValue("cachedUserDetails"),d=yield ot.__init__(t,r,n,i,i.name,a);if(K.hasFeature(X.INTERNAL_CALL_STATS)&&navigator.product!=="ReactNative"){const h=!K.hasFeature(X.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),B.onSafeInitialization(()=>u(this,null,function*(){B.devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),B.devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),B.devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput"))})),B.initialize({peerId:o,engineName:ye.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:K.getAllFlags(),logger:l,apiHostnames:mm(t),skipConnectivityChecks:h})}))}return new xg(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:n,audioEnabled:i,videoEnabled:s,screenShareEnabled:o,screenShareTracks:a}=this.self;if(n.canProduceAudio&&i)try{yield c(this,Ft,$t).shareMic(e)}catch(d){this.self.disableAudio()}if(n.canProduceVideo&&s)try{const d=yield c(this,Ft,$t).shareWebcam(r);d&&d.id!==r.id&&K.hasFeature(X.EXP_RESHARE)&&(yield c(this,Ft,$t).shareWebcam(d))}catch(d){this.self.disableVideo()}if(n.canProduceScreenshare&&o)try{yield(t=c(this,Ft,$t))==null?void 0:t.shareScreen({video:a.video,audio:a.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(){l.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(l.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){l.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(l.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){l.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){if(B.callEnded(),!t){c(this,Ft,$t).reset();return}yield this.joinRoom(t)})}setupEvents(){b.on(w.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.self.roomJoined&&this.shareMediaTracks()})),b.on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),b.on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),b.on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),b.on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{this.self.roomState="init",this.resetSelf(t)}),b.on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;(t||this.self.waitlistStatus==="waiting")&&K.hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(e=gn()),c(this,ri).updateURL(e),y.resetPeerId(e),je().setHeader("dyte-tracing-id",e),Ts.remapContext(e,c(this,kt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),b.on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),c(this,nr).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),c(this,nr).on(va.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&b.emit(w.UPDATE_PERMISSIONS,e.patch)})}),c(this,nr).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),c(this,nr).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),c(this,nr).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),b.onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),b.on(w.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r})=>{var n;const i=e==="video"&&((n=r==null?void 0:r.screenShare)!=null?n:!1);this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:i,score:t,participantId:this.self.id})}),b.on(w.MUTE_ALL,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),B.audioOff())})),b.on(w.MUTE_ALL_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),B.videoOff())})),b.onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),b.on(w.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield c(this,nr).joinRoom(this.self.name,this.self.id,this.self.userId,this.self.config.viewType);c(this,nr).socket.flush();const r=Pa(e.stageType);if(c(this,kt).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),c(this,kt).notify("stageStatus")}catch(e){throw l.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(t==="rejected"){try{(e=c(this,ri))==null||e.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),yield c(this,nr).leaveRoom(),c(this,kt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),c(this,kt).notify("stageStatus");try{(r=c(this,ri))==null||r.disconnect()}catch(n){l.error("SelfController::leaveRoom::socketDisconnect")}Og(c(this,kt)),vc.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}partialMediaRoom(){var t;(t=c(this,Ft,$t))==null||t.partialJoinRoom(this.self.name,c(this,kt).getValue("meetingId"),void 0)}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:n,viewType:i,meetingId:s,authToken:o,stageStatus:a,roomNodeOptions:d}=c(this,kt).getAllValues(),{sfu:h,roomNodeUrl:p,meetingTitle:f}=d;try{if(i===We.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}yield Dg(c(this,kt),{socket:c(this,ri),peerId:n,meetingId:s,authToken:o,roomNodeUrl:p,meetingTitle:f},h)}const{roomJoined:g}=(r=yield(e=c(this,Ft,$t))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?r:{};if(!g)return;a==="ON_STAGE"&&this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(g){throw l.error("Error:SelfController.mediaRoomJoin",g),new C("Error: could not join media room",g)}})}leaveMediaRoom(t){return u(this,null,function*(){const e=c(this,kt).getValue("viewType");yield this.cleanupSelf(),!(t==="stageLeft"&&e===We.Webinar)&&c(this,Ft,$t)&&(c(this,Ft,$t).roomJoined&&t!=="disconnected"&&(yield c(this,Ft,$t).leaveRoom()),!(t==="stageLeft"&&e===We.Livestream)&&(this.self.roomState="init",c(this,Ft,$t).roomJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},ri=new WeakMap,nr=new WeakMap,kt=new WeakMap,Ft=new WeakSet,$t=function(){return c(this,kt).getValue("roomNodeClient")},Lg);let ni=xg;is([y.trace("SelfController.resetSelf")],ni.prototype,"resetSelf",1),is([y.trace("SelfController.setupEvents")],ni.prototype,"setupEvents",1),is([y.trace("SelfController.joinRoom")],ni.prototype,"joinRoom",1),is([y.trace("SelfController.leaveRoom")],ni.prototype,"leaveRoom",1),is([y.trace("SelfController.joinMediaRoom")],ni.prototype,"joinMediaRoom",1),is([y.trace("SelfController.leaveMediaRoom")],ni.prototype,"leaveMediaRoom",1);var yc;class ED{constructor(e){_(this,yc,void 0),T(this,yc,e)}on(e,r){let n;e===j.roomPeerCount?n=Ym.fromBinary.bind(Ym):n=pf.fromBinary.bind(pf),c(this,yc).on(e,({payload:i})=>{const s=n(i);return r(s)})}}yc=new WeakMap;var Ec;class SD{constructor(e){_(this,Ec,void 0),T(this,Ec,e)}on(e,r){let n,i;switch(e){case j.transcript:{n=$d.fromBinary.bind($d),i=$d.create();break}default:{l.debug("AISocketHandler switch case hit default, event not accounted for.");break}}c(this,Ec).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("chatSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}Ec=new WeakMap;var TD=Object.defineProperty,kD=Object.getOwnPropertyDescriptor,Jl=(t,e,r,n)=>{for(var i=n>1?void 0:n?kD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&TD(e,r,i),i},ii;class Sc{constructor(e){_(this,ii,void 0),T(this,ii,e)}getPolls(){return c(this,ii).sendMessagePromise(_r.getPolls)}createPoll(e,r,n=!1,i=!1){const s={anonymous:n,hideVotes:i,question:e,options:r};return c(this,ii).sendMessage(_r.createPoll,iP.toBinary(s))}votePoll(e,r){const n={index:r,pollId:e};return c(this,ii).sendMessage(_r.votePoll,oP.toBinary(n))}on(e,r){let n,i;switch(e){case _r.updatePoll:case _r.createPoll:case _r.votePoll:{n=rl.fromBinary.bind(rl),i=rl.create();break}}c(this,ii).on(e,({payload:s})=>{let o=i;try{o=n(s)}catch(a){l.error("pollSocketHandler::on::binary_decode_error",{error:a})}return r(o)})}}ii=new WeakMap,Jl([y.trace("PollSocketHandler.getPolls")],Sc.prototype,"getPolls",1),Jl([y.trace("PollSocketHandler.createPoll")],Sc.prototype,"createPoll",1),Jl([y.trace("PollSocketHandler.votePoll")],Sc.prototype,"votePoll",1);var Ut;class _D{constructor(e){_(this,Ut,void 0),T(this,Ut,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield c(this,Ut).sendMessagePromise(j.getStageRequests);return e?tl.fromBinary(e):{stageRequests:[]}})}requestAccess(){c(this,Ut).sendMessage(j.requestStageAccess)}cancelRequestAccess(){c(this,Ut).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ut).sendMessage(j.grantStageAccess,KR.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};c(this,Ut).sendMessage(j.denyStageAccess,YR.toBinary(r))})}joinStage(){return c(this,Ut).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return c(this,Ut).sendMessagePromise(j.leaveStage,ff.toBinary(r),void 0,j.peerStageStatusUpdate)}kick(e){const r={userIds:e};return c(this,Ut).sendMessagePromise(j.leaveStage,ff.toBinary(r))}on(e,r){let n;switch(e){case j.grantStageAccess:case j.denyStageAccess:{n=void 0;break}case j.getStagePeers:{n=mf.fromBinary.bind(mf);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{n=tl.fromBinary.bind(tl);break}case j.peerStageStatusUpdate:{n=zm.fromBinary.bind(zm);break}}c(this,Ut).on(e,({payload:i,id:s})=>{if(!i||!n)return r(void 0,s);const o=n(i);return r(o,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield c(this,Ut).sendMessagePromise(j.getPeerInfo,Zm.toBinary({peerId:e}));return wi.fromBinary(r.payload)})}}Ut=new WeakMap;var tt;class bD{constructor(e){_(this,tt,void 0),T(this,tt,e)}addPlugin(e,r){c(this,tt).sendMessage(J.addPlugin,uR.toBinary({pluginId:e,staggered:r}))}removePlugin(e){c(this,tt).sendMessage(J.removePlugin,pR.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield c(this,tt).sendMessagePromise(J.getPlugins);return e?xR.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,n){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};c(this,tt).sendMessage(J.customPluginEventToRoom,_R.toBinary(i),n)}customPluginEventToPeers(e,r,n,i){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(n))};c(this,tt).sendMessage(J.customPluginEventToPeers,wR.toBinary(s),i)}enablePluginForRoom(e,r){c(this,tt).sendMessage(J.enablePluginForRoom,fR.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.enablePluginForPeers,ER.toBinary({pluginId:e,peerIds:r}),n)}disablePluginForRoom(e,r){c(this,tt).sendMessage(J.disablePluginForRoom,vR.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,n){c(this,tt).sendMessage(J.disablePluginForPeers,TR.toBinary({pluginId:e,peerIds:r}),n)}storeInsertKeys(e,r,n,i){const s={pluginId:e,storeName:r,insertKeys:n.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};c(this,tt).sendMessage(J.storeInsertKeys,df.toBinary(s),i)}storeGetKeys(e,r,n,i){const s={pluginId:e,storeName:r,getKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeGetKeys,PR.toBinary(s),i)}storeDeleteKeys(e,r,n,i){const s={pluginId:e,storeName:r,deleteKeys:n.map(o=>({storeKey:o.key}))};c(this,tt).sendMessage(J.storeDeleteKeys,MR.toBinary(s),i)}storeDelete(e,r,n){c(this,tt).sendMessage(J.storeDelete,OR.toBinary({pluginId:e,storeName:r}),n)}getPluginDataOld(e,r){l.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,n){const i={pluginId:e,storeName:r,insertKeys:[{storeKey:n.key,payload:new TextEncoder().encode(JSON.stringify(n))}]};c(this,tt).sendMessage(J.storeInsertKeys,df.toBinary(i))}on(e,r){let n;switch(e){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{n=el.fromBinary.bind(el);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{n=lf.fromBinary.bind(lf);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{n=hf.fromBinary.bind(hf);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{n=uf.fromBinary.bind(uf);break}}c(this,tt).on(e,({payload:i,id:s})=>{const o=n(i);return r(o,s)})}}tt=new WeakMap;var wD=Object.defineProperty,CD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ID=(t,e,r)=>(CD(t,typeof e!="symbol"?e+"":e,r),r),ql=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},O=(t,e,r)=>(ql(t,e,"read from private field"),r?r.call(t):e.get(t)),Pe=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},ge=(t,e,r,n)=>(ql(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),Ae=(t,e,r)=>(ql(t,e,"access private method"),r),dn,si,oi,Ue,ai,Me,He,ln,rt,xr,un,ir,ss,Fr,Kl,Fg,oo,Tc,zl,Ug,Yl,Vg,kc,Ql,Xl,Bg,ao,_c,co,bc,wc,Zl,os,lo,uo,Cc,eu={exports:{}},as=typeof Reflect=="object"?Reflect:null,jg=as&&typeof as.apply=="function"?as.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Ic;as&&typeof as.ownKeys=="function"?Ic=as.ownKeys:Object.getOwnPropertySymbols?Ic=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Ic=function(t){return Object.getOwnPropertyNames(t)};function RD(t){console&&console.warn&&console.warn(t)}var Hg=Number.isNaN||function(t){return t!==t};function Ee(){Ee.init.call(this)}eu.exports=Ee,eu.exports.once=DD,Ee.EventEmitter=Ee,Ee.prototype._events=void 0,Ee.prototype._eventsCount=0,Ee.prototype._maxListeners=void 0;var Wg=10;function Rc(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ee,"defaultMaxListeners",{enumerable:!0,get:function(){return Wg},set:function(t){if(typeof t!="number"||t<0||Hg(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wg=t}}),Ee.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},Ee.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Hg(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 $g(t){return t._maxListeners===void 0?Ee.defaultMaxListeners:t._maxListeners}Ee.prototype.getMaxListeners=function(){return $g(this)},Ee.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var n=t==="error",i=this._events;if(i!==void 0)n=n&&i.error===void 0;else if(!n)return!1;if(n){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var a=i[t];if(a===void 0)return!1;if(typeof a=="function")jg(a,this,e);else for(var d=a.length,h=zg(a,d),r=0;r<d;++r)jg(h[r],this,e);return!0};function Gg(t,e,r,n){var i,s,o;if(Rc(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=$g(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,RD(a)}return t}Ee.prototype.addListener=function(t,e){return Gg(this,t,e,!1)},Ee.prototype.on=Ee.prototype.addListener,Ee.prototype.prependListener=function(t,e){return Gg(this,t,e,!0)};function PD(){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 Jg(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=PD.bind(n);return i.listener=r,n.wrapFn=i,i}Ee.prototype.once=function(t,e){return Rc(e),this.on(t,Jg(this,t,e)),this},Ee.prototype.prependOnceListener=function(t,e){return Rc(e),this.prependListener(t,Jg(this,t,e)),this},Ee.prototype.removeListener=function(t,e){var r,n,i,s,o;if(Rc(e),n=this._events,n===void 0)return this;if(r=n[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete n[t],n.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(i=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,i=s;break}if(i<0)return this;i===0?r.shift():AD(r,i),r.length===1&&(n[t]=r[0]),n.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this},Ee.prototype.off=Ee.prototype.removeListener,Ee.prototype.removeAllListeners=function(t){var e,r,n;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var i=Object.keys(r),s;for(n=0;n<i.length;++n)s=i[n],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(n=e.length-1;n>=0;n--)this.removeListener(t,e[n]);return this};function qg(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?MD(i):zg(i,i.length)}Ee.prototype.listeners=function(t){return qg(this,t,!0)},Ee.prototype.rawListeners=function(t){return qg(this,t,!1)},Ee.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Kg.call(t,e)},Ee.prototype.listenerCount=Kg;function Kg(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ee.prototype.eventNames=function(){return this._eventsCount>0?Ic(this._events):[]};function zg(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function AD(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function MD(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function DD(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Yg(t,e,s,{once:!0}),e!=="error"&&OD(t,i,{once:!0})})}function OD(t,e,r){typeof t.on=="function"&&Yg(t,"error",e,r)}function Yg(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var ND=eu.exports;class LD extends k{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 Qg=new LD;class Xg{static encode(e){return Qg.toBinary(e)}static decode(e){return Qg.fromBinary(new Uint8Array(e))}}function xD(t,e){return Math.floor(Math.random()*(e-t+1)+t)}class FD{constructor(e={}){ID(this,"opts"),Pe(this,dn,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},ge(this,dn,0)}wait(){return u(this,null,function*(){ge(this,dn,O(this,dn)+1);const e=xD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*dy(2,O(this,dn))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return O(this,dn)}reset(){ge(this,dn,0)}}dn=new WeakMap;const hn={debug:0,info:1,warn:2,error:3};class UD{constructor(e){Pe(this,si,void 0),Pe(this,oi,void 0),ge(this,si,console),ge(this,oi,e)}debug(...e){hn[O(this,oi)]>hn.debug||O(this,si).debug("[Sockrates]:",...e)}info(...e){hn[O(this,oi)]>hn.info||O(this,si).info("[Sockrates]:",...e)}warn(...e){hn[O(this,oi)]>hn.warn||O(this,si).warn("[Sockrates]:",...e)}error(...e){hn[O(this,oi)]>hn.error||O(this,si).error("[Sockrates]:",...e)}}si=new WeakMap,oi=new WeakMap;var Zg=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Zg||{});const VD="2",BD="3";class jD{constructor(e,r){Pe(this,Kl),Pe(this,oo),Pe(this,zl),Pe(this,Yl),Pe(this,kc),Pe(this,Xl),Pe(this,ao),Pe(this,co),Pe(this,wc),Pe(this,os),Pe(this,uo),Pe(this,Ue,void 0),Pe(this,ai,void 0),Pe(this,Me,void 0),Pe(this,He,void 0),Pe(this,ln,void 0),Pe(this,rt,void 0),Pe(this,xr,void 0),Pe(this,un,void 0),Pe(this,ir,void 0),Pe(this,ss,void 0),Pe(this,Fr,void 0);var n,i,s,o,a,d,h,p,f,g;ge(this,ai,e),ge(this,ln,[]),ge(this,rt,new ND),ge(this,xr,!0),ge(this,ir,!1),ge(this,Me,r!=null?r:{}),(n=O(this,Me)).autoReconnect!=null||(n.autoReconnect=!0),(i=O(this,Me)).retryConnectionInterval!=null||(i.retryConnectionInterval=1e3),(s=O(this,Me)).pingTimeout!=null||(s.pingTimeout=3e4),(o=O(this,Me)).connectionTimeout!=null||(o.connectionTimeout=5e3),(a=O(this,Me)).debug!=null||(a.debug=!0),(d=O(this,Me)).maxReconnectionAttempts!=null||(d.maxReconnectionAttempts=10),(h=O(this,Me)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=O(this,Me)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(f=O(this,Me)).flushOnReconnect!=null||(f.flushOnReconnect=!1),ge(this,un,{code:void 0,reason:void 0}),ge(this,He,(g=O(this,Me).logger)!=null?g:new UD(O(this,Me).debug?"debug":"info")),ge(this,Fr,new FD)}get readyState(){var e;return(e=O(this,Ue))==null?void 0:e.readyState}get url(){return O(this,ai)}updateURL(e){ge(this,ai,e),Ae(this,Xl,Bg).call(this)}get config(){return O(this,Me)}get sendQueue(){return O(this,ln)}flush(){if(!O(this,Me).queueOnDisconnect)return!1;const e=[];return O(this,ln).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),ge(this,ln,e),O(this,ln)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){O(this,He).debug("Websocket was already connecting or connected.");return}if(O(this,xr)!==!1)return new Promise((r,n)=>{Ae(this,os,lo).call(this),Ae(this,uo,Cc).call(this);try{ge(this,Ue,new WebSocket(Ae(this,Kl,Fg).call(this,O(this,ai)))),O(this,Ue).binaryType="arraybuffer",O(this,He).debug("Connecting to",O(this,ai));const i=setTimeout(()=>{O(this,He).debug("Connection timeout. Closing socket"),ge(this,xr,!0),Ae(this,uo,Cc).call(this),O(this,Ue).close(3001,"Connection Timeout"),O(this,Me).autoReconnect&&!O(this,ir)&&(O(this,rt).emit("reconnecting"),Ae(this,ao,_c).call(this)),n(new Error("Connection timed out!"))},O(this,Me).connectionTimeout);O(this,Ue).onopen=()=>{O(this,He).debug(`Ready State: ${Zg[O(this,Ue).readyState]}`),i&&clearTimeout(i),Ae(this,wc,Zl).call(this),ge(this,un,{code:void 0,reason:void 0}),O(this,rt).emit("connected"),O(this,Me).flushOnReconnect&&this.flush(),r()},O(this,Ue).onclose=s=>{try{i&&clearTimeout(i);const{code:o,reason:a}=s;n(a),O(this,He).debug("Socket closed. Close event:",s),O(this,He).debug("Connection closed code:",o),O(this,He).debug("Connection closed reason:",a),O(this,ir)||Ae(this,kc,Ql).call(this,o,a)}catch(o){Ae(this,oo,Tc).call(this,o)}},O(this,Ue).onerror=s=>{Ae(this,oo,Tc).call(this,s)},O(this,Ue).onmessage=s=>Ae(this,zl,Ug).call(this,s)}catch(i){Ae(this,oo,Tc).call(this,i,n)}})})}send(e,r,n,i){const s={event:e,id:r,payload:n,metadata:i};if(O(this,Me).queueOnDisconnect&&(!O(this,Ue)||O(this,Ue).readyState!==1))return O(this,He).debug("Queuing message since socket is not connected!",s),O(this,ln).push(s),!1;const o=Xg.encode(s);return Ae(this,co,bc).call(this,o)}emit(e,r,n,i){return this.send(e,r,n,i)}sendRaw(e){return Ae(this,co,bc).call(this,e)}receive(e,r){return O(this,rt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){O(this,rt).on(e,r);return}this.receive(e,r)}removeAllListeners(){O(this,rt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){O(this,rt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){O(this,rt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){ge(this,xr,!1),Ae(this,os,lo).call(this),this.removeAllListeners(),ge(this,un,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ue).close(1e3,"Sockrates disconnect method called.")}}Ue=new WeakMap,ai=new WeakMap,Me=new WeakMap,He=new WeakMap,ln=new WeakMap,rt=new WeakMap,xr=new WeakMap,un=new WeakMap,ir=new WeakMap,ss=new WeakMap,Fr=new WeakMap,Kl=new WeakSet,Fg=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)://.")},oo=new WeakSet,Tc=function(t,e){O(this,He).error("Error:",{error:t}),O(this,rt).emit("errored",{error:t}),e==null||e(t)},zl=new WeakSet,Ug=function(t){if(Ae(this,wc,Zl).call(this),t.data===VD){O(this,He).debug("Received ping from server"),Ae(this,co,bc).call(this,BD);return}O(this,He).debug("Received data:",t.data);const e=Xg.decode(t.data),{id:r,payload:n}=e;O(this,rt).emit(e.event.toString(),{id:r,payload:n})},Yl=new WeakSet,Vg=function(){return O(this,Ue).readyState===1},kc=new WeakSet,Ql=function(t,e){ge(this,un,{reason:e,code:t}),O(this,rt).emit("disconnected",{code:t,reason:e})},Xl=new WeakSet,Bg=function(){const{reason:t,code:e}=O(this,un);e&&e!==1e3&&O(this,xr)&&O(this,Me).autoReconnect&&!O(this,ir)&&(O(this,He).debug(`Triggering reconnection due to ${t}.`),O(this,rt).emit("reconnecting"),Ae(this,ao,_c).call(this))},ao=new WeakSet,_c=function(t=!0){return u(this,null,function*(){if(t&&O(this,ir)){O(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,ir)||O(this,Fr).reset(),O(this,Me).maxReconnectionAttempts!==null&&O(this,Fr).getAttempts()>=O(this,Me).maxReconnectionAttempts){O(this,rt).emit("failed"),ge(this,ir,!1);return}ge(this,ir,!0),Ae(this,uo,Cc).call(this),Ae(this,os,lo).call(this);try{if(yield O(this,Fr).wait(),O(this,xr)===!1)return;if(O(this,He).debug(`Reconnection attempt ${O(this,Fr).getAttempts()}`),O(this,rt).emit("reconnectAttempt",{attempt:O(this,Fr).getAttempts()}),yield this.connect(),!Ae(this,Yl,Vg).call(this))throw Error("Reconnect Failed");ge(this,ir,!1),ge(this,un,{code:void 0,reason:void 0}),O(this,rt).emit("reconnected")}catch(e){O(this,He).debug("Failed to reconnect."),O(this,rt).emit("reconnectFailure",{attempt:O(this,Fr).getAttempts()}),Ae(this,ao,_c).call(this,!1)}})},co=new WeakSet,bc=function(t){try{return O(this,Ue).send(t),!0}catch(e){return O(this,He).error(e.message),!1}},wc=new WeakSet,Zl=function(){this.config.disconnectOnPingTimeout&&(O(this,He).debug("Resetting ping timeout"),Ae(this,os,lo).call(this),ge(this,ss,setTimeout(()=>{var t;O(this,He).debug("Disconnecting the socket due to ping timeout"),ge(this,xr,!0);const e=3002,r="Ping timeout";(t=O(this,Ue))==null||t.close(e,r),Ae(this,kc,Ql).call(this,e,r)},O(this,Me).pingTimeout)))},os=new WeakSet,lo=function(){O(this,ss)&&(clearTimeout(O(this,ss)),ge(this,ss,void 0))},uo=new WeakSet,Cc=function(){O(this,Ue)&&(O(this,Ue).onopen=void 0,O(this,Ue).onerror=void 0,O(this,Ue).onmessage=void 0,O(this,Ue).onclose=void 0)};var HD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Pc=(t,e,r,n)=>{for(var i=n>1?void 0:n?WD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&HD(e,r,i),i};const ev=65535;var ci,Je,di,Ac,tu,Mc,ru,tv;const rv=(tv=class{constructor(t,{peerId:e,meetingId:r,authToken:n,capabilities:i}){_(this,Ac),_(this,Mc),_(this,ci,void 0),_(this,Je,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),m(this,"connectionState"),_(this,di,void 0);var s;if(!e||!r||!n)throw new C("peerId, roomName, or authToken can not be empty");T(this,di,t),this.capabilities=i,this.roomName=r,this.authToken=n,this.connectionState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},T(this,ci,ue(this,Ac,tu).call(this,e)),T(this,Je,new jD(c(this,ci),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:l}))}get peerId(){return c(this,di).getValue("peerId")}updateURL(t){t!==this.peerId&&(T(this,ci,ue(this,Ac,tu).call(this,t)),l.debug("SocketService:: Connection URL updated.")),c(this,Je).updateURL(c(this,ci))}static getSocketEdgeDomain(t){return bi({servicePrefix:"socket-edge",baseURI:t})}get url(){return c(this,ci)}connect(){return u(this,null,function*(){yield c(this,Je).connect()})}disconnect(){return c(this,Je).disconnect()}get isConnected(){try{return c(this,Je).readyState===1}catch(t){return!1}}sendMessage(t,e,r){const n={};return y.injectContext(n),c(this,Je).send(t,r!=null?r:ue(this,Mc,ru).call(this),e,new TextEncoder().encode(JSON.stringify(n)))}sendMessagePromise(t,e,r,n){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:r,resp:n})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:n,resp:i}){const s=i!=null?i:t;return new Promise((o,a)=>{const d=(E,v)=>{c(this,Je).removeListener(s,E),c(this,Je).removeListener(ev,v),c(this,Je).removeListener(ie.errorResponse,v),c(this,Je).removeListener(se.errorResponse,v)},h=n!=null?n:ue(this,Mc,ru).call(this),p={};y.injectContext(p);const f=({id:E,payload:v})=>{if(h===E){let R;try{const A=Vw.fromBinary(v);R=new Error(A.errorMessage)}catch(A){R=new Error("failed to parse error message",{cause:A});try{const L=I0.fromBinary(v);R=new Error(L.message)}catch(L){R=new Error("failed to parse error message",{cause:L})}}a(R),d(g,f)}},g=({id:E,payload:v})=>{h===E&&(o({id:E,payload:v}),d(g,f))};c(this,Je).on(s,g),c(this,Je).on(ev,f),c(this,Je).on(ie.errorResponse,f),c(this,Je).on(se.errorResponse,f),setTimeout(()=>{d(g,f),a(new Error(`request timeout for callback eventId:${t}`))},e),c(this,Je).send(t,h,r,new TextEncoder().encode(JSON.stringify(p)))})}on(t,e){c(this,Je).on(t,e)}onStateEvent(t,e){c(this,Je).on(t,e)}flush(){return c(this,Je).flush()}},ci=new WeakMap,Je=new WeakMap,di=new WeakMap,Ac=new WeakSet,tu=function(t){let e=rv.getSocketEdgeDomain(c(this,di).getValue("baseURI"));typeof pm(c(this,di),"socket_server_base")=="string"&&(e=pm(c(this,di),"socket_server_base"));const r=`wss://${e}`,n=new URL(`${r}/ws`),i=this.peerId,s=ne(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>la[o]).join(" ")});return Object.entries(s).forEach(([o,a])=>{n.searchParams.append(o,a.toString())}),n.href},Mc=new WeakSet,ru=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},tv);let ho=rv;Pc([y.trace("SocketService.connect")],ho.prototype,"connect",1),Pc([y.trace("SocketService.disconnect")],ho.prototype,"disconnect",1),Pc([y.trace("SocketService.sendMessagePromise")],ho.prototype,"sendMessagePromise",1),Pc([y.trace("SocketService.sendMessagePromiseWithTimeout")],ho.prototype,"sendMessagePromiseWithTimeout",1);const li=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const r=eC.fromBinary(t),n=r.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:r.parentMeeting.id,title:r.parentMeeting.title,participants:(e=r.parentMeeting.participants)!=null?e:[]},meetings:n}}static handleTransferPeerRaw({payload:t}){const e=CC.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=rf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return tf.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return gC.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield li.socketService.sendMessagePromise(j.getConnectedRoomsDump);return li.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield li.socketService.sendMessagePromise(j.createConnectedRooms,iC.toBinary({payloads:t}));return tf.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(n=>({id:n})),r=yield li.socketService.sendMessagePromise(j.deleteConnectedRooms,mC.toBinary({payloads:e}));return li.handleConnectedRoomsDeletedRaw(r)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield li.socketService.sendMessagePromise(j.movePeers,kC.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 Ne=li;m(Ne,"socketService"),m(Ne,"currentMeetingId");var $D=Object.defineProperty,GD=Object.getOwnPropertyDescriptor,Dc=(t,e,r,n)=>{for(var i=n>1?void 0:n?GD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&$D(e,r,i),i};const ui=class{constructor(t,e){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){const{peerId:e,apiBase:r,authToken:n,meetingId:i,organizationId:s,cachedUserDetails:o}=t.getAllValues();if(b.reset(),vc.cleanup(),Og(t),ye.isSupported()===!1)throw new C("Browser not supported","0010",!0);const a=UP(t,{authToken:n,baseURL:r,cachedUserDetails:o});a.setRoomName(i),a.setRoomUUID(i),a.setOrganizationId(s),a.setHeader("dyte-tracing-id",e),t.setValue("apiClient",a);const d=ui.createSocketService(t),h=d.connect(),p=a.getPlugins(),[{sfu:f,userResponse:g,meetingTitle:E,roomNodeUrl:v}]=yield Promise.all([ui.getRoomMetadata(),ui.setupFlagsmith(t)]);t.setValue("roomNodeOptions",{sfu:f,meetingTitle:E,roomNodeUrl:v});const{theme:R,controllers:A}=yield ui.setupControllers(d,t,g,p);dA(R)&&ui.createRoomNodeClient(t,d),Zb();try{yield h,A.selfController.partialMediaRoom()}catch(L){throw l.error("[Socket Service] Failed to connect to socket server:",{error:L}),new C("Failed to connect to websocket","0012")}return new ui(r,A)})}static getRoomMetadata(){return u(this,null,function*(){const t=je(),[{roomNodeUrl:e,meetingTitle:r,sfu:n=Qi.HIVE},i]=yield Promise.all([t.getRoomNodeData(),t.getUserDetails()]);return{sfu:n,roomNodeUrl:e,meetingTitle:r,userResponse:i}})}static setupFlagsmith(t){return u(this,null,function*(){const{peerId:e,baseURI:r,overrides:n,meetingId:i,organizationId:s}=t.getAllValues(),o=Qb(i),a=ne(V({entity:Vd.PEER,clientId:s,isAnonUser:!s,sdkVersion:t.getValue("sdkVersion"),meetingHash:o,roomName:i},ye.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const d=n!=null&&n.whitelabelled_flags_endpoint?bi({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield K.identify(`${Vd.PEER}_${e}`,JSON.parse(JSON.stringify(a)),!1,5e3,d),l.info("flagsmith::allFlags",{flags:JSON.stringify(K.getAllFlags())},!0)}catch(d){l.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,n){return u(this,null,function*(){var i,s,o;const a=e.getValue("modules"),{preset:d,participant:h}=r,p=e.getValue("defaults"),{sfu:f,meetingTitle:g}=e.getValue("roomNodeOptions"),E=nM.init(d,!a.theme),{viewType:v,mediaConstraints:{audio:R}}=E;e.setValue("viewType",v),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(i=R.enableHighBitrate)!=null?i:!1,enableStereo:(s=R.enableStereo)!=null?s:!1}}},p));const A=XM.init(e,v,d.permissions);let L,F,W,H,I,S,P,N;const ce=new SD(t);Ne.socketService=t;const Le=new Sc(t),$=new Bt(t),x=new _D(t),Se=vc.create(t),fn=new bD(t),pi=new ED(t),mi=new In(t),ht=yield ni.init(e,Se,h,A,E),Qe=yield Nf.init(e,ht.self,Se,ce,g);if(a.participant&&(f===Qi.CF&&(N=new wg(e,ht.self,Se,a)),N=new Cg(e,ht.self,Se,a)),(o=a.e2ee)!=null&&o.enabled&&a.e2ee.manager.init(l,b),a.chat&&(F=yield wr.init(e,$,mi,ht.self,N.participants)),a.internals&&(I=yield gl.init()),a.livestream&&E.viewType===We.Livestream&&K.hasFeature(X.LIVESTREAM)&&(P=new rg(ht.self,pi)),E.viewType!==We.Chat&&(a.poll&&(L=yield Rf.init(e,ht.self,Le)),a.recording&&(S=new Hf(e,ht.self,Se)),a.stage&&(W=new Lf(e,x,Se,ht.self,N.participants)),a.plugin)){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module");const fo=yield n;H=yield Ns.init(e,fo,fn,$,F==null?void 0:F.chat,ht.self,N.participants)}const Xe={storesManager:new uM(e,fn),pollController:L,selfController:ht,metaController:Qe,chatController:F,stageController:W,pluginController:H,recordingController:S,internalsController:I,livestreamController:P,participantController:N};return{theme:E,permissions:A,controllers:Xe}})}static createRoomNodeClient(t,e){return u(this,null,function*(){const{peerId:r,meetingId:n,authToken:i,roomNodeOptions:s}=t.getAllValues(),{sfu:o,roomNodeUrl:a,meetingTitle:d}=s;return Dg(t,{socket:e,peerId:r,meetingId:n,authToken:i,roomNodeUrl:a,meetingTitle:d},o)})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:n}=t.getAllValues(),i=["PING"];return new ho(t,{peerId:e,meetingId:r,authToken:n,capabilities:i})}};let po=ui;Dc([y.trace("Controller.init")],po,"init",1),Dc([y.trace("setupFlagsmith")],po,"setupFlagsmith",1),Dc([y.trace("Controller.createSocketServiceAndRoomNodeClient")],po,"createRoomNodeClient",1),Dc([y.trace("Controller.createSocketService")],po,"createSocketService",1);var JD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,KD=(t,e,r,n)=>{for(var i=n>1?void 0:n?qD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&JD(e,r,i),i},Oc,nu;class nv extends Dt{constructor(e,r){super(),_(this,Oc,void 0),m(this,"meetings",[]),m(this,"parentMeeting",null),_(this,nu,void 0),T(this,nu,e),T(this,Oc,r.self)}get supportsConnectedMeetings(){return c(this,Oc).id!==""&&K.hasFeature(X.CONNECTED_MEETINGS)}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.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.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(r),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,r,n),i})}moveParticipantsWithCustomPreset(e,r,n){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:n});return i.success&&this.moveSuccessHandler(e,r,n.map(s=>s.id)),i})}moveSuccessHandler(e,r,n){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(n.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!n.includes(s.id))),this.meetings=this.meetings.map(s=>{if(r===s.id){const o=s.participants.concat(n.map(a=>i.get(a)));return ne(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(a=>!n.includes(a.id));return ne(V({},s),{participants:o})}return s})}}Oc=new WeakMap,nu=new WeakMap,KD([Ct({maxInvocations:60,period:60})],nv.prototype,"getConnectedMeetings",1);var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,iu=(t,e,r,n)=>{for(var i=n>1?void 0:n?YD(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&zD(e,r,i),i},mo,hi,su,ou;const pn=(su=class{constructor(t,e,r){m(this,"connectedMeetings"),_(this,mo,void 0),_(this,hi,void 0),_(this,ou,void 0),T(this,ou,t),T(this,mo,r),this.connectedMeetings=new nv(t,e),this.setCurrentMeeting(e)}static init(t,e,r){return pn.instance||(pn.instance=new pn(t,e,r)),pn.instance.connectedMeetings.supportsConnectedMeetings&&(pn.instance.setupEvents(),e.self.once("roomJoined",()=>pn.instance.getConnectedMeetings())),pn.instance}setCurrentMeeting(t){T(this,hi,t),Ne.currentMeetingId=t.meta.roomName}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.connectedMeetings.emit("changingMeeting",r),yield c(this,hi).leave("connected-meeting"),Ne.socketService=void 0;const n=yield av.init(ne(V({},c(this,mo)),{cachedUserDetails:null,defaults:ne(V({},c(this,mo).defaults),{video:c(this,hi).self.videoEnabled,audio:c(this,hi).self.audioEnabled}),authToken:e}));n.self.setName(c(this,hi).self.name);try{yield n.join()}catch(i){y.addLogInCurrentSpan("error","ConnectedMeetingsController.joinRoom",{error:i})}return this.connectedMeetings.emit("meetingChanged",n),this.setCurrentMeeting(n),n})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(n=>{r.set(n.id,n)}),e.forEach(n=>{r.has(n.id)?r.get(n.id).title=n.title:r.set(n.id,ne(V({},n),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id))}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},mo=new WeakMap,hi=new WeakMap,ou=new WeakMap,m(su,"instance"),su);let Nc=pn;iu([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Nc.prototype,"getConnectedMeetings",1),iu([y.trace("ConnectedMeetingsController.setupEvents")],Nc.prototype,"setupEvents",1),iu([y.trace("ConnectedMeetingsController.switchMeeting")],Nc.prototype,"switchMeeting",1);class QD{constructor(){m(this,"battery"),m(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){l.error("Error getting battery",e)}})),m(this,"updateChargeInfo",()=>{var e;l.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){l.log("Battery level: Not known");return}l.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const iv=new QD;function XD(t,e){try{const{meetingId:r,orgId:n,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://api.${s}`;return{meetingId:r,orgId:n,participantId:i,baseURI:s,apiBase:o}}catch(r){throw l.error("constants::decodeAuthToken",{error:r,debuggingHint:`Unable to decode auth token: ${t}`},!0),new C("Invalid auth token")}}var ZD=Object.defineProperty,eO=Object.getOwnPropertyDescriptor,Lc=(t,e,r,n)=>{for(var i=n>1?void 0:n?eO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(i=(n?o(e,r,i):o(i))||i);return n&&i&&ZD(e,r,i),i},at,xc,Fc,au,sv,ov;let mn=(ov=class{constructor(t,e){_(this,au),_(this,at,void 0),_(this,xc,void 0),_(this,Fc,void 0),T(this,Fc,t),T(this,at,e)}static init(t){return u(this,null,function*(){var e,r,n,i,s;Kb(),ye.init();const o=gn();iv.init();const{authToken:a,baseURI:d}=t,h=XD(a,d),{meetingId:p}=h,f=Ro(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const g=mn.setupContext(o,t,p,f);y.meetingMetadata.roomName=p,y.meetingMetadata.userId=f.participantId,y.meetingMetadata.organizationId=f.orgId,y.init(g,(r=(e=t.modules)==null?void 0:e.tracing)!=null?r:!0),l.info("DyteClient::init::options",{dyteClientInitOptions:ne(V({},t),{authToken:`${(n=t.authToken)==null?void 0:n.slice(0,10)}...
23
+ ${(i=t.authToken)==null?void 0:i.slice(-10)}`})});const E=yield po.init(g),v=new mn(g,E);return ue(s=v,au,sv).call(s,t),v})}static setupContext(t,e,r,n){var i;const s=Ts.createContext(t,e),o=V(V({},$b),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",o),s.setValue("sdkName","web-core"),s.setValue("meetingId",r),s.setValue("apiBase",n.apiBase),s.setValue("baseURI",n.baseURI),s.setValue("userId",n.participantId),s.setValue("organizationId",n.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",Gb({baseURI:n.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("cachedUserDetails",dr(e.cachedUserDetails)),s.setValue("sdkVersion","2.0.0-staging.50"),s}join(){return u(this,null,function*(){const{selfController:t}=c(this,at);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){iv.cleanup();const{selfController:e}=c(this,at);return e.leaveRoom(t)})}get participants(){var t;return(t=c(this,at).participantController)==null?void 0:t.participants}get self(){var t;return(t=c(this,at).selfController)==null?void 0:t.self}get meta(){var t;return(t=c(this,at).metaController)==null?void 0:t.meta}get ai(){var t;return(t=c(this,at).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=c(this,at).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=c(this,at).chatController)==null?void 0:t.chat}get polls(){var t;return(t=c(this,at).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=c(this,xc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=c(this,at).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=c(this,at).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=c(this,at).stageController)==null?void 0:t.stage}get stores(){return c(this,at).storesManager}get __internals__(){var t;return(t=c(this,at).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)})}},at=new WeakMap,xc=new WeakMap,Fc=new WeakMap,au=new WeakSet,sv=function(t){T(this,xc,Nc.init(c(this,Fc),this,t))},ov);Lc([dt("0002"),sn.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],mn.prototype,"join",1),Lc([dt("0003")],mn.prototype,"leave",1),Lc([dt("0001"),sn.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],mn,"init",1),mn=Lc([dt("0000")],mn);const av=mn;return av}();